diff --git a/changelog/new_add_nodestring_literal_to_match_str_and.md b/changelog/new_add_nodestring_literal_to_match_str_and.md new file mode 100644 index 000000000..96b4ddc2e --- /dev/null +++ b/changelog/new_add_nodestring_literal_to_match_str_and.md @@ -0,0 +1 @@ +* [#328](https://github.com/rubocop/rubocop-ast/pull/328): Add `Node#string_type?` to match `str` and `dstr` types. ([@dvandersluis][]) diff --git a/lib/rubocop/ast/node.rb b/lib/rubocop/ast/node.rb index 98e175465..6352cd9d4 100644 --- a/lib/rubocop/ast/node.rb +++ b/lib/rubocop/ast/node.rb @@ -41,6 +41,8 @@ class Node < Parser::AST::Node # rubocop:disable Metrics/ClassLength # @api private BASIC_LITERALS = (LITERALS - COMPOSITE_LITERALS).freeze # @api private + STRING_LITERALS = %i[str dstr].freeze + # @api private MUTABLE_LITERALS = %i[str dstr xstr array hash regexp irange erange].to_set.freeze # @api private @@ -108,6 +110,9 @@ class Node < Parser::AST::Node # rubocop:disable Metrics/ClassLength rational: :numeric, complex: :numeric, + str: :string, + dstr: :string, + irange: :range, erange: :range, @@ -520,6 +525,10 @@ def boolean_type? GROUP_FOR_TYPE[type] == :boolean end + def string_type? + GROUP_FOR_TYPE[type] == :string + end + def numeric_type? GROUP_FOR_TYPE[type] == :numeric end diff --git a/spec/rubocop/ast/node_spec.rb b/spec/rubocop/ast/node_spec.rb index 96a795078..9b66630d9 100644 --- a/spec/rubocop/ast/node_spec.rb +++ b/spec/rubocop/ast/node_spec.rb @@ -855,6 +855,40 @@ class << expr end end + describe '#string_type?' do + context 'when string literal' do + let(:src) { "'foo'" } + + it 'is true' do + expect(node).to be_string_type + end + end + + context 'when interpolated string' do + let(:src) { %q("foo #{bar}") } + + it 'is true' do + expect(node).to be_string_type + end + end + + context 'when `xstr` node' do + let(:src) { '`ls`' } + + it 'is false' do + expect(node).not_to be_string_type + end + end + + context 'when numeric literal' do + let(:src) { '42' } + + it 'is false' do + expect(node).not_to be_string_type + end + end + end + describe '#numeric_type?' do context 'when integer literal' do let(:src) { '42' } @@ -899,7 +933,7 @@ class << expr context 'when string literal' do let(:src) { '"42"' } - it 'is true' do + it 'is false' do expect(node).not_to be_numeric_type end end