parenthesise casts and conditionals by precedence

Neither took part in it: a cast parenthesised its operand only from a
list of binary heads that missed `|', and never itself, so `->' took
it apart; `?:' was written bare under any operator, swallowing it into
the test. Three of the four still compiled, to wrong values.

Fixes #59, #61, #62.
This commit is contained in:
2026-10-09 15:41:43 +03:00
parent 913af0b463
commit 8d1c12d03b
4 changed files with 81 additions and 26 deletions

View File

@@ -114,7 +114,35 @@ compiles."
"(int *)&a"))
(test-assert "sizeof is left bare"
(emits? (in-fn "(var n int (cast (sizeof int) int))")
"(int)sizeof(int)")))
"(int)sizeof(int)"))
;; `|' reaches fmt-c as a string, which a list of binary heads to
;; parenthesise did not have
(test-assert "bitwise operand is parenthesised"
(emits? (in-fn "(var f float (cast (| a b) float))")
"(float)(a | b)"))
(test-assert "conditional operand is parenthesised"
(emits? (in-fn "(var f float (cast (if a a b) float))")
"(float)(a ? a : b)"))
;; A cast is the operand here, and binds looser than `->'
(test-assert "cast under a member access is parenthesised"
(emits? (in-line "(var v (* void) pp) (var x int (. (cast v (* struct point)) x))")
"((struct point*)v)->x"))
(test-assert "cast under a unary operator is left bare"
(emits? (in-line "(var v (* void) pp) (var x int (* (cast v (* int))))")
"*(int *)v")))
;; `?:' binds looser than every binary operator, so as an operand it
;; has to be parenthesised, or C takes the operator into its test
(test-group "conditional expression precedence"
(test-assert "operand of a binary operator"
(emits? (in-fn "(var x int (/ a (if a a b)))")
"a / (a ? a : b)"))
(test-assert "left bare where it is the whole value"
(emits? (in-fn "(var x int (if a a b))")
"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)")))
;; 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

View File

@@ -0,0 +1,28 @@
(input)
(output "conditional operand: 75"
"cast as object of .: 7"
"cast of bitwise: 1"
"cast of conditional: 44")
(return 0)
;;; A Sex form is parenthesised by construction, and C is not: whatever
;;; the writer leaves bare, C regroups by its own precedence. Each line
;;; below came out regrouped, and the first and the last two still
;;; compiled -- computing 4, 257 and 300.
(include stdio.h)
(record wanted ((distance int)))
(pub fn main () int
(var compared int 4)
(printf "conditional operand: %d\n" (/ 300 (if (> compared 0) compared 1)))
(var w wanted #(wanted : 7))
(var pa (* const void) (& w))
(printf "cast as object of .: %d\n" (. (cast pa (* const wanted)) distance))
(var x int 1)
(printf "cast of bitwise: %d\n" (cast (| x 256) u8))
(printf "cast of conditional: %d\n" (cast (if x 300 1) u8))
(return 0))