0

I can't make Treetop parse according to the most basic set of rules. Any help would be appreciated

# 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
synapse
  • 5,588
  • 6
  • 35
  • 65

1 Answers1

1

Treetop always matches the first rule in the grammar unless you pass an option to parse(). In this case, you have asked it to parse "hello", and provided no way for it to reach the other two rules.

If you want any of the three rules to match, you need to add a new top rule:

rule main
  greeting / hello / world
end

Note that in a list of alternates, the first one to match will exclude the others from being tested, so you cannot match "greeting" if you put "hello" first.

cliffordheath
  • 2,536
  • 15
  • 16