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

@@ -167,7 +167,30 @@ whitespace aside, THEN?"
"int x = a ? a : b"))
(test-assert "left bare as an argument"
(emits? (in-fn "(g (if a a b) b)")
"g(a ? a : b, b)")))
"g(a ? a : b, b)"))
;; ?: groups to the right, so a chain needs none in its else arm
(test-assert "a chain in the else arm is left bare"
(emits? (in-fn "(var x int (if a a (if b b 0)))")
"a ? a : b ? b : 0"))
(test-assert "but an assignment there is not"
(emits? (in-fn "(var x int (if a a (= b 1)))")
"a ? a : (b = 1)")))
;; A subscript binds tighter than anything, so what it subscripts is
;; parenthesised whenever it is an operator: `*q[i]' is *(q[i])
(test-group "subscript precedence"
(test-assert "a dereference"
(emits? "(fn f ((q (* * int)) (i int)) int (return [(* q) i]))" "(*q)[i]"))
(test-assert "a sum"
(emits? "(fn f ((p (* int))) int (return [(+ p 1) 0]))" "(p + 1)[0]"))
(test-assert "a cast"
(emits? "(fn f ((v (* void))) int (return [(cast v (* int)) 0]))" "((int *)v)[0]"))
(test-assert "a path is left bare"
(emits? (in-line "(var x int [(. p x) 0])") "p.x[0]"))
;; ...while the index is in brackets of its own
(test-assert "an index is never parenthesised"
(emits? "(fn f ((p (* int)) (i int)) int (return (cast [p (+ i 1)] int)))"
"(int)p[i + 1]")))
;; A comment among a call's arguments used to become an argument,
;; and c-apply put a comma on each side of it -- which does not