Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PetitParser: How to match to token set

In PetitParser2, how do I match a closed set of tokens, like month names? E.g. (in pseudocode) [ :word | MonthNames anySatisfy: [ :mn | mn beginsWith: word ] ] asParser.

PPPredicateSequenceParser seemed like a possibility, but it seems you have to know the string size in advance. I guess I could just do something like:

| monthRules |
    monthRules := Array streamContents: [ :unamused: |
        MonthNames collect: [ :e | 
            s nextPut: e asString asPParser.
            s nextPut: (e first: 3) asPParser ] ].
    ^ PP2ChoiceNode withAll: monthRules

But I was wondering if there was something built in/straightforward

like image 996
Sean DeNigris Avatar asked Jan 20 '26 03:01

Sean DeNigris


1 Answers

Other, more clumsy and less efficient option is to use a custom block:

[ :context | 
    | position names |
    names := #('January' 'February' 'March' 'April').   
    position := context position.
    names do: [ :name | 
        (context next: name size) = name ifTrue: [  
            ^ name
        ] ifFalse: [ 
            context position: position
        ]
    ].
    ^ PP2Failure new
] asPParser parse: 'April'

I would not recommend this though, because PP2 does not know anything about the block and cannot apply any optimizations.

like image 183
jk_ Avatar answered Jan 22 '26 23:01

jk_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!