我正在尝试使用 Treetop 编写一个解析器,它的玩具语言看起来像这样:
prog test is
a = b;
if c then
d=f;
end;
end
我的语法似乎没问题,但是当我尝试在语法中嵌入 Ruby 代码时,我收到了我无法理解的奇怪消息。
22:in `ruby_source_from_string': Expected one of #, .., &, !, ~, ', ", [, ., rule, end, ( at line 21, column 5 (byte 312) after grammar Gram (RuntimeError)
问题似乎是“陈述”的替代品使用不当,但我不确定。
我的树顶语法是这样的:
grammar Gram
rule program
'program' s id:identifier s 'is' s b:block 'end' {
def ast
Program.new(id.ast,b.ast)
end
}
end
rule block
s? st:(statement)* s? {
def ast
Block.new( *st.elements.collect{|e| e.ast} )
end
}
end
rule statement
aa:assign
{
def ast
a.ast
end
}
/ bb:ifStmt
{
def ast
b.ast
end
}
end
rule assign
i1:identifier s? '=' s? i2:identifier s? ';' s? {
def ast
Assign.new(i1.ast,i2.ast)
end
}
end
rule ifStmt
s? 'if' s i:identifier s 'then' s b:block s? 'end' s? ';' {
def ast
IfStmt.new(i.ast,b.ast)
end
}
end
rule identifier
[a-zA-Z]+ {
def ast
Identifier.new(text_value)
end
}
end
rule s
[\s]+
end
end
高手可以看看这个吗?