kschiess / parslet

A small PEG based parser library. See the Hacking page in the Wiki as well.
kschiess.github.com/parslet
MIT License
809 stars 95 forks source link

rule parse error #209

Closed Baozi2 closed 1 year ago

Baozi2 commented 3 years ago

This is my code, why the rule sgt can used for EURO, cannot used for EUR? Thanks

require 'parslet'

class Parser < Parslet::Parser

    rule(:sgt) { (str('EU') >> (str('RO').maybe | str('R').maybe)).as(:sgt) }
    rule(:digit) {
        match('\d').repeat(1).as(:digit)
    }
    rule(:simple_size) { (sgt >> digit.as(:value)).as(:size) }
    root :simple_size
end

require 'pp'
pp Parser.new.parse 'EU1'
pp Parser.new.parse 'EUR1'
pp Parser.new.parse 'EURO1'
kschiess commented 1 year ago
rule(:sgt) { (str('EU') >> (str('RO') | str('R')).maybe).as(:sgt) }

works. In general, alternation and 'maybe' will never interact constructively; one says that either of A or B should be parsed - the other says that A might be empty. If A is empty, the first branch of the alternation will always be accepted.

This is still a ratpack parser, with all the downsides. The upside is that behaviour is predictable.