escape a ? that follows a ? in string literals

Under -std=c11 C reads trigraphs, which Sex has none of: "??=" came out
"#", and "??/" before the closing quote left the string open.
This commit is contained in:
2026-10-16 14:19:51 +03:00
parent e835d39f58
commit 753406462d
2 changed files with 22 additions and 6 deletions

View File

@@ -212,14 +212,24 @@
(define (c-format-string x)
(lambda (st) ((cat #\" (apply-cat (c-string-escaped x)) #\") st)))
;; MODIFIED FROM UPSTREAM fmt-c: a `?' after a `?' is escaped, so no
;; two stand together for C to read a trigraph off -- under -std=c11
;; "??=" is "#", and "??/" before the closing quote is \", which
;; leaves the string open.
(define (c-string-escaped x)
(define (special? i)
(let ((c (string-ref x i)))
(or (c-needs-string-escape? c)
(and (eqv? c #\?) (> i 0) (eqv? (string-ref x (- i 1)) #\?)))))
(let loop ((parts '()) (idx (string-length x)))
(cond ((string-index-right x c-needs-string-escape? 0 idx)
(cond ((let find ((i (- idx 1)))
(cond ((< i 0) #f) ((special? i) i) (else (find (- i 1)))))
=> (lambda (special-idx)
(loop (cons (c-escape-char (string-ref x special-idx) #\")
(cons (substring/shared x (+ special-idx 1) idx)
parts))
special-idx)))
(let ((c (string-ref x special-idx)))
(loop (cons (if (eqv? c #\?) "\\?" (c-escape-char c #\"))
(cons (substring/shared x (+ special-idx 1) idx)
parts))
special-idx))))
(else
(cons (substring/shared x 0 idx) parts)))))