首先我想說C++語法對於Lex/Bison來說太複雜了。這裏的問題主要是在語法衝突中。編寫沒有它們的C++語法是不可能的。 C++標準明確規定了這一點,幷包含一些關於如何解決它們的指導原則。
解決語法衝突沒有通用的解決方案。特別是C++的語法衝突解決方案需要詳細瞭解已定義的標識符。這意味着你需要擁有更大部分的C++前端。只有語法是不夠的。
儘管如此,構建AST仍是可能的。看一個小樣本程序。
class HashEntry
{
private:
int key;
int value;
public:
HashEntry(int key, int value)
{
this->key = key;
this->value = value;
}
int getKey() { return key; }
int getValue() { return value; }
};
const int TABLE_SIZE = 128;
class HashMap
{
private:
HashEntry **table;
public:
HashMap()
{
table = new HashEntry*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = NULL;
}
int get(int key)
{
int hash = (key % TABLE_SIZE);
while (table[hash] != NULL && table[hash]->getKey() != key)
hash = (hash + 1) % TABLE_SIZE;
if (table[hash] == NULL)
return -1;
else
return table[hash]->getValue();
}
void put(int key, int value)
{
int hash = (key % TABLE_SIZE);
while (table[hash] != NULL && table[hash]->getKey() != key)
hash = (hash + 1) % TABLE_SIZE;
if (table[hash] != NULL)
delete table[hash];
table[hash] = new HashEntry(key, value);
}
~HashMap()
{
for (int i = 0; i < TABLE_SIZE; i++)
if (table[i] != NULL)
delete table[i];
delete[] table;
}
};
這是對這一計劃的AST: ![enter image description here](https://i.stack.imgur.com/S6kW9.jpg)
這棵樹被嚴重縮小。葉子上的黃色圓圈(非常小)是終端符號,中間的綠色圓圈是非終端符號。中心的粉紅色圓圈就是TranslationUnit。這棵樹有2009個節點。
您的意思是用C++編碼?或者你想解析C++? –
我希望我的代碼與flex/bison交互爲C++。特別是AST(抽象語法樹)。提到的例子取決於c型寬大。另外,我想使用STL等等。至於我想解析的內容:一個類似於正則表達式的簡單語法。 –