ruby / prism

Prism Ruby parser
https://ruby.github.io/prism/
MIT License
790 stars 134 forks source link

Document some nodes related to pattern matching #2914

Open herwinw opened 1 week ago

herwinw commented 1 week ago

Part of #2123

This adds documentation for ArrayPatternNode, FindPatternNode, HashPatternNode, LocalVariableTargetNode (a small update) and MatchRequiredNode.

herwinw commented 1 week ago

MatchRequiredNode has some additional information on what types of nodes it will generate:

- name: pattern
  type: node
  comment: |
    Represents the right-hand side of the operator. The type of the node depends on the expression.

    Anything that looks like a local variable name (including `_`) will result in a `LocalVariableTargetNode`.

        foo => a # This is equivalent to writing `a = foo`
               ^

    Using an explicit `Array` or combining expressions with `,` will result in a `ArrayPatternNode`. This can be preceded by a constant.

        foo => [a]
               ^^^

        foo => a, b
               ^^^^

        foo => Bar[a, b]
               ^^^^^^^^^

    If the array pattern contains at least two wildcard matches, a `FindPatternNode` is created instead.

        foo => *, *a
               ^^^^^

    Using an explicit `Hash` or a constant with square brackets and hash keys in the square brackets will result in a `HashPatternNode`.

        foo => { a: 1, b: }

        foo => Bar[a: 1, b:]

        foo => Bar[**]

    Anything else will result in the regular node for that expression, for example a `ConstantReadNode`.

        foo => CONST

But this information applies to other locations as well. It is recursively applied to all possible fields (e.g. something that looks like a variable name inside an ArrayPatternNode will result in a LocalVariableTargetNode. And this applies to all other pattern matching related parse nodes as well (like foo in [a]). There probably is a better way to document this than to copy-paste it everywhere or referring back to other nodes for details. Marking this one as draft until this issue has been resolved/answered.