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 27ef5ac805
commit c05904c15e
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)))))

View File

@@ -1,6 +1,7 @@
(compilation "-- -std=c11 -pedantic-errors")
(input)
(output "c11: 42 43 6 4 6 12")
(output "c11: 42 43 6 4 6 12"
"trigraphs: what??! ??= ???( ??/")
(return 0)
;;; C11 is the floor, and this is the program that holds it there: the
@@ -12,6 +13,10 @@
;;; max_align_t in the environment and `_Static_assert' on its size;
;;; the record, the method and the match are here for what they emit,
;;; and the globals for initializers that have to be constants.
;;;
;;; It is also the one mode where C still reads trigraphs, which Sex has
;;; none of: a string says what was written, `??/' before its closing
;;; quote included.
(include stdio.h)
@@ -42,4 +47,5 @@
(printf "c11: %d %d %d %d %d %d\n"
(.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2)
(sides unit) (.area corner) (.area [pair 1]))
(printf "trigraphs: %s\n" "what??! ??= ???( ??/")
(return 0))