From c05904c15e22780fb32bf5effe4b73b31df916a0 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 14:19:51 +0300 Subject: [PATCH] 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. --- sex-fmt-c.scm | 20 +++++++++++++++----- tests/sex-programs/c11.sex | 8 +++++++- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index 07cc9b32..a533ad7b 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -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))))) diff --git a/tests/sex-programs/c11.sex b/tests/sex-programs/c11.sex index 375503d9..2081ca90 100644 --- a/tests/sex-programs/c11.sex +++ b/tests/sex-programs/c11.sex @@ -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))