Skip to content

Commit b7336e8

Browse files
eregonEarlopain
andcommitted
Handle line continuations for Ripper :on_sp events
Co-authored-by: Earlopain <[email protected]>
1 parent 782bdcc commit b7336e8

File tree

1 file changed

+42
-10
lines changed

1 file changed

+42
-10
lines changed

lib/prism/lex_compat.rb

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -874,18 +874,50 @@ def add_on_sp_tokens(tokens)
874874
line, column = token.location
875875
start_offset = @source.line_to_byte_offset(line) + column
876876
if start_offset > prev_token_end
877-
new_tokens << IgnoreStateToken.new([
878-
[
879-
@source.line(prev_token_end),
880-
@source.column(prev_token_end),
881-
],
882-
:on_sp,
883-
@source.slice(prev_token_end, start_offset - prev_token_end),
884-
prev_token_state
885-
])
877+
sp_value = @source.slice(prev_token_end, start_offset - prev_token_end)
878+
sp_line = @source.line(prev_token_end)
879+
sp_column = @source.column(prev_token_end)
880+
continuation_index = sp_value.byteindex("\\")
881+
882+
# ripper emits up to three :on_sp tokens when line continuations are used
883+
if continuation_index
884+
next_whitespace_index = continuation_index + 1
885+
next_whitespace_index += 1 if sp_value.byteslice(next_whitespace_index) == "\r"
886+
first_whitespace = sp_value[0...continuation_index]
887+
continuation = sp_value[continuation_index..next_whitespace_index]
888+
second_whitespace = sp_value[next_whitespace_index+1..]
889+
890+
new_tokens << IgnoreStateToken.new([
891+
[sp_line, sp_column],
892+
:on_sp,
893+
first_whitespace,
894+
prev_token_state
895+
]) if first_whitespace != ""
896+
897+
new_tokens << IgnoreStateToken.new([
898+
[sp_line, sp_column + continuation_index],
899+
:on_sp,
900+
continuation,
901+
prev_token_state
902+
])
903+
904+
new_tokens << IgnoreStateToken.new([
905+
[sp_line + 1, 0],
906+
:on_sp,
907+
second_whitespace,
908+
prev_token_state
909+
]) if second_whitespace != ""
910+
else
911+
new_tokens << IgnoreStateToken.new([
912+
[sp_line, sp_column],
913+
:on_sp,
914+
sp_value,
915+
prev_token_state
916+
])
917+
end
886918
end
887-
new_tokens << token
888919

920+
new_tokens << token
889921
prev_token_state = token.state
890922
prev_token_end = start_offset + token.value.bytesize
891923
end

0 commit comments

Comments
 (0)