Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable matching with Node#deconstruct #31

Merged
merged 2 commits into from
Jan 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions lib/ast/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -229,9 +229,9 @@ def inspect(indent=0)
def to_ast
self
end

# Converts `self` to an Array where the first element is the type as a Symbol,
# and subsequent elements are the same representation of its children.
# and subsequent elements are the same representation of its children.
#
# @return [Array<Symbol, [...Array]>]
def to_sexp_array
Expand All @@ -246,6 +246,14 @@ def to_sexp_array
[type, *children_sexp_arrs]
end

# Enables matching for Node, where type is the first element
# and the children are remaining items.
#
# @return [Array]
def deconstruct
[type, *children]
end

protected

# Returns `@type` with all underscores replaced by dashes. This allows
Expand Down
18 changes: 17 additions & 1 deletion test/test_ast.rb
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def initialize(*)
it 'should return self in to_ast' do
@node.to_ast.should.be.identical_to @node
end

it 'should produce to_sexp_array correctly' do
AST::Node.new(:a, [ :sym, [ 1, 2 ] ]).to_sexp_array.should.equal [:a, :sym, [1, 2]]
AST::Node.new(:a, [ :sym,
Expand Down Expand Up @@ -175,6 +175,22 @@ def obj.children
rescue SyntaxError
# Running on 1.8, ignore.
end

begin
eval <<-CODE
it 'should be matchable' do
baz = s(:baz, s(:bar, 1), 2)
r = case baz
in [:baz, [:bar, val], Integer] then val
else
:no_match
end
r.should.equal 1
end
CODE
rescue SyntaxError
# Running on < 2.7, ignore.
end
end

describe AST::Processor do
Expand Down