Commit 1bf0d77f

1bf0d77f44c3Merged

Yusuke Endoh <[email protected]> · 6 months ago · 2 files · +1 added · ~1 modified

Description

fix(codegen): escape \n \t \r in emitted regex literals

A regex source that contains a raw newline, tab, or CR (e.g. a multi-line /x pattern) used to produce a broken C source — the character flowed through to the emitted re_compile("...", N, F) call unescaped, closing the C string literal mid-line:

/tmp/_t.c:8:28: warning: missing terminating " character
    8 |   sp_re_pat_0 = re_compile("
      |                            ^
/tmp/_t.c:9:3: error: 'hello' undeclared (first use in this function)
/tmp/_t.c:11:1: warning: missing terminating " character
   11 | ", 17, 0);
      | ^

Only \ and " were being escaped. Extend the substitution loop to also rewrite raw \n, \t, and \r in the pattern bytes to the corresponding C escape sequences. The byte length passed to re_compile stays the original pat.length, so the regex engine still sees the same raw bytes at runtime — only the C-source representation of the literal changes.

Adds test/regex_multiline_pattern.rb covering a multi-line /x literal plus single-character \t / \n / \r escapes.

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
1bf0d77f44c3
Parent
c98048e104bd

spinel_codegen.rbmodifiedView file

@@ -8848,12 +8848,19 @@
88488848 ch = pat[pi]
88498849 if ch == 92.chr
88508850 cpat = cpat + 92.chr + 92.chr
8851+ elsif ch == 34.chr
8852+ cpat = cpat + 92.chr + 34.chr
8853+ elsif ch == 10.chr
8854+ # Embedded newlines / tabs / CRs in /x patterns must be
8855+ # encoded as escape sequences; emitting them raw produces an
8856+ # unterminated C string literal.
8857+ cpat = cpat + 92.chr + "n"
8858+ elsif ch == 13.chr
8859+ cpat = cpat + 92.chr + "r"
8860+ elsif ch == 9.chr
8861+ cpat = cpat + 92.chr + "t"
88518862 else
8852- if ch == 34.chr
8853- cpat = cpat + 92.chr + 34.chr
8854- else
8855- cpat = cpat + ch
8856- end
8863+ cpat = cpat + ch
88578864 end
88588865 pi = pi + 1
88598866 end