Search code examples
rubyparsinggrammartreetop

Treetop: parsing single node returns nil


I'm trying to get the basic of Treetop parsing. Here's a very simple bit of grammar so that I can say ArithmeticParser.parse('2+2').value == 4.

grammar Arithmetic
  rule additive
    first:number '+' second:number {
      def value
        first.value + second.value
      end
    }
  end

  rule number
    [1-9] [0-9]* {
      def value
        text_value.to_i
      end
    }
  end
end

Parsing 2+2 works correctly, returning a node. However, parsing 2 or 22 returns nil.

What did I miss?


Solution

  • Got it! Though I'd normally delete the question, I wouldn't be surprised if someone else also fundamentally misunderstands Treetop, so I'll leave this here for reference.

    Treetop doesn't just go through the rules, looking for which one applies. Instead, it starts at the first rule, and, if the first rule does not match, it must be forced to consider alternatives. Therefore, / number must appear at the end of the additive rule.

    grammar Arithmetic
      rule additive
        first:number '+' second:number {
          def value
            first.value + second.value
          end
        }
        / number
      end
    
      rule number
        [1-9] [0-9]* {
          def value
            text_value.to_i
          end
        }
      end
    end