walk a define's body, and parenthesise it

The body was pasted as read, so `cast' stayed a call and names kept
their dashes; and fmt-c parenthesised only a function-like body, so
an object-like one regrouped with the operator it was pasted under.

Fixes #55.
This commit is contained in:
2026-10-09 16:00:28 +03:00
parent 8db9246389
commit ba45069484
4 changed files with 34 additions and 7 deletions

View File

@@ -703,6 +703,21 @@ compiles."
(test-assert "nor one behind a pointer"
(emits? "(struct t ((z int))) (struct s ((a (¤ * struct t))))" "struct t* a[]")))
;; A define's body was pasted unwalked, and unparenthesised: `cast'
;; stayed a call, and (* x D) regrouped with D's own operator
(test-group "defines"
(test-assert "an atom is left bare"
(emits? "(define N 4)" "#define N 4"))
(test-assert "and its name converted"
(emits? "(define MAX-N MIN-N)" "#define MAX_N MIN_N"))
(test-assert "an expression is walked and parenthesised"
(emits? "(define K (/ (cast 255 float) (cast 60 float)))"
"#define K ((float)255 / (float)60)"))
(test-assert "so is a negative literal"
(emits? "(define NEG -1)" "#define NEG (-1)"))
(test-assert "a function-like one is converted too"
(emits? "(define (sq-of x) (* x x))" "#define sq_of(x) ((x) * (x))")))
;; A typedef's target is a type, and was walked as an expression: a
;; pointer read as a dereference, an array as a subscript
(test-group "typedefs"

View File

@@ -2,18 +2,21 @@
(output "conditional operand: 75"
"cast as object of .: 7"
"cast of bitwise: 1"
"cast of conditional: 44")
"cast of conditional: 44"
"define body: 6")
(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.
;;; below came out regrouped, and all but the member access still
;;; compiled -- computing 4, 257, 300, and 4 from `2 * 1 + 2'.
(include stdio.h)
(record wanted ((distance int)))
(define SUM (+ 1 2))
(pub fn main () int
(var compared int 4)
(printf "conditional operand: %d\n" (/ 300 (if (> compared 0) compared 1)))
@@ -25,4 +28,5 @@
(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))
(printf "define body: %d\n" (* 2 SUM))
(return 0))