mpe85 / grampa

A PEG parser library for Kotlin/JVM
https://mpe85.github.io/grampa/
MIT License
13 stars 1 forks source link

Evaluation rule? #48

Open jottinger opened 1 week ago

jottinger commented 1 week ago

Is there a way to include rules in evaluation based on an external condition?

like: sequence( ifTrue( dayOfWeek==MONDAY ), string("Monday") )

would match IF the dayOfWeek (provided somehow) was indeed MONDAY, and the string passed into the parser was "Monday".

jottinger commented 1 week ago

I think this IS provided for in the API, it just desperately needs docs.

mpe85 commented 1 week ago

Thanks @jottinger,

This could probably be accomplished by using a conditional() rule. I will shortly try to build up an example showing how to achieve that and provide it to you.

mpe85 commented 1 week ago

Try something like this:

open class MyGrammar : AbstractGrammar<Unit>() {

    var day: DayOfWeek = DayOfWeek.MONDAY

    override fun start(): Rule<Unit> = conditional(
        { day == DayOfWeek.MONDAY },
        string("Monday"),
    )

}

You can change the day on your grammar instance:

val myGrammar = MyGrammar::class.createGrammar()
myGrammar.day = DayOfWeek.FRIDAY

Note that the conditional rule will match when the condition evaluates to false (i.e. the day is not MONDAY). If you want it to fail in this case you could add a failing rule to the else case like this:

conditional(
    { day == DayOfWeek.MONDAY },
    string("Monday"),
    never(),
)

Hope this helps somehow

jottinger commented 1 week ago

It does! ... and this is the sort of thing that I'd want more docs to capture.

On Wed, Sep 11, 2024 at 5:59 PM Marco Perazzo @.***> wrote:

Try something like this:

open class MyGrammar : AbstractGrammar() {

var day: DayOfWeek = DayOfWeek.MONDAY

override fun start(): Rule<Unit> = conditional(
    { day == DayOfWeek.MONDAY },
    string("Monday"),
)

}

You can change the day on your grammar instance:

val myGrammar = MyGrammar::class.createGrammar() myGrammar.day = DayOfWeek.FRIDAY

Note that the conditional rule will match when the condition evaluates to false (i.e. the day is not MONDAY). If you want it to fail in this case you could add a failing rule to the else case like this:

conditional( { day == DayOfWeek.MONDAY }, string("Monday"), never(), )

Hope this helps somehow

— Reply to this email directly, view it on GitHub https://github.com/mpe85/grampa/issues/48#issuecomment-2344776721, or unsubscribe https://github.com/notifications/unsubscribe-auth/AADSNGTGTD7WEEXPKGRLEILZWC4NBAVCNFSM6AAAAABN5ITZLWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDGNBUG43TMNZSGE . You are receiving this because you were mentioned.Message ID: @.***>

-- Joseph B. Ottinger http://www.enigmastation.com http://enigmastation.com To the beautiful and the wise,