基本的Treetop语法不起作用

时间:2015-10-06 18:55:37

标签: ruby parsing treetop

我无法根据最基本的规则对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 个答案:

答案 0 :(得分:1)

除非您将选项传递给parse(),否则Treetop始终匹配语法中的第一个规则。在这种情况下,您已要求它解析“hello”,并且没有办法让它达到其他两个规则。

如果您希望三个规则中的任何一个匹配,则需要添加新的顶级规则:

rule main
  greeting / hello / world
end

请注意,在替换列表中,第一个匹配将排除其他人进行测试,因此如果先将“hello”放在首位,则无法匹配“问候”。