為直接構造語法樹,狀態機邊需攜帶語義指令:
Create:創建節點類型。Set:設置成員常量值。Assign:將子節點賦給成員。Using:以子節點作為本規則返回值。Shift/Reduce:棧操作。
token NAME = "[a-zA-Z_]\w*";
token NUMBER = "\d+(\.\d+)?";
rule NumberExpression Number = NUMBER : value;
rule FunctionExpression Call = NAME : functionName "(" [ Exp : arguments { "," Exp : arguments } ] ")";
rule Expression Factor = !Number | !Call;
rule Expression Term = !Factor;
= Term : firstOperand "*" Factor : secondOperand as BinaryExpression with { binaryOperator = "Mul" };
= Term : firstOperand "/" Factor : secondOperand as BinaryExpression with { binaryOperator = "Div" };
rule Expression Exp = !Term;
= Exp : firstOperand "+" Term : secondOperand as BinaryExpression with { binaryOperator = "Add" };
= Exp : firstOperand "-" Term : secondOperand as BinaryExpression with { binaryOperator = "Sub" };
$TokenBegin/$TokenFinish 的起始/終結狀態。$ 邊不可帶語義信息(信息前移)。Create/Set 可前移。

下一篇將講述連接所有規則並處理轉換信息。