Commit 4c63fda3
4c63fda3bee2Merged
Ryan Seys <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified
Description
fix(codegen): c_string_literal preserves literal backslashes
The c_string_literal helper receives runtime Ruby string content
(prism's already-cooked AST string), where any backslash is a
LITERAL backslash byte, not the start of a Ruby escape sequence.
The previous version still treated \ as an escape introducer and
peeked at the next byte to "decode" \n, \t, etc. — collapsing
the 2-byte input "\n" (backslash + n) to a single C newline byte
instead of emitting \\n (backslash + n) for the C compiler.
Symptoms:
puts "\\n".lengthprinted 1 instead of 2"a\\nb".linesproduced invalid C with a literal newline inside a string literal, failing the cc step
Fix: any backslash → emit \\ to C source unconditionally. The
existing handling of newline (10.chr → \n), CR, tab, and quote is
correct because those branches match the runtime byte values
directly, not Ruby's source-level escape sequences.
Bootstrap fixed-point still reached (gen2.c == gen3.c). The bsl/bsl_n helpers used throughout codegen.rb construct their escape sequences via 92.chr / 10.chr to dodge this very bug, so the generated codegen output is unchanged for those call sites.
Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]
Details
- Commit
- 4c63fda3bee2
- Parent
- 8ff9aa915a30
spinel_codegen.rbmodifiedView file
end def c_string_literal(s) # Input `s` is the runtime Ruby string content (already-cooked: any # backslash in `s` is a literal backslash, NOT an escape introducer). # We C-escape the small set that needs it: backslash, double-quote, # newline, carriage return, tab. Everything else copies through. # The previous version treated `s` as if it still carried Ruby # escapes, so a 2-char input "\\n" (backslash + n) wrongly collapsed # to a C newline; that bug is what made `"hello\\nworld\\n".lines` # emit invalid C with a literal newline inside a string literal. result = "\"" i = 0 while i < s.length ch = s[i] if ch == bsl # Check for Ruby escape sequences if i + 1 < s.length nch = s[i + 1] if nch == "n" result = result + bsl_n i = i + 2 else if nch == "t" result = result + bsl + "t" i = i + 2 else if nch == "r" result = result + bsl + "r" i = i + 2 else if nch == bsl result = result + bsl + bsl i = i + 2 else if nch == "\"" result = result + bsl + "\"" i = i + 2 else result = result + bsl + bsl i = i + 1 end end end end end else result = result + "\\\\" i = i + 1 end result = result + bsl + bsl else if ch == "\"" result = result + bsl + "\"" end end end i = i + 1 end i = i + 1 end # Prepend 0xff marker byte so GC can identify static literals. # Return form: (&("\xff" "content")[1]) — same pointer value as thetest/string_escape.rbaddedView file
Loading diff…
test/string_escape.rb.expectedaddedView file
Loading diff…