Scony / godot-gdscript-toolkit

Independent set of GDScript tools - parser, linter, formatter, and more
MIT License
944 stars 65 forks source link

Guard Patterns in `match` statement with `when` #298

Closed DDarby-Lewis closed 4 months ago

DDarby-Lewis commented 4 months ago

Match statement cases accept a guard condition which is currently not recognised by the parser/formatter... As per the docs here: https://docs.godotengine.org/en/stable/tutorials/scripting/gdscript/gdscript_basics.html#pattern-guards

I have looked at implementing this myself in the gdscript.lark by adding this to the pattern for the match_branch

pattern: list_pattern when_pattern?

and:

when_pattern: "when" test_pattern

and adding to the expression_to_str method this extra key:

        "when_pattern": lambda e: f"when {expression_to_str(e.children[0])}",

Which didn't quite get ut working. Does anyone know how this can be added?

DDarby-Lewis commented 4 months ago

Turns out this can be done by simply replacing the test pattern with:

!?test_pattern: or_pattern ["if" or_pattern "else" test_pattern] ["when" expr]

I'm not sure if this is the "right" way to do this but it does seem to work.

Scony commented 4 months ago

Duplicate of https://github.com/Scony/godot-gdscript-toolkit/issues/258

The implementation will require handling in formatter and linter + adding tests to cover that. But no worries - I'll handle that soon.