Enable matching with `Node#deconstruct` (#31)

This commit is contained in:
Marc-André Lafortune 2021-01-23 13:39:31 -05:00 committed by GitHub
parent 2a878a2b5f
commit d9ea9fea92
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 3 deletions

View File

@ -229,9 +229,9 @@ module AST
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
@ -246,6 +246,14 @@ module AST
[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

View File

@ -102,7 +102,7 @@ describe AST::Node do
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,
@ -175,6 +175,22 @@ describe AST::Node do
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