Files
sex/tests/sex-programs/compound-literals.sex
alex-eg 10de092ab0 designate an initializer's element by its index
[3] in braces reached the writer as a subscript of one operand, and
sexc died taking the second.
2026-10-27 01:31:37 +03:00

62 lines
2.0 KiB
Scheme

(input)
(output "plain 1 2"
"literal 3 4"
"designated zoe 7"
"through a pointer 9"
"array 10 20 30"
"argument 6"
"mixed 1 5"
"read through a pointer 1 5"
"by index 0 2 0 1")
(return 0)
;;; `:' inside #(...) ends a type and makes the rest a C99 compound
;;; literal. Without one, #(...) is the brace initializer it always was.
(include stdio.h)
(struct point ((x int) (y int)))
(struct named ((first-name (* const char)) (n int)))
(fn sum ((p (struct point))) int
(return (+ (. p x) (. p y))))
(pub fn main () int
;; unchanged: a bare initializer has no type of its own
(var p (struct point) #(1 2))
(printf "plain %d %d\n" (. p x) (. p y))
(var q (struct point) #(struct point : 3 4))
(printf "literal %d %d\n" (. q x) (. q y))
;; designated, out of declaration order, and kebab-cased
(var r (struct named) #(struct named : .n 7 .first-name "zoe"))
(printf "designated %s %d\n" (. r first-name) (. r n))
;; a compound literal is an lvalue, so its address can be taken --
;; until the end of the enclosing block, and no longer
(var pp (* struct point) (& #(struct point : 9 9)))
(printf "through a pointer %d\n" (. pp x))
;; an array literal decays the way an array does
(var a (* int) #([int 3] : 10 20 30))
(printf "array %d %d %d\n" [a 0] [a 1] [a 2])
(printf "argument %d\n" (sum #(struct point : 2 4)))
;; positional and designated may be mixed, as in C
(var m (struct point) #(struct point : 1 .y 5))
(printf "mixed %d %d\n" (. m x) (. m y))
;; what a literal holds is walked like any expression, so a path in
;; it reads through a pointer as it does outside one
(var pm (* (struct point)) (& m))
(var c (struct point) #(struct point : (. pm x) (. pm y)))
(printf "read through a pointer %d %d\n" (. c x) (. c y))
;; an element may be named by its index, as a field is by its name
(var sparse [int 4] #([3] 1 [1] 2))
(printf "by index %d %d %d %d\n" [sparse 0] [sparse 1] [sparse 2] [sparse 3])
(return 0))