Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix StrNode#last_line and StrNode#line_count for heredocs #40

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### Bug fixes

* [#40](https://github.com/rubocop-hq/rubocop-ast/pull/40): Fix `StrNode#last_line` and `StrNode#line_count` for heredocs. ([@fatkodima][])

## 1.3.0 (2020-11-30)

### Changes
Expand Down
12 changes: 12 additions & 0 deletions lib/rubocop/ast/node/str_node.rb
Expand Up @@ -11,6 +11,18 @@ class StrNode < Node
def heredoc?
loc.is_a?(Parser::Source::Map::Heredoc)
end

def last_line
if heredoc?
loc.heredoc_end.line
else
super
end
end

def line_count
last_line - first_line + 1
end
end
end
end
69 changes: 69 additions & 0 deletions spec/rubocop/ast/str_node_spec.rb
Expand Up @@ -56,4 +56,73 @@
it { is_expected.to be_heredoc }
end
end

describe '#first_line' do
context 'with a normal string' do
let(:source) { "'foo'" }

it { expect(str_node.first_line).to eq(1) }
end

context 'with a heredoc' do
let(:source) do
<<~RUBY
<<-CODE
foo
bar
CODE
RUBY
end

it { expect(str_node.first_line).to eq(1) }
end
end

describe '#last_line' do
context 'with a normal string' do
let(:source) do
['"foo"\\',
'"bar"'].join("\n")
end

it { expect(str_node.last_line).to eq(2) }
end

context 'with a heredoc' do
let(:source) do
<<~RUBY
<<-CODE
foo
bar
CODE
RUBY
end

it { expect(str_node.last_line).to eq(4) }
end
end

describe '#line_count' do
context 'with a normal string' do
let(:source) do
['"foo"\\',
'"bar"'].join("\n")
end

it { expect(str_node.line_count).to eq(2) }
end

context 'with a heredoc' do
let(:source) do
<<~RUBY
<<-CODE
foo
bar
CODE
RUBY
end

it { expect(str_node.line_count).to eq(4) }
end
end
end