简体   繁体   中英

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 :

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.

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.

Is there any chance you could show the rest of your code—the classes specifically?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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