Skip to content

Commit 304dd78

Browse files
committed
Fix lex_compat for <<HEREDOC # comment at EOF
Fixes #1874
1 parent ec2faa9 commit 304dd78

File tree

3 files changed

+36
-8
lines changed

3 files changed

+36
-8
lines changed

lib/prism/lex_compat.rb

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -729,16 +729,31 @@ def result
729729
# comment and there is still whitespace after the comment, then
730730
# Ripper will append a on_nl token (even though there isn't
731731
# necessarily a newline). We mirror that here.
732-
start_offset = previous_token.location.end_offset
733-
end_offset = token.location.start_offset
734-
735-
if previous_token.type == :COMMENT && start_offset < end_offset
736-
if bom
737-
start_offset += 3
738-
end_offset += 3
732+
if previous_token.type == :COMMENT
733+
# If the token before the comment was a heredoc end, then
734+
# the comment's end_offset is before the heredoc end token.
735+
# This is not the correct offset to use for figuring out if
736+
# there is trailing whitespace after the comment.
737+
# Use the end_offset of the heredoc end instead.
738+
before_comment = result_value[index - 2]
739+
before_comment &&= before_comment[0]
740+
741+
if before_comment&.type == :HEREDOC_END
742+
start_offset = before_comment.location.end_offset
743+
else
744+
start_offset = previous_token.location.end_offset
739745
end
740746

741-
tokens << Token.new([[lineno, 0], :on_nl, source.byteslice(start_offset...end_offset), lex_state])
747+
end_offset = token.location.start_offset
748+
749+
if start_offset < end_offset
750+
if bom
751+
start_offset += 3
752+
end_offset += 3
753+
end
754+
755+
tokens << Token.new([[lineno, 0], :on_nl, source.byteslice(start_offset...end_offset), lex_state])
756+
end
742757
end
743758

744759
Token.new([[lineno, column], event, value, lex_state])
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
<<-TARGET # comment
2+
TARGET

test/prism/snapshots/heredoc_with_comment_at_start.txt

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)