Commit d6f84294

d6f84294de53Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 2 files · +1 added · ~1 modified

Description

Fix parse error for bare-string require with a trailing modifier

require 'json' rescue nil (and require 'x' if cond, etc.) failed to parse: the require preprocessor replaced the require 'x' statement with inlined content or a comment but stopped before the trailing modifier, stranding rescue nil on its own and making Prism report "unexpected 'rescue'". Only the parenthesized form require('x') rescue nil worked.

When a trailing same-line modifier follows the require, substitute a nil expression for the require 'x' token so the modifier attaches and the statement parses; an optional/unavailable require degrades to nil, which is what the rescue guards for. Statement boundaries (;, #, newline, EOF) keep the normal inlining path.

Fixes #1285

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
d6f84294de53
Parent
a99d24e95c24

spinel_parse.cmodifiedView file

@@ -1677,6 +1677,33 @@
16771677 }
16781678 }
16791679
1680+ /* A trailing same-line modifier (`rescue`, `if`, `unless`, `and`,
1681+ `&&`, ...) puts the require in expression position: `require 'x'
1682+ rescue nil`. Replacing it with inlined statements or a comment
1683+ strands the modifier and Prism reports `unexpected 'rescue'`.
1684+ Substitute a `nil` expression instead so the modifier attaches;
1685+ an optional/unavailable require degrades to nil, which is what the
1686+ `rescue` guards for. `;`, `#`, newline and EOF are statement
1687+ boundaries, not modifiers, and keep the normal inlining path. */
1688+ {
1689+ char *trail = end + 1;
1690+ while (*trail == ' ' || *trail == '\t') trail++;
1691+ if (*trail != '\n' && *trail != ';' && *trail != '\0' && *trail != '#') {
1692+ free(content);
1693+ size_t rl_len = (size_t)((end + 1) - pos); /* the `require 'x'` span */
1694+ size_t result_len = strlen(result);
1695+ size_t before_len = (size_t)(pos - result);
1696+ char *new_result = malloc(result_len - rl_len + 4);
1697+ memcpy(new_result, result, before_len);
1698+ memcpy(new_result + before_len, "nil", 3);
1699+ memcpy(new_result + before_len + 3, pos + rl_len,
1700+ result_len - before_len - rl_len + 1);
1701+ free(result);
1702+ result = new_result;
1703+ continue;
1704+ }
1705+ }
1706+
16801707 /* Replace only the `require "name"` statement itself, not the whole
16811708 line, so `require "x"; code` keeps `code`. Consume trailing
16821709 horizontal whitespace and a single terminating newline (so a