From 2512d52dd13efd1a81a62ef7015016a45c4f6b95 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 3 Oct 2026 22:28:14 +0300 Subject: [PATCH 01/40] keep a module's public forms in declaration order read-public-interface folded with cons and never reversed, so an imported pub fn whose prototype named a type declared above it in the same module was pasted before that type, and the unit did not compile. --- sex-modules.scm | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/sex-modules.scm b/sex-modules.scm index 9939bd8..744e68a 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -65,12 +65,16 @@ module-path)))) (define (read-public-interface module-path) - ;; pub fns are reduced to prototypes, other pub forms are just pasted + ;; pub fns are reduced to prototypes, other pub forms are just pasted. + ;; Declaration order is kept: a module that declares a type and then a + ;; pub fn taking it has to paste them that way round, or the prototype + ;; names a type C has not seen. (let ((raw-forms (read-from-file module-path))) - (fold - process-public-interface-form - (list) - raw-forms))) + (reverse + (fold + process-public-interface-form + (list) + raw-forms)))) (define (public-fn-interface raw-form) ;; (pub fn name args ret . body) -> prototype, keeping a docstring so -- 2.52.0 From 622db8eadc5b6450fa2f68a0787797095c0245d6 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 3 Oct 2026 22:28:48 +0300 Subject: [PATCH 02/40] add record, a struct that names itself (record point ...) emits the struct and a typedef of the same name, so point stands alone wherever (struct point) had to -- in a var, a pointer, an arglist, a sizeof. struct, union and enum keep C's meaning, for a type that came from a header or is laid out to match one. --- Makefile | 1 + semen.scm | 22 +++++++++++++++++ sex-mode.el | 2 ++ sex-modules.scm | 2 +- tests/sex-programs/records.sex | 45 ++++++++++++++++++++++++++++++++++ 5 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 tests/sex-programs/records.sex diff --git a/Makefile b/Makefile index a0924ab..c1b6a37 100644 --- a/Makefile +++ b/Makefile @@ -109,6 +109,7 @@ SEX_TEST_PROGRAMS = c99 \ lambdas \ lists \ operators \ + records \ serialize \ type-shapes \ unicode \ diff --git a/semen.scm b/semen.scm index e1952ea..96bb6e4 100644 --- a/semen.scm +++ b/semen.scm @@ -82,6 +82,8 @@ ((or ('fn . _) ('pub 'fn . _) ('extern 'fn . _)) (process-fn sex-form acc)) + ((or ('record . _) + ('pub 'record . _)) (process-record sex-form acc)) ((or ('struct . _) ('pub 'struct . _)) (process-struct sex-form acc)) ((or ('union . _) @@ -1120,6 +1122,26 @@ (register-aggregate! form) (with-docstring doc form acc)))) +;;; (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). +;;; +;;; struct, union and enum keep C's meaning, for a type that comes from +;;; a header or is laid out to match one. +(define (process-record form acc) + (let* ((core (if (eq? (car form) 'pub) (cdr form) form)) + (name (and (pair? (cdr core)) (cadr core)))) + (unless (symbol? name) + (sex-error form "record needs a name" form)) + (add-typedef name `(typedef ,name (struct ,name))) + (cons (copy-form-source! form `(typedef (struct ,name) ,name)) + (process-struct + (copy-form-source! form + (if (eq? (car form) 'pub) + `(pub struct ,@(cdr core)) + `(struct ,@(cdr core)))) + acc)))) + (define (register-aggregate! form) (let* ((f (if (eq? (car form) 'pub) (cdr form) form)) (name (and (pair? (cdr f)) (symbol? (cadr f)) (cadr f)))) diff --git a/sex-mode.el b/sex-mode.el index b2197d0..2b45b6f 100644 --- a/sex-mode.el +++ b/sex-mode.el @@ -39,6 +39,7 @@ All commands in `lisp-mode-shared-map' are inherited by this map.") "include" "fn" "pub" + "record" "struct" "var" "union") @@ -81,6 +82,7 @@ All commands in `lisp-mode-shared-map' are inherited by this map.") (put 'fn 'lisp-indent-function 'defun) (put 'pub 'lisp-indent-function 'defun) (put 'defmacro 'lisp-indent-function 'defun) +(put 'record 'lisp-indent-function 'defun) (put 'struct 'lisp-indent-function 'defun) (put 'union 'lisp-indent-function 'defun) (put 'var 'lisp-indent-function 0) diff --git a/sex-modules.scm b/sex-modules.scm index 744e68a..595a6dc 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -100,7 +100,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 'struct 'typedef 'union) . _) + (('pub (or 'define 'defmacro 'enum 'import 'include 'record 'struct 'typedef 'union) . _) (cons (copy-form-source! form (cdr form)) acc)) (('pub . _) (sex-error form "pub must be followed by a definition" form)) diff --git a/tests/sex-programs/records.sex b/tests/sex-programs/records.sex new file mode 100644 index 0000000..9c0eefd --- /dev/null +++ b/tests/sex-programs/records.sex @@ -0,0 +1,45 @@ +(input) +(output "p 3 4 / n 7 zoe / area 12 / sizes 8 8") +(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))) + +(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))) + (return (+ (. [ps 1] x) (- (. r a) 1)))) -- 2.52.0 From dea36e3c02ab4676bfae115dee1e81869dd83426 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 3 Oct 2026 22:29:55 +0300 Subject: [PATCH 03/40] implement ops MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A method is reachable two ways, spelled out as vec2/length or through its receiver as (. v length), and both land on the same function. The registry behind the second one is why this is a form and not a defmacro: a macro expands and vanishes, while resolution, module export and the spec bounds still to come all want a declaration site they can read. The receiver is adjusted to whatever the method asks for -- & where a value meets a pointer self, * where a pointer meets a value one -- so the call reads the same whichever is in hand. A field wins over a method of the same name, so adding one cannot shadow a field in silence, and needing & on something that is not an lvalue is refused here rather than by cc: &(f()) is not C, and an expression has nowhere to put a temporary. Qualified names are spelled vec2ːlength. The compiler composes them and the user does not, so __ would collide with a hand-written vec2__length, and is reserved in C++ besides. The separator has to be a letter, C admitting letters in an identifier and not symbols, which is what ruled out § -- hence U+02D0, on the same grounds as the ƛ a lifted closure carries. A block crosses a module boundary as a block, its pub methods cut down to prototypes. Prototypes alone would say that vec2ːlength exists without saying that vec2 has a length, and the receiver needs the second thing; which is also why sex-modules now links against types. --- Makefile | 5 +- fmt-c-writer.scm | 18 +++++-- semen.scm | 98 +++++++++++++++++++++++++++++++++++++ sex-modules.scm | 20 ++++++++ tests/Makefile | 4 +- tests/modules/Makefile | 2 +- tests/modules/greet-app.sex | 4 ++ tests/modules/greet.sex | 12 +++++ tests/sex-programs/ops.sex | 52 ++++++++++++++++++++ tests/types.module.scm | 5 ++ types.module.scm | 5 ++ types.scm | 31 ++++++++++++ 12 files changed, 246 insertions(+), 10 deletions(-) create mode 100644 tests/sex-programs/ops.sex diff --git a/Makefile b/Makefile index c1b6a37..ccb9dd6 100644 --- a/Makefile +++ b/Makefile @@ -72,8 +72,8 @@ sex-macros.o: sex-macros.module.scm sex-macros.scm reader.o: reader.module.scm reader.scm utils.o $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) reader.module.scm -o reader.o -unit reader -link utils -sex-modules.o: sex-modules.module.scm sex-modules.scm reader.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-modules.module.scm -o sex-modules.o -unit sex-modules -link reader,utils +sex-modules.o: sex-modules.module.scm sex-modules.scm reader.o types.o utils.o + $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-modules.module.scm -o sex-modules.o -unit sex-modules -link reader,types,utils semen.o: semen.module.scm semen.scm infer.o sex-macros.o sex-modules.o types.o utils.o $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) semen.module.scm -o semen.o -unit semen -link sex-macros,sex-modules,infer,types,utils @@ -109,6 +109,7 @@ SEX_TEST_PROGRAMS = c99 \ lambdas \ lists \ operators \ + ops \ records \ serialize \ type-shapes \ diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 05f9b8b..56ad82d 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -94,15 +94,23 @@ forms, and what remains." (cons (walk-stmt (cadr cs)) (cons (walk-expr (car cs)) acc))))))) +;;; mouse-x -> mouse_x, vec2/length -> vec2ːlength. +;;; +;;; `ː' is U+02D0, a modifier letter, because C takes letters in an +;;; identifier and not symbols -- clang rejects `§' outright. Not `__', +;;; because the compiler composes these names and the user does not: a +;;; hand-written vec2__length would collide, and an identifier holding +;;; `__' is reserved in C++, which a pub header may be included from. +;;; Lifted closures carry a ƛ for the same reason. (define (unkebabify sym) (case sym - ((-) sym) - ((--) sym) - ((->) sym) - ((-=) sym) + ((- -- -> -= / /=) sym) ; bare operators, not names (else (string->symbol - (irregex-replace/all "-(?!>)" (symbol->string sym) "_"))))) + (irregex-replace/all + "/" + (irregex-replace/all "-(?!>)" (symbol->string sym) "_") + "ː"))))) (define (atom-to-fmt-c atom) (case atom diff --git a/semen.scm b/semen.scm index 96bb6e4..f8b8af7 100644 --- a/semen.scm +++ b/semen.scm @@ -82,6 +82,9 @@ ((or ('fn . _) ('pub 'fn . _) ('extern 'fn . _)) (process-fn 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)) ((or ('record . _) ('pub 'record . _)) (process-record sex-form acc)) ((or ('struct . _) @@ -259,6 +262,39 @@ (with-docstring doc processed (append (hash-table-ref env :lambda-aux-code) acc)))))) +;;; (ops vec2 +;;; (pub fn length ((self (* const vec2))) float ...)) +;;; +;;; is (pub fn vec2/length ...) plus a registry entry, so that +;;; (. v length) can find it later. The block itself never reaches the +;;; writer; `pub' inside it means what it means outside. +(define (process-ops form acc) + (let ((type (and (pair? (cdr form)) (cadr form)))) + (unless (symbol? type) + (sex-error form "ops needs a type name" form)) + (fold (lambda (method acc) (process-op type method acc)) + acc + (cddr form)))) + +(define (process-op type form acc) + (if (comment-form? form) + (cons form acc) + (let ((core (and (pair? form) (fn-core form)))) + (unless (and (pair? core) (eq? (car core) 'fn) + (pair? (cdr core)) (symbol? (second core))) + (sex-error form "ops takes fn forms" form)) + (let ((name (second core))) + (when (get-method type name) + (sex-error form "method is already defined on" type name)) + (let ((qualified (qualify-op type name))) + (add-method! type name qualified) + (process-fn (rename-fn form qualified) acc)))))) + +(define (rename-fn form name) + (if (memq (first form) '(pub extern)) + (copy-form-source! form (cons (first form) (rename-fn (cdr form) name))) + (copy-form-source! form `(fn ,name ,@(cddr form))))) + (define (make-fn-env fn-form) (let ((env (make-hash-table)) (parameters (make-hash-table))) @@ -430,6 +466,8 @@ (cddr walked)))) walked))) + ((dot-access ->) (walk-member-access form env)) + (else (let ((closure (receiver-closure-type (car form) env))) (if closure @@ -556,6 +594,66 @@ (define (walk-parts form env) (copy-form-source! form (walk-body form env))) +;;; (. v length) is member access while `length' is a field of v, and a +;;; call to vec2ːlength once it is a method: +;;; +;;; (. v length) -> (vec2/length (& v)) +;;; (-> p length) -> (vec2/length p) +;;; (. v x) -> untouched, v.x +;;; +;;; A field wins, so adding a method cannot quietly shadow one. +(define (walk-member-access form env) + (let* ((arrow? (eq? (first form) '->)) + (object (second form)) + (name (and (>= (length form) 3) (third form))) + (type (let ((written (expression-type object env))) + (if arrow? (pointer-target written) written))) + (key (and (symbol? name) (ops-key type))) + (method (and key + (not (member-path-type type (list name))) + (get-method key name)))) + (if method + (copy-form-source! + form + `(,method + ,(method-receiver method arrow? (walk-statement object env) form) + ,@(map (lambda (argument) (walk-statement argument env)) + (cdddr form)))) + (convert-arguments (walk-parts form env) env)))) + +;;; A method taking (* Self) wants an address and one taking Self wants +;;; a value; the receiver was written as one or the other, so one of +;;; the two needs `&' or `*' put in front of it +(define (method-receiver method arrow? object form) + (let ((pointer? (let ((self (method-self-type method))) + (and (pair? self) (eq? '* (car self)))))) + (cond ((eq? pointer? arrow?) object) + ((not pointer?) `(* ,object)) + ;; `&(f())' is not C, and the method cannot be given a + ;; temporary from inside an expression + ((not (lvalue? object)) + (sex-error form "receiver is not an lvalue; bind it to a var first" + method)) + (else `(& ,object))))) + +(define (lvalue? expr) + (cond ((symbol? expr) #t) + ((vector? expr) #t) ; a compound literal is one + ((not (pair? expr)) #f) + (else (case (car expr) + ((dot-access -> ¤) #t) + ((*) (= 2 (length expr))) + (else #f))))) + +(define (method-self-type method) + (let ((signature (get-name-type method))) + (and (pair? signature) + (eq? 'fn (car signature)) + (pair? (cdr signature)) + (pair? (second signature)) + (let ((self (car (second signature)))) + (if (pair? self) (car self) self))))) + (define (as-closure-type type) (cond diff --git a/sex-modules.scm b/sex-modules.scm index 595a6dc..973aa9d 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -11,6 +11,7 @@ matchable reader srfi-1 + types utils) (define +persistent-module-paths+ (list)) @@ -90,6 +91,22 @@ (('pub 'fn name args ret . _) `(pub fn ,name ,args ,ret))))) +;;; An ops block is not pub itself -- its methods are. The block leaves +;;; as a block, its pub methods reduced to prototypes, so the importer +;;; runs its own `process-ops' over it: prototypes alone would say that +;;; vec2ːlength exists without saying that vec2 has a `length', and +;;; (. v length) needs the second thing. +(define (ops-public-interface form) + (let ((type (and (pair? (cdr form)) (cadr form))) + (methods (filter (lambda (m) + (and (pair? m) (eq? (car m) 'pub) + (pair? (cdr m)) (eq? (cadr m) 'fn))) + (cddr form)))) + (and (symbol? type) + (pair? methods) + (copy-form-source! form + `(ops ,type ,@(map public-fn-interface methods)))))) + ;;; TODO: use semen facilities to analyze modules (define (process-public-interface-form form acc) (match form @@ -102,6 +119,9 @@ (cons (copy-form-source! form `(extern var ,name ,type)) acc))) (('pub (or 'define 'defmacro 'enum 'import 'include 'record 'struct 'typedef 'union) . _) (cons (copy-form-source! form (cdr form)) acc)) + (('ops . _) + (let ((exported (ops-public-interface form))) + (if exported (cons exported acc) acc))) (('pub . _) (sex-error form "pub must be followed by a definition" form)) (_ acc))) diff --git a/tests/Makefile b/tests/Makefile index deae867..afcd4bc 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -29,8 +29,8 @@ sex-macros.o: sex-macros.module.scm ../sex-macros.scm reader.o: reader.module.scm ../reader.scm utils.o $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) reader.module.scm -o reader.o -unit reader -link utils -sex-modules.o: sex-modules.module.scm ../sex-modules.scm reader.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-modules.module.scm -o sex-modules.o -unit sex-modules -link reader,utils +sex-modules.o: sex-modules.module.scm ../sex-modules.scm reader.o types.o utils.o + $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-modules.module.scm -o sex-modules.o -unit sex-modules -link reader,types,utils semen.o: semen.module.scm ../semen.scm infer.o sex-macros.o sex-modules.o types.o utils.o $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) semen.module.scm -o semen.o -unit semen -link sex-macros,sex-modules,infer,types,utils diff --git a/tests/modules/Makefile b/tests/modules/Makefile index 5ff1468..44a2e0a 100644 --- a/tests/modules/Makefile +++ b/tests/modules/Makefile @@ -20,7 +20,7 @@ SEXC ?= ../../sexc -EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201 +EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7 check: @$(SEXC) greet.sex -c -o greet.o diff --git a/tests/modules/greet-app.sex b/tests/modules/greet-app.sex index 5903f81..2e3ba11 100644 --- a/tests/modules/greet-app.sex +++ b/tests/modules/greet-app.sex @@ -33,4 +33,8 @@ (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))) (return 0)) diff --git a/tests/modules/greet.sex b/tests/modules/greet.sex index 43da31e..2e38576 100644 --- a/tests/modules/greet.sex +++ b/tests/modules/greet.sex @@ -48,6 +48,18 @@ (pub fn apply-twice ((f (closure ((int)) int)) (x int)) int (return (f (f x)))) +;;; A record and an ops block crossing the boundary. The record has to +;;; arrive as the struct *and* its typedef, or the bare name does not +;;; work there; the ops block has to arrive as a block rather than as +;;; loose prototypes, or the importer learns that vec2ːmanhattan exists +;;; without learning that vec2 has a `manhattan' -- and (. v manhattan) +;;; needs the second thing. +(pub record vec2 ((x int) (y int))) + +(ops vec2 + (pub fn manhattan ((self (* const vec2))) int + (return (+ (-> self x) (-> self y))))) + ;;; Not `pub': invisible to importers, and static in the generated C. (fn unused-helper () void (printf "private\n")) diff --git a/tests/sex-programs/ops.sex b/tests/sex-programs/ops.sex new file mode 100644 index 0000000..75c45e2 --- /dev/null +++ b/tests/sex-programs/ops.sex @@ -0,0 +1,52 @@ +(input) +(output "5.0 5.0 10.0 14.0 14.0 6.0" + "struct receiver: 14" + "private: 8.0") +(return 0) + +;;; An ops block is mangled fns plus a registry entry, so a method is +;;; reachable both ways: spelled out as vec2/length, or through the +;;; receiver as (. v length). A field still wins over a method of the +;;; same name, and `ops' works on a plain C struct too -- it keys on +;;; the tag, not on the typedef a record happens to add. + +(include stdio.h) +(include math.h) + +(record vec2 ((x float) (y float))) + +(ops vec2 + (pub fn length ((self (* const vec2))) float + "Pointer self, so (. v length) has to take the address." + (return (sqrtf (+ (* (-> self x) (-> self x)) + (* (-> self y) (-> self y)))))) + + (fn scale ((self (* vec2)) (k float)) void + (*= (-> self x) k) + (*= (-> self y) k)) + + (fn sum-of ((self vec2)) float + ;; value self, so (-> p sum-of) has to dereference + (return (+ (. self x) (. self y))))) + +(struct raw ((a int) (b int))) + +(ops raw + (fn total ((self (* const (struct raw)))) int + (return (+ (-> self a) (-> self b))))) + +(pub fn main () int + (var v vec2 #(vec2 : 3.0 4.0)) + (var p (* vec2) (& v)) + + (printf "%.1f %.1f " (. v length) (vec2/length (& v))) + (. v scale 2.0) + (printf "%.1f %.1f %.1f %.1f\n" + (-> p length) (. v sum-of) (-> p sum-of) (. v x)) + + (var r (struct raw) #(struct raw : 6 8)) + (printf "struct receiver: %d\n" (. r total)) + + (var u vec2 #(vec2 : 8.0 0.0)) + (printf "private: %.1f\n" (vec2/sum-of u)) + (return 0)) diff --git a/tests/types.module.scm b/tests/types.module.scm index cf06139..2a6984a 100644 --- a/tests/types.module.scm +++ b/tests/types.module.scm @@ -9,6 +9,11 @@ type-pattern-matches? map-fields + add-method! + get-method + qualify-op + ops-key + add-name-type! get-name-type type-of diff --git a/types.module.scm b/types.module.scm index ed00b5c..dfeef13 100644 --- a/types.module.scm +++ b/types.module.scm @@ -9,6 +9,11 @@ type-pattern-matches? map-fields + add-method! + get-method + qualify-op + ops-key + add-name-type! get-name-type type-of diff --git a/types.scm b/types.scm index f2cfd5e..3ddbf6f 100644 --- a/types.scm +++ b/types.scm @@ -90,6 +90,37 @@ (define (type-of form) ((current-type-of) form)) +;;; Methods of an `ops' block: (type . method) -> the qualified name +;;; the call is rewritten to. +;;; +;;; (ops vec2 (fn length ((self (* const vec2))) float ...)) +;;; -> (vec2 . length) -> vec2/length +;;; +;;; The signature is not kept here; `vec2/length' is an ordinary +;;; function by the time anything asks, so +name-db+ already has it. +(define +ops-db+ (make-hash-table)) + +(define (add-method! type method qualified) + (hash-table-set! +ops-db+ (cons type method) qualified)) + +(define (get-method type method) + (hash-table-ref/default +ops-db+ (cons type method) #f)) + +;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength +(define (qualify-op type name) + (string->symbol + (string-append (symbol->string type) "/" (symbol->string name)))) + +;;; The name an `ops' block was written against: `(struct point)' and a +;;; `const' wrapper both name `point', and anything else names nothing. +(define (ops-key type) + (cond ((symbol? type) type) + ((not (and (pair? type) (symbol? (car type)))) #f) + ((memq (car type) '(struct union enum)) + (and (pair? (cdr type)) (symbol? (cadr type)) (cadr type))) + ((memq (car type) '(const volatile)) (ops-key (cadr type))) + (else #f))) + (define (add-name-type! name type) (hash-table-set! +name-db+ name type)) -- 2.52.0 From 3a10ee099bc15e8b03e484d5962a4eb3d9e51384 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 3 Oct 2026 22:59:15 +0300 Subject: [PATCH 04/40] implement sum and match MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- Makefile | 1 + semen.scm | 170 ++++++++++++++++++++++++++++++++++++ sex-mode.el | 3 + sex-modules.scm | 2 +- tests/modules/Makefile | 2 +- tests/modules/greet-app.sex | 5 ++ tests/modules/greet.sex | 5 ++ tests/sex-programs/sums.sex | 78 +++++++++++++++++ tests/types.module.scm | 5 ++ types.module.scm | 5 ++ types.scm | 19 ++++ 11 files changed, 293 insertions(+), 2 deletions(-) create mode 100644 tests/sex-programs/sums.sex diff --git a/Makefile b/Makefile index ccb9dd6..27126d2 100644 --- a/Makefile +++ b/Makefile @@ -112,6 +112,7 @@ SEX_TEST_PROGRAMS = c99 \ ops \ records \ serialize \ + sums \ type-shapes \ unicode \ unnamed-params \ diff --git a/semen.scm b/semen.scm index f8b8af7..f494db4 100644 --- a/semen.scm +++ b/semen.scm @@ -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). diff --git a/sex-mode.el b/sex-mode.el index 2b45b6f..b2ed808 100644 --- a/sex-mode.el +++ b/sex-mode.el @@ -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) diff --git a/sex-modules.scm b/sex-modules.scm index 973aa9d..e536b43 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -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))) diff --git a/tests/modules/Makefile b/tests/modules/Makefile index 44a2e0a..5b04e57 100644 --- a/tests/modules/Makefile +++ b/tests/modules/Makefile @@ -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 diff --git a/tests/modules/greet-app.sex b/tests/modules/greet-app.sex index 2e3ba11..1667849 100644 --- a/tests/modules/greet-app.sex +++ b/tests/modules/greet-app.sex @@ -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)) diff --git a/tests/modules/greet.sex b/tests/modules/greet.sex index 2e38576..b272404 100644 --- a/tests/modules/greet.sex +++ b/tests/modules/greet.sex @@ -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")) diff --git a/tests/sex-programs/sums.sex b/tests/sex-programs/sums.sex new file mode 100644 index 0000000..bb3cc2a --- /dev/null +++ b/tests/sex-programs/sums.sex @@ -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)) diff --git a/tests/types.module.scm b/tests/types.module.scm index 2a6984a..97bc4f0 100644 --- a/tests/types.module.scm +++ b/tests/types.module.scm @@ -9,6 +9,11 @@ type-pattern-matches? map-fields + add-sum! + get-sum + variant-fields + normalize-fields + add-method! get-method qualify-op diff --git a/types.module.scm b/types.module.scm index dfeef13..26e919b 100644 --- a/types.module.scm +++ b/types.module.scm @@ -9,6 +9,11 @@ type-pattern-matches? map-fields + add-sum! + get-sum + variant-fields + normalize-fields + add-method! get-method qualify-op diff --git a/types.scm b/types.scm index 3ddbf6f..134c78c 100644 --- a/types.scm +++ b/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. ;;; -- 2.52.0 From bbdedb97771900ec0617ed2aaa1d0716ed12f020 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 3 Oct 2026 23:17:44 +0300 Subject: [PATCH 05/40] put the method in the head, not in a field position (. v length) made the shape of a form depend on the receiver's type: (. a b c d e) was either the path a.b.c.d.e or a/b called on c d e, and nothing but the ops registry could say which. Resolution had to arbitrate, a field won, and so adding a field named length to vec2 turned every (. v length) in reach from a call into a read -- silently, and only sometimes into a type error. Resolution may need types; shape must not. (.length v) puts the method where an operator belongs, so (. v x) is always the field x, a field and a method of one name coexist, and a reader needs no symbol table to see where the arguments start. Which of &, * or nothing goes in front of the receiver now follows from its own type against the method's self, rather than from whether the caller wrote . or ->, so (.length v) and (.length p) are the same call and -> is member access again and nothing else. The reader already allowed it: only a standalone . becomes dot-access, and .foo is the ordinary symbol designated initializers are made of. --- semen.scm | 103 +++++++++++++++++++++--------------- tests/modules/greet-app.sex | 2 +- tests/sex-programs/ops.sex | 23 ++++---- 3 files changed, 74 insertions(+), 54 deletions(-) diff --git a/semen.scm b/semen.scm index f494db4..b5e462f 100644 --- a/semen.scm +++ b/semen.scm @@ -470,22 +470,22 @@ ((match) (walk-match form env)) - ((dot-access ->) (walk-member-access form env)) - (else - (let ((closure (receiver-closure-type (car form) env))) - (if closure - ;; the receiver is walked first: `((closure ((x int)) int - ;; () ...) 5)' registers `struct ƛint_int' on the way, and - ;; the call helper's signature names it - (let ((receiver (walk-statement (car form) env))) - (copy-form-source! - form - `(,(register-closure-call! closure form) - ,receiver - ,@(map (lambda (argument) (walk-statement argument env)) - (cdr form))))) - (convert-arguments (walk-parts form env) env)))))))) + (if (method-head? (car form)) + (walk-method-call form env) + (let ((closure (receiver-closure-type (car form) env))) + (if closure + ;; the receiver is walked first: `((closure ((x int)) + ;; int () ...) 5)' registers `struct ƛint_int' on the + ;; way, and the call helper's signature names it + (let ((receiver (walk-statement (car form) env))) + (copy-form-source! + form + `(,(register-closure-call! closure form) + ,receiver + ,@(map (lambda (a) (walk-statement a env)) + (cdr form))))) + (convert-arguments (walk-parts form env) env))))))))) ;;; `(var n _ (strlen s))' becomes `(var n size-t (strlen s))'. (define (resolve-wildcard form env) @@ -686,47 +686,62 @@ ,(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: +;;; (.length v) is a call to vec2ːlength; (. v length) is the field +;;; `length', always. Keeping them apart means the shape of a form can +;;; be read without knowing the receiver's type -- (. a b c d) is a +;;; path and (.b a c d) is a call, and adding a field named like a +;;; method cannot quietly turn calls into reads. ;;; -;;; (. v length) -> (vec2/length (& v)) -;;; (-> p length) -> (vec2/length p) -;;; (. v x) -> untouched, v.x +;;; (.length v) -> (vec2ːlength (& v)) +;;; (.length p) -> (vec2ːlength p) +;;; (.sum-of p) -> (vec2ːsum_of (* p)) ;;; -;;; A field wins, so adding a method cannot quietly shadow one. -(define (walk-member-access form env) - (let* ((arrow? (eq? (first form) '->)) - (object (second form)) - (name (and (>= (length form) 3) (third form))) - (type (let ((written (expression-type object env))) - (if arrow? (pointer-target written) written))) - (key (and (symbol? name) (ops-key type))) - (method (and key - (not (member-path-type type (list name))) - (get-method key name)))) - (if method +;;; Which of those is written is decided by the receiver's type against +;;; the method's own, so the caller never has to match them up. +(define (method-head? head) + (and (symbol? head) + (let ((spelling (symbol->string head))) + (and (> (string-length spelling) 1) + (char=? #\. (string-ref spelling 0)))))) + +(define (method-head-name head) + (string->symbol (substring (symbol->string head) 1))) + +(define (walk-method-call form env) + (let ((name (method-head-name (car form)))) + (unless (pair? (cdr form)) + (sex-error form "a method call needs a receiver" form)) + (let* ((receiver (second form)) + (written (expression-type receiver env)) + (target (pointer-target written)) + (key (ops-key (or target written)))) + (unless key + (sex-error form "receiver of this has no type to dispatch on" name)) + (let ((method (get-method key name))) + (unless method + (sex-error form "no such method on" key name)) (copy-form-source! form `(,method - ,(method-receiver method arrow? (walk-statement object env) form) + ,(method-receiver method (and target #t) + (walk-statement receiver env) form) ,@(map (lambda (argument) (walk-statement argument env)) - (cdddr form)))) - (convert-arguments (walk-parts form env) env)))) + (cddr form)))))))) ;;; A method taking (* Self) wants an address and one taking Self wants -;;; a value; the receiver was written as one or the other, so one of -;;; the two needs `&' or `*' put in front of it -(define (method-receiver method arrow? object form) - (let ((pointer? (let ((self (method-self-type method))) - (and (pair? self) (eq? '* (car self)))))) - (cond ((eq? pointer? arrow?) object) - ((not pointer?) `(* ,object)) +;;; a value; the receiver is one or the other, so one of the two gets +;;; `&' or `*' put in front of it +(define (method-receiver method pointer? receiver form) + (let ((wants-pointer? (let ((self (method-self-type method))) + (and (pair? self) (eq? '* (car self)))))) + (cond ((eq? wants-pointer? pointer?) receiver) + ((not wants-pointer?) `(* ,receiver)) ;; `&(f())' is not C, and the method cannot be given a ;; temporary from inside an expression - ((not (lvalue? object)) + ((not (lvalue? receiver)) (sex-error form "receiver is not an lvalue; bind it to a var first" method)) - (else `(& ,object))))) + (else `(& ,receiver))))) (define (lvalue? expr) (cond ((symbol? expr) #t) diff --git a/tests/modules/greet-app.sex b/tests/modules/greet-app.sex index 1667849..0205f77 100644 --- a/tests/modules/greet-app.sex +++ b/tests/modules/greet-app.sex @@ -36,7 +36,7 @@ ;; 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))) + (printf "vec2 %d %d\n" (.manhattan v) (vec2/manhattan (& v))) (var c colour (colour/rgb 1 2 3)) (match c diff --git a/tests/sex-programs/ops.sex b/tests/sex-programs/ops.sex index 75c45e2..cc4edf6 100644 --- a/tests/sex-programs/ops.sex +++ b/tests/sex-programs/ops.sex @@ -5,9 +5,14 @@ (return 0) ;;; An ops block is mangled fns plus a registry entry, so a method is -;;; reachable both ways: spelled out as vec2/length, or through the -;;; receiver as (. v length). A field still wins over a method of the -;;; same name, and `ops' works on a plain C struct too -- it keys on +;;; reachable both ways: spelled out as vec2/length, or as (.length v). +;;; The method sits in the head, not in a field position, so (. v x) is +;;; always the field x and the two cannot be confused -- here vec2 has +;;; both a field x and methods, and nothing arbitrates between them. +;;; +;;; Whether the receiver is addressed, dereferenced or passed along is +;;; decided by its type against the method's own, so (.length v) and +;;; (.length p) both work. `ops' takes a plain C struct too: it keys on ;;; the tag, not on the typedef a record happens to add. (include stdio.h) @@ -17,7 +22,7 @@ (ops vec2 (pub fn length ((self (* const vec2))) float - "Pointer self, so (. v length) has to take the address." + "Pointer self, so (.length v) has to take the address." (return (sqrtf (+ (* (-> self x) (-> self x)) (* (-> self y) (-> self y)))))) @@ -26,7 +31,7 @@ (*= (-> self y) k)) (fn sum-of ((self vec2)) float - ;; value self, so (-> p sum-of) has to dereference + ;; value self, so (.sum-of p) has to dereference (return (+ (. self x) (. self y))))) (struct raw ((a int) (b int))) @@ -39,13 +44,13 @@ (var v vec2 #(vec2 : 3.0 4.0)) (var p (* vec2) (& v)) - (printf "%.1f %.1f " (. v length) (vec2/length (& v))) - (. v scale 2.0) + (printf "%.1f %.1f " (.length v) (vec2/length (& v))) + (.scale v 2.0) (printf "%.1f %.1f %.1f %.1f\n" - (-> p length) (. v sum-of) (-> p sum-of) (. v x)) + (.length p) (.sum-of v) (.sum-of p) (. v x)) (var r (struct raw) #(struct raw : 6 8)) - (printf "struct receiver: %d\n" (. r total)) + (printf "struct receiver: %d\n" (.total r)) (var u vec2 #(vec2 : 8.0 0.0)) (printf "private: %.1f\n" (vec2/sum-of u)) -- 2.52.0 From 4a649e5bf4059caae1e3a3d21d5a8293e4729886 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 3 Oct 2026 23:33:32 +0300 Subject: [PATCH 06/40] walk the cdr of a form as a list, not as a form The walker offered walk-fn every cdr as well as every form, so the tail (t) of (fn g () t) read as a call to a macro named t: any function whose return type or parameter type shared a name with a macro expanded that tail and died on the macro's arity. --- semen.scm | 28 ++++++++++++++++++---------- tests/codegen.scm | 15 +++++++++++++++ 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/semen.scm b/semen.scm index b5e462f..8e2d1ad 100644 --- a/semen.scm +++ b/semen.scm @@ -29,6 +29,7 @@ ;;; multiple forms, e.g. lambdas collected from a function may result ;;; in auxiliary structures and functions. (define (process raw-sex-forms) + (reset-declarations!) (process-rec raw-sex-forms (list))) (define (process-rec forms acc) @@ -160,16 +161,23 @@ (define (walk-form form walk-fn env) (if (atom? form) form (let ((new-form (walk-fn form env))) - (cond ((not (eq? form new-form)) - (walk-form new-form walk-fn env)) - (else - (let ((new-car (walk-form (car new-form) walk-fn env)) - (new-cdr (walk-form (cdr new-form) walk-fn env))) - (cond ((and (pair? new-car) - (eq? (car new-car) walk-embed-result)) - (append (cdr new-car) new-cdr)) - (else - (recons new-form new-car new-cdr))))))))) + (if (not (eq? form new-form)) + (walk-form new-form walk-fn env) + (walk-rest new-form walk-fn env))))) + +;;; The cdr of a form is a list of forms and not itself one, so it is +;;; walked without being offered to WALK-FN: otherwise the tail of +;;; (fn g () t) is the list (t), which reads as a call to a macro +;;; named t -- and a function whose return type shares a name with a +;;; macro expanded that tail and died on the arity. +(define (walk-rest form walk-fn env) + (if (atom? form) form + (let ((new-car (walk-form (car form) walk-fn env)) + (new-cdr (walk-rest (cdr form) walk-fn env))) + (if (and (pair? new-car) + (eq? (car new-car) walk-embed-result)) + (append (cdr new-car) new-cdr) + (recons form new-car new-cdr))))) ;;; Typdef diff --git a/tests/codegen.scm b/tests/codegen.scm index 51b0a48..fdb3412 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -394,6 +394,21 @@ compiles." (fn f ((c (closure ((int)) int))) int (return (g c)))" "g(c)"))) + ;; The walker offered WALK-FN the cdr of every form as well as the + ;; form, so the tail (t) of (fn g () t) read as a call to a macro + ;; named t, and any function returning a type that shared a name + ;; with a macro died on that macro's arity. + (test-group "a form's tail is not a form" + (test-assert "a return type may share a name with a macro" + (emits? "(defmacro (t x) 1)(typedef t int)(fn g () t (return 1))" + "t g (void)")) + (test-assert "so may a parameter's type" + (emits? "(defmacro (u x) 1)(typedef u int)(fn g ((a u)) void (return))" + "void g (u a)")) + (test-assert "and the macro still expands where it is called" + (emits? "(defmacro (t x) x)(fn g () int (return (t 7)))" + "return 7"))) + ;; a macro body reads types as lists, so the srfi-1 accessors are in ;; scope beside the type database (test-group "macro list accessors" -- 2.52.0 From 07cf85910aaf3ece127d2fbbf01cc922788e0ce6 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 3 Oct 2026 23:33:38 +0300 Subject: [PATCH 07/40] test what record, ops, sum and match refuse The diagnostics are what these forms are for -- a match that leaves a variant out is the thing C cannot say -- and until now every one of them was checked by hand and none by the suite. The two registries refuse a second declaration of one name, which is per translation unit and not per process, so semen-process clears them on the way in. sexc compiles one file per process and never noticed; a suite that compiles forty in one did. --- tests/Makefile | 2 +- tests/encapsulation.scm | 180 ++++++++++++++++++++++++++++++++++++++++ tests/run.scm | 1 + tests/types.module.scm | 1 + types.module.scm | 1 + types.scm | 7 ++ 6 files changed, 191 insertions(+), 1 deletion(-) create mode 100644 tests/encapsulation.scm diff --git a/tests/Makefile b/tests/Makefile index afcd4bc..1e87b3c 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -6,7 +6,7 @@ MODULE_FLAGS = -emit-all-import-libraries -module-registration -c MODULES = utils types infer sex-macros reader sex-modules semen sex-fmt-c fmt-c-writer sexc SEX_OBJ = $(MODULES:%=%.o) -TESTS = basic semen reader fmt-c-writer utils line-directives codegen args types infer +TESTS = basic semen reader fmt-c-writer utils line-directives codegen encapsulation args types infer TEST_SRCS = $(TESTS:%=%.scm) sex-tests: run.scm $(TEST_SRCS) $(SEX_OBJ) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm new file mode 100644 index 0000000..6a18818 --- /dev/null +++ b/tests/encapsulation.scm @@ -0,0 +1,180 @@ +;;; record, ops, sum and match, through the whole pipeline. +;;; +;;; The diagnostics are the point of these forms -- a match that +;;; leaves a variant out is the thing C cannot say -- so most of what +;;; is checked here is what the compiler refuses, and that it refuses +;;; it with the name of whatever is wrong. +;;; +;;; `sex->c', `emits?', `reports?' and `in-fn' come from codegen.scm, +;;; which run.scm includes first. + +(define (ops-src . body) + (string-append + "(record vec2 ((x float) (y float)))" + "(ops vec2" + " (pub fn length ((self (* const vec2))) float (return 1.0))" + " (fn sum-of ((self vec2)) float (return (. self x))))" + "(fn mk () vec2 (return #(vec2 : 1.0 2.0)))" + "(fn f () void (var v vec2 #(vec2 : 1.0 2.0)) (var p (* vec2) (& v)) " + (apply string-append body) ")")) + +(define (sum-src . body) + (string-append + "(sum shape ((circle ((r float))) (rect ((w float) (h float))) (empty ())))" + "(fn mk () shape (return (shape/circle 1.0)))" + "(fn f () void (var s shape (shape/circle 1.0)) (var out float 0.0) " + (apply string-append body) ")")) + +(test-group "encapsulation" + + ;; A record is a struct plus a typedef of its own name, so the bare + ;; name stands where (struct name) had to. + (test-group "record" + (test-assert "emits the struct" + (emits? "(record point ((x int) (y int)))" "struct point {")) + (test-assert "and a typedef of the same name" + (emits? "(record point ((x int) (y int)))" "typedef struct point point;")) + (test-assert "so the bare name is a type" + (emits? "(record point ((x int)))(fn f () void (var p point))" "point p;")) + (test-assert "and so is a pointer to it" + (emits? "(record point ((x int)))(fn f () void (var p (* const point)))" + "const point * p")) + (test-assert "struct keeps C's meaning" + (not (emits? "(struct raw ((x int)))" "typedef"))) + (test-assert "a record needs a name" + (reports? "(record ((x int)))" "record needs a name"))) + + ;; An ops block is mangled functions plus a registry entry. `pub' + ;; inside it means what it means outside. + (test-group "ops" + (test-assert "a method is the type and the name, mangled" + (emits? (ops-src "") "float vec2ːlength")) + (test-assert "a pub method has external linkage" + (not (emits? (ops-src "") "static float vec2ːlength"))) + (test-assert "a private one does not" + (emits? (ops-src "") "static float vec2ːsum_of")) + (test-assert "the slash is not a division" + (emits? "(fn f () int (return (/ 10 2)))" "10 / 2")) + (test-assert "ops needs a type name" + (reports? "(ops (fn g ((s int)) void))" "ops needs a type name")) + (test-assert "and takes only fn forms" + (reports? "(record v ((x int)))(ops v (var n int 1))" "ops takes fn forms")) + (test-assert "a method is defined once" + (reports? (string-append "(record v ((x int)))" + "(ops v (fn g ((s v)) int (return 1))" + " (fn g ((s v)) int (return 2)))") + "method is already defined on")) + (test-assert "pub goes on the methods, not the block" + (reports? "(record v ((x int)))(pub ops v)" "pub belongs on the methods"))) + + ;; The method sits in the head, so the shape of a form can be read + ;; without knowing the receiver's type. + (test-group "method calls" + (test-assert "a value meeting a pointer self is addressed" + (emits? (ops-src "(.length v)") "vec2ːlength(&v)")) + (test-assert "a pointer meeting a pointer self is passed along" + (emits? (ops-src "(.length p)") "vec2ːlength(p)")) + (test-assert "a pointer meeting a value self is dereferenced" + (emits? (ops-src "(.sum-of p)") "vec2ːsum_of(*p)")) + (test-assert "a value meeting a value self is passed along" + (emits? (ops-src "(.sum-of v)") "vec2ːsum_of(v)")) + (test-assert "a field is still a field" + (emits? (ops-src "(var q float (. v x))") "v.x")) + ;; the whole reason the method moved into the head + (test-assert "a field and a method of one name coexist" + (emits? (string-append + "(record w ((x int)))" + "(ops w (fn x ((self (* const w))) int (return 2)))" + "(fn f () void (var a w #(w : 1)) (var b int (. a x))" + " (var c int (.x a)))") + "wːx(&a)")) + (test-assert "and the field reading is untouched" + (emits? (string-append + "(record w ((x int)))" + "(ops w (fn x ((self (* const w))) int (return 2)))" + "(fn f () void (var a w #(w : 1)) (var b int (. a x)))") + "int b = a.x")) + (test-assert "a method that is not there is named" + (reports? (ops-src "(.nope v)") "no such method on")) + (test-assert "and so is a receiver with no type to dispatch on" + (reports? "(fn f () void (var n int 1) (.get n))" "no such method on")) + (test-assert "an address cannot be taken of a call" + (reports? (ops-src "(.length (mk))") "receiver is not an lvalue"))) + + ;; A sum is the tag enum, a payload struct per variant that carries + ;; fields, the record holding both, and a constructor each. + (test-group "sum" + (test-assert "the tag enum is named after the sum" + (emits? (sum-src "") "enum shapeːtag")) + (test-assert "a variant with fields gets a payload struct" + (emits? (sum-src "") "struct shapeːcircle {")) + (test-assert "the sum is typedef'd" + (emits? (sum-src "") "typedef struct shape shape;")) + ;; a typedef here would land in the namespace the constructor holds + (test-assert "a payload struct is not" + (not (emits? (sum-src "") "typedef struct shapeːcircle"))) + (test-assert "the typedef comes before the payloads, for a recursive sum" + (emits? "(sum expr ((lit ((v float))) (neg ((e (* const expr))))))" + "typedef struct expr expr;")) + (test-assert "constructors are static even when the sum is pub" + (emits? "(pub sum t ((a ((x int)))))" "static t tːa")) + (test-assert "a tag-only sum has no union at all" + (not (emits? "(sum light ((red ()) (green ())))" "union"))) + (test-assert "a sum is declared once" + (reports? "(sum t ((a ())))(sum t ((b ())))" "sum is already defined")) + (test-assert "and needs variants" + (reports? "(sum t)" "sum needs a name and a list of variants")) + (test-assert "a variant is a name and a field list" + (reports? "(sum t (a))" "a variant is"))) + + ;; match is a switch over the tag whose arms bind the payload. What + ;; it refuses is why it exists. + (test-group "match" + (test-assert "it switches on the tag" + (emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))" + " ((empty ()) (= out 0.0)))") + "switch (s.tag)")) + (test-assert "an arm binds its payload" + (emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))" + " ((empty ()) (= out 0.0)))") + "float r = ((s.u).circle).r")) + (test-assert "_ binds nothing" + (not (emits? (sum-src "(match s ((circle (r)) (= out r))" + " ((rect (w _)) (= out w))" + " ((empty ()) (= out 0.0)))") + ").h"))) + (test-assert "a scrutinee that is not a path is read once" + (emits? (sum-src "(match (mk) ((circle (r)) (= out r)) (else (= out 0.0)))") + "shape ƛm0 = mk()")) + (test-assert "a path scrutinee is not copied" + (not (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))") + "ƛm0"))) + (test-assert "else becomes default" + (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))") + "default:")) + (test-assert "a comment between arms is dropped" + (emits? (sum-src "(match s ((circle (r)) (= out r)) ;; gone\n (else (= out 0.0)))") + "default:")) + + (test-assert "a variant left out is an error" + (reports? (sum-src "(match s ((circle (r)) (= out r)))") + "match leaves a variant out")) + (test-assert "and the missing ones are named" + (reports? (sum-src "(match s ((circle (r)) (= out r)))") "rect")) + (test-assert "else excuses the rest" + (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))") + "switch (s.tag)")) + (test-assert "a variant the sum does not have is an error" + (reports? (sum-src "(match s ((circle (r)) (= out r)) ((square (w)) (= out w))" + " ((rect (w h)) (= out w)) ((empty ()) (= out 0.0)))") + "not a variant of")) + (test-assert "so is the wrong number of binders" + (reports? (sum-src "(match s ((circle (r q)) (= out r)) (else (= out 0.0)))") + "variant takes this many fields")) + (test-assert "so is the same arm twice" + (reports? (sum-src "(match s ((circle (r)) (= out r)) ((circle (q)) (= out q))" + " (else (= out 0.0)))") + "arm is written twice")) + (test-assert "and a scrutinee that is not a sum" + (reports? "(fn f () void (var n int 1) (match n ((a ()) (= n 2))))" + "match wants a sum")))) diff --git a/tests/run.scm b/tests/run.scm index 4f77bfa..d0cc9ca 100644 --- a/tests/run.scm +++ b/tests/run.scm @@ -8,6 +8,7 @@ (include "utils.scm") (include "line-directives.scm") (include "codegen.scm") +(include "encapsulation.scm") (include "args.scm") (include "types.scm") (include "infer.scm") diff --git a/tests/types.module.scm b/tests/types.module.scm index 97bc4f0..64cca48 100644 --- a/tests/types.module.scm +++ b/tests/types.module.scm @@ -12,6 +12,7 @@ add-sum! get-sum variant-fields + reset-declarations! normalize-fields add-method! diff --git a/types.module.scm b/types.module.scm index 26e919b..e9d039a 100644 --- a/types.module.scm +++ b/types.module.scm @@ -12,6 +12,7 @@ add-sum! get-sum variant-fields + reset-declarations! normalize-fields add-method! diff --git a/types.scm b/types.scm index 134c78c..93e1650 100644 --- a/types.scm +++ b/types.scm @@ -109,6 +109,13 @@ (let ((entry (assq name variants))) (and entry (cdr entry)))) +;;; 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))) + ;;; Methods of an `ops' block: (type . method) -> the qualified name ;;; the call is rewritten to. ;;; -- 2.52.0 From 6181a6c8d41a88e365047337e5d2e410f3625cd8 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 4 Oct 2026 12:56:24 +0300 Subject: [PATCH 08/40] implement spec and realize MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A spec is a contract that emits nothing; a realization is that contract's methods for one type, mangled typeːspecːmethod. A default is copied into every realizing type with the parameter substituted, so the `show' a default calls is that type's own and the whole thing stays static dispatch with nothing left at runtime. The methods land in the ops registry beside inherent ones, which is what lets (.show v) find them with no second lookup -- and makes the duplicate check already there catch a spec method colliding with an ops method or with another spec's. Coherence came free. A realization's signatures are checked against the spec, arguments and return type both, after substituting the parameter; a missing required method is named, and so is one the spec has not got. That is what makes a spec a contract rather than a naming convention. The bound is asked rather than declared: realizes? goes into the macro API beside type-of, and a generic calls it and raises its own error. That is the return this document was written for -- `plain does not realize ord' where the line is, instead of a wall of C errors from a monomorphization two stages downstream. A default is static even when the realization is pub, and does not travel on export: every importing unit synthesizes its own copy, so sending one too would be a second definition of one symbol. The cost is that a module whose defaults call printf has to pub include stdio.h -- which is also why pub include and pub import now work, both having been accepted by read-public-interface and refused by semen. --- Makefile | 1 + semen.scm | 125 ++++++++++++++++++++++++++++++++++- sex-macros.scm | 6 +- sex-mode.el | 5 ++ sex-modules.scm | 17 ++++- tests/encapsulation.scm | 83 +++++++++++++++++++++++ tests/modules/Makefile | 2 +- tests/modules/greet-app.sex | 2 + tests/modules/greet.sex | 16 ++++- tests/sex-programs/specs.sex | 68 +++++++++++++++++++ tests/types.module.scm | 7 ++ types.module.scm | 7 ++ types.scm | 31 ++++++++- 13 files changed, 363 insertions(+), 7 deletions(-) create mode 100644 tests/sex-programs/specs.sex diff --git a/Makefile b/Makefile index 27126d2..90d5acf 100644 --- a/Makefile +++ b/Makefile @@ -112,6 +112,7 @@ SEX_TEST_PROGRAMS = c99 \ ops \ records \ serialize \ + specs \ sums \ type-shapes \ unicode \ diff --git a/semen.scm b/semen.scm index 8e2d1ad..877aec7 100644 --- a/semen.scm +++ b/semen.scm @@ -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 ...)) ;;; diff --git a/sex-macros.scm b/sex-macros.scm index 350bddb..327c180 100644 --- a/sex-macros.scm +++ b/sex-macros.scm @@ -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) diff --git a/sex-mode.el b/sex-mode.el index b2ed808..733ba73 100644 --- a/sex-mode.el +++ b/sex-mode.el @@ -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) diff --git a/sex-modules.scm b/sex-modules.scm index e536b43..fa0c31a 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -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))) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 6a18818..05fabfe 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -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" diff --git a/tests/modules/Makefile b/tests/modules/Makefile index 5b04e57..af3442a 100644 --- a/tests/modules/Makefile +++ b/tests/modules/Makefile @@ -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 diff --git a/tests/modules/greet-app.sex b/tests/modules/greet-app.sex index 0205f77..e064bab 100644 --- a/tests/modules/greet-app.sex +++ b/tests/modules/greet-app.sex @@ -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)) diff --git a/tests/modules/greet.sex b/tests/modules/greet.sex index b272404..ade5285 100644 --- a/tests/modules/greet.sex +++ b/tests/modules/greet.sex @@ -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")) diff --git a/tests/sex-programs/specs.sex b/tests/sex-programs/specs.sex new file mode 100644 index 0000000..915e27d --- /dev/null +++ b/tests/sex-programs/specs.sex @@ -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)) diff --git a/tests/types.module.scm b/tests/types.module.scm index 64cca48..d31804e 100644 --- a/tests/types.module.scm +++ b/tests/types.module.scm @@ -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! diff --git a/types.module.scm b/types.module.scm index e9d039a..0b42e8d 100644 --- a/types.module.scm +++ b/types.module.scm @@ -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! diff --git a/types.scm b/types.scm index 93e1650..0a5ac3d 100644 --- a/types.scm +++ b/types.scm @@ -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. -- 2.52.0 From 737864dadc595fc9748ab809aa67eeb4b7bb3f8c Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 4 Oct 2026 13:25:17 +0300 Subject: [PATCH 09/40] keep the worked example honest Encapsulation.org's example was written before any of it was built and still called methods the way the first draft did. It compiles now, so it lives here as well, and the doc's block and this file are the same text. --- Makefile | 3 +- tests/sex-programs/worked-example.sex | 45 +++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 tests/sex-programs/worked-example.sex diff --git a/Makefile b/Makefile index 90d5acf..7afb0f2 100644 --- a/Makefile +++ b/Makefile @@ -117,7 +117,8 @@ SEX_TEST_PROGRAMS = c99 \ type-shapes \ unicode \ unnamed-params \ - wildcards + wildcards \ + worked-example # Multi-module linking is checked end to end; see tests/modules/Makefile. check-modules: sexc diff --git a/tests/sex-programs/worked-example.sex b/tests/sex-programs/worked-example.sex new file mode 100644 index 0000000..8195647 --- /dev/null +++ b/tests/sex-programs/worked-example.sex @@ -0,0 +1,45 @@ +(input) +(output "-(2 + 3)" + "-5") +(return 0) + +;;; The worked example from Encapsulation.org, kept here so it stays +;;; true: a recursive sum, an inherent method on it, and a spec +;;; realized for it, which is every layer that is built at once. + +(include stdio.h) + +(sum expr + ((lit ((v float))) + (neg ((e (* const expr)))) + (add ((l (* const expr)) (r (* const expr)))))) + +(ops expr + (pub 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))))))) + +(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"))) + +(realize (printable expr) + (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 ")"))))) + +(pub fn main () int + (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))) + + (.show-line e) ; -(2 + 3) + (printf "%g\n" (.eval e)) ; -5 + (return 0)) -- 2.52.0 From f071684aecd827798d1945f6d96cd79faf5b8e2e Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 4 Oct 2026 13:59:18 +0300 Subject: [PATCH 10/40] do not mangle an include's target MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A target is a filename, and the ː separator turned GL/gl.h into GLːgl.h, so every program including a header from a subdirectory stopped compiling the moment qualified names got their separator. --- fmt-c-writer.scm | 3 +++ tests/codegen.scm | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 56ad82d..d787e17 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -492,6 +492,9 @@ forms, and what remains." ((or ('struct . _) ('union . _)) (walk-struct form)) (('enum . _) (walk-enum form)) + ;; A target is a filename and not an identifier: GL/gl.h is a path, + ;; and unkebabify would spell it GLːgl.h + (('include target) (list '%include target)) (('define name . rest) `(%define ,(atom-to-fmt-c name) ,@rest)) (else (walk-expr form)))) diff --git a/tests/codegen.scm b/tests/codegen.scm index fdb3412..a456674 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -394,6 +394,16 @@ compiles." (fn f ((c (closure ((int)) int))) int (return (g c)))" "g(c)"))) + ;; An include target is a path, so none of the identifier mangling + ;; applies to it: GL/gl.h is a file and GLːgl.h is not. + (test-group "include targets are paths" + (test-assert "a slash survives" + (emits? "(include SDL3/SDL.h)" "#include ")) + (test-assert "and so does a dash" + (emits? "(include my-header.h)" "#include ")) + (test-assert "pub include emits the same" + (emits? "(pub include GL/gl.h)" "#include "))) + ;; The walker offered WALK-FN the cdr of every form as well as the ;; form, so the tail (t) of (fn g () t) read as a call to a macro ;; named t, and any function returning a type that shared a name -- 2.52.0 From 7f3f22e853796e8a55c46e07f6a9ea9f12ce65e6 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 4 Oct 2026 14:04:01 +0300 Subject: [PATCH 11/40] type a method call, so one can be another's receiver expression-type knew nothing about a .method head, so the receiver of (.length-sq (.sub a b)) had no type and the outer call could not resolve. Vector arithmetic is nothing but nested calls like that one. --- semen.scm | 24 ++++++++++++++++++------ tests/encapsulation.scm | 10 +++++++++- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/semen.scm b/semen.scm index 877aec7..d5af781 100644 --- a/semen.scm +++ b/semen.scm @@ -970,13 +970,25 @@ ;; ...and an increment is the operand unpromoted: ;; (++ c), c : char -> char ((++ --) (expression-type (second expr) env)) - ;; otherwise a call: a closure answers with its own return type, - ;; anything else with what its signature says + ;; otherwise a call: a method answers for the name it resolves + ;; to, a closure with its own return type, anything else with + ;; what its signature says (else - (let ((closure (receiver-closure-type (car expr) env))) - (if closure - (third closure) - (and (symbol? (car expr)) (get-return-type (car expr)))))))))) + (cond + ((method-head? (car expr)) (method-call-type expr env)) + ((receiver-closure-type (car expr) env) => third) + (else (and (symbol? (car expr)) (get-return-type (car expr)))))))))) + +;;; (.length-sq (.sub a b)) types the inner call to find the outer +;;; one's receiver, so a method call has to answer like any other +(define (method-call-type expr env) + (and (pair? (cdr expr)) + (let* ((written (expression-type (second expr) env)) + (target (pointer-target written)) + (key (ops-key (or target written)))) + (and key + (let ((method (get-method key (method-head-name (car expr))))) + (and method (get-return-type method))))))) ;;; C's usual arithmetic conversions, far enough to answer `_': ;;; diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 05fabfe..c855546 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -109,7 +109,15 @@ (test-assert "and so is a receiver with no type to dispatch on" (reports? "(fn f () void (var n int 1) (.get n))" "no such method on")) (test-assert "an address cannot be taken of a call" - (reports? (ops-src "(.length (mk))") "receiver is not an lvalue"))) + (reports? (ops-src "(.length (mk))") "receiver is not an lvalue")) + ;; the inner call has to be typed to find the outer one's receiver + (test-assert "a method call can be another's receiver" + (emits? (string-append + "(record w ((x int)))" + "(ops w (fn twice ((a w)) w (return a))" + " (fn get ((a w)) int (return (. a x))))" + "(fn f () int (var a w #(w : 1)) (return (.get (.twice a))))") + "wːget(wːtwice(a))"))) ;; A sum is the tag enum, a payload struct per variant that carries ;; fields, the record holding both, and a constructor each. -- 2.52.0 From 95f39e4b44419edcf05fd3f67ef10b64fb8fe0db Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 5 Oct 2026 02:08:15 +0300 Subject: [PATCH 12/40] space toplevel forms the way the source does Every toplevel form was followed by a blank line whether or not one was written, so the prelude's run of typedefs arrived at twice the height. A function had no location of its own to measure from either, having lost it where its header and body are stitched together. --- Readme.org | 3 ++- fmt-c-writer.scm | 40 ++++++++++++++++++++++++++++----------- reader.scm | 8 +++++--- semen.scm | 8 ++++++-- tests/codegen.scm | 16 +++++++++++++++- tests/line-directives.scm | 2 +- utils.module.scm | 1 + utils.scm | 19 +++++++++++++------ 8 files changed, 72 insertions(+), 25 deletions(-) diff --git a/Readme.org b/Readme.org index 57d7e66..7c433d1 100644 --- a/Readme.org +++ b/Readme.org @@ -123,7 +123,8 @@ Hello, Alex! * Features ** Full C interoperability Just ~(include "Your/Favourite/Library.h")~ and use it as you would -have is C. +have is C. One ~include~ takes as many headers as you care to name: +~(include stdio.h stdlib.h string.h)~. *** Auto kebabification For hardcore fans of traditional Lisp naming convention, diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index d787e17..3f57965 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -36,7 +36,7 @@ (define (line-directive src) ;; `%line' is fmt-c's #line directive. cpp-line concatenates its ;; second argument verbatim, so the file name arrives already quoted. - `(%line ,(cdr src) ,(fmt #f #\" (car src) #\"))) + `(%line ,(cadr src) ,(fmt #f #\" (car src) #\"))) (define (walk-body stmts) "Walk a statement list, re-anchoring each statement that has a known @@ -498,14 +498,32 @@ forms, and what remains." (('define name . rest) `(%define ,(atom-to-fmt-c name) ,@rest)) (else (walk-expr form)))) +;;; Two toplevel forms are separated by a blank line only if they were +;;; written that way: the prelude's typedefs come out packed, and so do +;;; the three includes at the top of a program that wrote them as three +;;; adjacent lines. Forms from different files -- the prelude, then an +;;; imported module, then the unit itself -- always get one. +(define (blank-line-between? prev next) + (if (equal? (form-file prev) (form-file next)) + (let ((end (form-end-line prev)) + (start (form-line next))) + (and end start (> (- start end) 1))) + #t)) + (define (emit-c sex-forms) - (for-each (lambda (form) - ;; Forms the reader did not produce -- the prelude, and - ;; anything a macro built that we could not attribute -- - ;; have no location and get no directive. - (let ((src (and (not (eq? (sex-line-directives) 'none)) - (form-source form)))) - (when src - (fmt #t (c-expr (line-directive src))))) - (fmt #t (c-expr (process-toplevel-form form)) nl)) - (pack-comments sex-forms))) + (let emit ((forms (pack-comments sex-forms)) (prev #f)) + (unless (null? forms) + (let ((form (car forms))) + (when (and prev (blank-line-between? prev form)) + (fmt #t nl)) + ;; Forms the reader did not produce -- the prelude, and + ;; anything a macro built that we could not attribute -- + ;; have no location and get no directive. + (let ((src (and (not (eq? (sex-line-directives) 'none)) + (form-source form)))) + (when src + (fmt #t (c-expr (line-directive src))))) + ;; `fl', not `nl': a comment leaves the cursor at the end of + ;; its line while everything else has already broken it + (fmt #t (c-expr (process-toplevel-form form)) fl) + (emit (cdr forms) form))))) diff --git a/reader.scm b/reader.scm index dcc8e94..566fd10 100644 --- a/reader.scm +++ b/reader.scm @@ -38,11 +38,13 @@ (define (peek port) (peek-char port)) -;;; Record where a form started. Called with the line of the opening -;;; delimiter, sampled before it is consumed +;;; Record where a form started and where it ended. Called with the +;;; line of the opening delimiter, sampled before it is consumed, once +;;; the form itself has been read -- so the current line is the one its +;;; closing delimiter sits on (define (stamp form line) (when (pair? form) - (set-form-source! form (current-source-file) line)) + (set-form-source! form (current-source-file) line (current-line))) form) (define (delimiter? c) diff --git a/semen.scm b/semen.scm index d5af781..adb4dd5 100644 --- a/semen.scm +++ b/semen.scm @@ -254,7 +254,7 @@ ;; emits the comment immediately before the declaration (cons form (if doc - (cons (list 'comment doc) acc) + (cons (copy-form-source! form (list 'comment doc)) acc) acc))) (define (strip-fn-header-comments fn-form) @@ -277,7 +277,11 @@ ;; the parameters are the body's outermost scope (header (map resolve-closure-types (take expanded boundary))) (body (walk-body (drop expanded boundary) env)) - (processed (append header body))) + ;; A function is header and body stitched together, so the + ;; result is fresh structure: without this the definition + ;; has no location, and nothing downstream can say where + ;; the function was written + (processed (copy-form-source! sex-fn-raw (append header body)))) (with-docstring doc processed (append (hash-table-ref env :lambda-aux-code) acc)))))) diff --git a/tests/codegen.scm b/tests/codegen.scm index a456674..8538ec0 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -633,4 +633,18 @@ compiles." (test-assert "nor is an aggregate tag" (emits? "(struct t ((z int))) (struct s ((a (¤ struct t))))" "struct t a[]")) (test-assert "nor one behind a pointer" - (emits? "(struct t ((z int))) (struct s ((a (¤ * struct t))))" "struct t* a[]")))) + (emits? "(struct t ((z int))) (struct s ((a (¤ * struct t))))" "struct t* a[]"))) + + ;; Toplevel forms used to be separated by a blank line unconditionally, + ;; which spread a block of adjacent typedefs over twice the lines its + ;; author wrote + (test-group "vertical spacing" + (test-assert "adjacent forms stay adjacent" + (emits? "(include a.h)\n(include b.h)" "#include \n#include ")) + (test-assert "a blank line is kept" + (emits? "(include a.h)\n\n(include b.h)" "#include \n\n#include ")) + ;; the gap is measured from where the form ended, not where it began + (test-assert "a multi-line form does not invent one" + (emits? "(struct s\n ((x int)))\n(include b.h)" "};\n#include ")) + (test-assert "nor swallows one" + (emits? "(struct s\n ((x int)))\n\n(include b.h)" "};\n\n#include ")))) diff --git a/tests/line-directives.scm b/tests/line-directives.scm index db74cd4..fa11abd 100644 --- a/tests/line-directives.scm +++ b/tests/line-directives.scm @@ -97,7 +97,7 @@ (define (compile-to-c source) "Run reader -> semen -> writer on SOURCE, returning the generated C. parse-all is called directly rather than through read-raw-forms so the -fixture can be given a file name: a location is (file . line), and the +fixture can be given a file name: a location carries one, and the file is what makes an imported module report itself rather than the unit that imported it." (let ((forms (with-input-from-string source diff --git a/utils.module.scm b/utils.module.scm index 79ec527..5b3463c 100644 --- a/utils.module.scm +++ b/utils.module.scm @@ -12,6 +12,7 @@ form-source form-file form-line + form-end-line copy-form-source! stamp-form-source! form-location diff --git a/utils.scm b/utils.scm index ee0a3a1..326b554 100644 --- a/utils.scm +++ b/utils.scm @@ -93,9 +93,12 @@ ;;; read-with-source-info / get-line-number, which only works when forms ;;; are produced by the built-in `read'. ;;; -;;; A location is (file . line). The file matters because imported +;;; A location is (file line end-line): where the form starts and the +;;; line its closing delimiter is on. The file matters because imported ;;; modules paste their public forms into the current unit: those forms -;;; originate in another file and must be reported as such +;;; originate in another file and must be reported as such. The end line +;;; tells the C writer whether two toplevel forms were written with a +;;; blank line between them (define +form-sources+ (make-hash-table eq?)) ;;; The file `parse-all' is currently reading. Bound by the reader @@ -114,8 +117,8 @@ (define (form-type form) (hash-table-ref/default +form-types+ form #f)) -(define (set-form-source! form file line) - (hash-table-set! +form-sources+ form (cons file line))) +(define (set-form-source! form file line #!optional (end-line line)) + (hash-table-set! +form-sources+ form (list file line end-line))) (define (form-source form) (hash-table-ref/default +form-sources+ form #f)) @@ -126,7 +129,11 @@ (define (form-line form) (let ((src (form-source form))) - (and src (cdr src)))) + (and src (cadr src)))) + +(define (form-end-line form) + (let ((src (form-source form))) + (and src (caddr src)))) (define (copy-form-source! from to) "Give TO the location of FROM, if FROM has one. Returns TO, so it can @@ -144,7 +151,7 @@ wrap a form-building expression." "\"file:line: \" for FORM, or \"\" when it has none" (let ((src (form-source form))) (if src - (string-append (car src) ":" (number->string (cdr src)) ": ") + (string-append (car src) ":" (number->string (cadr src)) ": ") ""))) (define (sex-error form message . args) -- 2.52.0 From fb4b8aa1f96ed78a8e9fe034054ffe71a0f17d1a Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 5 Oct 2026 02:08:15 +0300 Subject: [PATCH 13/40] dispatch . on the type it reads from Which of C's two member operators applies is a question the compiler can already answer -- (.length v) and (.length p) have picked & or * off the receiver's type since methods moved into the head -- so making the programmer answer it again asks them to restate what semen knows, and to revisit every reader of a field the day it becomes a pointer. A path resolves a step at a time, since only the type in hand answers for the next field. A receiver nothing can type is read as a value and warned about rather than refused: refusing leaves no spelling at all for a struct out of a header nobody has parsed. Two things had to come along. A parameter written (p * struct point) was recorded with nothing but the `*' for a type, which left half the paths in list-macros unanswerable. And fmt-c parenthesised a member access written inside another, which went unnoticed while only match nested them -- its bindings have been reading ((s.u).circle).r since sums went in. --- semen.scm | 76 ++++++++++++++++++++++++++++++++++------- sex-fmt-c.scm | 9 +++++ tests/codegen.scm | 53 +++++++++++++++++++++++++++- tests/encapsulation.scm | 2 +- 4 files changed, 125 insertions(+), 15 deletions(-) diff --git a/semen.scm b/semen.scm index adb4dd5..f961d21 100644 --- a/semen.scm +++ b/semen.scm @@ -433,9 +433,17 @@ (define (make-fn-env fn-form) (let ((env (make-hash-table)) (parameters (make-hash-table))) + ;; `(p (* struct point))' writes the type in one piece and + ;; `(p * struct point)' spreads it over the rest, so the type is + ;; the whole tail whenever there is more of it than one element (for-each (lambda (param) - (when (and (pair? param) (pair? (cdr param))) - (hash-table-set! parameters (first param) (second param)))) + (when (and (pair? param) (pair? (cdr param)) + (named-arg? param)) + (hash-table-set! parameters + (first param) + (if (null? (cddr param)) + (second param) + (cdr param))))) (sex-fn-arglist fn-form)) (set! (hash-table-ref env :fn-name) (sex-fn-name fn-form)) (set! (hash-table-ref env :lambda-counter) 0) @@ -603,6 +611,8 @@ ((match) (walk-match form env)) + ((dot-access) (walk-member-path form env)) + (else (if (method-head? (car form)) (walk-method-call form env) @@ -876,6 +886,32 @@ method)) (else `(& ,receiver))))) +;;; `(. p x)' is `p->x' when p is a pointer and `p.x' when it is not: +;;; the receiver's type says which, so a path reads the same however +;;; what it starts from is held. One step at a time, since only the +;;; type in hand can answer for the next field: +;;; +;;; (. l a x) l : (struct line), l.a : (* struct point) -> l.a->x +;;; +;;; A type we cannot work out is read as a value, which is what the +;;; path would have meant before any of this. +(define (walk-member-path form env) + (let ((base (second form))) + (let step ((expr (walk-statement base env)) + (type (expression-type base env)) + (fields (cddr form)) + (told? #f)) + (if (null? fields) + (copy-form-source! form expr) + (let ((target (pointer-target type))) + (unless (or type told?) + (sex-warning form "cannot type this; `.' reads it as a value" + base)) + (step (list (if target '-> 'dot-access) expr (car fields)) + (field-type (or target type) (car fields)) + (cdr fields) + (or told? (not type)))))))) + (define (lvalue? expr) (cond ((symbol? expr) #t) ((vector? expr) #t) ; a compound literal is one @@ -1081,22 +1117,36 @@ (eq? '* (car type)) (unwrap-type (cdr type)))) +;;; A path looks through a pointer wherever it meets one, the way the +;;; access itself does: `l.a->x' and `l.b.x' are both (. l a x) and +;;; both answer with x's type (define (member-path-type type fields) (if (null? fields) type - (member-path-type (field-type type (car fields)) (cdr fields)))) + (member-path-type (field-type (or (pointer-target type) type) + (car fields)) + (cdr fields)))) (define (field-type type field) - (let ((name (cond ((symbol? type) type) - ((and (list? type) - (= 2 (length type)) - (memq (car type) '(struct union))) - (second type)) - (else #f)))) - (and name - (let* ((fields (get-fields name)) - (entry (and fields (assq field fields)))) - (and entry (second entry)))))) + (let* ((fields (type-fields type)) + (entry (and fields (assq field fields)))) + (and entry (second entry)))) + +;;; `(struct point)' names its fields in the type database. A sum's +;;; payload writes its union out in place -- `(union ((circle (struct +;;; shapeːcircle)) ...))' -- and carries them with it, so there is +;;; nothing to look up +(define (type-fields type) + (cond ((and (list? type) + (= 2 (length type)) + (memq (car type) '(struct union)) + (list? (second type))) + (second type)) + ;; `ops-key' is already the "name of the aggregate" question, + ;; const and all: (* const expr) derefs to (const expr), which + ;; has the fields `expr' has + ((ops-key type) => get-fields) + (else #f))) (define (make-lambda-name enclosing-fn-name counter) (string->symbol diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index fd05daf..a29fd26 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -110,10 +110,19 @@ (define (c-paren x) (cat "(" (c-expr x) ")")) + ;; `.' and `->' associate left, and their right operand is always a + ;; name, so a member access written inside another is the left one + ;; and needs no parens of its own: `s.u.circle.r', not `((s.u).circle).r' + (define (c-member-op? x) + (let ((str (display-to-string x))) + (or (string=? str ".") (string=? str "->")))) + (define (c-maybe-paren op x) (lambda (st) ((fmt-let 'op op (if (and (c-op<= (fmt-op st) op) + (not (and (c-member-op? (fmt-op st)) + (c-member-op? op))) (not (vector? x))) (c-paren x) x)) diff --git a/tests/codegen.scm b/tests/codegen.scm index 8538ec0..43215e3 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -26,8 +26,16 @@ (parameterize ((sex-line-directives 'none)) (emit-c (semen-process forms))))))) +;;; Warnings are what `warns?' is for; a test that happens to trip one +;;; should not print it +(define (silently thunk) + "THUNK's value, with whatever it wrote to stderr dropped." + (let ((value #f)) + (with-error-output-to-string (lambda () (set! value (thunk)))) + value)) + (define (emits? source fragment) - (and (string-contains (sex->c source) fragment) #t)) + (and (string-contains (silently (lambda () (sex->c source))) fragment) #t)) (define (error-message source) "Compile SOURCE and return the error text as the user sees it -- @@ -48,6 +56,23 @@ compiles." (define (in-fn body) (string-append "(fn f ((a int) (b int)) void " body ")")) +;;; A struct, a struct holding a pointer to one, and locals of every +;;; shape a member path can start from +(define (in-line body) + (string-append + "(struct point ((x int) (y int)))" + "(struct line ((a (* struct point)) (b (struct point))))" + "(fn f ((lp (* struct line))) void" + " (var p (struct point)) (var pp (* struct point) (& p))" + " (var l (struct line)) " body ")")) + +(define (warnings source) + "What compiling SOURCE writes to stderr." + (with-error-output-to-string (lambda () (sex->c source)))) + +(define (warns? source fragment) + (and (string-contains (warnings source) fragment) #t)) + (test-group "codegen" ;; c-switch handed its scrutinee straight to `cat', which only works @@ -635,6 +660,32 @@ compiles." (test-assert "nor one behind a pointer" (emits? "(struct t ((z int))) (struct s ((a (¤ * struct t))))" "struct t* a[]"))) + ;; `.' is C's `.' or its `->' depending on what is being read from, + ;; so a path reads the same however the thing it starts from is held + (test-group "member access" + (test-assert "a value reads with a dot" + (emits? (in-line "(= (. p x) 1)") "p.x = 1")) + (test-assert "a pointer reads with an arrow" + (emits? (in-line "(= (. pp x) 1)") "pp->x = 1")) + ;; each step asks the type in hand, so one path may be both + (test-assert "a pointer field inside a value" + (emits? (in-line "(= (. l a x) 1)") "l.a->x = 1")) + (test-assert "a value field inside a pointer" + (emits? (in-line "(= (. lp b y) 1)") "lp->b.y = 1")) + (test-assert "and two pointers in a row" + (emits? (in-line "(= (. lp a x) 1)") "lp->a->x = 1")) + ;; a path is left-associative and its right operand is always a + ;; name, so none of it needs parenthesising + (test-assert "a path carries no parens" + (not (emits? (in-line "(= (. lp a x) 1)") "(lp->a)"))) + ;; ...which is not to say nothing does + (test-assert "though a dereference still does" + (emits? (in-line "(= (. (* pp) x) 1)") "(*pp).x = 1")) + (test-assert "a type we cannot work out is read as a value" + (emits? (in-line "(= (. (guess) x) 1)") "guess().x = 1")) + (test-assert "and said so" + (warns? (in-line "(= (. (guess) x) 1)") "cannot type this"))) + ;; Toplevel forms used to be separated by a blank line unconditionally, ;; which spread a block of adjacent typedefs over twice the lines its ;; author wrote diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index c855546..8bf0285 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -228,7 +228,7 @@ (test-assert "an arm binds its payload" (emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))" " ((empty ()) (= out 0.0)))") - "float r = ((s.u).circle).r")) + "float r = s.u.circle.r")) (test-assert "_ binds nothing" (not (emits? (sum-src "(match s ((circle (r)) (= out r))" " ((rect (w _)) (= out w))" -- 2.52.0 From dd3a4bdac57218a222928c73db43ceca47650122 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 5 Oct 2026 02:08:15 +0300 Subject: [PATCH 14/40] implement thread-first -> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `.' now writes whichever of C's member operators the type calls for, so nothing needs the arrow spelled out and the name is free for the macro Clojure spells the same way: (-> 5 double-it (add 3)) reads in the order it happens rather than inside out. It has no business in the prelude, which every unit pays for whether or not it threads anything, so it opens the standard library instead and is imported like anything else. The compiler finds lib/ by asking the binary where it is -- beside sexc in a work tree, under ../share/sex once installed -- and looks there last, so a module of one's own by that name still wins. The C arrow becomes `%->', and that rename is what makes the rest possible. The closure lifter writes arrows of its own for the capture record, those forms go back through walk-statement, and a macro named `->' threads them: (-> ƛcaptures n) turns into a call to n, with nothing saying so until the C compiler. fmt-c rendered a bare `->' as the arrow, which left the one spelling that cannot be right -- threading with no import -- looking like the operator it stopped being. It goes through c-apply now, the way any other head nothing knows does. --- Makefile | 14 +++++- Readme.org | 59 ++++++++++++++++++++++-- example/list.sex | 24 +++++----- example/serialize.sex | 2 +- fmt-c-writer.scm | 4 ++ lib/threading-macros.sex | 20 ++++++++ semen.scm | 18 ++++---- sex-fmt-c.scm | 2 - sex-modules.scm | 15 +++++- tests/codegen.scm | 7 ++- tests/modules/greet.sex | 4 +- tests/sex-programs/compound-literals.sex | 2 +- tests/sex-programs/fixpoint.sex | 8 ++-- tests/sex-programs/inference.sex | 6 +-- tests/sex-programs/list-macros.sex | 24 +++++----- tests/sex-programs/ops.sex | 10 ++-- tests/sex-programs/records.sex | 4 +- tests/sex-programs/serialize.sex | 2 +- tests/sex-programs/specs.sex | 6 +-- tests/sex-programs/threading.sex | 50 ++++++++++++++++++++ tests/sex-programs/wildcards.sex | 4 +- 21 files changed, 219 insertions(+), 66 deletions(-) create mode 100644 lib/threading-macros.sex create mode 100644 tests/sex-programs/threading.sex diff --git a/Makefile b/Makefile index 7afb0f2..feabf33 100644 --- a/Makefile +++ b/Makefile @@ -20,8 +20,16 @@ CSC_FLAGS += -K prefix -static prefix = /usr/local exec_prefix = $(prefix) bindir = $(exec_prefix)/bin +datarootdir = $(prefix)/share +datadir = $(datarootdir) +# sexc looks for the standard library beside itself: next to the binary +# in a work tree, and bindir/../share/sex once installed +sexlibdir = $(datadir)/sex INSTALL = install INSTALL_PROGRAM = $(INSTALL) +INSTALL_DATA = $(INSTALL) -m 644 + +SEX_LIB = $(wildcard lib/*.sex) MODULE_FLAGS = -emit-all-import-libraries -module-registration -c @@ -114,6 +122,7 @@ SEX_TEST_PROGRAMS = c99 \ serialize \ specs \ sums \ + threading \ type-shapes \ unicode \ unnamed-params \ @@ -133,15 +142,18 @@ check run-tests: sexc sex-tests sextest install: all installdirs $(INSTALL_PROGRAM) sexc $(DESTDIR)$(bindir)/sexc + $(INSTALL_DATA) $(SEX_LIB) $(DESTDIR)$(sexlibdir) install-strip: $(MAKE) INSTALL_PROGRAM='$(INSTALL_PROGRAM) -s' install installdirs: - $(INSTALL) -d $(DESTDIR)$(bindir) + $(INSTALL) -d $(DESTDIR)$(bindir) $(DESTDIR)$(sexlibdir) uninstall: rm -f $(DESTDIR)$(bindir)/sexc + rm -f $(SEX_LIB:lib/%=$(DESTDIR)$(sexlibdir)/%) + -rmdir $(DESTDIR)$(sexlibdir) $(EGGS_STAMP) deps-update: export CHICKEN_EGG_CACHE := $(EGGS_DIR)/cache $(EGGS_STAMP) deps-update: export CHICKEN_INSTALL_REPOSITORY := $(EGGS_DIR) diff --git a/Readme.org b/Readme.org index 7c433d1..1e35308 100644 --- a/Readme.org +++ b/Readme.org @@ -45,7 +45,9 @@ tree's ~.eggs~ path): #+end_src ** Installation -GNU directory variables: ~prefix~, ~exec_prefix~, ~bindir~, ~DESTDIR~. +GNU directory variables: ~prefix~, ~exec_prefix~, ~bindir~, ~datadir~, +~DESTDIR~. The binary goes to ~bindir~ and the standard library to +~$(datadir)/sex~. #+begin_src sh # default installation (/usr/local/bin/) @@ -132,17 +134,66 @@ Sex offers automatic kebabification of all symbols, i.e. no more ugly ~GL_ARRAY_BUFFER~ s in your code, they may be written in their proper form: ~GL-ARRAY-BUFFER~. +** Member access +~(. x field ...)~ reads a path, and writes C's ~.~ or its ~->~ according +to what it is reading from. Each step asks the type in hand, so one path +may be both: + +#+begin_src scheme +(struct point ((x int) (y int))) +(struct line ((a (* struct point)) (b (struct point)))) + +(. p x) ; p : (struct point) -> p.x +(. pp x) ; pp : (* struct point) -> pp->x +(. l a x) ; l.a is a pointer -> l.a->x +(. lp b y) ; lp is, l.b is not -> lp->b.y +#+end_src + +A receiver whose type cannot be worked out --- something out of a header +nothing has parsed --- is read as a value, with a warning saying so. + +A method is ~(.name receiver args ...)~ and a field is ~(. receiver +name)~, so the shape of a form says which of the two it is without +knowing any types: ~(. a b c)~ is a path and ~(.b a c)~ is a call. + ** Modules Each source file is a module. Module can provide public interface and be imported by using ~(import path/to/module)~ expression. Module -search path consists of two parts: first is relative to the source -being compiled location, and the second is ~SEX_MODULE_PATH~ -environment variable. +search path has three parts: first is relative to the source being +compiled location, then the ~SEX_MODULE_PATH~ environment variable, +and last the standard library. Module's public interface consists of everything declared ~pub~. Structures, function, macros, types, variables can be public. +** Standard library +~lib/~ holds the modules that come with the compiler. They are imported +like any other, and being searched last, a module of your own by the +same name wins over one of ours. + +~sexc~ looks for them beside itself, so a work tree needs nothing set +up; installed, ~$(bindir)/sexc~ finds them under ~$(prefix)/share/sex~. + +There is one so far. + +*** threading-macros +~->~ passes a value through a chain of forms, each step taking what came +before it as its first argument, so the chain reads in the order it +happens instead of inside out. Clojure spells it this way and this is +the same thing: + +#+begin_src scheme +(import threading-macros) + +(-> 5 double-it (add 3) double-it) ; (double-it (add (double-it 5) 3)) +(-> lp (. a x)) ; lp->a->x +(-> q .length-sq) ; a method is a step like any other +#+end_src + +A step that is not a list is a call of one argument: ~(-> x f)~ is +~(f x)~. + ** Read-time feature expressions Sex is able to use ~#+~ and ~#-~ for conditional compilation: the form that follows is kept only when the feature expression is true, and otherwise diff --git a/example/list.sex b/example/list.sex index 809ad68..5a1f8c9 100644 --- a/example/list.sex +++ b/example/list.sex @@ -9,25 +9,25 @@ (fn-name (cat 'make-list- type))) `(,@(if is-public? '(pub) '()) fn ,fn-name () (* ,list-type) (var list (* ,list-type) (cast (malloc (sizeof ,list-type)) (* ,list-type))) - (= (-> list next) NULL) + (= (. list next) NULL) (return list)))) (pub defmacro (add-value-list-T type is-public?) (let ((list-type (list 'struct (cat 'list- type))) (fn-name (cat 'add-value-list- type))) `(,@(if is-public? '(pub) '()) fn ,fn-name ((list * ,list-type) (value ,type)) void - (while (!= (-> list next) NULL) - (= list (-> list next))) - (= (-> list next) (,(cat 'make-list- type))) - (= (-> list value) value)))) + (while (!= (. list next) NULL) + (= list (. list next))) + (= (. list next) (,(cat 'make-list- type))) + (= (. list value) value)))) (pub defmacro (length-list-T type is-public?) (let ((fn-name (cat 'length-list- type)) (list-type (list 'struct (cat 'list- type)))) `(,@(if is-public? '(pub) '()) fn ,fn-name ((list ,(cons '* list-type))) size-t (var n size-t 0) - (while (!= (-> list next) NULL) - (= list (-> list next)) + (while (!= (. list next) NULL) + (= list (. list next)) (++ n)) (return n)))) @@ -35,14 +35,14 @@ `(,@(if is-public? '(pub) '()) fn ,(cat 'is-empty-list- type) ((list ,(list '* 'struct (cat 'list- type)))) bool - (return (== (-> list next) NULL)))) + (return (== (. list next) NULL)))) (pub defmacro (list-for-each list-type list-var elt-type elt-var what-do) (let ((list-var-2 (cat list-var '-2))) `(do (var ,list-var-2 (* ,list-type) ,list-var) - (var ,elt-var ,elt-type (-> ,list-var-2 value)) - (while (!= (-> ,list-var-2 next) NULL) + (var ,elt-var ,elt-type (. ,list-var-2 value)) + (while (!= (. ,list-var-2 next) NULL) ,what-do - (= ,list-var-2 (-> ,list-var-2 next)) - (= ,elt-var (-> ,list-var-2 value)))))) + (= ,list-var-2 (. ,list-var-2 next)) + (= ,elt-var (. ,list-var-2 value)))))) diff --git a/example/serialize.sex b/example/serialize.sex index b6d2d6d..9b30a1f 100644 --- a/example/serialize.sex +++ b/example/serialize.sex @@ -32,7 +32,7 @@ ((* char) "%s") (else (error "serialize-struct: unsupported field type" type-name name type)))) - (-> v ,name)))))) + (. v ,name)))))) (if (not printers) (error "serialize-struct: no such struct" type-name) `(pub fn ,(cat 'serialize- type-name) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 3f57965..0ded714 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -190,6 +190,10 @@ forms, and what remains." ;; (dot-access obj field ...) -> obj.field... member access. `%.' ;; is the fmt-c directive for the `.' operator (see sex-fmt-c). (('dot-access . rest) (cons '%. (map walk-expr rest))) + ;; `%->' is the C arrow. Nothing writes it: it is what a member + ;; path lowers to where the thing it reads from is a pointer, the + ;; name `->' itself being the threading macro + (('%-> . rest) (cons '%-> (map walk-expr rest))) (('var . _) (walk-var form)) ;; An expression has no room for a statement, so a comment in a ;; cast is dropped rather than relocated. diff --git a/lib/threading-macros.sex b/lib/threading-macros.sex new file mode 100644 index 0000000..e572774 --- /dev/null +++ b/lib/threading-macros.sex @@ -0,0 +1,20 @@ +;;; Threading macros +;;; +;;; `->' passes a value through a chain of forms, each step taking what +;;; came before it as its first argument, so a chain of calls reads in +;;; the order it happens rather than inside out. Clojure spells it this +;;; way and this is the same thing: +;;; +;;; (-> 5 double-it (add 3)) == (add (double-it 5) 3) +;;; +;;; A step that is not a list is a call of one argument, so `(-> x f)' +;;; is `(f x)' and a method is a step like any other. + +(pub defmacro (-> x . steps) + (let thread ((acc x) (steps steps)) + (if (null? steps) + acc + (thread (if (pair? (car steps)) + (cons (car (car steps)) (cons acc (cdr (car steps)))) + (list (car steps) acc)) + (cdr steps))))) diff --git a/semen.scm b/semen.scm index f961d21..ea8bf4f 100644 --- a/semen.scm +++ b/semen.scm @@ -777,7 +777,7 @@ (cond ((symbol? expr) #t) ((not (pair? expr)) #f) (else (case (car expr) - ((dot-access ->) (simple-path? (second expr))) + ((dot-access %->) (simple-path? (second expr))) ((*) (and (= 2 (length expr)) (simple-path? (second expr)))) (else #f))))) @@ -907,7 +907,7 @@ (unless (or type told?) (sex-warning form "cannot type this; `.' reads it as a value" base)) - (step (list (if target '-> 'dot-access) expr (car fields)) + (step (list (if target '%-> 'dot-access) expr (car fields)) (field-type (or target type) (car fields)) (cdr fields) (or told? (not type)))))))) @@ -917,7 +917,7 @@ ((vector? expr) #t) ; a compound literal is one ((not (pair? expr)) #f) (else (case (car expr) - ((dot-access -> ¤) #t) + ((dot-access %-> ¤) #t) ((*) (= 2 (length expr))) (else #f))))) @@ -991,8 +991,8 @@ (arithmetic-type expr env))) ((dot-access) (member-path-type (expression-type (second expr) env) (cddr expr))) - ((->) (member-path-type (pointer-target (expression-type (second expr) env)) - (cddr expr))) + ((%->) (member-path-type (pointer-target (expression-type (second expr) env)) + (cddr expr))) ((cast) (and (= 3 (length expr)) (third expr))) ((sizeof) 'size-t) ;; `(closure ((x int)) int () ...)' is a `(closure ((int)) int)', @@ -1351,7 +1351,7 @@ (iota (length (second type)))))) (unless (hash-table-exists? +closure-conversions+ convert) (hash-table-set! +closure-conversions+ convert #t) - (let ((call `((-> ƛcaptures f) ,@(map first params)))) + (let ((call `((%-> ƛcaptures f) ,@(map first params)))) (for-each (lambda (emitted) (set! *pending-closure-structs* @@ -1369,7 +1369,7 @@ (= (dot-access ƛc code) ,thunk) (var ƛcaptures (* (struct ,record)) (cast (& (dot-access ƛc env)) (* (struct ,record)))) - (= (-> ƛcaptures f) f) + (= (%-> ƛcaptures f) f) (return ƛc)))))) convert)) @@ -1487,7 +1487,7 @@ `((var ƛcaptures (* (struct ,record)) ƛe) ,@(map (lambda (cap) `(var ,(first cap) ,(second cap) - (-> ƛcaptures ,(first cap)))) + (%-> ƛcaptures ,(first cap)))) caps))) ,@body) @@ -1505,7 +1505,7 @@ `((var ƛcaptures (* (struct ,record)) (cast (& (dot-access ƛc env)) (* (struct ,record)))) ,@(map (lambda (cap) - `(= (-> ƛcaptures ,(first cap)) ,(first cap))) + `(= (%-> ƛcaptures ,(first cap)) ,(first cap))) caps))) (return ƛc)))))))) (else (sex-error form "malformed closure" form)))) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index a29fd26..89f8835 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -306,8 +306,6 @@ (cond ((eq? (car x) (string->symbol ".")) ((apply c-op "." (cdr x)) st)) - ((eq? (car x) (string->symbol "->")) - ((apply c-op "->" (cdr x)) st)) ((eq? (car x) (string->symbol "++")) ((apply c-op "++" (cdr x)) st)) ((eq? (car x) (string->symbol "--")) diff --git a/sex-modules.scm b/sex-modules.scm index fa0c31a..c3f1c61 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -43,7 +43,20 @@ (define (get-module-paths) (cons (current-directory) - +persistent-module-paths+)) + (append +persistent-module-paths+ (standard-library-paths)))) + +;;; Where the modules shipped with the compiler live. Asked of the +;;; binary rather than baked in when it is built: in a work tree sexc +;;; sits beside lib/, and installed it sits in bindir with the modules +;;; under ../share/sex. Last in the search order, so a module of one's +;;; own wins over one of ours by the same name +(define (standard-library-paths) + (let ((binary (executable-pathname))) + (if binary + (let ((bin (pathname-directory binary))) + (list (make-pathname bin "lib") + (make-pathname (list (pathname-directory bin) "share") "sex"))) + (list)))) (define (locate-module name) ;; Module locations: relative to file being compiled, or in what was diff --git a/tests/codegen.scm b/tests/codegen.scm index 43215e3..43283e4 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -684,7 +684,12 @@ compiles." (test-assert "a type we cannot work out is read as a value" (emits? (in-line "(= (. (guess) x) 1)") "guess().x = 1")) (test-assert "and said so" - (warns? (in-line "(= (. (guess) x) 1)") "cannot type this"))) + (warns? (in-line "(= (. (guess) x) 1)") "cannot type this")) + ;; the arrow is `%->' and nothing else writes one, so a bare `->' + ;; is an ordinary head -- a threading macro that nobody imported, + ;; and a call like any other unknown + (test-assert "a bare -> is not the arrow" + (emits? (in-line "(= (-> pp x) 1)") "->(pp, x) = 1"))) ;; Toplevel forms used to be separated by a blank line unconditionally, ;; which spread a block of adjacent typedefs over twice the lines its diff --git a/tests/modules/greet.sex b/tests/modules/greet.sex index ade5285..a6e6660 100644 --- a/tests/modules/greet.sex +++ b/tests/modules/greet.sex @@ -58,7 +58,7 @@ (ops vec2 (pub fn manhattan ((self (* const vec2))) int - (return (+ (-> self x) (-> self y))))) + (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 @@ -77,7 +77,7 @@ (pub realize (printable vec2) (fn show ((self (* const vec2))) void - (printf "vec2(%d %d)" (-> self x) (-> self y)))) + (printf "vec2(%d %d)" (. self x) (. self y)))) ;;; Not `pub': invisible to importers, and static in the generated C. (fn unused-helper () void diff --git a/tests/sex-programs/compound-literals.sex b/tests/sex-programs/compound-literals.sex index 26a84ef..ec1e5df 100644 --- a/tests/sex-programs/compound-literals.sex +++ b/tests/sex-programs/compound-literals.sex @@ -34,7 +34,7 @@ ;; a compound literal is an lvalue, so its address can be taken -- ;; until the end of the enclosing block, and no longer (var pp (* struct point) (& #(struct point : 9 9))) - (printf "through a pointer %d\n" (-> pp x)) + (printf "through a pointer %d\n" (. pp x)) ;; an array literal decays the way an array does (var a (* int) #([int 3] : 10 20 30)) diff --git a/tests/sex-programs/fixpoint.sex b/tests/sex-programs/fixpoint.sex index 9d62771..624a617 100644 --- a/tests/sex-programs/fixpoint.sex +++ b/tests/sex-programs/fixpoint.sex @@ -29,14 +29,14 @@ ;;; the self-application hidden inside (fn fix ((step (* (struct rec)))) (closure ((int)) int) (return (closure ((n int)) int (step) - (return ((-> step f) step n))))) + (return ((. step f) step n))))) (pub fn main () int (var fac-knot (struct rec)) (= (. fac-knot f) (closure ((self (* (struct rec))) (n int)) int () (if (<= n 1) (return 1)) - (return (* n ((-> self f) self (- n 1)))))) + (return (* n ((. self f) self (- n 1)))))) ;; the knot applied to itself directly, without fix (printf "direct: %d\n" ((. fac-knot f) (& fac-knot) 5)) @@ -45,8 +45,8 @@ (= (. fib-knot f) (closure ((self (* (struct rec))) (n int)) int () (if (< n 2) (return n)) - (return (+ ((-> self f) self (- n 1)) - ((-> self f) self (- n 2)))))) + (return (+ ((. self f) self (- n 1)) + ((. self f) self (- n 2)))))) ;; one combinator, two different recursions (var fac (closure ((int)) int) (fix (& fac-knot))) diff --git a/tests/sex-programs/inference.sex b/tests/sex-programs/inference.sex index 4dfbfb6..b5d3f0a 100644 --- a/tests/sex-programs/inference.sex +++ b/tests/sex-programs/inference.sex @@ -43,8 +43,8 @@ (var m (struct point)) ;; No `_' here: `m' has no initializer to infer from. Inference fills ;; in a type, it does not invent one. - (= (. m x) (/ (+ (-> a x) (-> b x)) 2)) - (= (. m y) (/ (+ (-> a y) (-> b y)) 2)) + (= (. m x) (/ (+ (. a x) (. b x)) 2)) + (= (. m y) (/ (+ (. a y) (. b y)) 2)) (return m)) ;;; The closure's type is written once, in the signature; `_' reads it @@ -118,7 +118,7 @@ (var p (* _) (& origin)) ;; Member access reads the same type database the macros do. - (var x _ (-> p x)) + (var x _ (. p x)) (printf "%d\n" x) ;; A call into a function Sex has actually parsed: the return type is diff --git a/tests/sex-programs/list-macros.sex b/tests/sex-programs/list-macros.sex index 809ad68..5a1f8c9 100644 --- a/tests/sex-programs/list-macros.sex +++ b/tests/sex-programs/list-macros.sex @@ -9,25 +9,25 @@ (fn-name (cat 'make-list- type))) `(,@(if is-public? '(pub) '()) fn ,fn-name () (* ,list-type) (var list (* ,list-type) (cast (malloc (sizeof ,list-type)) (* ,list-type))) - (= (-> list next) NULL) + (= (. list next) NULL) (return list)))) (pub defmacro (add-value-list-T type is-public?) (let ((list-type (list 'struct (cat 'list- type))) (fn-name (cat 'add-value-list- type))) `(,@(if is-public? '(pub) '()) fn ,fn-name ((list * ,list-type) (value ,type)) void - (while (!= (-> list next) NULL) - (= list (-> list next))) - (= (-> list next) (,(cat 'make-list- type))) - (= (-> list value) value)))) + (while (!= (. list next) NULL) + (= list (. list next))) + (= (. list next) (,(cat 'make-list- type))) + (= (. list value) value)))) (pub defmacro (length-list-T type is-public?) (let ((fn-name (cat 'length-list- type)) (list-type (list 'struct (cat 'list- type)))) `(,@(if is-public? '(pub) '()) fn ,fn-name ((list ,(cons '* list-type))) size-t (var n size-t 0) - (while (!= (-> list next) NULL) - (= list (-> list next)) + (while (!= (. list next) NULL) + (= list (. list next)) (++ n)) (return n)))) @@ -35,14 +35,14 @@ `(,@(if is-public? '(pub) '()) fn ,(cat 'is-empty-list- type) ((list ,(list '* 'struct (cat 'list- type)))) bool - (return (== (-> list next) NULL)))) + (return (== (. list next) NULL)))) (pub defmacro (list-for-each list-type list-var elt-type elt-var what-do) (let ((list-var-2 (cat list-var '-2))) `(do (var ,list-var-2 (* ,list-type) ,list-var) - (var ,elt-var ,elt-type (-> ,list-var-2 value)) - (while (!= (-> ,list-var-2 next) NULL) + (var ,elt-var ,elt-type (. ,list-var-2 value)) + (while (!= (. ,list-var-2 next) NULL) ,what-do - (= ,list-var-2 (-> ,list-var-2 next)) - (= ,elt-var (-> ,list-var-2 value)))))) + (= ,list-var-2 (. ,list-var-2 next)) + (= ,elt-var (. ,list-var-2 value)))))) diff --git a/tests/sex-programs/ops.sex b/tests/sex-programs/ops.sex index cc4edf6..10c62e7 100644 --- a/tests/sex-programs/ops.sex +++ b/tests/sex-programs/ops.sex @@ -23,12 +23,12 @@ (ops vec2 (pub fn length ((self (* const vec2))) float "Pointer self, so (.length v) has to take the address." - (return (sqrtf (+ (* (-> self x) (-> self x)) - (* (-> self y) (-> self y)))))) + (return (sqrtf (+ (* (. self x) (. self x)) + (* (. self y) (. self y)))))) (fn scale ((self (* vec2)) (k float)) void - (*= (-> self x) k) - (*= (-> self y) k)) + (*= (. self x) k) + (*= (. self y) k)) (fn sum-of ((self vec2)) float ;; value self, so (.sum-of p) has to dereference @@ -38,7 +38,7 @@ (ops raw (fn total ((self (* const (struct raw)))) int - (return (+ (-> self a) (-> self b))))) + (return (+ (. self a) (. self b))))) (pub fn main () int (var v vec2 #(vec2 : 3.0 4.0)) diff --git a/tests/sex-programs/records.sex b/tests/sex-programs/records.sex index 9c0eefd..c99050c 100644 --- a/tests/sex-programs/records.sex +++ b/tests/sex-programs/records.sex @@ -18,8 +18,8 @@ (struct raw ((a int) (b int))) (fn shift ((p (* point)) (dx int) (dy int)) void - (+= (-> p x) dx) - (+= (-> p y) dy)) + (+= (. p x) dx) + (+= (. p y) dy)) (fn area ((p point)) int (return (* (. p x) (. p y)))) diff --git a/tests/sex-programs/serialize.sex b/tests/sex-programs/serialize.sex index 344d305..bce7653 100644 --- a/tests/sex-programs/serialize.sex +++ b/tests/sex-programs/serialize.sex @@ -19,7 +19,7 @@ ((* const char) "%s") (else (error "print-struct: unsupported field type" name type)))) - (-> v ,name)))))) + (. v ,name)))))) (if (not printers) (error "print-struct: no such struct" type-name) `(fn ,(cat 'print- type-name) ((v (* const struct ,type-name))) void diff --git a/tests/sex-programs/specs.sex b/tests/sex-programs/specs.sex index 915e27d..93f6680 100644 --- a/tests/sex-programs/specs.sex +++ b/tests/sex-programs/specs.sex @@ -30,15 +30,15 @@ (realize (printable money) (fn show ((self (* const money))) void - (printf "$%d.%02d" (/ (-> self cents) 100) (% (-> self cents) 100)))) + (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)))) + (printf "(%d, %d)" (. self x) (. self y)))) (realize (ord money) (fn less ((a (* const money)) (b (* const money))) bool - (return (< (-> a cents) (-> b cents))))) + (return (< (. a cents) (. b cents))))) ;;; A bounded generic: the macro refuses before it expands (defmacro (max-of type) diff --git a/tests/sex-programs/threading.sex b/tests/sex-programs/threading.sex new file mode 100644 index 0000000..c7c271a --- /dev/null +++ b/tests/sex-programs/threading.sex @@ -0,0 +1,50 @@ +(input) +(output "arithmetic: 26" + "a bare step needs no parens: 20" + "through a path: 1 4" + "mixed with a method: 25" + "one step is just the value: 7") +(return 0) + +;;; `->' used to be C's arrow. The arrow is what `.' writes now when +;;; the thing it reads from is a pointer, which left the name free for +;;; threading -- the first module of the standard library. +;;; +;;; What this pins is that a step may be a call, a bare name or a +;;; method, that the value is threaded into the *first* argument, and +;;; that the compiler's own generated arrows survived the rename -- +;;; `ops' below lifts a method, which is where the captures live. + +(include stdio.h) +(import threading-macros) + +(struct point ((x int) (y int))) +(struct line ((a (* struct point)) (b (struct point)))) + +(fn double-it ((n int)) int + (return (* n 2))) + +(fn add ((n int) (m int)) int + (return (+ n m))) + +(ops point + (pub fn length-sq ((self (* const struct point))) int + (return (+ (* (. self x) (. self x)) + (* (. self y) (. self y)))))) + +(pub fn main () int + ;; (add (double-it 5) 3) doubled: inside out, written outside in + (printf "arithmetic: %d\n" (-> 5 double-it (add 3) double-it)) + (printf "a bare step needs no parens: %d\n" (-> 5 double-it double-it)) + + (var p (struct point) #(1 2)) + (var l (struct line) #(struct line : .a (& p) .b #(3 4))) + (var lp (* struct line) (& l)) + ;; a member path is an ordinary step, and reads through both pointers + (printf "through a path: %d %d\n" (-> lp (. a x)) (. lp b y)) + + (var q (struct point) #(3 4)) + (printf "mixed with a method: %d\n" (-> q .length-sq)) + + (printf "one step is just the value: %d\n" (-> 7)) + (return 0)) diff --git a/tests/sex-programs/wildcards.sex b/tests/sex-programs/wildcards.sex index 20b7752..1bf0764 100644 --- a/tests/sex-programs/wildcards.sex +++ b/tests/sex-programs/wildcards.sex @@ -42,7 +42,7 @@ (printf "members: %d %g\n" px py) (var pp _ (& p)) - (printf "pointers: %d %g\n" (-> pp x) (-> pp y)) + (printf "pointers: %d %g\n" (. pp x) (. pp y)) (var table (¤ int 3)) (= (¤ table 0) 10) @@ -77,7 +77,7 @@ ;; a wildcard inside a written type: only it is solved (var pp2 (* _) (& p)) - (printf "partial: %d %g\n" (-> pp2 x) (-> pp2 y)) + (printf "partial: %d %g\n" (. pp2 x) (. pp2 y)) ;; C's usual arithmetic conversions, far enough to answer `_' (var d double 1.5) -- 2.52.0 From 6c8b38b7e2e68cce186d9df7935c210a40f1aa6e Mon Sep 17 00:00:00 2001 From: alex-eg Date: Thu, 8 Oct 2026 11:09:42 +0300 Subject: [PATCH 15/40] floor the C target at C11 f5eee71 spelled the closure environment in C99 for a floor nobody meant to keep: closures were already C11 through _Static_assert. max_align_t says the alignment in one word again, and the floor test now holds C11. --- Makefile | 2 +- semen.scm | 14 ++++---------- tests/sex-programs/c11.sex | 39 ++++++++++++++++++++++++++++++++++++++ tests/sex-programs/c99.sex | 28 --------------------------- 4 files changed, 44 insertions(+), 39 deletions(-) create mode 100644 tests/sex-programs/c11.sex delete mode 100644 tests/sex-programs/c99.sex diff --git a/Makefile b/Makefile index feabf33..8e40f4d 100644 --- a/Makefile +++ b/Makefile @@ -104,7 +104,7 @@ sextest: $(MAKE) -C ./tools/sextest sextest cp ./tools/sextest/sextest . -SEX_TEST_PROGRAMS = c99 \ +SEX_TEST_PROGRAMS = c11 \ closure-signatures \ closures \ comments \ diff --git a/semen.scm b/semen.scm index ea8bf4f..d53401a 100644 --- a/semen.scm +++ b/semen.scm @@ -1182,19 +1182,13 @@ (define +closure-env-bytes+ 16) -;;; +closure-env-bytes+ for capacity, the widest built-ins for -;;; alignment, hence union -- a union takes the strictest alignment of -;;; its members. `max_align_t' would say the second in one word: -;;; -;;; sexc hello-world.sex -- -std=c99 unknown type name 'max_align_t' +;;; +closure-env-bytes+ for capacity, max_align_t for alignment, hence +;;; union -- a union takes the strictest alignment of its members. (define +closure-env-type+ 'ƛenv) (define (closure-env-declaration) - `(union ,+closure-env-type+ ((bytes (¤ char ,+closure-env-bytes+)) - (align-integer (long long)) - (align-real (long double)) - (align-pointer (* void)) - (align-code (fn ((* void)) void))))) + `(union ,+closure-env-type+ ((align max-align-t) + (bytes (¤ char ,+closure-env-bytes+))))) (define +closure-structs+ (make-hash-table)) (define +closure-forwards+ (make-hash-table)) diff --git a/tests/sex-programs/c11.sex b/tests/sex-programs/c11.sex new file mode 100644 index 0000000..3d40462 --- /dev/null +++ b/tests/sex-programs/c11.sex @@ -0,0 +1,39 @@ +(compilation "-- -std=c11 -pedantic-errors") +(input) +(output "c11: 42 43 6") +(return 0) + +;;; C11 is the floor, and this is the program that holds it there: the +;;; C every feature emits has to build under it with no extension, so +;;; one that reaches past it -- a GNU statement expression, a C23 +;;; keyword -- fails here rather than on a user's compiler. +;;; +;;; A capturing closure is the one that leans on C11 itself, through +;;; max_align_t in the environment and `_Static_assert' on its size; +;;; the record, the method and the match are here for what they emit. + +(include stdio.h) + +(record point ((x int) (y int))) + +(ops point + (fn area ((self (* const point))) int + (return (* (. self x) (. self y))))) + +(sum shape ((square ((side int))) (dot ()))) + +(fn sides ((s shape)) int + (var n int 0) + (match s + ((square (side)) (= n (* 4 side))) + ((dot ()) (= n 0))) + (return n)) + +(pub fn main () int + (var p point #(point : 6 7)) + (var k int 1) + (var add-k (closure ((int)) int) + (closure ((v int)) int (k) (return (+ v k)))) + (printf "c11: %d %d %d\n" + (.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2)) + (return 0)) diff --git a/tests/sex-programs/c99.sex b/tests/sex-programs/c99.sex deleted file mode 100644 index f65cd37..0000000 --- a/tests/sex-programs/c99.sex +++ /dev/null @@ -1,28 +0,0 @@ -(compilation "-- -std=c99 -pedantic-errors") -(input) -(output "c99: 42") -(return 0) - -;;; The closure environment is part of the ABI, so its union is declared -;;; in every translation unit whether or not one is used. That put -;;; whatever it was written with into every program: `max_align_t' named -;;; the alignment in one word, and made C11 the floor for a program with -;;; no closure in it at all. -;;; -;;; The widest built-ins say the same thing -- a union is aligned for the -;;; strictest of its members -- and say it in C99. -;;; -;;; Closures themselves still want C11 for the `_Static_assert' that -;;; checks the captures fit, so this program keeps clear of them. - -(include stdio.h) - -(struct point ((x int) (y int))) - -(fn area ((p (struct point))) int - (return (* (. p x) (. p y)))) - -(pub fn main () int - (var p (struct point) #((struct point) : 6 7)) - (printf "c99: %d\n" (area p)) - (return 0)) -- 2.52.0 From e9960488fbd56a651a2c5b5e1146018a7690a10b Mon Sep 17 00:00:00 2001 From: alex-eg Date: Thu, 8 Oct 2026 11:09:42 +0300 Subject: [PATCH 16/40] test an opaque record across a module boundary A bodyless pub record ahead of a private definition exports the handle and keeps the fields, the way flecs keeps ecs_world_t. It worked with nothing added, and nothing said so. --- tests/encapsulation.scm | 5 ++++- tests/modules/Makefile | 5 +++-- tests/modules/greet-app.sex | 7 +++++++ tests/modules/greet.sex | 19 +++++++++++++++++++ 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 8bf0285..9ecef47 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -52,7 +52,10 @@ (test-assert "struct keeps C's meaning" (not (emits? "(struct raw ((x int)))" "typedef"))) (test-assert "a record needs a name" - (reports? "(record ((x int)))" "record needs a name"))) + (reports? "(record ((x int)))" "record needs a name")) + ;; An opaque handle: the declaration is public, the fields are not + (test-assert "declared, then defined, is still defined" + (emits? "(pub record h)(record h ((x int)))" "struct h {"))) ;; An ops block is mangled functions plus a registry entry. `pub' ;; inside it means what it means outside. diff --git a/tests/modules/Makefile b/tests/modules/Makefile index af3442a..034cd95 100644 --- a/tests/modules/Makefile +++ b/tests/modules/Makefile @@ -13,14 +13,15 @@ # reads the imported struct's fields; and that a closure type crossing # the boundary works both ways -- one built in the module and called # here, one built here and called there, through a code pointer that is -# static in the other object. +# static in the other object. And that a record can cross as a handle +# alone, its fields left behind and its methods still found. # # The public forms carry comments in their headers, which the reduction # to a prototype and to an extern both have to look past. SEXC ?= ../../sexc -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 +EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7\nvec2(3 4)\ntally 2\ncolour 123 check: @$(SEXC) greet.sex -c -o greet.o diff --git a/tests/modules/greet-app.sex b/tests/modules/greet-app.sex index e064bab..7675207 100644 --- a/tests/modules/greet-app.sex +++ b/tests/modules/greet-app.sex @@ -40,6 +40,13 @@ (.show-line v) + ;; only the handle crossed: (. t n) here is an incomplete type + (var t (* tally) (tally/make)) + (.bump t) + (.bump t) + (printf "tally %d\n" (.count t)) + (.drop t) + (var c colour (colour/rgb 1 2 3)) (match c ((rgb (r g b)) (printf "colour %d%d%d\n" r g b)) diff --git a/tests/modules/greet.sex b/tests/modules/greet.sex index a6e6660..f309a19 100644 --- a/tests/modules/greet.sex +++ b/tests/modules/greet.sex @@ -6,6 +6,7 @@ ;;; greet-app.sex. (pub include stdio.h) +(include stdlib.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 @@ -60,6 +61,24 @@ (pub fn manhattan ((self (* const vec2))) int (return (+ (. self x) (. self y))))) +;;; An opaque record: the handle is public and the fields are not, so +;;; the importer holds a (* tally) and reaches it only through methods. +(pub record tally) + +(record tally ((n int))) + +(ops tally + (pub fn make () (* tally) + (var t (* tally) (malloc (sizeof tally))) + (= (. t n) 0) + (return t)) + (pub fn bump ((self (* tally))) void + (++ (. self n))) + (pub fn count ((self (* const tally))) int + (return (. self n))) + (pub fn drop ((self (* tally))) void + (free self))) + ;;; 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. -- 2.52.0 From dfafe8becd2846fbbe5a98176b72ddaa4ed346b0 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Thu, 8 Oct 2026 11:09:42 +0300 Subject: [PATCH 17/40] lay out threading.sex one step to a line --- tests/sex-programs/threading.sex | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/sex-programs/threading.sex b/tests/sex-programs/threading.sex index c7c271a..2082caa 100644 --- a/tests/sex-programs/threading.sex +++ b/tests/sex-programs/threading.sex @@ -34,14 +34,20 @@ (pub fn main () int ;; (add (double-it 5) 3) doubled: inside out, written outside in - (printf "arithmetic: %d\n" (-> 5 double-it (add 3) double-it)) + (printf "arithmetic: %d\n" + (-> 5 + double-it + (add 3) + double-it)) (printf "a bare step needs no parens: %d\n" (-> 5 double-it double-it)) (var p (struct point) #(1 2)) (var l (struct line) #(struct line : .a (& p) .b #(3 4))) (var lp (* struct line) (& l)) ;; a member path is an ordinary step, and reads through both pointers - (printf "through a path: %d %d\n" (-> lp (. a x)) (. lp b y)) + (printf "through a path: %d %d\n" + (-> lp (. a x)) + (. lp b y)) (var q (struct point) #(3 4)) (printf "mixed with a method: %d\n" (-> q .length-sq)) -- 2.52.0 From 0119c85dedbad9969a6e5c3748cdbcce4b2eb4db Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 15:18:18 +0300 Subject: [PATCH 18/40] link ops.sex against libm sqrtf lives in libm on glibc; macOS folds it into libSystem, which hid the missing -lm until CI linked on Linux. --- tests/sex-programs/ops.sex | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/sex-programs/ops.sex b/tests/sex-programs/ops.sex index 10c62e7..12bb812 100644 --- a/tests/sex-programs/ops.sex +++ b/tests/sex-programs/ops.sex @@ -1,3 +1,4 @@ +(compilation "-- -lm") (input) (output "5.0 5.0 10.0 14.0 14.0 6.0" "struct receiver: 14" -- 2.52.0 From f5c53cdd41e596aa0b0836bb761cba6fbad346fd Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 15:54:07 +0300 Subject: [PATCH 19/40] tell a spec default by its body, not its length A required method with a docstring or a comment counted as a default: the realization could leave it out, and got a prototype with no definition or a function with no return. --- semen.scm | 14 ++++++++++++-- tests/encapsulation.scm | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/semen.scm b/semen.scm index d53401a..c4954dc 100644 --- a/semen.scm +++ b/semen.scm @@ -346,11 +346,21 @@ (append (map (lambda (g) (cons g #t)) given) (filter-map (lambda (w) - (and (> (length w) 4) ; carries a body, so a default + (and (spec-default? w) (not (find (lambda (g) (eq? (second g) (second w))) given)) (cons (substitute-parameter parameter type w) #f))) wanted))) +;;; A docstring or a comment is not a body, so +;;; +;;; (fn s ((self (* const T))) void "what s is for") +;;; +;;; is still a method every realization has to write. +(define (spec-default? method) + (let-values (((doc fn) (extract-fn-docstring (strip-fn-header-comments method)))) + (any (lambda (form) (not (comment-form? form))) + (drop fn (fn-header-length fn))))) + (define (check-realization form name type parameter wanted given) (for-each (lambda (g) @@ -369,7 +379,7 @@ given) (let ((missing (filter-map (lambda (w) - (and (= (length w) 4) ; no body, so required + (and (not (spec-default? w)) (not (find (lambda (g) (eq? (second g) (second w))) given)) (second w))) wanted))) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 9ecef47..22f4ced 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -198,6 +198,23 @@ " (fn q ((a (* const T))) void))" "(realize (p v) (fn s ((a (* const v))) void (return)))") "q")) + (test-assert "a docstring is not a body" + (reports? (string-append "(record v ((x int)))" + "(spec (p T) (fn s ((a (* const T))) void \"doc\"))" + "(realize (p v))") + "realization is missing a method of")) + (test-assert "nor is a comment" + (reports? (string-append "(record v ((x int)))" + "(spec (p T) (fn s ((a (* const T))) int\n" + " ;; must be implemented\n" + " ))" + "(realize (p v))") + "realization is missing a method of")) + (test-assert "a documented default is still a default" + (emits? (string-append "(record v ((x int)))" + "(spec (p T) (fn s ((a (* const T))) int \"doc\" (return 1)))" + "(realize (p v))") + "/* doc */")) (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))" -- 2.52.0 From 5ba55f05a5efd46366e789a373788cdf3d9e29e1 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 16:24:00 +0300 Subject: [PATCH 20/40] read a spread self as the pointer it is (self * const v) typed the method's self as `self', so a call passed a value where the method took a pointer, and a spec written one way refused a realization written the other. A const receiver handed to a method taking (* v) is now refused rather than left to cc's warning. --- semen.scm | 53 +++++++++++++++++++++++++---------------- tests/encapsulation.scm | 21 +++++++++++++++- 2 files changed, 53 insertions(+), 21 deletions(-) diff --git a/semen.scm b/semen.scm index c4954dc..55e5b6c 100644 --- a/semen.scm +++ b/semen.scm @@ -443,17 +443,11 @@ (define (make-fn-env fn-form) (let ((env (make-hash-table)) (parameters (make-hash-table))) - ;; `(p (* struct point))' writes the type in one piece and - ;; `(p * struct point)' spreads it over the rest, so the type is - ;; the whole tail whenever there is more of it than one element (for-each (lambda (param) - (when (and (pair? param) (pair? (cdr param)) - (named-arg? param)) + (when (named-arg? param) (hash-table-set! parameters (first param) - (if (null? (cddr param)) - (second param) - (cdr param))))) + (named-arg-type param)))) (sex-fn-arglist fn-form)) (set! (hash-table-ref env :fn-name) (sex-fn-name fn-form)) (set! (hash-table-ref env :lambda-counter) 0) @@ -462,13 +456,22 @@ (set! (hash-table-ref env :scopes) (list parameters)) env)) -;;; (fn sum ((a int) (b int)) int ...) -> (fn ((int) (int)) int). -;;; Anything that is not a plain (name type) -- a variadic tail -- goes -;;; through untouched. +;;; `(p (* struct point))' writes the type in one piece and +;;; `(p * struct point)' spreads it over the rest; both are +;;; `(* struct point)' +(define (named-arg-type param) + (if (null? (cddr param)) + (second param) + (cdr param))) + +;;; (fn sum ((a int) (b int)) int ...) -> (fn ((int) (int)) int), and +;;; (self * const v) is ((* const v)) just as (self (* const v)) is. +;;; Anything that names nothing -- a variadic tail -- goes through +;;; untouched. (define (arglist-types arglist) (map (lambda (param) - (if (and (pair? param) (= 2 (length param)) (named-arg? param)) - (list (second param)) + (if (named-arg? param) + (list (named-arg-type param)) param)) arglist)) @@ -876,17 +879,25 @@ (copy-form-source! form `(,method - ,(method-receiver method (and target #t) + ,(method-receiver method (or target written) (and target #t) (walk-statement receiver env) form) ,@(map (lambda (argument) (walk-statement argument env)) (cddr form)))))))) ;;; A method taking (* Self) wants an address and one taking Self wants ;;; a value; the receiver is one or the other, so one of the two gets -;;; `&' or `*' put in front of it -(define (method-receiver method pointer? receiver form) - (let ((wants-pointer? (let ((self (method-self-type method))) - (and (pair? self) (eq? '* (car self)))))) +;;; `&' or `*' put in front of it. +;;; +;;; OBJECT is what the receiver holds or points at: a `(const v)' handed +;;; to a method taking (* v) would be quietly stripped of its const. +(define (method-receiver method object pointer? receiver form) + (let* ((self (method-self-type method)) + (wants-pointer? (and (pair? self) (eq? '* (car self))))) + (when (and wants-pointer? + (const-type? object) + (not (const-type? (pointer-target self)))) + (sex-error form "method may change its receiver, and this one is const" + method)) (cond ((eq? wants-pointer? pointer?) receiver) ((not wants-pointer?) `(* ,receiver)) ;; `&(f())' is not C, and the method cannot be given a @@ -937,8 +948,10 @@ (eq? 'fn (car signature)) (pair? (cdr signature)) (pair? (second signature)) - (let ((self (car (second signature)))) - (if (pair? self) (car self) self))))) + (unwrap-type (car (second signature)))))) + +(define (const-type? type) + (and (pair? type) (eq? 'const (car type)))) (define (as-closure-type type) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 22f4ced..ce8d772 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -13,7 +13,8 @@ "(record vec2 ((x float) (y float)))" "(ops vec2" " (pub fn length ((self (* const vec2))) float (return 1.0))" - " (fn sum-of ((self vec2)) float (return (. self x))))" + " (fn sum-of ((self vec2)) float (return (. self x)))" + " (fn scale ((self (* vec2))) void (= (. self x) 2.0)))" "(fn mk () vec2 (return #(vec2 : 1.0 2.0)))" "(fn f () void (var v vec2 #(vec2 : 1.0 2.0)) (var p (* vec2) (& v)) " (apply string-append body) ")")) @@ -111,6 +112,19 @@ (reports? (ops-src "(.nope v)") "no such method on")) (test-assert "and so is a receiver with no type to dispatch on" (reports? "(fn f () void (var n int 1) (.get n))" "no such method on")) + (test-assert "a self spread over the parameter is a pointer self too" + (emits? (string-append + "(record w ((x int)))" + "(ops w (fn get ((self * const w)) int (return (. self x))))" + "(fn f () int (var a w #(w : 1)) (var p (* const w) (& a))" + " (return (+ (.get a) (.get p))))") + "wːget(&a) + wːget(p)")) + (test-assert "a const receiver is not handed to a method that may change it" + (reports? (ops-src "(var c (* const vec2) p) (.scale c)") + "this one is const")) + (test-assert "one that cannot change it takes it" + (emits? (ops-src "(var c (* const vec2) p) (var n float (.length c))") + "vec2ːlength(c)")) (test-assert "an address cannot be taken of a call" (reports? (ops-src "(.length (mk))") "receiver is not an lvalue")) ;; the inner call has to be typed to find the outer one's receiver @@ -231,6 +245,11 @@ "(spec (p T) (fn s ((a (* const T))) void))" "(realize (p v) (fn s ((a v)) void (return)))") "arguments do not match")) + (test-assert "but not on how a pointer is spelled" + (emits? (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)))") + "void vːpːs (const v * a)")) (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)))" -- 2.52.0 From 3baaafafc3ed9654596ba489e0b37e05b62b3ad0 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 16:37:51 +0300 Subject: [PATCH 21/40] refuse the matches and sums cc would refuse MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two else arms, a variant declared twice, and a match standing where a value is wanted all reached cc as broken C; an arm that is not a list crashed sexc. A variant called tag collided with the tag enum, now spelled shapeǂ so no variant name can reach it. --- semen.scm | 81 ++++++++++++++++++++++++++++++++--------- tests/encapsulation.scm | 30 ++++++++++++++- 2 files changed, 91 insertions(+), 20 deletions(-) diff --git a/semen.scm b/semen.scm index 55e5b6c..7ce7935 100644 --- a/semen.scm +++ b/semen.scm @@ -2,6 +2,7 @@ (import scheme + (only (scheme base) make-parameter) (chicken base) (chicken keyword) (chicken string) @@ -276,7 +277,8 @@ (let* ((env (make-fn-env expanded)) ;; the parameters are the body's outermost scope (header (map resolve-closure-types (take expanded boundary))) - (body (walk-body (drop expanded boundary) env)) + (body (parameterize ((operand-position? #f)) + (walk-body (drop expanded boundary) env))) ;; A function is header and body stitched together, so the ;; result is fresh structure: without this the definition ;; has no location, and nothing downstream can say where @@ -538,6 +540,20 @@ (list walked)))) forms)) +;;; #t while the walk is inside a value -- an initializer, an argument, +;;; a returned expression -- where a statement-only form has no C +;;; spelling: +;;; +;;; (var n int (match s ...)) -> int n = switch (s.tag) { ... +;;; +;;; A condition is not tracked: `walk-parts' takes every slot of an `if' +;;; alike. +(define operand-position? (make-parameter #f)) + +(define (walk-operand form env) + (parameterize ((operand-position? #t)) + (walk-statement form env))) + (define (walk-statement form env) (cond ((not (list? form)) form) @@ -557,7 +573,12 @@ (else (case (car form) ((do for while if switch) - (with-scope env (lambda () (walk-parts form env)))) + (parameterize ((operand-position? #f)) + (with-scope env (lambda () (walk-parts form env))))) + + ((case case/fallthrough default) + (parameterize ((operand-position? #f)) + (walk-parts form env))) ((lambda) (let ((name (aux-name! env make-lambda-name))) @@ -574,8 +595,8 @@ (copy-form-source! form `(,construct ,@(map (lambda (capture) - (walk-statement (capture-argument capture) - env)) + (walk-operand (capture-argument capture) + env)) (fourth form)))))))) ((var) @@ -595,7 +616,8 @@ form (append prefix (if (> (length form) 3) - (walk-body (drop form 3) env) + (parameterize ((operand-position? #t)) + (walk-body (drop form 3) env)) (list)))) env)) (bound (if (>= (length walked) 4) @@ -612,7 +634,8 @@ bound)) ((return) - (let ((walked (walk-parts form env))) + (let ((walked (parameterize ((operand-position? #t)) + (walk-parts form env)))) (if (>= (length walked) 2) (copy-form-source! walked @@ -622,7 +645,10 @@ (cddr walked)))) walked))) - ((match) (walk-match form env)) + ((match) + (when (operand-position?) + (sex-error form "match is a statement, and has no value")) + (walk-match form env)) ((dot-access) (walk-member-path form env)) @@ -634,14 +660,16 @@ ;; the receiver is walked first: `((closure ((x int)) ;; int () ...) 5)' registers `struct ƛint_int' on the ;; way, and the call helper's signature names it - (let ((receiver (walk-statement (car form) env))) + (let ((receiver (walk-operand (car form) env))) (copy-form-source! form `(,(register-closure-call! closure form) ,receiver - ,@(map (lambda (a) (walk-statement a env)) + ,@(map (lambda (a) (walk-operand a env)) (cdr form))))) - (convert-arguments (walk-parts form env) env))))))))) + (convert-arguments (parameterize ((operand-position? #t)) + (walk-parts form env)) + env))))))))) ;;; `(var n _ (strlen s))' becomes `(var n size-t (strlen s))'. (define (resolve-wildcard form env) @@ -797,15 +825,23 @@ (define (match-arm-variant arm) (and (pair? (car arm)) (car (car arm)))) (define (check-match form name variants arms) + (for-each + (lambda (arm) + (unless (and (pair? arm) + (or (eq? (car arm) 'else) + (and (list? (car arm)) (= 2 (length (car arm))) + (list? (second (car arm)))))) + (sex-error form "an arm is ((variant (binders ...)) body ...)" arm))) + arms) (let* ((else? (lambda (arm) (eq? (car arm) 'else))) (named (remove else? arms)) (covered (map match-arm-variant named))) + (when (> (count else? arms) 1) + (sex-error form "match has more than one else")) (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)))) @@ -880,8 +916,8 @@ form `(,method ,(method-receiver method (or target written) (and target #t) - (walk-statement receiver env) form) - ,@(map (lambda (argument) (walk-statement argument env)) + (walk-operand receiver env) form) + ,@(map (lambda (argument) (walk-operand argument env)) (cddr form)))))))) ;;; A method taking (* Self) wants an address and one taking Self wants @@ -918,7 +954,7 @@ ;;; path would have meant before any of this. (define (walk-member-path form env) (let ((base (second form))) - (let step ((expr (walk-statement base env)) + (let step ((expr (walk-operand base env)) (type (expression-type base env)) (fields (cddr form)) (told? #f)) @@ -1556,6 +1592,10 @@ (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))) + (let* ((names (map car variants)) + (twice (find (lambda (v) (> (count (cut eq? <> v) names) 1)) names))) + (when twice + (sex-error form "variant is declared twice" twice))) (when (get-sum name) (sex-error form "sum is already defined" name)) (add-sum! name variants) @@ -1597,7 +1637,7 @@ `(fn ,payload ,fields ,name (return ,(sum-literal name tag payload fields))))) -;;; #(shape : .tag shapeːtagːcircle .u #(.circle #((struct shapeːcircle) : r))) +;;; #(shape : .tag shapeǂ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)) @@ -1612,10 +1652,15 @@ (define (dotted name) (string->symbol (string-append "." (symbol->string name)))) -(define (sum-tag name) (qualify-op name 'tag)) +;;; shape -> enum shapeǂ, circle -> shapeǂcircle. Not shapeːtag: that +;;; is where a variant named `tag' keeps its payload struct, and an enum +;;; and a struct share C's tag namespace. +(define (sum-tag name) + (string->symbol (string-append (symbol->string name) "ǂ"))) (define (sum-tag-constant name variant) - (qualify-op (sum-tag name) variant)) + (string->symbol (string-append (symbol->string (sum-tag name)) + (symbol->string variant)))) ;;; (record point ((x int) (y int))) is a struct that also names ;;; itself, so `point' alone stands where `(struct point)' had to: diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index ce8d772..cdce09b 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -140,7 +140,11 @@ ;; fields, the record holding both, and a constructor each. (test-group "sum" (test-assert "the tag enum is named after the sum" - (emits? (sum-src "") "enum shapeːtag")) + (emits? (sum-src "") "enum shapeǂ {")) + (test-assert "and its constants after the sum and the variant" + (emits? (sum-src "") "shapeǂcircle")) + (test-assert "a variant may be called tag" + (emits? "(sum t ((tag ((x int))) (none ())))" "struct tːtag {")) (test-assert "a variant with fields gets a payload struct" (emits? (sum-src "") "struct shapeːcircle {")) (test-assert "the sum is typedef'd" @@ -160,7 +164,9 @@ (test-assert "and needs variants" (reports? "(sum t)" "sum needs a name and a list of variants")) (test-assert "a variant is a name and a field list" - (reports? "(sum t (a))" "a variant is"))) + (reports? "(sum t (a))" "a variant is")) + (test-assert "and is declared once" + (reports? "(sum t ((a ((x int))) (a ())))" "variant is declared twice"))) ;; A spec is a contract that emits nothing; a realization is its ;; methods for one type. The refusals are what make it a contract. @@ -305,6 +311,26 @@ (reports? (sum-src "(match s ((circle (r)) (= out r)) ((circle (q)) (= out q))" " (else (= out 0.0)))") "arm is written twice")) + (test-assert "so is a second else" + (reports? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0))" + " (else (= out 1.0)))") + "more than one else")) + (test-assert "so is an arm that is not one" + (reports? (sum-src "(match s foo)") "an arm is")) + (test-assert "match has no value" + (reports? (sum-src "(var n float (match s ((circle (r)) r) (else 0.0)))") + "match is a statement")) + (test-assert "not even as an argument" + (reports? (sum-src "(= out (match s ((circle (r)) r) (else 0.0)))") + "match is a statement")) + (test-assert "but a case body is a statement" + (emits? (sum-src "(switch 1 (case 1 (match s ((circle (r)) (= out r))" + " (else (= out 0.0)))))") + "switch (s.tag)")) + (test-assert "and so is a closure's, wherever the closure stands" + (emits? (sum-src "(var c (closure () int) (closure () int ((t s))" + " (match t ((circle (r)) (return 1)) (else (return 0)))))") + "switch (t.tag)")) (test-assert "and a scrutinee that is not a sum" (reports? "(fn f () void (var n int 1) (match n ((a ()) (= n 2))))" "match wants a sum")))) -- 2.52.0 From bb2f05fa3638bbecfc9d23affeb8f07bf77906e0 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 16:40:37 +0300 Subject: [PATCH 22/40] type a macro call by what it expands to A receiver, a scrutinee or the start of a path was typed before the walk had expanded it, so (.len (the a)) had no type to dispatch on and (. (the p) x) read a pointer as a value. --- semen.scm | 23 +++++++++++++++++------ tests/encapsulation.scm | 13 +++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/semen.scm b/semen.scm index 7ce7935..9adfdca 100644 --- a/semen.scm +++ b/semen.scm @@ -561,12 +561,7 @@ ;; expanded here rather than before the walk, so the macro body can ;; ask `(type-of x)' about a local the walk has already passed ((macro? form) - (let ((expansion (parameterize - ((current-type-of - (lambda (queried) - (unresolve-closure-types - (expression-type queried env))))) - (macroexpand form (list))))) + (let ((expansion (expand-call form env))) (if (and (pair? expansion) (null? (cdr expansion))) (walk-statement (car expansion) env) (cons walk-embed-result (walk-body expansion env))))) @@ -671,6 +666,14 @@ (walk-parts form env)) env))))))))) +;;; The forms a macro call stands for, with `(type-of x)' answered from +;;; ENV +(define (expand-call form env) + (parameterize ((current-type-of + (lambda (queried) + (unresolve-closure-types (expression-type queried env))))) + (macroexpand form (list)))) + ;;; `(var n _ (strlen s))' becomes `(var n size-t (strlen s))'. (define (resolve-wildcard form env) (if (and (>= (length form) 3) (wildcard-type? (third form))) @@ -1029,6 +1032,14 @@ (let ((written (car parts))) (if (= 1 (length written)) (car written) written))))) ((symbol? expr) (or (lookup-name env expr) (get-name-type expr))) + ;; the walk expands `(the a)' before it gets there, so its type is + ;; that of what it expands to: + ;; + ;; (.len (the a)) (match (the s) ...) (. (the a) x) + ((macro? expr) + (let ((expansion (expand-call expr env))) + (and (pair? expansion) (null? (cdr expansion)) + (expression-type (car expansion) env)))) ((not (and (list? expr) (pair? expr))) #f) ;; a call of no arguments is still a call ((< (length expr) 2) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index cdce09b..0f05f74 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -125,6 +125,14 @@ (test-assert "one that cannot change it takes it" (emits? (ops-src "(var c (* const vec2) p) (var n float (.length c))") "vec2ːlength(c)")) + (test-assert "a macro receiver is typed by what it expands to" + (emits? (string-append "(defmacro (the a) a)" + (ops-src "(var n float (.length (the v)))")) + "vec2ːlength(&v)")) + (test-assert "and so is the start of a path" + (emits? (string-append "(defmacro (the a) a)" + (ops-src "(var q float (. (the p) x))")) + "p->x")) (test-assert "an address cannot be taken of a call" (reports? (ops-src "(.length (mk))") "receiver is not an lvalue")) ;; the inner call has to be typed to find the outer one's receiver @@ -285,6 +293,11 @@ (test-assert "a path scrutinee is not copied" (not (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))") "ƛm0"))) + (test-assert "a macro scrutinee is typed by what it expands to" + (emits? (string-append "(defmacro (the a) a)" + (sum-src "(match (the s) ((circle (r)) (= out r))" + " (else (= out 0.0)))")) + "shape ƛm0 = s")) (test-assert "else becomes default" (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))") "default:")) -- 2.52.0 From 224ef8fb6b63ccdfa16e63c94b2f1df248985b7f Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 16:54:16 +0300 Subject: [PATCH 23/40] file methods, realizations and sums under what a typedef names A typedef had the fields of its record but none of its methods, and a typedef of a sum was not a sum to match. A typedef that ends in a scalar still keeps its own, so (typedef meters float) does not lend its methods to every float. --- tests/encapsulation.scm | 37 +++++++++++++++++++++++++++++++++++++ types.scm | 34 +++++++++++++++++++++++++++------- 2 files changed, 64 insertions(+), 7 deletions(-) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 0f05f74..119e334 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -133,6 +133,33 @@ (emits? (string-append "(defmacro (the a) a)" (ops-src "(var q float (. (the p) x))")) "p->x")) + (test-assert "a typedef of the type has its methods" + (emits? (string-append + "(record w ((x int)))" + "(typedef alias w)" + "(ops w (fn get ((self (* const w))) int (return (. self x))))" + "(fn f () int (var a alias #(alias : 1)) (return (.get a)))") + "wːget(&a)")) + (test-assert "and a method written on the typedef is the type's" + (emits? (string-append + "(record w ((x int)))" + "(typedef alias w)" + "(ops alias (fn get ((self (* const alias))) int (return 1)))" + "(fn f () int (var a w #(w : 1)) (return (.get a)))") + "aliasːget(&a)")) + (test-assert "a typedef of a scalar keeps its own" + (reports? (string-append + "(typedef meters float)" + "(ops meters (fn half ((self meters)) meters (return self)))" + "(fn f () void (var x float 1.0) (.half x))") + "no such method on")) + (test-assert "which a typedef of it shares" + (emits? (string-append + "(typedef meters float)" + "(typedef km meters)" + "(ops meters (fn half ((self meters)) meters (return self)))" + "(fn f () void (var x km 1.0) (var y km (.half x)))") + "metersːhalf(x)")) (test-assert "an address cannot be taken of a call" (reports? (ops-src "(.length (mk))") "receiver is not an lvalue")) ;; the inner call has to be typed to find the outer one's receiver @@ -208,6 +235,9 @@ (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 typedef realizes what its type does" + (reports? (string-append (spec-src "") "(typedef alias v)(realize (p alias))") + "spec is already realized for")) (test-assert "a type realizes a spec once" (reports? (string-append (spec-src "") "(realize (p v)" " (fn s ((a (* const v))) void (return)))") @@ -298,6 +328,13 @@ (sum-src "(match (the s) ((circle (r)) (= out r))" " (else (= out 0.0)))")) "shape ƛm0 = s")) + (test-assert "a typedef of a sum is matched as the sum" + (emits? (string-append + "(sum shape ((circle ((r int))) (empty ())))" + "(typedef alias shape)" + "(fn f () int (var s alias (shape/circle 1))" + " (match s ((circle (r)) (return r)) ((empty ()) (return 0))))") + "case shapeǂcircle")) (test-assert "else becomes default" (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))") "default:")) diff --git a/types.scm b/types.scm index 0a5ac3d..25166f2 100644 --- a/types.scm +++ b/types.scm @@ -100,10 +100,10 @@ (define +sum-db+ (make-hash-table)) (define (add-sum! name variants) - (hash-table-set! +sum-db+ name variants)) + (hash-table-set! +sum-db+ (type-key name) variants)) (define (get-sum name) - (hash-table-ref/default +sum-db+ name #f)) + (hash-table-ref/default +sum-db+ (type-key name) #f)) (define (variant-fields variants name) (let ((entry (assq name variants))) @@ -130,11 +130,11 @@ (define (spec-methods spec) (cdr spec)) (define (add-realization! spec type) - (hash-table-set! +realize-db+ (cons spec type) #t)) + (hash-table-set! +realize-db+ (cons spec (type-key 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))) + (hash-table-exists? +realize-db+ (cons spec (type-key type)))) ;;; Both of these refuse a second declaration of the same name, which ;;; is per translation unit rather than per process -- so a process @@ -156,10 +156,10 @@ (define +ops-db+ (make-hash-table)) (define (add-method! type method qualified) - (hash-table-set! +ops-db+ (cons type method) qualified)) + (hash-table-set! +ops-db+ (cons (type-key type) method) qualified)) (define (get-method type method) - (hash-table-ref/default +ops-db+ (cons type method) #f)) + (hash-table-ref/default +ops-db+ (cons (type-key type) method) #f)) ;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength (define (qualify-op type name) @@ -169,13 +169,33 @@ ;;; The name an `ops' block was written against: `(struct point)' and a ;;; `const' wrapper both name `point', and anything else names nothing. (define (ops-key type) - (cond ((symbol? type) type) + (cond ((symbol? type) (type-key type)) ((not (and (pair? type) (symbol? (car type)))) #f) ((memq (car type) '(struct union enum)) (and (pair? (cdr type)) (symbol? (cadr type)) (cadr type))) ((memq (car type) '(const volatile)) (ops-key (cadr type))) (else #f))) +;;; The name methods, realizations and sums are filed under. A typedef +;;; is followed to the aggregate it names, and one that ends in anything +;;; else stops at the last typedef, so a scalar does not share them: +;;; +;;; (record v ...) (typedef alias v) alias -> v +;;; (typedef meters float) meters -> meters +;;; (typedef km meters) km -> meters +(define (type-key name) + (let follow ((name name) (seen (list))) + (let ((target (and (not (memq name seen)) (typedef-target name)))) + (cond ((not target) name) + ((symbol? target) + (if (typedef-target target) (follow target (cons name seen)) name)) + ((target-tag target)) + (else name))))) + +(define (typedef-target name) + (let ((info (and (symbol? name) (get-type-info name)))) + (and info (eq? (car info) 'typedef) (caddr info)))) + (define (add-name-type! name type) (hash-table-set! +name-db+ name type)) -- 2.52.0 From 9af9113bf520fc6678c55735688ef56e8e9cacfc Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 17:07:20 +0300 Subject: [PATCH 24/40] walk the values of a brace literal The walk stopped at a vector, so whatever a literal held reached the writer as written: #(v : (.get a)) was (v){.get(a)}, and a path through a pointer inside one read it as a value. --- semen.scm | 10 ++++++++++ tests/encapsulation.scm | 6 ++++++ 2 files changed, 16 insertions(+) diff --git a/semen.scm b/semen.scm index 9adfdca..88abd4f 100644 --- a/semen.scm +++ b/semen.scm @@ -556,6 +556,7 @@ (define (walk-statement form env) (cond + ((vector? form) (walk-literal form env)) ((not (list? form)) form) ((null? form) form) ;; expanded here rather than before the walk, so the macro body can @@ -674,6 +675,15 @@ (unresolve-closure-types (expression-type queried env))))) (macroexpand form (list)))) +;;; `#(v : (.get a))' is `(v){vːget(&a)}': the values are expressions +;;; like any other, and the type before `:' is not one +(define (walk-literal form env) + (let* ((parts (vector->list form)) + (elements (or (and (memq ': parts) (cdr (memq ': parts))) parts))) + (list->vector + (append (drop-right parts (length elements)) + (map (lambda (element) (walk-operand element env)) elements))))) + ;;; `(var n _ (strlen s))' becomes `(var n size-t (strlen s))'. (define (resolve-wildcard form env) (if (and (>= (length form) 3) (wildcard-type? (third form))) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 119e334..5baf266 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -160,6 +160,12 @@ "(ops meters (fn half ((self meters)) meters (return self)))" "(fn f () void (var x km 1.0) (var y km (.half x)))") "metersːhalf(x)")) + (test-assert "a method call inside a literal is still a call" + (emits? (ops-src "(var w vec2 #(vec2 : (.length v) 1.0))") + "(vec2){vec2ːlength(&v), 1.0}")) + (test-assert "however deep" + (emits? (ops-src "(var ws [vec2 1] #(#(vec2 : (.length p) 1.0)))") + "{(vec2){vec2ːlength(p), 1.0}}")) (test-assert "an address cannot be taken of a call" (reports? (ops-src "(.length (mk))") "receiver is not an lvalue")) ;; the inner call has to be typed to find the outer one's receiver -- 2.52.0 From e91b44dbe192496a2c2adb53a76e27230a873a74 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 17:08:42 +0300 Subject: [PATCH 25/40] walk a global's initializer like a local's Only a local's initializer was walked, so at file scope a path was not dispatched, a lambda was never lifted, and a constructor written in place would have been left a call to nothing. --- semen.scm | 27 ++++++++++++++++++++++----- tests/codegen.scm | 16 ++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/semen.scm b/semen.scm index 88abd4f..51f7fda 100644 --- a/semen.scm +++ b/semen.scm @@ -1716,28 +1716,45 @@ ;;; No function around a toplevel form, so no scope chain: what a ;;; global's initializer names comes from `get-name-type' alone. -(define (make-toplevel-env) +;;; What a global's initializer is walked in: no names but its own, +;;; and anything it lifts is named after the global +(define (make-toplevel-env name) (let ((env (make-hash-table))) + (set! (hash-table-ref env :fn-name) name) + (set! (hash-table-ref env :lambda-counter) 0) + (set! (hash-table-ref env :lambda-aux-code) (list)) (set! (hash-table-ref env :scopes) (list)) env)) +;;; The writer spells neither `closure' nor `_', and an initializer is +;;; an expression like any other: +;;; +;;; (var n _ 1) -> int n = 1 +;;; (var o v #(v : (.get a))) -> v o = (v){vːget(&a)} (define (process-global-var sex-var acc) - ;; A global is not walked for lambdas, but the writer spells neither - ;; `closure' nor `_': `(var n _ 1)' has to reach it as `int n = 1' (let* ((resolved (resolve-closure-types sex-var)) (qualifier (and (memq (car resolved) '(pub extern)) (car resolved))) (core (if qualifier (cdr resolved) resolved)) + (env (make-toplevel-env (and (pair? (cdr core)) (second core)))) ;; `(extern var n int)' has no initializer to work a `_' out ;; from (core (if (eq? 'extern qualifier) core - (resolve-wildcard core (make-toplevel-env)))) + (resolve-wildcard + (copy-form-source! + core + (if (> (length core) 3) + (append (take core 3) + (parameterize ((operand-position? #t)) + (walk-body (drop core 3) env))) + core)) + env))) (form (if qualifier (copy-form-source! resolved (cons qualifier core)) core))) (when (and (pair? (cdr core)) (pair? (cddr core)) (symbol? (second core))) (add-name-type! (second core) (third core))) - (cons form acc))) + (cons form (append (hash-table-ref env :lambda-aux-code) acc)))) ;;; Utils (define (non-empty-list? form) diff --git a/tests/codegen.scm b/tests/codegen.scm index 43283e4..7fe9c25 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -691,6 +691,22 @@ compiles." (test-assert "a bare -> is not the arrow" (emits? (in-line "(= (-> pp x) 1)") "->(pp, x) = 1"))) + ;; A global's initializer is an expression like a local's, and walked + ;; the same way + (test-group "global initializers" + (test-assert "a path is dispatched on its type" + (emits? (string-append "(struct pt ((x int)))" + "(var a (struct pt) #((struct pt) : 1))" + "(var q (* int) (& (. a x)))") + "int * q = &a.x")) + (test-assert "a lambda is lifted, and named after the global" + (emits? "(var f (fn ((x int)) int) (lambda ((x int)) int (return x)))" + "int (*f)(int) = λ0_f")) + (test-assert "ahead of it" + (let ((c (sex->c "(var f (fn ((x int)) int) (lambda ((x int)) int (return x)))"))) + (< (string-contains c "static int λ0_f (int x)") + (string-contains c "(*f)(int) = λ0_f"))))) + ;; Toplevel forms used to be separated by a blank line unconditionally, ;; which spread a block of adjacent typedefs over twice the lines its ;; author wrote -- 2.52.0 From 427177d50f19b4a909c1e8b3cee656edd3a85946 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 17:11:38 +0300 Subject: [PATCH 26/40] write a sum's constructors in place A constructor was a static function per variant. One taking an array field cannot exist, its parameter being a pointer, and building some variants in place and others by call would make two kinds of constructor. In place, every one is a constant where one is wanted, an lvalue a method can take the address of, and nothing a pub sum has to paste into its importer. What the function did for free is done here instead: arity is checked, since a short compound literal zero-fills quietly, and an argument is converted against its field's closure type. The price is that a constructor is no longer a function value; a lambda makes one. --- semen.scm | 110 ++++++++++++++++++++++++---------------- tests/encapsulation.scm | 28 +++++++++- tests/modules/greet.sex | 4 +- tests/types.module.scm | 2 + types.module.scm | 2 + types.scm | 10 ++++ 6 files changed, 109 insertions(+), 47 deletions(-) diff --git a/semen.scm b/semen.scm index 51f7fda..e7c2ab3 100644 --- a/semen.scm +++ b/semen.scm @@ -554,6 +554,21 @@ (parameterize ((operand-position? #t)) (walk-statement form env))) +;;; FORMS are values written inside PARENT, which is what a diagnostic +;;; about one of them points at -- a bare name has no location of its +;;; own: +;;; +;;; (var f (fn ((r float)) shape) shape/circle) +(define (walk-operands parent forms env) + (for-each (lambda (form) + (when (and (symbol? form) (get-constructor form)) + (sex-error parent + "a constructor is not a function; call it from a lambda" + form))) + forms) + (parameterize ((operand-position? #t)) + (walk-body forms env))) + (define (walk-statement form env) (cond ((vector? form) (walk-literal form env)) @@ -612,8 +627,7 @@ form (append prefix (if (> (length form) 3) - (parameterize ((operand-position? #t)) - (walk-body (drop form 3) env)) + (walk-operands form (drop form 3) env) (list)))) env)) (bound (if (>= (length walked) 4) @@ -630,8 +644,7 @@ bound)) ((return) - (let ((walked (parameterize ((operand-position? #t)) - (walk-parts form env)))) + (let ((walked (copy-form-source! form (walk-operands form form env)))) (if (>= (length walked) 2) (copy-form-source! walked @@ -649,23 +662,44 @@ ((dot-access) (walk-member-path form env)) (else - (if (method-head? (car form)) - (walk-method-call form env) - (let ((closure (receiver-closure-type (car form) env))) - (if closure - ;; the receiver is walked first: `((closure ((x int)) - ;; int () ...) 5)' registers `struct ƛint_int' on the - ;; way, and the call helper's signature names it - (let ((receiver (walk-operand (car form) env))) - (copy-form-source! - form - `(,(register-closure-call! closure form) - ,receiver - ,@(map (lambda (a) (walk-operand a env)) - (cdr form))))) - (convert-arguments (parameterize ((operand-position? #t)) - (walk-parts form env)) - env))))))))) + (cond + ((method-head? (car form)) (walk-method-call form env)) + ((get-constructor (car form)) + => (lambda (constructor) (walk-construction form constructor env))) + ((receiver-closure-type (car form) env) + => (lambda (closure) + ;; the receiver is walked first: `((closure ((x int)) + ;; int () ...) 5)' registers `struct ƛint_int' on the + ;; way, and the call helper's signature names it + (let ((receiver (walk-operand (car form) env))) + (copy-form-source! + form + `(,(register-closure-call! closure form) + ,receiver + ,@(walk-operands form (cdr form) env)))))) + (else + (convert-arguments (copy-form-source! form (walk-operands form form env)) + env)))))))) + +;;; (shape/circle 1.0) is the value itself, written where it is used: +;;; +;;; (shape){.tag = shapeǂcircle, .u = {.circle = (struct shapeːcircle){1.0}}} +;;; +;;; so it is a constant where one is wanted, an lvalue a method can take +;;; the address of, and a pub sum pastes nothing into the importer but +;;; its declarations. A lambda argument is converted against its field +;;; the way a call converts one against its parameter. +(define (walk-construction form constructor env) + (let* ((name (car constructor)) + (tag (cdr constructor)) + (fields (variant-fields (get-sum name) tag)) + (args (walk-operands form (cdr form) env))) + (unless (= (length fields) (length args)) + (sex-error form "variant takes this many fields" tag (length fields))) + (sum-literal name tag + (map (lambda (field arg) + (convert-to-closure (second field) arg env form)) + fields args)))) ;;; The forms a macro call stands for, with `(type-of x)' answered from ;;; ENV @@ -930,8 +964,7 @@ `(,method ,(method-receiver method (or target written) (and target #t) (walk-operand receiver env) form) - ,@(map (lambda (argument) (walk-operand argument env)) - (cddr form)))))))) + ,@(walk-operands form (cddr form) env))))))) ;;; A method taking (* Self) wants an address and one taking Self wants ;;; a value; the receiver is one or the other, so one of the two gets @@ -1051,6 +1084,8 @@ (and (pair? expansion) (null? (cdr expansion)) (expression-type (car expansion) env)))) ((not (and (list? expr) (pair? expr))) #f) + ;; (shape/circle 1.0) -> shape + ((and (symbol? (car expr)) (get-constructor (car expr))) => car) ;; a call of no arguments is still a call ((< (length expr) 2) (and (symbol? (car expr)) (get-return-type (car expr)))) @@ -1620,6 +1655,8 @@ (when (get-sum name) (sex-error form "sum is already defined" name)) (add-sum! name variants) + (for-each (lambda (v) (add-constructor! (qualify-op name (car v)) name (car v))) + variants) (fold match-sex-form acc (map (lambda (f) (copy-form-source! form f)) (sum-forms name variants)))))) @@ -1644,31 +1681,19 @@ `((u (union ,(map (lambda (v) `(,(car v) (struct ,(qualify-op name (car v))))) - carried))))))) - ,@(map (lambda (v) (sum-constructor name v)) variants)))) + carried)))))))))) -;;; (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ǂcircle .u #(.circle #((struct shapeːcircle) : r))) -(define (sum-literal name tag payload fields) +;;; #(shape : .tag shapeǂcircle .u #(.circle #((struct shapeːcircle) : 1.0))) +(define (sum-literal name tag values) (list->vector (append (list name ': (dotted 'tag) (sum-tag-constant name tag)) - (if (null? fields) + (if (null? values) (list) (list (dotted 'u) (vector (dotted tag) (list->vector - (append (list (list 'struct payload) ':) - (map car fields))))))))) + (append (list (list 'struct (qualify-op name tag)) ':) + values)))))))) (define (dotted name) (string->symbol (string-append "." (symbol->string name)))) @@ -1745,8 +1770,7 @@ core (if (> (length core) 3) (append (take core 3) - (parameterize ((operand-position? #t)) - (walk-body (drop core 3) env))) + (walk-operands core (drop core 3) env)) core)) env))) (form (if qualifier diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 5baf266..6a2c5a9 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -196,8 +196,32 @@ (test-assert "the typedef comes before the payloads, for a recursive sum" (emits? "(sum expr ((lit ((v float))) (neg ((e (* const expr))))))" "typedef struct expr expr;")) - (test-assert "constructors are static even when the sum is pub" - (emits? "(pub sum t ((a ((x int)))))" "static t tːa")) + (test-assert "a constructor is written in place" + (emits? "(pub sum t ((a ((x int)))))(fn f () t (return (t/a 1)))" + "(struct tːa){1}")) + (test-assert "and is no function" + (not (emits? "(pub sum t ((a ((x int)))))(fn f () t (return (t/a 1)))" + "t tːa ("))) + (test-assert "so it is a constant at file scope" + (emits? "(sum t ((a ((x int)))))(var g t (t/a 1))" "static t g = (t){")) + (test-assert "and an lvalue a method can take the address of" + (emits? (string-append + "(sum t ((a ((x int)))))" + "(ops t (fn get ((self (* const t))) int (return 1)))" + "(fn f () int (return (.get (t/a 1))))") + "tːget(&(t){")) + (test-assert "a constructor takes as many arguments as its variant has fields" + (reports? "(sum t ((a ((x int)))))(fn f () t (return (t/a 1 2)))" + "variant takes this many fields")) + (test-assert "and is not a function value" + (reports? "(sum t ((a ((x int)))))(fn f () void (var g (fn ((x int)) t) t/a))" + "a constructor is not a function")) + (test-assert "a function argument becomes the closure its field holds" + (emits? (string-append + "(fn g ((n int)) int (return n))" + "(sum t ((a ((k (closure ((int)) int))))))" + "(fn f () t (return (t/a g)))") + "ƛint_int_fromfn(g)")) (test-assert "a tag-only sum has no union at all" (not (emits? "(sum light ((red ()) (green ())))" "union"))) (test-assert "a sum is declared once" diff --git a/tests/modules/greet.sex b/tests/modules/greet.sex index f309a19..3da58b3 100644 --- a/tests/modules/greet.sex +++ b/tests/modules/greet.sex @@ -80,8 +80,8 @@ (free self))) ;;; 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. +;;; the declarations; a constructor is written in place where it is +;;; called, so there is no function for two units to both define. (pub sum colour ((rgb ((r int) (g int) (b int))) (none ()))) ;;; A spec and a realization over the boundary. The written method diff --git a/tests/types.module.scm b/tests/types.module.scm index d31804e..7b0f366 100644 --- a/tests/types.module.scm +++ b/tests/types.module.scm @@ -11,6 +11,8 @@ add-sum! get-sum + add-constructor! + get-constructor variant-fields reset-declarations! diff --git a/types.module.scm b/types.module.scm index 0b42e8d..e2a67c5 100644 --- a/types.module.scm +++ b/types.module.scm @@ -11,6 +11,8 @@ add-sum! get-sum + add-constructor! + get-constructor variant-fields reset-declarations! diff --git a/types.scm b/types.scm index 25166f2..20c150c 100644 --- a/types.scm +++ b/types.scm @@ -105,6 +105,15 @@ (define (get-sum name) (hash-table-ref/default +sum-db+ (type-key name) #f)) +;;; shape/circle -> (shape . circle), for each variant of each sum +(define +constructor-db+ (make-hash-table)) + +(define (add-constructor! constructor sum variant) + (hash-table-set! +constructor-db+ constructor (cons sum variant))) + +(define (get-constructor name) + (hash-table-ref/default +constructor-db+ name #f)) + (define (variant-fields variants name) (let ((entry (assq name variants))) (and entry (cdr entry)))) @@ -141,6 +150,7 @@ ;;; that compiles two units has to start the second one clean. (define (reset-declarations!) (set! +sum-db+ (make-hash-table)) + (set! +constructor-db+ (make-hash-table)) (set! +ops-db+ (make-hash-table)) (set! +spec-db+ (make-hash-table)) (set! +realize-db+ (make-hash-table))) -- 2.52.0 From 9c5f678830d8f7f3904db6b62027721dfd00eac5 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 17:14:36 +0300 Subject: [PATCH 27/40] hand an array field its elements An array field compiled to C that cc refused: an array is neither an initializer of another nor something a payload literal can be built from. Both the constructor and the binder now spell it out element by element, which needs a length sexc can count. A sum holding itself by value is refused at the declaration rather than as cc's incomplete type. --- semen.scm | 86 ++++++++++++++++++++++++++++++++++--- tests/encapsulation.scm | 29 +++++++++++++ tests/sex-programs/sums.sex | 29 ++++++++++--- 3 files changed, 134 insertions(+), 10 deletions(-) diff --git a/semen.scm b/semen.scm index e7c2ab3..87423d7 100644 --- a/semen.scm +++ b/semen.scm @@ -697,10 +697,55 @@ (unless (= (length fields) (length args)) (sex-error form "variant takes this many fields" tag (length fields))) (sum-literal name tag - (map (lambda (field arg) - (convert-to-closure (second field) arg env form)) + (map (lambda (field arg) (field-argument field arg env form)) fields args)))) +;;; An array field cannot be handed an array, C copying neither, so it +;;; is handed the array's elements: +;;; +;;; (shape/row #(1 2 3 4)) -> ...(struct shapeːrow){{1, 2, 3, 4}} +;;; (shape/row a) -> ...(struct shapeːrow){{a[0], a[1], a[2], a[3]}} +(define (field-argument field arg env form) + (let ((type (second field))) + (if (not (array-form? type)) + (convert-to-closure type arg env form) + (let ((given (expression-type arg env))) + (cond + ((brace-initializer? arg) arg) + ((not (array-form? given)) + (sex-error form "an array field takes an array" (first field))) + ((not (eqv? (array-length given) (array-length type))) + (sex-error form "array is not as long as its field" (first field))) + ;; `#([int 4] : 1 2 3 4)' is its own elements + ((vector? arg) (list->vector (cdr (memq ': (vector->list arg))))) + ((not (simple-path? arg)) + (sex-error form "an array is read once per element; bind it to a var first" + (first field))) + (else (spell-out-array type arg))))))) + +(define (array-form? type) + (and (pair? type) (eq? '¤ (car type)))) + +;;; [int 4] -> 4, and [int N] -> 4 after (define N 4); #f for a length +;;; nothing here can count +(define (array-length type) + (and (array-bound? type) + (let ((bound (last type))) + (cond ((and (integer? bound) (exact? bound)) bound) + ((symbol? bound) + (let ((info (get-type-info bound))) + (and info (eq? 'define (car info)) + (let ((value (caddr info))) + (and (= 1 (length value)) + (integer? (car value)) + (exact? (car value)) + (car value)))))) + (else #f))))) + +;;; xs : [int 2] -> #((¤ xs 0) (¤ xs 1)) +(define (spell-out-array type expr) + (list->vector (map (lambda (i) `(¤ ,expr ,i)) (iota (array-length type))))) + ;;; The forms a macro call stands for, with `(type-of x)' answered from ;;; ENV (define (expand-call form env) @@ -867,6 +912,9 @@ (else (case (car expr) ((dot-access %->) (simple-path? (second expr))) ((*) (and (= 2 (length expr)) (simple-path? (second expr)))) + ((¤) (and (= 3 (length expr)) + (simple-path? (second expr)) + (or (symbol? (third expr)) (number? (third expr))))) (else #f))))) (define (match-arm-variant arm) (and (pair? (car arm)) (car (car arm)))) @@ -916,13 +964,18 @@ ,@(cdr arm)))))) arms))) +;;; A binder is a copy of its field, an array one included: +;;; +;;; (var xs [int 2] #((¤ s.u.row.xs 0) (¤ s.u.row.xs 1))) (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))))) + (let ((type (second field)) + (path `(dot-access (dot-access (dot-access ,scrutinee u) ,variant) + ,(first field)))) + `(var ,binder ,type + ,(if (array-form? type) (spell-out-array type path) path))))) binders fields)) ;;; (.length v) is a call to vec2ːlength; (. v length) is the field @@ -1648,6 +1701,10 @@ (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))) + (for-each (lambda (v) + (for-each (lambda (field) (check-variant-field form name field)) + (cdr v))) + variants) (let* ((names (map car variants)) (twice (find (lambda (v) (> (count (cut eq? <> v) names) 1)) names))) (when twice @@ -1666,6 +1723,25 @@ (sex-error form "a variant is (name (fields ...))" v)) (cons (car v) (normalize-fields (cadr v)))) +;;; (sum expr ((neg ((e expr))))) has no size; (neg ((e (* expr)))) does. +;;; An array field is spelled out element by element wherever it is +;;; copied, so its length has to be one sexc can count. +(define (check-variant-field form name field) + (let ((type (second field))) + (when (holds-by-value? type name) + (sex-error form "a sum holds itself through a pointer" (first field))) + (when (and (array-form? type) (not (array-length type))) + (sex-error form "array field needs a length written as a number" + (first field))))) + +(define (holds-by-value? type name) + (cond ((eq? type name) #t) + ((not (pair? type)) #f) + ((memq (car type) '(struct const volatile)) + (and (pair? (cdr type)) (holds-by-value? (cadr type) name))) + ((array-form? type) (holds-by-value? (array-element-type type) name)) + (else #f))) + (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 diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 6a2c5a9..3243911 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -216,6 +216,35 @@ (test-assert "and is not a function value" (reports? "(sum t ((a ((x int)))))(fn f () void (var g (fn ((x int)) t) t/a))" "a constructor is not a function")) + (test-assert "an array field takes a brace literal as it is" + (emits? "(sum t ((a ((xs [int 2])))))(fn f () t (return (t/a #(1 2))))" + "(struct tːa){{1, 2}}")) + (test-assert "and an array by its elements" + (emits? "(sum t ((a ((xs [int 2])))))(fn f () t (var v [int 2] #(1 2)) (return (t/a v)))" + "(struct tːa){{v[0], v[1]}}")) + (test-assert "which have to be countable" + (reports? "(fn n () int (return 2))(sum t ((a ((xs [int (n)])))))" + "array field needs a length")) + (test-assert "and as many as the field holds" + (reports? "(sum t ((a ((xs [int 2])))))(fn f () t (var v [int 3] #(1 2 3)) (return (t/a v)))" + "array is not as long as its field")) + (test-assert "an array field takes an array" + (reports? "(sum t ((a ((xs [int 2])))))(fn f () t (var p (* int) 0) (return (t/a p)))" + "an array field takes an array")) + (test-assert "read from a path, not from a call" + (reports? (string-append "(sum t ((a ((xs [int 2])))))(fn g () int (return 0))" + "(fn f () t (var m [t 2]) (return (t/a (. [m (g)] u a xs))))") + "bind it to a var first")) + (test-assert "an array binder is a copy of each element" + (emits? (string-append "(sum t ((a ((xs [int 2])))))" + "(fn f ((s t)) int (match s ((a (xs)) (return [xs 0]))))") + "int xs[2] = {s.u.a.xs[0], s.u.a.xs[1]}")) + (test-assert "a sum cannot hold itself" + (reports? "(sum box ((inner ((x box)))))" "a sum holds itself through a pointer")) + (test-assert "nor an array of itself" + (reports? "(sum box ((inner ((x [box 2])))))" "a sum holds itself through a pointer")) + (test-assert "though it can point at itself" + (emits? "(sum box ((inner ((x (* box))))))" "box * x;")) (test-assert "a function argument becomes the closure its field holds" (emits? (string-append "(fn g ((n int)) int (return n))" diff --git a/tests/sex-programs/sums.sex b/tests/sex-programs/sums.sex index bb3cc2a..5eb49db 100644 --- a/tests/sex-programs/sums.sex +++ b/tests/sex-programs/sums.sex @@ -2,14 +2,15 @@ (output "3.14 12.00 0.00" "held once: a 1" "nested: -(2 + 3) = -5" - "tagged only: 1") + "tagged only: 1" + "rows: 18 5") (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. +;;; fields, and the record holding both; a constructor is the value +;;; itself, written in place. 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) @@ -52,6 +53,12 @@ (sum held ((a ((x int) (y int))) (b ()))) (fn mk-held () held (return (held/a 1 2))) +;;; An array field is handed elements, never an array: C copies neither +;;; into a parameter nor into another array, so both the constructor +;;; and the binder spell it out +(define N 4) +(sum row ((cells ((xs [int N]))) (none ()))) + (pub fn main () int (printf "%.2f %.2f %.2f\n" (area (mk-shape)) @@ -75,4 +82,16 @@ (match l ((red ()) (printf "tagged only: 0\n")) ((green ()) (printf "tagged only: 1\n"))) + + (var a [int N] #(5 6 7 8)) + (var rows [row 2] #((row/cells a) (row/cells #(1 2 3 4)))) + (= [a 0] 50) ; the row holds a copy + (var sum int 0) + (for (var i int 0) (< i 2) (++ i) + (match [rows i] + ((cells (xs)) + (= [xs 0] 100) ; and so does the binder + (+= sum (+ [xs 1] [xs 2]))) + ((none ()) (+= sum 0)))) + (printf "rows: %d %d\n" sum (. [rows 0] u cells [xs 0])) (return 0)) -- 2.52.0 From b51cda0af36ea32b29e608fc56171832e570a3e1 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 17:27:52 +0300 Subject: [PATCH 28/40] highlight ops and match --- sex-mode.el | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sex-mode.el b/sex-mode.el index 733ba73..3531666 100644 --- a/sex-mode.el +++ b/sex-mode.el @@ -38,6 +38,7 @@ All commands in `lisp-mode-shared-map' are inherited by this map.") "import" "include" "fn" + "ops" "pub" "record" "realize" @@ -62,6 +63,7 @@ All commands in `lisp-mode-shared-map' are inherited by this map.") "if" "for" "goto" + "match" "return" "switch" "var" -- 2.52.0 From 0a565046af130ce87ceaefe4fb6d0df8df705314 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 17:27:52 +0300 Subject: [PATCH 29/40] say that a binder is a copy, and where %-> is A match binder looks like a reference to its field and is not one. And with `.' reading an untyped receiver as a value, nothing said how to write the arrow by hand. --- Readme.org | 3 ++- tests/sex-programs/worked-example.sex | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.org b/Readme.org index 1e35308..d3e2270 100644 --- a/Readme.org +++ b/Readme.org @@ -150,7 +150,8 @@ may be both: #+end_src A receiver whose type cannot be worked out --- something out of a header -nothing has parsed --- is read as a value, with a warning saying so. +nothing has parsed --- is read as a value, with a warning saying so. For a +pointer there, ~(%-> p x)~ writes ~p->x~ whatever ~p~ is. A method is ~(.name receiver args ...)~ and a field is ~(. receiver name)~, so the shape of a form says which of the two it is without diff --git a/tests/sex-programs/worked-example.sex b/tests/sex-programs/worked-example.sex index 8195647..4ecc184 100644 --- a/tests/sex-programs/worked-example.sex +++ b/tests/sex-programs/worked-example.sex @@ -16,6 +16,7 @@ (ops expr (pub fn eval ((self (* const expr))) float + ;; v, e, l and r are copies of the fields, not references to them (match (* self) ((lit (v)) (return v)) ((neg (e)) (return (- (.eval e)))) -- 2.52.0 From 0a5eb1e0ce853a227266a24bfd2fbeb421e703d9 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Thu, 15 Oct 2026 11:15:19 +0300 Subject: [PATCH 30/40] refuse a match in a control form's test An if, while or for walked every slot as a statement, so a match in its test came out as a switch inside the condition, which cc refuses. --- semen.scm | 33 ++++++++++++++++++++++++++++++--- tests/encapsulation.scm | 14 ++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/semen.scm b/semen.scm index 87423d7..8902d0c 100644 --- a/semen.scm +++ b/semen.scm @@ -546,8 +546,9 @@ ;;; ;;; (var n int (match s ...)) -> int n = switch (s.tag) { ... ;;; -;;; A condition is not tracked: `walk-parts' takes every slot of an `if' -;;; alike. +;;; and in a control form's test, which C reads as an expression too: +;;; +;;; (if (match s ...) ...) -> if (switch (s.tag) { ... (define operand-position? (make-parameter #f)) (define (walk-operand form env) @@ -583,10 +584,13 @@ (cons walk-embed-result (walk-body expansion env))))) (else (case (car form) - ((do for while if switch) + ((do) (parameterize ((operand-position? #f)) (with-scope env (lambda () (walk-parts form env))))) + ((for while if switch) + (with-scope env (lambda () (walk-control form env)))) + ((case case/fallthrough default) (parameterize ((operand-position? #f)) (walk-parts form env))) @@ -874,6 +878,29 @@ (define (walk-parts form env) (copy-form-source! form (walk-body form env))) +;;; A control form, its tests walked as values and the rest as +;;; statements +(define (walk-control form env) + (let ((slots (count (lambda (part) (not (comment-form? part))) (cdr form)))) + (let loop ((parts (cdr form)) (i 0) (acc (list (car form)))) + (cond + ((null? parts) (copy-form-source! form (reverse acc))) + ((comment-form? (car parts)) (loop (cdr parts) i (cons (car parts) acc))) + (else + (let ((walked (parameterize ((operand-position? + (test-slot? (car form) i slots))) + (walk-body (list (car parts)) env)))) + (loop (cdr parts) (+ i 1) (append-reverse walked acc)))))))) + +;;; Whether the Ith of a control form's SLOTS is read as a value: an +;;; `if''s tests but not its trailing else, a `for''s header, the +;;; scrutinee of a `while' or a `switch' +(define (test-slot? head i slots) + (case head + ((if) (and (even? i) (< (+ i 1) slots))) + ((for) (< i 3)) + (else (= i 0)))) + ;;; (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 diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 3243911..58c8498 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -432,6 +432,20 @@ (test-assert "not even as an argument" (reports? (sum-src "(= out (match s ((circle (r)) r) (else 0.0)))") "match is a statement")) + (test-assert "nor as an if's test" + (reports? (sum-src "(if (match s ((circle (r)) 1) (else 0)) (= out 1.0))") + "match is a statement")) + (test-assert "nor as a while's" + (reports? (sum-src "(while (match s ((circle (r)) 1) (else 0)) (= out 1.0))") + "match is a statement")) + (test-assert "nor in a for's header" + (reports? (sum-src "(for (var i int 0) (match s ((circle (r)) 1) (else 0)) (++ i)" + " (= out 1.0))") + "match is a statement")) + (test-assert "but an if's branches are statements, the else among them" + (emits? (sum-src "(if (== out 0.0) (match s ((circle (r)) (= out r)) (else (= out 1.0)))" + " (match s ((circle (r)) (= out 2.0)) (else (= out 3.0))))") + "out = 3.0;")) (test-assert "but a case body is a statement" (emits? (sum-src "(switch 1 (case 1 (match s ((circle (r)) (= out r))" " (else (= out 0.0)))))") -- 2.52.0 From 6cda0873c601136263dce3a6fe1255e524547e30 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Thu, 15 Oct 2026 11:15:57 +0300 Subject: [PATCH 31/40] hold a literal for an array field to the field's length A longer one reached cc as excess elements, and a shorter one filled the rest with zeros where a named array of that length was refused. --- semen.scm | 7 ++++++- tests/encapsulation.scm | 6 ++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/semen.scm b/semen.scm index 8902d0c..5d53e72 100644 --- a/semen.scm +++ b/semen.scm @@ -715,7 +715,12 @@ (convert-to-closure type arg env form) (let ((given (expression-type arg env))) (cond - ((brace-initializer? arg) arg) + ((brace-initializer? arg) + (let ((held (array-length type))) + (when (and held (not (= held (length (remove comment-form? + (vector->list arg)))))) + (sex-error form "array is not as long as its field" (first field)))) + arg) ((not (array-form? given)) (sex-error form "an array field takes an array" (first field))) ((not (eqv? (array-length given) (array-length type))) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 58c8498..95d553e 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -228,6 +228,12 @@ (test-assert "and as many as the field holds" (reports? "(sum t ((a ((xs [int 2])))))(fn f () t (var v [int 3] #(1 2 3)) (return (t/a v)))" "array is not as long as its field")) + (test-assert "and so must a literal" + (reports? "(sum t ((a ((xs [int 2])))))(fn f () t (return (t/a #(1 2 3))))" + "array is not as long as its field")) + (test-assert "not filling it with zeros either" + (reports? "(sum t ((a ((xs [int 2])))))(fn f () t (return (t/a #(1))))" + "array is not as long as its field")) (test-assert "an array field takes an array" (reports? "(sum t ((a ((xs [int 2])))))(fn f () t (var p (* int) 0) (return (t/a p)))" "an array field takes an array")) -- 2.52.0 From 913af0b4637a554edca14386aa178ea98c56ef1b Mon Sep 17 00:00:00 2001 From: alex-eg Date: Thu, 15 Oct 2026 11:20:53 +0300 Subject: [PATCH 32/40] start a global from braces, not a compound literal A compound literal is no constant in C11, so a global built by a constructor or a typed literal failed under -pedantic-errors; gcc says so, clang lets it pass. --- semen.scm | 14 +++++++++++++- tests/encapsulation.scm | 6 +++++- tests/sex-programs/c11.sex | 13 +++++++++---- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/semen.scm b/semen.scm index 5d53e72..c9b33c7 100644 --- a/semen.scm +++ b/semen.scm @@ -1878,7 +1878,8 @@ core (if (> (length core) 3) (append (take core 3) - (walk-operands core (drop core 3) env)) + (map bare-braces + (walk-operands core (drop core 3) env))) core)) env))) (form (if qualifier @@ -1888,6 +1889,17 @@ (add-name-type! (second core) (third core))) (cons form (append (hash-table-ref env :lambda-aux-code) acc)))) +;;; A compound literal is not a constant, though cc lets one pass at file +;;; scope unless asked to be pedantic; where it initializes, its braces +;;; alone say the same: +;;; +;;; (var g t (t/a 1)) -> static t g = {.tag = tǂa, .u = {.a = {1}}} +(define (bare-braces form) + (if (vector? form) + (let ((parts (list-split (vector->list form) ':))) + (list->vector (map bare-braces (last parts)))) + form)) + ;;; Utils (define (non-empty-list? form) (and (list? form) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 95d553e..3d5b577 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -203,7 +203,11 @@ (not (emits? "(pub sum t ((a ((x int)))))(fn f () t (return (t/a 1)))" "t tːa ("))) (test-assert "so it is a constant at file scope" - (emits? "(sum t ((a ((x int)))))(var g t (t/a 1))" "static t g = (t){")) + (emits? "(sum t ((a ((x int)))))(var g t (t/a 1))" + "static t g = {.tag = tǂa, .u = {.a = {1}}};")) + (test-assert "as is any literal a global starts from" + (emits? "(record point ((x int) (y int)))(var g point #(point : 1 2))" + "static point g = {1, 2};")) (test-assert "and an lvalue a method can take the address of" (emits? (string-append "(sum t ((a ((x int)))))" diff --git a/tests/sex-programs/c11.sex b/tests/sex-programs/c11.sex index 3d40462..174aca4 100644 --- a/tests/sex-programs/c11.sex +++ b/tests/sex-programs/c11.sex @@ -1,6 +1,6 @@ (compilation "-- -std=c11 -pedantic-errors") (input) -(output "c11: 42 43 6") +(output "c11: 42 43 6 4 6") (return 0) ;;; C11 is the floor, and this is the program that holds it there: the @@ -10,7 +10,8 @@ ;;; ;;; A capturing closure is the one that leans on C11 itself, through ;;; max_align_t in the environment and `_Static_assert' on its size; -;;; the record, the method and the match are here for what they emit. +;;; the record, the method and the match are here for what they emit, +;;; and the globals for initializers that have to be constants. (include stdio.h) @@ -22,6 +23,9 @@ (sum shape ((square ((side int))) (dot ()))) +(var corner point #(point : 2 3)) +(var unit shape (shape/square 1)) + (fn sides ((s shape)) int (var n int 0) (match s @@ -34,6 +38,7 @@ (var k int 1) (var add-k (closure ((int)) int) (closure ((v int)) int (k) (return (+ v k)))) - (printf "c11: %d %d %d\n" - (.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2)) + (printf "c11: %d %d %d %d %d\n" + (.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2) + (sides unit) (.area corner)) (return 0)) -- 2.52.0 From a0b323980fdec01cbbdb8e0957c4f3fb56c0357f Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 15:32:47 +0300 Subject: [PATCH 33/40] refuse a match in a case label case and case/fallthrough walked their label as a statement, so a match there was taken and wrote `case switch:'. --- semen.scm | 7 +++++-- tests/encapsulation.scm | 7 +++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/semen.scm b/semen.scm index c9b33c7..888445f 100644 --- a/semen.scm +++ b/semen.scm @@ -591,7 +591,10 @@ ((for while if switch) (with-scope env (lambda () (walk-control form env)))) - ((case case/fallthrough default) + ((case case/fallthrough) + (walk-control form env)) + + ((default) (parameterize ((operand-position? #f)) (walk-parts form env))) @@ -899,7 +902,7 @@ ;;; Whether the Ith of a control form's SLOTS is read as a value: an ;;; `if''s tests but not its trailing else, a `for''s header, the -;;; scrutinee of a `while' or a `switch' +;;; scrutinee of a `while' or a `switch', a `case''s label (define (test-slot? head i slots) (case head ((if) (and (even? i) (< (+ i 1) slots))) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 3d5b577..8df2b09 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -452,6 +452,13 @@ (reports? (sum-src "(for (var i int 0) (match s ((circle (r)) 1) (else 0)) (++ i)" " (= out 1.0))") "match is a statement")) + (test-assert "nor as a case label" + (reports? (sum-src "(switch 1 (case (match s ((circle (r)) 1) (else 0)) (= out 1.0)))") + "match is a statement")) + (test-assert "nor as a case/fallthrough's" + (reports? (sum-src "(switch 1 (case/fallthrough (match s ((circle (r)) 1) (else 0))" + " (= out 1.0)))") + "match is a statement")) (test-assert "but an if's branches are statements, the else among them" (emits? (sum-src "(if (== out 0.0) (match s ((circle (r)) (= out r)) (else (= out 1.0)))" " (match s ((circle (r)) (= out 2.0)) (else (= out 3.0))))") -- 2.52.0 From a885c21b9b65e980ff3e9a992a073af2f35912cc Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 15:33:37 +0300 Subject: [PATCH 34/40] infer a global's type before its braces lose theirs A global's initializer was stripped to plain braces before `_' was solved, so #(point : 2 3) left nothing to infer point from. --- semen.scm | 18 +++++++++--------- tests/sex-programs/c11.sex | 11 ++++++----- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/semen.scm b/semen.scm index 888445f..62aba86 100644 --- a/semen.scm +++ b/semen.scm @@ -1876,15 +1876,15 @@ ;; from (core (if (eq? 'extern qualifier) core - (resolve-wildcard - (copy-form-source! - core - (if (> (length core) 3) - (append (take core 3) - (map bare-braces - (walk-operands core (drop core 3) env))) - core)) - env))) + (let ((solved (resolve-wildcard + (copy-form-source! + core + (if (> (length core) 3) + (append (take core 3) + (walk-operands core (drop core 3) env)) + core)) + env))) + (copy-form-source! solved (map bare-braces solved))))) (form (if qualifier (copy-form-source! resolved (cons qualifier core)) core))) diff --git a/tests/sex-programs/c11.sex b/tests/sex-programs/c11.sex index 174aca4..375503d 100644 --- a/tests/sex-programs/c11.sex +++ b/tests/sex-programs/c11.sex @@ -1,6 +1,6 @@ (compilation "-- -std=c11 -pedantic-errors") (input) -(output "c11: 42 43 6 4 6") +(output "c11: 42 43 6 4 6 12") (return 0) ;;; C11 is the floor, and this is the program that holds it there: the @@ -23,8 +23,9 @@ (sum shape ((square ((side int))) (dot ()))) -(var corner point #(point : 2 3)) -(var unit shape (shape/square 1)) +(var corner _ #(point : 2 3)) +(var unit _ (shape/square 1)) +(var pair [_ 2] #(#(point : 1 2) #(point : 3 4))) (fn sides ((s shape)) int (var n int 0) @@ -38,7 +39,7 @@ (var k int 1) (var add-k (closure ((int)) int) (closure ((v int)) int (k) (return (+ v k)))) - (printf "c11: %d %d %d %d %d\n" + (printf "c11: %d %d %d %d %d %d\n" (.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2) - (sides unit) (.area corner)) + (sides unit) (.area corner) (.area [pair 1])) (return 0)) -- 2.52.0 From 063770d3bc3abf98629717d4bb04cc36111281de Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 15:33:51 +0300 Subject: [PATCH 35/40] document the standard library beside it, not in the readme --- Readme.org | 19 ++----------------- lib/threading-macros.org | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 17 deletions(-) create mode 100644 lib/threading-macros.org diff --git a/Readme.org b/Readme.org index d3e2270..251a2f6 100644 --- a/Readme.org +++ b/Readme.org @@ -176,24 +176,9 @@ same name wins over one of ours. ~sexc~ looks for them beside itself, so a work tree needs nothing set up; installed, ~$(bindir)/sexc~ finds them under ~$(prefix)/share/sex~. -There is one so far. +Each module is documented in a file of its own beside it: -*** threading-macros -~->~ passes a value through a chain of forms, each step taking what came -before it as its first argument, so the chain reads in the order it -happens instead of inside out. Clojure spells it this way and this is -the same thing: - -#+begin_src scheme -(import threading-macros) - -(-> 5 double-it (add 3) double-it) ; (double-it (add (double-it 5) 3)) -(-> lp (. a x)) ; lp->a->x -(-> q .length-sq) ; a method is a step like any other -#+end_src - -A step that is not a list is a call of one argument: ~(-> x f)~ is -~(f x)~. +- [[file:lib/threading-macros.org][threading-macros]] --- ~->~, threading a value through a chain of calls ** Read-time feature expressions Sex is able to use ~#+~ and ~#-~ for conditional compilation: the form that diff --git a/lib/threading-macros.org b/lib/threading-macros.org new file mode 100644 index 0000000..8bcb3b4 --- /dev/null +++ b/lib/threading-macros.org @@ -0,0 +1,16 @@ +* threading-macros +~->~ passes a value through a chain of forms, each step taking what came +before it as its first argument, so the chain reads in the order it +happens instead of inside out. Clojure spells it this way and this is +the same thing: + +#+begin_src scheme +(import threading-macros) + +(-> 5 double-it (add 3) double-it) ; (double-it (add (double-it 5) 3)) +(-> lp (. a x)) ; lp->a->x +(-> q .length-sq) ; a method is a step like any other +#+end_src + +A step that is not a list is a call of one argument: ~(-> x f)~ is +~(f x)~. -- 2.52.0 From 958978efd36a65ffa279349b9ae8317ce8f84a5e Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 15:33:51 +0300 Subject: [PATCH 36/40] keep the threading macro out of the writer's arrow comment --- fmt-c-writer.scm | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 0ded714..35be150 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -191,8 +191,7 @@ forms, and what remains." ;; is the fmt-c directive for the `.' operator (see sex-fmt-c). (('dot-access . rest) (cons '%. (map walk-expr rest))) ;; `%->' is the C arrow. Nothing writes it: it is what a member - ;; path lowers to where the thing it reads from is a pointer, the - ;; name `->' itself being the threading macro + ;; path lowers to where the thing it reads from is a pointer (('%-> . rest) (cons '%-> (map walk-expr rest))) (('var . _) (walk-var form)) ;; An expression has no room for a statement, so a comment in a -- 2.52.0 From 8f7b26eafab5a2c3b3ff94bce25da065aa8a64d1 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 15:34:10 +0300 Subject: [PATCH 37/40] name the encapsulation test after what it covers --- Makefile | 4 ++-- tests/sex-programs/{worked-example.sex => encapsulation.sex} | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) rename tests/sex-programs/{worked-example.sex => encapsulation.sex} (85%) diff --git a/Makefile b/Makefile index 8e40f4d..2ba0f4c 100644 --- a/Makefile +++ b/Makefile @@ -109,6 +109,7 @@ SEX_TEST_PROGRAMS = c11 \ closures \ comments \ compound-literals \ + encapsulation \ feature-flags \ features \ fixpoint \ @@ -126,8 +127,7 @@ SEX_TEST_PROGRAMS = c11 \ type-shapes \ unicode \ unnamed-params \ - wildcards \ - worked-example + wildcards # Multi-module linking is checked end to end; see tests/modules/Makefile. check-modules: sexc diff --git a/tests/sex-programs/worked-example.sex b/tests/sex-programs/encapsulation.sex similarity index 85% rename from tests/sex-programs/worked-example.sex rename to tests/sex-programs/encapsulation.sex index 4ecc184..4a4308d 100644 --- a/tests/sex-programs/worked-example.sex +++ b/tests/sex-programs/encapsulation.sex @@ -3,9 +3,8 @@ "-5") (return 0) -;;; The worked example from Encapsulation.org, kept here so it stays -;;; true: a recursive sum, an inherent method on it, and a spec -;;; realized for it, which is every layer that is built at once. +;;; A recursive sum, an inherent method on it, and a spec realized for +;;; it: every layer of encapsulation in one program, built at once. (include stdio.h) -- 2.52.0 From b5030e3824418d2e9d78d779feb8998942fdf662 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 15:34:20 +0300 Subject: [PATCH 38/40] say what the threading test checks, not how -> came free --- tests/sex-programs/threading.sex | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/tests/sex-programs/threading.sex b/tests/sex-programs/threading.sex index 2082caa..7cd2cb7 100644 --- a/tests/sex-programs/threading.sex +++ b/tests/sex-programs/threading.sex @@ -6,14 +6,8 @@ "one step is just the value: 7") (return 0) -;;; `->' used to be C's arrow. The arrow is what `.' writes now when -;;; the thing it reads from is a pointer, which left the name free for -;;; threading -- the first module of the standard library. -;;; -;;; What this pins is that a step may be a call, a bare name or a -;;; method, that the value is threaded into the *first* argument, and -;;; that the compiler's own generated arrows survived the rename -- -;;; `ops' below lifts a method, which is where the captures live. +;;; A step may be a call, a bare name, a member path or a method, and +;;; the value goes in as its first argument. (include stdio.h) (import threading-macros) -- 2.52.0 From 5f130f4f32ded59cf8eddd5cdb36e85679b3f8c0 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 15:35:26 +0300 Subject: [PATCH 39/40] order types.scm by what each part reads The lookups came after the tables built on them, type-key after the sums filed under it, and reset-declarations! before +ops-db+. --- types.scm | 233 +++++++++++++++++++++++++++--------------------------- 1 file changed, 117 insertions(+), 116 deletions(-) diff --git a/types.scm b/types.scm index 20c150c..78a183c 100644 --- a/types.scm +++ b/types.scm @@ -90,122 +90,6 @@ (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+ (type-key name) variants)) - -(define (get-sum name) - (hash-table-ref/default +sum-db+ (type-key name) #f)) - -;;; shape/circle -> (shape . circle), for each variant of each sum -(define +constructor-db+ (make-hash-table)) - -(define (add-constructor! constructor sum variant) - (hash-table-set! +constructor-db+ constructor (cons sum variant))) - -(define (get-constructor name) - (hash-table-ref/default +constructor-db+ name #f)) - -(define (variant-fields variants name) - (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-key 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-key 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! +constructor-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. -;;; -;;; (ops vec2 (fn length ((self (* const vec2))) float ...)) -;;; -> (vec2 . length) -> vec2/length -;;; -;;; The signature is not kept here; `vec2/length' is an ordinary -;;; function by the time anything asks, so +name-db+ already has it. -(define +ops-db+ (make-hash-table)) - -(define (add-method! type method qualified) - (hash-table-set! +ops-db+ (cons (type-key type) method) qualified)) - -(define (get-method type method) - (hash-table-ref/default +ops-db+ (cons (type-key type) method) #f)) - -;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength -(define (qualify-op type name) - (string->symbol - (string-append (symbol->string type) "/" (symbol->string name)))) - -;;; The name an `ops' block was written against: `(struct point)' and a -;;; `const' wrapper both name `point', and anything else names nothing. -(define (ops-key type) - (cond ((symbol? type) (type-key type)) - ((not (and (pair? type) (symbol? (car type)))) #f) - ((memq (car type) '(struct union enum)) - (and (pair? (cdr type)) (symbol? (cadr type)) (cadr type))) - ((memq (car type) '(const volatile)) (ops-key (cadr type))) - (else #f))) - -;;; The name methods, realizations and sums are filed under. A typedef -;;; is followed to the aggregate it names, and one that ends in anything -;;; else stops at the last typedef, so a scalar does not share them: -;;; -;;; (record v ...) (typedef alias v) alias -> v -;;; (typedef meters float) meters -> meters -;;; (typedef km meters) km -> meters -(define (type-key name) - (let follow ((name name) (seen (list))) - (let ((target (and (not (memq name seen)) (typedef-target name)))) - (cond ((not target) name) - ((symbol? target) - (if (typedef-target target) (follow target (cons name seen)) name)) - ((target-tag target)) - (else name))))) - -(define (typedef-target name) - (let ((info (and (symbol? name) (get-type-info name)))) - (and info (eq? (car info) 'typedef) (caddr info)))) - (define (add-name-type! name type) (hash-table-set! +name-db+ name type)) @@ -287,6 +171,123 @@ (and tag (or (get-tag-info tag) (get-type-info tag)))) info)))) +;;; The name methods, realizations and sums are filed under. A typedef +;;; is followed to the aggregate it names, and one that ends in anything +;;; else stops at the last typedef, so a scalar does not share them: +;;; +;;; (record v ...) (typedef alias v) alias -> v +;;; (typedef meters float) meters -> meters +;;; (typedef km meters) km -> meters +(define (type-key name) + (let follow ((name name) (seen (list))) + (let ((target (and (not (memq name seen)) (typedef-target name)))) + (cond ((not target) name) + ((symbol? target) + (if (typedef-target target) (follow target (cons name seen)) name)) + ((target-tag target)) + (else name))))) + +(define (typedef-target name) + (let ((info (and (symbol? name) (get-type-info name)))) + (and info (eq? (car info) 'typedef) (caddr info)))) + +;;; 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+ (type-key name) variants)) + +(define (get-sum name) + (hash-table-ref/default +sum-db+ (type-key name) #f)) + +;;; shape/circle -> (shape . circle), for each variant of each sum +(define +constructor-db+ (make-hash-table)) + +(define (add-constructor! constructor sum variant) + (hash-table-set! +constructor-db+ constructor (cons sum variant))) + +(define (get-constructor name) + (hash-table-ref/default +constructor-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. +;;; +;;; (ops vec2 (fn length ((self (* const vec2))) float ...)) +;;; -> (vec2 . length) -> vec2/length +;;; +;;; The signature is not kept here; `vec2/length' is an ordinary +;;; function by the time anything asks, so +name-db+ already has it. +(define +ops-db+ (make-hash-table)) + +(define (add-method! type method qualified) + (hash-table-set! +ops-db+ (cons (type-key type) method) qualified)) + +(define (get-method type method) + (hash-table-ref/default +ops-db+ (cons (type-key type) method) #f)) + +;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength +(define (qualify-op type name) + (string->symbol + (string-append (symbol->string type) "/" (symbol->string name)))) + +;;; The name an `ops' block was written against: `(struct point)' and a +;;; `const' wrapper both name `point', and anything else names nothing. +(define (ops-key type) + (cond ((symbol? type) (type-key type)) + ((not (and (pair? type) (symbol? (car type)))) #f) + ((memq (car type) '(struct union enum)) + (and (pair? (cdr type)) (symbol? (cadr type)) (cadr type))) + ((memq (car type) '(const volatile)) (ops-key (cadr type))) + (else #f))) + +;;; 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-key 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-key type)))) + +;;; Sums, constructors, methods and specs 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! +constructor-db+ (make-hash-table)) + (set! +ops-db+ (make-hash-table)) + (set! +spec-db+ (make-hash-table)) + (set! +realize-db+ (make-hash-table))) + ;;; Type matcher macro ;;; (type-match type ;;; (int ...) -- 2.52.0 From db5507b18006bbb867eeab8a24103e90e26af5fb Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 15:35:34 +0300 Subject: [PATCH 40/40] give a record's docstring a line of its own --- tests/sex-programs/records.sex | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/sex-programs/records.sex b/tests/sex-programs/records.sex index c99050c..0477e97 100644 --- a/tests/sex-programs/records.sex +++ b/tests/sex-programs/records.sex @@ -12,7 +12,8 @@ (record point ((x int) (y int))) -(record named "Fields of more than one kind, and a docstring." +(record named + "Fields of more than one kind, and a docstring." ((id int) (first-name (* const char)))) (struct raw ((a int) (b int))) -- 2.52.0