From: Phrogz Date: 2008-01-28T14:54:56+09:00 Subject: Re: Treetop parser (or PEG in general?) questions An additional Treetop question that has me stumped: I have a simple grammar as listed at the end of this post. In the following code, why can I not get the 'to_xml' method to flow through the 'inline_atom' rule, to use the to_xml of the underlying wrrd and numz classes? Why does inline_atom not provide the #wrrd and #numz SyntaxNode methods inside the handlers for inline_atom? How can I rewrite inline_atom to allow the flow through? require 'rubygems' require 'treetop' Treetop.load "t1.treetop" @parser = T1Parser.new @root = @parser.parse( "Hi 123\n\n" ) p @root #=>SyntaxNode+Paragraph1+Paragraph0 offset=0, "Hi 123\n \n" (inline_content,to_xml): #=> SyntaxNode+InlineContent2+InlineContent1 offset=0, "Hi 123" (all_items,to_xml,items,last_item): #=> SyntaxNode offset=0, "Hi ": #=> SyntaxNode+InlineContent0 offset=0, "Hi " (wspace,item): #=> SyntaxNode+InlineAtom1+Wrrd0 offset=0, "Hi" (to_xml): #=> SyntaxNode offset=0, "H" #=> SyntaxNode offset=1, "i" #=> SyntaxNode offset=2, " ": #=> SyntaxNode offset=2, " " #=> SyntaxNode+InlineAtom0+Numz0 offset=3, "123" (to_xml): #=> SyntaxNode offset=3, "1" #=> SyntaxNode offset=4, "2" #=> SyntaxNode offset=5, "3" #=> SyntaxNode offset=6, "\n\n" p @root.to_xml #=> NameError: undefined local variable or method 'wrrd' for # -_- t1.treetop -_- grammar T1 rule paragraph inline_content "\n\n" { def to_xml "

#{inline_content.to_xml}

\n" end } end rule inline_content items:( item:inline_atom wspace )* last_item:inline_atom { def to_xml all_items.map{ |atom| atom.to_xml }.join( ' ' ) end def all_items all = [] all << first_item if methods.include?( 'first_item' ) all.concat items.elements.map{ |el| el.item } all << last_item if methods.include?( 'last_item' ) all end } end rule inline_atom numz { def to_xml numz.to_xml end } / wrrd { def to_xml wrrd.to_xml end } end rule wrrd [A-Za-z]+ { def to_xml "#{text_value}" end } end rule numz ([1-9]+ / '0') { def to_xml "#{text_value}" end } end rule wspace [ \t]+ end end