算符优先分析
1. 算符优先文法
Expr ::= Expr + Term | Expr – Term | Term;
Term ::= Term * Factor | Term / Factor | Factor;
Factor ::= ( Expr ) | NUM | REAL
2. 构建算符优先分析表
求解算符优先分析表,实质为求解三种关系
等于(同时规约):P ::= ...a[Q]b...
小于(后规约): P ::= ...aQ..., b 属于 firstVT(Q)
大于(先规约): P ::= ...Qb..., a 属于 lastVT(Q)
此外,由于在开头结尾都加上#,需要特别考虑#,#《Termianl,T》#,#与#不比较
算法:初始化#,遍历文法,遍历每条文法右部,以此判断上述三中条件,并填写表格。
3. 关于firstVT
为什么要就算firstVT
若 a 《 b;
则存在P ::= ...aR..., R ->(+) b 或者 R ->(+) Qb,
那么针对规则 P ::= ...aR... 只要b 属于 firstVT(R), 便可以确定优先级
算法:
1)初始化:若P ::= a... |Qa... 则 firstVT(P) = {a}
2)若存在:P ::= Q... 则 firstVT(P)= firstVT(P) UNION firstVT(Q)
3)反复运用1)2),直到不变为止
4. 关于lastVT
为什么要就算lastVT
若 a 》 b;
则存在P ::= ...Rb..., R ->(+) a 或者 R ->(+) Qa,
那么针对规则 P ::= ...Rb... 只要a 属于 firstVT(R), 便可以确定优先级
算法:
1)初始化:若P ::= ...a |...aQ 则 lastVT(P) = {a}
2)若存在:P ::= ...Q 则 lastVT(P) =lastVT(P) UNION lastVT(Q)
3)反复运用1)2),直到不变为止
5. 关于表达式求值
《:移进; =:移进;
》规约,出栈直至第一个《出现,并规约
(规约应当确保至少包含一个终结符,避免由F 到 T 到 E这样的无效规约)
求值终止条件:栈只包含结束符 和 结果,并且表达式读取到 终止符。
6. 关于规约
寻找至少包含一个终结符的素短语,避免由F 到 T 到 E这样的无效规约
素短语形如着色处 : a1 《a2= a3》 a4 a5