Add encapsulation, sum types, type constraints and all the required machinery. Also -> threading macro #64

Merged
pkulev merged 40 commits from static-dispatch into main 2026-10-19 17:07:45 +02:00
13 changed files with 363 additions and 7 deletions
Showing only changes of commit 6181a6c8d4 - Show all commits

View File

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

125
semen.scm
View File

@@ -83,6 +83,10 @@
((or ('fn . _)
('pub 'fn . _)
('extern 'fn . _)) (process-fn sex-form acc))
((or ('spec . _)
('pub 'spec . _)) (process-spec sex-form acc))
((or ('realize . _)
('pub 'realize . _)) (process-realize sex-form acc))
(('ops . _) (process-ops sex-form acc))
(('pub 'ops . _)
(sex-error sex-form "pub belongs on the methods, not on ops" sex-form))
@@ -99,14 +103,19 @@
((or ('var . _)
('pub 'var . _)
('extern 'var . _)) (process-global-var sex-form acc))
(('include . includes) (process-includes sex-form includes acc))
;; `pub' on either of these is what read-public-interface already
;; accepts, and a module whose spec defaults call printf has to be
;; able to say so
((or ('include . includes)
('pub 'include . includes)) (process-includes sex-form includes acc))
((or ('define name . _)
('pub 'define name . _))
(add-define name sex-form)
(cons sex-form acc))
(('comment . _) (cons sex-form acc))
(('import . modules)
((or ('import . modules)
('pub 'import . modules))
(process-imports (get-modules-public-forms modules) acc))
((or ('defmacro . rest)
@@ -272,6 +281,118 @@
(with-docstring doc processed
(append (hash-table-ref env :lambda-aux-code) acc))))))
;;; (spec (printable T) (fn show ((self (* const T))) void))
;;;
;;; declares a contract and emits nothing: a spec method only exists
;;; once some type realizes it, and then once per type.
(define (process-spec form acc)
(let* ((core (if (eq? (car form) 'pub) (cdr form) form))
(head (and (pair? (cdr core)) (cadr core)))
(methods (remove comment-form? (cddr core))))
(unless (and (list? head) (= 2 (length head))
(symbol? (car head)) (symbol? (cadr head)))
(sex-error form "a spec is (spec (name T) methods ...)" form))
(let ((name (car head)))
(when (get-spec name)
(sex-error form "spec is already declared" name))
(for-each (lambda (m)
(unless (and (pair? m) (eq? (car m) 'fn)
(pair? (cdr m)) (symbol? (second m)))
(sex-error form "a spec takes fn forms" m)))
methods)
(add-spec! name (cadr head) methods)
acc)))
;;; (realize (printable expr) (fn show ((self (* const expr))) void ...))
;;;
;;; is the spec's methods for one type: the ones written here, plus a
;;; copy of every default the spec carries, each with the parameter
;;; substituted and the name mangled to exprːprintableːshow. They land
;;; in the ops registry beside inherent methods, so (.show e) finds
;;; them and a name used twice on one type is caught either way.
(define (process-realize form acc)
(let* ((pub? (eq? (car form) 'pub))
(core (if pub? (cdr form) form))
(head (and (pair? (cdr core)) (cadr core)))
(given (remove comment-form? (cddr core))))
(unless (and (list? head) (= 2 (length head))
(symbol? (car head)) (symbol? (cadr head)))
(sex-error form "a realization is (realize (spec type) methods ...)" form))
(let* ((name (car head))
(type (cadr head))
(spec (or (get-spec name)
(sex-error form "no such spec" name))))
(when (realizes? name type)
(sex-error form "spec is already realized for" name type))
(add-realization! name type)
(let ((wanted (spec-methods spec))
(parameter (spec-parameter spec)))
(check-realization form name type parameter wanted given)
(fold (lambda (entry acc)
(process-realized-method form name type
(and pub? (cdr entry)) (car entry) acc))
acc
(realization-methods type parameter wanted given))))))
;;; What is written here, which a pub realization exports, and then
;;; every default nobody overrode, which it does not: a default is
;;; synthesized again in every unit that imports the realization, so
;;; exporting one too would be a second definition of one symbol.
(define (realization-methods type parameter wanted given)
(append (map (lambda (g) (cons g #t)) given)
(filter-map
(lambda (w)
(and (> (length w) 4) ; carries a body, so a default
(not (find (lambda (g) (eq? (second g) (second w))) given))
(cons (substitute-parameter parameter type w) #f)))
wanted)))
(define (check-realization form name type parameter wanted given)
(for-each
(lambda (g)
(unless (and (pair? g) (eq? (car g) 'fn) (pair? (cdr g)) (symbol? (second g)))
(sex-error form "a realization takes fn forms" g))
(let ((w (find (lambda (w) (eq? (second w) (second g))) wanted)))
(unless w
(sex-error form "spec has no such method" name (second g)))
(let ((expected (substitute-parameter parameter type w)))
(unless (equal? (arglist-types (sex-fn-arglist expected))
(arglist-types (sex-fn-arglist g)))
(sex-error form "method's arguments do not match the spec" (second g)))
(unless (equal? (sex-fn-return-type expected) (sex-fn-return-type g))
(sex-error form "method's return type does not match the spec"
(second g))))))
given)
(let ((missing (filter-map
(lambda (w)
(and (= (length w) 4) ; no body, so required
(not (find (lambda (g) (eq? (second g) (second w))) given))
(second w)))
wanted)))
(when (pair? missing)
(apply sex-error form "realization is missing a method of" name missing))))
;;; A realization is public or private as a unit -- its methods do
;;; not carry `pub' of their own, the way an ops block's do, because
;;; the spec already says which of them there are.
(define (process-realized-method form spec type pub? method acc)
(let* ((name (second method))
(qualified (qualify-op (qualify-op type spec) name))
(renamed (rename-fn method qualified)))
(when (get-method type name)
(sex-error form "method is already defined on" type name))
(add-method! type name qualified)
(process-fn (copy-form-source! form (if pub? (cons 'pub renamed) renamed))
acc)))
;;; T in a spec's method stands for whatever realizes it
(define (substitute-parameter parameter type form)
(cond ((eq? form parameter) type)
((pair? form) (recons form
(substitute-parameter parameter type (car form))
(substitute-parameter parameter type (cdr form))))
(else form)))
;;; (ops vec2
;;; (pub fn length ((self (* const vec2))) float ...))
;;;

View File

@@ -32,7 +32,11 @@
(only types get-type-info get-tag-info get-fields
get-underlying-type type-match type-pattern-matches?
map-fields
get-name-type get-return-type type-of))
get-name-type get-return-type type-of
;; what a generic asks before it expands:
;; (realizes? 'ord type) beats a wall of C
;; errors two stages downstream
realizes? get-method))
,@body)))
(define (get-macro name)

View File

@@ -40,6 +40,8 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
"fn"
"pub"
"record"
"realize"
"spec"
"struct"
"sum"
"var"
@@ -85,6 +87,9 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
(put 'defmacro 'lisp-indent-function 'defun)
(put 'record 'lisp-indent-function 'defun)
(put 'sum 'lisp-indent-function 'defun)
(put 'spec 'lisp-indent-function 'defun)
(put 'realize 'lisp-indent-function 'defun)
(put 'ops 'lisp-indent-function 'defun)
(put 'match 'lisp-indent-function 1)
(put 'struct 'lisp-indent-function 'defun)
(put 'union 'lisp-indent-function 'defun)

View File

@@ -107,6 +107,19 @@
(copy-form-source! form
`(ops ,type ,@(map public-fn-interface methods))))))
;;; A realization leaves with the methods written in it, reduced to
;;; prototypes. Its defaults do not travel: the importer synthesizes
;;; its own static copies from the spec, which is why a default is
;;; static even when the realization is pub.
(define (realize-public-interface form)
(let ((core (cdr form)))
(copy-form-source!
form
`(pub realize ,(second core)
;; pub goes back on at the realize, not on its methods
,@(map (lambda (m) (cdr (public-fn-interface (cons 'pub m))))
(remove comment-form? (cddr core)))))))
;;; TODO: use semen facilities to analyze modules
(define (process-public-interface-form form acc)
(match form
@@ -117,11 +130,13 @@
(('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 'sum 'typedef 'union) . _)
(('pub (or 'define 'defmacro 'enum 'import 'include 'record 'spec 'struct 'sum 'typedef 'union) . _)
(cons (copy-form-source! form (cdr form)) acc))
(('ops . _)
(let ((exported (ops-public-interface form)))
(if exported (cons exported acc) acc)))
(('pub 'realize . _)
(cons (realize-public-interface form) acc))
(('pub . _)
(sex-error form "pub must be followed by a definition" form))
(_ acc)))

View File

@@ -25,6 +25,16 @@
"(fn f () void (var s shape (shape/circle 1.0)) (var out float 0.0) "
(apply string-append body) ")"))
(define (spec-src . body)
(string-append
"(record v ((x int)))"
"(spec (p T)"
" (fn s ((self (* const T))) void)"
" (fn both ((self (* const T))) void (.s self)))"
"(realize (p v)"
" (fn s ((self (* const v))) void (return)))"
(apply string-append body)))
(test-group "encapsulation"
;; A record is a struct plus a typedef of its own name, so the bare
@@ -127,6 +137,79 @@
(test-assert "a variant is a name and a field list"
(reports? "(sum t (a))" "a variant is")))
;; A spec is a contract that emits nothing; a realization is its
;; methods for one type. The refusals are what make it a contract.
(test-group "spec and realize"
(test-assert "a spec on its own emits nothing"
(not (emits? "(spec (p T) (fn s ((a (* const T))) void))" "p")))
(test-assert "a realization mangles type, spec and method"
(emits? (spec-src "") "void vːpːs"))
(test-assert "a default is copied per realizing type"
(emits? (spec-src "") "vːpːboth"))
(test-assert "and its parameter is substituted"
(emits? (spec-src "") "void vːpːboth (const v * self)"))
(test-assert "a default calls that type's own required method"
(emits? (spec-src "") "vːpːs(self)"))
(test-assert "a default is static even when the realization is pub"
(emits? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void)"
" (fn d ((a (* const T))) void (.s a)))"
"(pub realize (p v)"
" (fn s ((a (* const v))) void (return)))")
"static void vːpːd"))
(test-assert "but a written method is not"
(not (emits? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(pub realize (p v)"
" (fn s ((a (* const v))) void (return)))")
"static void vːpːs")))
(test-assert "a spec method answers to .method"
(emits? (spec-src "(fn f () void (var a v #(v : 1)) (.s (& a)))") "vːpːs(&a)"))
(test-assert "a spec is declared once"
(reports? "(spec (p T) (fn s ((a T)) void))(spec (p T) (fn q ((a T)) void))"
"spec is already declared"))
(test-assert "a type realizes a spec once"
(reports? (string-append (spec-src "") "(realize (p v)"
" (fn s ((a (* const v))) void (return)))")
"spec is already realized for"))
(test-assert "a realization names a spec that exists"
(reports? "(record v ((x int)))(realize (nope v))" "no such spec"))
(test-assert "every required method is provided"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void)"
" (fn q ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) void (return)))")
"realization is missing a method of"))
(test-assert "and the missing one is named"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void)"
" (fn q ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) void (return)))")
"q"))
(test-assert "a method the spec has not got is refused"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) void (return))"
" (fn z ((a (* const v))) void (return)))")
"spec has no such method"))
(test-assert "a return type has to match the spec"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) int (return 1)))")
"return type does not match"))
(test-assert "so do the arguments"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(realize (p v) (fn s ((a v)) void (return)))")
"arguments do not match"))
(test-assert "a method name already taken on the type is refused"
(reports? (string-append "(record v ((x int)))"
"(ops v (fn s ((a (* const v))) void (return)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) void (return)))")
"method is already defined on")))
;; match is a switch over the tag whose arms bind the payload. What
;; it refuses is why it exists.
(test-group "match"

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\ncolour 123
EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7\nvec2(3 4)\ncolour 123
check:
@$(SEXC) greet.sex -c -o greet.o

View File

@@ -38,6 +38,8 @@
(var v vec2 #(vec2 : 3 4))
(printf "vec2 %d %d\n" (.manhattan v) (vec2/manhattan (& v)))
(.show-line v)
(var c colour (colour/rgb 1 2 3))
(match c
((rgb (r g b)) (printf "colour %d%d%d\n" r g b))

View File

@@ -5,7 +5,7 @@
;;; the compiled object still has to be handed to the C compiler. See
;;; greet-app.sex.
(include stdio.h)
(pub include stdio.h)
(pub var greet-count ;; a comment in the header of a public form is
;; not part of it: what the importer is given has
@@ -65,6 +65,20 @@
;;; static: two units defining colourːrgb would not link.
(pub sum colour ((rgb ((r int) (g int) (b int))) (none ())))
;;; A spec and a realization over the boundary. The written method
;;; travels as a prototype and keeps external linkage; the default
;;; does not travel at all -- the importer synthesizes its own static
;;; copy from the spec, which is why a default is static even here.
(pub spec (printable T)
(fn show ((self (* const T))) void)
(fn show-line ((self (* const T))) void
(.show self)
(printf "\n")))
(pub realize (printable vec2)
(fn show ((self (* const vec2))) void
(printf "vec2(%d %d)" (-> self x) (-> self y))))
;;; Not `pub': invisible to importers, and static in the generated C.
(fn unused-helper () void
(printf "private\n"))

View File

@@ -0,0 +1,68 @@
(input)
(output "$12.34"
"(3, 4)"
"max 1234"
"realizes ord: money 1, point 0")
(return 0)
;;; A spec is a contract and emits nothing; a realization is the
;;; spec's methods for one type, mangled typeːspecːmethod. A default
;;; is copied into every realizing type with the parameter
;;; substituted, so the `show' it calls is that type's own.
;;;
;;; What the layer is for is the last line: a generic asks `realizes?'
;;; before it expands, and says so itself rather than leaving a wall
;;; of C errors two stages downstream.
(include stdio.h)
(record money ((cents int)))
(record point ((x int) (y int)))
(spec (printable T)
(fn show ((self (* const T))) void)
(fn show-line ((self (* const T))) void ; default, calls the required one
(.show self)
(printf "\n")))
(spec (ord T)
(fn less ((a (* const T)) (b (* const T))) bool))
(realize (printable money)
(fn show ((self (* const money))) void
(printf "$%d.%02d" (/ (-> self cents) 100) (% (-> self cents) 100))))
(realize (printable point)
(fn show ((self (* const point))) void
(printf "(%d, %d)" (-> self x) (-> self y))))
(realize (ord money)
(fn less ((a (* const money)) (b (* const money))) bool
(return (< (-> a cents) (-> b cents)))))
;;; A bounded generic: the macro refuses before it expands
(defmacro (max-of type)
(unless (realizes? 'ord type)
(error "does not realize ord" type))
`(fn ,(cat 'max- type) ((a (* const ,type)) (b (* const ,type))) ,type
(if (,(cat type '/ord/less) a b)
(return (* b))
(return (* a)))))
(max-of money)
(defmacro (ord? type) (if (realizes? 'ord type) 1 0))
(pub fn main () int
(var m money #(money : 1234))
(var p point #(point : 3 4))
(.show-line m) ; the default, through the registry
(point/printable/show-line (& p)) ; and spelled out
(var cheap money #(money : 150))
(var big money (max-money (& m) (& cheap)))
(printf "max %d\n" (. big cents))
(printf "realizes ord: money %d, point %d\n" (ord? money) (ord? point))
(return 0))

View File

@@ -13,6 +13,13 @@
get-sum
variant-fields
reset-declarations!
add-spec!
get-spec
spec-parameter
spec-methods
add-realization!
realizes?
normalize-fields
add-method!

View File

@@ -13,6 +13,13 @@
get-sum
variant-fields
reset-declarations!
add-spec!
get-spec
spec-parameter
spec-methods
add-realization!
realizes?
normalize-fields
add-method!

View File

@@ -109,12 +109,41 @@
(let ((entry (assq name variants)))
(and entry (cdr entry))))
;;; A spec is a parameter and a list of methods, each of which either
;;; declares a signature or also carries a default body:
;;;
;;; (spec (printable T) (fn show ((self (* const T))) void))
;;; -> printable -> (T (fn show ((self (* const T))) void))
;;;
;;; And a realization is only ever asked whether it exists -- the
;;; methods it provides land in +ops-db+ like any others.
(define +spec-db+ (make-hash-table))
(define +realize-db+ (make-hash-table))
(define (add-spec! name parameter methods)
(hash-table-set! +spec-db+ name (cons parameter methods)))
(define (get-spec name)
(hash-table-ref/default +spec-db+ name #f))
(define (spec-parameter spec) (car spec))
(define (spec-methods spec) (cdr spec))
(define (add-realization! spec type)
(hash-table-set! +realize-db+ (cons spec type) #t))
;;; What a generic macro asks before it expands: (realizes? 'ord 'circle)
(define (realizes? spec type)
(hash-table-exists? +realize-db+ (cons spec type)))
;;; Both of these refuse a second declaration of the same name, which
;;; is per translation unit rather than per process -- so a process
;;; that compiles two units has to start the second one clean.
(define (reset-declarations!)
(set! +sum-db+ (make-hash-table))
(set! +ops-db+ (make-hash-table)))
(set! +ops-db+ (make-hash-table))
(set! +spec-db+ (make-hash-table))
(set! +realize-db+ (make-hash-table)))
;;; Methods of an `ops' block: (type . method) -> the qualified name
;;; the call is rewritten to.