QLanguage 的 AST 採用經典的「左子右兄」表示法,每個節點包含三大核心欄位:
type)與附加值(value):標識節點語義(如 stIf、stDeclare、stExp 等)。child):指向第一個子節點的智慧指標串列(List<NAutoPtr<CSyntaxTreeNode>>)。next):串聯同層級的下一個節點。class CSyntaxTreeNode {
public:
CSyntaxTreeNode(int _type, int _value) : type(_type), value(_value) {}
inline List<NAutoPtr<CSyntaxTreeNode>>& Child() { return child; }
inline NAutoPtr<CSyntaxTreeNode> Next() { return next; }
inline int& Type() { return type; }
inline int& Value() { return value; }
protected:
int type, value;
List<NAutoPtr<CSyntaxTreeNode>> child;
NAutoPtr<CSyntaxTreeNode> next;
};
CParserAnalyze 維護一棵語法樹的根節點與一個節點堆疊,支援推入、彈出、取頂、取根四種基本操作,配合遞迴下降或算子優先分析器在歸約時建樹:
class CParserAnalyze {
public:
inline void Push(NAutoPtr<CSyntaxTreeNode>& node) { SyntaxTreeStack.Push(node); }
inline NAutoPtr<CSyntaxTreeNode> Pop() { return SyntaxTreeStack.Pop(); }
inline NAutoPtr<CSyntaxTreeNode> Top() { return SyntaxTreeStack.Top(); }
inline NAutoPtr<CSyntaxTreeNode> Root() { return SyntaxTreeRoot; }
protected:
NAutoPtr<CSyntaxTreeNode> SyntaxTreeRoot;
Stack<NAutoPtr<CSyntaxTreeNode>> SyntaxTreeStack;
};
輸入程式碼:
if a then
declare b as integer
end if
分析步驟(簡化):
if a,a 歸約為 exp 節點壓入堆疊。if a 歸約產生 stIf 節點,彈出 exp 填充為第一個子節點。then declare b as integer,integer 歸約為 stDeclare 壓堆疊。declare b as integer 歸約,給 stDeclare 加上識別符 b 子節點。then ... 歸約,彈出 stmt_list,標記 stIf 值域最低位為 1(表示 then 區塊非空)。else 子句,整體歸約完成,堆疊頂為含 stExp、stDeclare 兩個子節點的 stIf 根節點。此過程展示了「移進-歸約」解析器如何利用堆疊輔助構建階層式 AST,為後續語義分析與程式碼生成奠定基礎。