[英]How to trigger functions in subnodes in Ruby Treetop tree. (was:How to prevent ruby Treetop doing AST squashing)
[英]How to embed Ruby code in Treetop for fully custom AST generation?
我正在尝试使用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
专家可以看看这个吗?
据我所知,它似乎解析得很好。 您发布的代码中有一些错别字。 aa:assign
应该是a:assign
, bb:ifStmt
应该是b:ifStmt
,并且'program'
应该在顶部是'prog'
。
您是否有机会展示其余的代码-特别是类?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.