From 7112f43b8399d2f74e902d6c27e67e4f9ae0aef4 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 13:54:57 +0300 Subject: [PATCH] parenthesize a negative literal under a unary operator A negative literal is one token in Sex and two in C, so (- -1) came out --1, which C reads as decrementing a constant. --- sex-fmt-c.scm | 8 +++++++- tests/sex-programs/operators.sex | 7 ++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index 6b02d3b..07cc9b3 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -1075,10 +1075,16 @@ ;; Parenthesises the whole expression rather than the operand: the ;; other way round, `(. (* p) x)' came out `*(p).x', which C reads as ;; `*(p.x)'. + ;; MODIFIED FROM UPSTREAM fmt-c: a negative literal is one token in + ;; Sex and two in C, so (- -1) is -(-1), not the decrement --1. (define (c-unary-op op x) (c-wrap-stmt (c-maybe-paren (unary-operator op) - (cat (display-to-string op) (c-expr x))))) + (cat (display-to-string op) + (if (and (number? x) + (char=? #\- (string-ref (number->string x) 0))) + (c-paren x) + (c-expr x)))))) ;; some convenience definitions diff --git a/tests/sex-programs/operators.sex b/tests/sex-programs/operators.sex index 7481f55..78b9ad9 100644 --- a/tests/sex-programs/operators.sex +++ b/tests/sex-programs/operators.sex @@ -9,7 +9,8 @@ "closure in place: 5" "a type is not a call: 7" "radix literals: 224 5 128" - "a double reaches C whole: 1") + "a double reaches C whole: 1" + "negated literals: 1 2.5") (return 0) ;;; The walk types an expression by its head, and the heads it had a @@ -97,4 +98,8 @@ ;; ...and a double in all the digits it was written with (var sixth double (/ 1.0 6.0)) (printf "a double reaches C whole: %d\n" (== 0.16666666666666666 sixth)) + + ;; a negative literal is one token in Sex and two in C, and C reads a + ;; minus written before them as `--' + (printf "negated literals: %d %g\n" (- -1) (- -2.5)) (return 0))