2015-10-06 38 views
0

我无法根据最基本的一组规则进行Treetop解析。任何帮助,将不胜感激基本树梢语法不起作用

# my_grammar.treetop 
grammar MyGrammar 
    rule hello 
    'hello' 
    end 

    rule world 
    'world' 
    end 

    rule greeting 
    hello ' ' world 
    end 
end 

# test.rb 
require 'treetop' 
Treetop.load 'my_grammar' 
parser = MyGrammarParser.new 

puts parser.parse("hello").inspect # => SyntaxNode offset=0, "hello" 
puts parser.parse("world").inspect # => nil 
puts parser.parse("hello world").inspect # => nil 

回答

1

Treetop总是匹配语法中的第一条规则,除非你传递一个选项parse()。在这种情况下,你已经要求它解析“你好”,并且没有办法让它达到另外两条规则。

如果你想要任何的三个规则相匹配,你需要添加一个新的顶级规则:

rule main 
    greeting/hello/world 
end 

注意,在候补名单,第一个匹配会排除其他人被测试过,所以如果你先打“你好”,那么你就无法匹配“问候语”。