repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/complex_node_spec.rb
spec/rubocop/ast/complex_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::ComplexNode do subject(:complex_node) { parse_source(source).ast } describe '.new' do let(:source) { '+4.2i' } it { is_expected.to be_a(described_class) } end describe '#sign?' do subject { complex_node.sign? } context 'when explicit positive complex' do let(:source) { '+4.2i' } it { is_expected.to be(true) } end context 'when explicit negative complex' do let(:source) { '-4.2i' } it { is_expected.to be(true) } end end describe '#value' do let(:source) { '+4.2i' } it { expect(complex_node.value).to eq(+4.2i) } end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/super_node_spec.rb
spec/rubocop/ast/super_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::SuperNode do subject(:super_node) { ast } let(:ast) { parse_source(source).ast } describe '.new' do context 'with a super node' do let(:source) { 'super(:baz)' } it { is_expected.to be_a(described_class) } end context 'with a zsuper node' do let(:source) { 'super' } it { is_expected.to be_a(described_class) } end end describe '#receiver' do let(:source) { 'super(foo)' } it { expect(super_node.receiver).to be_nil } end describe '#method_name' do let(:source) { 'super(foo)' } it { expect(super_node.method_name).to eq(:super) } end describe '#selector' do let(:source) { 'super(foo)' } it { expect(super_node.selector.source).to eq('super') } end describe '#method?' do context 'when message matches' do context 'when argument is a symbol' do let(:source) { 'super(:baz)' } it { is_expected.to be_method(:super) } end context 'when argument is a string' do let(:source) { 'super(:baz)' } it { is_expected.to be_method('super') } end end context 'when message does not match' do context 'when argument is a symbol' do let(:source) { 'super(:baz)' } it { is_expected.not_to be_method(:foo) } end context 'when argument is a string' do let(:source) { 'super(:baz)' } it { is_expected.not_to be_method('foo') } end end end describe '#macro?' do subject(:super_node) { ast.children[2] } let(:source) do ['def initialize', ' super(foo)', 'end'].join("\n") end it { is_expected.not_to be_macro } end describe '#command?' do context 'when argument is a symbol' do let(:source) { 'super(foo)' } it { is_expected.to be_command(:super) } end context 'when argument is a string' do let(:source) { 'super(foo)' } it { is_expected.to be_command('super') } end end describe '#setter_method?' do let(:source) { 'super(foo)' } it { is_expected.not_to be_setter_method } end describe '#operator_method?' do let(:source) { 'super(foo)' } it { is_expected.not_to be_operator_method } end describe '#comparison_method?' do let(:source) { 'super(foo)' } it { is_expected.not_to be_comparison_method } end describe '#assignment_method?' do let(:source) { 'super(foo)' } it { is_expected.not_to be_assignment_method } end describe '#dot?' do let(:source) { 'super(foo)' } it { is_expected.not_to be_dot } end describe '#double_colon?' do let(:source) { 'super(foo)' } it { is_expected.not_to be_double_colon } end describe '#self_receiver?' do let(:source) { 'super(foo)' } it { is_expected.not_to be_self_receiver } end describe '#const_receiver?' do let(:source) { 'super(foo)' } it { is_expected.not_to be_const_receiver } end describe '#implicit_call?' do let(:source) { 'super(foo)' } it { is_expected.not_to be_implicit_call } end describe '#predicate_method?' do let(:source) { 'super(foo)' } it { is_expected.not_to be_predicate_method } end describe '#bang_method?' do let(:source) { 'super(foo)' } it { is_expected.not_to be_bang_method } end describe '#camel_case_method?' do let(:source) { 'super(foo)' } it { is_expected.not_to be_camel_case_method } end describe '#parenthesized?' do context 'with no arguments' do context 'when not using parentheses' do let(:source) { 'super' } it { is_expected.not_to be_parenthesized } end context 'when using parentheses' do let(:source) { 'foo.bar()' } it { is_expected.to be_parenthesized } end end context 'with arguments' do context 'when not using parentheses' do let(:source) { 'foo.bar :baz' } it { is_expected.not_to be_parenthesized } end context 'when using parentheses' do let(:source) { 'foo.bar(:baz)' } it { is_expected.to be_parenthesized } end end end describe '#block_argument?' do context 'with a block argument' do let(:source) { 'super(&baz)' } it { is_expected.to be_block_argument } end context 'with no arguments' do let(:source) { 'super' } it { is_expected.not_to be_block_argument } end context 'with regular arguments' do let(:source) { 'super(:baz)' } it { is_expected.not_to be_block_argument } end context 'with mixed arguments' do let(:source) { 'super(:baz, &qux)' } it { is_expected.to be_block_argument } end end describe '#block_literal?' do context 'with a block literal' do subject(:super_node) { ast.children[0] } let(:source) { 'super { |q| baz(q) }' } it { is_expected.to be_block_literal } end context 'with a block argument' do let(:source) { 'super(&baz)' } it { is_expected.not_to be_block_literal } end context 'with no block' do let(:source) { 'super' } it { is_expected.not_to be_block_literal } end end describe '#block_node' do context 'with a block literal' do subject(:super_node) { ast.children[0] } let(:source) { 'super { |q| baz(q) }' } it { expect(super_node.block_node).to be_block_type } end context 'with a block argument' do let(:source) { 'super(&baz)' } it { expect(super_node.block_node).to be_nil } end context 'with no block' do let(:source) { 'super' } it { expect(super_node.block_node).to be_nil } end end describe '#arguments' do context 'with no arguments' do let(:source) { 'super' } it { expect(super_node.arguments).to be_empty } end context 'with a single literal argument' do let(:source) { 'super(:baz)' } it { expect(super_node.arguments.size).to eq(1) } end context 'with a single splat argument' do let(:source) { 'super(*baz)' } it { expect(super_node.arguments.size).to eq(1) } end context 'with multiple literal arguments' do let(:source) { 'super(:baz, :qux)' } it { expect(super_node.arguments.size).to eq(2) } end context 'with multiple mixed arguments' do let(:source) { 'super(:baz, *qux)' } it { expect(super_node.arguments.size).to eq(2) } end end describe '#first_argument' do context 'with no arguments' do let(:source) { 'super' } it { expect(super_node.first_argument).to be_nil } end context 'with a single literal argument' do let(:source) { 'super(:baz)' } it { expect(super_node.first_argument).to be_sym_type } end context 'with a single splat argument' do let(:source) { 'super(*baz)' } it { expect(super_node.first_argument).to be_splat_type } end context 'with multiple literal arguments' do let(:source) { 'super(:baz, :qux)' } it { expect(super_node.first_argument).to be_sym_type } end context 'with multiple mixed arguments' do let(:source) { 'superr(:baz, *qux)' } it { expect(super_node.first_argument).to be_sym_type } end end describe '#last_argument' do context 'with no arguments' do let(:source) { 'super' } it { expect(super_node.last_argument).to be_nil } end context 'with a single literal argument' do let(:source) { 'super(:baz)' } it { expect(super_node.last_argument).to be_sym_type } end context 'with a single splat argument' do let(:source) { 'super(*baz)' } it { expect(super_node.last_argument).to be_splat_type } end context 'with multiple literal arguments' do let(:source) { 'super(:baz, :qux)' } it { expect(super_node.last_argument).to be_sym_type } end context 'with multiple mixed arguments' do let(:source) { 'super(:baz, *qux)' } it { expect(super_node.last_argument).to be_splat_type } end end describe '#arguments?' do context 'with no arguments' do let(:source) { 'super' } it { is_expected.not_to be_arguments } end context 'with a single literal argument' do let(:source) { 'super(:baz)' } it { is_expected.to be_arguments } end context 'with a single splat argument' do let(:source) { 'super(*baz)' } it { is_expected.to be_arguments } end context 'with multiple literal arguments' do let(:source) { 'super(:baz, :qux)' } it { is_expected.to be_arguments } end context 'with multiple mixed arguments' do let(:source) { 'super(:baz, *qux)' } it { is_expected.to be_arguments } end end describe '#splat_argument?' do context 'with a splat argument' do let(:source) { 'super(*baz)' } it { is_expected.to be_splat_argument } end context 'with no arguments' do let(:source) { 'super' } it { is_expected.not_to be_splat_argument } end context 'with regular arguments' do let(:source) { 'super(:baz)' } it { is_expected.not_to be_splat_argument } end context 'with mixed arguments' do let(:source) { 'super(:baz, *qux)' } it { is_expected.to be_splat_argument } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/or_node_spec.rb
spec/rubocop/ast/or_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::OrNode do subject(:or_node) { parse_source(source).ast } describe '.new' do context 'with a logical or node' do let(:source) do ':foo || :bar' end it { is_expected.to be_a(described_class) } end context 'with a semantic or node' do let(:source) do ':foo or :bar' end it { is_expected.to be_a(described_class) } end end describe '#logical_operator?' do context 'with a logical or node' do let(:source) do ':foo || :bar' end it { is_expected.to be_logical_operator } end context 'with a semantic or node' do let(:source) do ':foo or :bar' end it { is_expected.not_to be_logical_operator } end end describe '#semantic_operator?' do context 'with a logical or node' do let(:source) do ':foo || :bar' end it { is_expected.not_to be_semantic_operator } end context 'with a semantic or node' do let(:source) do ':foo or :bar' end it { is_expected.to be_semantic_operator } end end describe '#operator' do context 'with a logical or node' do let(:source) do ':foo || :bar' end it { expect(or_node.operator).to eq('||') } end context 'with a semantic or node' do let(:source) do ':foo or :bar' end it { expect(or_node.operator).to eq('or') } end end describe '#alternate_operator' do context 'with a logical or node' do let(:source) do ':foo || :bar' end it { expect(or_node.alternate_operator).to eq('or') } end context 'with a semantic or node' do let(:source) do ':foo or :bar' end it { expect(or_node.alternate_operator).to eq('||') } end end describe '#inverse_operator' do context 'with a logical or node' do let(:source) do ':foo || :bar' end it { expect(or_node.inverse_operator).to eq('&&') } end context 'with a semantic or node' do let(:source) do ':foo or :bar' end it { expect(or_node.inverse_operator).to eq('and') } end end describe '#lhs' do context 'with a logical or node' do let(:source) do ':foo || 42' end it { expect(or_node.lhs).to be_sym_type } end context 'with a semantic or node' do let(:source) do ':foo or 42' end it { expect(or_node.lhs).to be_sym_type } end end describe '#rhs' do context 'with a logical or node' do let(:source) do ':foo || 42' end it { expect(or_node.rhs).to be_int_type } end context 'with a semantic or node' do let(:source) do ':foo or 42' end it { expect(or_node.rhs).to be_int_type } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/keyword_splat_node_spec.rb
spec/rubocop/ast/keyword_splat_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::KeywordSplatNode do let(:kwsplat_node) { parse_source(source).ast.children.last } let(:source) { '{ a: 1, **foo }' } describe '.new' do it { expect(kwsplat_node).to be_a(described_class) } end describe '#hash_rocket?' do it { expect(kwsplat_node).not_to be_hash_rocket } end describe '#colon?' do it { expect(kwsplat_node).not_to be_colon } end describe '#key' do it { expect(kwsplat_node.key).to eq(kwsplat_node) } end describe '#value' do it { expect(kwsplat_node.value).to eq(kwsplat_node) } end describe '#operator' do it { expect(kwsplat_node.operator).to eq('**') } end describe '#kwsplat_type?' do it { expect(kwsplat_node).to be_kwsplat_type } end describe '#forwarded_kwrestarg_type?' do it { expect(kwsplat_node).not_to be_forwarded_kwrestarg_type } end context 'when forwarded keyword rest arguments', :ruby32 do let(:kwsplat_node) { parse_source(source).ast.children.last.children.last } let(:source) do <<~RUBY def foo(**) { a: 1, ** } end RUBY end describe '.new' do it { expect(kwsplat_node).to be_a(described_class) } end describe '#hash_rocket?' do it { expect(kwsplat_node).not_to be_hash_rocket } end describe '#colon?' do it { expect(kwsplat_node).not_to be_colon } end describe '#key' do it { expect(kwsplat_node.key).to eq(kwsplat_node) } end describe '#value' do it { expect(kwsplat_node.value).to eq(kwsplat_node) } end describe '#operator' do it { expect(kwsplat_node.operator).to eq('**') } end describe '#kwsplat_type?' do it { expect(kwsplat_node).to be_kwsplat_type } end describe '#forwarded_kwrestarg_type?' do it { expect(kwsplat_node).to be_forwarded_kwrestarg_type } end end describe '#same_line?' do let(:first_pair) { parse_source(source).ast.children[0] } let(:second_pair) { parse_source(source).ast.children[1] } context 'when both pairs are on the same line' do let(:source) do ['{', ' a: 1, **foo', '}'].join("\n") end it { expect(first_pair).to be_same_line(second_pair) } end context 'when a multiline pair shares the same line' do let(:source) do ['{', ' a: (', ' ), **foo', '}'].join("\n") end it { expect(first_pair).to be_same_line(second_pair) } it { expect(second_pair).to be_same_line(first_pair) } end context 'when pairs are on separate lines' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(first_pair).not_to be_same_line(second_pair) } end end describe '#key_delta' do let(:pair_node) { parse_source(source).ast.children[0] } let(:kwsplat_node) { parse_source(source).ast.children[1] } context 'with alignment set to :left' do context 'when using colon delimiters' do context 'when keyword splat is aligned' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node)).to eq(0) } end context 'when keyword splat is ahead' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node)).to eq(2) } end context 'when keyword splat is behind' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node)).to eq(-2) } end context 'when keyword splat is on the same line' do let(:source) do ['{', ' a: 1, **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node)).to eq(0) } end end context 'when using hash rocket delimiters' do context 'when keyword splat is aligned' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node)).to eq(0) } end context 'when keyword splat is ahead' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node)).to eq(2) } end context 'when keyword splat is behind' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node)).to eq(-2) } end context 'when keyword splat is on the same line' do let(:source) do ['{', ' a => 1, **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node)).to eq(0) } end end end context 'with alignment set to :right' do context 'when using colon delimiters' do context 'when keyword splat is aligned' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node, :right)).to eq(0) } end context 'when keyword splat is ahead' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node, :right)).to eq(0) } end context 'when keyword splat is behind' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node, :right)).to eq(0) } end context 'when keyword splat is on the same line' do let(:source) do ['{', ' a: 1, **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node, :right)).to eq(0) } end end context 'when using hash rocket delimiters' do context 'when keyword splat is aligned' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node, :right)).to eq(0) } end context 'when keyword splat is ahead' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node, :right)).to eq(0) } end context 'when keyword splat is behind' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node, :right)).to eq(0) } end context 'when keyword splat is on the same line' do let(:source) do ['{', ' a => 1, **foo', '}'].join("\n") end it { expect(kwsplat_node.key_delta(pair_node, :right)).to eq(0) } end end end end describe '#value_delta' do let(:pair_node) { parse_source(source).ast.children[0] } let(:kwsplat_node) { parse_source(source).ast.children[1] } context 'when using colon delimiters' do context 'when keyword splat is left aligned' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.value_delta(pair_node)).to eq(0) } end context 'when keyword splat is ahead' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.value_delta(pair_node)).to eq(0) } end context 'when keyword splat is behind' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.value_delta(pair_node)).to eq(0) } end context 'when keyword splat is on the same line' do let(:source) do ['{', ' a: 1, **foo', '}'].join("\n") end it { expect(kwsplat_node.value_delta(pair_node)).to eq(0) } end end context 'when using hash rocket delimiters' do context 'when keyword splat is left aligned' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.value_delta(pair_node)).to eq(0) } end context 'when keyword splat is ahead' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.value_delta(pair_node)).to eq(0) } end context 'when keyword splat is behind' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(kwsplat_node.value_delta(pair_node)).to eq(0) } end context 'when keyword splat is on the same line' do let(:source) do ['{', ' a => 1, **foo', '}'].join("\n") end it { expect(kwsplat_node.value_delta(pair_node)).to eq(0) } end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/int_node_spec.rb
spec/rubocop/ast/int_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::IntNode do subject(:int_node) { parse_source(source).ast } describe '.new' do let(:source) { '42' } it { is_expected.to be_a(described_class) } end describe '#sign?' do subject { int_node.sign? } context 'explicit positive int' do let(:source) { '+42' } it { is_expected.to be(true) } end context 'explicit negative int' do let(:source) { '-42' } it { is_expected.to be(true) } end end describe '#value' do let(:source) do '10' end it { expect(int_node.value).to eq(10) } end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/pair_node_spec.rb
spec/rubocop/ast/pair_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::PairNode do let(:pair_node) { parse_source(source).ast.children.first } describe '.new' do let(:source) { '{ a: 1 }' } it { expect(pair_node).to be_a(described_class) } end describe '#hash_rocket?' do context 'when using a hash rocket delimiter' do let(:source) { '{ a => 1 }' } it { expect(pair_node).to be_hash_rocket } end context 'when using a colon delimiter' do let(:source) { '{ a: 1 }' } it { expect(pair_node).not_to be_hash_rocket } end end describe '#colon?' do context 'when using a hash rocket delimiter' do let(:source) { '{ a => 1 }' } it { expect(pair_node).not_to be_colon } end context 'when using a colon delimiter' do let(:source) { '{ a: 1 }' } it { expect(pair_node).to be_colon } end end describe '#delimiter' do context 'when using a hash rocket delimiter' do let(:source) { '{ a => 1 }' } it { expect(pair_node.delimiter).to eq('=>') } it { expect(pair_node.delimiter(true)).to eq(' => ') } end context 'when using a colon delimiter' do let(:source) { '{ a: 1 }' } it { expect(pair_node.delimiter).to eq(':') } it { expect(pair_node.delimiter(true)).to eq(': ') } end end describe '#inverse_delimiter' do context 'when using a hash rocket delimiter' do let(:source) { '{ a => 1 }' } it { expect(pair_node.inverse_delimiter).to eq(':') } it { expect(pair_node.inverse_delimiter(true)).to eq(': ') } end context 'when using a colon delimiter' do let(:source) { '{ a: 1 }' } it { expect(pair_node.inverse_delimiter).to eq('=>') } it { expect(pair_node.inverse_delimiter(true)).to eq(' => ') } end end describe '#key' do context 'when using a symbol key' do let(:source) { '{ a: 1 }' } it { expect(pair_node.key).to be_sym_type } end context 'when using a string key' do let(:source) { "{ 'a' => 1 }" } it { expect(pair_node.key).to be_str_type } end end describe '#value' do let(:source) { '{ a: 1 }' } it { expect(pair_node.value).to be_int_type } end describe '#value_on_new_line?' do let(:pair) { parse_source(source).ast.children[0] } context 'when value starts on a new line' do let(:source) do ['{', ' a:', ' 1', '}'].join("\n") end it { expect(pair).to be_value_on_new_line } end context 'when value spans multiple lines' do let(:source) do ['{', ' a: (', ' )', '}'].join("\n") end it { expect(pair).not_to be_value_on_new_line } end context 'when pair is on a single line' do let(:source) { "{ 'a' => 1 }" } it { expect(pair).not_to be_value_on_new_line } end end describe '#same_line?' do let(:first_pair) { parse_source(source).ast.children[0] } let(:second_pair) { parse_source(source).ast.children[1] } context 'when both pairs are on the same line' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a: 1, b: 2', '}'].join("\n") end it { expect(first_pair).to be_same_line(second_pair) } end context 'when both pair is a keyword splat' do let(:source) do ['{', ' a: 1, **foo', '}'].join("\n") end it { expect(first_pair).to be_same_line(second_pair) } end end context 'when a multiline pair shares the same line' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a: (', ' ), b: 2', '}'].join("\n") end it { expect(first_pair).to be_same_line(second_pair) } it { expect(second_pair).to be_same_line(first_pair) } end context 'when last pair is a keyword splat' do let(:source) do ['{', ' a: (', ' ), **foo', '}'].join("\n") end it { expect(first_pair).to be_same_line(second_pair) } it { expect(second_pair).to be_same_line(first_pair) } end end context 'when pairs are on separate lines' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a: 1,', ' b: 2', '}'].join("\n") end it { expect(first_pair).not_to be_same_line(second_pair) } end context 'when last pair is a keyword splat' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(first_pair).not_to be_same_line(second_pair) } end end end describe '#key_delta' do let(:first_pair) { parse_source(source).ast.children[0] } let(:second_pair) { parse_source(source).ast.children[1] } context 'with alignment set to :left' do context 'when using colon delimiters' do context 'when keys are aligned' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a: 1,', ' b: 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(0) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(0) } end end context 'when receiver key is behind' do context 'when both pairs are reail pairs' do let(:source) do ['{', ' a: 1,', ' b: 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(-2) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(-2) } end end context 'when receiver key is ahead' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a: 1,', ' b: 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(2) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(2) } end end context 'when both keys are on the same line' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a: 1, b: 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(0) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a: 1, **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(0) } end end end context 'when using hash rocket delimiters' do context 'when keys are aligned' do context 'when both keys are explicit keys' do let(:source) do ['{', ' a => 1,', ' b => 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(0) } end context 'when second key is a keyword splat' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(0) } end end context 'when receiver key is behind' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a => 1,', ' b => 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(-2) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(-2) } end end context 'when receiver key is ahead' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a => 1,', ' b => 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(2) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(2) } end end context 'when both keys are on the same line' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a => 1, b => 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(0) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a => 1, **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair)).to eq(0) } end end end end context 'with alignment set to :right' do context 'when using colon delimiters' do context 'when keys are aligned' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a: 1,', ' b: 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(0) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(0) } end end context 'when receiver key is behind' do context 'when both pairs are reail pairs' do let(:source) do ['{', ' a: 1,', ' b: 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(-2) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(0) } end end context 'when receiver key is ahead' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a: 1,', ' b: 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(2) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(0) } end end context 'when both keys are on the same line' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a: 1, b: 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(0) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a: 1, **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(0) } end end end context 'when using hash rocket delimiters' do context 'when keys are aligned' do context 'when both keys are explicit keys' do let(:source) do ['{', ' a => 1,', ' b => 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(0) } end context 'when second key is a keyword splat' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(0) } end end context 'when receiver key is behind' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a => 1,', ' b => 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(-2) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(0) } end end context 'when receiver key is ahead' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a => 1,', ' b => 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(2) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(0) } end end context 'when both keys are on the same line' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a => 1, b => 2', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(0) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a => 1, **foo', '}'].join("\n") end it { expect(first_pair.key_delta(second_pair, :right)).to eq(0) } end end end end end describe '#value_delta' do let(:first_pair) { parse_source(source).ast.children[0] } let(:second_pair) { parse_source(source).ast.children[1] } context 'when using colon delimiters' do context 'when values are aligned' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a: 1,', ' b: 2', '}'].join("\n") end it { expect(first_pair.value_delta(second_pair)).to eq(0) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a: 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.value_delta(second_pair)).to eq(0) } end end context 'when receiver value is behind' do let(:source) do ['{', ' a: 1,', ' b: 2', '}'].join("\n") end it { expect(first_pair.value_delta(second_pair)).to eq(-2) } end context 'when receiver value is ahead' do let(:source) do ['{', ' a: 1,', ' b: 2', '}'].join("\n") end it { expect(first_pair.value_delta(second_pair)).to eq(2) } end context 'when both pairs are on the same line' do let(:source) do ['{', ' a: 1, b: 2', '}'].join("\n") end it { expect(first_pair.value_delta(second_pair)).to eq(0) } end end context 'when using hash rocket delimiters' do context 'when values are aligned' do context 'when both pairs are explicit pairs' do let(:source) do ['{', ' a => 1,', ' b => 2', '}'].join("\n") end it { expect(first_pair.value_delta(second_pair)).to eq(0) } end context 'when second pair is a keyword splat' do let(:source) do ['{', ' a => 1,', ' **foo', '}'].join("\n") end it { expect(first_pair.value_delta(second_pair)).to eq(0) } end end context 'when receiver value is behind' do let(:source) do ['{', ' a => 1,', ' b => 2', '}'].join("\n") end it { expect(first_pair.value_delta(second_pair)).to eq(-2) } end context 'when receiver value is ahead' do let(:source) do ['{', ' a => 1,', ' b => 2', '}'].join("\n") end it { expect(first_pair.value_delta(second_pair)).to eq(2) } end context 'when both pairs are on the same line' do let(:source) do ['{', ' a => 1, b => 2', '}'].join("\n") end it { expect(first_pair.value_delta(second_pair)).to eq(0) } end end end describe '#value_omission?' do context 'when using hash value omission', :ruby31 do let(:source) { '{ x: }' } it { expect(pair_node).to be_value_omission } end context 'when not using hash value omission' do let(:source) { '{ x: x }' } it { expect(pair_node).not_to be_value_omission } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/lambda_node_spec.rb
spec/rubocop/ast/lambda_node_spec.rb
# frozen_string_literal: true # NOTE: specs for `lambda?` and `lambda_literal?` in `send_node_spec` RSpec.describe RuboCop::AST::LambdaNode do subject(:lambda_node) { parse_source(source).ast } let(:source) { '->(a, b) { a + b }' } describe '#receiver' do it { expect(lambda_node.receiver).to be_nil } end describe '#method_name' do it { expect(lambda_node.method_name).to eq :lambda } end describe '#arguments' do it { expect(lambda_node.arguments.size).to eq 2 } end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/return_node_spec.rb
spec/rubocop/ast/return_node_spec.rb
# frozen_string_literal: true require_relative 'wrapped_arguments_node' RSpec.describe RuboCop::AST::ReturnNode do it_behaves_like 'wrapped arguments node', 'return' end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/op_asgn_node_spec.rb
spec/rubocop/ast/op_asgn_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::OpAsgnNode do let(:parsed_source) { parse_source(source) } let(:op_asgn_node) { parsed_source.ast } describe '.new' do context 'with an `op_asgn_node` node' do let(:source) { 'var += value' } it { expect(op_asgn_node).to be_a(described_class) } end end describe '#assignment_node' do subject { op_asgn_node.assignment_node } let(:source) { 'var += value' } let(:node) { parsed_source.node } it { is_expected.to be_a(RuboCop::AST::AsgnNode) } context 'when the LHS is a `send` node' do let(:source) { '>> foo.var << += value' } it { is_expected.to eq(node) } end context 'when the LHS is a `csend` node' do let(:source) { '>> foo&.var << += value' } it { is_expected.to eq(node) } end end describe '#name' do subject { op_asgn_node.name } let(:source) { 'var += value' } it { is_expected.to eq(:var) } context 'when the LHS is a `send` node' do let(:source) { 'foo.var += value' } it { is_expected.to eq(:var) } end context 'when the LHS is a `csend` node' do let(:source) { 'foo&.var += value' } it { is_expected.to eq(:var) } end end describe '#operator' do subject { op_asgn_node.operator } context 'with +=' do let(:source) { 'var += value' } it { is_expected.to eq(:+) } end context 'with -=' do let(:source) { 'var -= value' } it { is_expected.to eq(:-) } end context 'with *=' do let(:source) { 'var *= value' } it { is_expected.to eq(:*) } end context 'with /=' do let(:source) { 'var /= value' } it { is_expected.to eq(:/) } end context 'with &=' do let(:source) { 'var &= value' } it { is_expected.to eq(:&) } end context 'with |=' do let(:source) { 'var |= value' } it { is_expected.to eq(:|) } end context 'with %=' do let(:source) { 'var %= value' } it { is_expected.to eq(:%) } end context 'with **=' do let(:source) { 'var **= value' } it { is_expected.to eq(:**) } end end describe '#expression' do include AST::Sexp subject { op_asgn_node.expression } let(:source) { 'var += value' } it { is_expected.to eq(s(:send, nil, :value)) } end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/resbody_node_spec.rb
spec/rubocop/ast/resbody_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::ResbodyNode do let(:resbody_node) do begin_node = parse_source(source).ast rescue_node, = *begin_node rescue_node.children[1] end describe '.new' do let(:source) { 'begin; beginbody; rescue; rescuebody; end' } it { expect(resbody_node).to be_a(described_class) } end describe '#exceptions' do context 'without exception' do let(:source) { <<~RUBY } begin rescue end RUBY it { expect(resbody_node.exceptions.size).to eq(0) } end context 'with a single exception' do let(:source) { <<~RUBY } begin rescue FooError end RUBY it { expect(resbody_node.exceptions.size).to eq(1) } it { expect(resbody_node.exceptions).to all(be_const_type) } end context 'with multiple exceptions' do let(:source) { <<~RUBY } begin rescue FooError, BarError end RUBY it { expect(resbody_node.exceptions.size).to eq(2) } it { expect(resbody_node.exceptions).to all(be_const_type) } end end describe '#exception_variable' do context 'for an explicit rescue' do let(:source) { 'begin; beginbody; rescue Error => ex; rescuebody; end' } it { expect(resbody_node.exception_variable.source).to eq('ex') } end context 'for an implicit rescue' do let(:source) { 'begin; beginbody; rescue => ex; rescuebody; end' } it { expect(resbody_node.exception_variable.source).to eq('ex') } end context 'when an exception variable is not given' do let(:source) { 'begin; beginbody; rescue; rescuebody; end' } it { expect(resbody_node.exception_variable).to be_nil } end end describe '#body' do let(:source) { 'begin; beginbody; rescue Error => ex; :rescuebody; end' } it { expect(resbody_node.body).to be_sym_type } end describe '#branch_index' do let(:source) { <<~RUBY } begin rescue FooError then foo rescue BarError, BazError then bar_and_baz rescue QuuxError => e then quux end RUBY let(:resbodies) { parse_source(source).ast.children.first.resbody_branches } it { expect(resbodies[0].branch_index).to eq(0) } it { expect(resbodies[1].branch_index).to eq(1) } it { expect(resbodies[2].branch_index).to eq(2) } end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/node_pattern_spec.rb
spec/rubocop/ast/node_pattern_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::NodePattern do include RuboCop::AST::Sexp def parse(code) RuboCop::AST::ProcessedSource.new(code, ruby_version, '(string)').ast end let(:ruby_version) { 3.3 } let(:root_node) { parse(ruby) } let(:node) { root_node } let(:params) { [] } let(:keyword_params) { {} } let(:instance) { described_class.new(pattern) } let(:method_name) { :match } let(:result) do instance.match(node, *params, **keyword_params) end RSpec::Matchers.define :match_code do |code, *params, **keyword_params| match do |pattern| instance = pattern.is_a?(String) ? described_class.new(pattern) : pattern code = parse(code) if code.is_a?(String) instance.public_send(method_name, code, *params, **keyword_params) end end RSpec::Matchers.define_negated_matcher :not_match_code, :match_code def match_codes(*codes) codes.map { |code| match_code(code) }.inject(:and) end def not_match_codes(*codes) codes.map { |code| not_match_code(code) }.inject(:and) end shared_examples 'nonmatching' do it "doesn't match" do expect(result).to be_nil end end shared_examples 'invalid' do it 'is invalid' do expect { instance } .to raise_error(described_class::Invalid) end end shared_examples 'single capture' do it 'yields captured value(s) and returns true if there is a block' do expect do |probe| compiled = instance retval = compiled.match(node, *params) do |capture| probe.to_proc.call(capture) :retval_from_block end expect(retval).to be :retval_from_block end.to yield_with_args(captured_val) end it 'returns captured values if there is no block' do retval = instance.match(node, *params) expect(retval).to eq captured_val end end shared_examples 'multiple capture' do it 'yields captured value(s) and returns true if there is a block' do expect do |probe| compiled = instance retval = compiled.match(node, *params) do |*captures| probe.to_proc.call(captures) :retval_from_block end expect(retval).to be :retval_from_block end.to yield_with_args(captured_vals) end it 'returns captured values if there is no block' do retval = instance.match(node, *params) expect(retval).to eq captured_vals end end describe 'bare node type' do let(:pattern) { 'send' } context 'on a node with the same type' do let(:ruby) { 'obj.method' } it { expect(pattern).to match_code(node) } end context 'on a node with a different type' do let(:ruby) { '@ivar' } it_behaves_like 'nonmatching' end context 'on a node with a matching, hyphenated type' do let(:pattern) { 'op-asgn' } let(:ruby) { 'a += 1' } # this is an (op-asgn ...) node it { expect(pattern).to match_code(node) } end describe '#pattern' do it 'returns the pattern' do expect(instance.pattern).to eq pattern end end describe '#to_s' do it 'is instructive' do expect(instance.to_s).to include pattern end end describe 'marshal compatibility' do let(:instance) { Marshal.load(Marshal.dump(super())) } let(:ruby) { 'obj.method' } it { expect(pattern).to match_code(node) } end describe '#dup' do let(:instance) { super().dup } let(:ruby) { 'obj.method' } it { expect(pattern).to match_code(node) } end describe 'yaml compatibility' do let(:instance) do YAML.safe_load(YAML.dump(super()), permitted_classes: [described_class]) end let(:ruby) { 'obj.method' } it { expect(pattern).to match_code(node) } end describe '#==' do let(:pattern) { " (send 42 \n :to_s ) " } it 'returns true iff the patterns are similar' do expect(instance == instance.dup).to be true expect(instance == 42).to be false expect(instance == described_class.new('(send)')).to be false expect(instance == described_class.new('(send 42 :to_s)')).to be true end end end describe 'node type' do describe 'in seq head' do let(:pattern) { '(send ...)' } context 'on a node with the same type' do let(:ruby) { '@ivar + 2' } it { expect(pattern).to match_code(node) } end context 'on a child with a different type' do let(:ruby) { '@ivar += 2' } it_behaves_like 'nonmatching' end end describe 'for a child' do let(:pattern) { '(_ send ...)' } context 'on a child with the same type' do let(:ruby) { 'foo.bar' } it { expect(pattern).to match_code(node) } end context 'on a child with a different type' do let(:ruby) { '@ivar.bar' } it_behaves_like 'nonmatching' end context 'on a child litteral' do let(:pattern) { '(_ _ send)' } let(:ruby) { '42.bar' } it_behaves_like 'nonmatching' end end end describe 'literals' do context 'negative integer literals' do let(:pattern) { '(int -100)' } let(:ruby) { '-100' } it { expect(pattern).to match_code(node) } end context 'positive float literals' do let(:pattern) { '(float 1.0)' } let(:ruby) { '1.0' } it { expect(pattern).to match_code(node) } end context 'negative float literals' do let(:pattern) { '(float -2.5)' } let(:ruby) { '-2.5' } it { expect(pattern).to match_code(node) } end context 'single quoted string literals' do let(:pattern) { '(str "foo")' } let(:ruby) { '"foo"' } it { expect(pattern).to match_code(node) } end context 'double quoted string literals' do let(:pattern) { '(str "foo")' } let(:ruby) { "'foo'" } it { expect(pattern).to match_code(node) } end context 'empty string literals' do let(:pattern) { '(str "")' } let(:ruby) { '""' } it { expect(pattern).to match_code(node) } end context 'symbol literals' do let(:pattern) { '(sym :foo)' } let(:ruby) { ':foo' } it { expect(pattern).to match_code(node) } end describe 'bare literal' do let(:ruby) { ':bar' } let(:pattern) { ':bar' } context 'on a node' do it_behaves_like 'nonmatching' end context 'on a matching literal' do let(:node) { root_node.children[0] } it { expect(pattern).to match_code(node) } end end end describe 'nil' do context 'nil literals' do let(:pattern) { '(nil)' } let(:ruby) { 'nil' } it { expect(pattern).to match_code(node) } end context 'nil value in AST' do let(:pattern) { '(send nil :foo)' } let(:ruby) { 'foo' } it_behaves_like 'nonmatching' end context 'nil value in AST, use nil? method' do let(:pattern) { '(send nil? :foo)' } let(:ruby) { 'foo' } it { expect(pattern).to match_code(node) } end context 'against a node pattern (bug #5470)' do let(:pattern) { '(:send (:const ...) ...)' } let(:ruby) { 'foo' } it_behaves_like 'nonmatching' end end describe 'simple sequence' do let(:pattern) { '(send int :+ int)' } context 'on a node with the same type and matching children' do let(:ruby) { '1 + 1' } it { expect(pattern).to match_code(node) } end context 'on a node with a different type' do let(:ruby) { 'a = 1' } it_behaves_like 'nonmatching' end context 'on a node with the same type and non-matching children' do context 'with non-matching selector' do let(:ruby) { '1 - 1' } it_behaves_like 'nonmatching' end context 'with non-matching receiver type' do let(:ruby) { '1.0 + 1' } it_behaves_like 'nonmatching' end end context 'on a node with too many children' do let(:pattern) { '(send int :blah int)' } let(:ruby) { '1.blah(1, 2)' } it_behaves_like 'nonmatching' end context 'with a nested sequence in head position' do let(:pattern) { '((send) int :blah)' } it_behaves_like 'invalid' end context 'with a nested sequence in non-head position' do let(:pattern) { '(send (send _ :a) :b)' } let(:ruby) { 'obj.a.b' } it { expect(pattern).to match_code(node) } end end describe 'sequence with trailing ...' do let(:pattern) { '(send int :blah ...)' } context 'on a node with the same type and exact number of children' do let(:ruby) { '1.blah' } it { expect(pattern).to match_code(node) } end context 'on a node with the same type and more children' do context 'with 1 child more' do let(:ruby) { '1.blah(1)' } it { expect(pattern).to match_code(node) } end context 'with 2 children more' do let(:ruby) { '1.blah(1, :something)' } it { expect(pattern).to match_code(node) } end end context 'on a node with the same type and fewer children' do let(:pattern) { '(send int :blah int int ...)' } let(:ruby) { '1.blah(2)' } it_behaves_like 'nonmatching' end context 'on a node with fewer children, with a wildcard preceding' do let(:pattern) { '(hash _ ...)' } let(:ruby) { '{}' } it_behaves_like 'nonmatching' end context 'on a node with a different type' do let(:ruby) { 'A = 1' } it_behaves_like 'nonmatching' end context 'on a node with non-matching children' do let(:ruby) { '1.foo' } it_behaves_like 'nonmatching' end end describe 'wildcards' do describe 'unnamed wildcards' do context 'at the root level' do let(:pattern) { '_' } let(:ruby) { 'class << self; def something; 1; end end.freeze' } it { expect(pattern).to match_code(node) } end context 'within a sequence' do let(:pattern) { '(const _ _)' } let(:ruby) { 'Const' } it { expect(pattern).to match_code(node) } end context 'within a sequence with other patterns intervening' do let(:pattern) { '(ivasgn _ (int _))' } let(:ruby) { '@abc = 22' } it { expect(pattern).to match_code(node) } end context 'in head position of a sequence' do let(:pattern) { '(_ int ...)' } let(:ruby) { '1 + a' } it { expect(pattern).to match_code(node) } end context 'negated' do let(:pattern) { '!_' } let(:ruby) { '123' } it_behaves_like 'nonmatching' end end describe 'named wildcards' do # unification is done on named wildcards! context 'at the root level' do let(:pattern) { '_node' } let(:ruby) { 'class << self; def something; 1; end end.freeze' } it { expect(pattern).to match_code(node) } end context 'within a sequence' do context 'with values which can be unified' do let(:pattern) { '(send _num :+ _num)' } let(:ruby) { '5 + 5' } it { expect(pattern).to match_code(node) } end context 'with values which cannot be unified' do let(:pattern) { '(send _num :+ _num)' } let(:ruby) { '5 + 4' } it_behaves_like 'nonmatching' end context 'unifying the node type with an argument' do let(:pattern) { '(_type _ _type)' } let(:ruby) { 'obj.send' } it { expect(pattern).to match_code(node) } end end context 'within a sequence with other patterns intervening' do let(:pattern) { '(ivasgn _ivar (int _val))' } let(:ruby) { '@abc = 22' } it { expect(pattern).to match_code(node) } end context 'in head position of a sequence' do let(:pattern) { '(_type int ...)' } let(:ruby) { '1 + a' } it { expect(pattern).to match_code(node) } end context 'within a union' do context 'confined to the union' do context 'without unification' do let(:pattern) { '{(array (int 1) _num) (array _num (int 1))}' } let(:ruby) { '[2, 1]' } it { expect(pattern).to match_code(node) } end context 'with partial unification' do let(:pattern) { '{(array _num _num) (array _num (int 1))}' } context 'matching the unified branch' do let(:ruby) { '[5, 5]' } it { expect(pattern).to match_code(node) } end context 'matching the free branch' do let(:ruby) { '[2, 1]' } it { expect(pattern).to match_code(node) } end context 'that can not be unified' do let(:ruby) { '[3, 2]' } it_behaves_like 'nonmatching' end end end context 'with a preceding unifying constraint' do let(:pattern) do '(array _num {(array (int 1) _num) send (array _num (int 1))})' end context 'matching a branch' do let(:ruby) { '[2, [2, 1]]' } it { expect(pattern).to match_code(node) } end context 'that can not be unified' do let(:ruby) { '[3, [2, 1]]' } it_behaves_like 'nonmatching' end end context 'with a succeeding unifying constraint' do context 'with branches without the wildcard' do context 'encountered first' do let(:pattern) do '(array {send (array (int 1) _num) } _num)' end it_behaves_like 'invalid' end context 'encountered after' do let(:pattern) do '(array {(array (int 1) _num) (array _num (int 1)) send } _num)' end it_behaves_like 'invalid' end end context 'with all branches with the wildcard' do let(:pattern) do '(array {(array (int 1) _num) (array _num (int 1)) } _num)' end context 'matching the first branch' do let(:ruby) { '[[1, 2], 2]' } it { expect(pattern).to match_code(node) } end context 'matching another branch' do let(:ruby) { '[[2, 1], 2]' } it { expect(pattern).to match_code(node) } end context 'that can not be unified' do let(:ruby) { '[[2, 1], 1]' } it_behaves_like 'nonmatching' end end end end end end describe 'unions' do context 'at the top level' do context 'containing symbol literals' do context 'when the AST has a matching symbol' do let(:pattern) { '(send _ {:a :b})' } let(:ruby) { 'obj.b' } it { expect(pattern).to match_code(node) } end context 'when the AST does not have a matching symbol' do let(:pattern) { '(send _ {:a :b})' } let(:ruby) { 'obj.c' } it_behaves_like 'nonmatching' end end context 'containing string literals' do let(:pattern) { '(send (str {"a" "b"}) :upcase)' } let(:ruby) { '"a".upcase' } it { expect(pattern).to match_code(node) } end context 'containing integer literals' do let(:pattern) { '(send (int {1 10}) :abs)' } let(:ruby) { '10.abs' } it { expect(pattern).to match_code(node) } end context 'containing mixed node and literals' do let(:pattern) { '(send {int nil?} ...)' } let(:ruby) { 'obj' } it { expect(pattern).to match_code(node) } end context 'containing multiple []' do let(:pattern) { '{[(int odd?) int] [!nil float]}' } context 'on a node which meets all requirements of the first []' do let(:ruby) { '3' } it { expect(pattern).to match_code(node) } end context 'on a node which meets all requirements of the second []' do let(:ruby) { '2.4' } it { expect(pattern).to match_code(node) } end context 'on a node which meets some requirements but not all' do let(:ruby) { '2' } it_behaves_like 'nonmatching' end end end context 'nested inside a sequence' do let(:pattern) { '(send {const int} ...)' } let(:ruby) { 'Const.method' } it { expect(pattern).to match_code(node) } end context 'with a nested sequence' do let(:pattern) { '{(send int ...) (send const ...)}' } let(:ruby) { 'Const.method' } it { expect(pattern).to match_code(node) } end context 'variadic' do context 'with fixed terms' do it 'works for cases with fixed arity before and after union' do expect('(_ { int | sym _ str | } const)').to match_codes( '[X]', '[42, X]', '[:foo, //, "bar", X]' ).and not_match_codes( '[42]', '[4.2, X]', '["bar", //, :foo, X]' ) end it 'works for cases with variadic terms after union' do expect('(_ { int | sym _ str | } const+)').to match_codes( '[X]', '[42, X, Y, Z]', '[:foo, //, "bar", X]' ).and not_match_codes( '[42]', '[4.2, X]', '["bar", //, :foo, X]' ) end it 'works for cases with variadic terms before and after union' do expect('(_ const ? { int | sym _ str | } const+)').to match_codes( '[X]', '[FOO, 42, X, Y, Z]', '[:foo, //, "bar", X]', '[X, Y, Z]' ).and not_match_codes( '[42]', '[4.2, X]', '["bar", //, :foo, X]', '[FOO BAR, 42]' ) end end context 'with variadic terms' do it 'works for cases with fixed arity before and after union' do expect('(_ { sym+ _ str | int* } const)').to match_codes( '[X]', '[42, 666, X]', '[:foo, :foo2, //, "bar", X]' ).and not_match_codes( '[42]', '[4.2, X]', '["bar", //, :foo, X]' ) end it 'works for cases with variadic terms after union' do expect('(_ { sym+ _ str | int* } const+)').to match_codes( '[X]', '[42, 666, X, Y, Z]', '[:foo, :foo2, //, "bar", X]' ).and not_match_codes( '[42]', '[4.2, X]', '["bar", //, :foo, X]' ) end it 'works for cases with variadic terms before and after union' do expect('(_ const ? { sym+ _ str | int* } const+)').to match_codes( '[X]', '[FOO, 42, 666, X, Y, Z]', '[:foo, :foo2, //, "bar", X]', '[X, Y, Z]' ).and not_match_codes( '[42]', '[4.2, X]', '["bar", //, :foo, X]', '[FOO BAR, 42]' ) end end context 'multiple' do it 'works for complex cases' do expect('(_ const ? { sym+ int+ | int+ sym+ } { str+ | regexp+ } ... )').to match_codes( '[X, :foo, :bar, 42, "a", Y]', '[42, 666, :foo, //]' ).and not_match_codes( '[42, :almost, X]', '[X, 42, :foo, 42, //]', '[X, :foo, //, :foo, X]' ) end end end end describe 'captures on a wildcard' do context 'at the root level' do let(:pattern) { '$_' } let(:ruby) { 'begin; raise StandardError; rescue Exception => e; end' } let(:captured_val) { node } it_behaves_like 'single capture' end context 'in head position in a sequence' do let(:pattern) { '($_ ...)' } let(:ruby) { 'A.method' } let(:captured_val) { :send } it_behaves_like 'single capture' end context 'in head position in a sequence against nil (bug #5470)' do let(:pattern) { '($_ ...)' } let(:ruby) { '' } it_behaves_like 'nonmatching' end context 'in head position in a sequence against literal (bug #5470)' do let(:pattern) { '(int ($_ ...))' } let(:ruby) { '42' } it_behaves_like 'nonmatching' end context 'in non-head position in a sequence' do let(:pattern) { '(send $_ ...)' } let(:ruby) { 'A.method' } let(:captured_val) { s(:const, nil, :A) } it_behaves_like 'single capture' end context 'in a nested sequence' do let(:pattern) { '(send (const nil? $_) ...)' } let(:ruby) { 'A.method' } let(:captured_val) { :A } it_behaves_like 'single capture' end context 'nested in any child' do let(:pattern) { '(send $<(const nil? $_) $...>)' } let(:ruby) { 'A.method' } let(:captured_vals) { [[s(:const, nil, :A), :method], :A, [:method]] } it_behaves_like 'multiple capture' end end describe 'captures which also perform a match' do context 'on a sequence' do let(:pattern) { '(send $(send _ :keys) :each)' } let(:ruby) { '{}.keys.each' } let(:captured_val) { s(:send, s(:hash), :keys) } it_behaves_like 'single capture' end context 'on a set' do let(:pattern) { '(send _ ${:inc :dec})' } let(:ruby) { '1.dec' } let(:captured_val) { :dec } it_behaves_like 'single capture' end context 'on []' do let(:pattern) { '(send (int $[!odd? !zero?]) :inc)' } let(:ruby) { '2.inc' } let(:captured_val) { 2 } it_behaves_like 'single capture' end context 'on a node type' do let(:pattern) { '(send $int :inc)' } let(:ruby) { '5.inc' } let(:captured_val) { s(:int, 5) } it_behaves_like 'single capture' end context 'on a literal' do let(:pattern) { '(send int $:inc)' } let(:ruby) { '5.inc' } let(:captured_val) { :inc } it_behaves_like 'single capture' end context 'when nested' do let(:pattern) { '(send $(int $_) :inc)' } let(:ruby) { '5.inc' } let(:captured_vals) { [s(:int, 5), 5] } it_behaves_like 'multiple capture' end end describe 'captures on ...' do context 'with no remaining pattern at the end' do let(:pattern) { '(send $...)' } let(:ruby) { '5.inc' } let(:captured_val) { [s(:int, 5), :inc] } it_behaves_like 'single capture' end context 'with a remaining node type at the end' do let(:pattern) { '(send $... int)' } let(:ruby) { '5 + 4' } let(:captured_val) { [s(:int, 5), :+] } it_behaves_like 'single capture' end context 'with remaining patterns at the end' do let(:pattern) { '(send $... int int)' } let(:ruby) { '[].push(1, 2, 3)' } let(:captured_val) { [s(:array), :push, s(:int, 1)] } it_behaves_like 'single capture' end context 'with a remaining sequence at the end' do let(:pattern) { '(send $... (int 4))' } let(:ruby) { '5 + 4' } let(:captured_val) { [s(:int, 5), :+] } it_behaves_like 'single capture' end context 'with a remaining set at the end' do let(:pattern) { '(send $... {int float})' } let(:ruby) { '5 + 4' } let(:captured_val) { [s(:int, 5), :+] } it_behaves_like 'single capture' end context 'with a remaining [] at the end' do let(:pattern) { '(send $... [(int even?) (int zero?)])' } let(:ruby) { '5 + 0' } let(:captured_val) { [s(:int, 5), :+] } it_behaves_like 'single capture' end context 'with a remaining literal at the end' do let(:pattern) { '(send $... :inc)' } let(:ruby) { '5.inc' } let(:captured_val) { [s(:int, 5)] } it_behaves_like 'single capture' end context 'with a remaining wildcard at the end' do let(:pattern) { '(send $... _)' } let(:ruby) { '5.inc' } let(:captured_val) { [s(:int, 5)] } it_behaves_like 'single capture' end context 'with a remaining capture at the end' do let(:pattern) { '(send $... $_)' } let(:ruby) { '5 + 4' } let(:captured_vals) { [[s(:int, 5), :+], s(:int, 4)] } it_behaves_like 'multiple capture' end context 'at the very beginning of a sequence' do let(:pattern) { '($... (int 1))' } let(:ruby) { '10 * 1' } let(:captured_val) { [s(:int, 10), :*] } it_behaves_like 'single capture' end context 'after a child' do let(:pattern) { '(send (int 10) $...)' } let(:ruby) { '10 * 1' } let(:captured_val) { [:*, s(:int, 1)] } it_behaves_like 'single capture' end end describe 'captures within union' do context 'on simple subpatterns' do let(:pattern) { '{$send $int $float}' } let(:ruby) { '2.0' } let(:captured_val) { s(:float, 2.0) } it_behaves_like 'single capture' end context 'within nested sequences' do let(:pattern) { '{(send $_ $_) (const $_ $_)}' } let(:ruby) { 'Namespace::CONST' } let(:captured_vals) { [s(:const, nil, :Namespace), :CONST] } it_behaves_like 'multiple capture' end context 'with complex nesting' do let(:pattern) do '{(send {$int $float} {$:inc $:dec}) ' \ '[!nil {($_ sym $_) (send ($_ $_) :object_id)}]}' end let(:ruby) { '10.object_id' } let(:captured_vals) { [:int, 10] } it_behaves_like 'multiple capture' end context 'with a different number of captures in each branch' do let(:pattern) { '{(send $...) (int $...) (send $_ $_)}' } it_behaves_like 'invalid' end context 'using repetition' do shared_examples 'repetition' do |behavior| context 'with one capture' do let(:pattern) { pattern_placeholder.sub('{}', '{$_}') } it_behaves_like behavior end context 'with two captures' do let(:pattern) { pattern_placeholder.sub('{}', '{$_ | $_}') } it_behaves_like behavior end context 'with three captures' do let(:pattern) { pattern_placeholder.sub('{}', '{$_ | $_ | $_}') } it_behaves_like behavior end end context 'with ?' do context 'one capture' do let(:pattern_placeholder) { '(send _ _ (int {})?)' } context 'one match' do it_behaves_like 'repetition', 'single capture' do let(:ruby) { 'foo(1)' } let(:captured_val) { [1] } end end context 'no match' do it_behaves_like 'repetition', 'single capture' do let(:ruby) { 'foo' } let(:captured_val) { [] } end end end context 'two captures' do let(:pattern_placeholder) { '(send _ $_ (int {})?)' } context 'one match' do it_behaves_like 'repetition', 'multiple capture' do let(:ruby) { 'foo(1)' } let(:captured_vals) { [:foo, [1]] } end end context 'no match' do it_behaves_like 'repetition', 'multiple capture' do let(:ruby) { 'foo' } let(:captured_vals) { [:foo, []] } end end end end context 'with +' do context 'one capture' do let(:pattern_placeholder) { '(send _ _ (int {})+)' } context 'one match' do it_behaves_like 'repetition', 'single capture' do let(:ruby) { 'foo(1)' } let(:captured_val) { [1] } end end context 'two matches' do it_behaves_like 'repetition', 'single capture' do let(:ruby) { 'foo(1, 2)' } let(:captured_val) { [1, 2] } end end context 'no match' do it_behaves_like 'repetition', 'nonmatching' do let(:ruby) { 'foo' } end end end context 'two captures' do let(:pattern_placeholder) { '(send _ $_ (int {})+)' } context 'one match' do it_behaves_like 'repetition', 'multiple capture' do let(:ruby) { 'foo(1)' } let(:captured_vals) { [:foo, [1]] } end end context 'two matches' do it_behaves_like 'repetition', 'multiple capture' do let(:ruby) { 'foo(1, 2)' } let(:captured_vals) { [:foo, [1, 2]] } end end context 'no match' do it_behaves_like 'repetition', 'nonmatching' do let(:ruby) { 'foo' } end end end end context 'with *' do context 'one capture' do let(:pattern_placeholder) { '(send _ _ (int {})*)' } context 'one match' do it_behaves_like 'repetition', 'single capture' do let(:ruby) { 'foo(1)' } let(:captured_val) { [1] } end end context 'two matches' do it_behaves_like 'repetition', 'single capture' do let(:ruby) { 'foo(1, 2)' } let(:captured_val) { [1, 2] } end end context 'no match' do it_behaves_like 'repetition', 'single capture' do let(:ruby) { 'foo' } let(:captured_val) { [] } end end end context 'two captures' do let(:pattern_placeholder) { '(send _ $_ (int {})*)' } context 'one match' do it_behaves_like 'repetition', 'multiple capture' do let(:ruby) { 'foo(1)' } let(:captured_vals) { [:foo, [1]] } end end context 'two matches' do it_behaves_like 'repetition', 'multiple capture' do let(:ruby) { 'foo(1, 2)' } let(:captured_vals) { [:foo, [1, 2]] } end end context 'no match' do it_behaves_like 'repetition', 'multiple capture' do let(:ruby) { 'foo' } let(:captured_vals) { [:foo, []] } end end end end end end describe 'negation' do context 'on a symbol' do let(:pattern) { '(send _ !:abc)' } context 'with a matching symbol' do let(:ruby) { 'obj.abc' } it_behaves_like 'nonmatching' end context 'with a non-matching symbol' do let(:ruby) { 'obj.xyz' } it { expect(pattern).to match_code(node) } end context 'with a non-matching symbol, but too many children' do let(:ruby) { 'obj.xyz(1)' } it_behaves_like 'nonmatching' end end context 'on a string' do let(:pattern) { '(send (str !"foo") :upcase)' } context 'with a matching string' do let(:ruby) { '"foo".upcase' } it_behaves_like 'nonmatching' end context 'with a non-matching symbol' do let(:ruby) { '"bar".upcase' } it { expect(pattern).to match_code(node) } end end context 'on a set' do let(:pattern) { '(ivasgn _ !(int {1 2}))' } context 'with a matching value' do let(:ruby) { '@a = 1' } it_behaves_like 'nonmatching' end context 'with a non-matching value' do let(:ruby) { '@a = 3' } it { expect(pattern).to match_code(node) } end end context 'on a sequence' do let(:pattern) { '!(ivasgn :@a ...)' } context 'with a matching node' do let(:ruby) { '@a = 1' } it_behaves_like 'nonmatching' end context 'with a node of different type' do let(:ruby) { '@@a = 1' } it { expect(pattern).to match_code(node) } end context 'with a node with non-matching children' do let(:ruby) { '@b = 1' } it { expect(pattern).to match_code(node) } end end context 'on square brackets' do let(:pattern) { '![!int !float]' } context 'with a node which meets all requirements of []' do let(:ruby) { '"abc"' } it_behaves_like 'nonmatching' end context 'with a node which meets only 1 requirement of []' do let(:ruby) { '1' } it { expect(pattern).to match_code(node) } end end context 'when nested in complex ways' do
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
true
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/case_match_node_spec.rb
spec/rubocop/ast/case_match_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::CaseMatchNode do subject(:case_match_node) { parse_source(source).ast } context 'when using Ruby 2.7 or newer', :ruby27 do describe '.new' do let(:source) do <<~RUBY case expr in pattern end RUBY end it { is_expected.to be_a(described_class) } end describe '#keyword' do let(:source) do <<~RUBY case expr in pattern end RUBY end it { expect(case_match_node.keyword).to eq('case') } end describe '#in_pattern_branches' do let(:source) do <<~RUBY case expr in pattern in pattern in pattern end RUBY end it { expect(case_match_node.in_pattern_branches.size).to eq(3) } it { expect(case_match_node.in_pattern_branches).to all(be_in_pattern_type) } end describe '#each_in_pattern' do let(:source) do <<~RUBY case expr in pattern in pattern in pattern end RUBY end context 'when not passed a block' do it { expect(case_match_node.each_in_pattern).to be_a(Enumerator) } end context 'when passed a block' do it 'yields all the conditions' do expect { |b| case_match_node.each_in_pattern(&b) } .to yield_successive_args(*case_match_node.in_pattern_branches) end end end describe '#else?' do context 'without an else statement' do let(:source) do <<~RUBY case expr in pattern end RUBY end it { is_expected.not_to be_else } end context 'with an else statement' do let(:source) do <<~RUBY case expr in pattern else end RUBY end it { is_expected.to be_else } end end describe '#else_branch' do describe '#else?' do context 'without an else statement' do let(:source) do <<~RUBY case expr in pattern end RUBY end it { expect(case_match_node.else_branch).to be_nil } end context 'with an else statement' do let(:source) do <<~RUBY case expr in pattern else :foo end RUBY end it { expect(case_match_node.else_branch).to be_sym_type } end context 'with an empty else statement' do let(:source) do <<~RUBY case expr in pattern else end RUBY end it { expect(case_match_node.else_branch).to be_empty_else_type } end end end describe '#branches' do context 'when there is an else' do context 'with else body' do let(:source) { <<~RUBY } case pattern in :foo then # do nothing in :bar then 42 else 'hello' end RUBY it 'returns all the bodies' do expect(case_match_node.branches).to match [nil, be_int_type, be_str_type] end end context 'with empty else' do let(:source) { <<~RUBY } case pattern in :foo then # do nothing in :bar then 42 else # do nothing end RUBY it 'returns all the bodies' do expect(case_match_node.branches).to match [nil, be_int_type, nil] end end end context 'when there is no else keyword' do let(:source) { <<~RUBY } case pattern in :foo then # do nothing in :bar then 42 end RUBY it 'returns only then when bodies' do expect(case_match_node.branches).to match [nil, be_int_type] end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/symbol_node_spec.rb
spec/rubocop/ast/symbol_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::SymbolNode do subject(:sym_node) { parse_source(source).ast } describe '.new' do context 'with a symbol node' do let(:source) do ':foo' end it { is_expected.to be_a(described_class) } end end describe '#value' do let(:source) do ':foo' end it { expect(sym_node.value).to eq(:foo) } end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/asgn_node_spec.rb
spec/rubocop/ast/asgn_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::AsgnNode do let(:asgn_node) { parse_source(source).ast } describe '.new' do context 'with a `lvasgn` node' do let(:source) { 'var = value' } it { expect(asgn_node).to be_a(described_class) } end context 'with a `ivasgn` node' do let(:source) { '@var = value' } it { expect(asgn_node).to be_a(described_class) } end context 'with a `cvasgn` node' do let(:source) { '@@var = value' } it { expect(asgn_node).to be_a(described_class) } end context 'with a `gvasgn` node' do let(:source) { '$var = value' } it { expect(asgn_node).to be_a(described_class) } end end describe '#name' do subject { asgn_node.name } context 'with a `lvasgn` node' do let(:source) { 'var = value' } it { is_expected.to eq(:var) } end context 'with a `ivasgn` node' do let(:source) { '@var = value' } it { is_expected.to eq(:@var) } end context 'with a `cvasgn` node' do let(:source) { '@@var = value' } it { is_expected.to eq(:@@var) } end context 'with a `gvasgn` node' do let(:source) { '$var = value' } it { is_expected.to eq(:$var) } end end describe '#expression' do include AST::Sexp subject { asgn_node.expression } context 'with a `lvasgn` node' do let(:source) { 'var = value' } it { is_expected.to eq(s(:send, nil, :value)) } end context 'with a `ivasgn` node' do let(:source) { '@var = value' } it { is_expected.to eq(s(:send, nil, :value)) } end context 'with a `cvasgn` node' do let(:source) { '@@var = value' } it { is_expected.to eq(s(:send, nil, :value)) } end context 'with a `gvasgn` node' do let(:source) { '$var = value' } it { is_expected.to eq(s(:send, nil, :value)) } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/const_node_spec.rb
spec/rubocop/ast/const_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::ConstNode do subject(:ast) { parse_source(source).ast } let(:const_node) { ast } let(:source) { '::Foo::Bar::BAZ' } describe '#namespace' do it { expect(const_node.namespace.source).to eq '::Foo::Bar' } end describe '#short_name' do it { expect(const_node.short_name).to eq :BAZ } end describe '#module_name?' do it { expect(const_node).not_to be_module_name } context 'with a constant with a lowercase letter' do let(:source) { '::Foo::Bar' } it { expect(const_node).to be_module_name } end end describe '#absolute?' do it { expect(const_node).to be_absolute } context 'with a constant not starting with ::' do let(:source) { 'Foo::Bar::BAZ' } it { expect(const_node).not_to be_absolute } end context 'with a non-namespaced constant' do let(:source) { 'Foo' } it { expect(const_node).not_to be_absolute } end end describe '#relative?' do context 'with a non-namespaced constant' do let(:source) { 'Foo' } it { expect(const_node).to be_relative } end end describe '#each_path' do let(:source) { 'var = ::Foo::Bar::BAZ' } let(:const_node) { ast.children.last } it 'yields all parts of the namespace' do expect(const_node.each_path.map(&:type)).to eq %i[cbase const const] expect(const_node.each_path.to_a.last(2).map(&:short_name)).to eq %i[Foo Bar] end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/ensure_node_spec.rb
spec/rubocop/ast/ensure_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::EnsureNode do let(:parsed_source) { parse_source(source) } let(:ensure_node) { parsed_source.ast.children.first } let(:node) { parsed_source.node } describe '.new' do let(:source) { 'begin; beginbody; ensure; ensurebody; end' } it { expect(ensure_node).to be_a(described_class) } end describe '#branch' do let(:source) { 'begin; beginbody; ensure; >>ensurebody<<; end' } it { expect(ensure_node.branch).to eq(node) } end describe '#rescue_node' do subject(:rescue_node) { ensure_node.rescue_node } context 'when there is no `rescue` node' do let(:source) do <<~RUBY begin beginbody ensure ensurebody end RUBY end it { is_expected.to be_nil } end context 'when there is a `rescue` node' do let(:source) do <<~RUBY begin beginbody rescue rescuebody ensure ensurebody end RUBY end it { is_expected.to be_a(RuboCop::AST::RescueNode) } end end describe '#void_context?' do let(:source) { 'begin; beginbody; ensure; ensurebody; end' } it { expect(ensure_node).to be_void_context } end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/regexp_node_spec.rb
spec/rubocop/ast/regexp_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::RegexpNode do subject(:regexp_node) { parse_source(source).ast } describe '.new' do let(:source) { '/re/' } it { is_expected.to be_a(described_class) } end describe '#to_regexp' do # rubocop:disable Security/Eval context 'with an empty regexp' do let(:source) { '//' } it { expect(regexp_node.to_regexp).to eq(eval(source)) } end context 'with a regexp without option' do let(:source) { '/.+/' } it { expect(regexp_node.to_regexp).to eq(eval(source)) } end context 'with a multi-line regexp without option' do let(:source) { "/\n.+\n/" } it { expect(regexp_node.to_regexp).to eq(eval(source)) } end context 'with an empty regexp with option' do let(:source) { '//ix' } it { expect(regexp_node.to_regexp).to eq(eval(source)) } end context 'with a regexp with option' do let(:source) { '/.+/imx' } it { expect(regexp_node.to_regexp).to eq(eval(source)) } end context 'with a multi-line regexp with option' do let(:source) { "/\n.+\n/ix" } it { expect(regexp_node.to_regexp).to eq(eval(source)) } end # rubocop:enable Security/Eval context 'with a regexp with an "o" option' do let(:source) { '/abc/io' } it { expect(regexp_node.to_regexp.inspect).to eq('/abc/i') } end context 'with a regexp with an "n" option' do let(:source) { '/abc/n' } it { expect(regexp_node.to_regexp.inspect).to eq('/abc/n') } end context 'with a regexp with an "u" option' do let(:source) { '/abc/u' } it { expect(regexp_node.to_regexp.inspect).to eq('/abc/') } end end describe '#regopt' do let(:regopt) { regexp_node.regopt } context 'with an empty regexp' do let(:source) { '//' } it { expect(regopt).to be_regopt_type } it { expect(regopt.children).to be_empty } end context 'with a regexp without option' do let(:source) { '/.+/' } it { expect(regopt).to be_regopt_type } it { expect(regopt.children).to be_empty } end context 'with a multi-line regexp without option' do let(:source) { "/\n.+\n/" } it { expect(regopt).to be_regopt_type } it { expect(regopt.children).to be_empty } end context 'with an empty regexp with option' do let(:source) { '//ix' } it { expect(regopt).to be_regopt_type } it { expect(regopt.children).to eq(%i[i x]) } end context 'with a regexp with option' do let(:source) { '/.+/imx' } it { expect(regopt).to be_regopt_type } it { expect(regopt.children).to eq(%i[i m x]) } end context 'with a multi-line regexp with option' do let(:source) { "/\n.+\n/imx" } it { expect(regopt).to be_regopt_type } it { expect(regopt.children).to eq(%i[i m x]) } end end describe '#options' do let(:actual_options) { regexp_node.options } # rubocop:disable Security/Eval let(:expected_options) { eval(source).options } # rubocop:enable Security/Eval context 'with an empty regexp' do let(:source) { '//' } it { expect(actual_options).to eq(expected_options) } end context 'with a regexp without option' do let(:source) { '/.+/' } it { expect(actual_options).to eq(expected_options) } end context 'with a regexp with single option' do let(:source) { '/.+/i' } it { expect(actual_options).to eq(expected_options) } end context 'with a regexp with multiple options' do let(:source) { '/.+/ix' } it { expect(actual_options).to eq(expected_options) } end context 'with a regexp with "o" option' do let(:source) { '/.+/o' } it { expect(actual_options).to eq(expected_options) } end end describe '#content' do let(:content) { regexp_node.content } context 'with an empty regexp' do let(:source) { '//' } it { expect(content).to eq('') } end context 'with a regexp without option' do let(:source) { '/.+/' } it { expect(content).to eq('.+') } end context 'with a multi-line regexp without option' do let(:source) { "/\n.+\n/" } it { expect(content).to eq("\n.+\n") } end context 'with an empty regexp with option' do let(:source) { '//ix' } it { expect(content).to eq('') } end context 'with a regexp with option' do let(:source) { '/.+/imx' } it { expect(content).to eq('.+') } end context 'with a multi-line regexp with option' do let(:source) { "/\n.+\n/imx" } it { expect(content).to eq("\n.+\n") } end end describe '#slash_literal?' do context 'with /-delimiters' do let(:source) { '/abc/' } it { is_expected.to be_slash_literal } end context 'with %r/-delimiters' do let(:source) { '%r/abc/' } it { is_expected.not_to be_slash_literal } end context 'with %r{-delimiters' do let(:source) { '%r{abc}' } it { is_expected.not_to be_slash_literal } end context 'with multi-line %r{-delimiters' do let(:source) do <<~SRC %r{ abc }x SRC end it { is_expected.not_to be_slash_literal } end context 'with %r<-delimiters' do let(:source) { '%r<abc>x' } it { is_expected.not_to be_slash_literal } end end describe '#percent_r_literal?' do context 'with /-delimiters' do let(:source) { '/abc/' } it { is_expected.not_to be_percent_r_literal } end context 'with %r/-delimiters' do let(:source) { '%r/abc/' } it { is_expected.to be_percent_r_literal } end context 'with %r{-delimiters' do let(:source) { '%r{abc}' } it { is_expected.to be_percent_r_literal } end context 'with multi-line %r{-delimiters' do let(:source) do <<~SRC %r{ abc }x SRC end it { is_expected.to be_percent_r_literal } end context 'with %r<-delimiters' do let(:source) { '%r<abc>x' } it { is_expected.to be_percent_r_literal } end end describe '#delimiters' do context 'with /-delimiters' do let(:source) { '/abc/' } it { expect(regexp_node.delimiters).to eq(['/', '/']) } end context 'with %r/-delimiters' do let(:source) { '%r/abc/' } it { expect(regexp_node.delimiters).to eq(['/', '/']) } end context 'with %r{-delimiters' do let(:source) { '%r{abc}' } it { expect(regexp_node.delimiters).to eq(['{', '}']) } end context 'with multi-line %r{-delimiters' do let(:source) do <<~SRC %r{ abc }x SRC end it { expect(regexp_node.delimiters).to eq(['{', '}']) } end context 'with %r<-delimiters' do let(:source) { '%r<abc>x' } it { expect(regexp_node.delimiters).to eq(['<', '>']) } end end describe '#delimiter?' do context 'with /-delimiters' do let(:source) { '/abc/' } it { is_expected.to be_delimiter('/') } it { is_expected.not_to be_delimiter('{') } end context 'with %r/-delimiters' do let(:source) { '%r/abc/' } it { is_expected.to be_delimiter('/') } it { is_expected.not_to be_delimiter('{') } it { is_expected.not_to be_delimiter('}') } it { is_expected.not_to be_delimiter('%') } it { is_expected.not_to be_delimiter('r') } it { is_expected.not_to be_delimiter('%r') } it { is_expected.not_to be_delimiter('%r/') } end context 'with %r{-delimiters' do let(:source) { '%r{abc}' } it { is_expected.to be_delimiter('{') } it { is_expected.to be_delimiter('}') } it { is_expected.not_to be_delimiter('/') } it { is_expected.not_to be_delimiter('%') } it { is_expected.not_to be_delimiter('r') } it { is_expected.not_to be_delimiter('%r') } it { is_expected.not_to be_delimiter('%r/') } it { is_expected.not_to be_delimiter('%r{') } end context 'with multi-line %r{-delimiters' do let(:source) do <<~SRC %r{ abc }x SRC end it { is_expected.to be_delimiter('{') } it { is_expected.to be_delimiter('}') } it { is_expected.not_to be_delimiter('/') } it { is_expected.not_to be_delimiter('%') } it { is_expected.not_to be_delimiter('r') } it { is_expected.not_to be_delimiter('%r') } it { is_expected.not_to be_delimiter('%r/') } it { is_expected.not_to be_delimiter('%r{') } end context 'with %r<-delimiters' do let(:source) { '%r<abc>x' } it { is_expected.to be_delimiter('<') } it { is_expected.to be_delimiter('>') } it { is_expected.not_to be_delimiter('{') } it { is_expected.not_to be_delimiter('}') } it { is_expected.not_to be_delimiter('/') } it { is_expected.not_to be_delimiter('%') } it { is_expected.not_to be_delimiter('r') } it { is_expected.not_to be_delimiter('%r') } it { is_expected.not_to be_delimiter('%r/') } it { is_expected.not_to be_delimiter('%r{') } it { is_expected.not_to be_delimiter('%r<') } end end describe '#interpolation?' do context 'with direct variable interpoation' do let(:source) { '/\n\n#{foo}(abc)+/' } it { is_expected.to be_interpolation } end context 'with regexp quote' do let(:source) { '/\n\n#{Regexp.quote(foo)}(abc)+/' } it { is_expected.to be_interpolation } end context 'with no interpolation returns false' do let(:source) { '/a{3,6}/' } it { is_expected.not_to be_interpolation } end end describe '#multiline_mode?' do context 'with no options' do let(:source) { '/x/' } it { is_expected.not_to be_multiline_mode } end context 'with other options' do let(:source) { '/x/ix' } it { is_expected.not_to be_multiline_mode } end context 'with only m option' do let(:source) { '/x/m' } it { is_expected.to be_multiline_mode } end context 'with m and other options' do let(:source) { '/x/imx' } it { is_expected.to be_multiline_mode } end end describe '#extended?' do context 'with no options' do let(:source) { '/x/' } it { is_expected.not_to be_extended } end context 'with other options' do let(:source) { '/x/im' } it { is_expected.not_to be_extended } end context 'with only x option' do let(:source) { '/x/x' } it { is_expected.to be_extended } end context 'with x and other options' do let(:source) { '/x/ixm' } it { is_expected.to be_extended } end end describe '#ignore_case?' do context 'with no options' do let(:source) { '/x/' } it { is_expected.not_to be_ignore_case } end context 'with other options' do let(:source) { '/x/xm' } it { is_expected.not_to be_ignore_case } end context 'with only i option' do let(:source) { '/x/i' } it { is_expected.to be_ignore_case } end context 'with i and other options' do let(:source) { '/x/xim' } it { is_expected.to be_ignore_case } end end describe '#no_encoding?' do context 'with no options' do let(:source) { '/x/' } it { is_expected.not_to be_no_encoding } end context 'with other options' do let(:source) { '/x/xm' } it { is_expected.not_to be_no_encoding } end context 'with only n option' do let(:source) { '/x/n' } it { is_expected.to be_no_encoding } end context 'with n and other options' do let(:source) { '/x/xnm' } it { is_expected.to be_no_encoding } end end describe '#fixed_encoding?' do context 'with no options' do let(:source) { '/x/' } it { is_expected.not_to be_fixed_encoding } end context 'with other options' do let(:source) { '/x/xm' } it { is_expected.not_to be_fixed_encoding } end context 'with only u option' do let(:source) { '/x/u' } it { is_expected.to be_fixed_encoding } end context 'with u and other options' do let(:source) { '/x/unm' } it { is_expected.to be_fixed_encoding } end end describe '#single_interpolation?' do context 'with no options' do let(:source) { '/x/' } it { is_expected.not_to be_single_interpolation } end context 'with other options' do let(:source) { '/x/xm' } it { is_expected.not_to be_single_interpolation } end context 'with only o option' do let(:source) { '/x/o' } it { is_expected.to be_single_interpolation } end context 'with o and other options' do let(:source) { '/x/xom' } it { is_expected.to be_single_interpolation } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/array_node_spec.rb
spec/rubocop/ast/array_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::ArrayNode do subject(:array_node) { parse_source(source).ast } describe '.new' do let(:source) { '[]' } it { is_expected.to be_a(described_class) } end describe '#values' do context 'with an empty array' do let(:source) { '[]' } it { expect(array_node.values).to be_empty } end context 'with an array of literals' do let(:source) { '[1, 2, 3]' } it { expect(array_node.values.size).to eq(3) } it { expect(array_node.values).to all(be_literal) } end context 'with an array of variables' do let(:source) { '[foo, bar]' } it { expect(array_node.values.size).to eq(2) } it { expect(array_node.values).to all(be_send_type) } end end describe '#each_value' do let(:source) { '[1, 2, 3]' } context 'with block' do it { expect(array_node.each_value { nil }).to be_a(described_class) } it do ret = [] array_node.each_value { |i| ret << i.to_s } expect(ret).to eq(['(int 1)', '(int 2)', '(int 3)']) end end context 'without block' do it { expect(array_node.each_value).to be_a(Enumerator) } end end describe '#square_brackets?' do context 'with square brackets' do let(:source) { '[1, 2, 3]' } it { is_expected.to be_square_brackets } end context 'with a percent literal' do let(:source) { '%w(foo bar)' } it { is_expected.not_to be_square_brackets } end end describe '#percent_literal?' do context 'with square brackets' do let(:source) { '[1, 2, 3]' } it { is_expected.not_to be_percent_literal } it { is_expected.not_to be_percent_literal(:string) } it { is_expected.not_to be_percent_literal(:symbol) } end context 'with a string percent literal' do let(:source) { '%w(foo bar)' } it { is_expected.to be_percent_literal } it { is_expected.to be_percent_literal(:string) } it { is_expected.not_to be_percent_literal(:symbol) } end context 'with a symbol percent literal' do let(:source) { '%i(foo bar)' } it { is_expected.to be_percent_literal } it { is_expected.not_to be_percent_literal(:string) } it { is_expected.to be_percent_literal(:symbol) } end context 'with an invalid type' do let(:source) { '%i(foo bar)' } it 'raises KeyError' do expect { array_node.percent_literal?(:foo) }.to raise_error(KeyError, 'key not found: :foo') end end end describe '#bracketed?' do context 'with square brackets' do let(:source) { '[1, 2, 3]' } it { is_expected.to be_bracketed } end context 'with a percent literal' do let(:source) { '%w(foo bar)' } it { is_expected.to be_bracketed } end context 'unbracketed' do let(:array_node) do parse_source('foo = 1, 2, 3').ast.to_a.last end it { expect(array_node.bracketed?).to be_nil } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/var_node_spec.rb
spec/rubocop/ast/var_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::VarNode do let(:node) { parse_source(source).node } describe '.new' do context 'with a `lvar` node' do let(:source) { 'x = 1; >>x<<' } it { expect(node).to be_a(described_class) } end context 'with an `ivar` node' do let(:source) { '@x' } it { expect(node).to be_a(described_class) } end context 'with an `cvar` node' do let(:source) { '@@x' } it { expect(node).to be_a(described_class) } end context 'with an `gvar` node' do let(:source) { '$x' } it { expect(node).to be_a(described_class) } end end describe '#name' do subject { node.name } context 'with a `lvar` node' do let(:source) { 'x = 1; >>x<<' } it { is_expected.to eq(:x) } end context 'with an `ivar` node' do let(:source) { '@x' } it { is_expected.to eq(:@x) } end context 'with an `cvar` node' do let(:source) { '@@x' } it { is_expected.to eq(:@@x) } end context 'with an `gvar` node' do let(:source) { '$x' } it { is_expected.to eq(:$x) } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/break_node_spec.rb
spec/rubocop/ast/break_node_spec.rb
# frozen_string_literal: true require_relative 'wrapped_arguments_node' RSpec.describe RuboCop::AST::BreakNode do it_behaves_like 'wrapped arguments node', 'break' end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/casgn_node_spec.rb
spec/rubocop/ast/casgn_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::CasgnNode do let(:casgn_node) { parse_source(source).ast } describe '.new' do context 'with a `casgn` node' do let(:source) { 'VAR = value' } it { expect(casgn_node).to be_a(described_class) } end end describe '#namespace' do include AST::Sexp subject { casgn_node.namespace } context 'when there is no parent' do let(:source) { 'VAR = value' } it { is_expected.to be_nil } end context 'when the parent is a `cbase`' do let(:source) { '::VAR = value' } it { is_expected.to eq(s(:cbase)) } end context 'when the parent is a `const`' do let(:source) { 'FOO::VAR = value' } it { is_expected.to eq(s(:const, nil, :FOO)) } end end describe '#name' do subject { casgn_node.name } let(:source) { 'VAR = value' } it { is_expected.to eq(:VAR) } end describe '#short_name' do subject { casgn_node.short_name } let(:source) { 'VAR = value' } it { is_expected.to eq(:VAR) } end describe '#expression' do include AST::Sexp subject { casgn_node.expression } let(:source) { 'VAR = value' } it { is_expected.to eq(s(:send, nil, :value)) } end describe '#module_name?' do context 'with a constant with only uppercase letters' do let(:source) { 'VAR = value' } it { expect(casgn_node).not_to be_module_name } end context 'with a constant with a lowercase letter' do let(:source) { '::Foo::Bar = value' } it { expect(casgn_node).to be_module_name } end end describe '#absolute?' do context 'with a constant starting with ::' do let(:source) { '::VAR' } it { expect(casgn_node).to be_absolute } end context 'with a constant not starting with ::' do let(:source) { 'Foo::Bar::BAZ' } it { expect(casgn_node).not_to be_absolute } end context 'with a non-namespaced constant' do let(:source) { 'Foo' } it { expect(casgn_node).not_to be_absolute } end end describe '#relative?' do context 'with a constant starting with ::' do let(:source) { '::VAR' } it { expect(casgn_node).not_to be_relative } end context 'with a constant not starting with ::' do let(:source) { 'Foo::Bar::BAZ' } it { expect(casgn_node).to be_relative } end context 'with a non-namespaced constant' do let(:source) { 'Foo' } it { expect(casgn_node).to be_relative } end end describe '#each_path' do let(:source) { '::Foo::Bar::BAZ = value' } it 'yields all parts of the namespace' do expect(casgn_node.each_path.map(&:type)).to eq %i[cbase const const] expect(casgn_node.each_path.to_a.last(2).map(&:short_name)).to eq %i[Foo Bar] end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/next_node_spec.rb
spec/rubocop/ast/next_node_spec.rb
# frozen_string_literal: true require_relative 'wrapped_arguments_node' RSpec.describe RuboCop::AST::NextNode do it_behaves_like 'wrapped arguments node', 'next' end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/forward_args_node_spec.rb
spec/rubocop/ast/forward_args_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::ForwardArgsNode do let(:args_node) { parse_source(source).ast.arguments } let(:source) { 'def foo(...); end' } context 'when using Ruby 2.7 or newer', :ruby27 do if RuboCop::AST::Builder.emit_forward_arg describe '#to_a' do it { expect(args_node.to_a).to contain_exactly(be_forward_arg_type) } end else describe '.new' do it { expect(args_node).to be_a(described_class) } end describe '#to_a' do it { expect(args_node.to_a).to contain_exactly(args_node) } end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/processed_source_spec.rb
spec/rubocop/ast/processed_source_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::ProcessedSource do subject(:processed_source) do described_class.new( source, ruby_version, path, parser_engine: parser_engine, prism_result: prism_result ) end let(:source) { <<~RUBY } # an awesome method def some_method puts 'foo' end some_method RUBY let(:prism_result) { nil } let(:prism_parse_lex_result) { Prism.parse_lex(source) } let(:ast) { processed_source.ast } let(:path) { 'ast/and_node_spec.rb' } shared_context 'invalid encoding source' do let(:source) { "# \xf9" } end describe '#initialize' do context 'when parsing non UTF-8 frozen string' do let(:source) { (+'true').force_encoding(Encoding::ASCII_8BIT).freeze } it 'returns an instance of ProcessedSource' do is_expected.to be_a(described_class) end end context 'when parsing code with an invalid encoding comment' do let(:source) { '# encoding: foobar' } it 'returns a parser error' do expect(processed_source.parser_error).to be_a(Parser::UnknownEncodingInMagicComment) expect(processed_source.parser_error.message) .to include('unknown encoding name - foobar') end end shared_examples 'invalid parser_engine' do it 'raises ArgumentError' do expect { processed_source }.to raise_error(ArgumentError) do |e| expected = 'The keyword argument `parser_engine` accepts .*, ' \ "but `#{parser_engine}` was passed." expect(e.message).to match(expected) end end end context 'when using an invalid `parser_engine` symbol argument' do let(:parser_engine) { :unknown_parser_engine } it_behaves_like 'invalid parser_engine' end context 'when using an invalid `parser_engine` string argument' do let(:parser_engine) { 'unknown_parser_engine' } it_behaves_like 'invalid parser_engine' end context 'when using `parser_engine: :parser_prism` and `prism_result` with a `ParseLexResult`' do let(:ruby_version) { 3.4 } let(:parser_engine) { :parser_prism } let(:prism_result) { prism_parse_lex_result } it 'returns an instance of ProcessedSource' do is_expected.to be_a(described_class) end end context 'when `parser_engine` is `parser_whitequark`' do let(:parser_engine) { :parser_whitequark } context 'and Ruby 3.4 is requested' do let(:ruby_version) { 3.4 } it 'uses `parser_whitequark`' do expect(processed_source.parser_engine).to eq(:parser_whitequark) end end end context 'when `parser_engine` is `parser_prism`' do let(:parser_engine) { :parser_prism } context 'and Ruby 3.3 is requested' do let(:ruby_version) { 3.3 } it 'uses `parser_prism`' do expect(processed_source.parser_engine).to eq(:parser_prism) end end end context 'when `parser_engine` is `:default`' do let(:parser_engine) { :default } context 'and Ruby 3.3 is requested' do let(:ruby_version) { 3.3 } it 'uses `parser_whitequark`' do expect(processed_source.parser_engine).to eq(:parser_whitequark) end end context 'and Ruby 3.4 is requested' do let(:ruby_version) { 3.4 } it 'uses `parser_prism`' do expect(processed_source.parser_engine).to eq(:parser_prism) end end end end describe '.from_file' do describe 'when the file exists' do around do |example| org_pwd = Dir.pwd Dir.chdir("#{__dir__}/..") example.run Dir.chdir(org_pwd) end let(:processed_source) do described_class.from_file(path, ruby_version, parser_engine: parser_engine) end it 'returns an instance of ProcessedSource' do is_expected.to be_a(described_class) end it "sets the file path to the instance's #path" do expect(processed_source.path).to eq(path) end end it 'raises a Errno::ENOENT when the file does not exist' do expect do described_class.from_file('foo', ruby_version) end.to raise_error(Errno::ENOENT) end end describe '#path' do it 'is the path passed to .new' do expect(processed_source.path).to eq(path) end context 'when using `parser_engine: :parser_prism` and `prism_result` with a `ParseLexResult`' do let(:ruby_version) { 3.4 } let(:parser_engine) { :parser_prism } let(:prism_result) { prism_parse_lex_result } it 'is the path passed to .new' do expect(processed_source.path).to eq(path) end end end describe '#buffer' do it 'is a source buffer' do expect(processed_source.buffer).to be_a(Parser::Source::Buffer) end context 'when using `parser_engine: :parser_prism` and `prism_result` with a `ParseLexResult`' do let(:ruby_version) { 3.4 } let(:parser_engine) { :parser_prism } let(:prism_result) { prism_parse_lex_result } it 'is a source buffer' do expect(processed_source.buffer).to be_a(Parser::Source::Buffer) end end end describe '#ast' do it 'is the root node of AST' do expect(processed_source.ast).to be_a(RuboCop::AST::Node) end context 'when using `parser_engine: :parser_prism` and `prism_result` with a `ParseLexResult`' do let(:ruby_version) { 3.4 } let(:parser_engine) { :parser_prism } let(:prism_result) { prism_parse_lex_result } it 'is the root node of AST' do expect(processed_source.ast).to be_a(RuboCop::AST::Node) end end end describe '#comments' do it 'is an array of comments' do expect(processed_source.comments).to be_a(Array) expect( processed_source.comments.first ).to be_a(Parser::Source::Comment) end context 'when the source is invalid' do include_context 'invalid encoding source' it 'returns []' do expect(processed_source.comments).to eq [] end end end describe '#tokens' do it 'has an array of tokens' do expect(processed_source.tokens).to be_a(Array) expect(processed_source.tokens.first).to be_a(RuboCop::AST::Token) end end describe '#parser_error' do context 'when the source was properly parsed' do it 'is nil' do expect(processed_source.parser_error).to be_nil end end context 'when the source lacks encoding comment and is really utf-8 ' \ 'encoded but has been read as US-ASCII' do let(:source) do # When files are read into RuboCop, the encoding of source code # lacking an encoding comment will default to the external encoding, # which could for example be US-ASCII if the LC_ALL environment # variable is set to "C". (+'号码 = 3').force_encoding('US-ASCII') end it 'is nil' do # ProcessedSource#parse sets UTF-8 as default encoding, so no error. expect(processed_source.parser_error).to be_nil end end context 'when the source could not be parsed due to encoding error' do include_context 'invalid encoding source' it 'returns the error' do expect(processed_source.parser_error).to be_a(Exception) expect(processed_source.parser_error.message) .to include('invalid byte sequence') end end end describe '#lines' do it 'is an array' do expect(processed_source.lines).to be_a(Array) end it 'has same number of elements as line count' do # Since the source has a trailing newline, there is a final empty line expect(processed_source.lines.size).to eq(6) end it 'contains lines as string without linefeed' do first_line = processed_source.lines.first expect(first_line).to eq('# an awesome method') end end describe '#[]' do context 'when an index is passed' do it 'returns the line' do expect(processed_source[3]).to eq('end') end end context 'when a range is passed' do it 'returns the array of lines' do expect(processed_source[3..4]).to eq(%w[end some_method]) end end context 'when start index and length are passed' do it 'returns the array of lines' do expect(processed_source[3, 2]).to eq(%w[end some_method]) end end end describe 'valid_syntax?' do subject { processed_source.valid_syntax? } context 'when the source is completely valid' do let(:source) { 'def valid_code; end' } it 'returns true' do expect(processed_source.diagnostics).to be_empty expect(processed_source).to be_valid_syntax end end context 'when the source is invalid' do let(:source) { 'def invalid_code; en' } it 'returns false' do expect(processed_source).not_to be_valid_syntax end end context 'when the source is valid but has some warning diagnostics' do let(:source) { 'do_something *array' } it 'returns true' do expect(processed_source.diagnostics).not_to be_empty expect(processed_source.diagnostics.first.level).to eq(:warning) expect(processed_source).to be_valid_syntax end end context 'when the source could not be parsed due to encoding error' do include_context 'invalid encoding source' it 'returns false' do expect(processed_source).not_to be_valid_syntax end end # https://github.com/whitequark/parser/issues/283 context 'when the source itself is valid encoding but includes strange ' \ 'encoding literals that are accepted by MRI' do let(:source) do 'p "\xff"' end it 'returns true' do expect(processed_source.diagnostics).to be_empty expect(processed_source).to be_valid_syntax end end context 'when a line starts with an integer literal' do let(:source) { '1 + 1' } # regression test it 'tokenizes the source correctly' do expect(processed_source.tokens[0].text).to eq '1' end end end context 'with heavily commented source' do let(:source) { <<~RUBY } # comment one [ 1, { a: 2, b: 3 # comment two } ] RUBY describe '#each_comment' do it 'yields all comments' do comments = [] processed_source.each_comment do |item| expect(item).to be_a(Parser::Source::Comment) comments << item end expect(comments.size).to eq 2 end end describe '#find_comment' do it 'yields correct comment' do comment = processed_source.find_comment do |item| item.text == '# comment two' end expect(comment.text).to eq '# comment two' end it 'yields nil when there is no match' do comment = processed_source.find_comment do |item| item.text == '# comment four' end expect(comment).to be_nil end end describe '#comment_at_line' do it 'returns the comment at the given line number' do expect(processed_source.comment_at_line(1).text).to eq '# comment one' expect(processed_source.comment_at_line(4).text).to eq '# comment two' end it 'returns nil if line has no comment' do expect(processed_source.comment_at_line(3)).to be_nil end end describe '#each_comment_in_lines' do it 'yields the comments' do enum = processed_source.each_comment_in_lines(1..4) expect(enum).to be_a(Enumerable) expect(enum.to_a).to eq processed_source.comments expect(processed_source.each_comment_in_lines(2..5).map(&:text)).to eq ['# comment two'] end end describe '#line_with_comment?' do it 'returns true for lines with comments' do expect(processed_source).to be_line_with_comment(1) expect(processed_source).to be_line_with_comment(4) end it 'returns false for lines without comments' do expect(processed_source).not_to be_line_with_comment(2) expect(processed_source).not_to be_line_with_comment(5) end end describe '#contains_comment?' do subject(:commented) { processed_source.contains_comment?(range) } let(:array) { ast } let(:hash) { array.children[1] } context 'provided source_range on line without comment' do let(:range) { hash.pairs.first.source_range } it { is_expected.to be false } end context 'provided source_range on comment line' do let(:range) { processed_source.find_token(&:comment?).pos } it { is_expected.to be true } end context 'provided source_range on line with comment' do let(:range) { hash.pairs.last.source_range } it { is_expected.to be true } end context 'provided a multiline source_range with at least one line with comment' do let(:range) { array.source_range } it { is_expected.to be true } end end describe '#comments_before_line' do let(:source) { <<~RUBY } # comment one # comment two [ 1, 2 ] # comment three RUBY it 'returns comments on or before given line' do expect(processed_source.comments_before_line(1).size).to eq 1 expect(processed_source.comments_before_line(2).size).to eq 2 expect(processed_source.comments_before_line(3).size).to eq 2 expect(processed_source.comments_before_line(4).size).to eq 3 expect(processed_source.comments_before_line(1) .first).to be_a(Parser::Source::Comment) end end end context 'token enumerables' do let(:source) { <<~RUBY } foo(1, 2) RUBY describe '#each_token' do it 'yields all tokens' do tokens = [] processed_source.each_token do |item| expect(item).to be_a(RuboCop::AST::Token) tokens << item end expect(tokens.size).to eq 7 end end describe '#find_token' do it 'yields correct token' do token = processed_source.find_token(&:comma?) expect(token.text).to eq ',' end it 'yields nil when there is no match' do token = processed_source.find_token(&:right_bracket?) expect(token).to be_nil end end end describe '#file_path' do it 'returns file path' do expect(processed_source.file_path).to eq path end end describe '#blank?' do context 'with source of no content' do let(:source) { '' } it 'returns true' do expect(processed_source).to be_blank end end context 'with source with content' do let(:source) { <<~RUBY } foo RUBY it 'returns false' do expect(processed_source).not_to be_blank end end end # rubocop:disable RSpec/RedundantPredicateMatcher describe '#start_with?' do context 'with blank source' do let(:source) { '' } it 'returns false' do expect(processed_source).not_to be_start_with('start') expect(processed_source).not_to be_start_with('#') expect(processed_source).not_to be_start_with('') end end context 'with present source' do let(:source) { <<~RUBY } foo RUBY it 'returns true when passed string that starts source' do expect(processed_source).to be_start_with('foo') expect(processed_source).to be_start_with('f') expect(processed_source).to be_start_with('') end it 'returns false when passed string that does not start source' do expect(processed_source).not_to be_start_with('bar') expect(processed_source).not_to be_start_with('qux') expect(processed_source).not_to be_start_with('1') end end end # rubocop:enable RSpec/RedundantPredicateMatcher describe '#preceding_line' do let(:source) { <<~RUBY } [ line, 1 ] { line: 2 } # line 3 RUBY it 'returns source of line before token' do brace_token = processed_source.find_token(&:left_brace?) expect(processed_source.preceding_line(brace_token)).to eq '[ line, 1 ]' comment_token = processed_source.find_token(&:comment?) expect(processed_source.preceding_line(comment_token)).to eq '{ line: 2 }' end end describe '#following_line' do let(:source) { <<~RUBY } [ line, 1 ] { line: 2 } # line 3 RUBY it 'returns source of line after token' do bracket_token = processed_source.find_token(&:right_bracket?) expect(processed_source.following_line(bracket_token)).to eq '{ line: 2 }' brace_token = processed_source.find_token(&:left_brace?) expect(processed_source.following_line(brace_token)).to eq '# line 3' end end describe '#tokens_within' do let(:source) { <<~RUBY } foo(1, 2) bar(3) RUBY it 'returns tokens for node' do node = ast.children[1] tokens = processed_source.tokens_within(node.source_range) expect(tokens.map(&:text)).to eq(['bar', '(', '3', ')']) end it 'accepts Node as an argument' do node = ast.children[1] tokens = processed_source.tokens_within(node) expect(tokens.map(&:text)).to eq(['bar', '(', '3', ')']) end context 'when heredoc as argument is present' do let(:source) { <<~RUBY } foo(1, [before], <<~DOC, [after]) inside heredoc. DOC bar(2) RUBY it 'returns tokens for node before heredoc' do node = ast.children[0].arguments[1] tokens = processed_source.tokens_within(node.source_range) expect(tokens.map(&:text)).to eq(['[', 'before', ']']) end it 'returns tokens for heredoc node' do node = ast.children[0].arguments[2] tokens = processed_source.tokens_within(node.source_range) expect(tokens.map(&:text)).to eq(['<<"']) end it 'returns tokens for node after heredoc' do node = ast.children[0].arguments[3] tokens = processed_source.tokens_within(node.source_range) expect(tokens.map(&:text)).to eq(['[', 'after', ']']) end end end describe '#first_token_of' do let(:source) { <<~RUBY } foo(1, 2) bar(3) RUBY it 'returns first token for node' do node = ast.children[1] expect(processed_source.first_token_of(node.source_range).text).to eq('bar') end it 'accepts Node as an argument' do node = ast.children[1] expect(processed_source.first_token_of(node).text).to eq('bar') end end describe '#last_token_of' do let(:source) { <<~RUBY } foo(1, 2) bar = baz RUBY it 'returns last token for node' do node = ast.children[1] expect(processed_source.last_token_of(node.source_range).text).to eq('baz') end it 'accepts Node as an argument' do node = ast.children[1] expect(processed_source.last_token_of(node).text).to eq('baz') end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/module_node_spec.rb
spec/rubocop/ast/module_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::ModuleNode do subject(:module_node) { parse_source(source).ast } describe '.new' do let(:source) do 'module Foo; end' end it { is_expected.to be_a(described_class) } end describe '#identifier' do let(:source) do 'module Foo; end' end it { expect(module_node.identifier).to be_const_type } end describe '#body' do context 'with a single expression body' do let(:source) do 'module Foo; bar; end' end it { expect(module_node.body).to be_send_type } end context 'with a multi-expression body' do let(:source) do 'module Foo; bar; baz; end' end it { expect(module_node.body).to be_begin_type } end context 'with an empty body' do let(:source) do 'module Foo; end' end it { expect(module_node.body).to be_nil } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/and_node_spec.rb
spec/rubocop/ast/and_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::AndNode do subject(:and_node) { parse_source(source).ast } describe '.new' do context 'with a logical and node' do let(:source) do ':foo && :bar' end it { is_expected.to be_a(described_class) } end context 'with a semantic and node' do let(:source) do ':foo and :bar' end it { is_expected.to be_a(described_class) } end end describe '#logical_operator?' do context 'with a logical and node' do let(:source) do ':foo && :bar' end it { is_expected.to be_logical_operator } end context 'with a semantic and node' do let(:source) do ':foo and :bar' end it { is_expected.not_to be_logical_operator } end end describe '#semantic_operator?' do context 'with a logical and node' do let(:source) do ':foo && :bar' end it { is_expected.not_to be_semantic_operator } end context 'with a semantic and node' do let(:source) do ':foo and :bar' end it { is_expected.to be_semantic_operator } end end describe '#operator' do context 'with a logical and node' do let(:source) do ':foo && :bar' end it { expect(and_node.operator).to eq('&&') } end context 'with a semantic and node' do let(:source) do ':foo and :bar' end it { expect(and_node.operator).to eq('and') } end end describe '#alternate_operator' do context 'with a logical and node' do let(:source) do ':foo && :bar' end it { expect(and_node.alternate_operator).to eq('and') } end context 'with a semantic and node' do let(:source) do ':foo and :bar' end it { expect(and_node.alternate_operator).to eq('&&') } end end describe '#inverse_operator' do context 'with a logical and node' do let(:source) do ':foo && :bar' end it { expect(and_node.inverse_operator).to eq('||') } end context 'with a semantic and node' do let(:source) do ':foo and :bar' end it { expect(and_node.inverse_operator).to eq('or') } end end describe '#lhs' do context 'with a logical and node' do let(:source) do ':foo && 42' end it { expect(and_node.lhs).to be_sym_type } end context 'with a semantic and node' do let(:source) do ':foo and 42' end it { expect(and_node.lhs).to be_sym_type } end end describe '#rhs' do context 'with a logical and node' do let(:source) do ':foo && 42' end it { expect(and_node.rhs).to be_int_type } end context 'with a semantic and node' do let(:source) do ':foo and 42' end it { expect(and_node.rhs).to be_int_type } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/defined_node_spec.rb
spec/rubocop/ast/defined_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::DefinedNode do subject(:defined_node) { parse_source(source).ast } describe '.new' do context 'with a defined? node' do let(:source) { 'defined? :foo' } it { is_expected.to be_a(described_class) } end end describe '#receiver' do let(:source) { 'defined? :foo' } it { expect(defined_node.receiver).to be_nil } end describe '#method_name' do let(:source) { 'defined? :foo' } it { expect(defined_node.method_name).to eq(:defined?) } end describe '#arguments' do let(:source) { 'defined? :foo' } it { expect(defined_node.arguments.size).to eq(1) } it { expect(defined_node.arguments).to all(be_sym_type) } end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/class_node_spec.rb
spec/rubocop/ast/class_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::ClassNode do subject(:class_node) { parse_source(source).ast } describe '.new' do let(:source) do 'class Foo; end' end it { is_expected.to be_a(described_class) } end describe '#identifier' do let(:source) do 'class Foo; end' end it { expect(class_node.identifier).to be_const_type } end describe '#parent_class' do context 'when a parent class is specified' do let(:source) do 'class Foo < Bar; end' end it { expect(class_node.parent_class).to be_const_type } end context 'when no parent class is specified' do let(:source) do 'class Foo; end' end it { expect(class_node.parent_class).to be_nil } end end describe '#body' do context 'with a single expression body' do let(:source) do 'class Foo; bar; end' end it { expect(class_node.body).to be_send_type } end context 'with a multi-expression body' do let(:source) do 'class Foo; bar; baz; end' end it { expect(class_node.body).to be_begin_type } end context 'with an empty body' do let(:source) do 'class Foo; end' end it { expect(class_node.body).to be_nil } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/procarg0_node_spec.rb
spec/rubocop/ast/procarg0_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::Procarg0Node, :ruby27 do let(:procarg0_node) { parse_source(source).ast.first_argument } describe '.new' do context 'with a block' do let(:source) { 'foo { |x| x }' } if RuboCop::AST::Builder.emit_procarg0 it { expect(procarg0_node).to be_a(described_class) } else it { expect(procarg0_node).to be_a(RuboCop::AST::ArgNode) } end end end describe '#name' do subject { procarg0_node.name } let(:source) { 'foo { |x| x }' } it { is_expected.to eq(:x) } end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/block_node_spec.rb
spec/rubocop/ast/block_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::BlockNode do subject(:block_node) { parse_source(source).ast } describe '.new' do let(:source) { 'foo { |q| bar(q) }' } it { is_expected.to be_a(described_class) } end describe '#arguments' do context 'with no arguments' do let(:source) { 'foo { bar }' } it { expect(block_node.arguments).to be_empty } end context 'with a single literal argument' do let(:source) { 'foo { |q| bar(q) }' } it { expect(block_node.arguments.size).to eq(1) } end context 'with a single splat argument' do let(:source) { 'foo { |*q| bar(q) }' } it { expect(block_node.arguments.size).to eq(1) } end context 'with multiple mixed arguments' do let(:source) { 'foo { |q, *z| bar(q, z) }' } it { expect(block_node.arguments.size).to eq(2) } end context 'with destructured arguments' do let(:source) { 'foo { |q, (r, s)| bar(q, r, s) }' } it { expect(block_node.arguments.size).to eq(2) } end context '>= Ruby 2.7', :ruby27 do context 'using numbered parameters' do let(:source) { 'foo { _1 }' } it { expect(block_node.arguments).to be_empty } end end context '>= Ruby 3.4', :ruby34, broken_on: :parser do context 'using `it` block parameter' do let(:source) { 'foo { it }' } it { expect(block_node.arguments).to be_empty } end end end describe '#argument_list' do subject(:argument_list) { block_node.argument_list } let(:names) { argument_list.map(&:name) } context 'with no arguments' do let(:source) { 'foo { bar }' } it { is_expected.to be_empty } end context 'all argument types' do let(:source) { 'foo { |a, b = 42, (c, *d), e:, f: 42, **g, &h; i| nil }' } it { expect(names).to eq(%i[a b c d e f g h i]) } end context '>= Ruby 2.7', :ruby27 do context 'using numbered parameters' do context 'with skipped params' do let(:source) { 'foo { _7 }' } it { expect(names).to eq(%i[_1 _2 _3 _4 _5 _6 _7]) } end context 'with sequential params' do let(:source) { 'foo { _1 + _2 }' } it { expect(names).to eq(%i[_1 _2]) } end end end context '>= Ruby 3.4', :ruby34, broken_on: :parser do context 'using `it` block parameter' do let(:source) { 'foo { it }' } it { expect(names).to eq(%i[it]) } end end end describe '#arguments?' do context 'with no arguments' do let(:source) { 'foo { bar }' } it { is_expected.not_to be_arguments } end context 'with a single argument' do let(:source) { 'foo { |q| bar(q) }' } it { is_expected.to be_arguments } end context 'with a single splat argument' do let(:source) { 'foo { |*q| bar(q) }' } it { is_expected.to be_arguments } end context 'with multiple mixed arguments' do let(:source) { 'foo { |q, *z| bar(q, z) }' } it { is_expected.to be_arguments } end context 'with destructuring arguments' do let(:source) { 'foo { |(q, r)| bar(q, r) }' } it { is_expected.to be_arguments } end context '>= Ruby 2.7', :ruby27 do context 'using numbered parameters' do let(:source) { 'foo { _1 }' } it { is_expected.not_to be_arguments } end end context '>= Ruby 3.4', :ruby34 do context 'using `it` block parameter' do let(:source) { 'foo { it }' } it { is_expected.not_to be_arguments } end end end describe '#braces?' do context 'when enclosed in braces' do let(:source) { 'foo { bar }' } it { is_expected.to be_braces } end context 'when enclosed in do-end keywords' do let(:source) do ['foo do', ' bar', 'end'].join("\n") end it { is_expected.not_to be_braces } end end describe '#keywords?' do context 'when enclosed in braces' do let(:source) { 'foo { bar }' } it { is_expected.not_to be_keywords } end context 'when enclosed in do-end keywords' do let(:source) do ['foo do', ' bar', 'end'].join("\n") end it { is_expected.to be_keywords } end end describe '#lambda?' do context 'when block belongs to a stabby lambda' do let(:source) { '-> { bar }' } it { is_expected.to be_lambda } end context 'when block belongs to a method lambda' do let(:source) { 'lambda { bar }' } it { is_expected.to be_lambda } end context 'when block belongs to a non-lambda method' do let(:source) { 'foo { bar }' } it { is_expected.not_to be_lambda } end end describe '#delimiters' do context 'when enclosed in braces' do let(:source) { 'foo { bar }' } it { expect(block_node.delimiters).to eq(%w[{ }]) } end context 'when enclosed in do-end keywords' do let(:source) do ['foo do', ' bar', 'end'].join("\n") end it { expect(block_node.delimiters).to eq(%w[do end]) } end end describe '#opening_delimiter' do context 'when enclosed in braces' do let(:source) { 'foo { bar }' } it { expect(block_node.opening_delimiter).to eq('{') } end context 'when enclosed in do-end keywords' do let(:source) do ['foo do', ' bar', 'end'].join("\n") end it { expect(block_node.opening_delimiter).to eq('do') } end end describe '#closing_delimiter' do context 'when enclosed in braces' do let(:source) { 'foo { bar }' } it { expect(block_node.closing_delimiter).to eq('}') } end context 'when enclosed in do-end keywords' do let(:source) do ['foo do', ' bar', 'end'].join("\n") end it { expect(block_node.closing_delimiter).to eq('end') } end end describe '#single_line?' do context 'when block is on a single line' do let(:source) { 'foo { bar }' } it { is_expected.to be_single_line } end context 'when block is on several lines' do let(:source) do ['foo do', ' bar', 'end'].join("\n") end it { is_expected.not_to be_single_line } end end describe '#multiline?' do context 'when block is on a single line' do let(:source) { 'foo { bar }' } it { is_expected.not_to be_multiline } end context 'when block is on several lines' do let(:source) do ['foo do', ' bar', 'end'].join("\n") end it { is_expected.to be_multiline } end end describe '#void_context?' do context 'when block method is each' do let(:source) { 'each { bar }' } it { is_expected.to be_void_context } end context 'when block method is tap' do let(:source) { 'tap { bar }' } it { is_expected.to be_void_context } end context 'when block method is not each' do let(:source) { 'map { bar }' } it { is_expected.not_to be_void_context } end end describe '#receiver' do context 'with dot operator call' do let(:source) { 'foo.bar { baz }' } it { expect(block_node.receiver.source).to eq('foo') } end context 'with safe navigation operator call' do let(:source) { 'foo&.bar { baz }' } it { expect(block_node.receiver.source).to eq('foo') } end end describe '#first_argument' do context 'with no arguments' do let(:source) { 'foo { bar }' } it { expect(block_node.first_argument).to be_nil } end context 'with a single literal argument' do let(:source) { 'foo { |q| bar(q) }' } it { expect(block_node.first_argument.source).to eq('q') } end context 'with a single splat argument' do let(:source) { 'foo { |*q| bar(q) }' } it { expect(block_node.first_argument.source).to eq('*q') } end context 'with multiple mixed arguments' do let(:source) { 'foo { |q, *z| bar(q, z) }' } it { expect(block_node.first_argument.source).to eq('q') } end context 'with destructured arguments' do let(:source) { 'foo { |(q, r), s| bar(q, r, s) }' } it { expect(block_node.first_argument.source).to eq('(q, r)') } end context '>= Ruby 2.7', :ruby27 do context 'using numbered parameters' do let(:source) { 'foo { _1 }' } it { expect(block_node.first_argument).to be_nil } end end context '>= Ruby 3.4', :ruby34 do context 'using `it` block parameter' do let(:source) { 'foo { it }' } it { expect(block_node.first_argument).to be_nil } end end end describe '#last_argument' do context 'with no arguments' do let(:source) { 'foo { bar }' } it { expect(block_node.last_argument).to be_nil } end context 'with a single literal argument' do let(:source) { 'foo { |q| bar(q) }' } it { expect(block_node.last_argument.source).to eq('q') } end context 'with a single splat argument' do let(:source) { 'foo { |*q| bar(q) }' } it { expect(block_node.last_argument.source).to eq('*q') } end context 'with multiple mixed arguments' do let(:source) { 'foo { |q, *z| bar(q, z) }' } it { expect(block_node.last_argument.source).to eq('*z') } end context 'with destructured arguments' do let(:source) { 'foo { |q, (r, s)| bar(q, r, s) }' } it { expect(block_node.last_argument.source).to eq('(r, s)') } end context '>= Ruby 2.7', :ruby27 do context 'using numbered parameters' do let(:source) { 'foo { _1 }' } it { expect(block_node.last_argument).to be_nil } end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/traversal_spec.rb
spec/rubocop/ast/traversal_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::Traversal do subject(:traverse) do instance.walk(node) instance end let(:ast) { parse_source(source).ast } let(:instance) { klass.new } let(:node) { ast } context 'when a class defines on_arg', :ruby30 do let(:klass) do Class.new do attr_reader :calls include RuboCop::AST::Traversal def on_arg(node) (@calls ||= []) << node.children.first super end end end let(:source) { <<~RUBY } class Foo def example 42.times { |x| p x } end end RUBY it 'calls it for all arguments', :ruby30 do expect(traverse.calls).to eq %i[x] end end context 'when a class defines `on_block_pass`', :ruby31 do let(:klass) do Class.new do attr_reader :calls include RuboCop::AST::Traversal def on_block_pass(node) (@calls ||= []) << node.children.first&.type super end end end let(:source) { <<~RUBY } def foo(&) # Anonymous block forwarding. bar(&) end def baz(&block) qux(&block) end RUBY it 'calls it for all block-pass arguments' do expect(traverse.calls).to eq [nil, :lvar] end end context 'when a class defines `on_itblock`', :ruby34, broken_on: :parser do let(:klass) do Class.new do attr_reader :calls include RuboCop::AST::Traversal def on_itblock(node) (@calls ||= []) << node.children.first.type super end end end let(:source) { <<~RUBY } it_block { do_something(it) } numbered_block { do_something(_1) } normal_block { |arg| do_something(arg) } RUBY it 'gets called' do expect(traverse.calls.count).to eq 1 end end File.read("#{__dir__}/fixtures/code_examples.rb").split("#----\n").each do |example| context "with example #{example}", :ruby27 do let(:klass) do Struct.new(:hits) do include RuboCop::AST::Traversal def initialize super(0) end instance_methods.grep(/^on_/).each do |m| define_method(m) do |node| self.hits += 1 super(node) end end end end let(:source) { "foo=bar=baz=nil; #{example}" } it 'traverses all nodes' do actual = node.each_node.count expect(traverse.hits).to eql(actual) end end end it 'knows all current node types' do expect(described_class::MISSING).to eq [] end # Sanity checking the debugging checks context 'when given an unexpected AST' do include RuboCop::AST::Sexp let(:klass) { Class.new { include RuboCop::AST::Traversal } } context 'with too few children' do let(:node) { s(:int) } it 'raises debugging error' do expect { traverse }.to raise_error(described_class::DebugError) end end context 'with too many children' do let(:node) { s(:int, 1, 2) } it 'raises debugging error' do expect { traverse }.to raise_error(described_class::DebugError) end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/case_node_spec.rb
spec/rubocop/ast/case_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::CaseNode do subject(:ast) { parse_source(source).ast } let(:case_node) { ast } describe '.new' do let(:source) do ['case', 'when :foo then bar', 'end'].join("\n") end it { expect(case_node).to be_a(described_class) } end describe '#keyword' do let(:source) do ['case', 'when :foo then bar', 'end'].join("\n") end it { expect(case_node.keyword).to eq('case') } end describe '#when_branches' do let(:source) do ['case', 'when :foo then 1', 'when :bar then 2', 'when :baz then 3', 'end'].join("\n") end it { expect(case_node.when_branches.size).to eq(3) } it { expect(case_node.when_branches).to all(be_when_type) } end describe '#each_when' do let(:source) do ['case', 'when :foo then 1', 'when :bar then 2', 'when :baz then 3', 'end'].join("\n") end context 'when not passed a block' do it { expect(case_node.each_when).to be_a(Enumerator) } end context 'when passed a block' do it 'yields all the conditions' do expect { |b| case_node.each_when(&b) } .to yield_successive_args(*case_node.when_branches) end end end describe '#else?' do context 'without an else statement' do let(:source) do ['case', 'when :foo then :bar', 'end'].join("\n") end it { expect(case_node).not_to be_else } end context 'with an else statement' do let(:source) do ['case', 'when :foo then :bar', 'else :baz', 'end'].join("\n") end it { expect(case_node).to be_else } end end describe '#else_branch' do describe '#else?' do context 'without an else statement' do let(:source) do ['case', 'when :foo then :bar', 'end'].join("\n") end it { expect(case_node.else_branch).to be_nil } end context 'with an else statement' do let(:source) do ['case', 'when :foo then :bar', 'else :baz', 'end'].join("\n") end it { expect(case_node.else_branch).to be_sym_type } end context 'with an empty else statement' do let(:source) do <<~RUBY case when :foo then :bar else end RUBY end it { expect(case_node.else_branch).to be_nil } end end end describe '#branches' do context 'when there is an else' do let(:source) { <<~RUBY } case when :foo then # do nothing when :bar then 42 else 'hello' end RUBY it 'returns all the bodies' do expect(case_node.branches).to match [nil, be_int_type, be_str_type] end context 'with an empty else' do let(:source) { <<~RUBY } case when :foo then # do nothing when :bar then 42 else # do nothing end RUBY it 'returns all the bodies' do expect(case_node.branches).to match [nil, be_int_type, nil] end end end context 'when there is no else keyword' do let(:source) { <<~RUBY } case when :foo then # do nothing when :bar then 42 end RUBY it 'returns only then when bodies' do expect(case_node.branches).to match [nil, be_int_type] end end context 'when compared to an IfNode' do let(:source) { <<~RUBY } case when foo then 1 when bar then 2 else end if foo then 1 elsif bar then 2 else end RUBY let(:case_node) { ast.children.first } let(:if_node) { ast.children.last } it 'returns the same' do expect(case_node.branches).to eq if_node.branches end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/float_node_spec.rb
spec/rubocop/ast/float_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::FloatNode do subject(:float_node) { parse_source(source).ast } describe '.new' do let(:source) { '42.0' } it { is_expected.to be_a(described_class) } end describe '#sign?' do subject { float_node.sign? } context 'explicit positive float' do let(:source) { '+42.0' } it { is_expected.to be(true) } end context 'explicit negative float' do let(:source) { '-42.0' } it { is_expected.to be(true) } end end describe '#value' do let(:source) do '1.5' end it { expect(float_node.value).to eq(1.5) } end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/yield_node_spec.rb
spec/rubocop/ast/yield_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::YieldNode do subject(:yield_node) { ast } let(:ast) { parse_source(source).ast } describe '.new' do let(:source) { 'yield :foo, :bar' } it { is_expected.to be_a(described_class) } end describe '#receiver' do let(:source) { 'yield :foo, :bar' } it { expect(yield_node.receiver).to be_nil } end describe '#method_name' do let(:source) { 'yield :foo, :bar' } it { expect(yield_node.method_name).to eq(:yield) } end describe '#selector' do let(:source) { 'yield :foo, :bar' } it { expect(yield_node.selector.source).to eq('yield') } end describe '#method?' do context 'when message matches' do context 'when argument is a symbol' do let(:source) { 'yield :foo' } it { is_expected.to be_method(:yield) } end context 'when argument is a string' do let(:source) { 'yield :foo' } it { is_expected.to be_method('yield') } end end context 'when message does not match' do context 'when argument is a symbol' do let(:source) { 'yield :bar' } it { is_expected.not_to be_method(:foo) } end context 'when argument is a string' do let(:source) { 'yield :bar' } it { is_expected.not_to be_method('foo') } end end end describe '#macro?' do subject(:yield_node) { ast.children[2] } let(:source) do ['def give_me_bar', ' yield :bar', 'end'].join("\n") end it { is_expected.not_to be_macro } end describe '#command?' do context 'when argument is a symbol' do let(:source) { 'yield :bar' } it { is_expected.to be_command(:yield) } end context 'when argument is a string' do let(:source) { 'yield :bar' } it { is_expected.to be_command('yield') } end end describe '#arguments' do context 'with no arguments' do let(:source) { 'yield' } it { expect(yield_node.arguments).to be_empty } end context 'with a single literal argument' do let(:source) { 'yield :foo' } it { expect(yield_node.arguments.size).to eq(1) } end context 'with a single splat argument' do let(:source) { 'yield *foo' } it { expect(yield_node.arguments.size).to eq(1) } end context 'with multiple literal arguments' do let(:source) { 'yield :foo, :bar' } it { expect(yield_node.arguments.size).to eq(2) } end context 'with multiple mixed arguments' do let(:source) { 'yield :foo, *bar' } it { expect(yield_node.arguments.size).to eq(2) } end end describe '#first_argument' do context 'with no arguments' do let(:source) { 'yield' } it { expect(yield_node.first_argument).to be_nil } end context 'with a single literal argument' do let(:source) { 'yield :foo' } it { expect(yield_node.first_argument).to be_sym_type } end context 'with a single splat argument' do let(:source) { 'yield *foo' } it { expect(yield_node.first_argument).to be_splat_type } end context 'with multiple literal arguments' do let(:source) { 'yield :foo, :bar' } it { expect(yield_node.first_argument).to be_sym_type } end context 'with multiple mixed arguments' do let(:source) { 'yield :foo, *bar' } it { expect(yield_node.first_argument).to be_sym_type } end end describe '#last_argument' do context 'with no arguments' do let(:source) { 'yield' } it { expect(yield_node.last_argument).to be_nil } end context 'with a single literal argument' do let(:source) { 'yield :foo' } it { expect(yield_node.last_argument).to be_sym_type } end context 'with a single splat argument' do let(:source) { 'yield *foo' } it { expect(yield_node.last_argument).to be_splat_type } end context 'with multiple literal arguments' do let(:source) { 'yield :foo, :bar' } it { expect(yield_node.last_argument).to be_sym_type } end context 'with multiple mixed arguments' do let(:source) { 'yield :foo, *bar' } it { expect(yield_node.last_argument).to be_splat_type } end end describe '#arguments?' do context 'with no arguments' do let(:source) { 'yield' } it { is_expected.not_to be_arguments } end context 'with a single literal argument' do let(:source) { 'yield :foo' } it { is_expected.to be_arguments } end context 'with a single splat argument' do let(:source) { 'yield *foo' } it { is_expected.to be_arguments } end context 'with multiple literal arguments' do let(:source) { 'yield :foo, :bar' } it { is_expected.to be_arguments } end context 'with multiple mixed arguments' do let(:source) { 'yield :foo, *bar' } it { is_expected.to be_arguments } end end describe '#parenthesized?' do context 'with no arguments' do context 'when not using parentheses' do let(:source) { 'yield' } it { is_expected.not_to be_parenthesized } end context 'when using parentheses' do let(:source) { 'yield()' } it { is_expected.to be_parenthesized } end end context 'with arguments' do context 'when not using parentheses' do let(:source) { 'yield :foo' } it { is_expected.not_to be_parenthesized } end context 'when using parentheses' do let(:source) { 'yield(:foo)' } it { is_expected.to be_parenthesized } end end end describe '#setter_method?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_setter_method } end describe '#operator_method?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_operator_method } end describe '#comparison_method?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_comparison_method } end describe '#assignment_method?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_assignment_method } end describe '#dot?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_dot } end describe '#double_colon?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_double_colon } end describe '#self_receiver?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_self_receiver } end describe '#const_receiver?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_const_receiver } end describe '#implicit_call?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_implicit_call } end describe '#predicate_method?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_predicate_method } end describe '#bang_method?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_bang_method } end describe '#camel_case_method?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_camel_case_method } end describe '#block_argument?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_block_argument } end describe '#block_literal?' do let(:source) { 'yield :foo' } it { is_expected.not_to be_block_literal } end describe '#block_node' do let(:source) { 'yield :foo' } it { expect(yield_node.block_node).to be_nil } end describe '#splat_argument?' do context 'with a splat argument' do let(:source) { 'yield *foo' } it { is_expected.to be_splat_argument } end context 'with no arguments' do let(:source) { 'yield' } it { is_expected.not_to be_splat_argument } end context 'with regular arguments' do let(:source) { 'yield :foo' } it { is_expected.not_to be_splat_argument } end context 'with mixed arguments' do let(:source) { 'yield :foo, *bar' } it { is_expected.to be_splat_argument } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/send_node_spec.rb
spec/rubocop/ast/send_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::SendNode do let(:send_node) { parse_source(source).node } describe '.new' do context 'with a regular method send' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).to be_a(described_class) } end context 'with a safe navigation method send' do let(:source) { 'foo&.bar(:baz)' } it { expect(send_node).to be_a(described_class) } end end describe '#receiver' do context 'with no receiver' do let(:source) { 'bar(:baz)' } it { expect(send_node.receiver).to be_nil } end context 'with a literal receiver' do let(:source) { "'foo'.bar(:baz)" } it { expect(send_node.receiver).to be_str_type } end context 'with a variable receiver' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node.receiver).to be_send_type } end end describe '#method_name' do context 'with a plain method' do let(:source) { 'bar(:baz)' } it { expect(send_node.method_name).to eq(:bar) } end context 'with a setter method' do let(:source) { 'foo.bar = :baz' } it { expect(send_node.method_name).to eq(:bar=) } end context 'with an operator method' do let(:source) { 'foo == bar' } it { expect(send_node.method_name).to eq(:==) } end context 'with an implicit call method' do let(:source) { 'foo.(:baz)' } it { expect(send_node.method_name).to eq(:call) } end end describe '#method?' do context 'when message matches' do context 'when argument is a symbol' do let(:source) { 'bar(:baz)' } it { expect(send_node).to be_method(:bar) } end context 'when argument is a string' do let(:source) { 'bar(:baz)' } it { expect(send_node).to be_method('bar') } end end context 'when message does not match' do context 'when argument is a symbol' do let(:source) { 'bar(:baz)' } it { expect(send_node).not_to be_method(:foo) } end context 'when argument is a string' do let(:source) { 'bar(:baz)' } it { expect(send_node).not_to be_method('foo') } end end end describe '#access_modifier?' do context 'when node is a bare `module_function`' do let(:source) do <<~RUBY module Foo >> module_function << end RUBY end it { expect(send_node).to be_access_modifier } end context 'when node is a non-bare `module_function`' do let(:source) do <<~RUBY module Foo >> module_function :foo << end RUBY end it { expect(send_node).to be_access_modifier } end context 'when node is a non-bare `module_function` with multiple arguments' do let(:source) do <<~RUBY module Foo >> module_function :foo, :bar << end RUBY end it { expect(send_node).to be_access_modifier } end context 'when node is not an access modifier' do let(:source) do <<~RUBY module Foo >> some_command << end RUBY end it { expect(send_node).not_to be_bare_access_modifier } end end describe '#bare_access_modifier?' do context 'when node is a bare `module_function`' do let(:source) do <<~RUBY module Foo >> module_function << end RUBY end it { expect(send_node).to be_bare_access_modifier } end context 'when node has an argument' do let(:source) do <<~RUBY module Foo >> private :foo << end RUBY end it { expect(send_node).not_to be_bare_access_modifier } end context 'when node is not an access modifier' do let(:source) do <<~RUBY module Foo >> some_command << end RUBY end it { expect(send_node).not_to be_bare_access_modifier } end context 'with Ruby >= 2.7', :ruby27 do context 'when node is access modifier in block' do let(:source) do <<~RUBY included do >> module_function << end RUBY end it { expect(send_node).to be_bare_access_modifier } end context 'when node is access modifier in numblock' do let(:source) do <<~RUBY included do _1 >> module_function << end RUBY end it { expect(send_node).to be_bare_access_modifier } end end context 'with Ruby >= 3.4', :ruby34 do context 'when node is access modifier in itblock' do let(:source) do <<~RUBY included do it >> module_function << end RUBY end it { expect(send_node).to be_bare_access_modifier } end end end describe '#non_bare_access_modifier?' do context 'when node is a non-bare `module_function`' do let(:source) do <<~RUBY module Foo >> module_function :foo << end RUBY end it { expect(send_node).to be_non_bare_access_modifier } end context 'when node is a non-bare `module_function` with multiple arguments' do let(:source) do <<~RUBY module Foo >> module_function :foo, :bar << end RUBY end it { expect(send_node).to be_non_bare_access_modifier } end context 'when node does not have an argument' do let(:source) do <<~RUBY module Foo >> private << end RUBY end it { expect(send_node).not_to be_non_bare_access_modifier } end context 'when node is not an access modifier' do let(:source) do <<~RUBY module Foo >> some_command << end RUBY end it { expect(send_node).not_to be_non_bare_access_modifier } end end describe '#macro?' do context 'without a receiver' do context 'when parent is a class' do let(:source) do ['class Foo', '>>bar :baz<<', ' bar :qux', 'end'].join("\n") end it { expect(send_node).to be_macro } end context 'when parent is a module' do let(:source) do ['module Foo', '>>bar :baz<<', ' bar :qux', 'end'].join("\n") end it { expect(send_node).to be_macro } end context 'when parent is a class constructor' do let(:source) do ['Module.new do', '>>bar :baz<<', ' bar :qux', 'end'].join("\n") end it { expect(send_node).to be_macro } end context 'when parent is a struct constructor' do let(:source) do ['Foo = Struct.new do', '>>bar :baz<<', ' bar :qux', 'end'].join("\n") end it { expect(send_node).to be_macro } end context 'when parent is a singleton class' do let(:source) do ['class << self', '>>bar :baz<<', ' bar :qux', 'end'].join("\n") end it { expect(send_node).to be_macro } end context 'when parent is a block in a macro scope' do let(:source) do ['concern :Auth do', '>>bar :baz<<', ' bar :qux', 'end'].join("\n") end it { expect(send_node).to be_macro } end context 'with Ruby >= 2.7', :ruby27 do context 'when parent is a numblock in a macro scope' do let(:source) do ['concern :Auth do', '>>bar :baz<<', ' bar _1', 'end'].join("\n") end it { expect(send_node).to be_macro } end end context 'with Ruby >= 3.4', :ruby27 do context 'when parent is an itblock in a macro scope' do let(:source) do ['concern :Auth do', '>>bar :baz<<', ' bar it', 'end'].join("\n") end it { expect(send_node).to be_macro } end end context 'when parent is a block not in a macro scope' do let(:source) { <<~RUBY } class Foo def bar 3.times do >>something :baz<< other end end end RUBY it { expect(send_node).not_to be_macro } end context 'when in the global scope' do let(:source) { <<~RUBY } >>something :baz<< other RUBY it { expect(send_node).to be_macro } end context 'when parent is a keyword begin inside of an class' do let(:source) do ['class Foo', ' begin', '>> bar :qux <<', ' end', 'end'].join("\n") end it { expect(send_node).to be_macro } end context 'without a parent' do let(:source) { 'bar :baz' } it { expect(send_node).to be_macro } end context 'when parent is a begin without a parent' do let(:source) do ['begin', '>>bar :qux<<', 'end'].join("\n") end it { expect(send_node).to be_macro } end context 'when parent is a method definition' do let(:source) do ['def foo', '>>bar :baz<<', 'end'].join("\n") end it { expect(send_node).not_to be_macro } end context 'when in an if' do let(:source) { <<~RUBY } >>bar :baz<< if qux other RUBY it { expect(send_node).to be_macro } end context 'when the condition of an if' do let(:source) { <<~RUBY } qux if >>bar :baz<< other RUBY it { expect(send_node).not_to be_macro } end end context 'with a receiver' do context 'when parent is a class' do let(:source) do ['class Foo', ' >> qux.bar :baz <<', 'end'].join("\n") end it { expect(send_node).not_to be_macro } end context 'when parent is a module' do let(:source) do ['module Foo', ' >> qux.bar :baz << ', 'end'].join("\n") end it { expect(send_node).not_to be_macro } end end end describe '#command?' do context 'when argument is a symbol' do context 'with an explicit receiver' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_command(:bar) } end context 'with an implicit receiver' do let(:source) { 'bar(:baz)' } it { expect(send_node).to be_command(:bar) } end end context 'when argument is a string' do context 'with an explicit receiver' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_command('bar') } end context 'with an implicit receiver' do let(:source) { 'bar(:baz)' } it { expect(send_node).to be_command('bar') } end end end describe '#arguments' do context 'with no arguments' do let(:source) { 'foo.bar' } it { expect(send_node.arguments).to be_empty } end context 'with a single literal argument' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node.arguments.size).to eq(1) } end context 'with a single splat argument' do let(:source) { 'foo.bar(*baz)' } it { expect(send_node.arguments.size).to eq(1) } end context 'with multiple literal arguments' do let(:source) { 'foo.bar(:baz, :qux)' } it { expect(send_node.arguments.size).to eq(2) } end context 'with multiple mixed arguments' do let(:source) { 'foo.bar(:baz, *qux)' } it { expect(send_node.arguments.size).to eq(2) } end end describe '#first_argument' do context 'with no arguments' do let(:source) { 'foo.bar' } it { expect(send_node.first_argument).to be_nil } end context 'with a single literal argument' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node.first_argument).to be_sym_type } end context 'with a single splat argument' do let(:source) { 'foo.bar(*baz)' } it { expect(send_node.first_argument).to be_splat_type } end context 'with multiple literal arguments' do let(:source) { 'foo.bar(:baz, :qux)' } it { expect(send_node.first_argument).to be_sym_type } end context 'with multiple mixed arguments' do let(:source) { 'foo.bar(:baz, *qux)' } it { expect(send_node.first_argument).to be_sym_type } end end describe '#last_argument' do context 'with no arguments' do let(:source) { 'foo.bar' } it { expect(send_node.last_argument).to be_nil } end context 'with a single literal argument' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node.last_argument).to be_sym_type } end context 'with a single splat argument' do let(:source) { 'foo.bar(*baz)' } it { expect(send_node.last_argument).to be_splat_type } end context 'with multiple literal arguments' do let(:source) { 'foo.bar(:baz, :qux)' } it { expect(send_node.last_argument).to be_sym_type } end context 'with multiple mixed arguments' do let(:source) { 'foo.bar(:baz, *qux)' } it { expect(send_node.last_argument).to be_splat_type } end end describe '#arguments?' do context 'with no arguments' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_arguments } end context 'with a single literal argument' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).to be_arguments } end context 'with a single splat argument' do let(:source) { 'foo.bar(*baz)' } it { expect(send_node).to be_arguments } end context 'with multiple literal arguments' do let(:source) { 'foo.bar(:baz, :qux)' } it { expect(send_node).to be_arguments } end context 'with multiple mixed arguments' do let(:source) { 'foo.bar(:baz, *qux)' } it { expect(send_node).to be_arguments } end end describe '#parenthesized?' do context 'with no arguments' do context 'when not using parentheses' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_parenthesized } end context 'when using parentheses' do let(:source) { 'foo.bar()' } it { expect(send_node).to be_parenthesized } end end context 'with arguments' do context 'when not using parentheses' do let(:source) { 'foo.bar :baz' } it { expect(send_node).not_to be_parenthesized } end context 'when using parentheses' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).to be_parenthesized } end end end describe '#setter_method?' do context 'with a setter method' do let(:source) { 'foo.bar = :baz' } it { expect(send_node).to be_setter_method } end context 'with an indexed setter method' do let(:source) { 'foo.bar[:baz] = :qux' } it { expect(send_node).to be_setter_method } end context 'with an operator method' do let(:source) { 'foo.bar + 1' } it { expect(send_node).not_to be_setter_method } end context 'with a regular method' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_setter_method } end end describe '#operator_method?' do context 'with a binary operator method' do let(:source) { 'foo.bar + :baz' } it { expect(send_node).to be_operator_method } end context 'with a unary operator method' do let(:source) { '!foo.bar' } it { expect(send_node).to be_operator_method } end context 'with a setter method' do let(:source) { 'foo.bar = :baz' } it { expect(send_node).not_to be_operator_method } end context 'with a regular method' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_operator_method } end end describe '#nonmutating_binary_operator_method?' do context 'with a nonmutating binary operator method' do let(:source) { 'foo + bar' } it { expect(send_node).to be_nonmutating_binary_operator_method } end context 'with a mutating binary operator method' do let(:source) { 'foo << bar' } it { expect(send_node).not_to be_nonmutating_binary_operator_method } end context 'with a regular method' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_nonmutating_binary_operator_method } end end describe '#nonmutating_unary_operator_method?' do context 'with a nonmutating unary operator method' do let(:source) { '!foo' } it { expect(send_node).to be_nonmutating_unary_operator_method } end context 'with a regular method' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_nonmutating_unary_operator_method } end end describe '#nonmutating_operator_method?' do context 'with a nonmutating binary operator method' do let(:source) { 'foo + bar' } it { expect(send_node).to be_nonmutating_operator_method } end context 'with a nonmutating unary operator method' do let(:source) { '!foo' } it { expect(send_node).to be_nonmutating_operator_method } end context 'with a mutating binary operator method' do let(:source) { 'foo << bar' } it { expect(send_node).not_to be_nonmutating_operator_method } end context 'with a regular method' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_nonmutating_operator_method } end end describe '#nonmutating_array_method?' do context 'with a nonmutating Array method' do let(:source) { 'array.reverse' } it { expect(send_node).to be_nonmutating_array_method } end context 'with a mutating Array method' do let(:source) { 'array.push(foo)' } it { expect(send_node).not_to be_nonmutating_array_method } end context 'with a regular method' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_nonmutating_array_method } end end describe '#nonmutating_hash_method?' do context 'with a nonmutating Hash method' do let(:source) { 'hash.slice(:foo, :bar)' } it { expect(send_node).to be_nonmutating_hash_method } end context 'with a mutating Hash method' do let(:source) { 'hash.delete(:foo)' } it { expect(send_node).not_to be_nonmutating_hash_method } end context 'with a regular method' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_nonmutating_hash_method } end end describe '#nonmutating_string_method?' do context 'with a nonmutating String method' do let(:source) { 'string.squeeze' } it { expect(send_node).to be_nonmutating_string_method } end context 'with a mutating String method' do let(:source) { 'string.lstrip!' } it { expect(send_node).not_to be_nonmutating_string_method } end context 'with a regular method' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_nonmutating_string_method } end end describe '#comparison_method?' do context 'with a comparison method' do let(:source) { 'foo.bar >= :baz' } it { expect(send_node).to be_comparison_method } end context 'with a regular method' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_comparison_method } end context 'with a negation method' do let(:source) { '!foo' } it { expect(send_node).not_to be_comparison_method } end end describe '#assignment_method?' do context 'with an assignment method' do let(:source) { 'foo.bar = :baz' } it { expect(send_node).to be_assignment_method } end context 'with a bracket assignment method' do let(:source) { 'foo.bar[:baz] = :qux' } it { expect(send_node).to be_assignment_method } end context 'with a comparison method' do let(:source) { 'foo.bar == :qux' } it { expect(send_node).not_to be_assignment_method } end context 'with a regular method' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_assignment_method } end end describe '#enumerable_method?' do context 'with an enumerable method' do let(:source) { '>> foo.all? << { |e| bar?(e) }' } it { expect(send_node).to be_enumerable_method } end context 'with a regular method' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_enumerable_method } end end describe '#attribute_accessor?' do context 'with an accessor' do let(:source) { 'attr_reader :foo, bar, *baz' } it 'returns the accessor method and Array<accessors>]' do expect(send_node.attribute_accessor?).to contain_exactly( :attr_reader, contain_exactly( be_sym_type, be_send_type, be_splat_type ) ) end context 'with a call without arguments' do let(:source) { 'attr_reader' } it do expect(send_node.attribute_accessor?).to be_nil end end end end describe '#dot?' do context 'with a dot' do let(:source) { 'foo.+ 1' } it { expect(send_node).to be_dot } end context 'without a dot' do let(:source) { 'foo + 1' } it { expect(send_node).not_to be_dot } end context 'with a double colon' do let(:source) { 'Foo::bar' } it { expect(send_node).not_to be_dot } end context 'with a unary method' do let(:source) { '!foo.bar' } it { expect(send_node).not_to be_dot } end end describe '#double_colon?' do context 'with a double colon' do let(:source) { 'Foo::bar' } it { expect(send_node).to be_double_colon } end context 'with a dot' do let(:source) { 'foo.+ 1' } it { expect(send_node).not_to be_double_colon } end context 'without a dot' do let(:source) { 'foo + 1' } it { expect(send_node).not_to be_double_colon } end context 'with a unary method' do let(:source) { '!foo.bar' } it { expect(send_node).not_to be_double_colon } end end describe '#self_receiver?' do context 'with a self receiver' do let(:source) { 'self.bar' } it { expect(send_node).to be_self_receiver } end context 'with a non-self receiver' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_self_receiver } end context 'with an implicit receiver' do let(:source) { 'bar' } it { expect(send_node).not_to be_self_receiver } end end describe '#const_receiver?' do context 'with a self receiver' do let(:source) { 'self.bar' } it { expect(send_node).not_to be_const_receiver } end context 'with a non-constant receiver' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_const_receiver } end context 'with a constant receiver' do let(:source) { 'Foo.bar' } it { expect(send_node).to be_const_receiver } end end describe '#implicit_call?' do context 'with an implicit call method' do let(:source) { 'foo.(:bar)' } it { expect(send_node).to be_implicit_call } end context 'with an explicit call method' do let(:source) { 'foo.call(:bar)' } it { expect(send_node).not_to be_implicit_call } end context 'with a regular method' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_implicit_call } end end describe '#predicate_method?' do context 'with a predicate method' do let(:source) { 'foo.bar?' } it { expect(send_node).to be_predicate_method } end context 'with a bang method' do let(:source) { 'foo.bar!' } it { expect(send_node).not_to be_predicate_method } end context 'with a regular method' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_predicate_method } end end describe '#bang_method?' do context 'with a bang method' do let(:source) { 'foo.bar!' } it { expect(send_node).to be_bang_method } end context 'with a predicate method' do let(:source) { 'foo.bar?' } it { expect(send_node).not_to be_bang_method } end context 'with a regular method' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_bang_method } end end describe '#camel_case_method?' do context 'with a camel case method' do let(:source) { 'Integer(1.0)' } it { expect(send_node).to be_camel_case_method } end context 'with a regular method' do let(:source) { 'integer(1.0)' } it { expect(send_node).not_to be_camel_case_method } end end describe '#block_argument?' do context 'with a block argument' do let(:source) { 'foo.bar(&baz)' } it { expect(send_node).to be_block_argument } end context 'with no arguments' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_block_argument } end context 'with regular arguments' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_block_argument } end context 'with mixed arguments' do let(:source) { 'foo.bar(:baz, &qux)' } it { expect(send_node).to be_block_argument } end end describe '#block_literal?' do context 'with a block literal' do let(:source) { '>> foo.bar << { |q| baz(q) }' } it { expect(send_node).to be_block_literal } end context 'with a block argument' do let(:source) { 'foo.bar(&baz)' } it { expect(send_node).not_to be_block_literal } end context 'with no block' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_block_literal } end context 'with Ruby >= 2.7', :ruby27 do context 'with a numblock literal' do let(:source) { '>> foo.bar << { baz(_1) }' } it { expect(send_node).to be_block_literal } end end context 'with Ruby >= 3.4', :ruby27 do context 'with an itblock literal' do let(:source) { '>> foo.bar << { baz(it) }' } it { expect(send_node).to be_block_literal } end end end describe '#arithmetic_operation?' do context 'with a binary arithmetic operation' do let(:source) { 'foo + bar' } it { expect(send_node).to be_arithmetic_operation } end context 'with a unary numeric operation' do let(:source) { '+foo' } it { expect(send_node).not_to be_arithmetic_operation } end context 'with a regular method call' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_arithmetic_operation } end end describe '#block_node' do context 'with a block literal' do let(:source) { '>>foo.bar<< { |q| baz(q) }' } it { expect(send_node.block_node).to be_block_type } end context 'with a block argument' do let(:source) { 'foo.bar(&baz)' } it { expect(send_node.block_node).to be_nil } end context 'with no block' do let(:source) { 'foo.bar' } it { expect(send_node.block_node).to be_nil } end context 'with Ruby >= 2.7', :ruby27 do context 'with a numblock literal' do let(:source) { '>>foo.bar<< { baz(_1) }' } it { expect(send_node.block_node).to be_numblock_type } end end context 'with Ruby >= 3.4', :ruby34, broken_on: :parser do context 'with an itblock literal' do let(:source) { '>>foo.bar<< { baz(it) }' } it { expect(send_node.block_node).to be_itblock_type } end end end describe '#splat_argument?' do context 'with a splat argument' do let(:source) { 'foo.bar(*baz)' } it { expect(send_node).to be_splat_argument } end context 'with no arguments' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_splat_argument } end context 'with regular arguments' do let(:source) { 'foo.bar(:baz)' } it { expect(send_node).not_to be_splat_argument } end context 'with mixed arguments' do let(:source) { 'foo.bar(:baz, *qux)' } it { expect(send_node).to be_splat_argument } end end describe '#def_modifier?' do context 'with a prefixed def modifier' do let(:source) { 'foo def bar; end' } it { expect(send_node).to be_def_modifier } end context 'with several prefixed def modifiers' do let(:source) { 'foo bar baz def qux; end' } it { expect(send_node).to be_def_modifier } end context 'with a block containing a method definition' do let(:source) { 'foo bar { baz def qux; end }' } it { expect(send_node).not_to be_def_modifier } end end describe '#def_modifier' do context 'with a prefixed def modifier' do let(:source) { 'foo def bar; end' } it { expect(send_node.def_modifier.method_name).to eq(:bar) } end context 'with several prefixed def modifiers' do let(:source) { 'foo bar baz def qux; end' } it { expect(send_node.def_modifier.method_name).to eq(:qux) } end context 'with a block containing a method definition' do let(:source) { 'foo bar { baz def qux; end }' } it { expect(send_node.def_modifier).to be_nil } end context 'with call with no argument' do let(:source) { 'foo' } it { expect(send_node.def_modifier).to be_nil } end end describe '#negation_method?' do context 'with prefix `not`' do let(:source) { 'not foo' } it { expect(send_node).to be_negation_method } end context 'with suffix `not`' do let(:source) { 'foo.not' } it { expect(send_node).not_to be_negation_method } end context 'with prefix bang' do let(:source) { '!foo' } it { expect(send_node).to be_negation_method } end context 'with a non-negated method' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_negation_method } end end describe '#prefix_not?' do context 'with keyword `not`' do let(:source) { 'not foo' } it { expect(send_node).to be_prefix_not } end context 'with a bang method' do let(:source) { '!foo' } it { expect(send_node).not_to be_prefix_not } end context 'with a non-negated method' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_prefix_not } end end describe '#prefix_bang?' do context 'with keyword `not`' do let(:source) { 'not foo' } it { expect(send_node).not_to be_prefix_bang } end context 'with a bang method' do let(:source) { '!foo' } it { expect(send_node).to be_prefix_bang } end context 'with a non-negated method' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_prefix_bang } end end describe '#lambda?' do context 'with a lambda method' do let(:source) { '>> lambda << { |foo| bar(foo) }' } it { expect(send_node).to be_lambda } end context 'with a method named lambda in a class' do let(:source) { '>> foo.lambda << { |bar| baz }' } it { expect(send_node).not_to be_lambda } end context 'with a stabby lambda method' do let(:source) { '>> -> << (foo) { do_something(foo) }' } it { expect(send_node).to be_lambda } end context 'with a non-lambda method' do let(:source) { 'foo.bar' } it { expect(send_node).not_to be_lambda } end end describe '#lambda_literal?' do context 'with a stabby lambda' do let(:source) { '>> -> << (foo) { do_something(foo) }' } it { expect(send_node).to be_lambda_literal } end context 'with a lambda method' do let(:source) { '>> lambda << { |foo| bar(foo) }' }
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
true
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/rubocop_compatibility_spec.rb
spec/rubocop/ast/rubocop_compatibility_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::RuboCopCompatibility do subject(:callback) { RuboCop::AST.rubocop_loaded } before do stub_const '::RuboCop::Version::STRING', rubocop_version end context 'when ran from an incompatible version of Rubocop' do let(:rubocop_version) { '0.42.0' } it 'issues a warning' do expect { callback }.to output(/LineLength/).to_stderr end end context 'when ran from a compatible version of Rubocop' do let(:rubocop_version) { '0.92.0' } it 'issues a warning' do expect { callback }.not_to output.to_stderr end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/dstr_node_spec.rb
spec/rubocop/ast/dstr_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::DstrNode do subject(:dstr_node) { parse_source(source).ast } describe '#value' do subject { dstr_node.value } context 'with a multiline string' do let(:source) do <<~RUBY 'this is a multiline ' \ 'string' RUBY end it { is_expected.to eq('this is a multiline string') } end context 'with interpolation' do let(:source) do '"foo #{bar} baz"' end it { is_expected.to eq('foo #{bar} baz') } end context 'with implicit concatenation' do let(:source) do <<~RUBY 'foo ' 'bar ' 'baz' RUBY end it { is_expected.to eq('foo bar baz') } end end describe '#single_quoted?' do context 'with a double-quoted string' do let(:source) { '"#{foo}"' } it { is_expected.not_to be_single_quoted } end context 'with a %() delimited string' do let(:source) { '%(#{foo})' } it { is_expected.not_to be_single_quoted } end context 'with a %Q() delimited string' do let(:source) { '%Q(#{foo})' } it { is_expected.not_to be_single_quoted } end end describe '#double_quoted?' do context 'with a double-quoted string' do let(:source) { '"#{foo}"' } it { is_expected.to be_double_quoted } end context 'with a %() delimited string' do let(:source) { '%(#{foo})' } it { is_expected.not_to be_double_quoted } end context 'with a %Q() delimited string' do let(:source) { '%Q(#{foo})' } it { is_expected.not_to be_double_quoted } end end describe '#percent_literal?' do context 'with a quoted string' do let(:source) { '"#{foo}"' } it { is_expected.not_to be_percent_literal } it { is_expected.not_to be_percent_literal(:%) } it { is_expected.not_to be_percent_literal(:q) } it { is_expected.not_to be_percent_literal(:Q) } end context 'with a %() delimited string' do let(:source) { '%(#{foo})' } it { is_expected.to be_percent_literal } it { is_expected.to be_percent_literal(:%) } it { is_expected.not_to be_percent_literal(:q) } it { is_expected.not_to be_percent_literal(:Q) } end context 'with a %Q() delimited string' do let(:source) { '%Q(#{foo})' } it { is_expected.to be_percent_literal } it { is_expected.not_to be_percent_literal(:%) } it { is_expected.not_to be_percent_literal(:q) } it { is_expected.to be_percent_literal(:Q) } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/hash_node_spec.rb
spec/rubocop/ast/hash_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::HashNode do subject(:hash_node) { parse_source(source).ast } describe '.new' do let(:source) { '{}' } it { is_expected.to be_a(described_class) } end describe '#pairs' do context 'with an empty hash' do let(:source) { '{}' } it { expect(hash_node.pairs).to be_empty } end context 'with a hash of literals' do let(:source) { '{ a: 1, b: 2, c: 3 }' } it { expect(hash_node.pairs.size).to eq(3) } it { expect(hash_node.pairs).to all(be_pair_type) } end context 'with a hash of variables' do let(:source) { '{ a: foo, b: bar }' } it { expect(hash_node.pairs.size).to eq(2) } it { expect(hash_node.pairs).to all(be_pair_type) } end end describe '#empty?' do context 'with an empty hash' do let(:source) { '{}' } it { is_expected.to be_empty } end context 'with a hash containing pairs' do let(:source) { '{ a: 1, b: 2 }' } it { is_expected.not_to be_empty } end context 'with a hash containing a keyword splat' do let(:source) { '{ **foo }' } it { is_expected.not_to be_empty } end end describe '#keys' do context 'with an empty hash' do let(:source) { '{}' } it { expect(hash_node.keys).to be_empty } end context 'with a hash with symbol keys' do let(:source) { '{ a: 1, b: 2, c: 3 }' } it { expect(hash_node.keys.size).to eq(3) } it { expect(hash_node.keys).to all(be_sym_type) } end context 'with a hash with string keys' do let(:source) { "{ 'a' => foo,'b' => bar }" } it { expect(hash_node.keys.size).to eq(2) } it { expect(hash_node.keys).to all(be_str_type) } end end describe '#each_key' do let(:source) { '{ a: 1, b: 2, c: 3 }' } context 'when not passed a block' do it { expect(hash_node.each_key).to be_a(Enumerator) } end context 'when passed a block' do let(:expected) do [ hash_node.pairs[0].key, hash_node.pairs[1].key, hash_node.pairs[2].key ] end it 'yields all the pairs' do expect { |b| hash_node.each_key(&b) } .to yield_successive_args(*expected) end end end describe '#values' do context 'with an empty hash' do let(:source) { '{}' } it { expect(hash_node.values).to be_empty } end context 'with a hash with literal values' do let(:source) { '{ a: 1, b: 2, c: 3 }' } it { expect(hash_node.values.size).to eq(3) } it { expect(hash_node.values).to all(be_literal) } end context 'with a hash with string keys' do let(:source) { '{ a: foo, b: bar }' } it { expect(hash_node.values.size).to eq(2) } it { expect(hash_node.values).to all(be_send_type) } end end describe '#each_value' do let(:source) { '{ a: 1, b: 2, c: 3 }' } context 'when not passed a block' do it { expect(hash_node.each_value).to be_a(Enumerator) } end context 'when passed a block' do let(:expected) do [ hash_node.pairs[0].value, hash_node.pairs[1].value, hash_node.pairs[2].value ] end it 'yields all the pairs' do expect { |b| hash_node.each_value(&b) } .to yield_successive_args(*expected) end end end describe '#each_pair' do let(:source) { '{ a: 1, b: 2, c: 3 }' } context 'when not passed a block' do it { expect(hash_node.each_pair).to be_a(Enumerator) } end context 'when passed a block' do let(:expected) do hash_node.pairs.map(&:to_a) end it 'yields all the pairs' do expect { |b| hash_node.each_pair(&b) } .to yield_successive_args(*expected) end end end describe '#pairs_on_same_line?' do context 'with all pairs on the same line' do let(:source) { '{ a: 1, b: 2 }' } it { is_expected.to be_pairs_on_same_line } end context 'with no pairs on the same line' do let(:source) do ['{ a: 1,', ' b: 2 }'].join("\n") end it { is_expected.not_to be_pairs_on_same_line } end context 'with some pairs on the same line' do let(:source) do ['{ a: 1,', ' b: 2, c: 3 }'].join("\n") end it { is_expected.to be_pairs_on_same_line } end end describe '#mixed_delimiters?' do context 'when all pairs are using a colon delimiter' do let(:source) { '{ a: 1, b: 2 }' } it { is_expected.not_to be_mixed_delimiters } end context 'when all pairs are using a hash rocket delimiter' do let(:source) { '{ :a => 1, :b => 2 }' } it { is_expected.not_to be_mixed_delimiters } end context 'when pairs are using different delimiters' do let(:source) { '{ :a => 1, b: 2 }' } it { is_expected.to be_mixed_delimiters } end end describe '#braces?' do context 'with braces' do let(:source) { '{ a: 1, b: 2 }' } it { is_expected.to be_braces } end context 'as an argument with no braces' do let(:source) { 'foo(:bar, a: 1, b: 2)' } let(:hash_argument) { hash_node.children.last } it { expect(hash_argument).not_to be_braces } end context 'as an argument with braces' do let(:source) { 'foo(:bar, { a: 1, b: 2 })' } let(:hash_argument) { hash_node.children.last } it { expect(hash_argument).to be_braces } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/mlhs_node_spec.rb
spec/rubocop/ast/mlhs_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::MlhsNode do let(:mlhs_node) { parse_source(source).ast.node_parts[0] } describe '.new' do context 'with a `masgn` node' do let(:source) { 'x, y = z' } it { expect(mlhs_node).to be_a(described_class) } end end describe '#assignments' do include AST::Sexp subject { mlhs_node.assignments } context 'with variables' do let(:source) { 'x, y = z' } it { is_expected.to eq([s(:lvasgn, :x), s(:lvasgn, :y)]) } end context 'with a splat' do let(:source) { 'x, *y = z' } it { is_expected.to eq([s(:lvasgn, :x), s(:lvasgn, :y)]) } end context 'with an anonymous splat' do let(:source) { 'x, * = z' } it { is_expected.to eq([s(:lvasgn, :x), s(:splat)]) } end context 'with nested `mlhs` nodes' do let(:source) { 'a, (b, c) = z' } it { is_expected.to eq([s(:lvasgn, :a), s(:lvasgn, :b), s(:lvasgn, :c)]) } end context 'with different variable types' do let(:source) { 'a, @b, @@c, $d, E, *f = z' } let(:expected_nodes) do [ s(:lvasgn, :a), s(:ivasgn, :@b), s(:cvasgn, :@@c), s(:gvasgn, :$d), s(:casgn, nil, :E), s(:lvasgn, :f) ] end it { is_expected.to eq(expected_nodes) } end context 'with assignment on RHS' do let(:source) { 'x, y = 1, z += 2' } it { is_expected.to eq([s(:lvasgn, :x), s(:lvasgn, :y)]) } end context 'with nested assignment on LHS' do let(:source) { 'a, b[c+=1] = z' } if RuboCop::AST::Builder.emit_index let(:expected_nodes) do [ s(:lvasgn, :a), s(:indexasgn, s(:send, nil, :b), s(:op_asgn, s(:lvasgn, :c), :+, s(:int, 1))) ] end else let(:expected_nodes) do [ s(:lvasgn, :a), s(:send, s(:send, nil, :b), :[]=, s(:op_asgn, s(:lvasgn, :c), :+, s(:int, 1))) ] end end it { is_expected.to eq(expected_nodes) } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/args_node_spec.rb
spec/rubocop/ast/args_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::ArgsNode do let(:args_node) { parse_source(source).ast.arguments } describe '.new' do context 'with a method definition' do let(:source) { 'def foo(x) end' } it { expect(args_node).to be_a(described_class) } end context 'with a block' do let(:source) { 'foo { |x| bar }' } it { expect(args_node).to be_a(described_class) } end context 'with a lambda literal' do let(:source) { '-> (x) { bar }' } it { expect(args_node).to be_a(described_class) } end end describe '#empty_and_without_delimiters?' do subject { args_node.empty_and_without_delimiters? } context 'with empty arguments' do context 'with a method definition' do let(:source) { 'def x; end' } it { is_expected.to be(true) } end context 'with a block' do let(:source) { 'x { }' } it { is_expected.to be(true) } end context 'with a lambda literal' do let(:source) { '-> { }' } it { is_expected.to be(true) } end end context 'with delimiters' do context 'with a method definition' do let(:source) { 'def x(); end' } it { is_expected.to be(false) } end context 'with a block' do let(:source) { 'x { || }' } it { is_expected.to be(false) } end context 'with a lambda literal' do let(:source) { '-> () { }' } it { is_expected.to be(false) } end end context 'with arguments' do context 'with a method definition' do let(:source) { 'def x a; end' } it { is_expected.to be(false) } end context 'with a lambda literal' do let(:source) { '-> a { }' } it { is_expected.to be(false) } end end end describe '#argument_list' do include AST::Sexp subject { args_node.argument_list } let(:source) { 'foo { |a, b = 42, (c, *d), e:, f: 42, **g, &h; i| nil }' } let(:arguments) do [ s(:arg, :a), s(:optarg, :b, s(:int, 42)), s(:arg, :c), s(:restarg, :d), s(:kwarg, :e), s(:kwoptarg, :f, s(:int, 42)), s(:kwrestarg, :g), s(:blockarg, :h), s(:shadowarg, :i) ] end it { is_expected.to eq(arguments) } context 'when using Ruby 2.7 or newer', :ruby27 do context 'with argument forwarding' do let(:source) { 'def foo(...); end' } let(:arguments) { [s(:forward_arg)] } it { is_expected.to eq(arguments) } if RuboCop::AST::Builder.emit_forward_arg end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/while_node_spec.rb
spec/rubocop/ast/while_node_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::WhileNode do subject(:while_node) { parse_source(source).ast } describe '.new' do context 'with a statement while' do let(:source) { 'while foo; bar; end' } it { is_expected.to be_a(described_class) } end context 'with a modifier while' do let(:source) { 'begin foo; end while bar' } it { is_expected.to be_a(described_class) } end end describe '#keyword' do let(:source) { 'while foo; bar; end' } it { expect(while_node.keyword).to eq('while') } end describe '#inverse_keyword' do let(:source) { 'while foo; bar; end' } it { expect(while_node.inverse_keyword).to eq('until') } end describe '#do?' do context 'with a do keyword' do let(:source) { 'while foo do; bar; end' } it { is_expected.to be_do } end context 'without a do keyword' do let(:source) { 'while foo; bar; end' } it { is_expected.not_to be_do } end end describe '#post_condition_loop?' do context 'with a statement while' do let(:source) { 'while foo; bar; end' } it { is_expected.not_to be_post_condition_loop } end context 'with a modifier while' do let(:source) { 'begin foo; end while bar' } it { is_expected.to be_post_condition_loop } end end describe '#loop_keyword?' do context 'with a statement while' do let(:source) { 'while foo; bar; end' } it { is_expected.to be_loop_keyword } end context 'with a modifier while' do let(:source) { 'begin foo; end while bar' } it { is_expected.to be_loop_keyword } end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/node_spec.rb
spec/rubocop/ast/node_spec.rb
# frozen_string_literal: true require 'uri' module RuboCop module AST # Patch Node class Node # Let's make our predicate matchers read better def used? value_used? end end end end RSpec.describe RuboCop::AST::Node do let(:ast) { parse_source(src).node } let(:node) { ast } describe '#value_used?' do context 'at the top level' do let(:src) { 'expr' } it 'is false' do expect(node).not_to be_used end end context 'within a method call node' do let(:src) { 'obj.method(arg1, arg2, arg3)' } it 'is always true' do expect(node.child_nodes).to all(be_used) end end context 'at the end of a block' do let(:src) { 'obj.method { blah; expr }' } it 'is always true' do expect(node.children.last).to be_used end end context 'within a class definition node' do let(:src) { 'class C < Super; def a; 1; end; self; end' } it 'is always true' do expect(node.child_nodes).to all(be_used) end end context 'within a module definition node' do let(:src) { 'module M; def method; end; 1; end' } it 'is always true' do expect(node.child_nodes).to all(be_used) end end context 'within a singleton class node' do let(:src) { 'class << obj; 1; 2; end' } it 'is always true' do expect(node.child_nodes).to all(be_used) end end context 'within an if...else..end node' do context 'nested in a method call' do let(:src) { 'obj.method(if a then b else c end)' } it 'is always true' do if_node = node.children[2] expect(if_node.child_nodes).to all(be_used) end end context 'at the top level' do let(:src) { 'if a then b else c end' } it 'is true only for the condition' do expect(node.condition).to be_used expect(node.if_branch).not_to be_used expect(node.else_branch).not_to be_used end end end context 'within an array literal' do context 'assigned to an ivar' do let(:src) { '@var = [a, b, c]' } it 'is always true' do ary_node = node.children[1] expect(ary_node.child_nodes).to all(be_used) end end context 'at the top level' do let(:src) { '[a, b, c]' } it 'is always false' do expect(node.child_nodes.map(&:used?)).to all(be false) end end end context 'within a while node' do let(:src) { 'while a; b; end' } it 'is true only for the condition' do expect(node.condition).to be_used expect(node.body).not_to be_used end end end describe '#recursive_basic_literal?' do shared_examples 'literal' do |source| let(:src) { source } it "returns true for `#{source}`" do expect(node).to be_recursive_literal end end it_behaves_like 'literal', '!true' it_behaves_like 'literal', '"#{2}"' it_behaves_like 'literal', '(1)' it_behaves_like 'literal', '(false && true)' it_behaves_like 'literal', '(false <=> true)' it_behaves_like 'literal', '(false or true)' it_behaves_like 'literal', '[1, 2, 3]' it_behaves_like 'literal', '{ :a => 1, :b => 2 }' it_behaves_like 'literal', '{ a: 1, b: 2 }' it_behaves_like 'literal', '/./' it_behaves_like 'literal', '%r{abx}ixo' it_behaves_like 'literal', '1.0' it_behaves_like 'literal', '1' it_behaves_like 'literal', 'false' it_behaves_like 'literal', 'nil' it_behaves_like 'literal', "'str'" shared_examples 'non literal' do |source| let(:src) { source } it "returns false for `#{source}`" do expect(node).not_to be_recursive_literal end end it_behaves_like 'non literal', '(x && false)' it_behaves_like 'non literal', '(x == false)' it_behaves_like 'non literal', '(x or false)' it_behaves_like 'non literal', '[some_method_call]' it_behaves_like 'non literal', '{ :sym => some_method_call }' it_behaves_like 'non literal', '{ some_method_call => :sym }' it_behaves_like 'non literal', '/.#{some_method_call}/' it_behaves_like 'non literal', '%r{abx#{foo}}ixo' it_behaves_like 'non literal', 'some_method_call' it_behaves_like 'non literal', 'some_method_call(x, y)' end describe '#pure?' do context 'for a method call' do let(:src) { 'obj.method(arg1, arg2)' } it 'returns false' do expect(node).not_to be_pure end end context 'for an integer literal' do let(:src) { '100' } it 'returns true' do expect(node).to be_pure end end context 'for an array literal' do context 'with only literal children' do let(:src) { '[1..100, false, :symbol, "string", 1.0]' } it 'returns true' do expect(node).to be_pure end end context 'which contains a method call' do let(:src) { '[1, 2, 3, 3 + 4]' } it 'returns false' do expect(node).not_to be_pure end end end context 'for a hash literal' do context 'with only literal children' do let(:src) { '{range: 1..100, bool: false, str: "string", float: 1.0}' } it 'returns true' do expect(node).to be_pure end end context 'which contains a method call' do let(:src) { '{a: 1, b: 2, c: Kernel.exit}' } it 'returns false' do expect(node).not_to be_pure end end end context 'for a nested if' do context 'where the innermost descendants are local vars and literals' do let(:src) do ['lvar1, lvar2 = method1, method2', 'if $global', ' if @initialized', ' [lvar1, lvar2, true]', ' else', ' :symbol', ' end', 'else', ' lvar1', 'end'].join("\n") end it 'returns true' do if_node = node.children[1] expect(if_node.type).to be :if expect(if_node).to be_pure end end context 'where one branch contains a method call' do let(:src) { 'if $DEBUG then puts "hello" else nil end' } it 'returns false' do expect(node).not_to be_pure end end context 'where one branch contains an assignment statement' do let(:src) { 'if @a then 1 else $global = "str" end' } it 'returns false' do expect(node).not_to be_pure end end end context 'for an ivar assignment' do let(:src) { '@var = 1' } it 'returns false' do expect(node).not_to be_pure end end context 'for a gvar assignment' do let(:src) { '$var = 1' } it 'returns false' do expect(node).not_to be_pure end end context 'for a cvar assignment' do let(:src) { '@@var = 1' } it 'returns false' do expect(node).not_to be_pure end end context 'for an lvar assignment' do let(:src) { 'var = 1' } it 'returns false' do expect(node).not_to be_pure end end context 'for a class definition' do let(:src) { 'class C < Super; def method; end end' } it 'returns false' do expect(node).not_to be_pure end end context 'for a module definition' do let(:src) { 'module M; def method; end end' } it 'returns false' do expect(node).not_to be_pure end end context 'for a regexp' do let(:opts) { '' } let(:body) { '' } let(:src) { "/#{body}/#{opts}" } context 'with interpolated segments' do let(:body) { '#{x}' } it 'returns false' do expect(node).not_to be_pure end end context 'with no interpolation' do let(:src) do # TODO: When supporting Ruby 3.3+ runtime, `URI::DEFAULT_PARSER` can be removed and # only `URI::RFC2396_PARSER` can be used. if defined?(URI::RFC2396_PARSER) URI::RFC2396_PARSER else URI::DEFAULT_PARSER end.make_regexp.inspect end it 'returns true' do expect(node).to be_pure end end context 'with options' do let(:opts) { 'oix' } it 'returns true' do expect(node).to be_pure end end end end describe 'sibling_access' do let(:src) { '[0, 1, 2, 3, 4, 5]' } it 'returns trivial values for a root node' do expect(node.sibling_index).to be_nil expect(node.left_sibling).to be_nil expect(node.right_sibling).to be_nil expect(node.left_siblings).to eq [] expect(node.right_siblings).to eq [] end context 'for a node with siblings' do let(:node) { ast.children[2] } it 'returns the expected values' do expect(node.sibling_index).to eq 2 expect(node.left_sibling.value).to eq 1 expect(node.right_sibling.value).to eq 3 expect(node.left_siblings.map(&:value)).to eq [0, 1] expect(node.right_siblings.map(&:value)).to eq [3, 4, 5] end end context 'for a single child' do let(:src) { '[0]' } let(:node) { ast.children[0] } it 'returns the expected values' do expect(node.sibling_index).to eq 0 expect(node.left_sibling).to be_nil expect(node.right_sibling).to be_nil expect(node.left_siblings.map(&:value)).to eq [] expect(node.right_siblings.map(&:value)).to eq [] end end end describe '#argument_type?' do context 'block arguments' do let(:src) { 'bar { |a, b = 42, *c, d: 42, **e| nil }' } it 'returns true for all argument types' do expect(node.arguments.children).to all be_argument_type expect(node.arguments).not_to be_argument_type end end context 'method arguments' do let(:src) { 'def method_name(a = 0, *b, c: 42, **d); end' } it 'returns true for all argument types' do expect(node.arguments.children).to all be_argument_type expect(node.arguments).not_to be_argument_type end end end describe '#class_constructor?' do context 'class definition with a block' do let(:src) { 'Class.new { a = 42 }' } it 'matches' do expect(node).to be_class_constructor end end context 'module definition with a block' do let(:src) { 'Module.new { a = 42 }' } it 'matches' do expect(node).to be_class_constructor end end context 'class definition' do let(:src) { 'class Foo; a = 42; end' } it 'does not match' do expect(node.class_constructor?).to be_nil end end context 'class definition on outer scope' do let(:src) { '::Class.new { a = 42 }' } it 'matches' do expect(node).to be_class_constructor end end context 'using Ruby >= 2.7', :ruby27 do context 'class definition with a numblock' do let(:src) { 'Class.new { do_something(_1) }' } it 'matches' do expect(node).to be_class_constructor end end context 'module definition with a numblock' do let(:src) { 'Module.new { do_something(_1) }' } it 'matches' do expect(node).to be_class_constructor end end context 'Struct definition with a numblock' do let(:src) { 'Struct.new(:foo, :bar) { do_something(_1) }' } it 'matches' do expect(node).to be_class_constructor end end end context 'using Ruby >= 3.2', :ruby32 do context 'Data definition with a block' do let(:src) { 'Data.define(:foo, :bar) { def a = 42 }' } it 'matches' do expect(node).to be_class_constructor end end context 'Data definition with a numblock' do let(:src) { 'Data.define(:foo, :bar) { do_something(_1) }' } it 'matches' do expect(node).to be_class_constructor end end context 'Data definition without block' do let(:src) { 'Data.define(:foo, :bar)' } it 'matches' do expect(node).to be_class_constructor end end context '::Data' do let(:src) { '::Data.define(:foo, :bar) { def a = 42 }' } it 'matches' do expect(node).to be_class_constructor end end end context 'using Ruby >= 3.4', :ruby34 do context 'class definition with an itblock' do let(:src) { 'Class.new { do_something(it) }' } it 'matches' do expect(node).to be_class_constructor end end context 'module definition with an itblock' do let(:src) { 'Module.new { do_something(it) }' } it 'matches' do expect(node).to be_class_constructor end end context 'Struct definition with an itblock' do let(:src) { 'Struct.new(:foo, :bar) { do_something(it) }' } it 'matches' do expect(node).to be_class_constructor end end context 'Data definition with an itblock' do let(:src) { 'Data.define(:foo, :bar) { do_something(it) }' } it 'matches' do expect(node).to be_class_constructor end end end end describe '#struct_constructor?' do context 'struct definition with a block' do let(:src) { 'Struct.new { a = 42 }' } it 'matches' do expect(node.struct_constructor?).to eq(node.body) end end context 'struct definition without block' do let(:src) { 'Struct.new(:foo, :bar)' } it 'does not match' do expect(node.struct_constructor?).to be_nil end end context '::Struct' do let(:src) { '::Struct.new { a = 42 }' } it 'matches' do expect(node.struct_constructor?).to eq(node.body) end end end describe '#class_definition?' do context 'without inheritance' do let(:src) { 'class Foo; a = 42; end' } it 'matches' do expect(node.class_definition?).to eq(node.body) end end context 'with inheritance' do let(:src) { 'class Foo < Bar; a = 42; end' } it 'matches' do expect(node.class_definition?).to eq(node.body) end end context 'with ::ClassName' do let(:src) { 'class ::Foo < Bar; a = 42; end' } it 'matches' do expect(node.class_definition?).to eq(node.body) end end context 'with Struct' do let(:src) do <<~RUBY Person = Struct.new(:name, :age) do a = 2 def details; end end RUBY end it 'matches' do class_node = node.children.last expect(class_node.class_definition?).to eq(class_node.body) end context 'when using numbered parameter', :ruby27 do let(:src) do <<~RUBY Person = Struct.new(:name, :age) do do_something _1 end RUBY end it 'matches' do class_node = node.children.last expect(class_node.class_definition?).to eq(class_node.body) end end end context 'constant defined as Struct without block' do let(:src) { 'Person = Struct.new(:name, :age)' } it 'does not match' do expect(node.class_definition?).to be_nil end end context 'with Class.new' do let(:src) do <<~RUBY Person = Class.new do a = 2 def details; end end RUBY end it 'matches' do class_node = node.children.last expect(class_node.class_definition?).to eq(class_node.body) end context 'when using numbered parameter', :ruby27 do let(:src) do <<~RUBY Person = Class.new do do_something _1 end RUBY end it 'matches' do class_node = node.children.last expect(class_node.class_definition?).to eq(class_node.body) end end end context 'namespaced class' do let(:src) do <<~RUBY class Foo::Bar::Baz BAZ = 2 def variables; end end RUBY end it 'matches' do expect(node.class_definition?).to eq(node.body) end end context 'with self singleton class' do let(:src) do <<~RUBY class << self BAZ = 2 def variables; end end RUBY end it 'matches' do expect(node.class_definition?).to eq(node.body) end end context 'with object singleton class' do let(:src) do <<~RUBY class << foo BAZ = 2 def variables; end end RUBY end it 'matches' do expect(node.class_definition?).to eq(node.body) end end end describe '#module_definition?' do context 'using module keyword' do let(:src) { 'module Foo; A = 42; end' } it 'matches' do expect(node.module_definition?).to eq(node.body) end end context 'with ::ModuleName' do let(:src) { 'module ::Foo; A = 42; end' } it 'matches' do expect(node.module_definition?).to eq(node.body) end end context 'with Module.new' do let(:src) do <<~RUBY Person = Module.new do a = 2 def details; end end RUBY end it 'matches' do module_node = node.children.last expect(module_node.module_definition?).to eq(module_node.body) end context 'when using numbered parameter', :ruby27 do let(:src) do <<~RUBY Person = Module.new do do_something _1 end RUBY end it 'matches' do module_node = node.children.last expect(module_node.module_definition?).to eq(module_node.body) end end end context 'prepend Module.new' do let(:src) do <<~RUBY prepend(Module.new do a = 2 def details; end end) RUBY end it 'matches' do module_node = node.children.last expect(module_node.module_definition?).to eq(module_node.body) end end context 'nested modules' do let(:src) do <<~RUBY module Foo module Bar BAZ = 2 def variables; end end end RUBY end it 'matches' do expect(node.module_definition?).to eq(node.body) end end context 'namespaced modules' do let(:src) do <<~RUBY module Foo::Bar::Baz BAZ = 2 def variables; end end RUBY end it 'matches' do expect(node.module_definition?).to eq(node.body) end end context 'included module definition' do let(:src) do <<~RUBY include(Module.new do BAZ = 2 def variables; end end) RUBY end it 'matches' do module_node = node.children.last expect(module_node.module_definition?).to eq(module_node.body) end end end describe '#parent_module_name' do subject(:parent_module_name) { node.parent_module_name } context 'when node on top level' do let(:src) { 'def config; end' } it { is_expected.to eq 'Object' } end context 'when node on module' do let(:src) do <<~RUBY module Foo >>attr_reader :config<< end RUBY end it { is_expected.to eq 'Foo' } end context 'when node on singleton class' do let(:src) do <<~RUBY module Foo class << self >>attr_reader :config<< end end RUBY end it { is_expected.to eq 'Foo::#<Class:Foo>' } end context 'when node on class in singleton class' do let(:src) do <<~RUBY module Foo class << self class Bar >>attr_reader :config<< end end end RUBY end it { is_expected.to eq 'Foo::#<Class:Foo>::Bar' } end context 'when node nested in an unknown block' do let(:src) do <<~RUBY module Foo foo do class Bar >>attr_reader :config<< end end end RUBY end it { is_expected.to be_nil } end context 'when node nested in a class << exp' do let(:src) do <<~RUBY class A class << expr >>attr_reader :config<< end end RUBY end it { is_expected.to be_nil } end end describe '#numeric_type?' do context 'when integer literal' do let(:src) { '42' } it 'is true' do expect(node).to be_numeric_type end end context 'when float literal' do let(:src) { '42.0' } it 'is true' do expect(node).to be_numeric_type end end context 'when rational literal' do let(:src) { '42r' } it 'is true' do expect(node).to be_numeric_type end end context 'when complex literal' do let(:src) { '42i' } it 'is true' do expect(node).to be_numeric_type end end context 'when complex literal whose imaginary part is a rational' do let(:src) { '42ri' } it 'is true' do expect(node).to be_numeric_type end end context 'when string literal' do let(:src) { '"42"' } it 'is false' do expect(node).not_to be_numeric_type end end end describe '#conditional?' do context 'when `if` node' do let(:src) do <<~RUBY if condition end RUBY end it 'is true' do expect(node).to be_conditional end end context 'when `while` node' do let(:src) do <<~RUBY while condition end RUBY end it 'is true' do expect(node).to be_conditional end end context 'when `until` node' do let(:src) do <<~RUBY until condition end RUBY end it 'is true' do expect(node).to be_conditional end end context 'when `case` node' do let(:src) do <<~RUBY case condition when foo end RUBY end it 'is true' do expect(node).to be_conditional end end context 'when `case_match` node', :ruby27 do let(:src) do <<~RUBY case pattern in foo end RUBY end it 'is true' do expect(node).to be_conditional end end context 'when post condition loop node' do let(:src) do <<~RUBY begin end while condition RUBY end it 'is false' do expect(node).not_to be_conditional end end end describe '#const_name' do context 'when given a `const` node' do context 'FOO' do let(:src) { 'FOO' } it 'returns FOO' do expect(node.const_name).to eq('FOO') end end context 'FOO::BAR::BAZ' do let(:src) { 'FOO::BAR::BAZ' } it 'returns FOO::BAR::BAZ' do expect(node.const_name).to eq('FOO::BAR::BAZ') end end context '::FOO::BAR::BAZ' do let(:src) { '::FOO::BAR::BAZ' } it 'returns FOO::BAR::BAZ' do expect(node.const_name).to eq('FOO::BAR::BAZ') end end end context 'when given a `casgn` node' do context 'FOO = 1' do let(:src) { 'FOO = 1' } it 'returns FOO' do expect(node.const_name).to eq('FOO') end end context 'FOO::BAR::BAZ = 1' do let(:src) { 'FOO::BAR::BAZ = 1' } it 'returns FOO::BAR::BAZ' do expect(node.const_name).to eq('FOO::BAR::BAZ') end end context '::FOO::BAR::BAZ = 1' do let(:src) { '::FOO::BAR::BAZ = 1' } it 'returns FOO::BAR::BAZ' do expect(node.const_name).to eq('FOO::BAR::BAZ') end end end context 'when given a `send` node' do let(:src) { 'foo.bar' } it 'return nil' do expect(node.const_name).to be_nil end end end describe '#any_match_pattern_type?' do # Ruby 2.7's one-line `in` pattern node type is `match-pattern`. context 'when `in` one-line pattern matching', :ruby27 do let(:src) { 'expression in pattern' } it 'is true' do if node.in_match_type? skip "`in_match` from `AST::Builder.modernize` isn't treated as one-line pattern matching." end expect(node).to be_any_match_pattern_type end end # Ruby 3.0's one-line `in` pattern node type is `match-pattern-p`. context 'when `in` one-line pattern matching', :ruby30 do let(:src) { 'expression in pattern' } it 'is true' do expect(node).to be_any_match_pattern_type end end # Ruby 3.0's one-line `=>` pattern node type is `match-pattern`. context 'when `=>` one-line pattern matching', :ruby30 do let(:src) { 'expression => pattern' } it 'is true' do expect(node).to be_any_match_pattern_type end end context 'when pattern matching', :ruby27 do let(:src) do <<~RUBY case expression in pattern end RUBY end it 'is false' do expect(node).not_to be_any_match_pattern_type end end end describe '#any_str_type?' do context 'when string literal' do let(:src) { "'foo'" } it 'is true' do expect(node).to be_any_str_type end end context 'when interpolated string' do let(:src) { %q("foo #{bar}") } it 'is true' do expect(node).to be_any_str_type end end context 'when `xstr` node' do let(:src) { '`ls`' } it 'is true' do expect(node).to be_any_str_type end end context 'when numeric literal' do let(:src) { '42' } it 'is false' do expect(node).not_to be_any_str_type end end end describe '#any_sym_type?' do context 'when symbol' do let(:src) { ':str' } it 'is true' do expect(node).to be_any_sym_type end end context 'when interpolated symbol' do let(:src) { ':"#{foo}"' } it 'is true' do expect(node).to be_any_sym_type end end context 'when string' do let(:src) { "'foo'" } it 'is false' do expect(node).not_to be_any_sym_type end end context 'when interpolated string' do let(:src) { %q("foo #{bar}") } it 'is false' do expect(node).not_to be_any_sym_type end end context 'when `xstr` node' do let(:src) { '`ls`' } it 'is false' do expect(node).not_to be_any_sym_type end end context 'when numeric literal' do let(:src) { '42' } it 'is false' do expect(node).not_to be_any_sym_type end end end describe '#type?' do let(:src) do <<~RUBY foo.bar RUBY end context 'when it is one of the given types' do it 'is true' do expect(node).to be_type(:send, :const, :lvar) end end context 'when it is not one of the given types' do it 'is false' do expect(node).not_to be_type(:if, :while, :until) end end context 'when given :argument with an `arg` node' do let(:src) { 'foo { |>> var <<| } ' } it 'is true' do arg_node = ast.procarg0_type? ? ast.child_nodes.first : node expect(arg_node).to be_type(:argument) end end context 'when given :boolean with an `true` node' do let(:src) { 'true' } it 'is true' do expect(node).to be_type(:boolean) end end context 'when given :numeric with an `int` node' do let(:src) { '42' } it 'is true' do expect(node).to be_type(:numeric) end end context 'when given :range with an `irange` node' do let(:src) { '1..3' } it 'is true' do expect(node).to be_type(:range) end end context 'when given :call with an `send` node' do let(:src) { 'foo.bar' } it 'is true' do expect(node).to be_type(:call) end end end describe '#loc?' do let(:src) { '%i[>> sym << sym2]' } before(:all) { RSpec::Matchers.alias_matcher :have_loc, :be_loc } context 'when loc exists' do let(:src) { ':sym' } it 'returns true when the location exists' do expect(node).to have_loc(:begin) end end it 'returns false when requested loc is `nil`' do expect(node).not_to have_loc(:begin) end it 'returns false when requested loc does not exist' do expect(node).not_to have_loc(:foo) end end describe '#loc_is?' do let(:src) { '%i[>> sym << sym2]' } context 'when loc exists' do let(:src) { ':sym' } it 'returns true when loc matches argument' do expect(node).to be_loc_is(:begin, ':') end it 'returns false when loc does not match argument' do expect(node).not_to be_loc_is(:begin, '!') end end it 'returns false when requested loc is `nil`' do expect(node).not_to be_loc_is(:begin, ':') end it 'returns false when requested loc does not exist' do expect(node).not_to be_loc_is(:foo, ':') end end context 'traversal' do shared_examples 'traverse' do |test_name, *types, result| it "handles #{test_name}" do expect(node.send(method, *types).map(&:type)).to eq(result) end end describe '#each_ancestor' do let(:src) { 'foo&.bar([>>baz<<]).bat' } let(:method) { :each_ancestor } it_behaves_like 'traverse', 'no argument', %i[array csend send] it_behaves_like 'traverse', 'single argument', :send, %i[send] it_behaves_like 'traverse', 'two arguments', :send, :csend, %i[csend send] it_behaves_like 'traverse', 'group argument', :call, %i[csend send] end describe '#each_child_node' do let(:src) { '[1, 2.0, foo, 3i, 4, BAR, 5r]' } let(:method) { :each_child_node } it_behaves_like 'traverse', 'no argument', %i[int float send complex int const rational] it_behaves_like 'traverse', 'single argument', :int, %i[int int] it_behaves_like 'traverse', 'two arguments', :int, :complex, :csend, %i[int complex int] it_behaves_like 'traverse', 'group argument', :numeric, %i[int float complex int rational] end describe '#each_descendant' do let(:src) { 'foo(true, false, bar(baz, true))' } let(:method) { :each_descendant } it_behaves_like 'traverse', 'no argument', %i[true false send send true] it_behaves_like 'traverse', 'single argument', :true, %i[true true] it_behaves_like 'traverse', 'two arguments', :false, :send, %i[false send send] it_behaves_like 'traverse', 'group argument', :boolean, %i[true false true] end describe '#each_node' do let(:src) { 'def foo(bar, *, baz, **kw, &block); 123; end' } let(:method) { :each_node } it_behaves_like 'traverse', 'no argument', %i[def args arg restarg arg kwrestarg blockarg int] it_behaves_like 'traverse', 'single argument', :arg, %i[arg arg] it_behaves_like 'traverse', 'two arguments', :restarg, :blockarg, %i[restarg blockarg] it_behaves_like 'traverse', 'group argument', :argument, %i[arg restarg arg kwrestarg blockarg] end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/fixtures/code_examples.rb
spec/rubocop/ast/fixtures/code_examples.rb
# Extracted from `parser` gem. # Add the following code at the beginning of `def assert_parses`: # # File.open('./out.rb', 'a+') do |f| # f << code << "\n\n#----\n" if versions.include? '2.7' # end alias $a $b #---- alias $a $+ #---- bar unless foo #---- foo[1, 2] #---- Foo = 10 #---- !foo #---- case foo; in A then true; end #---- case foo; in A::B then true; end #---- case foo; in ::A then true; end #---- () #---- begin end #---- foo[:baz => 1,] #---- Bar::Foo = 10 #---- foo += meth rescue bar #---- def foo(_, _); end #---- def foo(_a, _a); end #---- def a b: return end #---- o = { a: 1 } #---- a b{c d}, :e do end #---- a b{c(d)}, :e do end #---- a b(c d), :e do end #---- a b(c(d)), :e do end #---- a b{c d}, 1 do end #---- a b{c(d)}, 1 do end #---- a b(c d), 1 do end #---- a b(c(d)), 1 do end #---- a b{c d}, 1.0 do end #---- a b{c(d)}, 1.0 do end #---- a b(c d), 1.0 do end #---- a b(c(d)), 1.0 do end #---- a b{c d}, 1.0r do end #---- a b{c(d)}, 1.0r do end #---- a b(c d), 1.0r do end #---- a b(c(d)), 1.0r do end #---- a b{c d}, 1.0i do end #---- a b{c(d)}, 1.0i do end #---- a b(c d), 1.0i do end #---- a b(c(d)), 1.0i do end #---- td (1_500).toString(); td.num do; end #---- -> do rescue; end #---- bar if foo #---- yield(foo) #---- yield foo #---- yield() #---- yield #---- next(foo) #---- next foo #---- next() #---- next #---- 1...2 #---- case foo; when 1, *baz; bar; when *foo; end #---- def foo(...); bar(...); end #---- def foo(...); super(...); end #---- def foo(...); end #---- super(foo) #---- super foo #---- super() #---- desc "foo" do end #---- next fun foo do end #---- def f(foo); end #---- def f(foo, bar); end #---- %i[] #---- %I() #---- [1, 2] #---- {a: if true then 42 end} #---- def f(*foo); end #---- <<HERE foo bar HERE #---- <<'HERE' foo bar HERE #---- <<`HERE` foo bar HERE #---- ->(a; foo, bar) { } #---- 42 #---- +42 #---- -42 #---- module ::Foo; end #---- module Bar::Foo; end #---- foo&.bar {} #---- fun(f bar) #---- begin meth end while foo #---- case foo; in 1; end #---- case foo; in ->{ 42 } then true; end #---- begin; meth; rescue; baz; else foo; ensure; bar end #---- super #---- m "#{[]}" #---- foo[1, 2] = 3 #---- foo + 1 #---- foo - 1 #---- foo * 1 #---- foo / 1 #---- foo % 1 #---- foo ** 1 #---- foo | 1 #---- foo ^ 1 #---- foo & 1 #---- foo <=> 1 #---- foo < 1 #---- foo <= 1 #---- foo > 1 #---- foo >= 1 #---- foo == 1 #---- foo != 1 #---- foo === 1 #---- foo =~ 1 #---- foo !~ 1 #---- foo << 1 #---- foo >> 1 #---- tap (proc do end) #---- def foo =begin =end end #---- :foo #---- :'foo' #---- fun(*bar) #---- fun(*bar, &baz) #---- m { _1 + _9 } #---- m do _1 + _9 end #---- -> { _1 + _9} #---- -> do _1 + _9 end #---- case foo; when 'bar', 'baz'; bar; end #---- case foo; in x, then nil; end #---- case foo; in *x then nil; end #---- case foo; in * then nil; end #---- case foo; in x, y then nil; end #---- case foo; in x, y, then nil; end #---- case foo; in x, *y, z then nil; end #---- case foo; in *x, y, z then nil; end #---- case foo; in 1, "a", [], {} then nil; end #---- for a in foo do p a; end #---- for a in foo; p a; end #---- until foo do meth end #---- until foo; meth end #---- def self.foo; end #---- def self::foo; end #---- def (foo).foo; end #---- def String.foo; end #---- def String::foo; end #---- self::A, foo = foo #---- ::A, foo = foo #---- fun(&bar) #---- foo[bar, :baz => 1,] #---- { 1 => 2 } #---- { 1 => 2, :foo => "bar" } #---- m def x(); end; 1.tap do end #---- true #---- case foo; when 'bar'; bar; end #---- def f(foo:); end #---- f{ |a| } #---- redo #---- __FILE__ #---- 42r #---- 42.1r #---- def f a, o=1, *r, &b; end #---- def f a, o=1, *r, p, &b; end #---- def f a, o=1, &b; end #---- def f a, o=1, p, &b; end #---- def f a, *r, &b; end #---- def f a, *r, p, &b; end #---- def f a, &b; end #---- def f o=1, *r, &b; end #---- def f o=1, *r, p, &b; end #---- def f o=1, &b; end #---- def f o=1, p, &b; end #---- def f *r, &b; end #---- def f *r, p, &b; end #---- def f &b; end #---- def f ; end #---- { } #---- p <<~E " y" x E #---- class A; _1; end #---- module A; _1; end #---- class << foo; _1; end #---- def self.m; _1; end #---- _1 #---- case foo; in [x] then nil; end #---- case foo; in [x,] then nil; end #---- case foo; in [x, y] then true; end #---- case foo; in [x, y,] then true; end #---- case foo; in [x, y, *] then true; end #---- case foo; in [x, y, *z] then true; end #---- case foo; in [x, *y, z] then true; end #---- case foo; in [x, *, y] then true; end #---- case foo; in [*x, y] then true; end #---- case foo; in [*, x] then true; end #---- case foo; in 1 | 2 then true; end #---- a += 1 #---- @a |= 1 #---- @@var |= 10 #---- def a; @@var |= 10; end #---- def foo() a:b end #---- def foo a:b end #---- f { || a:b } #---- fun (f bar) #---- __ENCODING__ #---- __ENCODING__ #---- [ 1 => 2 ] #---- [ 1, 2 => 3 ] #---- 'a\ b' #---- <<-'HERE' a\ b HERE #---- %q{a\ b} #---- "a\ b" #---- <<-"HERE" a\ b HERE #---- %{a\ b} #---- %Q{a\ b} #---- %w{a\ b} #---- %W{a\ b} #---- %i{a\ b} #---- %I{a\ b} #---- :'a\ b' #---- %s{a\ b} #---- :"a\ b" #---- /a\ b/ #---- %r{a\ b} #---- %x{a\ b} #---- `a\ b` #---- <<-`HERE` a\ b HERE #---- ->(scope) {}; scope #---- while class Foo; tap do end; end; break; end #---- while class Foo a = tap do end; end; break; end #---- while class << self; tap do end; end; break; end #---- while class << self; a = tap do end; end; break; end #---- meth until foo #---- break fun foo do end #---- foo #---- BEGIN { 1 } #---- unless foo then bar; else baz; end #---- unless foo; bar; else baz; end #---- begin ensure end #---- case 1; in 2; 3; else; 4; end #---- case foo; in x if true; nil; end #---- case foo; in x unless true; nil; end #---- <<~FOO baz\ qux FOO #---- foo = raise(bar) rescue nil #---- foo += raise(bar) rescue nil #---- foo[0] += raise(bar) rescue nil #---- foo.m += raise(bar) rescue nil #---- foo::m += raise(bar) rescue nil #---- foo.C += raise(bar) rescue nil #---- foo::C ||= raise(bar) rescue nil #---- foo = raise bar rescue nil #---- foo += raise bar rescue nil #---- foo[0] += raise bar rescue nil #---- foo.m += raise bar rescue nil #---- foo::m += raise bar rescue nil #---- foo.C += raise bar rescue nil #---- foo::C ||= raise bar rescue nil #---- p p{p(p);p p}, tap do end #---- begin meth end until foo #---- m1 :k => m2 do; m3() do end; end #---- __LINE__ #---- if (bar); foo; end #---- foo.a = 1 #---- foo::a = 1 #---- foo.A = 1 #---- foo::A = 1 #---- $10 #---- 1 in [a]; a #---- true ? 1.tap do |n| p n end : 0 #---- false ? raise {} : tap {} #---- false ? raise do end : tap do end #---- Bar::Foo #---- a&.b = 1 #---- break(foo) #---- break foo #---- break() #---- break #---- if foo..bar; end #---- !(foo..bar) #---- Foo #---- END { 1 } #---- class Foo < Bar; end #---- begin; meth; rescue Exception; bar; end #---- fun { } #---- fun() { } #---- fun(1) { } #---- fun do end #---- case foo; when 'bar' then bar; end #---- begin; meth; rescue foo => ex; bar; end #---- @foo #---- if foo then bar end #---- fun (1).to_i #---- $var = 10 #---- /\xa8/n =~ "" #---- while not (true) do end #---- foo, bar = 1, 2 #---- (foo, bar) = 1, 2 #---- foo, bar, baz = 1, 2 #---- meth rescue bar #---- self.a, self[1, 2] = foo #---- self::a, foo = foo #---- self.A, foo = foo #---- foo.a += m foo #---- foo::a += m foo #---- foo.A += m foo #---- foo::A += m foo #---- m { |foo| } #---- m { |(foo, bar)| } #---- module Foo; end #---- f{ } #---- f{ | | } #---- f{ |;a| } #---- f{ |; a | } #---- f{ || } #---- f{ |a| } #---- f{ |a, c| } #---- f{ |a,| } #---- f{ |a, &b| } #---- f{ |a, *s, &b| } #---- f{ |a, *, &b| } #---- f{ |a, *s| } #---- f{ |a, *| } #---- f{ |*s, &b| } #---- f{ |*, &b| } #---- f{ |*s| } #---- f{ |*| } #---- f{ |&b| } #---- f{ |a, o=1, o1=2, *r, &b| } #---- f{ |a, o=1, *r, p, &b| } #---- f{ |a, o=1, &b| } #---- f{ |a, o=1, p, &b| } #---- f{ |a, *r, p, &b| } #---- f{ |o=1, *r, &b| } #---- f{ |o=1, *r, p, &b| } #---- f{ |o=1, &b| } #---- f{ |o=1, p, &b| } #---- f{ |*r, p, &b| } #---- assert dogs #---- assert do: true #---- f x: -> do meth do end end #---- foo "#{(1+1).to_i}" do; end #---- alias :foo bar #---- ..100 #---- ...100 #---- case foo; in ^foo then nil; end #---- for a, b in foo; p a, b; end #---- t=1;(foo)?t:T #---- foo[1, 2] #---- f{ |a| } #---- !m foo #---- fun(:foo => 1) #---- fun(:foo => 1, &baz) #---- %W[foo #{bar}] #---- %W[foo #{bar}foo#@baz] #---- fun (1) #---- %w[] #---- %W() #---- `foobar` #---- case foo; in self then true; end #---- a, (b, c) = foo #---- ((b, )) = foo #---- class A < B end #---- bar def foo; self.each do end end #---- case foo; in "a": then true; end #---- case foo; in "a": 1 then true; end #---- a&.b &&= 1 #---- "#{-> foo {}}" #---- -foo #---- +foo #---- ~foo #---- meth while foo #---- $+ #---- [1, *foo, 2] #---- [1, *foo] #---- [*foo] #---- f{ |foo: 1, bar: 2, **baz, &b| } #---- f{ |foo: 1, &b| } #---- f{ |**baz, &b| } #---- if foo...bar; end #---- !(...bar) #---- !(..bar) #---- !(bar...) #---- !(bar..) #---- !(foo...bar) #---- fun(foo, *bar) #---- fun(foo, *bar, &baz) #---- foo or bar #---- foo || bar #---- f{ |foo:| } #---- 1.33 #---- -1.33 #---- foo[1, 2] = 3 #---- def f foo = 1; end #---- def f(foo=1, bar=2); end #---- case foo; in A(1, 2) then true; end #---- case foo; in A(x:) then true; end #---- case foo; in A() then true; end #---- case foo; in A[1, 2] then true; end #---- case foo; in A[x:] then true; end #---- case foo; in A[] then true; end #---- meth (-1.3).abs #---- foo (-1.3).abs #---- foo[m bar] #---- m a + b do end #---- +2.0 ** 10 #---- -2 ** 10 #---- -2.0 ** 10 #---- class << foo; nil; end #---- def f (((a))); end #---- def f ((a, a1)); end #---- def f ((a, *r)); end #---- def f ((a, *r, p)); end #---- def f ((a, *)); end #---- def f ((a, *, p)); end #---- def f ((*r)); end #---- def f ((*r, p)); end #---- def f ((*)); end #---- def f ((*, p)); end #---- ->{ } #---- foo[bar,] #---- ->{ } #---- -> * { } #---- -> do end #---- m ->(a = ->{_1}) {a} #---- m ->(a: ->{_1}) {a} #---- %i[foo bar] #---- f (g rescue nil) #---- [/()\1/, ?#] #---- `foo#{bar}baz` #---- "#{1}" #---- %W"#{1}" #---- def f foo: ; end #---- def f foo: -1 ; end #---- foo, bar = m foo #---- foo.a &&= 1 #---- foo[0, 1] &&= 2 #---- ->(a) { } #---- -> (a) { } #---- fun(foo, :foo => 1) #---- fun(foo, :foo => 1, &baz) #---- foo[0, 1] += 2 #---- @@foo #---- @foo, @@bar = *foo #---- a, b = *foo, bar #---- a, *b = bar #---- a, *b, c = bar #---- a, * = bar #---- a, *, c = bar #---- *b = bar #---- *b, c = bar #---- * = bar #---- *, c, d = bar #---- 42i #---- 42ri #---- 42.1i #---- 42.1ri #---- case; when foo; 'foo'; end #---- f{ |a, b,| } #---- p begin 1.times do 1 end end #---- p <<~E E #---- p <<~E E #---- p <<~E x E #---- p <<~E x y E #---- p <<~E x y E #---- p <<~E x y E #---- p <<~E x y E #---- p <<~E x y E #---- p <<~E x y E #---- p <<~E x y E #---- p <<~E x \ y E #---- p <<~E x \ y E #---- p <<~"E" x #{foo} E #---- p <<~`E` x #{foo} E #---- p <<~"E" x #{" y"} E #---- case foo; in 1..2 then true; end #---- case foo; in 1.. then true; end #---- case foo; in ..2 then true; end #---- case foo; in 1...2 then true; end #---- case foo; in 1... then true; end #---- case foo; in ...2 then true; end #---- begin; meth; rescue; foo; else; bar; end #---- m [] do end #---- m [], 1 do end #---- %w[foo bar] #---- return fun foo do end #---- fun (1 ) #---- /foo#{bar}baz/ #---- if (a, b = foo); end #---- foo.(1) #---- foo::(1) #---- 1.. #---- 1... #---- def foo(...); bar(...); end #---- /#{1}(?<match>bar)/ =~ 'bar' #---- foo = meth rescue bar #---- begin; meth; ensure; bar; end #---- var = 10; var #---- begin; meth; rescue; foo; end #---- begin; meth; rescue => ex; bar; end #---- begin; meth; rescue => @ex; bar; end #---- case foo; in {} then true; end #---- case foo; in a: 1 then true; end #---- case foo; in { a: 1 } then true; end #---- case foo; in { a: 1, } then true; end #---- case foo; in a: then true; end #---- case foo; in **a then true; end #---- case foo; in ** then true; end #---- case foo; in a: 1, b: 2 then true; end #---- case foo; in a:, b: then true; end #---- case foo; in a: 1, _a:, ** then true; end #---- case foo; in {a: 1 } false ; end #---- case foo; in {a: 2} false ; end #---- case foo; in {Foo: 42 } false ; end #---- case foo; in a: {b:}, c: p c ; end #---- case foo; in {a: } true ; end #---- lambda{|;a|a} #---- -> (arg={}) {} #---- case [__FILE__, __LINE__ + 1, __ENCODING__] in [__FILE__, __LINE__, __ENCODING__] end #---- nil #---- def f (foo: 1, bar: 2, **baz, &b); end #---- def f (foo: 1, &b); end #---- def f **baz, &b; end #---- def f *, **; end #---- false #---- a ||= 1 #---- if foo then bar; else baz; end #---- if foo; bar; else baz; end #---- a b{c d}, "x" do end #---- a b(c d), "x" do end #---- a b{c(d)}, "x" do end #---- a b(c(d)), "x" do end #---- a b{c d}, /x/ do end #---- a b(c d), /x/ do end #---- a b{c(d)}, /x/ do end #---- a b(c(d)), /x/ do end #---- a b{c d}, /x/m do end #---- a b(c d), /x/m do end #---- a b{c(d)}, /x/m do end #---- a b(c(d)), /x/m do end #---- { foo: 2, **bar } #---- begin; meth; rescue; baz; ensure; bar; end #---- a&.b #---- super foo, bar do end #---- super do end #---- let () { m(a) do; end } #---- "foo#@a" "bar" #---- /#)/x #---- 'foobar' #---- %q(foobar) #---- not m foo #---- class Foo < a:b; end #---- ?a #---- foo ? 1 : 2 #---- def f(*); end #---- case foo; in **nil then true; end #---- foo.fun #---- foo::fun #---- foo::Fun() #---- if foo then bar; end #---- if foo; bar; end #---- return(foo) #---- return foo #---- return() #---- return #---- undef foo, :bar, :"foo#{1}" #---- f <<-TABLE do TABLE end #---- case foo; when 'bar'; bar; else baz; end #---- begin; rescue LoadError; else; end #---- foo += m foo #---- unless foo then bar; end #---- unless foo; bar; end #---- { foo: 2 } #---- fun (1) {} #---- foo.fun (1) {} #---- foo::fun (1) {} #---- if (bar; a, b = foo); end #---- meth do; foo; rescue; bar; end #---- foo, bar = meth rescue [1, 2] #---- '#@1' #---- '#@@1' #---- <<-'HERE' #@1 HERE #---- <<-'HERE' #@@1 HERE #---- %q{#@1} #---- %q{#@@1} #---- "#@1" #---- "#@@1" #---- <<-"HERE" #@1 HERE #---- <<-"HERE" #@@1 HERE #---- %{#@1} #---- %{#@@1} #---- %Q{#@1} #---- %Q{#@@1} #---- %w[ #@1 ] #---- %w[ #@@1 ] #---- %W[#@1] #---- %W[#@@1] #---- %i[ #@1 ] #---- %i[ #@@1 ] #---- %I[#@1] #---- %I[#@@1] #---- :'#@1' #---- :'#@@1' #---- %s{#@1} #---- %s{#@@1} #---- :"#@1" #---- :"#@@1" #---- /#@1/ #---- /#@@1/ #---- %r{#@1} #---- %r{#@@1} #---- %x{#@1} #---- %x{#@@1} #---- `#@1` #---- `#@@1` #---- <<-`HERE` #@1 HERE #---- <<-`HERE` #@@1 HERE #---- meth[] {} #---- "#@a #@@a #$a" #---- /source/im #---- foo && (a, b = bar) #---- foo || (a, b = bar) #---- if foo; bar; elsif baz; 1; else 2; end #---- def f(&block); end #---- m "#{}#{()}" #---- #---- a &&= 1 #---- ::Foo #---- class Foo; end #---- class Foo end #---- begin; meth; rescue Exception, foo; bar; end #---- 1..2 #---- case foo; in x then x; end #---- case 1; in 2; 3; else; end #---- -> a: 1 { } #---- -> a: { } #---- def foo; end #---- def String; end #---- def String=; end #---- def until; end #---- def BEGIN; end #---- def END; end #---- foo.fun bar #---- foo::fun bar #---- foo::Fun bar #---- @@var = 10 #---- a = b = raise :x #---- a += b = raise :x #---- a = b += raise :x #---- a += b += raise :x #---- p ->() do a() do end end #---- foo.a ||= 1 #---- foo[0, 1] ||= 2 #---- p -> { :hello }, a: 1 do end #---- foo[0, 1] += m foo #---- { 'foo': 2 } #---- { 'foo': 2, 'bar': {}} #---- f(a ? "a":1) #---- while foo do meth end #---- while foo; meth end #---- foo = bar, 1 #---- foo = *bar #---- foo = baz, *bar #---- m = -> *args do end #---- defined? foo #---- defined?(foo) #---- defined? @foo #---- A += 1 #---- ::A += 1 #---- B::A += 1 #---- def x; self::A ||= 1; end #---- def x; ::A ||= 1; end #---- foo.a += 1 #---- foo::a += 1 #---- foo.A += 1 #---- p <<~"E" x\n y E #---- case foo; in (1) then true; end #---- $foo #---- case; when foo; 'foo'; else 'bar'; end #---- a @b do |c|;end #---- p :foo, {a: proc do end, b: proc do end} #---- p :foo, {:a => proc do end, b: proc do end} #---- p :foo, {"a": proc do end, b: proc do end} #---- p :foo, {proc do end => proc do end, b: proc do end} #---- p :foo, {** proc do end, b: proc do end} #---- <<~E 1 \ 2 3 E #---- <<-E 1 \ 2 3 E #---- def f(**nil); end #---- m { |**nil| } #---- ->(**nil) {} #---- a # # .foo #---- a # # .foo #---- a # # &.foo #---- a # # &.foo #---- ::Foo = 10 #---- not foo #---- not(foo) #---- not() #---- :"foo#{bar}baz" #---- @var = 10 #---- "foo#{bar}baz" #---- case foo; in 1 => a then true; end #---- def f(foo: 1); end #---- a ? b & '': nil #---- meth 1 do end.fun bar #---- meth 1 do end.fun(bar) #---- meth 1 do end::fun bar #---- meth 1 do end::fun(bar) #---- meth 1 do end.fun bar do end #---- meth 1 do end.fun(bar) {} #---- meth 1 do end.fun {} #---- def f(**); end #---- foo and bar #---- foo && bar #---- !(a, b = foo) #---- def m; class << self; class C; end; end; end #---- def m; class << self; module M; end; end; end #---- def m; class << self; A = nil; end; end #---- begin foo!; bar! end #---- foo = m foo #---- foo = bar = m foo #---- def f(**foo); end #---- %I[foo #{bar}] #---- %I[foo#{bar}] #---- self #---- a = 1; a b: 1 #---- def foo raise; raise A::B, ''; end #---- /(?<match>bar)/ =~ 'bar'; match #---- let (:a) { m do; end } #---- fun #---- fun! #---- fun(1) #---- fun () {} #---- if /wat/; end #---- !/wat/ #---- # coding:utf-8 "\xD0\xBF\xD1\x80\xD0\xBE\xD0\xB2\xD0\xB5\xD1\x80\xD0\xBA\xD0\xB0" #---- while def foo; tap do end; end; break; end #---- while def self.foo; tap do end; end; break; end #---- while def foo a = tap do end; end; break; end #---- while def self.foo a = tap do end; end; break; end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/node_pattern/parse_helper.rb
spec/rubocop/ast/node_pattern/parse_helper.rb
# frozen_string_literal: true # Copied from Parser, some lines commented out with `# !!!` module ParseHelper include AST::Sexp # !!! require 'parser/all' # !!! require 'parser/macruby' # !!! require 'parser/rubymotion' ALL_VERSIONS = %w(1.8 1.9 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 mac ios) def setup @diagnostics = [] super if defined?(super) end def parser_for_ruby_version(version) case version when '1.8' then parser = Parser::Ruby18.new when '1.9' then parser = Parser::Ruby19.new when '2.0' then parser = Parser::Ruby20.new when '2.1' then parser = Parser::Ruby21.new when '2.2' then parser = Parser::Ruby22.new when '2.3' then parser = Parser::Ruby23.new when '2.4' then parser = Parser::Ruby24.new when '2.5' then parser = Parser::Ruby25.new when '2.6' then parser = Parser::Ruby26.new when '2.7' then parser = Parser::Ruby27.new when '2.8' then parser = Parser::Ruby28.new when 'mac' then parser = Parser::MacRuby.new when 'ios' then parser = Parser::RubyMotion.new else raise "Unrecognized Ruby version #{version}" end parser.diagnostics.consumer = lambda do |diagnostic| @diagnostics << diagnostic end parser end def with_versions(versions) (versions & ALL_VERSIONS).each do |version| @diagnostics.clear parser = parser_for_ruby_version(version) yield version, parser end end def assert_source_range(expect_range, range, version, what) if expect_range == nil # Avoid "Use assert_nil if expecting nil from .... This will fail in Minitest 6."" assert_nil range, "(#{version}) range of #{what}" else assert range.is_a?(Parser::Source::Range), "(#{version}) #{range.inspect}.is_a?(Source::Range) for #{what}" assert_equal expect_range, range.to_range, "(#{version}) range of #{what}" end end # Use like this: # ~~~ # assert_parses( # s(:send, s(:lit, 10), :+, s(:lit, 20)) # %q{10 + 20}, # %q{~~~~~~~ expression # | ^ operator # | ~~ expression (lit) # }, # %w(1.8 1.9) # optional # ) # ~~~ def assert_parses(ast, code, source_maps='', versions=ALL_VERSIONS) with_versions(versions) do |version, parser| try_parsing(ast, code, parser, source_maps, version) end # Also try parsing with lexer set to use UTF-32LE internally with_versions(versions) do |version, parser| parser.instance_eval { @lexer.force_utf32 = true } try_parsing(ast, code, parser, source_maps, version) end end def try_parsing(ast, code, parser, source_maps, version) source_file = Parser::Source::Buffer.new('(assert_parses)', source: code) begin parsed_ast = parser.parse(source_file) rescue => exc backtrace = exc.backtrace Exception.instance_method(:initialize).bind(exc). call("(#{version}) #{exc.message}") exc.set_backtrace(backtrace) raise end if ast.nil? assert_nil parsed_ast, "(#{version}) AST equality" return end assert_equal ast, parsed_ast, "(#{version}) AST equality" parse_source_map_descriptions(source_maps) do |range, map_field, ast_path, line| astlet = traverse_ast(parsed_ast, ast_path) if astlet.nil? # This is a testsuite bug. raise "No entity with AST path #{ast_path} in #{parsed_ast.inspect}" end assert astlet.frozen? assert astlet.location.respond_to?(map_field), "(#{version}) #{astlet.location.inspect}.respond_to?(#{map_field.inspect}) for:\n#{parsed_ast.inspect}" found_range = astlet.location.send(map_field) assert_source_range(range, found_range, version, line.inspect) end # !!! assert parser.instance_eval { @lexer }.cmdarg.empty?, # !!! "(#{version}) expected cmdarg to be empty after parsing" # !!! assert_equal 0, parser.instance_eval { @lexer.instance_eval { @paren_nest } }, # !!! "(#{version}) expected paren_nest to be 0 after parsing" end # Use like this: # ~~~ # assert_diagnoses( # [:warning, :ambiguous_prefix, { prefix: '*' }], # %q{foo *bar}, # %q{ ^ location # | ~~~ highlights (0)}) # ~~~ def assert_diagnoses(diagnostic, code, source_maps='', versions=ALL_VERSIONS) with_versions(versions) do |version, parser| source_file = Parser::Source::Buffer.new('(assert_diagnoses)', source: code) begin parser = parser.parse(source_file) rescue Parser::SyntaxError # do nothing; the diagnostic was reported end assert_equal 1, @diagnostics.count, "(#{version}) emits a single diagnostic, not\n" \ "#{@diagnostics.map(&:render).join("\n")}" emitted_diagnostic = @diagnostics.first level, reason, arguments = diagnostic arguments ||= {} message = Parser::Messages.compile(reason, arguments) assert_equal level, emitted_diagnostic.level assert_equal reason, emitted_diagnostic.reason assert_equal arguments, emitted_diagnostic.arguments assert_equal message, emitted_diagnostic.message parse_source_map_descriptions(source_maps) do |range, map_field, ast_path, line| case map_field when 'location' assert_source_range range, emitted_diagnostic.location, version, 'location' when 'highlights' index = ast_path.first.to_i assert_source_range range, emitted_diagnostic.highlights[index], version, "#{index}th highlight" else raise "Unknown diagnostic range #{map_field}" end end end end # Use like this: # ~~~ # assert_diagnoses_many( # [ # [:warning, :ambiguous_literal], # [:error, :unexpected_token, { :token => :tLCURLY }] # ], # %q{m /foo/ {}}, # SINCE_2_4) # ~~~ def assert_diagnoses_many(diagnostics, code, versions=ALL_VERSIONS) with_versions(versions) do |version, parser| source_file = Parser::Source::Buffer.new('(assert_diagnoses_many)', source: code) begin parser = parser.parse(source_file) rescue Parser::SyntaxError # do nothing; the diagnostic was reported end assert_equal diagnostics.count, @diagnostics.count diagnostics.zip(@diagnostics) do |expected_diagnostic, actual_diagnostic| level, reason, arguments = expected_diagnostic arguments ||= {} message = Parser::Messages.compile(reason, arguments) assert_equal level, actual_diagnostic.level assert_equal reason, actual_diagnostic.reason assert_equal arguments, actual_diagnostic.arguments assert_equal message, actual_diagnostic.message end end end def refute_diagnoses(code, versions=ALL_VERSIONS) with_versions(versions) do |version, parser| source_file = Parser::Source::Buffer.new('(refute_diagnoses)', source: code) begin parser = parser.parse(source_file) rescue Parser::SyntaxError # do nothing; the diagnostic was reported end assert_empty @diagnostics, "(#{version}) emits no diagnostics, not\n" \ "#{@diagnostics.map(&:render).join("\n")}" end end def assert_context(context, code, versions=ALL_VERSIONS) with_versions(versions) do |version, parser| source_file = Parser::Source::Buffer.new('(assert_context)', source: code) parsed_ast = parser.parse(source_file) nodes = find_matching_nodes(parsed_ast) { |node| node.type == :send && node.children[1] == :get_context } assert_equal 1, nodes.count, "there must exactly 1 `get_context()` call" node = nodes.first assert_equal context, node.context, "(#{version}) expect parsing context to match" end end SOURCE_MAP_DESCRIPTION_RE = /(?x) ^(?# $1 skip) ^(\s*) (?# $2 highlight) ([~\^]+|\!) \s+ (?# $3 source_map_field) ([a-z_]+) (?# $5 ast_path) (\s+\(([a-z_.\/0-9]+)\))? $/ def parse_source_map_descriptions(descriptions) unless block_given? return to_enum(:parse_source_map_descriptions, descriptions) end descriptions.each_line do |line| # Remove leading " |", if it exists. line = line.sub(/^\s*\|/, '').rstrip next if line.empty? if (match = SOURCE_MAP_DESCRIPTION_RE.match(line)) if match[2] != '!' begin_pos = match[1].length end_pos = begin_pos + match[2].length range = begin_pos...end_pos end source_map_field = match[3] if match[5] ast_path = match[5].split('.') else ast_path = [] end yield range, source_map_field, ast_path, line else raise "Cannot parse source map description line: #{line.inspect}." end end end def traverse_ast(ast, path) path.inject(ast) do |astlet, path_component| # Split "dstr/2" to :dstr and 1 type_str, index_str = path_component.split('/') type = type_str.to_sym if index_str.nil? index = 0 else index = index_str.to_i - 1 end matching_children = \ astlet.children.select do |child| AST::Node === child && child.type == type end matching_children[index] end end def find_matching_nodes(ast, &block) return [] unless ast.is_a?(AST::Node) result = [] result << ast if block.call(ast) ast.children.each { |child| result += find_matching_nodes(child, &block) } result end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/node_pattern/helper.rb
spec/rubocop/ast/node_pattern/helper.rb
# frozen_string_literal: true require_relative 'parse_helper' Failure = Struct.new(:expected, :actual) module NodePatternHelper include ParseHelper def assert_equal(expected, actual, mess = nil) expect(actual).to eq(expected), *mess end def assert(test, mess = nil) expect(test).to be(true), *mess end def expect_parsing(ast, source, source_maps) version = '-' try_parsing(ast, source, parser, source_maps, version) end end RSpec.shared_context 'parser' do include NodePatternHelper let(:parser) { RuboCop::AST::NodePattern::Parser::WithMeta.new } end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/node_pattern/parser_spec.rb
spec/rubocop/ast/node_pattern/parser_spec.rb
# frozen_string_literal: true require_relative 'helper' RSpec.describe RuboCop::AST::NodePattern::Parser do include_context 'parser' describe 'sequences' do it 'parses simple sequences properly' do expect_parsing( s(:sequence, s(:node_type, :int), s(:number, 42)), '(int 42)', '^ begin | ^ end |~~~~~~~~ expression | ~~~ expression (node_type) | ~~ expression (number)' ) end it 'parses capture vs repetition with correct priority' do s_int = s(:capture, s(:node_type, :int)) s_str = s(:capture, s(:node_type, :str)) expect_parsing( s(:sequence, s(:wildcard, '_'), s(:repetition, s_int, :*), s(:repetition, s(:sequence, s_str), :+)), '(_ $int* ($str)+)', '^ begin | ^ end |~~~~~~~~~~~~~~~~~ expression | ~~~~~ expression (repetition) | ^ operator (repetition) | ^ operator (repetition.capture) | ~~~ expression (repetition.capture.node_type)' ) end it 'parses function calls' do expect_parsing( s(:function_call, :func, s(:number, 1), s(:number, 2), s(:number, 3)), '#func(1, 2, 3)', ' ^ begin | ^ end |~~~~~ selector | ^ expression (number)' ) end it 'expands ... in sequence head deep inside unions' do rest = s(:rest, :'...') expect_parsing( s(:sequence, s(:union, s(:node_type, :a), s(:subsequence, s(:node_type, :b), rest), s(:subsequence, s(:wildcard), rest, s(:node_type, :c)), s(:subsequence, s(:wildcard), s(:capture, rest)))), '({a | b ... | ... c | $...})', '' ) end it 'parses unions of literals as a set' do expect_parsing( s(:sequence, s(:set, s(:symbol, :a), s(:number, 42), s(:string, 'hello'))), '({:a 42 "hello"})', ' ^ begin (set) | ^ end (set) | ~~ expression (set/1.number)' ) end it 'generates specialized nodes' do source_file = Parser::Source::Buffer.new('(spec)', source: '($_)') ast = parser.parse(source_file) expect(ast.class).to eq RuboCop::AST::NodePattern::Node::Sequence expect(ast.child.class).to eq RuboCop::AST::NodePattern::Node::Capture end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/node_pattern/lexer_spec.rb
spec/rubocop/ast/node_pattern/lexer_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::NodePattern::Lexer do let(:source) { '(send nil? #func(:foo) #func (bar))' } let(:lexer) { RuboCop::AST::NodePattern::Parser::WithMeta::Lexer.new(source) } let(:tokens) do tokens = [] while (token = lexer.next_token) tokens << token end tokens end it 'provides tokens via next_token' do type, (text, range) = tokens[3] expect(type).to eq :tFUNCTION_CALL expect(text).to eq :func expect(range.to_range).to eq 11...16 expect(tokens.map(&:first)).to eq [ '(', :tNODE_TYPE, :tPREDICATE, :tFUNCTION_CALL, :tARG_LIST, :tSYMBOL, ')', :tFUNCTION_CALL, '(', :tNODE_TYPE, ')', ')' ] end context 'with $type+' do let(:source) { '(array sym $int+ x)' } it 'is parsed as `$ int + x`' do expect(tokens.map { |token| token.last.first }).to eq \ %i[( array sym $ int + x )] end end [ /test/, /[abc]+\/()?/x, # rubocop:disable Style/RegexpLiteral /back\\slash/ ].each do |regexp| context "when given a regexp #{regexp.inspect}" do let(:source) { regexp.inspect } it 'round trips' do token = tokens.first value = token.last.first expect(value.inspect).to eq regexp.inspect end end end context 'when given a regexp ending with a backslash' do let(:source) { '/tricky\\/' } it 'does not lexes it properly' do expect { tokens }.to raise_error(RuboCop::AST::NodePattern::LexerRex::ScanError) end end context 'when given node types and constants' do let(:source) { '(aa bb Cc DD ::Ee Ff::GG %::Hh Zz %Zz)' } let(:tokens) { super()[1...-1] } it 'distinguishes them' do types = tokens.map(&:first) expect(types).to eq ([:tNODE_TYPE] * 2) + ([:tPARAM_CONST] * 7) zz, percent_zz = tokens.last(2).map { |token| token.last.first } expect(zz).to eq 'Zz' expect(percent_zz).to eq 'Zz' end end context 'when given arithmetic symbols' do let(:source) { ':&' } it 'is parsed as `:&`' do expect(tokens.map { |token| token.last.first }).to eq [:&] end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/node_pattern/sets_spec.rb
spec/rubocop/ast/node_pattern/sets_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::NodePattern::Sets do subject(:name) { described_class[set] } let(:set) { Set[1, 2, 3, 4, 5, 6] } it { is_expected.to eq '::RuboCop::AST::NodePattern::Sets::SET_1_2_3_ETC' } it { is_expected.to eq described_class[Set[6, 5, 4, 3, 2, 1]] } it { is_expected.not_to eq described_class[Set[1, 2, 3, 4, 5, 6, 7]] } it 'creates a constant with the right value' do expect(eval(name)).to eq set # rubocop:disable Security/Eval end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/ext/range_spec.rb
spec/rubocop/ast/ext/range_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::AST::Ext::Range do subject(:node) { parse_source(source).ast } let(:source) { <<~RUBY } [ 1, 2 ] RUBY describe '#line_span' do it 'returns the range of lines a range occupies' do expect(node.loc.begin.line_span).to eq 1..1 end it 'accepts an `exclude_end` keyword argument' do expect(node.source_range.line_span(exclude_end: true)).to eq 1...4 end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/ext/set_spec.rb
spec/rubocop/ast/ext/set_spec.rb
# frozen_string_literal: true # rubocop:disable RSpec/DescribeClass, Style/CaseEquality RSpec.describe 'Set#===' do it 'tests for inclusion' do expect(Set[1, 2, 3] === 2).to be true end end # rubocop:enable RSpec/DescribeClass, Style/CaseEquality
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop-ast.rb
lib/rubocop-ast.rb
# frozen_string_literal: true require_relative 'rubocop/ast'
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast.rb
lib/rubocop/ast.rb
# frozen_string_literal: true require 'parser' require 'prism' require 'forwardable' require 'set' require_relative 'ast/ext/range' require_relative 'ast/utilities/simple_forwardable' require_relative 'ast/node_pattern/method_definer' require_relative 'ast/node_pattern' require_relative 'ast/node/mixin/descendence' require_relative 'ast/node_pattern/builder' require_relative 'ast/node_pattern/comment' require_relative 'ast/node_pattern/compiler' require_relative 'ast/node_pattern/compiler/subcompiler' require_relative 'ast/node_pattern/compiler/atom_subcompiler' require_relative 'ast/node_pattern/compiler/binding' require_relative 'ast/node_pattern/compiler/node_pattern_subcompiler' require_relative 'ast/node_pattern/compiler/sequence_subcompiler' require_relative 'ast/node_pattern/lexer' require_relative 'ast/node_pattern/node' require_relative 'ast/node_pattern/parser' require_relative 'ast/node_pattern/sets' require_relative 'ast/sexp' require_relative 'ast/node' require_relative 'ast/node/mixin/method_identifier_predicates' require_relative 'ast/node/mixin/binary_operator_node' require_relative 'ast/node/mixin/collection_node' require_relative 'ast/node/mixin/conditional_node' require_relative 'ast/node/mixin/constant_node' require_relative 'ast/node/mixin/hash_element_node' require_relative 'ast/node/mixin/method_dispatch_node' require_relative 'ast/node/mixin/modifier_node' require_relative 'ast/node/mixin/numeric_node' require_relative 'ast/node/mixin/parameterized_node' require_relative 'ast/node/mixin/predicate_operator_node' require_relative 'ast/node/mixin/basic_literal_node' require_relative 'ast/node/alias_node' require_relative 'ast/node/and_node' require_relative 'ast/node/arg_node' require_relative 'ast/node/args_node' require_relative 'ast/node/array_node' require_relative 'ast/node/asgn_node' require_relative 'ast/node/block_node' require_relative 'ast/node/break_node' require_relative 'ast/node/case_match_node' require_relative 'ast/node/case_node' require_relative 'ast/node/casgn_node' require_relative 'ast/node/class_node' require_relative 'ast/node/complex_node' require_relative 'ast/node/const_node' require_relative 'ast/node/def_node' require_relative 'ast/node/defined_node' require_relative 'ast/node/ensure_node' require_relative 'ast/node/for_node' require_relative 'ast/node/forward_args_node' require_relative 'ast/node/float_node' require_relative 'ast/node/hash_node' require_relative 'ast/node/if_node' require_relative 'ast/node/in_pattern_node' require_relative 'ast/node/index_node' require_relative 'ast/node/indexasgn_node' require_relative 'ast/node/int_node' require_relative 'ast/node/keyword_begin_node' require_relative 'ast/node/keyword_splat_node' require_relative 'ast/node/lambda_node' require_relative 'ast/node/masgn_node' require_relative 'ast/node/mlhs_node' require_relative 'ast/node/module_node' require_relative 'ast/node/next_node' require_relative 'ast/node/op_asgn_node' require_relative 'ast/node/and_asgn_node' require_relative 'ast/node/or_asgn_node' require_relative 'ast/node/or_node' require_relative 'ast/node/pair_node' require_relative 'ast/node/procarg0_node' require_relative 'ast/node/range_node' require_relative 'ast/node/rational_node' require_relative 'ast/node/regexp_node' require_relative 'ast/node/rescue_node' require_relative 'ast/node/resbody_node' require_relative 'ast/node/return_node' require_relative 'ast/node/self_class_node' require_relative 'ast/node/send_node' require_relative 'ast/node/csend_node' require_relative 'ast/node/str_node' require_relative 'ast/node/dstr_node' require_relative 'ast/node/super_node' require_relative 'ast/node/symbol_node' require_relative 'ast/node/until_node' require_relative 'ast/node/var_node' require_relative 'ast/node/when_node' require_relative 'ast/node/while_node' require_relative 'ast/node/yield_node' require_relative 'ast/builder' require_relative 'ast/builder_prism' require_relative 'ast/processed_source' require_relative 'ast/rubocop_compatibility' require_relative 'ast/token' require_relative 'ast/traversal' require_relative 'ast/version' RuboCop::AST::NodePattern::Parser.autoload :WithMeta, "#{__dir__}/ast/node_pattern/with_meta" RuboCop::AST::NodePattern::Compiler.autoload :Debug, "#{__dir__}/ast/node_pattern/compiler/debug"
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/version.rb
lib/rubocop/ast/version.rb
# frozen_string_literal: true module RuboCop module AST module Version STRING = '1.49.0' end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/sexp.rb
lib/rubocop/ast/sexp.rb
# frozen_string_literal: true module RuboCop module AST # This module provides a shorthand method to create a {Node} like # `Parser::AST::Sexp`. # # @see https://www.rubydoc.info/gems/ast/AST/Sexp module Sexp # Creates a {Node} with type `type` and children `children`. def s(type, *children) klass = Builder::NODE_MAP[type] || Node klass.new(type, children) end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/processed_source.rb
lib/rubocop/ast/processed_source.rb
# frozen_string_literal: true require 'digest/sha1' module RuboCop module AST # A `Prism` interface's class that provides a fixed `Prism::ParseLexResult` instead of parsing. # # This class implements the `parse_lex` method to return a preparsed `Prism::ParseLexResult` # rather than parsing the source code. When the parse result is already available externally, # such as in Ruby LSP, the Prism parsing process can be bypassed. class PrismPreparsed def initialize(prism_result) unless prism_result.is_a?(Prism::ParseLexResult) raise ArgumentError, <<~MESSAGE Expected a `Prism::ParseLexResult` object, but received `#{prism_result.class}`. MESSAGE end @prism_result = prism_result end def parse_lex(_source, **_prism_options) @prism_result end end # ProcessedSource contains objects which are generated by Parser # and other information such as disabled lines for cops. # It also provides a convenient way to access source lines. class ProcessedSource # rubocop:disable Metrics/ClassLength # @api private STRING_SOURCE_NAME = '(string)' INVALID_LEVELS = %i[error fatal].freeze private_constant :INVALID_LEVELS PARSER_ENGINES = %i[default parser_whitequark parser_prism].freeze private_constant :PARSER_ENGINES attr_reader :path, :buffer, :ast, :comments, :tokens, :diagnostics, :parser_error, :raw_source, :ruby_version, :parser_engine def self.from_file(path, ruby_version, parser_engine: :default) file = File.read(path, mode: 'rb') new(file, ruby_version, path, parser_engine: parser_engine) end def initialize( source, ruby_version, path = nil, parser_engine: :default, prism_result: nil ) parser_engine = normalize_parser_engine(parser_engine, ruby_version) # Defaults source encoding to UTF-8, regardless of the encoding it has # been read with, which could be non-utf8 depending on the default # external encoding. (+source).force_encoding(Encoding::UTF_8) unless source.encoding == Encoding::UTF_8 @raw_source = source @path = path @diagnostics = [] @ruby_version = ruby_version @parser_engine = parser_engine @parser_error = nil parse(source, ruby_version, parser_engine, prism_result) end def ast_with_comments return if !ast || !comments @ast_with_comments ||= Parser::Source::Comment.associate_by_identity(ast, comments) end # Returns the source lines, line break characters removed, excluding a # possible __END__ and everything that comes after. def lines @lines ||= begin all_lines = @buffer.source_lines last_token_line = tokens.any? ? tokens.last.line : all_lines.size result = [] all_lines.each_with_index do |line, ix| break if ix >= last_token_line && line == '__END__' result << line end result end end def [](*args) lines[*args] end def valid_syntax? return false if @parser_error @diagnostics.none? { |d| INVALID_LEVELS.include?(d.level) } end # Raw source checksum for tracking infinite loops. def checksum Digest::SHA1.hexdigest(@raw_source) end # @deprecated Use `comments.each` def each_comment(&block) comments.each(&block) end # @deprecated Use `comment_at_line`, `each_comment_in_lines`, or `comments.find` def find_comment(&block) comments.find(&block) end # @deprecated Use `tokens.each` def each_token(&block) tokens.each(&block) end # @deprecated Use `tokens.find` def find_token(&block) tokens.find(&block) end def file_path buffer.name end def blank? ast.nil? end # @return [Comment, nil] the comment at that line, if any. def comment_at_line(line) comment_index[line] end # @return [Boolean] if the given line number has a comment. def line_with_comment?(line) comment_index.include?(line) end # Enumerates on the comments contained with the given `line_range` def each_comment_in_lines(line_range) return to_enum(:each_comment_in_lines, line_range) unless block_given? line_range.each do |line| if (comment = comment_index[line]) yield comment end end end # @return [Boolean] if any of the lines in the given `source_range` has a comment. # Consider using `each_comment_in_lines` instead def contains_comment?(source_range) each_comment_in_lines(source_range.line..source_range.last_line).any? end # @deprecated use contains_comment? alias commented? contains_comment? # @deprecated Use `each_comment_in_lines` # Should have been called `comments_before_or_at_line`. Doubtful it has of any valid use. def comments_before_line(line) each_comment_in_lines(0..line).to_a end def start_with?(string) return false if self[0].nil? self[0].start_with?(string) end def preceding_line(token) lines[token.line - 2] end def current_line(token) lines[token.line - 1] end def following_line(token) lines[token.line] end def line_indentation(line_number) lines[line_number - 1] .match(/^(\s*)/)[1] .to_s .length end def tokens_within(range_or_node) begin_index = first_token_index(range_or_node) end_index = last_token_index(range_or_node) sorted_tokens[begin_index..end_index] end def first_token_of(range_or_node) sorted_tokens[first_token_index(range_or_node)] end def last_token_of(range_or_node) sorted_tokens[last_token_index(range_or_node)] end # The tokens list is always sorted by token position, except for cases when heredoc # is passed as a method argument. In this case tokens are interleaved by # heredoc contents' tokens. def sorted_tokens # Use stable sort. @sorted_tokens ||= tokens.sort_by.with_index { |token, i| [token.begin_pos, i] } end private def comment_index @comment_index ||= {}.tap do |hash| comments.each { |c| hash[c.location.line] = c } end end def parse(source, ruby_version, parser_engine, prism_result) buffer_name = @path || STRING_SOURCE_NAME @buffer = Parser::Source::Buffer.new(buffer_name, 1) begin @buffer.source = source rescue EncodingError, Parser::UnknownEncodingInMagicComment => e @parser_error = e @ast = nil @comments = [] @tokens = [] return end parser = create_parser(ruby_version, parser_engine, prism_result) @ast, @comments, @tokens = tokenize(parser) end def tokenize(parser) begin ast, comments, tokens = parser.tokenize(@buffer) ast ||= nil # force `false` to `nil`, see https://github.com/whitequark/parser/pull/722 rescue Parser::SyntaxError # All errors are in diagnostics. No need to handle exception. comments = [] tokens = [] end ast&.complete! tokens.map! { |t| Token.from_parser_token(t) } [ast, comments, tokens] end # rubocop:disable Lint/FloatComparison, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength def parser_class(ruby_version, parser_engine) case parser_engine when :parser_whitequark case ruby_version when 1.9 require 'parser/ruby19' Parser::Ruby19 when 2.0 require 'parser/ruby20' Parser::Ruby20 when 2.1 require 'parser/ruby21' Parser::Ruby21 when 2.2 require 'parser/ruby22' Parser::Ruby22 when 2.3 require 'parser/ruby23' Parser::Ruby23 when 2.4 require 'parser/ruby24' Parser::Ruby24 when 2.5 require 'parser/ruby25' Parser::Ruby25 when 2.6 require 'parser/ruby26' Parser::Ruby26 when 2.7 require 'parser/ruby27' Parser::Ruby27 when 2.8, 3.0 require 'parser/ruby30' Parser::Ruby30 when 3.1 require 'parser/ruby31' Parser::Ruby31 when 3.2 require 'parser/ruby32' Parser::Ruby32 when 3.3 require 'parser/ruby33' Parser::Ruby33 when 3.4 require 'parser/ruby34' Parser::Ruby34 else raise ArgumentError, 'RuboCop supports target Ruby versions 3.4 and below with ' \ "`parser`. Specified target Ruby version: #{ruby_version.inspect}" end when :parser_prism case ruby_version when 3.3 Prism::Translation::Parser33 when 3.4 Prism::Translation::Parser34 when 3.5, 4.0 Prism::Translation::Parser40 when 4.1 Prism::Translation::Parser41 else raise ArgumentError, 'RuboCop supports target Ruby versions 3.3 and above with Prism. ' \ "Specified target Ruby version: #{ruby_version.inspect}" end end end # rubocop:enable Lint/FloatComparison, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength def builder_class(parser_engine) case parser_engine when :parser_whitequark RuboCop::AST::Builder when :parser_prism RuboCop::AST::BuilderPrism end end # rubocop:disable Metrics/AbcSize, Metrics/MethodLength def create_parser(ruby_version, parser_engine, prism_result) builder = builder_class(parser_engine).new parser_class = parser_class(ruby_version, parser_engine) parser_instance = if parser_engine == :parser_prism && prism_result # NOTE: Since it is intended for use with Ruby LSP, it targets only Prism. # If there is no reuse of a pre-parsed result, such as in Ruby LSP, # regular parsing with Prism occurs, and `else` branch will be executed. prism_reparsed = PrismPreparsed.new(prism_result) parser_class.new(builder, parser: prism_reparsed) else parser_class.new(builder) end parser_instance.tap do |parser| # On JRuby there's a risk that we hang in tokenize() if we # don't set the all errors as fatal flag. The problem is caused by a bug # in Racc that is discussed in issue #93 of the whitequark/parser # project on GitHub. parser.diagnostics.all_errors_are_fatal = (RUBY_ENGINE != 'ruby') parser.diagnostics.ignore_warnings = false parser.diagnostics.consumer = lambda do |diagnostic| @diagnostics << diagnostic end end end # rubocop:enable Metrics/AbcSize, Metrics/MethodLength def normalize_parser_engine(parser_engine, ruby_version) parser_engine = parser_engine.to_sym unless PARSER_ENGINES.include?(parser_engine) raise ArgumentError, 'The keyword argument `parser_engine` accepts `default`, ' \ "`parser_whitequark`, or `parser_prism`, but `#{parser_engine}` " \ 'was passed.' end if parser_engine == :default default_parser_engine(ruby_version) else parser_engine end end # The Parser gem does not support Ruby 3.5 or later. # It is also not fully compatible with Ruby 3.4 but for # now respects using parser for backwards compatibility. def default_parser_engine(ruby_version) if ruby_version >= 3.4 :parser_prism else :parser_whitequark end end def first_token_index(range_or_node) begin_pos = source_range(range_or_node).begin_pos sorted_tokens.bsearch_index { |token| token.begin_pos >= begin_pos } end def last_token_index(range_or_node) end_pos = source_range(range_or_node).end_pos sorted_tokens.bsearch_index { |token| token.end_pos >= end_pos } end def source_range(range_or_node) if range_or_node.respond_to?(:source_range) range_or_node.source_range else range_or_node end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node.rb
lib/rubocop/ast/node.rb
# frozen_string_literal: true module RuboCop module AST # `RuboCop::AST::Node` is a subclass of `Parser::AST::Node`. It provides # access to parent nodes and an object-oriented way to traverse an AST with # the power of `Enumerable`. # # It has predicate methods for every node type, like this: # # @example # node.send_type? # Equivalent to: `node.type == :send` # node.op_asgn_type? # Equivalent to: `node.type == :op_asgn` # # # Non-word characters (other than a-zA-Z0-9_) in type names are omitted. # node.defined_type? # Equivalent to: `node.type == :defined?` # # # Find the first lvar node under the receiver node. # lvar_node = node.each_descendant.find(&:lvar_type?) # class Node < Parser::AST::Node # rubocop:disable Metrics/ClassLength include RuboCop::AST::Sexp extend NodePattern::Macros include RuboCop::AST::Descendence # @api private # <=> isn't included here, because it doesn't return a boolean. COMPARISON_OPERATORS = %i[== === != <= >= > <].to_set.freeze # @api private TRUTHY_LITERALS = %i[str dstr xstr int float sym dsym array hash regexp true irange erange complex rational regopt].to_set.freeze # @api private FALSEY_LITERALS = %i[false nil].to_set.freeze # @api private LITERALS = (TRUTHY_LITERALS + FALSEY_LITERALS).freeze # @api private COMPOSITE_LITERALS = %i[dstr xstr dsym array hash irange erange regexp].to_set.freeze # @api private BASIC_LITERALS = (LITERALS - COMPOSITE_LITERALS).freeze # @api private MUTABLE_LITERALS = %i[str dstr xstr array hash regexp irange erange].to_set.freeze # @api private IMMUTABLE_LITERALS = (LITERALS - MUTABLE_LITERALS).freeze # @api private EQUALS_ASSIGNMENTS = %i[lvasgn ivasgn cvasgn gvasgn casgn masgn].to_set.freeze # @api private SHORTHAND_ASSIGNMENTS = %i[op_asgn or_asgn and_asgn].to_set.freeze # @api private ASSIGNMENTS = (EQUALS_ASSIGNMENTS + SHORTHAND_ASSIGNMENTS).freeze # @api private BASIC_CONDITIONALS = %i[if while until].to_set.freeze # @api private CONDITIONALS = (BASIC_CONDITIONALS + %i[case case_match]).freeze # @api private POST_CONDITION_LOOP_TYPES = %i[while_post until_post].to_set.freeze # @api private LOOP_TYPES = (POST_CONDITION_LOOP_TYPES + %i[while until for]).freeze # @api private VARIABLES = %i[ivar gvar cvar lvar].to_set.freeze # @api private REFERENCES = %i[nth_ref back_ref].to_set.freeze # @api private KEYWORDS = %i[alias and break case class def defs defined? kwbegin do else ensure for if module next not or postexe redo rescue retry return self super zsuper then undef until when while yield].to_set.freeze # @api private OPERATOR_KEYWORDS = %i[and or].to_set.freeze # @api private SPECIAL_KEYWORDS = %w[__FILE__ __LINE__ __ENCODING__].to_set.freeze LITERAL_RECURSIVE_METHODS = (COMPARISON_OPERATORS + %i[* ! <=>]).freeze LITERAL_RECURSIVE_TYPES = (OPERATOR_KEYWORDS + COMPOSITE_LITERALS + %i[begin pair]).freeze private_constant :LITERAL_RECURSIVE_METHODS, :LITERAL_RECURSIVE_TYPES EMPTY_CHILDREN = [].freeze EMPTY_PROPERTIES = {}.freeze private_constant :EMPTY_CHILDREN, :EMPTY_PROPERTIES # @api private GROUP_FOR_TYPE = { def: :any_def, defs: :any_def, arg: :argument, optarg: :argument, restarg: :argument, kwarg: :argument, kwoptarg: :argument, kwrestarg: :argument, blockarg: :argument, forward_arg: :argument, shadowarg: :argument, true: :boolean, false: :boolean, int: :numeric, float: :numeric, rational: :numeric, complex: :numeric, str: :any_str, dstr: :any_str, xstr: :any_str, sym: :any_sym, dsym: :any_sym, irange: :range, erange: :range, send: :call, csend: :call, block: :any_block, numblock: :any_block, itblock: :any_block, match_pattern: :any_match_pattern, match_pattern_p: :any_match_pattern }.freeze private_constant :GROUP_FOR_TYPE # Define a +recursive_?+ predicate method for the given node kind. private_class_method def self.def_recursive_literal_predicate(kind) # rubocop:disable Metrics/MethodLength recursive_kind = "recursive_#{kind}?" kind_filter = "#{kind}?" class_eval <<~RUBY, __FILE__, __LINE__ + 1 def #{recursive_kind} # def recursive_literal? case type # case type when :send # when :send LITERAL_RECURSIVE_METHODS.include?(method_name) && # LITERAL_RECURSIVE_METHODS.include?(method_name) && receiver.send(:#{recursive_kind}) && # receiver.send(:recursive_literal?) && arguments.all?(&:#{recursive_kind}) # arguments.all?(&:recursive_literal?) when LITERAL_RECURSIVE_TYPES # when LITERAL_RECURSIVE_TYPES children.compact.all?(&:#{recursive_kind}) # children.compact.all?(&:recursive_literal?) else # else send(:#{kind_filter}) # send(:literal?) end # end end # end RUBY end # @see https://www.rubydoc.info/gems/ast/AST/Node:initialize def initialize(type, children = EMPTY_CHILDREN, properties = EMPTY_PROPERTIES) @mutable_attributes = {} # ::AST::Node#initialize freezes itself. super # #parent= may be invoked multiple times for a node because there are # pending nodes while constructing AST and they are replaced later. # For example, `lvar` and `send` type nodes are initially created as an # `ident` type node and fixed to the appropriate type later. # So, the #parent attribute needs to be mutable. each_child_node do |child_node| child_node.parent = self unless child_node.complete? end end # Determine if the node is one of several node types in a single query # Allows specific single node types, as well as "grouped" types # (e.g. `:boolean` for `:true` or `:false`) def type?(*types) return true if types.include?(type) group_type = GROUP_FOR_TYPE[type] !group_type.nil? && types.include?(group_type) end (Parser::Meta::NODE_TYPES - [:send]).each do |node_type| method_name = "#{node_type.to_s.gsub(/\W/, '')}_type?" class_eval <<~RUBY, __FILE__, __LINE__ + 1 def #{method_name} # def block_type? @type == :#{node_type} # @type == :block end # end RUBY end # Most nodes are of 'send' type, so this method is defined # separately to make this check as fast as possible. def send_type? false end # Returns the parent node, or `nil` if the receiver is a root node. # # @return [Node, nil] the parent node or `nil` def parent @mutable_attributes[:parent] end def parent=(node) @mutable_attributes[:parent] = node end # @return [Boolean] def parent? !!parent end # @return [Boolean] def root? !parent end def complete! @mutable_attributes.freeze each_child_node(&:complete!) end def complete? @mutable_attributes.frozen? end protected :parent= # Override `AST::Node#updated` so that `AST::Processor` does not try to # mutate our ASTs. Since we keep references from children to parents and # not just the other way around, we cannot update an AST and share # identical subtrees. Rather, the entire AST must be copied any time any # part of it is changed. def updated(type = nil, children = nil, properties = {}) properties[:location] ||= @location klass = RuboCop::AST::Builder::NODE_MAP[type || @type] || Node klass.new(type || @type, children || @children, properties) end # Returns the index of the receiver node in its siblings. (Sibling index # uses zero based numbering.) # Use is discouraged, this is a potentially slow method. # # @return [Integer, nil] the index of the receiver node in its siblings def sibling_index parent&.children&.index { |sibling| sibling.equal?(self) } end # Use is discouraged, this is a potentially slow method and can lead # to even slower algorithms # @return [Node, nil] the right (aka next) sibling def right_sibling return unless parent parent.children[sibling_index + 1].freeze end # Use is discouraged, this is a potentially slow method and can lead # to even slower algorithms # @return [Node, nil] the left (aka previous) sibling def left_sibling i = sibling_index return if i.nil? || i.zero? parent.children[i - 1].freeze end # Use is discouraged, this is a potentially slow method and can lead # to even slower algorithms # @return [Array<Node>] the left (aka previous) siblings def left_siblings return [].freeze unless parent parent.children[0...sibling_index].freeze end # Use is discouraged, this is a potentially slow method and can lead # to even slower algorithms # @return [Array<Node>] the right (aka next) siblings def right_siblings return [].freeze unless parent parent.children[(sibling_index + 1)..].freeze end # Common destructuring method. This can be used to normalize # destructuring for different variations of the node. # Some node types override this with their own custom # destructuring method. # # @return [Array<Node>] the different parts of the ndde alias node_parts to_a # Calls the given block for each ancestor node from parent to root. # If no block is given, an `Enumerator` is returned. # # @overload each_ancestor # Yield all nodes. # @overload each_ancestor(type) # Yield only nodes matching the type. # @param [Symbol] type a node type # @overload each_ancestor(type_a, type_b, ...) # Yield only nodes matching any of the types. # @param [Symbol] type_a a node type # @param [Symbol] type_b a node type # @yieldparam [Node] node each ancestor node # @return [self] if a block is given # @return [Enumerator] if no block is given def each_ancestor(*types, &block) return to_enum(__method__, *types) unless block visit_ancestors(types, &block) self end # Returns an array of ancestor nodes. # This is a shorthand for `node.each_ancestor.to_a`. # # @return [Array<Node>] an array of ancestor nodes def ancestors each_ancestor.to_a end # NOTE: Some rare nodes may have no source, like `s(:args)` in `foo {}` # @return [String, nil] def source loc.expression&.source end def source_range loc.expression end def first_line loc.line end def last_line loc.last_line end def line_count return 0 unless source_range source_range.last_line - source_range.first_line + 1 end def nonempty_line_count source.lines.grep(/\S/).size end def source_length source_range ? source_range.size : 0 end ## Destructuring # @!method receiver(node = self) def_node_matcher :receiver, <<~PATTERN {(send $_ ...) (any_block (call $_ ...) ...)} PATTERN # @!method str_content(node = self) def_node_matcher :str_content, '(str $_)' def const_name return unless const_type? || casgn_type? if namespace && !namespace.cbase_type? "#{namespace.const_name}::#{short_name}" else short_name.to_s end end # @!method defined_module0(node = self) def_node_matcher :defined_module0, <<~PATTERN {(class (const $_ $_) ...) (module (const $_ $_) ...) (casgn $_ $_ (send #global_const?({:Class :Module}) :new ...)) (casgn $_ $_ (block (send #global_const?({:Class :Module}) :new ...) ...))} PATTERN private :defined_module0 def defined_module namespace, name = *defined_module0 s(:const, namespace, name) if name end def defined_module_name (const = defined_module) && const.const_name end ## Searching the AST def parent_module_name # what class or module is this method/constant/etc definition in? # returns nil if answer cannot be determined ancestors = each_ancestor(:class, :module, :sclass, :casgn, :block) result = ancestors.filter_map do |ancestor| parent_module_name_part(ancestor) do |full_name| return nil unless full_name full_name end end.reverse.join('::') result.empty? ? 'Object' : result end ## Predicates def multiline? line_count > 1 end def single_line? line_count == 1 end def empty_source? source_length.zero? end # Some cops treat the shovel operator as a kind of assignment. # @!method assignment_or_similar?(node = self) def_node_matcher :assignment_or_similar?, <<~PATTERN {assignment? (send _recv :<< ...)} PATTERN def literal? LITERALS.include?(type) end def basic_literal? BASIC_LITERALS.include?(type) end def truthy_literal? TRUTHY_LITERALS.include?(type) end def falsey_literal? FALSEY_LITERALS.include?(type) end def mutable_literal? MUTABLE_LITERALS.include?(type) end def immutable_literal? IMMUTABLE_LITERALS.include?(type) end # @!macro [attach] def_recursive_literal_predicate # @!method recursive_$1? # @return [Boolean] def_recursive_literal_predicate :literal def_recursive_literal_predicate :basic_literal def variable? VARIABLES.include?(type) end def reference? REFERENCES.include?(type) end def equals_asgn? EQUALS_ASSIGNMENTS.include?(type) end def shorthand_asgn? SHORTHAND_ASSIGNMENTS.include?(type) end def assignment? ASSIGNMENTS.include?(type) end def basic_conditional? BASIC_CONDITIONALS.include?(type) end def conditional? CONDITIONALS.include?(type) end def post_condition_loop? POST_CONDITION_LOOP_TYPES.include?(type) end # NOTE: `loop { }` is a normal method call and thus not a loop keyword. def loop_keyword? LOOP_TYPES.include?(type) end def keyword? return true if special_keyword? || (send_type? && prefix_not?) return false unless KEYWORDS.include?(type) !OPERATOR_KEYWORDS.include?(type) || loc.operator.is?(type.to_s) end def special_keyword? SPECIAL_KEYWORDS.include?(source) end def operator_keyword? OPERATOR_KEYWORDS.include?(type) end def parenthesized_call? loc_is?(:begin, '(') end def call_type? GROUP_FOR_TYPE[type] == :call end def chained? parent&.call_type? && eql?(parent.receiver) end def argument? parent&.send_type? && parent.arguments.include?(self) end def any_def_type? GROUP_FOR_TYPE[type] == :any_def end def argument_type? GROUP_FOR_TYPE[type] == :argument end def boolean_type? GROUP_FOR_TYPE[type] == :boolean end def numeric_type? GROUP_FOR_TYPE[type] == :numeric end def range_type? GROUP_FOR_TYPE[type] == :range end def any_block_type? GROUP_FOR_TYPE[type] == :any_block end def any_match_pattern_type? GROUP_FOR_TYPE[type] == :any_match_pattern end def any_str_type? GROUP_FOR_TYPE[type] == :any_str end def any_sym_type? GROUP_FOR_TYPE[type] == :any_sym end def guard_clause? node = operator_keyword? ? rhs : self node.match_guard_clause? end # Shortcut to safely check if a location is present # @return [Boolean] def loc?(which_loc) return false unless loc.respond_to?(which_loc) !loc.public_send(which_loc).nil? end # Shortcut to safely test a particular location, even if # this location does not exist or is `nil` def loc_is?(which_loc, str) return false unless loc?(which_loc) loc.public_send(which_loc).is?(str) end # @!method match_guard_clause?(node = self) def_node_matcher :match_guard_clause?, <<~PATTERN [${(send nil? {:raise :fail} ...) return break next} single_line?] PATTERN # @!method proc?(node = self) def_node_matcher :proc?, <<~PATTERN {(block (send nil? :proc) ...) (block (send #global_const?(:Proc) :new) ...) (send #global_const?(:Proc) :new)} PATTERN # @!method lambda?(node = self) def_node_matcher :lambda?, '(any_block (send nil? :lambda) ...)' # @!method lambda_or_proc?(node = self) def_node_matcher :lambda_or_proc?, '{lambda? proc?}' # @!method global_const?(node = self, name) def_node_matcher :global_const?, '(const {nil? cbase} %1)' # @!method class_constructor?(node = self) def_node_matcher :class_constructor?, <<~PATTERN { (send #global_const?({:Class :Module :Struct}) :new ...) (send #global_const?(:Data) :define ...) (any_block { (send #global_const?({:Class :Module :Struct}) :new ...) (send #global_const?(:Data) :define ...) } ...) } PATTERN # @deprecated Use `:class_constructor?` # @!method struct_constructor?(node = self) def_node_matcher :struct_constructor?, <<~PATTERN (any_block (send #global_const?(:Struct) :new ...) _ $_) PATTERN # @!method class_definition?(node = self) def_node_matcher :class_definition?, <<~PATTERN {(class _ _ $_) (sclass _ $_) (any_block (send #global_const?({:Struct :Class}) :new ...) _ $_)} PATTERN # @!method module_definition?(node = self) def_node_matcher :module_definition?, <<~PATTERN {(module _ $_) (any_block (send #global_const?(:Module) :new ...) _ $_)} PATTERN # Some expressions are evaluated for their value, some for their side # effects, and some for both # If we know that an expression is useful only for its side effects, that # means we can transform it in ways which preserve the side effects, but # change the return value # So, does the return value of this node matter? If we changed it to # `(...; nil)`, might that affect anything? # def value_used? # rubocop:disable Metrics/MethodLength # Be conservative and return true if we're not sure. return false if parent.nil? case parent.type when :array, :defined?, :dstr, :dsym, :eflipflop, :erange, :float, :hash, :iflipflop, :irange, :not, :pair, :regexp, :str, :sym, :when, :xstr parent.value_used? when :begin, :kwbegin begin_value_used? when :for for_value_used? when :case, :if case_if_value_used? when :while, :until, :while_post, :until_post while_until_value_used? else true end end # Some expressions are evaluated for their value, some for their side # effects, and some for both. # If we know that expressions are useful only for their return values, # and have no side effects, that means we can reorder them, change the # number of times they are evaluated, or replace them with other # expressions which are equivalent in value. # So, is evaluation of this node free of side effects? # def pure? # Be conservative and return false if we're not sure case type when :__FILE__, :__LINE__, :const, :cvar, :defined?, :false, :float, :gvar, :int, :ivar, :lvar, :nil, :str, :sym, :true, :regopt true when :and, :array, :begin, :case, :dstr, :dsym, :eflipflop, :ensure, :erange, :for, :hash, :if, :iflipflop, :irange, :kwbegin, :not, :or, :pair, :regexp, :until, :until_post, :when, :while, :while_post child_nodes.all?(&:pure?) else false end end private def visit_ancestors(types) last_node = self while (current_node = last_node.parent) yield current_node if types.empty? || current_node.type?(*types) last_node = current_node end end def begin_value_used? # the last child node determines the value of the parent sibling_index == parent.children.size - 1 ? parent.value_used? : false end def for_value_used? # `for var in enum; body; end` # (for <var> <enum> <body>) sibling_index == 2 ? parent.value_used? : true end def case_if_value_used? # (case <condition> <when...>) # (if <condition> <truebranch> <falsebranch>) sibling_index.zero? || parent.value_used? end def while_until_value_used? # (while <condition> <body>) -> always evaluates to `nil` sibling_index.zero? end def parent_module_name_part(node) case node.type when :class, :module, :casgn # TODO: if constant name has cbase (leading ::), then we don't need # to keep traversing up through nested classes/modules node.defined_module_name when :sclass yield parent_module_name_for_sclass(node) else # block parent_module_name_for_block(node) { yield nil } end end def parent_module_name_for_sclass(sclass_node) # TODO: look for constant definition and see if it is nested # inside a class or module subject = sclass_node.children[0] if subject.const_type? "#<Class:#{subject.const_name}>" elsif subject.self_type? "#<Class:#{sclass_node.parent_module_name}>" end end def parent_module_name_for_block(ancestor) if ancestor.method?(:class_eval) # `class_eval` with no receiver applies to whatever module or class # we are currently in return unless (receiver = ancestor.receiver) yield unless receiver.const_type? receiver.const_name elsif !new_class_or_module_block?(ancestor) yield end end # @!method new_class_or_module_block?(node = self) def_node_matcher :new_class_or_module_block?, <<~PATTERN ^(casgn _ _ (block (send (const _ {:Class :Module}) :new) ...)) PATTERN end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern.rb
lib/rubocop/ast/node_pattern.rb
# frozen_string_literal: true require 'delegate' module RuboCop module AST # This class performs a pattern-matching operation on an AST node. # # Detailed syntax: /docs/modules/ROOT/pages/node_pattern.adoc # # Initialize a new `NodePattern` with `NodePattern.new(pattern_string)`, then # pass an AST node to `NodePattern#match`. Alternatively, use one of the class # macros in `NodePattern::Macros` to define your own pattern-matching method. # # If the match fails, `nil` will be returned. If the match succeeds, the # return value depends on whether a block was provided to `#match`, and # whether the pattern contained any "captures" (values which are extracted # from a matching AST.) # # - With block: #match yields the captures (if any) and passes the return # value of the block through. # - With no block, but one capture: the capture is returned. # - With no block, but multiple captures: captures are returned as an array. # - With no block and no captures: #match returns `true`. # class NodePattern # Helpers for defining methods based on a pattern string module Macros # Define a method which applies a pattern to an AST node # # The new method will return nil if the node does not match. # If the node matches, and a block is provided, the new method will # yield to the block (passing any captures as block arguments). # If the node matches, and no block is provided, the new method will # return the captures, or `true` if there were none. def def_node_matcher(method_name, pattern_str, **keyword_defaults) NodePattern.new(pattern_str).def_node_matcher(self, method_name, **keyword_defaults) end # Define a method which recurses over the descendants of an AST node, # checking whether any of them match the provided pattern # # If the method name ends with '?', the new method will return `true` # as soon as it finds a descendant which matches. Otherwise, it will # yield all descendants which match. def def_node_search(method_name, pattern_str, **keyword_defaults) NodePattern.new(pattern_str).def_node_search(self, method_name, **keyword_defaults) end end extend SimpleForwardable include MethodDefiner Invalid = Class.new(StandardError) VAR = 'node' # Yields its argument and any descendants, depth-first. # def self.descend(element, &block) return to_enum(__method__, element) unless block yield element if element.is_a?(::RuboCop::AST::Node) element.children.each do |child| descend(child, &block) end end nil end attr_reader :pattern, :ast, :match_code def_delegators :@compiler, :captures, :named_parameters, :positional_parameters def initialize(str, compiler: Compiler.new) @pattern = str @ast = compiler.parser.parse(str) @compiler = compiler @match_code = @compiler.compile_as_node_pattern(@ast, var: VAR) @cache = {} end def match(*args, **rest, &block) @cache[:lambda] ||= as_lambda @cache[:lambda].call(*args, block: block, **rest) end def ==(other) other.is_a?(NodePattern) && other.ast == ast end alias eql? == def to_s "#<#{self.class} #{pattern}>" end def marshal_load(pattern) # :nodoc: initialize pattern end def marshal_dump # :nodoc: pattern end def as_json(_options = nil) # :nodoc: pattern end def encode_with(coder) # :nodoc: coder['pattern'] = pattern end def init_with(coder) # :nodoc: initialize(coder['pattern']) end def freeze @match_code.freeze @compiler.freeze super end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/rubocop_compatibility.rb
lib/rubocop/ast/rubocop_compatibility.rb
# frozen_string_literal: true module RuboCop # ... module AST # Responsible for compatibility with main gem # @api private module RuboCopCompatibility INCOMPATIBLE_COPS = { '0.89.0' => 'Layout/LineLength', '0.92.0' => 'Style/MixinUsage' }.freeze def rubocop_loaded loaded = Gem::Version.new(RuboCop::Version::STRING) incompatible = INCOMPATIBLE_COPS.select do |k, _v| loaded < Gem::Version.new(k) end.values return if incompatible.empty? warn <<~WARNING *** WARNING – Incompatible versions of `rubocop` and `rubocop-ast` You may encounter issues with the following \ Cop#{'s' if incompatible.size > 1}: #{incompatible.join(', ')} Please upgrade rubocop to at least v#{INCOMPATIBLE_COPS.keys.last} WARNING end end extend RuboCopCompatibility end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/token.rb
lib/rubocop/ast/token.rb
# frozen_string_literal: true module RuboCop module AST # A basic wrapper around Parser's tokens. class Token LEFT_PAREN_TYPES = %i[tLPAREN tLPAREN2].freeze LEFT_CURLY_TYPES = %i[tLCURLY tLAMBEG].freeze attr_reader :pos, :type, :text def self.from_parser_token(parser_token) type, details = parser_token text, range = details new(range, type, text) end def initialize(pos, type, text) @pos = pos @type = type # Parser token "text" may be an Integer @text = text.to_s end def line @pos.line end def column @pos.column end def begin_pos @pos.begin_pos end def end_pos @pos.end_pos end def to_s "[[#{line}, #{column}], #{type}, #{text.inspect}]" end # Checks if there is whitespace after token def space_after? pos.source_buffer.source.match(/\G\s/, end_pos) end # Checks if there is whitespace before token def space_before? position = begin_pos.zero? ? begin_pos : begin_pos - 1 pos.source_buffer.source.match(/\G\s/, position) end ## Type Predicates def comment? type == :tCOMMENT end def semicolon? type == :tSEMI end def left_array_bracket? type == :tLBRACK end def left_ref_bracket? type == :tLBRACK2 end def left_bracket? %i[tLBRACK tLBRACK2].include?(type) end def right_bracket? type == :tRBRACK end def left_brace? type == :tLBRACE end def left_curly_brace? LEFT_CURLY_TYPES.include?(type) end def right_curly_brace? type == :tRCURLY end def left_parens? LEFT_PAREN_TYPES.include?(type) end def right_parens? type == :tRPAREN end def comma? type == :tCOMMA end def dot? type == :tDOT end def regexp_dots? %i[tDOT2 tDOT3].include?(type) end def rescue_modifier? type == :kRESCUE_MOD end def end? type == :kEND end def equal_sign? %i[tEQL tOP_ASGN].include?(type) end def new_line? type == :tNL end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/builder.rb
lib/rubocop/ast/builder.rb
# frozen_string_literal: true module RuboCop module AST # Common functionality between the parser and prism builder # @api private module BuilderExtensions def self.included(base) base.emit_forward_arg = true base.emit_match_pattern = true end # @api private NODE_MAP = { and: AndNode, and_asgn: AndAsgnNode, alias: AliasNode, arg: ArgNode, blockarg: ArgNode, forward_arg: ArgNode, kwarg: ArgNode, kwoptarg: ArgNode, kwrestarg: ArgNode, optarg: ArgNode, restarg: ArgNode, shadowarg: ArgNode, args: ArgsNode, array: ArrayNode, lvasgn: AsgnNode, ivasgn: AsgnNode, cvasgn: AsgnNode, gvasgn: AsgnNode, block: BlockNode, numblock: BlockNode, itblock: BlockNode, break: BreakNode, case_match: CaseMatchNode, casgn: CasgnNode, case: CaseNode, class: ClassNode, complex: ComplexNode, const: ConstNode, def: DefNode, defined?: DefinedNode, defs: DefNode, dstr: DstrNode, ensure: EnsureNode, for: ForNode, forward_args: ForwardArgsNode, forwarded_kwrestarg: KeywordSplatNode, float: FloatNode, hash: HashNode, if: IfNode, in_pattern: InPatternNode, int: IntNode, index: IndexNode, indexasgn: IndexasgnNode, irange: RangeNode, erange: RangeNode, kwargs: HashNode, kwbegin: KeywordBeginNode, kwsplat: KeywordSplatNode, lambda: LambdaNode, masgn: MasgnNode, mlhs: MlhsNode, module: ModuleNode, next: NextNode, op_asgn: OpAsgnNode, or_asgn: OrAsgnNode, or: OrNode, pair: PairNode, procarg0: Procarg0Node, rational: RationalNode, regexp: RegexpNode, rescue: RescueNode, resbody: ResbodyNode, return: ReturnNode, csend: CsendNode, send: SendNode, str: StrNode, xstr: StrNode, sclass: SelfClassNode, super: SuperNode, zsuper: SuperNode, sym: SymbolNode, until: UntilNode, until_post: UntilNode, lvar: VarNode, ivar: VarNode, cvar: VarNode, gvar: VarNode, when: WhenNode, while: WhileNode, while_post: WhileNode, yield: YieldNode }.freeze # Generates {Node} from the given information. # # @return [Node] the generated node def n(type, children, source_map) node_klass(type).new(type, children, location: source_map) end # Overwrite the base method to allow strings with invalid encoding # More details here https://github.com/whitequark/parser/issues/283 def string_value(token) value(token) end private def node_klass(type) NODE_MAP[type] || Node end end # `RuboCop::AST::Builder` is an AST builder that is utilized to let `Parser` # generate ASTs with {RuboCop::AST::Node}. # # @example # buffer = Parser::Source::Buffer.new('(string)') # buffer.source = 'puts :foo' # # builder = RuboCop::AST::Builder.new # require 'parser/ruby25' # parser = Parser::Ruby25.new(builder) # root_node = parser.parse(buffer) class Builder < Parser::Builders::Default include BuilderExtensions end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/traversal.rb
lib/rubocop/ast/traversal.rb
# frozen_string_literal: true module RuboCop module AST # Provides methods for traversing an AST. # Does not transform an AST; for that, use Parser::AST::Processor. # Override methods to perform custom processing. Remember to call `super` # if you want to recursively process descendant nodes. module Traversal # Only for debugging. # @api private class DebugError < RuntimeError end TYPE_TO_METHOD = Hash.new { |h, type| h[type] = :"on_#{type}" } def walk(node) return if node.nil? send(TYPE_TO_METHOD[node.type], node) nil end # @api private module CallbackCompiler SEND = 'send(TYPE_TO_METHOD[child.type], child)' assign_code = 'child = node.children[%<index>i]' code = "#{assign_code}\n#{SEND}" # How a particular child node should be visited. For example, if a child node # can be nil it should be guarded behind a nil check. Or, if a child node is a literal # (like a symbol) then the literal itself should not be visited. TEMPLATE = { skip: '', always: code, nil?: "#{code} if child" }.freeze def def_callback(type, *child_node_types, expected_children_count: child_node_types.size..child_node_types.size, body: self.body(child_node_types, expected_children_count)) type, *aliases = type lineno = caller_locations(1, 1).first.lineno module_eval(<<~RUBY, __FILE__, lineno) def on_#{type}(node) # def on_send(node) #{body} # # body ... nil # nil end # end RUBY aliases.each do |m| alias_method :"on_#{m}", :"on_#{type}" end end def body(child_node_types, expected_children_count) visit_children_code = child_node_types .map.with_index do |child_type, i| TEMPLATE.fetch(child_type).gsub('%<index>i', i.to_s) end .join("\n") <<~BODY #{children_count_check_code(expected_children_count)} #{visit_children_code} BODY end def children_count_check_code(range) return '' unless ENV.fetch('RUBOCOP_DEBUG', false) <<~RUBY n = node.children.size raise DebugError, [ 'Expected #{range} children, got', n, 'for', node.inspect ].join(' ') unless (#{range}).cover?(node.children.size) RUBY end end private_constant :CallbackCompiler extend CallbackCompiler send_code = CallbackCompiler::SEND ### children count == 0 no_children = %i[true false nil self cbase zsuper redo retry forward_args forwarded_args match_nil_pattern forward_arg forwarded_restarg forwarded_kwrestarg lambda empty_else kwnilarg __FILE__ __LINE__ __ENCODING__] ### children count == 0..1 opt_symbol_child = %i[restarg kwrestarg] opt_node_child = %i[splat kwsplat match_rest] ### children count == 1 literal_child = %i[int float complex rational str sym lvar ivar cvar gvar nth_ref back_ref arg blockarg shadowarg kwarg match_var] many_symbol_children = %i[regopt] node_child = %i[not match_current_line defined? arg_expr pin if_guard unless_guard match_with_trailing_comma] node_or_nil_child = %i[block_pass preexe postexe] NO_CHILD_NODES = (no_children + opt_symbol_child + literal_child).to_set.freeze private_constant :NO_CHILD_NODES # Used by Commissioner ### children count > 1 symbol_then_opt_node = %i[lvasgn ivasgn cvasgn gvasgn] symbol_then_node_or_nil = %i[optarg kwoptarg] node_then_opt_node = %i[while until module sclass] ### variable children count many_node_children = %i[dstr dsym xstr regexp array hash pair mlhs masgn or_asgn and_asgn rasgn mrasgn undef alias args super yield or and while_post until_post match_with_lvasgn begin kwbegin return in_match match_alt break next match_as array_pattern array_pattern_with_tail hash_pattern const_pattern find_pattern index indexasgn procarg0 kwargs] many_opt_node_children = %i[case rescue resbody ensure for when case_match in_pattern irange erange match_pattern match_pattern_p iflipflop eflipflop] ### Callbacks for above def_callback no_children def_callback opt_symbol_child, :skip, expected_children_count: 0..1 def_callback opt_node_child, :nil?, expected_children_count: 0..1 def_callback literal_child, :skip def_callback node_child, :always def_callback node_or_nil_child, :nil? def_callback symbol_then_opt_node, :skip, :nil?, expected_children_count: 1..2 def_callback symbol_then_node_or_nil, :skip, :nil? def_callback node_then_opt_node, :always, :nil? def_callback many_symbol_children, :skip, expected_children_count: (0..) def_callback many_node_children, body: <<~RUBY node.children.each { |child| #{send_code} } RUBY def_callback many_opt_node_children, body: <<~RUBY node.children.each { |child| #{send_code} if child } RUBY ### Other particular cases def_callback :const, :nil?, :skip def_callback :casgn, :nil?, :skip, :nil?, expected_children_count: 2..3 def_callback :class, :always, :nil?, :nil? def_callback :def, :skip, :always, :nil? def_callback :op_asgn, :always, :skip, :always def_callback :if, :always, :nil?, :nil? def_callback :block, :always, :always, :nil? def_callback :numblock, :always, :skip, :nil? def_callback :itblock, :always, :skip, :nil? def_callback :defs, :always, :skip, :always, :nil? def_callback %i[send csend], body: <<~RUBY node.children.each_with_index do |child, i| next if i == 1 #{send_code} if child end RUBY ### generic processing of any other node (forward compatibility) defined = instance_methods(false) .grep(/^on_/) .map { |s| s.to_s[3..].to_sym } # :on_foo => :foo to_define = ::Parser::Meta::NODE_TYPES.to_a to_define -= defined to_define -= %i[numargs itarg ident] # transient to_define -= %i[blockarg_expr restarg_expr] # obsolete to_define -= %i[objc_kwarg objc_restarg objc_varargs] # mac_ruby def_callback to_define, body: <<~RUBY node.children.each do |child| next unless child.class == Node #{send_code} end RUBY MISSING = to_define if ENV['RUBOCOP_DEBUG'] end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/builder_prism.rb
lib/rubocop/ast/builder_prism.rb
# frozen_string_literal: true module RuboCop module AST # A parser builder, based on the one provided by prism, # which is capable of emitting AST for more recent Rubies. class BuilderPrism < Prism::Translation::Parser::Builder include BuilderExtensions end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/masgn_node.rb
lib/rubocop/ast/node/masgn_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `masgn` nodes. # This will be used in place of a plain node when the builder constructs # the AST, making its methods available to all assignment nodes within RuboCop. class MasgnNode < Node # @return [MlhsNode] the `mlhs` node def lhs # The first child is a `mlhs` node node_parts[0] end # @return [Array<Node>] the assignment nodes of the multiple assignment def assignments lhs.assignments end # @return [Array<Symbol>] names of all the variables being assigned def names assignments.map do |assignment| if assignment.type?(:send, :indexasgn) assignment.method_name else assignment.name end end end # The RHS (right hand side) of the multiple assignment. This returns # the nodes as parsed: either a single node if the RHS has a single value, # or an `array` node containing multiple nodes. # # NOTE: Due to how parsing works, `expression` will return the same for # `a, b = x, y` and `a, b = [x, y]`. # # @return [Node] the right hand side of a multiple assignment. def expression node_parts[1] end alias rhs expression # In contrast to `expression`, `values` always returns a Ruby array # containing all the nodes being assigned on the RHS. # # Literal arrays are considered a singular value; but unlike `expression`, # implied `array` nodes from assigning multiple values on the RHS are treated # as separate. # # @return [Array<Node>] individual values being assigned on the RHS of the multiple assignment def values multiple_rhs? ? expression.children : [expression] end private def multiple_rhs? expression.array_type? && !expression.bracketed? end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/regexp_node.rb
lib/rubocop/ast/node/regexp_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `regexp` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `regexp` nodes within RuboCop. class RegexpNode < Node OPTIONS = { x: Regexp::EXTENDED, i: Regexp::IGNORECASE, m: Regexp::MULTILINE, n: Regexp::NOENCODING, u: Regexp::FIXEDENCODING, o: 0 }.freeze private_constant :OPTIONS # @return [Regexp] a regexp of this node def to_regexp Regexp.new(content, options) end # @return [RuboCop::AST::Node] a regopt node def regopt children.last end # NOTE: The 'o' option is ignored. # # @return [Integer] the Regexp option bits as returned by Regexp#options def options regopt.children.map { |opt| OPTIONS.fetch(opt) }.inject(0, :|) end # @return [String] a string of regexp content def content children.select(&:str_type?).map(&:str_content).join end # @return [Bool] if the regexp is a /.../ literal def slash_literal? loc.begin.source == '/' end # @return [Bool] if the regexp is a %r{...} literal (using any delimiters) def percent_r_literal? !slash_literal? end # @return [String] the regexp delimiters (without %r) def delimiters [loc.begin.source[-1], loc.end.source[0]] end # @return [Bool] if char is one of the delimiters def delimiter?(char) delimiters.include?(char) end # @return [Bool] if regexp contains interpolation def interpolation? children.any?(&:begin_type?) end # @return [Bool] if regexp uses the multiline regopt def multiline_mode? regopt_include?(:m) end # @return [Bool] if regexp uses the extended regopt def extended? regopt_include?(:x) end # @return [Bool] if regexp uses the ignore-case regopt def ignore_case? regopt_include?(:i) end # @return [Bool] if regexp uses the single-interpolation regopt def single_interpolation? regopt_include?(:o) end # @return [Bool] if regexp uses the no-encoding regopt def no_encoding? regopt_include?(:n) end # @return [Bool] if regexp uses the fixed-encoding regopt def fixed_encoding? regopt_include?(:u) end private def regopt_include?(option) regopt.children.include?(option) end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/next_node.rb
lib/rubocop/ast/node/next_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `next` nodes. This will be used in place of a # plain node when the builder constructs the AST, making its methods # available to all `next` nodes within RuboCop. class NextNode < Node include ParameterizedNode::WrappedArguments end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/or_node.rb
lib/rubocop/ast/node/or_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `or` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `or` nodes within RuboCop. class OrNode < Node include BinaryOperatorNode include PredicateOperatorNode # Returns the alternate operator of the `or` as a string. # Returns `or` for `||` and vice versa. # # @return [String] the alternate of the `or` operator def alternate_operator logical_operator? ? SEMANTIC_OR : LOGICAL_OR end # Returns the inverse keyword of the `or` node as a string. # Returns `and` for `or` and `&&` for `||`. # # @return [String] the inverse of the `or` operator def inverse_operator logical_operator? ? LOGICAL_AND : SEMANTIC_AND end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/for_node.rb
lib/rubocop/ast/node/for_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `for` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `for` nodes within RuboCop. class ForNode < Node # Returns the keyword of the `for` statement as a string. # # @return [String] the keyword of the `until` statement def keyword 'for' end # Checks whether the `for` node has a `do` keyword. # # @return [Boolean] whether the `for` node has a `do` keyword def do? loc_is?(:begin, 'do') end # Checks whether this node body is a void context. # Always `true` for `for`. # # @return [true] whether the `for` node body is a void context def void_context? true end # Returns the iteration variable of the `for` loop. # # @return [Node] The iteration variable of the `for` loop def variable node_parts[0] end # Returns the collection the `for` loop is iterating over. # # @return [Node] The collection the `for` loop is iterating over def collection node_parts[1] end # Returns the body of the `for` loop. # # @return [Node, nil] The body of the `for` loop. def body node_parts[2] end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/int_node.rb
lib/rubocop/ast/node/int_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `int` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available to # all `int` nodes within RuboCop. class IntNode < Node include BasicLiteralNode include NumericNode end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/when_node.rb
lib/rubocop/ast/node/when_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `when` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `when` nodes within RuboCop. class WhenNode < Node # Returns an array of all the conditions in the `when` branch. # # @return [Array<Node>] an array of condition nodes def conditions node_parts[0...-1] end # @deprecated Use `conditions.each` def each_condition(&block) return conditions.to_enum(__method__) unless block conditions.each(&block) self end # Returns the index of the `when` branch within the `case` statement. # # @return [Integer] the index of the `when` branch def branch_index parent.when_branches.index(self) end # Checks whether the `when` node has a `then` keyword. # # @return [Boolean] whether the `when` node has a `then` keyword def then? loc_is?(:begin, 'then') end # Returns the body of the `when` node. # # @return [Node, nil] the body of the `when` node def body node_parts[-1] end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/op_asgn_node.rb
lib/rubocop/ast/node/op_asgn_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `op_asgn` nodes. # This will be used in place of a plain node when the builder constructs # the AST, making its methods available to all assignment nodes within RuboCop. class OpAsgnNode < Node # @return [AsgnNode] the assignment node def assignment_node node_parts[0] end alias lhs assignment_node # The name of the variable being assigned as a symbol. # # @return [Symbol] the name of the variable being assigned def name assignment_node.call_type? ? assignment_node.method_name : assignment_node.name end # The operator being used for assignment as a symbol. # # @return [Symbol] the assignment operator def operator node_parts[1] end # The expression being assigned to the variable. # # @return [Node] the expression being assigned. def expression node_parts.last end alias rhs expression end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/while_node.rb
lib/rubocop/ast/node/while_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `while` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `while` nodes within RuboCop. class WhileNode < Node include ConditionalNode include ModifierNode # Returns the keyword of the `while` statement as a string. # # @return [String] the keyword of the `while` statement def keyword 'while' end # Returns the inverse keyword of the `while` node as a string. # Returns `until` for `while` nodes and vice versa. # # @return [String] the inverse keyword of the `while` statement def inverse_keyword 'until' end # Checks whether the `until` node has a `do` keyword. # # @return [Boolean] whether the `until` node has a `do` keyword def do? loc_is?(:begin, 'do') end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/resbody_node.rb
lib/rubocop/ast/node/resbody_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `resbody` nodes. This will be used in place of a # plain node when the builder constructs the AST, making its methods # available to all `resbody` nodes within RuboCop. class ResbodyNode < Node # Returns the body of the `rescue` clause. # # @return [Node, nil] The body of the `resbody`. def body node_parts[2] end # Returns an array of all the exceptions in the `rescue` clause. # # @return [Array<Node>] an array of exception nodes def exceptions exceptions_node = node_parts[0] if exceptions_node.nil? [] elsif exceptions_node.array_type? exceptions_node.values else [exceptions_node] end end # Returns the exception variable of the `rescue` clause. # # @return [Node, nil] The exception variable of the `resbody`. def exception_variable node_parts[1] end # Returns the index of the `resbody` branch within the exception handling statement. # # @return [Integer] the index of the `resbody` branch def branch_index parent.resbody_branches.index(self) end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/block_node.rb
lib/rubocop/ast/node/block_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `block` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `send` nodes within RuboCop. # # A `block` node is essentially a method send with a block. Parser nests # the `send` node inside the `block` node. class BlockNode < Node include MethodIdentifierPredicates IT_BLOCK_ARGUMENT = [ArgNode.new(:arg, [:it])].freeze private_constant :IT_BLOCK_ARGUMENT VOID_CONTEXT_METHODS = %i[each tap].freeze private_constant :VOID_CONTEXT_METHODS # The `send` node associated with this block. # # @return [SendNode] the `send` node associated with the `block` node def send_node node_parts[0] end # A shorthand for getting the first argument of this block. # Equivalent to `arguments.first`. # # @return [Node, nil] the first argument of this block, # or `nil` if there are no arguments def first_argument arguments[0] end # A shorthand for getting the last argument of this block. # Equivalent to `arguments.last`. # # @return [Node, nil] the last argument of this block, # or `nil` if there are no arguments def last_argument arguments[-1] end # The arguments of this block. # Note that if the block has destructured arguments, `arguments` will # return a `mlhs` node, whereas `argument_list` will return only # actual argument nodes. # # @return [Array<Node>] def arguments if block_type? node_parts[1] else [].freeze # Numblocks and itblocks have no explicit block arguments. end end # Returns a collection of all descendants of this node that are # argument type nodes. See `ArgsNode#argument_list` for details. # # @return [Array<Node>] def argument_list if numblock_type? numbered_arguments elsif itblock_type? IT_BLOCK_ARGUMENT else arguments.argument_list end end # The body of this block. # # @return [Node, nil] the body of the `block` node or `nil` def body node_parts[2] end # The name of the dispatched method as a symbol. # # @return [Symbol] the name of the dispatched method def method_name send_node.method_name end # Checks whether this block takes any arguments. # # @return [Boolean] whether this `block` node takes any arguments def arguments? !arguments.empty? end # Checks whether the `block` literal is delimited by curly braces. # # @return [Boolean] whether the `block` literal is enclosed in braces def braces? loc.end.is?('}') end # Checks whether the `block` literal is delimited by `do`-`end` keywords. # # @return [Boolean] whether the `block` literal is enclosed in `do`-`end` def keywords? loc.end.is?('end') end # The delimiters for this `block` literal. # # @return [Array<String>] the delimiters for the `block` literal def delimiters [loc.begin.source, loc.end.source].freeze end # The opening delimiter for this `block` literal. # # @return [String] the opening delimiter for the `block` literal def opening_delimiter delimiters.first end # The closing delimiter for this `block` literal. # # @return [String] the closing delimiter for the `block` literal def closing_delimiter delimiters.last end # Checks whether this is a single line block. This is overridden here # because the general version in `Node` does not work for `block` nodes. # # @return [Boolean] whether the `block` literal is on a single line def single_line? loc.begin.line == loc.end.line end # Checks whether this is a multiline block. This is overridden here # because the general version in `Node` does not work for `block` nodes. # # @return [Boolean] whether the `block` literal is on a several lines def multiline? !single_line? end # Checks whether this `block` literal belongs to a lambda. # # @return [Boolean] whether the `block` literal belongs to a lambda def lambda? send_node.method?(:lambda) end # Checks whether this node body is a void context. # # @return [Boolean] whether the `block` node body is a void context def void_context? VOID_CONTEXT_METHODS.include?(method_name) end private def numbered_arguments max_param = children[1] 1.upto(max_param).map do |i| ArgNode.new(:arg, [:"_#{i}"]) end.freeze end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/hash_node.rb
lib/rubocop/ast/node/hash_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `hash` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `hash` nodes within RuboCop. class HashNode < Node # Returns an array of all the key value pairs in the `hash` literal. # # @note this may be different from children as `kwsplat` nodes are # ignored. # # @return [Array<PairNode>] an array of `pair` nodes def pairs each_pair.to_a end # Checks whether the `hash` node contains any `pair`- or `kwsplat` nodes. # # @return[Boolean] whether the `hash` is empty def empty? children.empty? end # Calls the given block for each `pair` node in the `hash` literal. # If no block is given, an `Enumerator` is returned. # # @note `kwsplat` nodes are ignored. # # @return [self] if a block is given # @return [Enumerator] if no block is given def each_pair return each_child_node(:pair).to_enum unless block_given? each_child_node(:pair) do |pair| yield(*pair) end self end # Returns an array of all the keys in the `hash` literal. # # @note `kwsplat` nodes are ignored. # # @return [Array<Node>] an array of keys in the `hash` literal def keys each_key.to_a end # Calls the given block for each `key` node in the `hash` literal. # If no block is given, an `Enumerator` is returned. # # @note `kwsplat` nodes are ignored. # # @return [self] if a block is given # @return [Enumerator] if no block is given def each_key(&block) return pairs.map(&:key).to_enum unless block pairs.map(&:key).each(&block) self end # Returns an array of all the values in the `hash` literal. # # @note `kwsplat` nodes are ignored. # # @return [Array<Node>] an array of values in the `hash` literal def values each_pair.map(&:value) end # Calls the given block for each `value` node in the `hash` literal. # If no block is given, an `Enumerator` is returned. # # @note `kwsplat` nodes are ignored. # # @return [self] if a block is given # @return [Enumerator] if no block is given def each_value(&block) return pairs.map(&:value).to_enum unless block pairs.map(&:value).each(&block) self end # Checks whether any of the key value pairs in the `hash` literal are on # the same line. # # @note A multiline `pair` is considered to be on the same line if it # shares any of its lines with another `pair` # # @note `kwsplat` nodes are ignored. # # @return [Boolean] whether any `pair` nodes are on the same line def pairs_on_same_line? pairs.each_cons(2).any? { |first, second| first.same_line?(second) } end # Checks whether this `hash` uses a mix of hash rocket and colon # delimiters for its pairs. # # @note `kwsplat` nodes are ignored. # # @return [Boolean] whether the `hash` uses mixed delimiters def mixed_delimiters? pairs.map(&:delimiter).uniq.size > 1 end # Checks whether the `hash` literal is delimited by curly braces. # # @return [Boolean] whether the `hash` literal is enclosed in braces def braces? loc_is?(:end, '}') end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/alias_node.rb
lib/rubocop/ast/node/alias_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `alias` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `alias` nodes within RuboCop. class AliasNode < Node # Returns the old identifier as specified by the `alias`. # # @return [SymbolNode] the old identifier def old_identifier node_parts[1] end # Returns the new identifier as specified by the `alias`. # # @return [SymbolNode] the new identifier def new_identifier node_parts[0] end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/if_node.rb
lib/rubocop/ast/node/if_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `if` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `if` nodes within RuboCop. class IfNode < Node include ConditionalNode include ModifierNode # Checks whether this node is an `if` statement. (This is not true of # ternary operators and `unless` statements.) # # @return [Boolean] whether the node is an `if` statement def if? keyword == 'if' end # Checks whether this node is an `unless` statement. (This is not true # of ternary operators and `if` statements.) # # @return [Boolean] whether the node is an `unless` statement def unless? keyword == 'unless' end # Checks whether the `if` node has an `then` clause. # # @return [Boolean] whether the node has an `then` clause def then? loc_is?(:begin, 'then') end # Checks whether the `if` is an `elsif`. Parser handles these by nesting # `if` nodes in the `else` branch. # # @return [Boolean] whether the node is an `elsif` def elsif? keyword == 'elsif' end # Checks whether the `if` node has an `else` clause. # # @note This returns `true` for nodes containing an `elsif` clause. # This is legacy behavior, and many cops rely on it. # # @return [Boolean] whether the node has an `else` clause def else? loc?(:else) end # Checks whether the `if` node is a ternary operator. # # @return [Boolean] whether the `if` node is a ternary operator def ternary? loc?(:question) end # Returns the keyword of the `if` statement as a string. Returns an empty # string for ternary operators. # # @return [String] the keyword of the `if` statement def keyword ternary? ? '' : loc.keyword.source end # Returns the inverse keyword of the `if` node as a string. Returns `if` # for `unless` nodes and vice versa. Returns an empty string for ternary # operators. # # @return [String] the inverse keyword of the `if` statement def inverse_keyword case keyword when 'if' then 'unless' when 'unless' then 'if' else '' end end # Checks whether the `if` node is in a modifier form, i.e. a condition # trailing behind an expression. Only `if` and `unless` nodes without # other branches can be modifiers. # # @return [Boolean] whether the `if` node is a modifier def modifier_form? (if? || unless?) && super end # Checks whether the `if` node has nested `if` nodes in any of its # branches. # # @note This performs a shallow search. # # @return [Boolean] whether the `if` node contains nested conditionals def nested_conditional? node_parts[1..2].compact.each do |branch| branch.each_node(:if) do |nested| return true unless nested.elsif? end end false end # Checks whether the `if` node has at least one `elsif` branch. Returns # true if this `if` node itself is an `elsif`. # # @return [Boolean] whether the `if` node has at least one `elsif` branch def elsif_conditional? else_branch&.if_type? && else_branch.elsif? end # Returns the branch of the `if` node that gets evaluated when its # condition is truthy. # # @note This is normalized for `unless` nodes. # # @return [Node] the truthy branch node of the `if` node # @return [nil] if the truthy branch is empty def if_branch node_parts[1] end # Returns the branch of the `if` node that gets evaluated when its # condition is falsey. # # @note This is normalized for `unless` nodes. # # @return [Node] the falsey branch node of the `if` node # @return [nil] when there is no else branch def else_branch node_parts[2] end # Custom destructuring method. This is used to normalize the branches # for `if` and `unless` nodes, to aid comparisons and conversions. # # @return [Array<Node>] the different parts of the `if` statement def node_parts if unless? condition, false_branch, true_branch = *self else condition, true_branch, false_branch = *self end [condition, true_branch, false_branch] end # Returns an array of all the branches in the conditional statement. # # @return [Array<Node>] an array of branch nodes def branches if ternary? [if_branch, else_branch] elsif !else? [if_branch] else branches = [if_branch] other_branches = if elsif_conditional? else_branch.branches else [else_branch] end branches.concat(other_branches) end end # @deprecated Use `branches.each` def each_branch(&block) return branches.to_enum(__method__) unless block branches.each(&block) end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/indexasgn_node.rb
lib/rubocop/ast/node/indexasgn_node.rb
# frozen_string_literal: true module RuboCop module AST # Used for modern support only! # Not as thoroughly tested as legacy equivalent # # $ ruby-parse -e "foo[:bar] = :baz" # (indexasgn # (send nil :foo) # (sym :bar) # (sym :baz)) # $ ruby-parse --legacy -e "foo[:bar] = :baz" # (send # (send nil :foo) :[]= # (sym :bar) # (sym :baz)) # # The main RuboCop runs in legacy mode; this node is only used # if user `AST::Builder.modernize` or `AST::Builder.emit_index=true` class IndexasgnNode < Node include ParameterizedNode::RestArguments include MethodDispatchNode # For similarity with legacy mode def attribute_accessor? false end # For similarity with legacy mode def assignment_method? true end # For similarity with legacy mode def method_name :[]= end private # An array containing the arguments of the dispatched method. # # @return [Array<Node>] the arguments of the dispatched method def first_argument_index 1 end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/class_node.rb
lib/rubocop/ast/node/class_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `class` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `class` nodes within RuboCop. class ClassNode < Node # The identifier for this `class` node. # # @return [Node] the identifier of the class def identifier node_parts[0] end # The parent class for this `class` node. # # @return [Node, nil] the parent class of the class def parent_class node_parts[1] end # The body of this `class` node. # # @return [Node, nil] the body of the class def body node_parts[2] end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/float_node.rb
lib/rubocop/ast/node/float_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `float` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available to # all `float` nodes within RuboCop. class FloatNode < Node include BasicLiteralNode include NumericNode end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/in_pattern_node.rb
lib/rubocop/ast/node/in_pattern_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `in` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `in` nodes within RuboCop. class InPatternNode < Node # Returns a node of the pattern in the `in` branch. # # @return [Node] a pattern node def pattern node_parts.first end # Returns the index of the `in` branch within the `case` statement. # # @return [Integer] the index of the `in` branch def branch_index parent.in_pattern_branches.index(self) end # Checks whether the `in` node has a `then` keyword. # # @return [Boolean] whether the `in` node has a `then` keyword def then? loc_is?(:begin, 'then') end # Returns the body of the `in` node. # # @return [Node, nil] the body of the `in` node def body node_parts[-1] end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/rescue_node.rb
lib/rubocop/ast/node/rescue_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `rescue` nodes. This will be used in place of a # plain node when the builder constructs the AST, making its methods # available to all `rescue` nodes within RuboCop. class RescueNode < Node # Returns the body of the rescue node. # # @return [Node, nil] The body of the rescue node. def body node_parts[0] end # Returns an array of all the rescue branches in the exception handling statement. # # @return [Array<ResbodyNode>] an array of `resbody` nodes def resbody_branches node_parts[1...-1] end # Returns an array of all the rescue branches in the exception handling statement. # # @return [Array<Node, nil>] an array of the bodies of the rescue branches # and the else (if any). Note that these bodies could be nil. def branches bodies = resbody_branches.map(&:body) bodies.push(else_branch) if else? bodies end # Returns the else branch of the exception handling statement, if any. # # @return [Node] the else branch node of the exception handling statement # @return [nil] if the exception handling statement does not have an else branch. def else_branch node_parts[-1] end # Checks whether this exception handling statement has an `else` branch. # # @return [Boolean] whether the exception handling statement has an `else` branch def else? loc.else end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/ensure_node.rb
lib/rubocop/ast/node/ensure_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `ensure` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `ensure` nodes within RuboCop. class EnsureNode < Node DEPRECATION_WARNING_LOCATION_CACHE = [] # rubocop:disable Style/MutableConstant private_constant :DEPRECATION_WARNING_LOCATION_CACHE # Returns the body of the `ensure` clause. # # @return [Node, nil] The body of the `ensure`. # @deprecated Use `EnsureNode#branch` def body first_caller = caller(1..1).first unless DEPRECATION_WARNING_LOCATION_CACHE.include?(first_caller) warn '`EnsureNode#body` is deprecated and will be changed in the next major version of ' \ 'rubocop-ast. Use `EnsureNode#branch` instead to get the body of the `ensure` branch.' warn "Called from:\n#{caller.join("\n")}\n\n" DEPRECATION_WARNING_LOCATION_CACHE << first_caller end branch end # Returns an the ensure branch in the exception handling statement. # # @return [Node, nil] the body of the ensure branch. def branch node_parts[1] end # Returns the `rescue` node of the `ensure`, if present. # # @return [Node, nil] The `rescue` node. def rescue_node node_parts[0] if node_parts[0].rescue_type? end # Checks whether this node body is a void context. # Always `true` for `ensure`. # # @return [true] whether the `ensure` node body is a void context def void_context? true end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/lambda_node.rb
lib/rubocop/ast/node/lambda_node.rb
# frozen_string_literal: true module RuboCop module AST # Used for modern support only: # Not as thoroughly tested as legacy equivalent # # $ ruby-parse -e "->(foo) { bar }" # (block # (lambda) # (args # (arg :foo)) # (send nil :bar)) # $ ruby-parse --legacy -e "->(foo) { bar }" # (block # (send nil :lambda) # (args # (arg :foo)) # (send nil :bar)) # # The main RuboCop runs in legacy mode; this node is only used # if user `AST::Builder.modernize` or `AST::Builder.emit_lambda=true` class LambdaNode < Node include ParameterizedNode::RestArguments include MethodDispatchNode # For similarity with legacy mode def lambda? true end # For similarity with legacy mode def lambda_literal? true end # For similarity with legacy mode def attribute_accessor? false end # For similarity with legacy mode def assignment_method? false end # For similarity with legacy mode def receiver nil end # For similarity with legacy mode def method_name :lambda end private # For similarity with legacy mode def first_argument_index 2 end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/case_match_node.rb
lib/rubocop/ast/node/case_match_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `case_match` nodes. This will be used in place of # a plain node when the builder constructs the AST, making its methods # available to all `case_match` nodes within RuboCop. class CaseMatchNode < Node include ConditionalNode # Returns the keyword of the `case` statement as a string. # # @return [String] the keyword of the `case` statement def keyword 'case' end # @deprecated Use `in_pattern_branches.each` def each_in_pattern(&block) return in_pattern_branches.to_enum(__method__) unless block in_pattern_branches.each(&block) self end # Returns an array of all the `in` pattern branches in the `case` statement. # # @return [Array<InPatternNode>] an array of `in_pattern` nodes def in_pattern_branches node_parts[1...-1] end # Returns an array of all the when branches in the `case` statement. # # @return [Array<Node, nil>] an array of the bodies of the `in` branches # and the `else` (if any). Note that these bodies could be nil. def branches bodies = in_pattern_branches.map(&:body) if else? # `empty-else` node sets nil because it has no body. else_branch.empty_else_type? ? bodies.push(nil) : bodies.push(else_branch) end bodies end # Returns the else branch of the `case` statement, if any. # # @return [Node] the else branch node of the `case` statement # @return [EmptyElse] the empty else branch node of the `case` statement # @return [nil] if the case statement does not have an else branch. def else_branch node_parts[-1] end # Checks whether this case statement has an `else` branch. # # @return [Boolean] whether the `case` statement has an `else` branch def else? !loc.else.nil? end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/send_node.rb
lib/rubocop/ast/node/send_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `send` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `send` nodes within RuboCop. class SendNode < Node include ParameterizedNode::RestArguments include MethodDispatchNode # @!method attribute_accessor?(node = self) def_node_matcher :attribute_accessor?, <<~PATTERN [(send nil? ${:attr_reader :attr_writer :attr_accessor :attr} $...) (_ _ _ _ ...)] PATTERN def send_type? true end private def first_argument_index 2 end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/range_node.rb
lib/rubocop/ast/node/range_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `irange` and `erange` nodes. This will be used in # place of a plain node when the builder constructs the AST, making its # methods available to all `irange` and `erange` nodes within RuboCop. class RangeNode < Node def begin node_parts[0] end def end node_parts[1] end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/rational_node.rb
lib/rubocop/ast/node/rational_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `rational` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available to # all `rational` nodes within RuboCop. class RationalNode < Node include BasicLiteralNode include NumericNode end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/complex_node.rb
lib/rubocop/ast/node/complex_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `complex` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available to # all `complex` nodes within RuboCop. class ComplexNode < Node include BasicLiteralNode include NumericNode end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/or_asgn_node.rb
lib/rubocop/ast/node/or_asgn_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `op_asgn` nodes. # This will be used in place of a plain node when the builder constructs # the AST, making its methods available to all assignment nodes within RuboCop. class OrAsgnNode < OpAsgnNode # The operator being used for assignment as a symbol. # # @return [Symbol] the assignment operator def operator :'||' end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/symbol_node.rb
lib/rubocop/ast/node/symbol_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `sym` nodes. This will be used in place of a # plain node when the builder constructs the AST, making its methods # available to all `sym` nodes within RuboCop. class SymbolNode < Node include BasicLiteralNode end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/array_node.rb
lib/rubocop/ast/node/array_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `array` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `array` nodes within RuboCop. class ArrayNode < Node PERCENT_LITERAL_TYPES = { string: /\A%[wW]/, symbol: /\A%[iI]/ }.freeze private_constant :PERCENT_LITERAL_TYPES # Returns an array of all value nodes in the `array` literal. # # @return [Array<Node>] an array of value nodes alias values children # Calls the given block for each `value` node in the `array` literal. # If no block is given, an `Enumerator` is returned. # # @return [self] if a block is given # @return [Enumerator] if no block is given def each_value(&block) return to_enum(__method__) unless block values.each(&block) self end # Checks whether the `array` literal is delimited by square brackets. # # @return [Boolean] whether the array is enclosed in square brackets def square_brackets? loc_is?(:begin, '[') end # Checks whether the `array` literal is delimited by percent brackets. # # @overload percent_literal? # Check for any percent literal. # # @overload percent_literal?(type) # Check for percent literal of type `type`. # # @param type [Symbol] an optional percent literal type # # @return [Boolean] whether the array is enclosed in percent brackets def percent_literal?(type = nil) if type loc.begin&.source&.match?(PERCENT_LITERAL_TYPES.fetch(type)) else loc.begin&.source&.start_with?('%') end end # Checks whether the `array` literal is delimited by either percent or # square brackets # # @return [Boolean] whether the array is enclosed in percent or square # brackets def bracketed? square_brackets? || percent_literal? end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mlhs_node.rb
lib/rubocop/ast/node/mlhs_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `mlhs` nodes. # This will be used in place of a plain node when the builder constructs # the AST, making its methods available to all assignment nodes within RuboCop. class MlhsNode < Node # Returns all the assignment nodes on the left hand side (LHS) of a multiple assignment. # These are generally assignment nodes (`lvasgn`, `ivasgn`, `cvasgn`, `gvasgn`, `casgn`) # but can also be `send` nodes in case of `foo.bar, ... =` or `foo[:bar], ... =`, # or a `splat` node for `*, ... =`. # # @return [Array<Node>] the assignment nodes of the multiple assignment LHS def assignments child_nodes.flat_map do |node| if node.splat_type? # Anonymous splats have no children node.child_nodes.first || node elsif node.mlhs_type? node.assignments else node end end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/defined_node.rb
lib/rubocop/ast/node/defined_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `defined?` nodes. This will be used in place of a # plain node when the builder constructs the AST, making its methods # available to all `send` nodes within RuboCop. class DefinedNode < Node include ParameterizedNode include MethodDispatchNode def node_parts [nil, :defined?, *to_a] end alias arguments children end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/pair_node.rb
lib/rubocop/ast/node/pair_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `pair` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `pair` nodes within RuboCop. class PairNode < Node include HashElementNode HASH_ROCKET = '=>' private_constant :HASH_ROCKET SPACED_HASH_ROCKET = ' => ' private_constant :SPACED_HASH_ROCKET COLON = ':' private_constant :COLON SPACED_COLON = ': ' private_constant :SPACED_COLON # Checks whether the `pair` uses a hash rocket delimiter. # # @return [Boolean] whether this `pair` uses a hash rocket delimiter def hash_rocket? loc.operator.is?(HASH_ROCKET) end # Checks whether the `pair` uses a colon delimiter. # # @return [Boolean] whether this `pair` uses a colon delimiter def colon? loc.operator.is?(COLON) end # Returns the delimiter of the `pair` as a string. Returns `=>` for a # colon delimited `pair` and `:` for a hash rocket delimited `pair`. # # @param [Boolean] with_spacing whether to include spacing # @return [String] the delimiter of the `pair` def delimiter(*deprecated, with_spacing: deprecated.first) if with_spacing hash_rocket? ? SPACED_HASH_ROCKET : SPACED_COLON else hash_rocket? ? HASH_ROCKET : COLON end end # Returns the inverse delimiter of the `pair` as a string. # # @param [Boolean] with_spacing whether to include spacing # @return [String] the inverse delimiter of the `pair` def inverse_delimiter(*deprecated, with_spacing: deprecated.first) if with_spacing hash_rocket? ? SPACED_COLON : SPACED_HASH_ROCKET else hash_rocket? ? COLON : HASH_ROCKET end end # Checks whether the value starts on its own line. # # @return [Boolean] whether the value in the `pair` starts its own line def value_on_new_line? key.loc.line != value.loc.line end # Checks whether the `pair` uses hash value omission. # # @return [Boolean] whether this `pair` uses hash value omission def value_omission? source.end_with?(':') end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/yield_node.rb
lib/rubocop/ast/node/yield_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `yield` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `yield` nodes within RuboCop. class YieldNode < Node include ParameterizedNode include MethodDispatchNode # Custom destructuring method. This can be used to normalize # destructuring for different variations of the node. # # @return [Array] the different parts of the `send` node def node_parts [nil, :yield, *to_a] end alias arguments children end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/asgn_node.rb
lib/rubocop/ast/node/asgn_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `lvasgn`, `ivasgn`, `cvasgn`, and `gvasgn` nodes. # This will be used in place of a plain node when the builder constructs # the AST, making its methods available to all assignment nodes within RuboCop. class AsgnNode < Node # The name of the variable being assigned as a symbol. # # @return [Symbol] the name of the variable being assigned def name node_parts[0] end alias lhs name # The expression being assigned to the variable. # # @return [Node] the expression being assigned. def expression node_parts[1] end alias rhs expression end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/def_node.rb
lib/rubocop/ast/node/def_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `def` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `def` nodes within RuboCop. class DefNode < Node include ParameterizedNode include MethodIdentifierPredicates # Checks whether this node body is a void context. # # @return [Boolean] whether the `def` node body is a void context def void_context? (def_type? && method?(:initialize)) || assignment_method? end # Checks whether this method definition node forwards its arguments # as per the feature added in Ruby 2.7. # # @note This is written in a way that may support lead arguments # which are rumored to be added in a later version of Ruby. # # @return [Boolean] whether the `def` node uses argument forwarding def argument_forwarding? arguments.any?(&:forward_args_type?) || arguments.any?(&:forward_arg_type?) end # The name of the defined method as a symbol. # # @return [Symbol] the name of the defined method def method_name children[-3] end # An array containing the arguments of the method definition. # # @return [Array<Node>] the arguments of the method definition def arguments children[-2] end # The body of the method definition. # # @note this can be either a `begin` node, if the method body contains # multiple expressions, or any other node, if it contains a single # expression. # # @return [Node] the body of the method definition def body children[-1] end # The receiver of the method definition, if any. # # @return [Node, nil] the receiver of the method definition, or `nil`. def receiver children[-4] end # @return [Boolean] if the definition is without an `end` or not. def endless? !loc.end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/module_node.rb
lib/rubocop/ast/node/module_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `module` nodes. This will be used in place of a # plain node when the builder constructs the AST, making its methods # available to all `module` nodes within RuboCop. class ModuleNode < Node # The identifier for this `module` node. # # @return [Node] the identifier of the module def identifier node_parts[0] end # The body of this `module` node. # # @return [Node, nil] the body of the module def body node_parts[1] end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/return_node.rb
lib/rubocop/ast/node/return_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `return` nodes. This will be used in place of a # plain node when the builder constructs the AST, making its methods # available to all `return` nodes within RuboCop. class ReturnNode < Node include ParameterizedNode::WrappedArguments end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/forward_args_node.rb
lib/rubocop/ast/node/forward_args_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `forward-args` nodes. This will be used in place # of a plain node when the builder constructs the AST, making its methods # available to all `forward-args` nodes within RuboCop. # # Not used with modern emitters: # # $ ruby-parse -e "def foo(...); end" # (def :foo # (args # (forward-arg)) nil) # $ ruby-parse --legacy -e "->(foo) { bar }" # (def :foo # (forward-args) nil) # # Note the extra 's' with legacy form. # # The main RuboCop runs in legacy mode; this node is only used # if user `AST::Builder.modernize` or `AST::Builder.emit_lambda=true` class ForwardArgsNode < Node include CollectionNode # Node wraps itself in an array to be compatible with other # enumerable argument types. def to_a [self] end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false