forked from alex-eg/sex
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:
19
types.scm
19
types.scm
@@ -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.
|
||||
;;;
|
||||
|
||||
Reference in New Issue
Block a user