From 5815f82aa89139280d50052eef70f20d0e54f36b Mon Sep 17 00:00:00 2001 From: Kevin Newton Date: Wed, 25 Nov 2026 10:37:51 -0500 Subject: [PATCH 01/11] Preserve enclosing terminators during hash pattern recovery --- src/prism.c | 54 +++++++++++++++-------------- test/prism/heredoc_recovery_test.rb | 21 +++++++++++ 2 files changed, 49 insertions(+), 26 deletions(-) diff --git a/src/prism.c b/src/prism.c index 5321aecc5e..5d16518398 100644 --- a/src/prism.c +++ b/src/prism.c @@ -17867,37 +17867,39 @@ parse_pattern_primitive(pm_parser_t *parser, pm_constant_id_set_t *captures, pm_ bool previous_in_keyword_arg = parser->in_keyword_arg; parser->in_keyword_arg = false; - pm_hash_pattern_node_t *node; pm_token_t opening = parser->current; parser_lex(parser); - if (accept1(parser, PM_TOKEN_BRACE_RIGHT)) { - // If we have an empty hash pattern, then we'll just return a new hash - // pattern node. - node = pm_hash_pattern_node_empty_create(parser, &opening, &parser->previous); - } else { - pm_node_t *first_node; - - switch (parser->current.type) { - case PM_TOKEN_LABEL: - parser_lex(parser); - first_node = UP(pm_symbol_node_label_create(parser, &parser->previous)); - break; - case PM_TOKEN_USTAR_STAR: - first_node = parse_pattern_keyword_rest(parser, captures); - break; - case PM_TOKEN_STRING_BEGIN: - first_node = parse_expression(parser, PM_BINDING_POWER_MAX, PM_PARSE_ACCEPTS_DO_BLOCK | PM_PARSE_ACCEPTS_LABEL, PM_ERR_PATTERN_HASH_KEY_LABEL, (uint16_t) (depth + 1)).node; - break; - default: { - pm_parser_err_token_type(parser, &parser->current, PM_ERR_PATTERN_HASH_KEY, parser->current.type); - parse_discard_token(parser, depth); + pm_node_t *first_node = NULL; + switch (parser->current.type) { + case PM_TOKEN_BRACE_RIGHT: + break; + case PM_TOKEN_LABEL: + parser_lex(parser); + first_node = UP(pm_symbol_node_label_create(parser, &parser->previous)); + break; + case PM_TOKEN_USTAR_STAR: + first_node = parse_pattern_keyword_rest(parser, captures); + break; + case PM_TOKEN_STRING_BEGIN: + first_node = parse_expression(parser, PM_BINDING_POWER_MAX, PM_PARSE_ACCEPTS_DO_BLOCK | PM_PARSE_ACCEPTS_LABEL, PM_ERR_PATTERN_HASH_KEY_LABEL, (uint16_t) (depth + 1)).node; + break; + default: + /* Leave an enclosing terminator to its owner. Consuming a + * heredoc end here can rewind past the opening brace. */ + if (context_recoverable(parser, &parser->current) != PM_CONTEXT_NONE) break; - first_node = UP(pm_error_recovery_node_create(parser, PM_TOKEN_START(parser, &parser->previous), PM_TOKEN_LENGTH(&parser->previous))); - break; - } - } + pm_parser_err_token_type(parser, &parser->current, PM_ERR_PATTERN_HASH_KEY, parser->current.type); + parse_discard_token(parser, depth); + first_node = UP(pm_error_recovery_node_create(parser, PM_TOKEN_START(parser, &parser->previous), PM_TOKEN_LENGTH(&parser->previous))); + break; + } + pm_hash_pattern_node_t *node; + if (first_node == NULL) { + expect1_opening(parser, PM_TOKEN_BRACE_RIGHT, PM_ERR_PATTERN_TERM_BRACE, &opening); + node = pm_hash_pattern_node_empty_create(parser, &opening, &parser->previous); + } else { node = parse_pattern_hash(parser, captures, first_node, (uint16_t) (depth + 1)); accept1(parser, PM_TOKEN_NEWLINE); diff --git a/test/prism/heredoc_recovery_test.rb b/test/prism/heredoc_recovery_test.rb index 1000d21b28..69b1b66bc9 100644 --- a/test/prism/heredoc_recovery_test.rb +++ b/test/prism/heredoc_recovery_test.rb @@ -24,6 +24,27 @@ def test_discarded_hash_pattern_heredoc_at_eof assert_equal :pattern_hash_key, result.errors.first.type end + def test_missing_hash_pattern_brace_preserves_enclosing_end + result = assert_bounded_locations(<<~RUBY) + def matches? + <<~TEXT in { + value + TEXT + end + :after + RUBY + + assert_equal [:pattern_term_brace], result.errors.map(&:type) + definition, following = result.value.statements.body + assert_equal "end", definition.end_keyword_loc.slice + assert_equal ":after", following.location.slice + + match = definition.body.body.first + assert_equal "<<~TEXT in {", match.location.slice + assert_equal "{", match.pattern.location.slice + assert_empty match.pattern.elements + end + def test_discarded_hash_pattern_heredoc_resumes_on_declaration_line ["body\n", "\#{< Date: Wed, 25 Nov 2026 10:50:08 -0500 Subject: [PATCH 02/11] Resolve implicit block parameters in shorthand hash values --- config.yml | 1 + lib/prism/translation/parser/compiler.rb | 2 +- rbi/generated/prism/dsl.rbi | 2 +- rbi/generated/prism/node.rbi | 6 +- sig/generated/prism/dsl.rbs | 4 +- sig/generated/prism/node.rbs | 16 ++--- snapshots/3.4/it.txt | 90 +++++++++++++++++++----- src/prism.c | 48 ++++++------- test/prism/errors_test.rb | 13 ++++ test/prism/fixtures/3.4/it.txt | 2 + test/prism/ruby/parser_test.rb | 6 +- 11 files changed, 129 insertions(+), 61 deletions(-) diff --git a/config.yml b/config.yml index 2eeba7c050..7da25f37cf 100644 --- a/config.yml +++ b/config.yml @@ -3542,6 +3542,7 @@ nodes: type: node kind: - LocalVariableReadNode + - ItLocalVariableReadNode - CallNode - ConstantReadNode - LocalVariableTargetNode diff --git a/lib/prism/translation/parser/compiler.rb b/lib/prism/translation/parser/compiler.rb index dc290a6e85..84f1535b2b 100644 --- a/lib/prism/translation/parser/compiler.rb +++ b/lib/prism/translation/parser/compiler.rb @@ -153,7 +153,7 @@ def visit_assoc_node(node) elsif value.is_a?(ConstantReadNode) builder.const([value.name, srange(key.content_loc)]) else - builder.ident([value.name, srange(key.content_loc)]).updated(:lvar) + builder.ident([key.unescaped, srange(key.content_loc)]).updated(:lvar) end builder.pair_keyword([key.unescaped, srange(key)], implicit_value) diff --git a/rbi/generated/prism/dsl.rbi b/rbi/generated/prism/dsl.rbi index b8f76d08a7..e4128a0fd2 100644 --- a/rbi/generated/prism/dsl.rbi +++ b/rbi/generated/prism/dsl.rbi @@ -338,7 +338,7 @@ module Prism def imaginary_node(source: T.unsafe(nil), node_id: T.unsafe(nil), location: T.unsafe(nil), flags: T.unsafe(nil), numeric: T.unsafe(nil)); end # Create a new ImplicitNode node. - sig { params(source: Source, node_id: Integer, location: Location, flags: Integer, value: ::T.any(LocalVariableReadNode, CallNode, ConstantReadNode, LocalVariableTargetNode)).returns(ImplicitNode) } + sig { params(source: Source, node_id: Integer, location: Location, flags: Integer, value: ::T.any(LocalVariableReadNode, ItLocalVariableReadNode, CallNode, ConstantReadNode, LocalVariableTargetNode)).returns(ImplicitNode) } def implicit_node(source: T.unsafe(nil), node_id: T.unsafe(nil), location: T.unsafe(nil), flags: T.unsafe(nil), value: T.unsafe(nil)); end # Create a new ImplicitRestNode node. diff --git a/rbi/generated/prism/node.rbi b/rbi/generated/prism/node.rbi index e8dc343808..c42b7cf0d0 100644 --- a/rbi/generated/prism/node.rbi +++ b/rbi/generated/prism/node.rbi @@ -7365,7 +7365,7 @@ module Prism # [Explore code sample](https://ruby.github.io/prism/playground.html#eyBmb286IH0KCnsgRm9vOiB9Cgpmb28gaW4geyBiYXI6IH0K) class ImplicitNode < Node # Initialize a new ImplicitNode node. - sig { params(source: Source, node_id: Integer, location: Location, flags: Integer, value: ::T.any(LocalVariableReadNode, CallNode, ConstantReadNode, LocalVariableTargetNode)).void } + sig { params(source: Source, node_id: Integer, location: Location, flags: Integer, value: ::T.any(LocalVariableReadNode, ItLocalVariableReadNode, CallNode, ConstantReadNode, LocalVariableTargetNode)).void } def initialize(source, node_id, location, flags, value); end # See Node.accept. @@ -7386,7 +7386,7 @@ module Prism def compact_child_nodes; end # Creates a copy of self with the given fields, using self as the template. - sig { params(node_id: Integer, location: Location, flags: Integer, value: ::T.any(LocalVariableReadNode, CallNode, ConstantReadNode, LocalVariableTargetNode)).returns(ImplicitNode) } + sig { params(node_id: Integer, location: Location, flags: Integer, value: ::T.any(LocalVariableReadNode, ItLocalVariableReadNode, CallNode, ConstantReadNode, LocalVariableTargetNode)).returns(ImplicitNode) } def copy(node_id: T.unsafe(nil), location: T.unsafe(nil), flags: T.unsafe(nil), value: T.unsafe(nil)); end sig { override.returns(T::Array[::T.nilable(Node)]) } @@ -7407,7 +7407,7 @@ module Prism def inspect; end # Returns the `value` attribute. - sig { returns(::T.any(LocalVariableReadNode, CallNode, ConstantReadNode, LocalVariableTargetNode)) } + sig { returns(::T.any(LocalVariableReadNode, ItLocalVariableReadNode, CallNode, ConstantReadNode, LocalVariableTargetNode)) } def value; end sig { params(other: ::T.untyped).returns(::T.nilable(T::Boolean)) } diff --git a/sig/generated/prism/dsl.rbs b/sig/generated/prism/dsl.rbs index d8f1e10800..39bc660b51 100644 --- a/sig/generated/prism/dsl.rbs +++ b/sig/generated/prism/dsl.rbs @@ -410,8 +410,8 @@ module Prism # Create a new ImplicitNode node. # - # : (?source: Source, ?node_id: Integer, ?location: Location, ?flags: Integer, ?value: (LocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode)) -> ImplicitNode - def implicit_node: (?source: Source, ?node_id: Integer, ?location: Location, ?flags: Integer, ?value: LocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode) -> ImplicitNode + # : (?source: Source, ?node_id: Integer, ?location: Location, ?flags: Integer, ?value: (LocalVariableReadNode | ItLocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode)) -> ImplicitNode + def implicit_node: (?source: Source, ?node_id: Integer, ?location: Location, ?flags: Integer, ?value: LocalVariableReadNode | ItLocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode) -> ImplicitNode # Create a new ImplicitRestNode node. # diff --git a/sig/generated/prism/node.rbs b/sig/generated/prism/node.rbs index 9c9c5339c5..c60a935276 100644 --- a/sig/generated/prism/node.rbs +++ b/sig/generated/prism/node.rbs @@ -10387,12 +10387,12 @@ module Prism # # [Explore code sample](https://ruby.github.io/prism/playground.html#eyBmb286IH0KCnsgRm9vOiB9Cgpmb28gaW4geyBiYXI6IH0K) class ImplicitNode < Node - @value: LocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode + @value: LocalVariableReadNode | ItLocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode # Initialize a new ImplicitNode node. # - # : (Source source, Integer node_id, Location location, Integer flags, (LocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode) value) -> void - def initialize: (Source source, Integer node_id, Location location, Integer flags, LocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode value) -> void + # : (Source source, Integer node_id, Location location, Integer flags, (LocalVariableReadNode | ItLocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode) value) -> void + def initialize: (Source source, Integer node_id, Location location, Integer flags, LocalVariableReadNode | ItLocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode value) -> void # See Node.accept. # @@ -10421,8 +10421,8 @@ module Prism # # Creates a copy of self with the given fields, using self as the template. # - # : (?node_id: Integer, ?location: Location, ?flags: Integer, ?value: (LocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode)) -> ImplicitNode - def copy: (?node_id: Integer, ?location: Location, ?flags: Integer, ?value: LocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode) -> ImplicitNode + # : (?node_id: Integer, ?location: Location, ?flags: Integer, ?value: (LocalVariableReadNode | ItLocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode)) -> ImplicitNode + def copy: (?node_id: Integer, ?location: Location, ?flags: Integer, ?value: LocalVariableReadNode | ItLocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode) -> ImplicitNode alias deconstruct child_nodes @@ -10443,12 +10443,12 @@ module Prism def inspect: () -> String # :call-seq: - # value -> LocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode + # value -> LocalVariableReadNode | ItLocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode # # Returns the `value` attribute. # - # : () -> (LocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode) - def value: () -> (LocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode) + # : () -> (LocalVariableReadNode | ItLocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode) + def value: () -> (LocalVariableReadNode | ItLocalVariableReadNode | CallNode | ConstantReadNode | LocalVariableTargetNode) # : (untyped other) -> boolish def ===: (untyped other) -> boolish diff --git a/snapshots/3.4/it.txt b/snapshots/3.4/it.txt index 6567f94a32..bdf717c2a9 100644 --- a/snapshots/3.4/it.txt +++ b/snapshots/3.4/it.txt @@ -1,10 +1,10 @@ -@ ProgramNode (location: (1,0)-(5,9)) +@ ProgramNode (location: (1,0)-(7,12)) ├── flags: ∅ ├── locals: [] └── statements: - @ StatementsNode (location: (1,0)-(5,9)) + @ StatementsNode (location: (1,0)-(7,12)) ├── flags: ∅ - └── body: (length: 2) + └── body: (length: 3) ├── @ CallNode (location: (1,0)-(3,3)) │ ├── flags: newline, ignore_visibility │ ├── receiver: ∅ @@ -30,18 +30,74 @@ │ │ └── flags: newline │ ├── opening_loc: (1,2)-(1,4) = "do" │ └── closing_loc: (3,0)-(3,3) = "end" - └── @ LambdaNode (location: (5,0)-(5,9)) - ├── flags: newline - ├── locals: [] - ├── operator_loc: (5,0)-(5,2) = "->" - ├── opening_loc: (5,3)-(5,4) = "{" - ├── closing_loc: (5,8)-(5,9) = "}" - ├── parameters: - │ @ ItParametersNode (location: (5,0)-(5,9)) - │ └── flags: ∅ - └── body: - @ StatementsNode (location: (5,5)-(5,7)) + ├── @ LambdaNode (location: (5,0)-(5,9)) + │ ├── flags: newline + │ ├── locals: [] + │ ├── operator_loc: (5,0)-(5,2) = "->" + │ ├── opening_loc: (5,3)-(5,4) = "{" + │ ├── closing_loc: (5,8)-(5,9) = "}" + │ ├── parameters: + │ │ @ ItParametersNode (location: (5,0)-(5,9)) + │ │ └── flags: ∅ + │ └── body: + │ @ StatementsNode (location: (5,5)-(5,7)) + │ ├── flags: ∅ + │ └── body: (length: 1) + │ └── @ ItLocalVariableReadNode (location: (5,5)-(5,7)) + │ └── flags: newline + └── @ CallNode (location: (7,0)-(7,12)) + ├── flags: newline, ignore_visibility + ├── receiver: ∅ + ├── call_operator_loc: ∅ + ├── name: :x + ├── message_loc: (7,0)-(7,1) = "x" + ├── opening_loc: ∅ + ├── arguments: ∅ + ├── closing_loc: ∅ + ├── equal_loc: ∅ + └── block: + @ BlockNode (location: (7,2)-(7,12)) ├── flags: ∅ - └── body: (length: 1) - └── @ ItLocalVariableReadNode (location: (5,5)-(5,7)) - └── flags: newline + ├── locals: [] + ├── parameters: + │ @ ItParametersNode (location: (7,2)-(7,12)) + │ └── flags: ∅ + ├── body: + │ @ StatementsNode (location: (7,4)-(7,10)) + │ ├── flags: ∅ + │ └── body: (length: 1) + │ └── @ CallNode (location: (7,4)-(7,10)) + │ ├── flags: newline, ignore_visibility + │ ├── receiver: ∅ + │ ├── call_operator_loc: ∅ + │ ├── name: :f + │ ├── message_loc: (7,4)-(7,5) = "f" + │ ├── opening_loc: (7,5)-(7,6) = "(" + │ ├── arguments: + │ │ @ ArgumentsNode (location: (7,6)-(7,9)) + │ │ ├── flags: contains_keywords + │ │ └── arguments: (length: 1) + │ │ └── @ KeywordHashNode (location: (7,6)-(7,9)) + │ │ ├── flags: symbol_keys + │ │ └── elements: (length: 1) + │ │ └── @ AssocNode (location: (7,6)-(7,9)) + │ │ ├── flags: ∅ + │ │ ├── key: + │ │ │ @ SymbolNode (location: (7,6)-(7,9)) + │ │ │ ├── flags: static_literal, forced_us_ascii_encoding + │ │ │ ├── opening_loc: ∅ + │ │ │ ├── content_loc: (7,6)-(7,8) = "it" + │ │ │ ├── closing_loc: (7,8)-(7,9) = ":" + │ │ │ └── unescaped: "it" + │ │ ├── value: + │ │ │ @ ImplicitNode (location: (7,6)-(7,9)) + │ │ │ ├── flags: ∅ + │ │ │ └── value: + │ │ │ @ ItLocalVariableReadNode (location: (7,6)-(7,9)) + │ │ │ └── flags: ∅ + │ │ └── operator_loc: ∅ + │ ├── closing_loc: (7,9)-(7,10) = ")" + │ ├── equal_loc: ∅ + │ └── block: ∅ + ├── opening_loc: (7,2)-(7,3) = "{" + └── closing_loc: (7,11)-(7,12) = "}" diff --git a/src/prism.c b/src/prism.c index 5d16518398..ef908138aa 100644 --- a/src/prism.c +++ b/src/prism.c @@ -5404,15 +5404,6 @@ pm_local_variable_read_node_create_constant_id(pm_parser_t *parser, const pm_tok ); } -/** - * Allocate and initialize a new LocalVariableReadNode node. - */ -static pm_local_variable_read_node_t * -pm_local_variable_read_node_create(pm_parser_t *parser, const pm_token_t *name, uint32_t depth) { - pm_constant_id_t name_id = pm_parser_constant_id_token(parser, name); - return pm_local_variable_read_node_create_constant_id(parser, name, name_id, depth, false); -} - /** * Allocate and initialize a new LocalVariableReadNode node for a missing local * variable. (This will only happen when there is a syntax error.) @@ -13163,6 +13154,9 @@ parse_expression_infixes(pm_parser_t *parser, pm_reduction_t left, pm_binding_po static pm_node_t * parse_heredoc(pm_parser_t *parser, uint16_t depth); +static pm_node_t * +parse_variable(pm_parser_t *parser, const pm_token_t *name); + /* Resource failure must preserve the same token/context ownership as ordinary * syntax recovery. In particular, do not consume an enclosing terminator or * leave an unparsed heredoc's lexer mode pending. */ @@ -14265,11 +14259,9 @@ parse_assocs(pm_parser_t *parser, pm_static_literals_t *literals, pm_hash_elemen identifier.type = PM_TOKEN_CONSTANT; value = UP(pm_constant_read_node_create(parser, &identifier)); } else { - int depth = invalid ? -1 : pm_parser_local_depth(parser, &identifier); - if (depth == -1) { + value = invalid ? NULL : parse_variable(parser, &identifier); + if (value == NULL) { value = UP(pm_call_node_variable_call_create(parser, &identifier)); - } else { - value = UP(pm_local_variable_read_node_create(parser, &identifier, (uint32_t) depth)); } } @@ -15529,10 +15521,10 @@ parse_blocklike_parameters(pm_parser_t *parser, pm_node_t *parameters, const pm_ pm_parser_err_node(parser, node, PM_ERR_NUMBERED_PARAMETER_OUTER_BLOCK); } else if (parser->current_scope->parameters & PM_SCOPE_PARAMETERS_NUMBERED_INNER) { pm_parser_err_node(parser, node, PM_ERR_NUMBERED_PARAMETER_INNER_BLOCK); - } else if (pm_token_is_numbered_parameter(parser, PM_NODE_START(node), PM_NODE_LENGTH(node))) { - numbered_parameter = MAX(numbered_parameter, (uint8_t) (parser->start[node->location.start + 1] - '0')); } else { - PRISM_ASSERT(false && "unreachable"); + // The location of a shorthand hash value also includes the colon. + PRISM_ASSERT(PM_NODE_LENGTH(node) >= 2 && pm_token_is_numbered_parameter(parser, PM_NODE_START(node), 2)); + numbered_parameter = MAX(numbered_parameter, (uint8_t) (parser->start[node->location.start + 1] - '0')); } } else if (PM_NODE_TYPE_P(node, PM_IT_LOCAL_VARIABLE_READ_NODE)) { if (numbered_parameter > 0) { @@ -16891,17 +16883,17 @@ parse_alias_argument(pm_parser_t *parser, bool first, uint16_t depth) { } /** - * Parse an identifier into either a local variable read. If the local variable - * is not found, it returns NULL instead. + * Resolve an identifier to a local variable or implicit parameter read. + * Return NULL if the name is a method call. */ static pm_node_t * -parse_variable(pm_parser_t *parser) { - pm_constant_id_t name_id = pm_parser_constant_id_token(parser, &parser->previous); +parse_variable(pm_parser_t *parser, const pm_token_t *name) { + pm_constant_id_t name_id = pm_parser_constant_id_token(parser, name); int depth; - bool is_numbered_param = pm_token_is_numbered_parameter(parser, PM_TOKEN_START(parser, &parser->previous), PM_TOKEN_LENGTH(&parser->previous)); + bool is_numbered_param = pm_token_is_numbered_parameter(parser, PM_TOKEN_START(parser, name), PM_TOKEN_LENGTH(name)); if (!is_numbered_param && ((depth = pm_parser_local_depth_constant_id(parser, name_id)) != -1)) { - return UP(pm_local_variable_read_node_create_constant_id(parser, &parser->previous, name_id, (uint32_t) depth, false)); + return UP(pm_local_variable_read_node_create_constant_id(parser, name, name_id, (uint32_t) depth, false)); } pm_scope_t *current_scope = parser->current_scope; @@ -16911,7 +16903,7 @@ parse_variable(pm_parser_t *parser) { // all of the locals that exist before it. For example, referencing // _2 means that _1 must exist. Therefore here we loop through all // of the possibilities and add them into the constant pool. - uint8_t maximum = (uint8_t) (parser->previous.start[1] - '0'); + uint8_t maximum = (uint8_t) (name->start[1] - '0'); for (uint8_t number = 1; number <= maximum; number++) { pm_parser_local_add_constant(parser, pm_numbered_parameter_names[number - 1], 2); } @@ -16920,12 +16912,12 @@ parse_variable(pm_parser_t *parser) { parser->current_scope->parameters |= PM_SCOPE_PARAMETERS_NUMBERED_FOUND; } - pm_node_t *node = UP(pm_local_variable_read_node_create_constant_id(parser, &parser->previous, name_id, 0, false)); + pm_node_t *node = UP(pm_local_variable_read_node_create_constant_id(parser, name, name_id, 0, false)); pm_scratch_node_list_append(&parser->scratch_arena, ¤t_scope->implicit_parameters, node); return node; - } else if ((parser->version >= PM_OPTIONS_VERSION_CRUBY_3_4) && pm_token_is_it(parser->previous.start, parser->previous.end)) { - pm_node_t *node = UP(pm_it_local_variable_read_node_create(parser, &parser->previous)); + } else if ((parser->version >= PM_OPTIONS_VERSION_CRUBY_3_4) && pm_token_is_it(name->start, name->end)) { + pm_node_t *node = UP(pm_it_local_variable_read_node_create(parser, name)); pm_scratch_node_list_append(&parser->scratch_arena, ¤t_scope->implicit_parameters, node); return node; @@ -16943,7 +16935,7 @@ parse_variable_call(pm_parser_t *parser) { pm_node_flags_t flags = 0; if (!match1(parser, PM_TOKEN_PARENTHESIS_LEFT) && (parser->previous.end[-1] != '!') && (parser->previous.end[-1] != '?')) { - pm_node_t *node = parse_variable(parser); + pm_node_t *node = parse_variable(parser, &parser->previous); if (node != NULL) return node; flags |= PM_CALL_NODE_FLAGS_VARIABLE_CALL; } @@ -17969,7 +17961,7 @@ parse_pattern_primitive(pm_parser_t *parser, pm_constant_id_set_t *captures, pm_ switch (parser->current.type) { case PM_TOKEN_IDENTIFIER: { parser_lex(parser); - pm_node_t *variable = UP(parse_variable(parser)); + pm_node_t *variable = parse_variable(parser, &parser->previous); if (variable == NULL) { pm_parser_err_token_content(parser, &parser->previous, PM_ERR_NO_LOCAL_VARIABLE); diff --git a/test/prism/errors_test.rb b/test/prism/errors_test.rb index 1d5073c9f5..86ae25f7f2 100644 --- a/test/prism/errors_test.rb +++ b/test/prism/errors_test.rb @@ -298,6 +298,19 @@ def test_singleton_method_definition_rejects_setter_name_as_receiver end end + def test_shorthand_hash_labels_resolve_block_parameters + assert_equal [:it_not_allowed_ordinary], Prism.parse("proc { |x| {it:} }").errors.map(&:type) + assert_equal [:it_not_allowed_numbered], Prism.parse("proc { _1; {it:} }").errors.map(&:type) + assert_equal [:numbered_parameter_it], Prism.parse("proc { it; {_2:} }").errors.map(&:type) + + numbered = Prism.parse_statement("proc { {_2:} }").block.parameters + assert_instance_of NumberedParametersNode, numbered + assert_equal 2, numbered.maximum + + assert_nil Prism.parse_statement("proc { {it:} }", version: "3.3.0").block.parameters + assert_nil Prism.parse("it = 1; proc { {it:} }").value.statements.body.last.block.parameters + end + def test_uppercase_shorthand_hash_labels_reject_method_suffixes ["Flag?", "Status!"].each do |name| result = Prism.parse("{ #{name}: }") diff --git a/test/prism/fixtures/3.4/it.txt b/test/prism/fixtures/3.4/it.txt index 5410b01e71..12c758a1d5 100644 --- a/test/prism/fixtures/3.4/it.txt +++ b/test/prism/fixtures/3.4/it.txt @@ -3,3 +3,5 @@ x do end -> { it } + +x { f(it:) } diff --git a/test/prism/ruby/parser_test.rb b/test/prism/ruby/parser_test.rb index 329733d17d..15c69ea05b 100644 --- a/test/prism/ruby/parser_test.rb +++ b/test/prism/ruby/parser_test.rb @@ -229,7 +229,11 @@ def test_it_block_parameter_syntax s(:lvar, :it)), s(:itblock, s(:lambda), :it, - s(:lvar, :it))) + s(:lvar, :it)), + s(:itblock, + s(:send, nil, :x), :it, + s(:send, nil, :f, + s(:kwargs, s(:pair, s(:sym, :it), s(:lvar, :it)))))) end end From ac9e81adc814c676c510bc73a239d49b4bc1627f Mon Sep 17 00:00:00 2001 From: Kevin Newton Date: Wed, 25 Nov 2026 14:00:52 -0500 Subject: [PATCH 03/11] Extract out shebang searching --- include/prism/internal/options.h | 21 +++ src/prism.c | 199 +++++++++++++--------------- test/prism/api/command_line_test.rb | 18 +++ 3 files changed, 131 insertions(+), 107 deletions(-) diff --git a/include/prism/internal/options.h b/include/prism/internal/options.h index 1bdba84ca7..91acd6b1bf 100644 --- a/include/prism/internal/options.h +++ b/include/prism/internal/options.h @@ -172,6 +172,27 @@ struct pm_options_t { bool attach_comments; }; +/* The kind of shebang found on a source line. */ +typedef enum { + PM_OPTIONS_SHEBANG_NONE, + PM_OPTIONS_SHEBANG_COMMENT, /* Only permits an encoding comment on the next line. */ + PM_OPTIONS_SHEBANG_OTHER, + PM_OPTIONS_SHEBANG_RUBY +} pm_options_shebang_type_t; + +/* Whether to search past the first line for a Ruby shebang. */ +static inline bool +pm_options_shebang_search_p(const pm_options_t *options, pm_options_shebang_type_t shebang) { + return ( + (options != NULL) && + (shebang != PM_OPTIONS_SHEBANG_RUBY) && + ( + (options->command_line & PM_OPTIONS_COMMAND_LINE_X) || + (shebang == PM_OPTIONS_SHEBANG_OTHER && options->main_script && !options->scopes_count) + ) + ); +} + /* Free the internal memory associated with the options. */ void pm_options_cleanup(pm_options_t *options); diff --git a/src/prism.c b/src/prism.c index ef908138aa..2d81048a9c 100644 --- a/src/prism.c +++ b/src/prism.c @@ -456,9 +456,6 @@ lex_state_set(pm_parser_t *parser, pm_lex_state_t state) { /** True if the -p command line option was given. */ #define PM_PARSER_COMMAND_LINE_OPTION_P(parser) PM_PARSER_COMMAND_LINE_OPTION(parser, PM_OPTIONS_COMMAND_LINE_P) -/** True if the -x command line option was given. */ -#define PM_PARSER_COMMAND_LINE_OPTION_X(parser) PM_PARSER_COMMAND_LINE_OPTION(parser, PM_OPTIONS_COMMAND_LINE_X) - /******************************************************************************/ /* Diagnostic-related functions */ /******************************************************************************/ @@ -23066,22 +23063,70 @@ parse_program(pm_parser_t *parser) { /* External functions */ /******************************************************************************/ +typedef struct { + pm_string_t switches; + pm_options_shebang_type_t shebang; + bool bom; +} pm_source_line_t; + /** - * Find a nonempty literal in a shebang line, which can contain NUL bytes. + * Find a nonempty literal in a source line, which can contain NUL bytes. */ static const uint8_t * -pm_shebang_find(const uint8_t *line, size_t length, const char *literal, size_t literal_length) { - if (length < literal_length) return NULL; - - /* Search only positions where the whole literal fits. */ - const uint8_t *end = line + (length - literal_length + 1); - for (; (line = memchr(line, (uint8_t) literal[0], (size_t) (end - line))) != NULL; line++) { - if (pm_memequal(line + 1, literal + 1, literal_length - 1)) return line; +pm_source_line_find(const uint8_t *line, size_t length, const char *value, size_t value_length) { + if (length >= value_length) { + const uint8_t *end = line + (length - value_length + 1); + for (; (line = pm_memchr(line, (uint8_t) value[0], (size_t) (end - line))); line++) { + if (pm_memequal(line + 1, value + 1, value_length - 1)) return line; + } } return NULL; } +/* Scan a line of the source and fill in a pm_source_line_t. */ +static void +pm_source_line_scan(pm_source_line_t *line, const uint8_t *start, size_t length, bool first_line) { + *line = (pm_source_line_t) { .shebang = PM_OPTIONS_SHEBANG_NONE }; + if (length > 0 && start[length - 1] == '\n') length--; + + /* A shebang must start at the first byte, so a line with a BOM cannot have one. */ + if (first_line && length >= 3 && pm_memequal(start, "\xef\xbb\xbf", 3)) { + line->bom = true; + return; + } + + /* Figure out if we have a shebang on this line, otherwise return. */ + if (length < 2 || !pm_memequal(start, "#!", 2)) { + return; + } + + /* If we have just #!, the encoding comment can start on the next line. */ + if (length == 2) { + line->shebang = PM_OPTIONS_SHEBANG_COMMENT; + return; + } + + const uint8_t *engine = pm_source_line_find(start, length, "ruby", 4); + if (engine == NULL) { + /* If we have no "ruby" in the shebang, then it is possible we will + * search further into the file for a "ruby" shebang. */ + line->shebang = PM_OPTIONS_SHEBANG_OTHER; + } else { + /* Otherwise we found one, so we also need to check if there are command + * line switches that may impact compilation that we need to call out to + * the embedder to handle. */ + line->shebang = PM_OPTIONS_SHEBANG_RUBY; + + const uint8_t *end = start + length; + const uint8_t *switches = pm_source_line_find(engine + 4, (size_t) (end - (engine + 4)), " -", 2); + + if (switches) { + line->switches = (pm_string_t) { .source = switches + 1, .length = (size_t) (end - (switches + 1)) }; + } + } +} + #ifdef _WIN32 #define pm_parser_warn_shebang_carriage_return(parser, start, length) ((void) 0) #else @@ -23103,15 +23148,12 @@ pm_parser_warn_shebang_carriage_return(pm_parser_t *parser, const uint8_t *start * the shebang_callback option has already been checked for nullability. */ static void -pm_parser_init_shebang(pm_parser_t *parser, const pm_options_t *options, const uint8_t *engine, size_t length) { - const uint8_t *switches = pm_shebang_find(engine, length, " -", 2); - if (switches == NULL) return; - +pm_parser_init_shebang(pm_parser_t *parser, const pm_options_t *options, const pm_string_t *switches) { pm_options_t next_options = *options; options->shebang_callback( &next_options, - switches + 1, - length - ((size_t) (switches - engine)) - 1, + switches->source, + switches->length, options->shebang_callback_data ); @@ -23338,114 +23380,57 @@ pm_parser_init(pm_arena_t *arena, pm_parser_t *parser, const uint8_t *source, si pm_accepts_block_stack_push(parser, true); - // Skip past the UTF-8 BOM if it exists. - if (size >= 3 && source[0] == 0xef && source[1] == 0xbb && source[2] == 0xbf) { + const uint8_t *shebang = source; + const uint8_t *newline = next_newline(source, parser->end - source); + size_t length = (size_t) ((newline ? newline + 1 : parser->end) - source); + pm_source_line_t line; + pm_source_line_scan(&line, source, length, true); + + if (line.bom) { parser->current.end += 3; parser->encoding_comment_start += 3; if (parser->encoding != PM_ENCODING_UTF_8_ENTRY) { parser->encoding = PM_ENCODING_UTF_8_ENTRY; - if (parser->encoding_changed_callback != NULL) parser->encoding_changed_callback(parser); + if (parser->encoding_changed_callback) parser->encoding_changed_callback(parser); } } - // If the -x command line flag is set, or the first shebang of the file does - // not include "ruby", then we'll search for a shebang that does include - // "ruby" and start parsing from there. - bool search_shebang = PM_PARSER_COMMAND_LINE_OPTION_X(parser); - - // If the first two bytes of the source are a shebang, then we will do a bit - // of extra processing. - // - // First, we'll indicate that the encoding comment is at the end of the - // shebang. This means that when a shebang is present the encoding comment - // can begin on the second line. - // - // Second, we will check if the shebang includes "ruby". If it does, then we - // we will start parsing from there. We will also potentially warning the - // user if there is a carriage return at the end of the shebang. We will - // also potentially call the shebang callback if this is the main script to - // allow the caller to parse the shebang and find any command-line options. - // If the shebang does not include "ruby" and this is the main script being - // parsed, then we will start searching the file for a shebang that does - // contain "ruby" as if -x were passed on the command line. - 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] == '!') { - parser->encoding_comment_start = newline != NULL ? newline + 1 : parser->end; - const uint8_t *engine; - - if ((engine = pm_shebang_find(parser->start, length, "ruby", 4)) != NULL) { - if (newline != NULL) { - if (options == NULL || options->main_script) { - pm_parser_warn_shebang_carriage_return(parser, parser->start, length + 1); - } - } - - if (options != NULL && options->main_script && options->shebang_callback != NULL) { - pm_parser_init_shebang(parser, options, engine, length - (size_t) (engine - parser->start)); - } - - search_shebang = false; - } else if (length > 2 && options != NULL && options->main_script && !parser->parsing_eval) { - search_shebang = true; - } + if (line.shebang != PM_OPTIONS_SHEBANG_NONE) { + parser->encoding_comment_start = newline ? newline + 1 : parser->end; } - // Here we're going to find the first shebang that includes "ruby" and start - // parsing from there. - if (search_shebang) { - // If a shebang that includes "ruby" is not found, then we're going to a - // a load error to the list of errors on the parser. - bool found_shebang = false; - - // This is going to point to the start of each line as we check it. - // We'll maintain a moving window looking at each line at they come. - const uint8_t *cursor = parser->start; - - // The newline pointer points to the end of the current line that we're - // considering. If it is NULL, then we're at the end of the file. - const uint8_t *newline = next_newline(cursor, parser->end - cursor); - - while (newline != NULL) { - pm_line_offset_list_append(&parser->metadata_arena, &parser->line_offsets, U32(newline - parser->start + 1)); - - cursor = newline + 1; - newline = next_newline(cursor, parser->end - cursor); - - size_t length = (size_t) ((newline != NULL ? newline : parser->end) - cursor); - if (length > 2 && cursor[0] == '#' && cursor[1] == '!') { - const uint8_t *engine; - if ((engine = pm_shebang_find(cursor, length, "ruby", 4)) != NULL) { - found_shebang = true; - - if (newline != NULL) { - pm_parser_warn_shebang_carriage_return(parser, cursor, length + 1); - parser->encoding_comment_start = newline + 1; - } - - if (options != NULL && options->shebang_callback != NULL) { - pm_parser_init_shebang(parser, options, engine, length - (size_t) (engine - cursor)); - } - - break; - } - } + if (pm_options_shebang_search_p(options, line.shebang)) { + while (line.shebang != PM_OPTIONS_SHEBANG_RUBY && newline) { + shebang = newline + 1; + pm_line_offset_list_append(&parser->metadata_arena, &parser->line_offsets, U32(shebang - source)); + newline = next_newline(shebang, parser->end - shebang); + length = (size_t) ((newline ? newline + 1 : parser->end) - shebang); + pm_source_line_scan(&line, shebang, length, false); } - if (found_shebang) { - parser->previous = (pm_token_t) { .type = PM_TOKEN_EOF, .start = cursor, .end = cursor }; - parser->current = (pm_token_t) { .type = PM_TOKEN_EOF, .start = cursor, .end = cursor }; + if (line.shebang == PM_OPTIONS_SHEBANG_RUBY) { + if (newline) parser->encoding_comment_start = newline + 1; + parser->current = (pm_token_t) { .type = PM_TOKEN_EOF, .start = shebang, .end = shebang }; + parser->previous = parser->current; } else { pm_parser_err(parser, 0, 0, PM_ERR_SCRIPT_NOT_FOUND); pm_line_offset_list_clear(&parser->line_offsets); } } - // The encoding comment can start after any amount of inline whitespace, so - // here we'll advance it to the first non-inline-whitespace character so - // that it is ready for future comparisons. + if (line.shebang == PM_OPTIONS_SHEBANG_RUBY && (shebang != source || !options || options->main_script)) { + if (newline) pm_parser_warn_shebang_carriage_return(parser, shebang, length); + if (line.switches.length && options && options->shebang_callback) { + pm_parser_init_shebang(parser, options, &line.switches); + } + } + + /* + * The encoding comment can start after any amount of inline whitespace, so + * here we'll advance it to the first non-inline-whitespace character so + * that it is ready for future comparisons. + */ parser->encoding_comment_start += pm_strspn_inline_whitespace(parser->encoding_comment_start, parser->end - parser->encoding_comment_start); } diff --git a/test/prism/api/command_line_test.rb b/test/prism/api/command_line_test.rb index 3266e76eb7..f420583074 100644 --- a/test/prism/api/command_line_test.rb +++ b/test/prism/api/command_line_test.rb @@ -116,6 +116,24 @@ def test_command_line_x_implicit_fail assert_equal :load, result.errors.first.level end + def test_bom_before_shebang_in_main_script + result = Prism.parse("\uFEFF#!ruby\n# encoding: US-ASCII\n1\n", main_script: true) + + assert_predicate result, :success? + assert_equal Encoding::UTF_8, result.encoding + assert_equal 1, result.statement.value + end + + def test_command_line_x_skips_bom_prefixed_shebang + source = "\uFEFF#!ruby -w\n1\n" + result = Prism.parse(source, command_line: "x") + assert_equal [:script_not_found], result.errors.map(&:type) + + result = Prism.parse(source + "#!ruby\n2\n", command_line: "x") + assert_predicate result, :success? + assert_equal [2], result.value.statements.body.map(&:value) + end + def test_command_line_x_explicit_fail result = Prism.parse(<<~RUBY, command_line: "x") exit 1 From d11ea10e82161877f70e2f10e5c3bb49e970d311 Mon Sep 17 00:00:00 2001 From: Kevin Newton Date: Wed, 25 Nov 2026 14:14:41 -0500 Subject: [PATCH 04/11] Handle searching for shebang properly in parse_stream --- include/prism/internal/source.h | 18 +++-- src/prism.c | 68 +--------------- src/source.c | 117 ++++++++++++++++++++-------- test/prism/api/parse_stream_test.rb | 70 +++++++++++++++++ 4 files changed, 171 insertions(+), 102 deletions(-) diff --git a/include/prism/internal/source.h b/include/prism/internal/source.h index b3c2b55be3..6f5bac458c 100644 --- a/include/prism/internal/source.h +++ b/include/prism/internal/source.h @@ -3,6 +3,8 @@ #include "prism/source.h" #include "prism/buffer.h" +#include "prism/internal/options.h" +#include "prism/stringy.h" #include @@ -58,11 +60,17 @@ struct pm_source_t { } stream; }; -/* - * Read from a stream into the source's internal buffer. This is used by - * pm_parse_stream to incrementally read the source. - */ -bool pm_source_stream_read(pm_source_t *source); +typedef struct { + pm_string_t switches; + pm_options_shebang_type_t shebang; + bool bom; + bool __end__; +} pm_source_line_t; + +void pm_source_line_scan(pm_source_line_t *line, const uint8_t *start, size_t length, bool first_line); + +/* Read through the next possible __END__ after the script begins, or to EOF. */ +bool pm_source_stream_read(pm_source_t *source, const pm_options_t *options); /* * Returns whether the stream source has reached EOF. diff --git a/src/prism.c b/src/prism.c index 2d81048a9c..fbbf828e43 100644 --- a/src/prism.c +++ b/src/prism.c @@ -23063,70 +23063,6 @@ parse_program(pm_parser_t *parser) { /* External functions */ /******************************************************************************/ -typedef struct { - pm_string_t switches; - pm_options_shebang_type_t shebang; - bool bom; -} pm_source_line_t; - -/** - * Find a nonempty literal in a source line, which can contain NUL bytes. - */ -static const uint8_t * -pm_source_line_find(const uint8_t *line, size_t length, const char *value, size_t value_length) { - if (length >= value_length) { - const uint8_t *end = line + (length - value_length + 1); - for (; (line = pm_memchr(line, (uint8_t) value[0], (size_t) (end - line))); line++) { - if (pm_memequal(line + 1, value + 1, value_length - 1)) return line; - } - } - - return NULL; -} - -/* Scan a line of the source and fill in a pm_source_line_t. */ -static void -pm_source_line_scan(pm_source_line_t *line, const uint8_t *start, size_t length, bool first_line) { - *line = (pm_source_line_t) { .shebang = PM_OPTIONS_SHEBANG_NONE }; - if (length > 0 && start[length - 1] == '\n') length--; - - /* A shebang must start at the first byte, so a line with a BOM cannot have one. */ - if (first_line && length >= 3 && pm_memequal(start, "\xef\xbb\xbf", 3)) { - line->bom = true; - return; - } - - /* Figure out if we have a shebang on this line, otherwise return. */ - if (length < 2 || !pm_memequal(start, "#!", 2)) { - return; - } - - /* If we have just #!, the encoding comment can start on the next line. */ - if (length == 2) { - line->shebang = PM_OPTIONS_SHEBANG_COMMENT; - return; - } - - const uint8_t *engine = pm_source_line_find(start, length, "ruby", 4); - if (engine == NULL) { - /* If we have no "ruby" in the shebang, then it is possible we will - * search further into the file for a "ruby" shebang. */ - line->shebang = PM_OPTIONS_SHEBANG_OTHER; - } else { - /* Otherwise we found one, so we also need to check if there are command - * line switches that may impact compilation that we need to call out to - * the embedder to handle. */ - line->shebang = PM_OPTIONS_SHEBANG_RUBY; - - const uint8_t *end = start + length; - const uint8_t *switches = pm_source_line_find(engine + 4, (size_t) (end - (engine + 4)), " -", 2); - - if (switches) { - line->switches = (pm_string_t) { .source = switches + 1, .length = (size_t) (end - (switches + 1)) }; - } - } -} - #ifdef _WIN32 #define pm_parser_warn_shebang_carriage_return(parser, start, length) ((void) 0) #else @@ -23652,7 +23588,7 @@ pm_parse(pm_parser_t *parser) { */ pm_node_t * pm_parse_stream(pm_parser_t **parser, pm_arena_t *arena, pm_source_t *source, const pm_options_t *options) { - bool eof = pm_source_stream_read(source); + bool eof = pm_source_stream_read(source, options); pm_parser_t *tmp = pm_parser_new(arena, pm_source_source(source), pm_source_length(source), options); pm_node_t *node = pm_parse(tmp); @@ -23660,7 +23596,7 @@ pm_parse_stream(pm_parser_t **parser, pm_arena_t *arena, pm_source_t *source, co /* The stream reader stops at possible markers. Only the lexer knows if * the marker is real, even when the preceding source has syntax errors. */ while (!eof && tmp->data_loc.length == 0) { - eof = pm_source_stream_read(source); + eof = pm_source_stream_read(source, options); pm_parser_free(tmp); pm_arena_cleanup(arena); diff --git a/src/source.c b/src/source.c index 722a931158..6943bb9737 100644 --- a/src/source.c +++ b/src/source.c @@ -2,6 +2,7 @@ #include "prism/internal/allocator.h" #include "prism/internal/buffer.h" +#include "prism/internal/memchr.h" #include "prism/internal/memequal.h" #include "prism/internal/oom.h" @@ -357,6 +358,67 @@ pm_source_stream_new(void *stream, pm_source_stream_fgets_t *fgets, pm_source_st return source; } +/** + * Find a nonempty literal in a source line, which can contain NUL bytes. + */ +static const uint8_t * +pm_source_line_find(const uint8_t *line, size_t length, const char *value, size_t value_length) { + if (length >= value_length) { + const uint8_t *end = line + (length - value_length + 1); + for (; (line = pm_memchr(line, (uint8_t) value[0], (size_t) (end - line))); line++) { + if (pm_memequal(line + 1, value + 1, value_length - 1)) return line; + } + } + + return NULL; +} + +/* Scan a line of the source and fill in a pm_source_line_t. */ +void +pm_source_line_scan(pm_source_line_t *line, const uint8_t *start, size_t length, bool first_line) { + *line = (pm_source_line_t) { .shebang = PM_OPTIONS_SHEBANG_NONE }; + bool newline = length > 0 && start[length - 1] == '\n'; + if (newline) length--; + + /* A BOM can precede __END__, but a shebang must start at the first byte. */ + if (first_line && length >= 3 && pm_memequal(start, "\xef\xbb\xbf", 3)) { + line->bom = true; + start += 3; + length -= 3; + } + + if (line->bom || length < 2 || !pm_memequal(start, "#!", 2)) { + if (newline && length > 0 && start[length - 1] == '\r') length--; + line->__end__ = length == 7 && pm_memequal(start, "__END__", 7); + return; + } + + /* If we have just #!, the encoding comment can start on the next line. */ + if (length == 2) { + line->shebang = PM_OPTIONS_SHEBANG_COMMENT; + return; + } + + const uint8_t *engine = pm_source_line_find(start, length, "ruby", 4); + if (engine == NULL) { + /* If we have no "ruby" in the shebang, then it is possible we will + * search further into the file for a "ruby" shebang. */ + line->shebang = PM_OPTIONS_SHEBANG_OTHER; + } else { + /* Otherwise we found one, so we also need to check if there are command + * line switches that may impact compilation that we need to call out to + * the embedder to handle. */ + line->shebang = PM_OPTIONS_SHEBANG_RUBY; + + const uint8_t *end = start + length; + const uint8_t *switches = pm_source_line_find(engine + 4, (size_t) (end - (engine + 4)), " -", 2); + + if (switches) { + line->switches = (pm_string_t) { .source = switches + 1, .length = (size_t) (end - (switches + 1)) }; + } + } +} + /** * Read from the stream into the source's internal buffer until __END__ is * encountered or EOF is reached. Updates the source pointer and length. @@ -364,8 +426,12 @@ pm_source_stream_new(void *stream, pm_source_stream_fgets_t *fgets, pm_source_st * Returns true if EOF was reached, false if __END__ was encountered. */ bool -pm_source_stream_read(pm_source_t *source) { +pm_source_stream_read(pm_source_t *source, const pm_options_t *options) { pm_buffer_t *buffer = source->stream.buffer; + size_t line_start = buffer->length; + + bool eof = true; + bool search_shebang = false; #define LINE_SIZE 4096 char line[LINE_SIZE]; @@ -420,34 +486,23 @@ pm_source_stream_read(pm_source_t *source) { continue; } - /* - * Check if the line matches the __END__ marker. If it does, then stop - * reading and return false. In most circumstances, this means we should - * stop reading from the stream so that the DATA constant can pick it - * up. - */ - switch (length) { - case 7: - if (pm_memequal(line, "__END__", 7)) { - source->source = (const uint8_t *) pm_buffer_value(buffer); - source->length = pm_buffer_length(buffer); - return false; - } - break; - case 8: - if (pm_memequal(line, "__END__\n", 8)) { - source->source = (const uint8_t *) pm_buffer_value(buffer); - source->length = pm_buffer_length(buffer); - return false; - } - break; - case 9: - if (pm_memequal(line, "__END__\r\n", 9)) { - source->source = (const uint8_t *) pm_buffer_value(buffer); - source->length = pm_buffer_length(buffer); - return false; - } - break; + /* Match complete lines, including lines split across multiple reads. */ + const uint8_t *start = (const uint8_t *) buffer->value + line_start; + bool first_line = line_start == 0; + + pm_source_line_t info; + pm_source_line_scan(&info, start, buffer->length - line_start, first_line); + line_start = buffer->length; + + if (first_line) { + search_shebang = pm_options_shebang_search_p(options, info.shebang); + } else if (info.shebang == PM_OPTIONS_SHEBANG_RUBY) { + search_shebang = false; + } + + if (info.__end__ && !search_shebang) { + eof = false; + break; } /* @@ -463,10 +518,10 @@ pm_source_stream_read(pm_source_t *source) { #undef LINE_FILL #undef LINE_SIZE - source->stream.eof = true; + source->stream.eof = eof; source->source = (const uint8_t *) pm_buffer_value(buffer); source->length = pm_buffer_length(buffer); - return true; + return eof; } /** diff --git a/test/prism/api/parse_stream_test.rb b/test/prism/api/parse_stream_test.rb index 785aa79d65..5f0fa8d276 100644 --- a/test/prism/api/parse_stream_test.rb +++ b/test/prism/api/parse_stream_test.rb @@ -53,6 +53,76 @@ def test___END___after_syntax_error assert_equal "data\n", io.read end + def test___END___before_ruby_shebang + [["preamble", { command_line: "x" }], ["#!/bin/sh", { main_script: true }]].each do |first_line, options| + io = StringIO.new("#{first_line}\n__END__\n__END__\n#!/usr/bin/env ruby\n42\n__END__\ndata\n") + result = Prism.parse_stream(io, **options) + + assert_predicate result, :success? + assert_equal 42, result.statement.value + assert_equal 5, result.statement.location.start_line + assert_equal 6, result.data_loc.start_line + assert_equal "data\n", io.read + end + end + + def test_ruby_shebang_spanning_stream_reads + io = StringIO.new("__END__\n#!" + (" " * 4096) + "ruby\n1\n__END__\ndata") + result = Prism.parse_stream(io, command_line: "x") + + assert_predicate result, :success? + assert_equal 1, result.statement.value + assert_equal "data", io.read + end + + def test___END___without_ruby_shebang + io = StringIO.new("__END__\nno Ruby script here\n") + result = Prism.parse_stream(io, command_line: "x") + + assert_equal [:script_not_found], result.errors.map(&:type) + assert_predicate io, :eof? + end + + def test_shebang_in_data_remains_unread + [ + ["#!ruby", { command_line: "x" }], + ["#!", { main_script: true }], + ["\uFEFF#!ruby", { main_script: true }], + ["\uFEFF#!/bin/sh", { main_script: true }], + ["#!/bin/sh", { main_script: true, scopes: [[]] }] + ].each do |first_line, options| + io = StringIO.new("#{first_line}\n1\n__END__\n#!ruby\n2\n") + result = Prism.parse_stream(io, **options) + + assert_predicate result, :success? + assert_equal 1, result.statement.value + assert_equal 1, Prism.parse(io.string, **options).statement.value + assert_equal "#!ruby\n2\n", io.read + end + end + + def test_command_line_x_skips_bom_prefixed_shebang + ["#!ruby", "#!ruby "].each do |first_line| + source = "\uFEFF#{first_line}\n1\n__END__\n#!ruby\n2\n__END__\ndata\n" + io = StringIO.new(source) + result = Prism.parse_stream(io, command_line: "x") + + assert_predicate result, :success? + assert_equal 2, result.statement.value + assert_equal 2, Prism.parse(source, command_line: "x").statement.value + assert_equal "data\n", io.read + end + end + + def test_initial___END___after_utf8_bom + io = StringIO.new("\uFEFF__END__\r\ndata\n") + result = Prism.parse_stream(io) + + assert_equal 3, result.data_loc.start_offset + assert_equal "__END__\r\n", result.data_loc.slice + assert_equal "data\n", io.read + end + def test_false___END___in_percent_string io = StringIO.new("p(%\n__END__\n+ %q{hi})\n") result = Prism.parse_stream(io) From 3f010a738604a0238c19f9862291e7539788f696 Mon Sep 17 00:00:00 2001 From: Kevin Newton Date: Wed, 25 Nov 2026 14:33:52 -0500 Subject: [PATCH 05/11] Match unterminated quoted encoding name behavior --- src/prism.c | 4 ++++ test/prism/magic_comment_test.rb | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/prism.c b/src/prism.c index fbbf828e43..72a415bd6a 100644 --- a/src/prism.c +++ b/src/prism.c @@ -7627,6 +7627,10 @@ static PRISM_INLINE bool parser_lex_magic_comment(pm_parser_t *parser, bool semantic_token_seen) { const uint8_t *start = parser->current.start + 1; const uint8_t *end = parser->current.end; + + /* The comment token ends at LF or EOF. An unterminated quoted value + * includes the LF. */ + if (end < parser->end) end++; if (end - start <= 7) return false; const uint8_t *cursor; diff --git a/test/prism/magic_comment_test.rb b/test/prism/magic_comment_test.rb index 9d7d34054f..3a73e878cf 100644 --- a/test/prism/magic_comment_test.rb +++ b/test/prism/magic_comment_test.rb @@ -131,6 +131,23 @@ def test_encoding_fallback_is_not_used_for_unrecognized_keys end end + def test_unterminated_quoted_encoding + comment = '# encoding: "binary' + + ["\n", "\r\n"].each do |newline| + result = Prism.parse("#{comment}#{newline}__ENCODING__") + assert_equal [:invalid_encoding_magic_comment], result.errors.map(&:type) + assert_equal "binary#{newline}", result.errors.first.location.slice + assert_equal Encoding::UTF_8, result.encoding + end + + [comment, "#{comment}\"\n"].each do |source| + result = Prism.parse(source) + assert_predicate result, :success? + assert_equal Encoding::BINARY, result.encoding + end + end + def test_encoding_after_leading_delimiters ['"', "'", ";", ":"].each do |delimiter| ["coding", "encoding"].each do |key| From 3f532b9d5be6cbbeb279840db1fe2c72c1ce1c63 Mon Sep 17 00:00:00 2001 From: Kevin Newton Date: Wed, 25 Nov 2026 14:50:30 -0500 Subject: [PATCH 06/11] Check encoding compatibility within %W and %I elements --- src/prism.c | 123 ++++++-------------- test/prism/encoding/string_encoding_test.rb | 25 ++++ 2 files changed, 63 insertions(+), 85 deletions(-) diff --git a/src/prism.c b/src/prism.c index 72a415bd6a..00c4b06362 100644 --- a/src/prism.c +++ b/src/prism.c @@ -6791,6 +6791,9 @@ pm_symbol_node_to_string_node(pm_parser_t *parser, pm_symbol_node_t *node) { break; } + if (PM_NODE_FLAG_P(node, PM_SYMBOL_FLAGS_FORCED_UTF8_ENCODING)) flags |= PM_STRING_FLAGS_FORCED_UTF8_ENCODING; + if (PM_NODE_FLAG_P(node, PM_SYMBOL_FLAGS_FORCED_BINARY_ENCODING)) flags |= PM_STRING_FLAGS_FORCED_BINARY_ENCODING; + pm_string_node_t *new_node = pm_string_node_new( parser->arena, ++parser->node_id, @@ -17139,6 +17142,13 @@ pm_string_parts_to_string(pm_parser_t *parser, const pm_token_t *opening, pm_str return node; } +static pm_node_t * +pm_string_parts_to_symbol(pm_parser_t *parser, const pm_token_t *opening, pm_string_parts_t *parts, const pm_token_t *closing) { + pm_node_t *node = UP(pm_interpolated_symbol_node_create(parser, opening, &parts->list, closing)); + if (parts->invalid_encoding) pm_node_flag_unset(node, PM_NODE_FLAG_STATIC_LITERAL); + return node; +} + /** * Parse a set of strings that could be concatenated together. */ @@ -17293,8 +17303,7 @@ parse_strings(pm_parser_t *parser, pm_node_t *current, bool accepts_label, uint1 } if (accept1(parser, PM_TOKEN_LABEL_END)) { - node = UP(pm_interpolated_symbol_node_create(parser, &opening, &parts.list, &parser->previous)); - if (parts.invalid_encoding) pm_node_flag_unset(node, PM_NODE_FLAG_STATIC_LITERAL); + node = pm_string_parts_to_symbol(parser, &opening, &parts, &parser->previous); if (!label_allowed) pm_parser_err_node(parser, node, PM_ERR_UNEXPECTED_LABEL); } else if (match1(parser, PM_TOKEN_EOF)) { pm_parser_err_token(parser, &opening, PM_ERR_STRING_INTERPOLATED_TERM); @@ -20548,7 +20557,7 @@ parse_interpolated_symbol_array(pm_parser_t *parser, uint16_t depth) { * once it needs more than one part, the open list of parts of an * interpolated symbol. */ pm_node_t *current = NULL; - pm_node_list_t parts = { 0 }; + pm_string_parts_t parts = { 0 }; while (!match2(parser, PM_TOKEN_STRING_END, PM_TOKEN_EOF)) { switch (parser->current.type) { @@ -20559,9 +20568,9 @@ 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 element. */ - if (parts.size > 0) { - pm_array_elements_append(parser, &elements, UP(pm_interpolated_symbol_node_create(parser, NULL, &parts, NULL))); - parts = (pm_node_list_t) { 0 }; + if (parts.list.size > 0) { + pm_array_elements_append(parser, &elements, pm_string_parts_to_symbol(parser, NULL, &parts, NULL)); + parts = (pm_string_parts_t) { 0 }; } else if (current != NULL) { parse_interpolated_symbol_array_element(parser, &elements, current); current = NULL; @@ -20570,56 +20579,23 @@ parse_interpolated_symbol_array(pm_parser_t *parser, uint16_t depth) { parser_lex(parser); break; } - case PM_TOKEN_STRING_CONTENT: { - if (parts.size > 0) { - /* If we hit string content and the element is already - * interpolated, then we need to append the string content - * to its parts. */ - pm_node_t *string = UP(pm_string_node_create_current_string(parser, NULL, &parser->current, NULL)); - parser_lex(parser); - - pm_node_list_open_append(&parser->node_chunks, &parts, string); - } else if (current == NULL) { - /* If we hit content and there is no element yet, then this - * is the first string content we've seen. In that case - * we're going to create a new symbol node for it. */ + case PM_TOKEN_STRING_CONTENT: + /* A single literal part can use a plain symbol node. */ + if (parts.list.size == 0 && current == NULL) { current = UP(pm_symbol_node_create_current_string(parser, NULL, &parser->current, NULL)); parser_lex(parser); - } else { - /* If we hit string content and the element is a symbol - * node, then we need to turn the element into the parts of - * an interpolated symbol and add the string content to - * them. */ - pm_symbol_node_t *cast = (pm_symbol_node_t *) current; - pm_token_t content = { - .type = PM_TOKEN_STRING_CONTENT, - .start = parser->start + cast->content_loc.start, - .end = parser->start + cast->content_loc.start + cast->content_loc.length - }; - - pm_node_t *first_string = UP(pm_string_node_create_unescaped(parser, NULL, &content, NULL, &cast->unescaped)); - pm_node_t *second_string = UP(pm_string_node_create_current_string(parser, NULL, &parser->current, NULL)); - parser_lex(parser); - - pm_node_list_open_append(&parser->node_chunks, &parts, first_string); - pm_node_list_open_append(&parser->node_chunks, &parts, second_string); - current = NULL; + break; } - - break; - } + PRISM_FALLTHROUGH case PM_TOKEN_EMBVAR: case PM_TOKEN_EMBEXPR_BEGIN: { - /* If we hit an embedded variable or expression and the element - * is a symbol node, then we'll turn the element into the parts - * of an interpolated symbol, starting with its string. */ if (current != NULL) { - pm_node_list_open_append(&parser->node_chunks, &parts, UP(pm_symbol_node_to_string_node(parser, (pm_symbol_node_t *) current))); + pm_string_parts_append(parser, &parts, UP(pm_symbol_node_to_string_node(parser, (pm_symbol_node_t *) current))); current = NULL; } pm_node_t *part = parse_string_part(parser, (uint16_t) (depth + 1)); - pm_node_list_open_append(&parser->node_chunks, &parts, part); + pm_string_parts_append(parser, &parts, part); break; } default: @@ -20630,8 +20606,8 @@ parse_interpolated_symbol_array(pm_parser_t *parser, uint16_t depth) { } /* If we have an element, then we need to append it to the list. */ - if (parts.size > 0) { - pm_array_elements_append(parser, &elements, UP(pm_interpolated_symbol_node_create(parser, NULL, &parts, NULL))); + if (parts.list.size > 0) { + pm_array_elements_append(parser, &elements, pm_string_parts_to_symbol(parser, NULL, &parts, NULL)); } else if (current != NULL) { parse_interpolated_symbol_array_element(parser, &elements, current); } @@ -20715,7 +20691,7 @@ parse_interpolated_string_array(pm_parser_t *parser, uint16_t depth) { * once it needs more than one part, the open list of parts of an * interpolated string. */ pm_node_t *current = NULL; - pm_node_list_t parts = { 0 }; + pm_string_parts_t parts = { 0 }; while (!match2(parser, PM_TOKEN_STRING_END, PM_TOKEN_EOF)) { switch (parser->current.type) { @@ -20726,9 +20702,9 @@ parse_interpolated_string_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 element. */ - if (parts.size > 0) { - pm_array_elements_append(parser, &elements, UP(pm_interpolated_string_node_create(parser, NULL, &parts, NULL))); - parts = (pm_node_list_t) { 0 }; + if (parts.list.size > 0) { + pm_array_elements_append(parser, &elements, pm_string_parts_to_string(parser, NULL, &parts, NULL)); + parts = (pm_string_parts_t) { 0 }; } else if (current != NULL) { pm_array_elements_append(parser, &elements, current); current = NULL; @@ -20737,45 +20713,22 @@ parse_interpolated_string_array(pm_parser_t *parser, uint16_t depth) { parser_lex(parser); break; } - case PM_TOKEN_STRING_CONTENT: { - pm_node_t *string = UP(pm_string_node_create_current_string(parser, NULL, &parser->current, NULL)); - pm_node_flag_set(string, parse_unescaped_encoding(parser, parser->explicit_encoding)); - parser_lex(parser); - - if (parts.size > 0) { - /* If we hit string content and the element is already - * interpolated, then we need to append the string content - * to its parts. */ - pm_node_list_open_append(&parser->node_chunks, &parts, string); - } else if (current == NULL) { - /* If we hit content and there is no element yet, then this - * is the first string content we've seen, and it becomes - * the element. */ - current = string; - } else { - /* If we hit string content and the element is a string - * node, then we need to turn the element into the parts of - * an interpolated string and add the string content to - * them. */ - pm_node_list_open_append(&parser->node_chunks, &parts, current); - pm_node_list_open_append(&parser->node_chunks, &parts, string); - current = NULL; + case PM_TOKEN_STRING_CONTENT: + /* A single literal part can use a plain string node. */ + if (parts.list.size == 0 && current == NULL) { + current = parse_string_part(parser, (uint16_t) (depth + 1)); + break; } - - break; - } + PRISM_FALLTHROUGH case PM_TOKEN_EMBVAR: case PM_TOKEN_EMBEXPR_BEGIN: { - /* If we hit an embedded variable or expression and the element - * is a string node, then we'll turn the element into the parts - * of an interpolated string, starting with that string. */ if (current != NULL) { - pm_node_list_open_append(&parser->node_chunks, &parts, current); + pm_string_parts_append(parser, &parts, current); current = NULL; } pm_node_t *part = parse_string_part(parser, (uint16_t) (depth + 1)); - pm_node_list_open_append(&parser->node_chunks, &parts, part); + pm_string_parts_append(parser, &parts, part); break; } default: @@ -20786,8 +20739,8 @@ parse_interpolated_string_array(pm_parser_t *parser, uint16_t depth) { } /* If we have an element, then we need to append it to the list. */ - if (parts.size > 0) { - pm_array_elements_append(parser, &elements, UP(pm_interpolated_string_node_create(parser, NULL, &parts, NULL))); + if (parts.list.size > 0) { + pm_array_elements_append(parser, &elements, pm_string_parts_to_string(parser, NULL, &parts, NULL)); } else if (current != NULL) { pm_array_elements_append(parser, &elements, current); } diff --git a/test/prism/encoding/string_encoding_test.rb b/test/prism/encoding/string_encoding_test.rb index 8854b18930..ce7e5c269f 100644 --- a/test/prism/encoding/string_encoding_test.rb +++ b/test/prism/encoding/string_encoding_test.rb @@ -130,6 +130,31 @@ def test_interpolation_encoding_errors_in_source_order assert_equal ["string literal encodings differ (UTF-8 / ASCII-8BIT)", "string literal encodings differ (ASCII-8BIT / UTF-8)"], errors.map(&:message) end + def test_incompatible_encodings_within_word_and_symbol_array_elements + %w[W I].each do |kind| + [ + ['#{"\u3042"}' + "\xD4".b, "UTF-8 / ASCII-8BIT", "\xD4".b], + ['\u3042#{"\xD4"} next', "UTF-8 / ASCII-8BIT", '#{"\xD4"}'], + ['#{"\xD4"}\u3042', "ASCII-8BIT / UTF-8", '\u3042'] + ].each do |words, encodings, location| + source = "%#{kind}[#{words}]" + result = Prism.parse(source, encoding: "ASCII-8BIT") + assert_equal ["string literal encodings differ (#{encodings})"], result.errors.map(&:message), source + assert_equal location, result.errors.first.location.slice + refute_predicate result.statement.elements.first, :static_literal? + end + end + end + + def test_independent_encodings_in_word_and_symbol_arrays + %w[W I].each do |kind| + ['#{"\u3042"}a \xD4#{"\xD4"}', '\u3042#{x}\xD4'].each do |words| + source = "%#{kind}[#{words}]" + assert_predicate Prism.parse(source, encoding: "ASCII-8BIT"), :success?, source + end + end + end + def test_dynamic_interpolation_separates_literal_encodings ['"\u3042#{; "\xD4"}"', '"\u3042#{x}#{"\xD4"}"', '"\u3042#$x#{"\xD4"}"'].each do |source| assert_predicate Prism.parse(source, encoding: "ASCII-8BIT"), :success?, source From 361cd13244d4354e0726aee5b4ca9624fad61df8 Mon Sep 17 00:00:00 2001 From: Kevin Newton Date: Wed, 25 Nov 2026 14:54:56 -0500 Subject: [PATCH 07/11] Disallow infix operators after interpolated labels --- src/prism.c | 1 + test/prism/errors/infix_after_label.txt | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/src/prism.c b/src/prism.c index 00c4b06362..4caded911a 100644 --- a/src/prism.c +++ b/src/prism.c @@ -22745,6 +22745,7 @@ parse_expression(pm_parser_t *parser, pm_binding_power_t binding_power, uint8_t } break; case PM_SYMBOL_NODE: + case PM_INTERPOLATED_SYMBOL_NODE: if (pm_symbol_node_label_p(parser, left.node)) { return left; } diff --git a/test/prism/errors/infix_after_label.txt b/test/prism/errors/infix_after_label.txt index f02a29470f..5333040fb6 100644 --- a/test/prism/errors/infix_after_label.txt +++ b/test/prism/errors/infix_after_label.txt @@ -4,3 +4,8 @@ ^ unexpected '}', expecting end-of-input ^ unexpected '}', ignoring it +f "#{key}": < 2 + ^ unexpected '<'; expected a value in the hash literal + ^ unexpected '<', expecting end-of-input + ^ unexpected '<', ignoring it + From da77eb28bf057faaa27c2d9c549bbdee5a0230a7 Mon Sep 17 00:00:00 2001 From: Kevin Newton Date: Wed, 25 Nov 2026 15:28:25 -0500 Subject: [PATCH 08/11] Make sure unterminated errors do not point into DATA --- include/prism/internal/parser.h | 5 +++- src/parser.c | 5 ++-- src/prism.c | 31 ++++++++++----------- test/prism/api/parse_stream_test.rb | 43 +++++++++++++++++++++++++++++ 4 files changed, 63 insertions(+), 21 deletions(-) diff --git a/include/prism/internal/parser.h b/include/prism/internal/parser.h index a7f661f999..94d94a6f9e 100644 --- a/include/prism/internal/parser.h +++ b/include/prism/internal/parser.h @@ -751,9 +751,12 @@ struct pm_parser_t { /* The pointer to the start of the source. */ const uint8_t *start; - /* The pointer to the end of the source. */ + /* The end of the full input, including the data section. */ const uint8_t *end; + /* The end of the Ruby code, at the start of the __END__ marker if present. */ + const uint8_t *source_end; + /* The previous token we were considering. */ pm_token_t previous; diff --git a/src/parser.c b/src/parser.c index 69dca45886..fb1a91b443 100644 --- a/src/parser.c +++ b/src/parser.c @@ -154,9 +154,8 @@ uint64_t pm_parser_checksum(const pm_parser_t *parser) { const uint8_t *end = parser->end; - if (parser->data_loc.length != 0) { - const uint8_t *cursor = parser->start + parser->data_loc.start; - const uint8_t *newline = pm_memchr(cursor, '\n', (size_t) (end - cursor)); + if (parser->source_end != end) { + const uint8_t *newline = pm_memchr(parser->source_end, '\n', (size_t) (end - parser->source_end)); if (newline != NULL) end = newline + 1; } diff --git a/src/prism.c b/src/prism.c index 4caded911a..8b4be0e1f6 100644 --- a/src/prism.c +++ b/src/prism.c @@ -10239,7 +10239,7 @@ parser_lex(pm_parser_t *parser) { // We'll check if we're at the end of the file. If we are, then we // need to return the EOF token. - if (parser->current.end >= parser->end) { + if (parser->current.end >= parser->source_end) { lex_eof: // We may be missing closing tokens. We should pop modes one by one // to do the appropriate cleanup like moving next_start for heredocs. @@ -11558,7 +11558,9 @@ parser_lex(pm_parser_t *parser) { parser->data_loc.start = PM_TOKEN_START(parser, &parser->current); parser->data_loc.length = PM_TOKEN_LENGTH(&parser->current); - parser->current.start = parser->current.end; + /* Recover at the end of the Ruby code, before the marker. */ + parser->source_end = parser->current.start; + parser->current.end = parser->source_end; goto lex_eof; } @@ -11635,7 +11637,7 @@ parser_lex(pm_parser_t *parser) { // We'll check if we're at the end of the file. If we are, then we // need to return the EOF token. - if (parser->current.end >= parser->end) { + if (parser->current.end >= parser->source_end) { LEX(PM_TOKEN_EOF); } @@ -11855,7 +11857,7 @@ parser_lex(pm_parser_t *parser) { // We'll check if we're at the end of the file. If we are, then we // need to return the EOF token. - if (parser->current.end >= parser->end) { + if (parser->current.end >= parser->source_end) { LEX(PM_TOKEN_EOF); } @@ -12125,7 +12127,7 @@ parser_lex(pm_parser_t *parser) { // We'll check if we're at the end of the file. If we are, then we need to // return the EOF token. - if (parser->current.end >= parser->end) { + if (parser->current.end >= parser->source_end) { LEX(PM_TOKEN_EOF); } @@ -12391,7 +12393,7 @@ parser_lex(pm_parser_t *parser) { // will add an error (because we weren't able to find the // terminator) but still continue parsing so that content after the // declaration of the heredoc can be parsed. - if (parser->current.end >= parser->end) { + if (parser->current.end >= parser->source_end) { pm_parser_err_heredoc_term(parser, heredoc_lex_mode->ident_start, heredoc_lex_mode->ident_length); parser->next_start = lex_mode->as.heredoc.next_start; parser->heredoc_end = parser->current.end; @@ -12689,7 +12691,8 @@ parser_lex(pm_parser_t *parser) { } token_cursor = parser->current.end; - breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, mode); + /* A continued heredoc can resume at __END__ within this token. */ + breakpoint = pm_strpbrk(parser, token_cursor, breakpoints, parser->source_end - token_cursor, mode); break; } case '#': { @@ -12718,15 +12721,8 @@ parser_lex(pm_parser_t *parser) { was_line_continuation = false; } - if (parser->current.end > parser->current.start) { - parser->current.end = parser->end; - pm_token_buffer_flush(parser, token_cursor); - LEX(PM_TOKEN_STRING_CONTENT); - } - - // If we've hit the end of the string, then this is an unterminated - // heredoc. In that case we'll return a string content token. - parser->current.end = parser->end; + /* Return the remaining content of the unterminated heredoc. */ + parser->current.end = parser->source_end; pm_token_buffer_flush(parser, token_cursor); LEX(PM_TOKEN_STRING_CONTENT); } @@ -23122,6 +23118,7 @@ pm_parser_init(pm_arena_t *arena, pm_parser_t *parser, const uint8_t *source, si .node_chunks = { .arena = &parser->scratch_arena }, .start = source, .end = source + size, + .source_end = source + size, .previous = { .type = PM_TOKEN_EOF, .start = source, .end = source }, .current = { .type = PM_TOKEN_EOF, .start = source, .end = source }, .next_start = NULL, @@ -23446,7 +23443,7 @@ pm_parse_continuable(pm_parser_t *parser) { if (!parser->continuable) return; - size_t source_length = (size_t) (parser->end - parser->start); + size_t source_length = (size_t) (parser->source_end - parser->start); // First pass: check if there are any non-stray, non-fatal errors. bool has_non_stray_error = false; diff --git a/test/prism/api/parse_stream_test.rb b/test/prism/api/parse_stream_test.rb index 5f0fa8d276..ae1b3b5e89 100644 --- a/test/prism/api/parse_stream_test.rb +++ b/test/prism/api/parse_stream_test.rb @@ -53,6 +53,49 @@ def test___END___after_syntax_error assert_equal "data\n", io.read end + def test_eof_diagnostic_before___END__ + ["\n", "\r\n"].each do |newline| + code = "[#{newline}" + marker = "__END__#{newline}" + io = StringIO.new(code + marker + "data\n") + buffer = Prism.parse(io.string) + stream = Prism.parse_stream(io) + + [buffer, stream].each do |result| + assert_equal [:array_term], result.errors.map(&:type) + assert_equal code.bytesize - 1, result.errors.first.location.start_offset + assert_equal "\n", result.errors.first.location.slice + end + + assert_equal marker + "data\n", buffer.data_loc.slice + assert_equal marker, stream.data_loc.slice + assert_equal "data\n", io.read + end + end + + def test___END___in_an_unterminated_interpolation + code = '"#{value' + "\n" + source = code + "__END__\ndata\n" + + [Prism.parse(source), Prism.parse_stream(StringIO.new(source))].each do |result| + assert_equal code, result.statement.slice + assert_equal [:unexpected_token_close_context, :embexpr_end, :string_interpolated_term], result.errors.map(&:type) + assert_equal code.bytesize, result.errors.first.location.start_offset + end + end + + def test_continued_heredoc_resumes_at___END__ + code = "<<~OUTER\n" + '#{< Date: Wed, 25 Nov 2026 15:33:07 -0500 Subject: [PATCH 09/11] Use a zero-width location for missing method names --- src/prism.c | 2 +- test/prism/result/error_recovery_test.rb | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/prism.c b/src/prism.c index 8b4be0e1f6..e5d4aacee9 100644 --- a/src/prism.c +++ b/src/prism.c @@ -16969,7 +16969,7 @@ parse_method_definition_name(pm_parser_t *parser) { return parser->previous; default: pm_parser_err_token_type(parser, &parser->current, PM_ERR_DEF_NAME, parser->current.type); - return (pm_token_t) { .type = 0, .start = parser->current.start, .end = parser->current.end }; + return (pm_token_t) { .type = 0, .start = parser->previous.end, .end = parser->previous.end }; } } diff --git a/test/prism/result/error_recovery_test.rb b/test/prism/result/error_recovery_test.rb index d07c858d1b..21c8e03d46 100644 --- a/test/prism/result/error_recovery_test.rb +++ b/test/prism/result/error_recovery_test.rb @@ -49,6 +49,18 @@ def test_class_node_constant_path_call assert_kind_of CallNode, node.constant_path.unexpected end + def test_def_node_missing_name + { "def\n__END__\n1" => "def", "def self. ; end" => "def self." }.each do |source, prefix| + result = Prism.parse(source) + assert_includes result.errors.map(&:type), :def_name + + node = result.value.statements.body.first + assert_equal :"", node.name + assert_equal prefix.bytesize, node.name_loc.start_offset + assert_equal 0, node.name_loc.length + end + end + def test_for_node_index_back_reference result = Prism.parse("for $& in a; end") refute result.success? From 7e76cada54995c1872a7079503f5e143291811d7 Mon Sep 17 00:00:00 2001 From: Kevin Newton Date: Wed, 25 Nov 2026 15:47:39 -0500 Subject: [PATCH 10/11] Ignore encoding directives on a shebang found at EOF --- include/prism/internal/parser.h | 2 +- src/prism.c | 8 +++++--- test/prism/magic_comment_test.rb | 7 +++++++ 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/include/prism/internal/parser.h b/include/prism/internal/parser.h index 94d94a6f9e..92230d6ade 100644 --- a/include/prism/internal/parser.h +++ b/include/prism/internal/parser.h @@ -862,7 +862,7 @@ struct pm_parser_t { /* * This pointer indicates where a comment must start if it is to be - * considered an encoding comment. + * considered an encoding comment. NULL if the shebang has no terminating newline. */ const uint8_t *encoding_comment_start; diff --git a/src/prism.c b/src/prism.c index e5d4aacee9..d355706eae 100644 --- a/src/prism.c +++ b/src/prism.c @@ -23288,7 +23288,7 @@ pm_parser_init(pm_arena_t *arena, pm_parser_t *parser, const uint8_t *source, si } if (line.shebang != PM_OPTIONS_SHEBANG_NONE) { - parser->encoding_comment_start = newline ? newline + 1 : parser->end; + parser->encoding_comment_start = newline ? newline + 1 : NULL; } if (pm_options_shebang_search_p(options, line.shebang)) { @@ -23301,7 +23301,7 @@ pm_parser_init(pm_arena_t *arena, pm_parser_t *parser, const uint8_t *source, si } if (line.shebang == PM_OPTIONS_SHEBANG_RUBY) { - if (newline) parser->encoding_comment_start = newline + 1; + parser->encoding_comment_start = newline ? newline + 1 : NULL; parser->current = (pm_token_t) { .type = PM_TOKEN_EOF, .start = shebang, .end = shebang }; parser->previous = parser->current; } else { @@ -23322,7 +23322,9 @@ pm_parser_init(pm_arena_t *arena, pm_parser_t *parser, const uint8_t *source, si * here we'll advance it to the first non-inline-whitespace character so * that it is ready for future comparisons. */ - parser->encoding_comment_start += pm_strspn_inline_whitespace(parser->encoding_comment_start, parser->end - parser->encoding_comment_start); + if (parser->encoding_comment_start) { + parser->encoding_comment_start += pm_strspn_inline_whitespace(parser->encoding_comment_start, parser->end - parser->encoding_comment_start); + } } /** diff --git a/test/prism/magic_comment_test.rb b/test/prism/magic_comment_test.rb index 3a73e878cf..50d04cc8d2 100644 --- a/test/prism/magic_comment_test.rb +++ b/test/prism/magic_comment_test.rb @@ -204,6 +204,13 @@ def test_encoding_after_searched_shebang end end + def test_searched_shebang_at_eof_is_not_an_encoding_comment + source = "#!/bin/sh\n#!ruby coding:bogus" + [{ main_script: true }, { command_line: "x" }].each do |options| + assert_empty Prism.parse(source, **options).errors + end + end + def test_binary_with_utf8_characters source = "# encoding: binary\n\"\xC4\x85\"".b From 6850a2389b7c4642752718dbe05d77646501921c Mon Sep 17 00:00:00 2001 From: Kevin Newton Date: Wed, 25 Nov 2026 16:00:00 -0500 Subject: [PATCH 11/11] Use Ruby 3.4 syntax for implicit it parameter assertions --- test/prism/errors_test.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/prism/errors_test.rb b/test/prism/errors_test.rb index 86ae25f7f2..53f4d06a3f 100644 --- a/test/prism/errors_test.rb +++ b/test/prism/errors_test.rb @@ -299,16 +299,16 @@ def test_singleton_method_definition_rejects_setter_name_as_receiver end def test_shorthand_hash_labels_resolve_block_parameters - assert_equal [:it_not_allowed_ordinary], Prism.parse("proc { |x| {it:} }").errors.map(&:type) - assert_equal [:it_not_allowed_numbered], Prism.parse("proc { _1; {it:} }").errors.map(&:type) - assert_equal [:numbered_parameter_it], Prism.parse("proc { it; {_2:} }").errors.map(&:type) + assert_equal [:it_not_allowed_ordinary], Prism.parse("proc { |x| {it:} }", version: "3.4").errors.map(&:type) + assert_equal [:it_not_allowed_numbered], Prism.parse("proc { _1; {it:} }", version: "3.4").errors.map(&:type) + assert_equal [:numbered_parameter_it], Prism.parse("proc { it; {_2:} }", version: "3.4").errors.map(&:type) numbered = Prism.parse_statement("proc { {_2:} }").block.parameters assert_instance_of NumberedParametersNode, numbered assert_equal 2, numbered.maximum assert_nil Prism.parse_statement("proc { {it:} }", version: "3.3.0").block.parameters - assert_nil Prism.parse("it = 1; proc { {it:} }").value.statements.body.last.block.parameters + assert_nil Prism.parse("it = 1; proc { {it:} }", version: "3.4").value.statements.body.last.block.parameters end def test_uppercase_shorthand_hash_labels_reject_method_suffixes