
214
|
第 6 章
解析
現在我們已經有了能夠正常運作的語意,接著讓我們建置 lambda 演算運算式的解析器
來完成整個任務。一如往常,我們可以使用 Treetop 來編寫文法:
grammar LambdaCalculus
rule expression
calls / variable / function
end
rule calls
first:(variable / function) rest:('[' expression ']')+ {
def to_ast
arguments.map(&:to_ast).inject(first.to_ast) { |l, r| LCCall.new(l, r) }
end
def arguments
rest.elements.map(&:expression)
end
}
end
rule variable
[a-z]+ {
def to_ast
LCVariable.new(text_value.to_sym)
end
}
end
rule function
'-> ' parameter:[a-z]+ ' { ' body:expression ' }' {
def to_ast
LCFunction.new(parameter.text_value.to_sym, body.to_ast)
end
}
end
end
就如第 61 頁『實作解析器』所述,Treetop 文法通常產生右結合樹,因
此該文法必須完成額外的工作來適應 ...