Skip to content

Handle invalid byte sequences in UTF-8 #262

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

Merged
merged 1 commit into from
Jan 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions lib/syntax_tree/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1103,6 +1103,7 @@ def on_command_call(receiver, operator, message, arguments)
# :call-seq:
# on_comment: (String value) -> Comment
def on_comment(value)
# char is the index of the # character in the source.
char = char_pos
location =
Location.token(
Expand All @@ -1112,8 +1113,24 @@ def on_comment(value)
size: value.size - 1
)

index = source.rindex(/[^\t ]/, char - 1) if char != 0
inline = index && (source[index] != "\n")
# Loop backward in the source string, starting from the beginning of the
# comment, and find the first character that is not a space or a tab. If
# index is -1, this indicates that we've checked all of the characters
# back to the start of the source, so this comment must be at the
# beginning of the file.
#
# We are purposefully not using rindex or regular expressions here because
# they check if there are invalid characters, which is actually possible
# with the use of __END__ syntax.
index = char - 1
while index > -1 && (source[index] == "\t" || source[index] == " ")
index -= 1
end

# If we found a character that was not a space or a tab before the comment
# and it's a newline, then this comment is inline. Otherwise, it stands on
# its own and can be attached as its own node in the tree.
inline = index != -1 && source[index] != "\n"
comment =
Comment.new(value: value.chomp, inline: inline, location: location)

Expand Down
9 changes: 9 additions & 0 deletions test/parser_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,5 +65,14 @@ def foo
end
RUBY
end

def test_does_not_choke_on_invalid_characters_in_source_string
SyntaxTree.parse(<<~RUBY)
# comment
# comment
__END__
\xC5
RUBY
end
end
end