rubyfan
1/28/2008 7:59:00 AM
I've been playing with TreeTop for a while now as well...
I would suggest that you use tt to generate the parser and then take a
look at the resulting code:
tt t1.treetop
Resulting code will be in t1.rb
I think you'll find that the call to wrrd.toxml doesn't work there
because wrrd is not in scope. Not sure how to fix it, though, maybe
you could use elements[0].wrrd?
Phil
On 1/27/08, Phrogz <phrogz@mac.com> wrote:
> 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
> #<Treetop::Runtime::SyntaxNode:0x5c7808>
>
>
> -_- t1.treetop -_-
>
> grammar T1
> rule paragraph
> inline_content "\n\n" {
> def to_xml
> "<p>#{inline_content.to_xml}</p>\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
> "<word>#{text_value}</word>"
> end
> }
> end
>
> rule numz
> ([1-9]+ / '0') {
> def to_xml
> "<i>#{text_value}</i>"
> end
> }
> end
>
> rule wspace
> [ \t]+
> end
>
> end
>
>