Skip to content

Commit 8e67e7b

Browse files
committed
Support AST::Node#any_match_pattern_type? method
This PR adds `AST::Node#any_match_pattern_type?`. This method can be used to simplify multiple places where `node.type?(:match_pattern, :match_pattern_p)` is used, such as in the changes made in rubocop/rubocop#14224.
1 parent 4c51ecd commit 8e67e7b

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

lib/rubocop/ast/node.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,10 @@ class Node < Parser::AST::Node # rubocop:disable Metrics/ClassLength
116116

117117
block: :any_block,
118118
numblock: :any_block,
119-
itblock: :any_block
119+
itblock: :any_block,
120+
121+
match_pattern: :any_match_pattern,
122+
match_pattern_p: :any_match_pattern
120123
}.freeze
121124
private_constant :GROUP_FOR_TYPE
122125

@@ -540,6 +543,10 @@ def any_block_type?
540543
GROUP_FOR_TYPE[type] == :any_block
541544
end
542545

546+
def any_match_pattern_type?
547+
GROUP_FOR_TYPE[type] == :any_match_pattern
548+
end
549+
543550
def guard_clause?
544551
node = operator_keyword? ? rhs : self
545552

spec/rubocop/ast/node_spec.rb

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1083,6 +1083,49 @@ class << expr
10831083
end
10841084
end
10851085

1086+
describe '#any_match_pattern_type?' do
1087+
# Ruby 2.7's one-line `in` pattern node type is `match-pattern`.
1088+
context 'when `in` one-line pattern matching', :ruby27 do
1089+
let(:src) { 'expression in pattern' }
1090+
1091+
it 'is true' do
1092+
expect(node).to be_any_match_pattern_type
1093+
end
1094+
end
1095+
1096+
# Ruby 3.0's one-line `in` pattern node type is `match-pattern-p`.
1097+
context 'when `in` one-line pattern matching', :ruby30 do
1098+
let(:src) { 'expression in pattern' }
1099+
1100+
it 'is true' do
1101+
expect(node).to be_any_match_pattern_type
1102+
end
1103+
end
1104+
1105+
# Ruby 3.0's one-line `=>` pattern node type is `match-pattern`.
1106+
context 'when `=>` one-line pattern matching', :ruby30 do
1107+
let(:src) { 'expression => pattern' }
1108+
1109+
it 'is true' do
1110+
expect(node).to be_any_match_pattern_type
1111+
end
1112+
end
1113+
1114+
context 'when pattern matching', :ruby27 do
1115+
let(:src) do
1116+
<<~RUBY
1117+
case expression
1118+
in pattern
1119+
end
1120+
RUBY
1121+
end
1122+
1123+
it 'is false' do
1124+
expect(node).not_to be_any_match_pattern_type
1125+
end
1126+
end
1127+
end
1128+
10861129
describe '#type?' do
10871130
let(:src) do
10881131
<<~RUBY

0 commit comments

Comments
 (0)