A sum is the tag enum, a payload struct per variant that carries fields, the record holding both, and a constructor each. match is a switch over the tag whose arms open a block and bind the payload as locals, so the shape of the generated C is the shape a C programmer would have written by hand. What it is for is the refusal: a match that leaves a variant out is an error naming the ones missing, and so are an arm the sum does not have, a wrong number of binders, and the same arm written twice. C cannot say any of that, which is why every switch over a tag in the wild ends in a defensive default nobody can tell from a real case. Only the sum is typedef'd. A payload struct would put shapeːcircle in the ordinary namespace, where the constructor of that name already lives; as a bare tag it collides with nothing. The sum's own typedef is emitted ahead of the payload structs, since a variant may hold a pointer back to the sum, and constructors are static even for a pub sum, which is pasted into the importer whole. The scrutinee is read once per binding, so one that is not a path of names is held in a local first -- otherwise (match (f) ...) would call f once for the tag and again for every field it binds.
46 lines
1.4 KiB
Scheme
46 lines
1.4 KiB
Scheme
;;; Uses the greet module. Build both, then link them:
|
|
;;;
|
|
;;; ./sexc example/greet.sex -c -o greet.o
|
|
;;; ./sexc example/greet-app.sex -o greet-app -- greet.o
|
|
;;;
|
|
;;; `(import greet)' pastes greet's public declarations here: `greet'
|
|
;;; as a prototype and `greet-count' as an extern. Both keep external
|
|
;;; linkage, so they refer to the one definition in greet.o rather than
|
|
;;; to private copies.
|
|
;;;
|
|
;;; Also check that import populates type-database, by means of
|
|
;;; describe-fields macro, which should work on imported type.
|
|
|
|
(include stdio.h)
|
|
|
|
(import greet)
|
|
|
|
(pub fn main () int
|
|
(greet "world")
|
|
(greet "sex")
|
|
(printf "%d greetings\n" greet-count)
|
|
(describe-fields greeting)
|
|
(printf "\n")
|
|
;; ...and through the imported typedef for it
|
|
(describe-fields greeting-t)
|
|
(printf "\n")
|
|
(var m (enum mood) grumpy)
|
|
(printf "mood %d\n" m)
|
|
|
|
(var add-10 (closure ((int)) int) (make-adder 10))
|
|
(printf "closure %d %d" (add-10 5) (apply-twice add-10 1))
|
|
(var base int 100)
|
|
(var here (closure ((int)) int)
|
|
(closure ((x int)) int (base) (return (+ base x))))
|
|
(printf " %d\n" (apply-twice here 1))
|
|
|
|
;; the bare record name, then the method both ways round
|
|
(var v vec2 #(vec2 : 3 4))
|
|
(printf "vec2 %d %d\n" (. v manhattan) (vec2/manhattan (& v)))
|
|
|
|
(var c colour (colour/rgb 1 2 3))
|
|
(match c
|
|
((rgb (r g b)) (printf "colour %d%d%d\n" r g b))
|
|
((none ()) (printf "colour none\n")))
|
|
(return 0))
|