简体   繁体   English

如何将Ruby代码嵌入Treetop中以完全自定义AST生成?

[英]How to embed Ruby code in Treetop for fully custom AST generation?

I am trying to write a parser using Treetop, for a toy langage that simply looks like this : 我正在尝试使用Treetop编写一个解析器,以使玩具语言看起来像这样:

prog test is
  a = b;
  if c then
    d=f;
  end; 
end

My grammar seems ok, but when I try to embed Ruby code in the grammar, I get weird messages that I can't understand. 我的语法似乎还不错,但是当我尝试在语法中嵌入Ruby代码时,收到了我无法理解的奇怪消息。

22:in `ruby_source_from_string': Expected one of #, .., &, !, ~, ', ", [, ., rule, end, ( at line 21, column 5 (byte 312) after grammar Gram     (RuntimeError)

The problem seems to be the bad use of alternative for "statement", but I am not sure. 问题似乎是对“声明”的替代使用不当,但我不确定。

My Treetop grammar is like this : 我的树梢语法是这样的:

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

Can an expert have a look at this ? 专家可以看看这个吗?

It seems to be parsing fine as far as I can tell. 据我所知,它似乎解析得很好。 There were a few typos in the code you posted. 您发布的代码中有一些错别字。 aa:assign should be a:assign , bb:ifStmt should be b:ifStmt , and 'program' should be 'prog' at the top. aa:assign应该是a:assignbb:ifStmt应该是b:ifStmt ,并且'program'应该在顶部是'prog'

Is there any chance you could show the rest of your code—the classes specifically? 您是否有机会展示其余的代码-特别是类?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM