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..f5e503f39 --- /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_literal?` to match `str` and `dstr` and `Node#string_type?` to match `str`, `dstr` and `xstr` types. ([@dvandersluis][]) diff --git a/lib/rubocop/ast/node.rb b/lib/rubocop/ast/node.rb index dae3ac078..3c3881750 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 @@ -385,6 +387,10 @@ def basic_literal? BASIC_LITERALS.include?(type) end + def string_literal? + STRING_LITERALS.include?(type) + end + def truthy_literal? TRUTHY_LITERALS.include?(type) end @@ -483,6 +489,10 @@ def boolean_type? true_type? || false_type? end + def string_type? + str_type? || dstr_type? || xstr_type? + end + def numeric_type? int_type? || float_type? || rational_type? || complex_type? end diff --git a/spec/rubocop/ast/node_spec.rb b/spec/rubocop/ast/node_spec.rb index 2b7d43b12..2ed7b3fd9 100644 --- a/spec/rubocop/ast/node_spec.rb +++ b/spec/rubocop/ast/node_spec.rb @@ -855,6 +855,74 @@ class << expr end end + describe '#string_literal?' do + context 'when string literal' do + let(:src) { "'foo'" } + + it 'is true' do + expect(node).to be_string_literal + end + end + + context 'when interpolated string' do + let(:src) { %q("foo #{bar}") } + + it 'is true' do + expect(node).to be_string_literal + end + end + + context 'when `xstr` node' do + let(:src) { '`ls`' } + + it 'is true' do + expect(node).not_to be_string_literal + end + end + + context 'when numeric literal' do + let(:src) { '42' } + + it 'is false' do + expect(node).not_to be_string_literal + end + 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 true' do + expect(node).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 +967,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