diff --git a/src/errors_format.c b/src/errors_format.c index 16b2edecd8..2c15153c1d 100644 --- a/src/errors_format.c +++ b/src/errors_format.c @@ -37,7 +37,8 @@ lines_are_utf8(const pm_parser_t *parser, size_t start_index, size_t end_index) typedef struct { pm_diagnostic_t *diagnostic; - int32_t line_start; + /* Zero-based line indices preserve source order across line-number wraparound. */ + uint32_t line_index; uint32_t column_start; uint32_t column_end; size_t idx; @@ -48,8 +49,8 @@ pm_rich_error_compare(const void *a, const void *b) { const pm_rich_error_t *left = (const pm_rich_error_t *) a; const pm_rich_error_t *right = (const pm_rich_error_t *) b; - if (left->line_start != right->line_start) { - return (left->line_start < right->line_start) ? -1 : 1; + if (left->line_index != right->line_index) { + return (left->line_index < right->line_index) ? -1 : 1; } if (left->column_start != right->column_start) { @@ -64,15 +65,15 @@ pm_rich_error_compare(const void *a, const void *b) { } /** - * Return the number of the last line of the source that can be displayed. When + * Return the zero-based index of the last line of the source that can be displayed. When * the source ends with a newline, the empty line after it is not displayed. */ -static int32_t +static uint32_t pm_rich_errors_final_line(const pm_parser_t *parser) { const pm_line_offset_list_t *line_offsets = &parser->line_offsets; - int32_t final_line = parser->start_line + ((int32_t) line_offsets->size) - 1; + uint32_t final_line = (uint32_t) (line_offsets->size - 1); - if ((parser->start + line_offsets->offsets[line_offsets->size - 1]) == parser->end) { + if (final_line > 0 && (parser->start + line_offsets->offsets[final_line]) == parser->end) { final_line--; } @@ -86,9 +87,9 @@ pm_rich_errors_final_line(const pm_parser_t *parser) { * empty line after a trailing newline. */ static void -pm_rich_error_context(int32_t line, int32_t start_line, int32_t final_line, int32_t *first, int32_t *last) { - *first = (line - start_line > 2) ? (line - 2) : start_line; - *last = (final_line - line > 2) ? (line + 2) : final_line; +pm_rich_error_context(uint32_t line, uint32_t final_line, uint32_t *first, uint32_t *last) { + *first = (line > 2) ? (line - 2) : 0; + *last = (final_line > line && final_line - line > 2) ? (line + 2) : final_line; if (*last < line) *last = line; } @@ -101,7 +102,7 @@ pm_rich_error_context(int32_t line, int32_t start_line, int32_t final_line, int3 */ static bool rich_errors_are_utf8(const pm_parser_t *parser, size_t nerrors, const pm_rich_error_t *rich_errors) { - int32_t final_line = pm_rich_errors_final_line(parser); + uint32_t final_line = pm_rich_errors_final_line(parser); /* Every line from the first line of context of the most recently visited * error up to (but not including) this index has already been checked. @@ -111,12 +112,12 @@ rich_errors_are_utf8(const pm_parser_t *parser, size_t nerrors, const pm_rich_er size_t checked_index = 0; for (size_t idx = 0; idx < nerrors; idx++) { - int32_t first_line; - int32_t last_line; - pm_rich_error_context(rich_errors[idx].line_start, parser->start_line, final_line, &first_line, &last_line); + uint32_t first_line; + uint32_t last_line; + pm_rich_error_context(rich_errors[idx].line_index, final_line, &first_line, &last_line); - size_t start_index = (size_t) (first_line - parser->start_line); - size_t end_index = (size_t) (last_line - parser->start_line); + size_t start_index = (size_t) first_line; + size_t end_index = (size_t) last_line; if (start_index < checked_index) start_index = checked_index; if (start_index > end_index) continue; @@ -189,14 +190,18 @@ pm_error_append_line_number(pm_buffer_t *buffer, int32_t line, uint8_t width) { /** * Initialize the given line format struct based on whether or not to highlight - * the line and the first and last line numbers that will be displayed. Every - * line number in between is no wider than one of these two. + * the line and the first and last line indices that will be displayed. The + * widest number is at an endpoint or at the signed 32-bit wraparound. */ static void -pm_error_line_format_init(pm_error_line_format_t *format, pm_errors_format_type_t format_type, int32_t first_line, int32_t last_line) { +pm_error_line_format_init(pm_error_line_format_t *format, pm_errors_format_type_t format_type, const pm_parser_t *parser, uint32_t first_line, uint32_t last_line) { char digits[11]; - uint8_t first_width = pm_error_line_digits(first_line, digits); - uint8_t last_width = pm_error_line_digits(last_line, digits); + uint8_t first_width = pm_error_line_digits(pm_line_offset_list_line_number(first_line, parser->start_line), digits); + uint8_t last_width = pm_error_line_digits(pm_line_offset_list_line_number(last_line, parser->start_line), digits); + + /* The range may cross the signed 32-bit display boundary. */ + uint32_t wrap_index = (uint32_t) INT32_MAX - (uint32_t) parser->start_line; + if (first_line <= wrap_index && last_line > wrap_index) last_width = 11; *format = (pm_error_line_format_t) { .type = format_type, @@ -271,11 +276,8 @@ pm_error_advance_columns(const pm_parser_t *parser, const uint8_t *start, size_t } static void -pm_error_format_line(const pm_parser_t *parser, pm_buffer_t *buffer, const pm_error_line_format_t *format, int32_t line, uint32_t column_start, uint32_t column_end) { - int32_t line_delta = line - parser->start_line; - PRISM_ASSERT(line_delta >= 0); - - size_t index = (size_t) line_delta; +pm_error_format_line(const pm_parser_t *parser, pm_buffer_t *buffer, const pm_error_line_format_t *format, uint32_t line, uint32_t column_start, uint32_t column_end) { + size_t index = line; PRISM_ASSERT(index < parser->line_offsets.size); const uint8_t *start = parser->start + parser->line_offsets.offsets[index]; @@ -287,7 +289,7 @@ pm_error_format_line(const pm_parser_t *parser, pm_buffer_t *buffer, const pm_er end = parser->start + parser->line_offsets.offsets[index + 1]; } - pm_error_line_format_number(format, buffer, line); + pm_error_line_format_number(format, buffer, pm_line_offset_list_line_number(line, parser->start_line)); /* Here we determine if we should truncate the start of the line. The * column is the start of a diagnostic, so it is on a character boundary. */ @@ -339,25 +341,25 @@ pm_error_format_line(const pm_parser_t *parser, pm_buffer_t *buffer, const pm_er * as a window so that a long line does not dominate the output. */ static void -pm_error_format_context_line(const pm_parser_t *parser, pm_buffer_t *buffer, const pm_error_line_format_t *format, int32_t line) { +pm_error_format_context_line(const pm_parser_t *parser, pm_buffer_t *buffer, const pm_error_line_format_t *format, uint32_t line) { PM_BUFFER_APPEND_LITERAL(buffer, " "); pm_error_format_line(parser, buffer, format, line, 0, WINDOW); } static void pm_rich_errors_format(const pm_parser_t *parser, pm_buffer_t *buffer, pm_errors_format_type_t format_type, size_t nerrors, pm_rich_error_t *rich_errors, bool inline_messages) { - int32_t final_line = pm_rich_errors_final_line(parser); + uint32_t final_line = pm_rich_errors_final_line(parser); /* The line numbers that are displayed range from the first line of context * of the first error to the last line of context of the last error. */ - int32_t first_displayed_line; - int32_t last_displayed_line; - int32_t unused_line; - pm_rich_error_context(rich_errors[0].line_start, parser->start_line, final_line, &first_displayed_line, &unused_line); - pm_rich_error_context(rich_errors[nerrors - 1].line_start, parser->start_line, final_line, &unused_line, &last_displayed_line); + uint32_t first_displayed_line; + uint32_t last_displayed_line; + uint32_t unused_line; + pm_rich_error_context(rich_errors[0].line_index, final_line, &first_displayed_line, &unused_line); + pm_rich_error_context(rich_errors[nerrors - 1].line_index, final_line, &unused_line, &last_displayed_line); pm_error_line_format_t format; - pm_error_line_format_init(&format, format_type, first_displayed_line, last_displayed_line); + pm_error_line_format_init(&format, format_type, parser, first_displayed_line, last_displayed_line); /* We are going to iterate through every error in our error list and display * it. While we are iterating, we will display some padding lines of the @@ -370,7 +372,7 @@ pm_rich_errors_format(const pm_parser_t *parser, pm_buffer_t *buffer, pm_errors_ * it are padded relative to the start of that slice and cut off at its * end. This bounds the length of every marker line, so the output grows * linearly with the number of errors no matter how long the line is. */ - int32_t last_line = parser->start_line - 1; + uint32_t last_line = 0; uint32_t window_column_start = 0; uint32_t window_column_end = 0; size_t window_end_idx = 0; @@ -380,16 +382,17 @@ pm_rich_errors_format(const pm_parser_t *parser, pm_buffer_t *buffer, pm_errors_ /* Here we determine how many lines of padding of the source to display, * based on the difference from the last line that was displayed. */ - if (rich_error->line_start - last_line > 1) { - if (rich_error->line_start - last_line > 2) { - if ((idx != 0) && (rich_error->line_start - last_line > 3)) { - pm_error_line_format_divider(&format, buffer); - } - - pm_error_format_context_line(parser, buffer, &format, rich_error->line_start - 2); + uint32_t first_context = (rich_error->line_index > 2) ? (rich_error->line_index - 2) : 0; + if (idx != 0) { + if (rich_error->line_index > last_line && rich_error->line_index - last_line > 3) { + pm_error_line_format_divider(&format, buffer); } + if (last_line >= rich_error->line_index) first_context = rich_error->line_index; + else if (first_context <= last_line) first_context = last_line + 1; + } - pm_error_format_context_line(parser, buffer, &format, rich_error->line_start - 1); + for (uint32_t line = first_context; line < rich_error->line_index; line++) { + pm_error_format_context_line(parser, buffer, &format, line); } /* If this error is not in the current window (because it is the first @@ -418,15 +421,15 @@ pm_rich_errors_format(const pm_parser_t *parser, pm_buffer_t *buffer, pm_errors_ window_column_end = rich_error->column_end; for (window_end_idx = idx + 1; window_end_idx < nerrors; window_end_idx++) { const pm_rich_error_t *next_error = &rich_errors[window_end_idx]; - if ((next_error->line_start != rich_error->line_start) || (next_error->column_start >= window_limit)) break; + if ((next_error->line_index != rich_error->line_index) || (next_error->column_start >= window_limit)) break; if (next_error->column_end > window_column_end) window_column_end = next_error->column_end; } if (window_column_end > window_limit) window_column_end = window_limit; - pm_error_format_line(parser, buffer, &format, rich_error->line_start, rich_error->column_start, window_column_end); + pm_error_format_line(parser, buffer, &format, rich_error->line_index, rich_error->column_start, window_column_end); } - const uint8_t *start = parser->start + parser->line_offsets.offsets[rich_error->line_start - parser->start_line]; + const uint8_t *start = parser->start + parser->line_offsets.offsets[rich_error->line_index]; if (start == parser->end) pm_buffer_append_byte(buffer, '\n'); /* Now we will display the actual error message. We will do this by @@ -482,16 +485,15 @@ pm_rich_errors_format(const pm_parser_t *parser, pm_buffer_t *buffer, pm_errors_ /* Here we determine how many lines of padding to display after the * diagnostic, depending on where the next diagnostic is in source. The - * line after the last error is one past the last line that can be - * displayed. */ - last_line = rich_error->line_start; - int32_t next_line = (idx == nerrors - 1) ? (final_line + 1) : rich_errors[idx + 1].line_start; - - if (next_line - last_line > 1) { - pm_error_format_context_line(parser, buffer, &format, ++last_line); + * context after the last error is limited to the source. */ + last_line = rich_error->line_index; + uint32_t last_context = final_line; + if (idx + 1 < nerrors) { + uint32_t next_line = rich_errors[idx + 1].line_index; + last_context = (next_line > last_line) ? next_line - 1 : last_line; } - if (next_line - last_line > 1) { + for (uint32_t count = 0; count < 2 && last_line < last_context; count++) { pm_error_format_context_line(parser, buffer, &format, ++last_line); } } @@ -500,14 +502,14 @@ pm_rich_errors_format(const pm_parser_t *parser, pm_buffer_t *buffer, pm_errors_ static void pm_rich_error_init(const pm_parser_t *parser, pm_rich_error_t *rich_error, pm_diagnostic_t *diagnostic, pm_location_t *location) { const pm_line_offset_list_t *line_offsets = &parser->line_offsets; - pm_line_column_t start_line_column = pm_line_offset_list_line_column(line_offsets, location->start, parser->start_line); - pm_line_column_t end_line_column = pm_line_offset_list_line_column(line_offsets, location->start + location->length, parser->start_line); + pm_line_column_t start_line_column = pm_line_offset_list_line_column(line_offsets, location->start, 0); + pm_line_column_t end_line_column = pm_line_offset_list_line_column(line_offsets, location->start + location->length, 0); uint32_t column_end; if (start_line_column.line == end_line_column.line) { column_end = end_line_column.column; } else { - column_end = (uint32_t) (line_offsets->offsets[start_line_column.line - parser->start_line + 1] - line_offsets->offsets[start_line_column.line - parser->start_line] - 1); + column_end = (uint32_t) (line_offsets->offsets[(uint32_t) start_line_column.line + 1] - line_offsets->offsets[(uint32_t) start_line_column.line] - 1); } /* Ensure we have at least one column of error. */ @@ -515,7 +517,7 @@ pm_rich_error_init(const pm_parser_t *parser, pm_rich_error_t *rich_error, pm_di *rich_error = (pm_rich_error_t) { .diagnostic = diagnostic, - .line_start = start_line_column.line, + .line_index = (uint32_t) start_line_column.line, .column_start = start_line_column.column, .column_end = column_end }; @@ -526,10 +528,10 @@ pm_rich_error_init(const pm_parser_t *parser, pm_rich_error_t *rich_error, pm_di * message, which is how an error is displayed without a source snippet. */ static void -pm_error_append_summary(const pm_parser_t *parser, pm_buffer_t *buffer, int32_t line, const char *message) { +pm_error_append_summary(const pm_parser_t *parser, pm_buffer_t *buffer, uint32_t line, const char *message) { pm_buffer_append_string(buffer, (const char *) pm_string_source(&parser->filepath), pm_string_length(&parser->filepath)); pm_buffer_append_byte(buffer, ':'); - pm_error_append_line_number(buffer, line, 0); + pm_error_append_line_number(buffer, pm_line_offset_list_line_number(line, parser->start_line), 0); PM_BUFFER_APPEND_LITERAL(buffer, ": "); pm_buffer_append_string(buffer, message, strlen(message)); } @@ -562,7 +564,7 @@ pm_errors_format(const pm_parser_t *parser, pm_buffer_t *buffer, pm_errors_forma * immediately. They should include a snippet of the source if * possible. */ pm_rich_error_init(parser, rich_errors, diagnostic, &location); - pm_error_append_summary(parser, buffer, rich_errors[0].line_start, pm_diagnostic_message(diagnostic)); + pm_error_append_summary(parser, buffer, rich_errors[0].line_index, pm_diagnostic_message(diagnostic)); if (rich_errors_are_utf8(parser, 1, rich_errors)) { pm_buffer_append_byte(buffer, '\n'); @@ -588,7 +590,7 @@ pm_errors_format(const pm_parser_t *parser, pm_buffer_t *buffer, pm_errors_forma * the source, so they are left out. It should include a snippet of * the source if possible. */ pm_rich_error_init(parser, rich_errors, diagnostic, &location); - pm_error_append_summary(parser, buffer, rich_errors[0].line_start, pm_diagnostic_message(diagnostic)); + pm_error_append_summary(parser, buffer, rich_errors[0].line_index, pm_diagnostic_message(diagnostic)); if (rich_errors_are_utf8(parser, 1, rich_errors)) { pm_buffer_append_byte(buffer, '\n'); @@ -605,7 +607,7 @@ pm_errors_format(const pm_parser_t *parser, pm_buffer_t *buffer, pm_errors_forma /* The header displays the line of the first error in parse order, which * is the first entry in the array because it has not been sorted yet. */ - pm_error_append_summary(parser, buffer, rich_errors[0].line_start, (nerrors > 1) ? "syntax errors found\n" : "syntax error found\n"); + pm_error_append_summary(parser, buffer, rich_errors[0].line_index, (nerrors > 1) ? "syntax errors found\n" : "syntax error found\n"); /* Sort the errors so that they are in the order that they appear in the * source. This is the order they are displayed in, and it also lets the @@ -625,7 +627,7 @@ pm_errors_format(const pm_parser_t *parser, pm_buffer_t *buffer, pm_errors_forma * source, as they are when the snippets are displayed. */ for (size_t idx = 0; idx < nerrors; idx++) { if (idx > 0) pm_buffer_append_byte(buffer, '\n'); - pm_error_append_summary(parser, buffer, rich_errors[idx].line_start, pm_diagnostic_message(rich_errors[idx].diagnostic)); + pm_error_append_summary(parser, buffer, rich_errors[idx].line_index, pm_diagnostic_message(rich_errors[idx].diagnostic)); } } diff --git a/src/prism.c b/src/prism.c index 83eb3d01b0..aec8931921 100644 --- a/src/prism.c +++ b/src/prism.c @@ -7625,8 +7625,6 @@ parser_magic_comment_key_p(const uint8_t *key, size_t key_length, const char *na */ static PRISM_INLINE bool parser_lex_magic_comment(pm_parser_t *parser, bool semantic_token_seen) { - bool result = true; - const uint8_t *start = parser->current.start + 1; const uint8_t *end = parser->current.end; if (end - start <= 7) return false; @@ -7645,24 +7643,23 @@ parser_lex_magic_comment(pm_parser_t *parser, bool semantic_token_seen) { // have a magic comment. return false; } - } else { - // Non-emacs magic comments must contain a colon for `key: value`. - // Reject early if there is no colon to avoid scanning the entire - // comment character-by-character. - if (pm_memchr(start, ':', (size_t) (end - start), parser->encoding_changed, parser->encoding) == NULL) { + } + + if (!indicator) { + /* The encoding-comment line needs the full scan because its result + * controls the fallback encoding scan. Other comments without a colon + * cannot contain a magic directive, so reject them early. */ + if ((parser->current.start != parser->encoding_comment_start || parser->encoding_locked) && + pm_memchr(start, ':', (size_t) (end - start), parser->encoding_changed, parser->encoding) == NULL) { return false; } - // Advance start past leading whitespace so the main loop begins - // directly at the key, avoiding a redundant whitespace scan. start += pm_strspn_whitespace(start, end - start); } cursor = start; while (cursor < end) { - if (indicator) { - while (cursor < end && (pm_char_is_magic_comment_key_delimiter(*cursor) || pm_char_is_whitespace(*cursor))) cursor++; - } + while (cursor < end && (pm_char_is_magic_comment_key_delimiter(*cursor) || pm_char_is_whitespace(*cursor))) cursor++; const uint8_t *key_start = cursor; while (cursor < end && (!pm_char_is_magic_comment_key_delimiter(*cursor) && !pm_char_is_whitespace(*cursor))) cursor++; @@ -7711,22 +7708,15 @@ parser_lex_magic_comment(pm_parser_t *parser, bool semantic_token_seen) { switch (key_length) { case 6: - /* We only want to attempt to compare against encoding comments - * if it is the first line in the file (or the second in the - * case of a shebang). */ - if (parser->current.start == parser->encoding_comment_start && !parser->encoding_locked) { - if (parser_magic_comment_key_p(key_start, key_length, "coding")) { - result = parser_lex_magic_comment_encoding_value(parser, value_start, value_end); - } - } - break; case 8: /* We only want to attempt to compare against encoding comments * if it is the first line in the file (or the second in the * case of a shebang). */ if (parser->current.start == parser->encoding_comment_start && !parser->encoding_locked) { - if (parser_magic_comment_key_p(key_start, key_length, "encoding")) { - result = parser_lex_magic_comment_encoding_value(parser, value_start, value_end); + if (parser_magic_comment_key_p(key_start, key_length, key_length == 6 ? "coding" : "encoding")) { + if (!parser_lex_magic_comment_encoding_value(parser, value_start, value_end)) { + pm_parser_err(parser, U32(value_start - parser->start), value_length, PM_ERR_INVALID_ENCODING_MAGIC_COMMENT); + } } } break; @@ -7820,7 +7810,7 @@ parser_lex_magic_comment(pm_parser_t *parser, bool semantic_token_seen) { pm_list_append(&parser->magic_comment_list, (pm_list_node_t *) magic_comment); } - return result; + return true; } /******************************************************************************/ @@ -8726,11 +8716,20 @@ lex_identifier(pm_parser_t *parser, bool previous_command_start) { /** * Returns true if the current token that the parser is considering is at the - * beginning of a line or the beginning of the source. + * beginning of a line or the beginning of the source, after an optional BOM. */ static bool current_token_starts_line(pm_parser_t *parser) { - return (parser->current.start == parser->start) || (parser->current.start[-1] == '\n'); + if (parser->current.start == parser->start) return true; + + switch (parser->current.start[-1]) { + case '\n': + return true; + case 0xbf: + return (parser->current.start - parser->start == 3 && parser->start[0] == 0xef && parser->start[1] == 0xbb); + default: + return false; + } } /** @@ -9361,7 +9360,7 @@ escape_read(pm_parser_t *parser, pm_buffer_t *buffer, uint8_t flags) { // ?\u{nnnn} character literal should contain only one codepoint // and cannot be like ?\u{nnnn mmmm}. if (flags & PM_ESCAPE_FLAG_SINGLE && codepoints_count > 1) { - pm_parser_err(parser, U32(extra_codepoints_start - parser->start), U32(parser->current.end - 1 - extra_codepoints_start), PM_ERR_ESCAPE_INVALID_UNICODE_LITERAL); + pm_parser_err(parser, U32(extra_codepoints_start - parser->start), U32(parser->current.end - extra_codepoints_start), PM_ERR_ESCAPE_INVALID_UNICODE_LITERAL); } if (parser->current.end == parser->end) { @@ -10661,7 +10660,12 @@ parser_lex(pm_parser_t *parser) { current_token_starts_line(parser) && (parser->current.end + 5 <= parser->end) && memcmp(parser->current.end, "begin", 5) == 0 && - (pm_char_is_whitespace(peek_offset(parser, 5)) || (peek_offset(parser, 5) == '\0')) + ( + pm_char_is_whitespace(peek_offset(parser, 5)) || + (peek_offset(parser, 5) == '\0') || + (peek_offset(parser, 5) == '\004') || /* Ctrl-D */ + (peek_offset(parser, 5) == '\032') /* Ctrl-Z */ + ) ) { pm_token_type_t type = lex_embdoc(parser); if (type == PM_TOKEN_EOF) { @@ -12372,11 +12376,13 @@ parser_lex(pm_parser_t *parser) { uint8_t breakpoints[PM_STRPBRK_CACHE_SIZE] = "\r\n\\#"; pm_heredoc_quote_t quote = heredoc_lex_mode->quote; + /* Single-quoted heredocs preserve bytes without validating them. */ + bool validate = quote != PM_HEREDOC_QUOTE_SINGLE; if (quote == PM_HEREDOC_QUOTE_SINGLE) { breakpoints[3] = '\0'; } - const uint8_t *breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true); + const uint8_t *breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, validate); pm_token_buffer_t token_buffer = { 0 }; bool was_line_continuation = false; @@ -12385,13 +12391,13 @@ parser_lex(pm_parser_t *parser) { case '\0': // Skip directly past the null character. parser->current.end = breakpoint + 1; - breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true); + breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, validate); break; case '\r': parser->current.end = breakpoint + 1; if (peek_at(parser, breakpoint + 1) != '\n') { - breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true); + breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, validate); break; } @@ -12482,7 +12488,7 @@ parser_lex(pm_parser_t *parser) { // Otherwise we hit a newline and it wasn't followed by // a terminator, so we can continue parsing. parser->current.end = breakpoint + 1; - breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true); + breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, validate); break; } case '\\': { @@ -12589,7 +12595,7 @@ parser_lex(pm_parser_t *parser) { } token_buffer.cursor = parser->current.end; - breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true); + breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, validate); break; } case '#': { @@ -12601,7 +12607,7 @@ parser_lex(pm_parser_t *parser) { // or instance variable like "#@" but wasn't // actually. In this case we'll just skip to the // next breakpoint. - breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true); + breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, validate); break; } @@ -14610,10 +14616,14 @@ parse_arguments(pm_parser_t *parser, pm_arguments_t *arguments, bool accepts_for * end * * - * It can recurse infinitely down, and splats are allowed to group arguments. + * Destructuring can be nested, and splats are allowed to group arguments. */ -static pm_multi_target_node_t * -parse_required_destructured_parameter(pm_parser_t *parser) { +static pm_node_t * +parse_required_destructured_parameter(pm_parser_t *parser, uint16_t depth) { + if (PRISM_UNLIKELY(depth >= PRISM_DEPTH_MAXIMUM || pm_parser_stack_exhausted(parser))) { + return parse_resource_recovery(parser, depth); + } + expect1(parser, PM_TOKEN_PARENTHESIS_LEFT_GROUPING, PM_ERR_EXPECT_LPAREN_REQ_PARAMETER); pm_multi_target_node_t *node = pm_multi_target_node_create(parser); @@ -14634,7 +14644,7 @@ parse_required_destructured_parameter(pm_parser_t *parser) { } if (match1(parser, PM_TOKEN_PARENTHESIS_LEFT_GROUPING)) { - param = UP(parse_required_destructured_parameter(parser)); + param = parse_required_destructured_parameter(parser, (uint16_t) (depth + 1)); } else if (accept1(parser, PM_TOKEN_USTAR)) { pm_token_t star = parser->previous; pm_node_t *value = NULL; @@ -14667,7 +14677,7 @@ parse_required_destructured_parameter(pm_parser_t *parser) { expect1(parser, PM_TOKEN_PARENTHESIS_RIGHT, PM_ERR_EXPECT_RPAREN_REQ_PARAMETER); pm_multi_target_node_closing_set(parser, node, &parser->previous); - return node; + return UP(node); } /** @@ -14804,7 +14814,7 @@ parse_parameters( switch (parser->current.type) { case PM_TOKEN_PARENTHESIS_LEFT_GROUPING: { update_parameter_state(parser, &parser->current, &order); - pm_node_t *param = UP(parse_required_destructured_parameter(parser)); + pm_node_t *param = parse_required_destructured_parameter(parser, (uint16_t) (depth + 1)); if (order > PM_PARAMETERS_ORDER_AFTER_OPTIONAL) { pm_parameters_node_requireds_append(parser->arena, params, param); @@ -20308,6 +20318,30 @@ parse_uninterpolated_symbol_array(pm_parser_t *parser) { return array; } +/** + * Validate completed static symbols before adding them to a symbol array. + * Interpolated symbols are validated at runtime instead. + */ +static void +parse_interpolated_symbol_array_element(pm_parser_t *parser, pm_array_node_t *array, pm_node_t *element) { + if (PM_NODE_TYPE_P(element, PM_SYMBOL_NODE) && !PM_NODE_FLAG_P(element, PM_SYMBOL_FLAGS_FORCED_BINARY_ENCODING | PM_SYMBOL_FLAGS_FORCED_US_ASCII_ENCODING)) { + const pm_symbol_node_t *symbol = (const pm_symbol_node_t *) element; + pm_token_t content = { + .type = PM_TOKEN_STRING_CONTENT, + .start = parser->start + symbol->content_loc.start, + .end = parser->start + PM_LOCATION_END(&symbol->content_loc) + }; + + if (PM_NODE_FLAG_P(element, PM_SYMBOL_FLAGS_FORCED_UTF8_ENCODING)) { + parse_symbol_encoding_validate_utf8(parser, &content, &symbol->unescaped); + } else { + parse_symbol_encoding_validate_other(parser, &content, &symbol->unescaped); + } + } + + pm_array_node_elements_append(parser->arena, array, element); +} + static pm_array_node_t * parse_interpolated_symbol_array(pm_parser_t *parser, uint16_t depth) { parser_lex(parser); @@ -20332,7 +20366,7 @@ parse_interpolated_symbol_array(pm_parser_t *parser, uint16_t depth) { /* If we hit a separator after we've hit content, then we * need to append that content to the list and reset the * current node. */ - pm_array_node_elements_append(parser->arena, array, current); + parse_interpolated_symbol_array_element(parser, array, current); current = NULL; } @@ -20444,7 +20478,7 @@ parse_interpolated_symbol_array(pm_parser_t *parser, uint16_t depth) { /* If we have a current node, then we need to append it to the list. */ if (current) { - pm_array_node_elements_append(parser->arena, array, current); + parse_interpolated_symbol_array_element(parser, array, current); } pm_token_t closing = parser->current; @@ -23505,13 +23539,12 @@ pm_parser_init(pm_arena_t *arena, pm_parser_t *parser, const uint8_t *source, si const uint8_t *newline = next_newline(parser->current.end, parser->end - parser->current.end); size_t length = (size_t) ((newline != NULL ? newline : parser->end) - parser->current.end); - if (length > 2 && parser->current.end[0] == '#' && parser->current.end[1] == '!') { + if (length >= 2 && parser->current.end[0] == '#' && parser->current.end[1] == '!') { + parser->encoding_comment_start = newline != NULL ? newline + 1 : parser->end; const char *engine; if ((engine = pm_strnstr((const char *) parser->start, "ruby", length)) != NULL) { if (newline != NULL) { - parser->encoding_comment_start = newline + 1; - if (options == NULL || options->main_script) { pm_parser_warn_shebang_carriage_return(parser, parser->start, length + 1); } @@ -23522,7 +23555,7 @@ pm_parser_init(pm_arena_t *arena, pm_parser_t *parser, const uint8_t *source, si } search_shebang = false; - } else if (options != NULL && options->main_script && !parser->parsing_eval) { + } else if (length > 2 && options != NULL && options->main_script && !parser->parsing_eval) { search_shebang = true; } } diff --git a/src/strncasecmp.c b/src/strncasecmp.c index a373cad6d7..816a2b9437 100644 --- a/src/strncasecmp.c +++ b/src/strncasecmp.c @@ -27,9 +27,9 @@ pm_strncasecmp(const uint8_t *string1, const uint8_t *string2, size_t length) { size_t offset = 0; int difference = 0; - while (offset < length && string1[offset] != '\0') { - if (string2[offset] == '\0') return string1[offset]; + while (offset < length) { if ((difference = pm_tolower(string1[offset]) - pm_tolower(string2[offset])) != 0) return difference; + if (string1[offset] == '\0') return 0; offset++; } diff --git a/src/strpbrk.c b/src/strpbrk.c index 77d9b3e53f..88fdea3aff 100644 --- a/src/strpbrk.c +++ b/src/strpbrk.c @@ -320,7 +320,7 @@ pm_strpbrk_ascii_8bit(pm_parser_t *parser, const uint8_t *source, const uint8_t return source + index; } - if (validate && source[index] >= 0x80) pm_strpbrk_explicit_encoding_set(parser, (uint32_t) (source - parser->start), 1); + if (validate && source[index] >= 0x80) pm_strpbrk_explicit_encoding_set(parser, (uint32_t) (source + index - parser->start), 1); index++; } @@ -343,7 +343,7 @@ pm_strpbrk_multi_byte(pm_parser_t *parser, const uint8_t *source, const uint8_t index++; } else { size_t width = pm_encoding_char_width(encoding, source + index, (ptrdiff_t) (maximum - index)); - if (validate) pm_strpbrk_explicit_encoding_set(parser, (uint32_t) (source - parser->start), (uint32_t) width); + if (validate) pm_strpbrk_explicit_encoding_set(parser, (uint32_t) (source + index - parser->start), (uint32_t) (width == 0 ? 1 : width)); if (width > 0) { index += width; @@ -385,7 +385,7 @@ pm_strpbrk_single_byte(pm_parser_t *parser, const uint8_t *source, const uint8_t index++; } else { size_t width = pm_encoding_char_width(encoding, source + index, (ptrdiff_t) (maximum - index)); - pm_strpbrk_explicit_encoding_set(parser, (uint32_t) (source - parser->start), (uint32_t) width); + pm_strpbrk_explicit_encoding_set(parser, (uint32_t) (source + index - parser->start), (uint32_t) (width == 0 ? 1 : width)); if (width > 0) { index += width; diff --git a/test/prism/api/raise_error_test.rb b/test/prism/api/raise_error_test.rb index 8347fbea00..25bbe8b8d6 100644 --- a/test/prism/api/raise_error_test.rb +++ b/test/prism/api/raise_error_test.rb @@ -89,6 +89,30 @@ def test_syntax_error_context_line_numbers assert_equal [gutters.first], gutters.uniq end + def test_syntax_error_extreme_line_numbers + [-(2**31), 2**31 - 1].each do |line| + error = assert_raise(SyntaxError) { Prism.parse("}\n", raise_error: :plain, line: line) } + assert_include error.message, "> #{line} | }\n" + end + end + + def test_syntax_error_context_across_line_number_wraparound + source = "\n}\n\n\n" + error = assert_raise(SyntaxError) { Prism.parse(source, raise_error: :plain, line: 2**31 - 4) } + assert_include error.message, "> 2147483645 | }\n" + assert_include error.message, " 2147483647 | \n" + + source = "1 2\n3 4\n5 6\n" + error = assert_raise(SyntaxError) { Prism.parse(source, raise_error: :plain, line: 2**31 - 1) } + source_lines = error.message.lines.grep(/^> /) + assert_equal [ + "> 2147483647 | 1 2\n", + "> -2147483648 | 3 4\n", + "> -2147483647 | 5 6\n" + ], source_lines + assert_equal [14], error.message.lines.grep(/\|/).map { |line| line.index("|") }.uniq + end + def test_syntax_error_not_utf8_in_context # A line of context is displayed, so it must be valid UTF-8 for the # snippet to be displayed, even though it has no error of its own. diff --git a/test/prism/bom_test.rb b/test/prism/bom_test.rb index 0fa00ae4e8..d1e67926a2 100644 --- a/test/prism/bom_test.rb +++ b/test/prism/bom_test.rb @@ -50,6 +50,43 @@ def test_string assert_bom("''") end + def test_embedded_document + source = "=begin\nignored\n=end\n1\n" + assert_bom(source) + result = Prism.parse("\xEF\xBB\xBF#{source}") + + assert_predicate result, :success? + assert_equal 1, result.statement.value + assert_kind_of EmbDocComment, result.comments.first + assert_equal 3, result.comments.first.location.start_offset + assert_equal "=begin\nignored\n=end\n", result.comments.first.location.slice + end + + def test_end_marker + ["", "\n", "\r\n"].each do |newline| + source = "__END__#{newline}" + source += "data\n" unless newline.empty? + assert_bom(source) + result = Prism.parse("\xEF\xBB\xBF#{source}") + + assert_predicate result, :success? + assert_empty result.value.statements.body + assert_not_nil result.data_loc + assert_equal 3, result.data_loc.start_offset + assert_equal source, result.data_loc.slice + end + end + + def test_indented_markers + result = Prism.parse("\xEF\xBB\xBF __END__\n") + assert_predicate result, :success? + assert_nil result.data_loc + + result = Prism.parse("\xEF\xBB\xBF =begin\n=end\n") + assert_predicate result, :failure? + assert_empty result.comments + end + private def assert_bom(source) diff --git a/test/prism/encoding/string_encoding_test.rb b/test/prism/encoding/string_encoding_test.rb index de54195a68..e5a32cbf47 100644 --- a/test/prism/encoding/string_encoding_test.rb +++ b/test/prism/encoding/string_encoding_test.rb @@ -131,6 +131,37 @@ def test_encodings_are_not_leaked_across_hash_elements end end + def test_invalid_bytes_in_single_quoted_heredocs + encodings = [Encoding::UTF_8, Encoding::US_ASCII] + encodings << Encoding::Shift_JIS unless ENV["PRISM_BUILD_MINIMAL"] + + encodings.each do |encoding| + ["", "-", "~"].each do |indent| + source = "# encoding: #{encoding.name}\n<<#{indent}'HERE'\n\x81\nHERE\n" + result = Prism.parse(source) + + assert_predicate result, :success? + assert_equal "\x81\n".b.force_encoding(encoding), result.statement.unescaped + refute_predicate result.statement.unescaped, :valid_encoding? + end + end + end + + def test_invalid_bytes_in_interpolating_heredocs + ["HERE", '"HERE"', "`HERE`"].each do |identifier| + result = Prism.parse("# encoding: UTF-8\n<<#{identifier}\n\x81\nHERE\n") + assert_equal [:invalid_multibyte_character], result.errors.map(&:type) + end + end + + def test_invalid_bytes_after_single_quoted_heredoc_breakpoints + ["a\n\x81\n", "a\r\n\x81\n", "\0\x81\n", "\\a\x81\n", "\\\x81\n", "\#{x}\x81\n"].each do |body| + result = Prism.parse("# encoding: UTF-8\n<<'HERE'\n#{body}HERE\n") + assert_predicate result, :success?, body.inspect + assert_equal body.b.gsub("\r\n", "\n").force_encoding(body.encoding), result.statement.unescaped + end + end + private def binary_node_encoding(node) diff --git a/test/prism/encoding/symbol_encoding_test.rb b/test/prism/encoding/symbol_encoding_test.rb index 20c998a58b..8a35e7d28b 100644 --- a/test/prism/encoding/symbol_encoding_test.rb +++ b/test/prism/encoding/symbol_encoding_test.rb @@ -16,6 +16,34 @@ class SymbolEncodingTest < TestCase end end + def test_invalid_static_symbol_array_elements + ["%I[\\xC0]", "%I[valid \\xC0]", "%I[\\xC0 valid]", "%I[\\xC0\\xAF]"].each do |expression| + source = "# encoding: UTF-8\nif false\n#{expression}\nend" + result = Prism.parse(source) + + assert_equal [:invalid_symbol], result.errors.map(&:type), expression + assert_match(/\\xC0/, result.errors.first.location.slice) + end + end + + def test_invalid_bytes_in_dynamic_symbol_array_elements + ['%I[\xC0#{x}]', '%I[#{x}\xC0]'].each do |expression| + assert_predicate Prism.parse("# encoding: UTF-8\n#{expression}"), :success? + end + end + + def test_symbol_array_element_encodings + ["binary", "us-ascii"].each do |encoding| + result = Prism.parse("# encoding: #{encoding}\n%I[\\xC0 \\u3042 ascii]") + assert_predicate result, :success? + binary, utf8, ascii = result.statement.elements + assert_equal [0xC0], binary.unescaped.bytes + assert_equal encoding == "us-ascii", binary.forced_binary_encoding? + assert_predicate utf8, :forced_utf8_encoding? + assert_predicate ascii, :forced_us_ascii_encoding? + end + end + private def expected_encoding(source) diff --git a/test/prism/errors/do_not_allow_multiple_codepoints_in_a_single_character_literal.txt b/test/prism/errors/do_not_allow_multiple_codepoints_in_a_single_character_literal.txt index 1a93dc6c69..b8810c209d 100644 --- a/test/prism/errors/do_not_allow_multiple_codepoints_in_a_single_character_literal.txt +++ b/test/prism/errors/do_not_allow_multiple_codepoints_in_a_single_character_literal.txt @@ -1,3 +1,3 @@ ?\u{0001 0002} - ^~~ invalid Unicode escape sequence; Multiple codepoints at single character literal are disallowed + ^~~~ invalid Unicode escape sequence; Multiple codepoints at single character literal are disallowed diff --git a/test/prism/errors_test.rb b/test/prism/errors_test.rb index 0637671ba4..c593f6b1ea 100644 --- a/test/prism/errors_test.rb +++ b/test/prism/errors_test.rb @@ -22,6 +22,44 @@ class ErrorsTest < TestCase end end + def test_mixed_encoding_locations + ["ASCII-8BIT", "US-ASCII", "EUC-JP"].each do |encoding| + next if ENV["PRISM_BUILD_MINIMAL"] && encoding == "EUC-JP" + + bytes = encoding == "EUC-JP" ? "\xA1\xA1" : "\xA1" + source = "\"\\u{df}abc#{bytes}\"".b + error = Prism.parse(source, encoding: encoding).errors.find { |diagnostic| diagnostic.type == :mixed_encoding } + + assert_not_nil error + assert_equal 10, error.location.start_offset + assert_equal bytes.bytesize, error.location.length + assert_equal bytes.b, error.location.slice.b + end + end + + def test_mixed_encoding_location_for_invalid_multibyte_character + return if ENV["PRISM_BUILD_MINIMAL"] + + source = "\"\\u{df\xD3&".b + error = Prism.parse(source, encoding: "EUC-JP").errors.find { |diagnostic| diagnostic.type == :mixed_encoding } + + assert_not_nil error + assert_equal 6, error.location.start_offset + assert_equal 1, error.location.length + assert_equal "\xD3".b, error.location.slice.b + end + + def test_extra_unicode_codepoint_locations + ["a", "00", "a b", "a "].each do |extra| + result = Prism.parse("?\\u{0 #{extra}}") + error = result.errors.find { |diagnostic| diagnostic.type == :escape_invalid_unicode_literal } + + assert_not_nil error + assert_equal 6, error.location.start_offset + assert_equal extra, error.location.slice + end + end + def test_newline_preceding_eof err = Prism.parse("foo(").errors.first assert_equal 1, err.location.start_line @@ -33,6 +71,28 @@ def test_newline_preceding_eof assert_equal 5, err.location.start_line end + def test_embdoc_beginning_control_characters + ["\0", "\C-d", "\C-z"].each do |character| + ["\n", "\r\n"].each do |newline| + comment = "=begin#{character}#{newline}ignored#{newline}=end#{newline}" + result = Prism.parse("#{comment}1#{newline}") + + assert_predicate result, :success? + assert_equal 1, result.statement.value + assert_equal 1, result.comments.length + assert_kind_of EmbDocComment, result.comments.first + assert_equal comment, result.comments.first.location.slice + end + end + end + + def test_unterminated_embdoc_after_control_character + ["\C-d", "\C-z"].each do |character| + result = Prism.parse("=begin#{character}") + assert_equal [:embdoc_term], result.errors.map(&:type) + end + end + def test_embdoc_ending source = <<~RUBY =begin\n=end diff --git a/test/prism/magic_comment_test.rb b/test/prism/magic_comment_test.rb index 7985bae568..bc9e4a5542 100644 --- a/test/prism/magic_comment_test.rb +++ b/test/prism/magic_comment_test.rb @@ -81,6 +81,112 @@ def test_vim assert_magic_encoding(Encoding::Windows_31J, "# vim: filetype=ruby, fileencoding=windows-31j, tabsize=3, shiftwidth=3") end + def test_nul_in_magic_comment_values + { + "frozen_string_literal" => ["true", "false"], + "warn_indent" => ["true", "false"], + "shareable_constant_value" => ["none", "literal", "experimental_everything", "experimental_copy"] + }.each do |key, values| + values.each do |value| + value.length.times do |index| + invalid = value.dup + invalid[index] = "\0" + result = Prism.parse("# #{key}: #{invalid}\n") + + assert_predicate result, :success? + assert_equal [:invalid_magic_comment_value], result.warnings.map(&:type), "#{key}: #{invalid.inspect}" + end + end + end + end + + def test_nul_value_preserves_frozen_string_literal_option + [false, true].each do |frozen| + result = Prism.parse("# frozen_string_literal: \0abc\n\"a\"", frozen_string_literal: frozen) + assert_equal frozen, result.value.statements.body.first.frozen? + assert_include result.warnings.map(&:type), :invalid_magic_comment_value + end + end + + def test_invalid_encoding_value_does_not_fall_back_to_prefix + ["coding", "encoding"].each do |key| + ["Windows-31J[", "ascii!", "binary?", "unknown"].each do |value| + ["# #{key}: #{value}", "# #{key}: \"#{value}\"", "# -*- #{key}: #{value} -*-"].each do |comment| + result = Prism.parse("#{comment}\n__ENCODING__") + + assert_equal [:invalid_encoding_magic_comment], result.errors.map(&:type) + assert_equal value, result.errors.first.location.slice + assert_equal Encoding::UTF_8, result.encoding + end + end + end + end + + def test_encoding_fallback_is_not_used_for_unrecognized_keys + ['#"ncoding:binary', "#'ncoding:binary", "#;ncoding:binary", "# coding=binary", "# coding=e", "# -*- coding=binary -*-"].each do |comment| + result = Prism.parse("#{comment}\n__ENCODING__") + + assert_predicate result, :success?, comment + assert_equal Encoding::UTF_8, result.encoding, comment + end + end + + def test_encoding_after_leading_delimiters + ['"', "'", ";", ":"].each do |delimiter| + ["coding", "encoding"].each do |key| + result = Prism.parse("##{delimiter}#{key}:binary\n__ENCODING__") + assert_predicate result, :success? + assert_equal Encoding::ASCII_8BIT, result.encoding + end + end + end + + def test_encoding_after_non_ruby_shebang + ["#!/bin/sh", "#!", "#!coding:;"].each do |shebang| + ["\n", "\r\n"].each do |newline| + source = "#{shebang}#{newline} # encoding: US-ASCII#{newline}__ENCODING__" + result = Prism.parse(source) + + assert_predicate result, :success? + assert_equal Encoding::US_ASCII, result.encoding + end + end + end + + def test_empty_shebang_in_main_script + ["#!", "#!\n", "#!\n# encoding: US-ASCII\n__ENCODING__"].each do |source| + result = Prism.parse(source, main_script: true) + assert_predicate result, :success?, source + end + + result = Prism.parse("#!\n# encoding: US-ASCII\n__ENCODING__", main_script: true) + assert_equal Encoding::US_ASCII, result.encoding + + result = Prism.parse("#!", main_script: true, command_line: "x") + assert_equal [:script_not_found], result.errors.map(&:type) + end + + def test_shebang_is_not_an_encoding_comment + ["#!coding:bogus", "#!ruby coding:bogus"].each do |shebang| + ["", "\n"].each do |newline| + result = Prism.parse("#{shebang}#{newline}") + + assert_predicate result, :success? + assert_equal Encoding::UTF_8, result.encoding + end + end + end + + def test_encoding_after_searched_shebang + source = "#!/bin/sh\n# encoding: US-ASCII\n#!ruby\n# encoding: binary\n__ENCODING__" + [{ main_script: true }, { command_line: "x" }].each do |options| + result = Prism.parse(source, **options) + + assert_predicate result, :success? + assert_equal Encoding::ASCII_8BIT, result.encoding + end + end + private def assert_magic_encoding(expected, line)