Files
sex/tests/sex-programs/records.sex
alex-eg 2729e41e32 declare a record's typedef ahead of its struct
It came after, so a record pointing at itself, (next (* node)), named a
type C had not been told of yet.
2026-10-19 16:05:16 +03:00

56 lines
1.4 KiB
Scheme

(input)
(output "p 3 4 / n 7 zoe / area 12 / sizes 8 8"
"chain 1 2")
(return 0)
;;; A record is a struct that also names itself, so the bare name
;;; stands wherever (struct name) had to: a var, a pointer, an array
;;; element, an arglist, a return type, a sizeof. struct keeps C's
;;; meaning, for a type that came from a header or is laid out to
;;; match one.
(include stdio.h)
(record point ((x int) (y int)))
(record named
"Fields of more than one kind, and a docstring."
((id int) (first-name (* const char))))
(struct raw ((a int) (b int)))
;;; A record naming itself in its own fields: the name is a type before
;;; the fields are
(record node ((value int) (next (* node))))
(fn shift ((p (* point)) (dx int) (dy int)) void
(+= (. p x) dx)
(+= (. p y) dy))
(fn area ((p point)) int
(return (* (. p x) (. p y))))
(fn origin () point
(return #(point : 0 0)))
(pub fn main () int
(var p point #(point : 1 2))
(shift (& p) 2 2)
(var n named #(named : .id 7 .first-name "zoe"))
(var r (struct raw) #(struct raw : 1 2))
(var ps [point 2])
(= [ps 0] p)
(= [ps 1] (origin))
(printf "p %d %d / n %d %s / area %d / sizes %zu %zu\n"
(. p x) (. p y) (. n id) (. n first-name)
(area [ps 0])
(sizeof point) (sizeof (struct raw)))
(var tail node #(node : 2 NULL))
(var head node #(node : 1 (& tail)))
(printf "chain %d %d\n" (. head value) (. head next value))
(return (+ (. [ps 1] x) (- (. r a) 1))))