2013-08-08 4 views
0

파서가 토큰을 인식 할 때마다 약간의 코드를 실행하려고합니다. 나무 꼭대기에 액션 트리거를 코딩하는 방법은 무엇입니까?

은의 여기

grammar FooBar 

    rule start 
    (foo "\n")+ 
    end 

    rule foo 
    stuff_i_want:([a-z]+) { 
     puts "Hi there I found: #{stuff_i_want.text_value}" 
    } 
    end 

end 

생각이 puts 조치가 foo 토큰이 발견 될 때마다 실행해야하는 것입니다 가정 해 봅시다. 있는 그대로 코드화되어 있으므로 클래스 로딩 시간에 한 번만 트리거되고 물론 stuff_i_want.text_value은 존재하지 않으므로 작동하지 않습니다.

아이디어가 있으십니까? 심지어 가능할까요? 도서관에 문서가 없다고해서 쉽게 알 수있는 것은 아닙니다.

답변

0

글쎄, 내가 downvote받을 가치가 있었는지 잘 모르겠습니다.

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 

은 모든이 남아있는 당신에 영향을 트리거하고하고 싶지 각 노드에 action(*args) 방법을 정의하는 것입니다 :

어쨌든, 여기에 내가 사용하는 솔루션입니다 상단 파서 노드의 크롤링 (

parse_tree = FooBarParser.new.parse "mycontent" 
parse_tree.crawl # add optional parameters for context/state 

선택적인 매개 변수는 각 action에 전달되는 구문 분석 호출에 의해 반환 된 하나의 시작 방법. 하위 트리 크롤링을 중지하기 위해 작동중인 거짓 값 (false 또는 nil)을 반환 할 수도 있습니다.

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 
0

이것은 사용자가 할 수있는 것보다 간단한 해결책 일 수 있습니다. 원하는 기능을 얻으려면 SyntaxNode 클래스를 열어야하는 이유를 알 수 없습니다. 내가하려는 일을 이해하지 않는 한, 노드를 조금 더 가로 지르면됩니다.

다음은 예입니다 :

require 'treetop' 

Treetop.load_from_string DATA.read 

parser = FooBarParser.new 

parser.parse("hello\nok\nmorestuff\n").action 

__END__ 
grammar FooBar 
    rule start 
    (foo "\n")+ 
    { 
     def action 
      elements.each {|e| e.elements[0].action } 
     end 
    } 
    end 

    rule foo 
    stuff_i_want:([a-z]+) 
    { 
     def action 
      puts "Hi there I found: #{stuff_i_want.text_value}" 
     end 
    } 
    end 
end 

# => Hi there I found: hello 
# Hi there I found: ok 
# Hi there I found: morestuff 
+0

좋은 점은 정말 간단 할 수있다. 그러나 내가 작업하고있는 파일에는 재귀 적으로'action'을 호출하여 많은 코드 중복을 필요로하는 중개 구문 노드가 많이 있습니다. 내 솔루션은 좀 더 유연하다고 믿습니다. 그러나 귀하의 의견을 주셔서 감사합니다 :) –

+0

그것은 일종의 영리한 방법입니다. –

관련 문제