From 65cb09bb72e8402b42b809513d3a490818f2e9bc Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Fri, 21 Oct 2022 15:43:48 +0900 Subject: [PATCH] Add `character_literal?` to `StrNode` This PR adds `character_literal?` to `StrNode`. `...begin.is?('?')` used in https://github.com/rubocop/rubocop/pull/11095 and `Style/CharacterLiteral` can be rewritten by `node.character_literal?`. --- .../new_add_character_literal_to_str_node.md | 1 + lib/rubocop/ast/node/str_node.rb | 4 +++ spec/rubocop/ast/str_node_spec.rb | 27 +++++++++++++++++++ 3 files changed, 32 insertions(+) create mode 100644 changelog/new_add_character_literal_to_str_node.md diff --git a/changelog/new_add_character_literal_to_str_node.md b/changelog/new_add_character_literal_to_str_node.md new file mode 100644 index 000000000..bf8164e6b --- /dev/null +++ b/changelog/new_add_character_literal_to_str_node.md @@ -0,0 +1 @@ +* [#242](https://github.com/rubocop/rubocop-ast/pull/242): Add `character_literal?` to `StrNode`. ([@koic][]) diff --git a/lib/rubocop/ast/node/str_node.rb b/lib/rubocop/ast/node/str_node.rb index 37b95bd73..13ee2b2c4 100644 --- a/lib/rubocop/ast/node/str_node.rb +++ b/lib/rubocop/ast/node/str_node.rb @@ -8,6 +8,10 @@ module AST class StrNode < Node include BasicLiteralNode + def character_literal? + loc.respond_to?(:begin) && loc.begin && loc.begin.is?('?') + end + def heredoc? loc.is_a?(Parser::Source::Map::Heredoc) end diff --git a/spec/rubocop/ast/str_node_spec.rb b/spec/rubocop/ast/str_node_spec.rb index 4a1f6e6b5..9be2ff23a 100644 --- a/spec/rubocop/ast/str_node_spec.rb +++ b/spec/rubocop/ast/str_node_spec.rb @@ -30,6 +30,33 @@ end end + describe '#character_literal?' do + context 'with a character literal' do + let(:source) { '?\n' } + + it { is_expected.to be_character_literal } + end + + context 'with a normal string literal' do + let(:source) { '"\n"' } + + it { is_expected.not_to be_character_literal } + end + + context 'with a heredoc' do + let(:source) do + <<~RUBY + <<-CODE + foo + bar + CODE + RUBY + end + + it { is_expected.not_to be_character_literal } + end + end + describe '#heredoc?' do context 'with a normal string' do let(:source) { "'foo'" }