1
0
forked from alex-eg/sex

parenthesise what a subscript subscripts

The array was written at whatever level surrounded it, so [(* q) i]
came out *q[i] -- *(q[i]) to C, compiling with q an int ** and reading
the wrong int. The index now starts afresh too: inside a cast it had
taken the cast's level and gained parens, and so had a chain in the
else arm of ?:, which groups to the right and needs none.
This commit is contained in:
2026-10-09 18:03:21 +03:00
parent 981eb6f755
commit e29c6ee5c9
2 changed files with 42 additions and 9 deletions

View File

@@ -97,6 +97,7 @@
;;((|\|\||) 75)
;;((.. ...) 77) ; Perl
((?) 80)
((conditional-else) 81) ; see c-if/expr
((= *= /= %= &= ^= <<= >>=) 85) ; |\|=| ; += -=
((comma) 90)
((=>) 90) ; Perl
@@ -111,6 +112,13 @@
(define (c-paren x) (cat "(" (c-expr x) ")"))
;; MODIFIED FROM UPSTREAM fmt-c: a subscript is postfix, tighter than
;; any operator, so what it subscripts is written at the level of
;; `.' -- (* q) comes out `(*q)[i]', not `*q[i]', which is *(q[i]).
;; The index has brackets of its own and starts afresh.
(define (c-subscript array index)
(cat (c-with-op "." (c-expr array)) "[" (c-with-op 'paren (c-expr index)) "]"))
;; `.' and `->' associate left, and their right operand is always a
;; name, so a member access written inside another is the left one
;; and needs no parens of its own: `s.u.circle.r', not `((s.u).circle).r'
@@ -249,12 +257,9 @@
;; non C-keywords must have some character invalid in a C
;; identifier to avoid conflicts - by default we prefix %
((vector-ref)
((c-wrap-stmt
(cat (c-expr (cadr x)) "[" (c-expr (caddr x)) "]"))
st))
((c-wrap-stmt (c-subscript (cadr x) (caddr x))) st))
((vector-set!)
((c= (c-in-expr
(cat (c-expr (cadr x)) "[" (c-expr (caddr x)) "]"))
((c= (c-in-expr (c-subscript (cadr x) (caddr x)))
(c-expr (cadddr x)))
st))
((extern/C) ((apply c-extern/C (cdr x)) st))
@@ -885,6 +890,10 @@
;; Upstream wrote it bare whatever surrounded it, and `?:' binds
;; looser than every binary operator: (/ 300 (if c c 1)) came out
;; `300 / c ? c : 1', a conditional on the quotient.
;;
;; It groups to the right, so its else arm is written at
;; `conditional-else', just looser: a chain there stays bare,
;; `a ? x : b ? y : z', and an assignment does not.
(define (c-if/expr . args)
(c-maybe-paren '? (apply c-if/expr/aux args)))
@@ -897,9 +906,10 @@
(c-expr p)))
((pair? ls)
(cat (c-in-test (c-expr c)) " ? " (c-expr p) " : "
(if (pair? (cdr ls))
(lp (car ls) (cadr ls) (cddr ls))
(lp 'else (car ls) '()))))
(c-with-op 'conditional-else
(if (pair? (cdr ls))
(lp (car ls) (cadr ls) (cddr ls))
(lp 'else (car ls) '())))))
(else
(c-or (c-in-test (c-expr c)) (c-expr p))))))