Search code examples
rubygrammarpegtreetop

Treetop ignore grammar rules


Treetop seems to ignore turther rules after the first and fails to parse anything that doesn't match the first rule on the grammar file. I already tried to swap the order of the rules, but still, only the first one is considered.

# grammar_pov.treetop
grammar Pov
    rule numeric
        '-'? [0-9]+ ('.' [0-9]+)? <::PovFabric::Nodes::NumericLiteral>
    end
    rule comma
        ','
    end
    rule space
        [\s]+
    end
end

This grammar file matches all integer and floats, but doesn't match '123, 456' or '123,456' The parser failure_reason property says this 'Expected - at line 1, column 1 (byte 1) after '

Am i missing something?


Solution

  • Like Jörg mentioned, you need to use your comma and space rules in the grammar. I built a simple example of what I think you're trying to accomplish below. It should match "100", "1,000", "1,000,000", etc.

    If you look at the numeric rule, first I test for a subtraction sign '-'?, then I test for one to three digits, then I test for zero or more combinations of comma's and three digits.

    require 'treetop'
    Treetop.load_from_string DATA.read
    
    parser = PovParser.new
    
    p parser.parse('1,000,000')
    
    __END__
    grammar Pov
       rule numeric
          '-'? digit 1..3 (comma space* (digit 3..3))*
       end
    
       rule digit
          [0-9]
       end
    
       rule comma
          ','
       end
    
       rule space
          [\s]
       end
    end