Well, I'm not sure what I did to deserve the downvote.
Anyway, here is the solution I used:
node_extension.rb
module Crawlable
def crawl *args
continue = true
continue = action(*args) if respond_to? :action
return if !continue || elements.nil?
elements.each do |elt|
elt.crawl(*args)
end
end
end
# reopen the SyntaxNode class and include the module to add the functionality
class Treetop::Runtime::SyntaxNode
include Crawlable
end
then all is left is to define a action(*args)
method on each node you want to trigger an effect on and have to start the crawling on the top parser node (the one returned by the parse call
parse_tree = FooBarParser.new.parse "mycontent"
parse_tree.crawl # add optional parameters for context/state
The optional parameters are passed to each action
method. You can also return a falsey value (false
or nil
) in action in order to stop the subtree crawling.
grammar FooBar
rule start
(foo "\n")+
end
rule foo
stuff_i_want:([a-z]+) {
def action
puts "Hi there I found: #{stuff_i_want.text_value}"
false
end
}
end
end