implement sum and match

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.
This commit is contained in:
2026-10-03 22:59:15 +03:00
parent dea36e3c02
commit 3a10ee099b
11 changed files with 293 additions and 2 deletions

View File

@@ -112,6 +112,7 @@ SEX_TEST_PROGRAMS = c99 \
ops \
records \
serialize \
sums \
type-shapes \
unicode \
unnamed-params \

170
semen.scm
View File

@@ -85,6 +85,8 @@
(('ops . _) (process-ops sex-form acc))
(('pub 'ops . _)
(sex-error sex-form "pub belongs on the methods, not on ops" sex-form))
((or ('sum . _)
('pub 'sum . _)) (process-sum sex-form acc))
((or ('record . _)
('pub 'record . _)) (process-record sex-form acc))
((or ('struct . _)
@@ -466,6 +468,8 @@
(cddr walked))))
walked)))
((match) (walk-match form env))
((dot-access ->) (walk-member-access form env))
(else
@@ -594,6 +598,94 @@
(define (walk-parts form env)
(copy-form-source! form (walk-body form env)))
;;; (match s ((circle (r)) ...) ((empty ()) ...)) is a switch over the
;;; tag, each arm a block binding that variant's fields as locals. `_'
;;; drops one. An arm the sum does not have, a wrong number of
;;; binders, or a variant left out with no `else' are all errors here:
;;; a missing case is the thing this form exists to catch.
(define (walk-match form env)
(let* ((scrutinee (and (pair? (cdr form)) (second form)))
;; a comment between arms goes the way the writer already
;; drops one between switch clauses
(arms (remove comment-form? (cddr form)))
(type (expression-type scrutinee env))
(name (ops-key type))
(variants (and name (get-sum name))))
(unless variants
(sex-error form "match wants a sum, and this is not one"
(or type 'unknown)))
(check-match form name variants arms)
(if (simple-path? scrutinee)
(walk-statement (match-switch name scrutinee variants arms) env)
;; the scrutinee is read once per binding, so anything that
;; could be read twice is read into a local first
(let ((held (aux-name! env make-match-name)))
(walk-statement
`(do (var ,held ,type ,scrutinee)
,(match-switch name held variants arms))
env)))))
(define (make-match-name fn-name counter)
(string->symbol (string-append "ƛm" (number->string counter))))
;;; A path of names reads the same however often it is written; a call
;;; in there does not
(define (simple-path? expr)
(cond ((symbol? expr) #t)
((not (pair? expr)) #f)
(else (case (car expr)
((dot-access ->) (simple-path? (second expr)))
((*) (and (= 2 (length expr)) (simple-path? (second expr))))
(else #f)))))
(define (match-arm-variant arm) (and (pair? (car arm)) (car (car arm))))
(define (check-match form name variants arms)
(let* ((else? (lambda (arm) (eq? (car arm) 'else)))
(named (remove else? arms))
(covered (map match-arm-variant named)))
(for-each
(lambda (arm)
(let* ((variant (match-arm-variant arm))
(fields (variant-fields variants variant)))
(unless (and (list? (car arm)) (= 2 (length (car arm))))
(sex-error form "an arm is ((variant (binders ...)) body ...)" arm))
(unless fields
(sex-error form "not a variant of" name variant))
(unless (= (length fields) (length (second (car arm))))
(sex-error form "variant takes this many fields" variant
(length fields)))))
named)
(let ((twice (find (lambda (v) (> (count (cut eq? <> v) covered) 1))
covered)))
(when twice
(sex-error form "arm is written twice" twice)))
(let ((missing (lset-difference eq? (map car variants) covered)))
(when (and (pair? missing) (not (any else? arms)))
(apply sex-error form "match leaves a variant out:" missing)))))
(define (match-switch name scrutinee variants arms)
`(switch (dot-access ,scrutinee tag)
,@(map (lambda (arm)
(if (eq? (car arm) 'else)
`(default (do ,@(cdr arm)))
(let* ((variant (match-arm-variant arm))
(binders (second (car arm)))
(fields (variant-fields variants variant)))
`(case ,(sum-tag-constant name variant)
(do ,@(match-bindings scrutinee variant binders fields)
,@(cdr arm))))))
arms)))
(define (match-bindings scrutinee variant binders fields)
(filter-map
(lambda (binder field)
(and (not (eq? binder '_))
`(var ,binder ,(second field)
(dot-access (dot-access (dot-access ,scrutinee u) ,variant)
,(first field)))))
binders fields))
;;; (. v length) is member access while `length' is a field of v, and a
;;; call to vec2ːlength once it is a method:
;;;
@@ -1220,6 +1312,84 @@
(register-aggregate! form)
(with-docstring doc form acc))))
;;; (sum shape ((circle ((r float))) (rect ((w float) (h float)))))
;;; is the tag enum, a payload struct per variant that has fields, the
;;; record holding both, and one constructor per variant:
;;;
;;; (var s shape (shape/circle 1.0))
;;;
;;; The payload structs are plain structs rather than records on
;;; purpose: a record would typedef shapeːcircle into the ordinary
;;; namespace, where the constructor of that name already lives. As a
;;; tag it shares nothing.
(define (process-sum form acc)
(let* ((core (if (eq? (car form) 'pub) (cdr form) form))
(name (and (pair? (cdr core)) (cadr core)))
(declared (and (pair? (cddr core)) (caddr core))))
(unless (and (symbol? name) (list? declared) (pair? declared))
(sex-error form "sum needs a name and a list of variants" form))
(let ((variants (map (lambda (v) (parse-variant form v)) declared)))
(when (get-sum name)
(sex-error form "sum is already defined" name))
(add-sum! name variants)
(fold match-sex-form acc
(map (lambda (f) (copy-form-source! form f))
(sum-forms name variants))))))
(define (parse-variant form v)
(unless (and (list? v) (= 2 (length v)) (symbol? (car v)) (list? (cadr v)))
(sex-error form "a variant is (name (fields ...))" v))
(cons (car v) (normalize-fields (cadr v))))
(define (sum-forms name variants)
(let ((carried (filter (lambda (v) (pair? (cdr v))) variants)))
`(;; forward, so a variant may hold a pointer back to the sum
(typedef ,name (struct ,name))
(enum ,(sum-tag name)
,(map (lambda (v) (sum-tag-constant name (car v))) variants))
,@(map (lambda (v) `(struct ,(qualify-op name (car v)) ,(cdr v)))
carried)
(struct ,name
((tag (enum ,(sum-tag name)))
,@(if (null? carried)
(list)
`((u (union ,(map (lambda (v)
`(,(car v)
(struct ,(qualify-op name (car v)))))
carried)))))))
,@(map (lambda (v) (sum-constructor name v)) variants))))
;;; (shape/circle 1.0) builds the value in one compound literal, so a
;;; constructor is an expression and not three statements
;;; Static even when the sum is pub: a pub sum is pasted whole into
;;; the importer, and two units defining shapeːcircle would not link.
(define (sum-constructor name variant)
(let* ((tag (car variant))
(fields (cdr variant))
(payload (qualify-op name tag)))
`(fn ,payload ,fields ,name
(return ,(sum-literal name tag payload fields)))))
;;; #(shape : .tag shapeːtagːcircle .u #(.circle #((struct shapeːcircle) : r)))
(define (sum-literal name tag payload fields)
(list->vector
(append (list name ': (dotted 'tag) (sum-tag-constant name tag))
(if (null? fields)
(list)
(list (dotted 'u)
(vector (dotted tag)
(list->vector
(append (list (list 'struct payload) ':)
(map car fields)))))))))
(define (dotted name)
(string->symbol (string-append "." (symbol->string name))))
(define (sum-tag name) (qualify-op name 'tag))
(define (sum-tag-constant name variant)
(qualify-op (sum-tag name) variant))
;;; (record point ((x int) (y int))) is a struct that also names
;;; itself, so `point' alone stands where `(struct point)' had to:
;;; (var p point ...), (* const point), (sizeof point).

View File

@@ -41,6 +41,7 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
"pub"
"record"
"struct"
"sum"
"var"
"union")
'word)
@@ -83,6 +84,8 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
(put 'pub 'lisp-indent-function 'defun)
(put 'defmacro 'lisp-indent-function 'defun)
(put 'record 'lisp-indent-function 'defun)
(put 'sum 'lisp-indent-function 'defun)
(put 'match 'lisp-indent-function 1)
(put 'struct 'lisp-indent-function 'defun)
(put 'union 'lisp-indent-function 'defun)
(put 'var 'lisp-indent-function 0)

View File

@@ -117,7 +117,7 @@
(('pub 'var . _)
(match-let ((('pub 'var name type . _) (strip-header-comments form 4)))
(cons (copy-form-source! form `(extern var ,name ,type)) acc)))
(('pub (or 'define 'defmacro 'enum 'import 'include 'record 'struct 'typedef 'union) . _)
(('pub (or 'define 'defmacro 'enum 'import 'include 'record 'struct 'sum 'typedef 'union) . _)
(cons (copy-form-source! form (cdr form)) acc))
(('ops . _)
(let ((exported (ops-public-interface form)))

View File

@@ -20,7 +20,7 @@
SEXC ?= ../../sexc
EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7
EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7\ncolour 123
check:
@$(SEXC) greet.sex -c -o greet.o

View File

@@ -37,4 +37,9 @@
;; 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))

View File

@@ -60,6 +60,11 @@
(pub fn manhattan ((self (* const vec2))) int
(return (+ (-> self x) (-> self y)))))
;;; A pub sum is pasted whole, so the importer builds its own copy of
;;; the declarations -- and of the constructors, which is why those are
;;; static: two units defining colourːrgb would not link.
(pub sum colour ((rgb ((r int) (g int) (b int))) (none ())))
;;; Not `pub': invisible to importers, and static in the generated C.
(fn unused-helper () void
(printf "private\n"))

View File

@@ -0,0 +1,78 @@
(input)
(output "3.14 12.00 0.00"
"held once: a 1"
"nested: -(2 + 3) = -5"
"tagged only: 1")
(return 0)
;;; A sum is a 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 bind the payload as locals, and
;;; the compiler refuses one that leaves a variant out -- which is the
;;; thing the form exists for.
(include stdio.h)
(sum shape
((circle ((r float)))
(rect ((w float) (h float)))
(empty ())))
(fn area ((s shape)) float
(var out float 0.0)
(match s
((circle (r)) (= out (* 3.14159 r r)))
((rect (w h)) (= out (* w h)))
((empty ()) (= out 0.0)))
(return out))
;;; Recursive through pointers, because a value cannot hold itself
(sum expr
((lit ((v float)))
(neg ((e (* const expr))))
(add ((l (* const expr)) (r (* const expr))))))
(fn eval ((self (* const expr))) float
(match (* self)
((lit (v)) (return v))
((neg (e)) (return (- (eval e))))
((add (l r)) (return (+ (eval l) (eval r))))))
(fn show ((self (* const expr))) void
(match (* self)
((lit (v)) (printf "%g" v))
((neg (e)) (printf "-") (show e))
((add (l r)) (printf "(") (show l) (printf " + ") (show r) (printf ")"))))
;;; No fields anywhere: the record is the tag alone, with no union
(sum light ((red ()) (green ())))
(fn mk-shape () shape (return (shape/circle 1.0)))
(sum held ((a ((x int) (y int))) (b ())))
(fn mk-held () held (return (held/a 1 2)))
(pub fn main () int
(printf "%.2f %.2f %.2f\n"
(area (mk-shape))
(area (shape/rect 3.0 4.0))
(area (shape/empty)))
;; the scrutinee is a call, so it is read into a local once
(match (mk-held)
((a (x _)) (printf "held once: a %d\n" x)) ; `_' drops y
(else (printf "held once: other\n")))
(var two expr (expr/lit 2.0))
(var three expr (expr/lit 3.0))
(var both expr (expr/add (& two) (& three)))
(var e expr (expr/neg (& both)))
(printf "nested: ")
(show (& e))
(printf " = %g\n" (eval (& e)))
(var l light (light/green))
(match l
((red ()) (printf "tagged only: 0\n"))
((green ()) (printf "tagged only: 1\n")))
(return 0))

View File

@@ -9,6 +9,11 @@
type-pattern-matches?
map-fields
add-sum!
get-sum
variant-fields
normalize-fields
add-method!
get-method
qualify-op

View File

@@ -9,6 +9,11 @@
type-pattern-matches?
map-fields
add-sum!
get-sum
variant-fields
normalize-fields
add-method!
get-method
qualify-op

View File

@@ -90,6 +90,25 @@
(define (type-of form) ((current-type-of) form))
;;; A sum's variants, in declaration order:
;;;
;;; (sum shape ((circle ((r float))) (empty ())))
;;; -> shape -> ((circle (r float)) (empty))
;;;
;;; Fields are normalized, so a caller counts them and reads their
;;; types without re-parsing the declaration.
(define +sum-db+ (make-hash-table))
(define (add-sum! name variants)
(hash-table-set! +sum-db+ name variants))
(define (get-sum name)
(hash-table-ref/default +sum-db+ name #f))
(define (variant-fields variants name)
(let ((entry (assq name variants)))
(and entry (cdr entry))))
;;; Methods of an `ops' block: (type . method) -> the qualified name
;;; the call is rewritten to.
;;;