whitequark / ast

A library for working with Abstract Syntax Trees.
MIT License
195 stars 25 forks source link

Enable matching with `Node#deconstruct` #31

Closed marcandre closed 3 years ago

marcandre commented 3 years ago

It would be helpful to be able to use pattern matching with Nodes.

I'm not sure we should define deconstruct_keys, but deconstruct seems clearer so the following is a match:

baz = s(:baz, s(:bar, 1), 2)
case baz
in [:baz, [:bar, val], Integer] then :match
# ...

cc/ @baweaver and https://bugs.ruby-lang.org/issues/17551

coveralls commented 3 years ago

Coverage Status

Coverage remained the same at 100.0% when pulling 726c2eb5f218fd6b7f0cf2c6af04c0837423bd18 on marcandre:deconstruct into 2a878a2b5fb33524b03e9d5cd176a4980ed21a8a on whitequark:master.

baweaver commented 3 years ago

Good call, and I can definitely see a case for deconstruct here. Maybe not deconstruct_keys as mentioned except that it may expose the public API of the node itself in a downstream like Rubocop does.

A HashNode, for instance, might expose deconstruct_keys for its public API like keys, values and others to be used as:

node in { class_name: 'HashNode', keys: [*, :our_key, *], values: [*, 42, *] }

So in the context of WhiteQuark's parser not quite. In the context of the downstream extensions on it? Perhaps.

marcandre commented 3 years ago

Right. Note that RuboCop has it's own pattern matching (NodePattern) that is more adapted and powerful.

iliabylich commented 3 years ago

@marcandre Sorry for delay and thanks! Looks like we don't run Ruby 3.0 on CI, and we still run on Travis, I'll migrate to Github actions.

iliabylich commented 3 years ago

ast 2.4.2 has been released

marcandre commented 3 years ago

Thanks ♥️