From 00efbc5442da08838b0c402e10338df73f62aeb5 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 13:53:49 +0300 Subject: [PATCH 01/74] read a match scrutinee before a binder can shadow it C has a declaration in scope from its own initializer, so in (match (* e) ((neg (e)) ...)) the binding read the new, uninitialized e. A binder named like a part of the scrutinee now has it held in a local. --- semen.scm | 14 +++++++++++--- tests/encapsulation.scm | 3 +++ tests/sex-programs/sums.sex | 10 ++++++++++ 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/semen.scm b/semen.scm index 429f623..b1c8be0 100644 --- a/semen.scm +++ b/semen.scm @@ -955,16 +955,24 @@ (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) + ;; the scrutinee is read once per binding, so anything that could + ;; read differently the second time is read into a local first -- + ;; a binder named like a part of it included, since C has a binder + ;; in scope from its own initializer on + (if (and (simple-path? scrutinee) + (not (any (cut mentions? scrutinee <>) (match-binders arms)))) (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 (match-binders arms) + (append-map (lambda (arm) + (if (eq? (car arm) 'else) '() (delete '_ (second (car arm))))) + arms)) + (define (make-match-name fn-name counter) (string->symbol (string-append "ƛm" (number->string counter)))) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 6dcc47a..d7bd86c 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -416,6 +416,9 @@ ahead of its pub forms." (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 "unless a binder is named like a part of it" + (emits? (sum-src "(match s ((circle (s)) (= out s)) (else (= out 0.0)))") + "shape ƛm0 = s")) (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))" diff --git a/tests/sex-programs/sums.sex b/tests/sex-programs/sums.sex index 5eb49db..3ad2b1c 100644 --- a/tests/sex-programs/sums.sex +++ b/tests/sex-programs/sums.sex @@ -2,6 +2,7 @@ (output "3.14 12.00 0.00" "held once: a 1" "nested: -(2 + 3) = -5" + "size: 4" "tagged only: 1" "rows: 18 5") (return 0) @@ -45,6 +46,14 @@ ((neg (e)) (printf "-") (show e)) ((add (l r)) (printf "(") (show l) (printf " + ") (show r) (printf ")")))) +;;; A binder may take the name the scrutinee is spelled with, and a +;;; later binder still reads the scrutinee, not the earlier binder +(fn size ((e (* const expr))) int + (match (* e) + ((lit (v)) (return 1)) + ((neg (e)) (return (+ 1 (size e)))) + ((add (e r)) (return (+ 1 (size e) (size r)))))) + ;;; No fields anywhere: the record is the tag alone, with no union (sum light ((red ()) (green ()))) @@ -77,6 +86,7 @@ (printf "nested: ") (show (& e)) (printf " = %g\n" (eval (& e))) + (printf "size: %d\n" (size (& e))) (var l light (light/green)) (match l -- 2.52.0 From 6d845536522ffe8a83fd316116494410faca4685 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 13:54:17 +0300 Subject: [PATCH 02/74] lower match to an if chain, so break in an arm leaves the loop The switch it lowered to took a break in an arm for its own, and the loop around the match went on. With no else the last arm is the chain's else, which keeps C from warning that a function may return nothing. --- semen.scm | 48 +++++++++++++++++++++++++------------ tests/encapsulation.scm | 30 +++++++++++++---------- tests/sex-programs/sums.sex | 12 ++++++++++ 3 files changed, 63 insertions(+), 27 deletions(-) diff --git a/semen.scm b/semen.scm index b1c8be0..38cb9df 100644 --- a/semen.scm +++ b/semen.scm @@ -938,7 +938,7 @@ ((for) (< i 3)) (else (= i 0)))) -;;; (match s ((circle (r)) ...) ((empty ()) ...)) is a switch over the +;;; (match s ((circle (r)) ...) ((empty ()) ...)) is an if 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: @@ -961,11 +961,11 @@ ;; in scope from its own initializer on (if (and (simple-path? scrutinee) (not (any (cut mentions? scrutinee <>) (match-binders arms)))) - (walk-statement (match-switch name scrutinee variants arms) env) + (walk-statement (match-branches name scrutinee variants arms) env) (let ((held (aux-name! env make-match-name))) (walk-statement `(do (var ,held ,type ,scrutinee) - ,(match-switch name held variants arms)) + ,(match-branches name held variants arms)) env))))) (define (match-binders arms) @@ -1023,18 +1023,36 @@ (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))) +;;; Not a switch, which would take a `break' in an arm for its own: +;;; there is none in the source, so the break is the loop's. With no +;;; else the arms cover every variant, so the last needs no test -- and +;;; C, seeing every path end, does not warn of one returning nothing +;;; +;;; (if (== s.tag shapeǂcircle) (do (var r float s.u.circle.r) ...) +;;; (== s.tag shapeǂrect) (do ...) +;;; (do ...)) ; the else, or else empty's arm +(define (match-branches name scrutinee variants arms) + (let-values (((otherwise named) (partition (lambda (arm) (eq? (car arm) 'else)) + arms))) + (let* ((body (lambda (arm) + (if (eq? (car arm) 'else) + `(do ,@(cdr arm)) + (let ((variant (match-arm-variant arm))) + `(do ,@(match-bindings scrutinee variant (second (car arm)) + (variant-fields variants variant)) + ,@(cdr arm)))))) + (ordered (append named otherwise)) + (tested (drop-right ordered 1)) + (final (body (last ordered)))) + (if (null? tested) + final + `(if ,@(append-map + (lambda (arm) + (list `(== (dot-access ,scrutinee tag) + ,(sum-tag-constant name (match-arm-variant arm))) + (body arm))) + tested) + ,final))))) ;;; A binder is a copy of its field, an array one included: ;;; diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index d7bd86c..bff967c 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -394,13 +394,17 @@ ahead of its pub forms." "(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 + ;; match is an if 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" + (test-assert "it tests the tag" (emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))" " ((empty ()) (= out 0.0)))") - "switch (s.tag)")) + "if (s.tag == shapeǂcircle)")) + (test-assert "but not for the last variant, which is all that is left" + (not (emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))" + " ((empty ()) (= out 0.0)))") + "s.tag == shapeǂempty"))) (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)))") @@ -430,13 +434,15 @@ ahead of its pub forms." "(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:")) + "s.tag == shapeǂcircle")) + (test-assert "else is the last branch, wherever it is written" + (let ((c (silently + (lambda () + (sex->c (sum-src "(match s (else (= out 2.0)) ((circle (r)) (= out r)))")))))) + (< (string-contains c "out = r") (string-contains c "out = 2.0")))) (test-assert "a comment between arms is dropped" - (emits? (sum-src "(match s ((circle (r)) (= out r)) ;; gone\n (else (= out 0.0)))") - "default:")) + (emits? (sum-src "(match s ((circle (r)) (= out r)) ;; gone\n (else (= out 2.0)))") + "out = 2.0")) (test-assert "a variant left out is an error" (reports? (sum-src "(match s ((circle (r)) (= out r)))") @@ -445,7 +451,7 @@ ahead of its pub forms." (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)")) + "s.tag == shapeǂcircle")) (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)))") @@ -493,11 +499,11 @@ ahead of its pub forms." (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)")) + "s.tag == shapeǂcircle")) (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)")) + "t.tag == shapeǂcircle")) (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/sex-programs/sums.sex b/tests/sex-programs/sums.sex index 3ad2b1c..ca1dbc7 100644 --- a/tests/sex-programs/sums.sex +++ b/tests/sex-programs/sums.sex @@ -4,6 +4,7 @@ "nested: -(2 + 3) = -5" "size: 4" "tagged only: 1" + "broke out after 2" "rows: 18 5") (return 0) @@ -93,6 +94,17 @@ ((red ()) (printf "tagged only: 0\n")) ((green ()) (printf "tagged only: 1\n"))) + ;; there is no switch in the source, so `break' in an arm leaves the + ;; loop around the match; one in a loop of the arm's own leaves that + (var lights [light 3] #((light/green) (light/red) (light/green))) + (var seen int 0) + (for (var i int 0) (< i 3) (++ i) + (++ seen) + (match [lights i] + ((red ()) (while true (break)) (break)) + ((green ()) (continue)))) + (printf "broke out after %d\n" seen) + (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 -- 2.52.0 From 5cd931cb4e0ce5ff84827e276f22692614efaf12 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 13:54:41 +0300 Subject: [PATCH 03/74] promote the prelude's integer types like C's own u8 and i32 are typedefs of names nothing parses, so they had no rank: (+ a a) over two u8 200s was a u8 holding 144, and (+ n 1) over an i32 could not be typed at all. --- tests/sex-programs/wildcards.sex | 9 +++++++++ tests/types.scm | 9 ++++++--- types.scm | 10 ++++++++++ 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/tests/sex-programs/wildcards.sex b/tests/sex-programs/wildcards.sex index 558a6d5..eaeea12 100644 --- a/tests/sex-programs/wildcards.sex +++ b/tests/sex-programs/wildcards.sex @@ -11,6 +11,7 @@ "partial: 1 2.5" "joined: 43.5 84 49 1" "promoted: 200 60000 3705032704" + "prelude: 400 6" "from elements: 4 9 0") (return 0) @@ -105,6 +106,14 @@ (var unpromoted _ (+ kept kept)) (printf "promoted: %d %d %u\n" narrow narrower unpromoted) + ;; the prelude's widths are C's own types under other names, and + ;; promote the way those do + (var b8 u8 200) + (var w32 i32 5) + (var bytes _ (+ b8 b8)) + (var next _ (+ w32 1)) + (printf "prelude: %d %d\n" bytes next) + ;; a brace initializer has no type of its own, but its elements solve ;; the hole in the array type around it -- and the length stays as ;; written, whether or not every slot is initialized diff --git a/tests/types.scm b/tests/types.scm index 144e770..74e9876 100644 --- a/tests/types.scm +++ b/tests/types.scm @@ -42,14 +42,17 @@ #f (get-fields 't-color)) - (add-typedef 't-u8 '(typedef t-u8 uint8-t)) + (add-typedef 't-u8 '(typedef t-u8 gl-ubyte)) (test "a typedef resolves to its target" - 'uint8-t + 'gl-ubyte (get-underlying-type 't-u8)) (add-typedef 't-byte '(typedef t-byte t-u8)) (test "and chains are followed to the end" - 'uint8-t + 'gl-ubyte (get-underlying-type 't-byte)) + (test "stdint.h's exact-width types are C's own" + '(unsigned char) + (get-underlying-type 'uint8-t)) (test "a struct is not a typedef" #f (get-underlying-type 't-point)) diff --git a/types.scm b/types.scm index 2a7080f..9d99c58 100644 --- a/types.scm +++ b/types.scm @@ -125,6 +125,16 @@ (hash-table-set! +type-db+ name (list 'typedef name (last (strip-pub form))))) +;;; , which nothing parses, as far as arithmetic asks: the +;;; prelude's `u8' is a `uint8-t', so (+ a a) over two of them is an +;;; `int', promoted like any narrow type. The 64-bit pair is `long' on +;;; some hosts; it ranks above the narrower ones either way. +(for-each (lambda (entry) (add-typedef (car entry) (cons 'typedef entry))) + '((int8-t (signed char)) (uint8-t (unsigned char)) + (int16-t short) (uint16-t (unsigned short)) + (int32-t int) (uint32-t (unsigned int)) + (int64-t (long long)) (uint64-t (unsigned long long)))) + ;;; (define name value ...) -- a C #define, kept so a macro can read a ;;; compile-time constant rather than re-parse the source. (define (add-define name form) -- 2.52.0 From 085207982775b09183bf66458e7c16eb53b14770 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 13:54:57 +0300 Subject: [PATCH 04/74] parenthesize a negative literal under a unary operator A negative literal is one token in Sex and two in C, so (- -1) came out --1, which C reads as decrementing a constant. --- sex-fmt-c.scm | 8 +++++++- tests/sex-programs/operators.sex | 7 ++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index 6b02d3b..07cc9b3 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -1075,10 +1075,16 @@ ;; Parenthesises the whole expression rather than the operand: the ;; other way round, `(. (* p) x)' came out `*(p).x', which C reads as ;; `*(p.x)'. + ;; MODIFIED FROM UPSTREAM fmt-c: a negative literal is one token in + ;; Sex and two in C, so (- -1) is -(-1), not the decrement --1. (define (c-unary-op op x) (c-wrap-stmt (c-maybe-paren (unary-operator op) - (cat (display-to-string op) (c-expr x))))) + (cat (display-to-string op) + (if (and (number? x) + (char=? #\- (string-ref (number->string x) 0))) + (c-paren x) + (c-expr x)))))) ;; some convenience definitions diff --git a/tests/sex-programs/operators.sex b/tests/sex-programs/operators.sex index 7481f55..78b9ad9 100644 --- a/tests/sex-programs/operators.sex +++ b/tests/sex-programs/operators.sex @@ -9,7 +9,8 @@ "closure in place: 5" "a type is not a call: 7" "radix literals: 224 5 128" - "a double reaches C whole: 1") + "a double reaches C whole: 1" + "negated literals: 1 2.5") (return 0) ;;; The walk types an expression by its head, and the heads it had a @@ -97,4 +98,8 @@ ;; ...and a double in all the digits it was written with (var sixth double (/ 1.0 6.0)) (printf "a double reaches C whole: %d\n" (== 0.16666666666666666 sixth)) + + ;; a negative literal is one token in Sex and two in C, and C reads a + ;; minus written before them as `--' + (printf "negated literals: %d %g\n" (- -1) (- -2.5)) (return 0)) -- 2.52.0 From 0cb3956e025c07086944eb517b71764bca9096d1 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 13:55:22 +0300 Subject: [PATCH 05/74] declare a record's typedef ahead of its struct It came after, so a record pointing at itself, (next (* node)), named a type C had not been told of yet. --- semen.scm | 20 +++++++++++++------- tests/sex-programs/records.sex | 11 ++++++++++- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/semen.scm b/semen.scm index 38cb9df..d6553e4 100644 --- a/semen.scm +++ b/semen.scm @@ -1895,13 +1895,19 @@ (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)))) + ;; the typedef first, so a field may point back at the record, and + ;; the docstring ahead of both + (let-values (((doc struct) + (extract-aggregate-docstring + (copy-form-source! form + (if (eq? (car form) 'pub) + `(pub struct ,@(cdr core)) + `(struct ,@(cdr core))))))) + (process-struct + struct + (with-docstring doc + (copy-form-source! form `(typedef (struct ,name) ,name)) + acc))))) (define (register-aggregate! form) (let* ((f (if (eq? (car form) 'pub) (cdr form) form)) diff --git a/tests/sex-programs/records.sex b/tests/sex-programs/records.sex index 0477e97..499d206 100644 --- a/tests/sex-programs/records.sex +++ b/tests/sex-programs/records.sex @@ -1,5 +1,6 @@ (input) -(output "p 3 4 / n 7 zoe / area 12 / sizes 8 8") +(output "p 3 4 / n 7 zoe / area 12 / sizes 8 8" + "chain 1 2") (return 0) ;;; A record is a struct that also names itself, so the bare name @@ -18,6 +19,10 @@ (struct raw ((a int) (b int))) +;;; A record naming itself in its own fields: the name is a type before +;;; the fields are +(record node ((value int) (next (* node)))) + (fn shift ((p (* point)) (dx int) (dy int)) void (+= (. p x) dx) (+= (. p y) dy)) @@ -43,4 +48,8 @@ (. p x) (. p y) (. n id) (. n first-name) (area [ps 0]) (sizeof point) (sizeof (struct raw))) + + (var tail node #(node : 2 NULL)) + (var head node #(node : 1 (& tail))) + (printf "chain %d %d\n" (. head value) (. head next value)) (return (+ (. [ps 1] x) (- (. r a) 1)))) -- 2.52.0 From 27ef5ac8054558216538c600b6889650f6c156c6 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 13:55:45 +0300 Subject: [PATCH 06/74] look for an import beside the file it is written in Imports were looked for from the unit's directory, so a module in a subdirectory could not import its neighbours: a pub import failed, a private one lost its handle declarations, and --public-interface changed with where sexc ran. --- semen.scm | 6 +-- sex-modules.scm | 76 +++++++++++++++++++---------------- tests/modules/check.scm | 18 +++++++++ tests/modules/shelf-app.sex | 9 +++++ tests/modules/shelf/book.sex | 8 ++++ tests/modules/shelf/page.sex | 4 ++ tests/modules/shelf/spine.sex | 3 ++ 7 files changed, 87 insertions(+), 37 deletions(-) create mode 100644 tests/modules/shelf-app.sex create mode 100644 tests/modules/shelf/book.sex create mode 100644 tests/modules/shelf/page.sex create mode 100644 tests/modules/shelf/spine.sex diff --git a/semen.scm b/semen.scm index d6553e4..dad2d97 100644 --- a/semen.scm +++ b/semen.scm @@ -115,9 +115,9 @@ (cons sex-form acc)) (('comment . _) (cons sex-form acc)) - ((or ('import . modules) - ('pub 'import . modules)) - (process-imports (get-modules-public-forms modules) acc)) + ((or ('import . _) + ('pub 'import . _)) + (process-imports (get-modules-public-forms sex-form) acc)) ((or ('defmacro . rest) ('pub 'defmacro . rest)) (defmacro rest) acc) diff --git a/sex-modules.scm b/sex-modules.scm index 21acc86..5ab1f79 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -1,6 +1,5 @@ (import scheme - brev-separate (chicken base) (chicken file) (chicken load) @@ -8,7 +7,6 @@ (chicken pathname) (chicken process-context) (chicken string) - fmt matchable reader srfi-1 @@ -28,29 +26,36 @@ ;;; once) (define +imported-modules+ (list)) -(define (get-modules-public-forms module-list) - ;; Module list is a list of symbols +(define (get-modules-public-forms import-form) ;; How Sex handles modules: - ;; For each module in a list, construct path, find module by path in - ;; module path directories, extract public definitions from the - ;; module, paste them in current one in emulation of C include + ;; For each module IMPORT-FORM names, construct path, find module by + ;; path in module path directories, extract public definitions from + ;; the module, paste them in current one in emulation of C include ;; directives. - (fold-right append (list) - (map (fn (import-module (symbol->string x))) - module-list))) + (append-map (lambda (name) (import-module (symbol->string name) import-form)) + (cdr (strip-pub import-form)))) -(define (import-module name) - (let ((module-path (locate-module name))) - (assert module-path (fmt #f "Failed to find module " name " in " - (get-module-paths))) +(define (import-module name form) + (let* ((directory (import-directory form)) + (module-path (locate-module name directory))) + (unless module-path + (sex-error form "Failed to find module" name (get-module-paths directory))) (if (member module-path +imported-modules+) (list) (begin (set! +imported-modules+ (cons module-path +imported-modules+)) (read-public-interface module-path))))) -(define (get-module-paths) - (cons (current-directory) +;;; An import is looked for beside the file it is written in, so a +;;; module's imports are its neighbours wherever the unit importing it +;;; is. One with no file to be beside -- stdin's, a macro's -- is looked +;;; for from the working directory, which is the unit's +(define (import-directory form) + (let ((file (form-file form))) + (or (and file (pathname-directory file)) (current-directory)))) + +(define (get-module-paths #!optional (directory (current-directory))) + (cons directory (append +persistent-module-paths+ (standard-library-paths)))) ;;; Where the modules shipped with the compiler live. Asked of the @@ -66,12 +71,12 @@ (make-pathname (list (pathname-directory bin) "share") "sex"))) (list)))) -(define (locate-module name) - ;; Module locations: relative to file being compiled, or in what was - ;; in SEX_MODULE_PATH env var at the start of the process (see +(define (locate-module name directory) + ;; Module locations: relative to DIRECTORY, or in what was in + ;; SEX_MODULE_PATH env var at the start of the process (see ;; load-persistent-module-paths function) - (let ((search-paths (get-module-paths))) + (let ((search-paths (get-module-paths directory))) (let loop ((paths search-paths)) (if (null? paths) #f @@ -279,28 +284,31 @@ (map (lambda (entry) (append entry (list #t))) (append-map exported-types (imported-modules forms #f))))) -;;; The names of the modules FORMS import, with pub or without +;;; The files of the modules FORMS import, with pub or without (define (imported-modules forms pub?) (append-map (lambda (form) (match form - (('pub 'import . modules) (if pub? modules (list))) - (('import . modules) (if pub? (list) modules)) + (('pub 'import . modules) (if pub? (located form modules) (list))) + (('import . modules) (if pub? (list) (located form modules))) (_ (list)))) forms)) +(define (located form modules) + (let ((directory (import-directory form))) + (filter-map (lambda (name) (locate-module (symbol->string name) directory)) + modules))) + ;;; The types a module gives its importers, its pub imports' included. ;;; Two modules may import each other, so each is read once -(define (exported-types module) - (let next ((modules (list module)) (seen (list)) (acc (list))) - (if (null? modules) - (concatenate (reverse acc)) - (let ((path (locate-module (symbol->string (car modules))))) - (if (or (not path) (member path seen)) - (next (cdr modules) seen acc) - (let ((exports (module-exports path))) - (next (append (cdr modules) (cdr exports)) - (cons path seen) - (cons (car exports) acc)))))))) +(define (exported-types path) + (let next ((paths (list path)) (seen (list)) (acc (list))) + (cond ((null? paths) (concatenate (reverse acc))) + ((member (car paths) seen) (next (cdr paths) seen acc)) + (else + (let ((exports (module-exports (car paths)))) + (next (append (cdr paths) (cdr exports)) + (cons (car paths) seen) + (cons (car exports) acc))))))) ;;; The types the module at PATH declares to its importers, and the ;;; modules its interface imports; worked out once, though the check of diff --git a/tests/modules/check.scm b/tests/modules/check.scm index 71e68ae..b882c74 100644 --- a/tests/modules/check.scm +++ b/tests/modules/check.scm @@ -28,6 +28,10 @@ ;;; and ledger, which only greet does but which decides what the app is ;;; told of it. ;;; +;;; A module in a directory of its own finds its imports beside itself, +;;; not beside the unit importing it: shelf-app imports shelf/book, and +;;; book its siblings page, with `pub', and spine, without. +;;; ;;; make check-modules (import scheme @@ -80,6 +84,20 @@ (and (irregex-match ".*\\.sex:" line) (pathname-strip-directory line))) (call-with-input-file (built "greet-app.d") read-lines))) +(test "a module's interface does not depend on where sexc runs" + '("(record spine)" "(import page)") + (take (or (output-of sexc "--public-interface" "shelf/book.sex") '()) 2)) + +(test-assert "a module in a directory finds its imports beside itself" + (and (output-of sexc "shelf/page.sex" "-c" "-o" (built "page.o")) + (output-of sexc "shelf/book.sex" "-c" "-o" (built "book.o")) + (output-of sexc "shelf-app.sex" "-o" (built "shelf-app") + "--" (built "book.o") (built "page.o")))) + +(test "and the app runs through it" + '("pages 2 3") + (output-of (built "shelf-app"))) + (test "the app runs through both" '("hello, world" "hello, sex" diff --git a/tests/modules/shelf-app.sex b/tests/modules/shelf-app.sex new file mode 100644 index 0000000..d97ca10 --- /dev/null +++ b/tests/modules/shelf-app.sex @@ -0,0 +1,9 @@ +(include stdio.h) +(import shelf/book) + +(pub fn main () int + (var b book #(book : NULL #(page : 1))) + (printf "pages %d %d\n" + (. (second-page (& b)) number) + (. (page-after (second-page (& b))) number)) + (return 0)) diff --git a/tests/modules/shelf/book.sex b/tests/modules/shelf/book.sex new file mode 100644 index 0000000..9a23e74 --- /dev/null +++ b/tests/modules/shelf/book.sex @@ -0,0 +1,8 @@ +;;; Its imports are found beside it, wherever the unit importing it is +(pub import page) +(import spine) + +(pub record book ((spine (* spine)) (first page))) + +(pub fn second-page ((b (* const book))) page + (return (page-after (. b first)))) diff --git a/tests/modules/shelf/page.sex b/tests/modules/shelf/page.sex new file mode 100644 index 0000000..42c9585 --- /dev/null +++ b/tests/modules/shelf/page.sex @@ -0,0 +1,4 @@ +(pub record page ((number int))) + +(pub fn page-after ((p page)) page + (return #(page : (+ (. p number) 1)))) diff --git a/tests/modules/shelf/spine.sex b/tests/modules/shelf/spine.sex new file mode 100644 index 0000000..b5e1f70 --- /dev/null +++ b/tests/modules/shelf/spine.sex @@ -0,0 +1,3 @@ +;;; book imports this without `pub', so book's importers get the record +;;; behind a pointer, declared and no more +(pub record spine ((width int))) -- 2.52.0 From c05904c15e22780fb32bf5effe4b73b31df916a0 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 14:19:51 +0300 Subject: [PATCH 07/74] escape a ? that follows a ? in string literals Under -std=c11 C reads trigraphs, which Sex has none of: "??=" came out "#", and "??/" before the closing quote left the string open. --- sex-fmt-c.scm | 20 +++++++++++++++----- tests/sex-programs/c11.sex | 8 +++++++- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index 07cc9b3..a533ad7 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -212,14 +212,24 @@ (define (c-format-string x) (lambda (st) ((cat #\" (apply-cat (c-string-escaped x)) #\") st))) + ;; MODIFIED FROM UPSTREAM fmt-c: a `?' after a `?' is escaped, so no + ;; two stand together for C to read a trigraph off -- under -std=c11 + ;; "??=" is "#", and "??/" before the closing quote is \", which + ;; leaves the string open. (define (c-string-escaped x) + (define (special? i) + (let ((c (string-ref x i))) + (or (c-needs-string-escape? c) + (and (eqv? c #\?) (> i 0) (eqv? (string-ref x (- i 1)) #\?))))) (let loop ((parts '()) (idx (string-length x))) - (cond ((string-index-right x c-needs-string-escape? 0 idx) + (cond ((let find ((i (- idx 1))) + (cond ((< i 0) #f) ((special? i) i) (else (find (- i 1))))) => (lambda (special-idx) - (loop (cons (c-escape-char (string-ref x special-idx) #\") - (cons (substring/shared x (+ special-idx 1) idx) - parts)) - special-idx))) + (let ((c (string-ref x special-idx))) + (loop (cons (if (eqv? c #\?) "\\?" (c-escape-char c #\")) + (cons (substring/shared x (+ special-idx 1) idx) + parts)) + special-idx)))) (else (cons (substring/shared x 0 idx) parts))))) diff --git a/tests/sex-programs/c11.sex b/tests/sex-programs/c11.sex index 375503d..2081ca9 100644 --- a/tests/sex-programs/c11.sex +++ b/tests/sex-programs/c11.sex @@ -1,6 +1,7 @@ (compilation "-- -std=c11 -pedantic-errors") (input) -(output "c11: 42 43 6 4 6 12") +(output "c11: 42 43 6 4 6 12" + "trigraphs: what??! ??= ???( ??/") (return 0) ;;; C11 is the floor, and this is the program that holds it there: the @@ -12,6 +13,10 @@ ;;; 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, ;;; and the globals for initializers that have to be constants. +;;; +;;; It is also the one mode where C still reads trigraphs, which Sex has +;;; none of: a string says what was written, `??/' before its closing +;;; quote included. (include stdio.h) @@ -42,4 +47,5 @@ (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) (.area [pair 1])) + (printf "trigraphs: %s\n" "what??! ??= ???( ??/") (return 0)) -- 2.52.0 From 8ddeac7babbe6cb1215a92bbe4f340890f3851bc Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 14:40:26 +0300 Subject: [PATCH 08/74] write number literals the way C reads them A C suffix was no number to string->number, so 1u and 1.5f became symbols, and C got them inside the |pipes| CHICKEN writes those with. They read now into a literal that prints its C spelling and is typed by its suffix: an integer in decimal, so 0b101u needs no C23, and a float in the digits it was written with, since through a double 0.1f could round to another float and 0.1L would lose what it has over one. Scheme also reads numbers C has none of. 1/2 reached C as integer division and +inf.0 as no C at all; those, and integers past 64 bits, are read errors now. An integer is typed by size as well, so 4000000000 is no longer an int, and one past long long gets the u C would otherwise only warn about. --- reader.scm | 97 ++++++++++++++++++++++++++++++++-- semen.scm | 26 ++++++++- tests/codegen.scm | 16 ++++++ tests/reader.scm | 30 ++++++++++- tests/sex-programs/numbers.sex | 39 ++++++++++++++ 5 files changed, 203 insertions(+), 5 deletions(-) create mode 100644 tests/sex-programs/numbers.sex diff --git a/reader.scm b/reader.scm index 9831012..24aeed4 100644 --- a/reader.scm +++ b/reader.scm @@ -16,6 +16,7 @@ scheme (scheme base) ; make-parameter (chicken base) + (chicken irregex) (chicken module) (chicken pathname) (chicken platform) ; software-version, machine-type @@ -27,7 +28,11 @@ read-raw-forms current-features - platform-features) + platform-features + + c-literal? + c-literal-value + c-literal-suffix) ;;; Sentinels for structural tokens (define close-paren (list '%close-paren)) @@ -186,11 +191,97 @@ (define (finish-atom s) (cond ((string=? s ".") dot-token) - ((string->number s) => identity) - ((radix-number s) => identity) + ((or (string->number s) (radix-number s)) + => (lambda (n) (c-number n s))) + ((suffixed-number s) => identity) ((negated-name? s) (list '- (string->symbol (substring s 1)))) (else (string->symbol s)))) +;;; Scheme reads numbers C has no literal for -- 1/2, #e1.5, 1e400, +;;; +nan.0, 1+2i -- and they reached C as written. An integer too wide +;;; for long long is unsigned to C, which says so only by a warning +;;; unless it is written with a `u'; so it is. +(define +llong-min+ (- (expt 2 63))) +(define +llong-max+ (- (expt 2 63) 1)) +(define +ullong-max+ (- (expt 2 64) 1)) + +(define (c-number n s) + (cond ((exact-integer? n) + (cond ((> (abs n) +ullong-max+) + (error "too large for any C integer type" s)) + ((> n +llong-max+) (make-c-literal n "u" #f)) + ((< n +llong-min+) (list '- (make-c-literal (- n) "u" #f))) + (else n))) + ((and (real? n) (inexact? n) (finite? n)) n) + (else (error "C has no literal for this number" s)))) + +;;; 1u, 10L, 1ULL, 1.5f, 0.1L: a number with C's suffix, which the C is +;;; written with. +;;; +;;; 0b101u -> 5u in decimal, so C23's 0b never reaches C11 +;;; 0.1f -> 0.1f in the digits written: through a double, 0.1f +;;; could round to another float, and 0.1L would +;;; lose all it has over one +;;; -1u -> (- 1u) which is what C reads it as too +(define-record-type + (make-c-literal value suffix digits) + c-literal? + (value c-literal-value) + (suffix c-literal-suffix) + (digits c-literal-digits)) + +(set-record-printer! + (lambda (literal port) + (display (or (c-literal-digits literal) + (number->string (c-literal-value literal))) + port) + (display (c-literal-suffix literal) port))) + +(define suffixed-integer + (irregex "(0[xX][0-9a-fA-F]+|0[bB][01]+|[0-9]+)([uU](?:ll|LL|l|L)?|(?:ll|LL|l|L)[uU]?)")) + +(define suffixed-float + (irregex "((?:[0-9]+\\.[0-9]*|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?|[0-9]+[eE][+-]?[0-9]+)([fFlL])")) + +(define (suffixed-number s) + (let* ((negative? (and (> (string-length s) 1) (char=? #\- (string-ref s 0)))) + (body (if negative? (substring s 1) s)) + ;; each spelling begins with a digit or a point, and few names do + (literal (and (> (string-length body) 0) + (or (char-numeric? (string-ref body 0)) + (char=? #\. (string-ref body 0))) + (or (suffixed-integer-literal body s) + (suffixed-float-literal body s))))) + (and literal (if negative? (list '- literal) literal)))) + +(define (suffixed-integer-literal body s) + (let ((m (irregex-match suffixed-integer body))) + (and m + (let* ((digits (irregex-match-substring m 1)) + (suffix (irregex-match-substring m 2)) + (n (or (radix-number digits) (string->number digits))) + (widest (if (irregex-search "[uU]" suffix) +ullong-max+ +llong-max+))) + (when (> n widest) + (error "too large for its suffix" s)) + (make-c-literal n suffix #f))))) + +(define (suffixed-float-literal body s) + (let ((m (irregex-match suffixed-float body))) + (and m + (let* ((digits (irregex-match-substring m 1)) + (suffix (irregex-match-substring m 2)) + (n (string->number digits))) + (unless (in-range? n suffix) + (error "C has no literal for this number" s)) + (make-c-literal n suffix digits))))) + +;;; A float overflows where it would round past FLT_MAX; a long double +;;; may be wider than any double, so whatever a double holds it does too +(define (in-range? n suffix) + (case (string-ref suffix 0) + ((#\f #\F) (< (abs n) (* (- 2 (expt 2. -24)) (expt 2. 127)))) + (else #t))) + ;;; 0xE0 and 0b101 are C's spelling of 224 and 5, and are read as those ;;; numbers: the C written from them says 224 and 5 (define (radix-number s) diff --git a/semen.scm b/semen.scm index dad2d97..2341e34 100644 --- a/semen.scm +++ b/semen.scm @@ -13,6 +13,7 @@ sex-modules types matchable ; pattern matching + reader ; c-literal srfi-1 ; list routines srfi-69 ; hash tables utils @@ -1212,9 +1213,32 @@ ;;; 42 -> int (. p x) -> that field's type ;;; "hi" -> (* const char) (& p) -> (* (struct point)) ;;; (area 3 4) -> what `area' returns +;;; What C makes of a literal: of the types its suffix allows, the +;;; first that holds it, by the widths every host has -- int and long +;;; of 32 bits, long long of 64 -- so it is never narrower than C's own. +;;; +;;; 1 -> int 1u -> (unsigned int) +;;; 4000000000 -> (long long) 10L -> long +;;; 1.5f -> float 0.1L -> (long double) +(define (c-literal-type literal) + (let ((n (c-literal-value literal)) + (suffix (map char-downcase (string->list (c-literal-suffix literal))))) + (cond ((exact? n) (integer-literal-type n suffix)) + ((memv #\f suffix) 'float) + (else '(long double))))) + +(define (integer-literal-type n suffix) + (let ((ranks (drop (if (memv #\u suffix) + '(((unsigned int) 32) ((unsigned long) 32) ((unsigned long long) 64)) + '((int 31) (long 31) ((long long) 63))) + (count (cut eqv? #\l <>) suffix)))) + (let ((rank (find (lambda (rank) (< (abs n) (expt 2 (second rank)))) ranks))) + (and rank (first rank))))) + (define (expression-type expr env) (cond - ((and (number? expr) (exact? expr)) 'int) + ((c-literal? expr) (c-literal-type expr)) + ((and (number? expr) (exact? expr)) (integer-literal-type expr '())) ((number? expr) 'double) ((string? expr) '(* const char)) ((char? expr) 'char) diff --git a/tests/codegen.scm b/tests/codegen.scm index 83f21bc..a89aeba 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -759,6 +759,22 @@ (test-assert "sixteen when that is enough" (emits? (in-fn "(var d double 0.9871465422297019)") "d = 0.9871465422297019;"))) + ;; A suffix is C's, and reached C inside |pipes|, the way CHICKEN + ;; writes a symbol that starts with a digit + (test-group "suffixed literals" + (test-assert "an integer keeps its suffix" + (emits? (in-fn "(var n (unsigned long long) 1ULL)") "n = 1ULL;")) + (test-assert "and is written in decimal, which C11 has a suffix for" + (emits? (in-fn "(var n (unsigned int) 0b101u)") "n = 5u;")) + (test-assert "a float keeps its digits, which a double would round" + (emits? (in-fn "(var x (long double) 3.14159265358979323846264338327950288L)") + "x = 3.14159265358979323846264338327950288L;")) + (test-assert "a minus is C's own" + (emits? (in-fn "(var n (unsigned int) -1u)") "n = -1u;")) + (test-assert "a number too wide for long long is unsigned, and says so" + (emits? (in-fn "(var n (unsigned long long) 0xFFFFFFFFFFFFFFFF)") + "n = 18446744073709551615u;"))) + ;; A define's body was pasted unwalked, and unparenthesised: `cast' ;; stayed a call, and (* x D) regrouped with D's own operator (test-group "defines" diff --git a/tests/reader.scm b/tests/reader.scm index a77ca0a..468872c 100644 --- a/tests/reader.scm +++ b/tests/reader.scm @@ -1,4 +1,5 @@ -(import (chicken port) +(import (chicken condition) + (chicken port) reader) (define-syntax feature-test @@ -9,6 +10,12 @@ (with-input-from-string string (lambda () (read-raw-forms 'stdin)))))))) +(define (read-error string) + "The message of the error reading STRING raises, or #f if it reads." + (handle-exceptions e ((condition-property-accessor 'exn 'message) e) + (with-input-from-string string (lambda () (read-raw-forms 'stdin))) + #f)) + (define-syntax reader-test (syntax-rules () ((reader-test result string) @@ -54,6 +61,27 @@ ;; ...and only a number: a prefix with nothing after it is a name (reader-test '(0x 0xg) "0x 0xg") + ;; Scheme reads numbers C has no literal for, and they reached C as + ;; written: 1/2 is integer division there, and +inf.0 no number at all + (test "a ratio is not a C number" + "C has no literal for this number" (read-error "1/2")) + (test "nor a double out of range" + "C has no literal for this number" (read-error "1e400")) + (test "nor a float" "C has no literal for this number" (read-error "1e39f")) + (test "but a long double may be wider than a double" + #f (read-error "1e400L")) + (test "nor an infinity" "C has no literal for this number" (read-error "-inf.0")) + (test "nor a NaN" "C has no literal for this number" (read-error "+nan.0")) + (test "nor a complex number" "C has no literal for this number" (read-error "1+2i")) + (test "an integer has 64 bits at most" + "too large for any C integer type" (read-error "18446744073709551616")) + (test "and a signed suffix leaves it 63" + "too large for its suffix" (read-error "9223372036854775808ll")) + (test "an unsigned one does not" + #f (read-error "18446744073709551615ull")) + ;; a name that only begins like a number is still a name + (reader-test '(3dmath.h) "3dmath.h") + ;; `;' comments are preserved as (comment "...") forms (reader-test '((comment " hi")) "; hi") (reader-test '((comment ";; Prototypes")) ";;; Prototypes") diff --git a/tests/sex-programs/numbers.sex b/tests/sex-programs/numbers.sex new file mode 100644 index 0000000..6a4e9a4 --- /dev/null +++ b/tests/sex-programs/numbers.sex @@ -0,0 +1,39 @@ +(compilation "-- -std=c11 -pedantic-errors -Werror") +(input) +(output "unsigned: 4294967295 18446744073709551615 4294967295" + "widths: 1 1 1" + "a float stays a float: 1" + "radix with suffix: 255 5" + "by magnitude: 4000000000 18446744073709551615") +(return 0) + +;;; A number is written the way C writes it, suffix included, and `_' +;;; takes the type C gives it: the suffix's, or for none the first type +;;; wide enough to hold it. + +(include stdio.h) + +(pub fn main () int + (var u _ 1u) + (var ull _ 1ULL) + (printf "unsigned: %u %llu %u\n" (- u 2) (- ull 2) -1u) + + (var l _ 10L) + (var f _ 1.5f) + (var ld _ 0.1L) + (printf "widths: %d %d %d\n" + (== (sizeof l) (sizeof long)) + (== (sizeof f) (sizeof float)) + (== (sizeof ld) (sizeof (long double)))) + + ;; the float nearest 0.1 is not the double nearest it + (var tenth-f _ 0.1f) + (var tenth _ 0.1) + (printf "a float stays a float: %d\n" (!= tenth-f tenth)) + + (printf "radix with suffix: %u %u\n" 0xFFu 0b101u) + + (var big _ 4000000000) + (var mask _ 0xFFFFFFFFFFFFFFFF) + (printf "by magnitude: %lld %llu\n" big mask) + (return 0)) -- 2.52.0 From 4463f796f8261442dd2e4a6b6aa1f808d34652bb Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 14:42:20 +0300 Subject: [PATCH 09/74] group a number's digits with _ C23 groups them with ', which in Sex is quote, so 1'000 read as 1 and (quote 0); _ between two digits is dropped instead, and anywhere else stays part of a name. --- reader.scm | 62 ++++++++++++++++++++++++++++++----------------- tests/codegen.scm | 2 ++ tests/reader.scm | 6 +++++ 3 files changed, 48 insertions(+), 22 deletions(-) diff --git a/reader.scm b/reader.scm index 24aeed4..c715381 100644 --- a/reader.scm +++ b/reader.scm @@ -20,6 +20,7 @@ (chicken module) (chicken pathname) (chicken platform) ; software-version, machine-type + (only (chicken string) substring-index) (only srfi-1 every any) ; srfi-1 also has an append-reverse utils) @@ -189,13 +190,26 @@ (begin (get-ch port) (loop (cons c chars))))))) (define (finish-atom s) - (cond - ((string=? s ".") dot-token) - ((or (string->number s) (radix-number s)) - => (lambda (n) (c-number n s))) - ((suffixed-number s) => identity) - ((negated-name? s) (list '- (string->symbol (substring s 1)))) - (else (string->symbol s)))) + (let ((digits (if (substring-index "_" s) (or (ungrouped s (or (c-radix s) 10)) s) s))) + (cond + ((string=? s ".") dot-token) + ((or (string->number digits) (radix-number digits)) + => (lambda (n) (c-number n s))) + ((suffixed-number digits s) => identity) + ((negated-name? s) (list '- (string->symbol (substring s 1)))) + (else (string->symbol s))))) + +;;; 1_000_000, 0xFF_FF: `_' between two digits groups them, the way +;;; C23's ' does -- which in Sex is quote. S without them, or #f when a +;;; `_' stands anywhere else, where it is part of a name +(define (ungrouped s radix) + (let ((digit? (lambda (c) (string->number (string c) radix)))) + (let loop ((cs (string->list s)) (previous #f) (acc (list))) + (cond ((null? cs) (list->string (reverse acc))) + ((char=? (car cs) #\_) + (and previous (digit? previous) (pair? (cdr cs)) (digit? (cadr cs)) + (loop (cdr cs) (car cs) acc))) + (else (loop (cdr cs) (car cs) (cons (car cs) acc))))))) ;;; Scheme reads numbers C has no literal for -- 1/2, #e1.5, 1e400, ;;; +nan.0, 1+2i -- and they reached C as written. An integer too wide @@ -243,9 +257,9 @@ (define suffixed-float (irregex "((?:[0-9]+\\.[0-9]*|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?|[0-9]+[eE][+-]?[0-9]+)([fFlL])")) -(define (suffixed-number s) - (let* ((negative? (and (> (string-length s) 1) (char=? #\- (string-ref s 0)))) - (body (if negative? (substring s 1) s)) +(define (suffixed-number digits s) + (let* ((negative? (and (> (string-length digits) 1) (char=? #\- (string-ref digits 0)))) + (body (if negative? (substring digits 1) digits)) ;; each spelling begins with a digit or a point, and few names do (literal (and (> (string-length body) 0) (or (char-numeric? (string-ref body 0)) @@ -285,20 +299,24 @@ ;;; 0xE0 and 0b101 are C's spelling of 224 and 5, and are read as those ;;; numbers: the C written from them says 224 and 5 (define (radix-number s) - (let* ((negative? (and (> (string-length s) 0) (char=? #\- (string-ref s 0)))) - (digits (if negative? (substring s 1) s))) - (and (> (string-length digits) 2) - (char=? #\0 (string-ref digits 0)) - (let ((radix (case (string-ref digits 1) - ((#\x #\X) 16) - ((#\b #\B) 2) - (else #f))) - (body (substring digits 2))) - (and radix - (not (memv (string-ref body 0) '(#\+ #\-))) + (let ((radix (c-radix s))) + (and radix + (let* ((negative? (char=? #\- (string-ref s 0))) + (body (substring s (if negative? 3 2)))) + (and (not (memv (string-ref body 0) '(#\+ #\-))) (let ((n (string->number body radix))) (and (exact-integer? n) (if negative? (- n) n)))))))) +;;; 16 for 0xE0 and 2 for 0b101, a minus aside; #f for any other spelling +(define (c-radix s) + (let ((i (if (and (> (string-length s) 0) (char=? #\- (string-ref s 0))) 1 0))) + (and (> (string-length s) (+ i 2)) + (char=? #\0 (string-ref s i)) + (case (string-ref s (+ i 1)) + ((#\x #\X) 16) + ((#\b #\B) 2) + (else #f))))) + ;;; -INFINITY is (- INFINITY), as -1 is minus one. No name begins with ;;; a dash, and an operator that does goes on with a non-letter: -> -- (define (negated-name? s) @@ -376,7 +394,7 @@ ;;; #x80, #b101, #o10 (define (read-radix port radix) (let* ((digits (read-atom-string port)) - (n (string->number digits radix))) + (n (string->number (or (ungrouped digits radix) digits) radix))) (if (exact-integer? n) n (error "Malformed number" digits)))) diff --git a/tests/codegen.scm b/tests/codegen.scm index a89aeba..0294243 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -769,6 +769,8 @@ (test-assert "a float keeps its digits, which a double would round" (emits? (in-fn "(var x (long double) 3.14159265358979323846264338327950288L)") "x = 3.14159265358979323846264338327950288L;")) + (test-assert "grouped digits reach C ungrouped" + (emits? (in-fn "(var x float 1_000.5f)") "x = 1000.5f;")) (test-assert "a minus is C's own" (emits? (in-fn "(var n (unsigned int) -1u)") "n = -1u;")) (test-assert "a number too wide for long long is unsigned, and says so" diff --git a/tests/reader.scm b/tests/reader.scm index 468872c..a99f2e9 100644 --- a/tests/reader.scm +++ b/tests/reader.scm @@ -61,6 +61,12 @@ ;; ...and only a number: a prefix with nothing after it is a name (reader-test '(0x 0xg) "0x 0xg") + ;; `_' between two digits groups them, the way C23's ' does, which in + ;; Sex is quote. Anywhere else it is part of a name + (reader-test '(1000000 65535 165 1000.5 -1000 100000.0 32768) + "1_000_000 0xFF_FF 0b1010_0101 1_000.5 -1_000 1e0_5 #x80_00") + (reader-test '(_1 1_ 1__0 0x_FF 0xF_p) "_1 1_ 1__0 0x_FF 0xF_p") + ;; Scheme reads numbers C has no literal for, and they reached C as ;; written: 1/2 is integer division there, and +inf.0 no number at all (test "a ratio is not a C number" -- 2.52.0 From 6b5a7128372beeb268d3e0f5b8bd6109fe23090f Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 14:44:29 +0300 Subject: [PATCH 10/74] read hex floats 0x1.8p3 was no number to the reader, so it became a symbol C got inside |pipes|, and _ could not type it. It reads now as a literal written as it was: the digits of a double's own bits, which no decimal rounds to. --- reader.scm | 51 ++++++++++++++++++++++++---------- semen.scm | 4 ++- tests/codegen.scm | 4 +++ tests/reader.scm | 4 +++ tests/sex-programs/numbers.sex | 8 +++++- 5 files changed, 55 insertions(+), 16 deletions(-) diff --git a/reader.scm b/reader.scm index c715381..5f75024 100644 --- a/reader.scm +++ b/reader.scm @@ -195,7 +195,7 @@ ((string=? s ".") dot-token) ((or (string->number digits) (radix-number digits)) => (lambda (n) (c-number n s))) - ((suffixed-number digits s) => identity) + ((spelled-number digits s) => identity) ((negated-name? s) (list '- (string->symbol (substring s 1)))) (else (string->symbol s))))) @@ -229,8 +229,8 @@ ((and (real? n) (inexact? n) (finite? n)) n) (else (error "C has no literal for this number" s)))) -;;; 1u, 10L, 1ULL, 1.5f, 0.1L: a number with C's suffix, which the C is -;;; written with. +;;; 1u, 10L, 1ULL, 1.5f, 0.1L, 0x1.8p3: a number with C's suffix, or a +;;; hex float, which the C is written with. ;;; ;;; 0b101u -> 5u in decimal, so C23's 0b never reaches C11 ;;; 0.1f -> 0.1f in the digits written: through a double, 0.1f @@ -257,7 +257,10 @@ (define suffixed-float (irregex "((?:[0-9]+\\.[0-9]*|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?|[0-9]+[eE][+-]?[0-9]+)([fFlL])")) -(define (suffixed-number digits s) +(define hex-float + (irregex "(0[xX]([0-9a-fA-F]*)\\.?([0-9a-fA-F]*)[pP]([+-]?[0-9]+))([fFlL]?)")) + +(define (spelled-number digits s) (let* ((negative? (and (> (string-length digits) 1) (char=? #\- (string-ref digits 0)))) (body (if negative? (substring digits 1) digits)) ;; each spelling begins with a digit or a point, and few names do @@ -265,7 +268,8 @@ (or (char-numeric? (string-ref body 0)) (char=? #\. (string-ref body 0))) (or (suffixed-integer-literal body s) - (suffixed-float-literal body s))))) + (suffixed-float-literal body s) + (hex-float-literal body s))))) (and literal (if negative? (list '- literal) literal)))) (define (suffixed-integer-literal body s) @@ -279,22 +283,41 @@ (error "too large for its suffix" s)) (make-c-literal n suffix #f))))) +;;; 0x1.8p3 is 0x18 sixteenths times 2^3 +(define (hex-float-literal body s) + (let ((m (irregex-match hex-float body))) + (and m + (let ((whole (irregex-match-substring m 2)) + (fraction (irregex-match-substring m 3)) + (exponent (string->number (irregex-match-substring m 4))) + (suffix (irregex-match-substring m 5))) + (and (> (+ (string-length whole) (string-length fraction)) 0) + (float-literal + (if (> (abs exponent) 20000) ; past any C type + (if (> exponent 0) +inf.0 0.) + (exact->inexact + (* (string->number (string-append whole fraction) 16) + (expt 2 (- exponent (* 4 (string-length fraction))))))) + suffix (irregex-match-substring m 1) s)))))) + (define (suffixed-float-literal body s) (let ((m (irregex-match suffixed-float body))) (and m - (let* ((digits (irregex-match-substring m 1)) - (suffix (irregex-match-substring m 2)) - (n (string->number digits))) - (unless (in-range? n suffix) - (error "C has no literal for this number" s)) - (make-c-literal n suffix digits))))) + (let ((digits (irregex-match-substring m 1))) + (float-literal (string->number digits) (irregex-match-substring m 2) + digits s))))) + +(define (float-literal n suffix digits s) + (unless (in-range? n suffix) + (error "C has no literal for this number" s)) + (make-c-literal n suffix digits)) ;;; A float overflows where it would round past FLT_MAX; a long double ;;; may be wider than any double, so whatever a double holds it does too (define (in-range? n suffix) - (case (string-ref suffix 0) - ((#\f #\F) (< (abs n) (* (- 2 (expt 2. -24)) (expt 2. 127)))) - (else #t))) + (cond ((string-ci=? suffix "f") (< (abs n) (* (- 2 (expt 2. -24)) (expt 2. 127)))) + ((string-ci=? suffix "l") #t) + (else (finite? n)))) ;;; 0xE0 and 0b101 are C's spelling of 224 and 5, and are read as those ;;; numbers: the C written from them says 224 and 5 diff --git a/semen.scm b/semen.scm index 2341e34..12843c8 100644 --- a/semen.scm +++ b/semen.scm @@ -1220,12 +1220,14 @@ ;;; 1 -> int 1u -> (unsigned int) ;;; 4000000000 -> (long long) 10L -> long ;;; 1.5f -> float 0.1L -> (long double) +;;; 0x1.8p3 -> double (define (c-literal-type literal) (let ((n (c-literal-value literal)) (suffix (map char-downcase (string->list (c-literal-suffix literal))))) (cond ((exact? n) (integer-literal-type n suffix)) ((memv #\f suffix) 'float) - (else '(long double))))) + ((memv #\l suffix) '(long double)) + (else 'double)))) (define (integer-literal-type n suffix) (let ((ranks (drop (if (memv #\u suffix) diff --git a/tests/codegen.scm b/tests/codegen.scm index 0294243..17436bd 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -769,6 +769,10 @@ (test-assert "a float keeps its digits, which a double would round" (emits? (in-fn "(var x (long double) 3.14159265358979323846264338327950288L)") "x = 3.14159265358979323846264338327950288L;")) + (test-assert "a hex float is written as it was" + (emits? (in-fn "(var x double 0x1.8p3)") "x = 0x1.8p3;")) + (test-assert "suffix and all" + (emits? (in-fn "(var x float -0x1p-2f)") "x = -0x1p-2f;")) (test-assert "grouped digits reach C ungrouped" (emits? (in-fn "(var x float 1_000.5f)") "x = 1000.5f;")) (test-assert "a minus is C's own" diff --git a/tests/reader.scm b/tests/reader.scm index a99f2e9..82944a1 100644 --- a/tests/reader.scm +++ b/tests/reader.scm @@ -76,6 +76,10 @@ (test "nor a float" "C has no literal for this number" (read-error "1e39f")) (test "but a long double may be wider than a double" #f (read-error "1e400L")) + (test "a hex float is held to the same ranges" + "C has no literal for this number" (read-error "0x1p1024")) + (test "a float's too" "C has no literal for this number" (read-error "0x1p128f")) + (test "and a long double's" #f (read-error "0x1p1024L")) (test "nor an infinity" "C has no literal for this number" (read-error "-inf.0")) (test "nor a NaN" "C has no literal for this number" (read-error "+nan.0")) (test "nor a complex number" "C has no literal for this number" (read-error "1+2i")) diff --git a/tests/sex-programs/numbers.sex b/tests/sex-programs/numbers.sex index 6a4e9a4..f5efc18 100644 --- a/tests/sex-programs/numbers.sex +++ b/tests/sex-programs/numbers.sex @@ -4,7 +4,8 @@ "widths: 1 1 1" "a float stays a float: 1" "radix with suffix: 255 5" - "by magnitude: 4000000000 18446744073709551615") + "by magnitude: 4000000000 18446744073709551615" + "hex floats: 12 0.25 1") (return 0) ;;; A number is written the way C writes it, suffix included, and `_' @@ -36,4 +37,9 @@ (var big _ 4000000000) (var mask _ 0xFFFFFFFFFFFFFFFF) (printf "by magnitude: %lld %llu\n" big mask) + + ;; a double's own digits, which no decimal has to round to + (var twelve _ 0x1.8p3) + (var quarter _ 0x1p-2f) + (printf "hex floats: %g %g %d\n" twelve quarter (== (sizeof quarter) (sizeof float))) (return 0)) -- 2.52.0 From 65aaf69835a1c6b0181790a080c9e56e577303d9 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 15:25:47 +0300 Subject: [PATCH 11/74] refuse an if used as a value with no else With nothing for the false case the writer made (if c 1) c || 1, a boolean; and a value if's branches were walked as statements, so one nested there got through as well. --- semen.scm | 10 +++++++--- tests/codegen.scm | 13 ++++++++++++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/semen.scm b/semen.scm index 12843c8..05f28a9 100644 --- a/semen.scm +++ b/semen.scm @@ -917,16 +917,20 @@ (copy-form-source! form (walk-body form env))) ;;; A control form, its tests walked as values and the rest as -;;; statements +;;; statements -- but an if that is a value has values for branches, +;;; and one for the false case too, or C has none to give it (define (walk-control form env) - (let ((slots (count (lambda (part) (not (comment-form? part))) (cdr form)))) + (let ((slots (count (lambda (part) (not (comment-form? part))) (cdr form))) + (valued? (and (eq? (car form) 'if) (operand-position?)))) + (when (and valued? (even? slots)) + (sex-error form "an if used as a value needs an else")) (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))) + (or valued? (test-slot? (car form) i slots)))) (walk-body (list (car parts)) env)))) (loop (cdr parts) (+ i 1) (append-reverse walked acc)))))))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 17436bd..a5b5e17 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -109,7 +109,18 @@ "a ? a : b ? b : 0")) (test-assert "but an assignment there is not" (emits? (in-fn "(var x int (if a a (= b 1)))") - "a ? a : (b = 1)"))) + "a ? a : (b = 1)")) + ;; with nothing for the false case it came out `a || 1', a boolean + (test-assert "a value needs an else" + (reports? (in-fn "(var x int (if a 1))") "an if used as a value needs an else")) + (test-assert "so does a chain" + (reports? (in-fn "(var x int (if a 1 b 2))") "an if used as a value needs an else")) + (test-assert "and an if in a value's branch" + (reports? (in-fn "(var x int (if a 1 (if b 2)))") "an if used as a value needs an else")) + (test-assert "a chain with one is a chain" + (emits? (in-fn "(var x int (if a 1 b 2 3))") "a ? 1 : b ? 2 : 3")) + (test-assert "and a statement needs none" + (emits? (in-fn "(if a (g a))") "if (a)"))) ;; A subscript binds tighter than anything, so what it subscripts is ;; parenthesised whenever it is an operator: `*q[i]' is *(q[i]) -- 2.52.0 From 9d5cd66514e4f6553bb2c01e3dcab9c927633bdc Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 15:26:05 +0300 Subject: [PATCH 12/74] read every trailing array bound as a dimension [m 1 2] lost its second index, and [int 2 3] came out int 2 x[3]. Each index now subscripts what the one before it gave, and [int 2 3] declares what it indexes, int[2][3]. An inline struct's fields, once more than one bound was looked for, were taken for one; their shape tells them apart. --- fmt-c-writer.scm | 5 +-- infer.scm | 2 +- semen.scm | 16 +++++++-- sex-modules.scm | 2 +- tests/codegen.scm | 27 ++++++++++++++- tests/sex-programs/type-shapes.sex | 8 ++++- types.scm | 53 +++++++++++++++++++++++++++--- 7 files changed, 99 insertions(+), 14 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 92ce013..6511f6e 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -353,9 +353,10 @@ forms, and what remains." ;; (const * const * const char) -> (const char * const * const) ;; (fn ((int) (float)) void) -> (%fun void ((int) (float))) (match form - (('¤ . array-type) + (('¤ . _) (if (array-bound? form) - `(%array ,(walk-type (array-element-type form)) ,(walk-expr (last array-type))) + `(%array ,(walk-type (array-element-type form)) + ,(walk-expr (array-bound form))) ;; sugar for pointer... Do we really need it? Guess why not, ;; it's a strong semantic cue `(%array ,(walk-type (array-element-type form))))) diff --git a/infer.scm b/infer.scm index 8063d7e..0dfca63 100644 --- a/infer.scm +++ b/infer.scm @@ -214,7 +214,7 @@ ;;; way the C writer unwraps them, so `[int 16]' and `[(int) 16]' are ;;; one type. (define (parse-array surface) - (let* ((rest (cdr surface)) + (let* ((rest (cdr (nest-array-type surface))) (sized? (and (pair? rest) (integer? (last rest)))) (size (and sized? (last rest))) (words (if sized? (drop-right rest 1) rest))) diff --git a/semen.scm b/semen.scm index 05f28a9..7ad2472 100644 --- a/semen.scm +++ b/semen.scm @@ -671,6 +671,16 @@ ((dot-access) (walk-member-path form env)) + ;; [m 1 2] is [[m 1] 2], m[1][2] + ((¤) + (if (> (length form) 3) + (walk-statement + (copy-form-source! + form + (list '¤ (copy-form-source! form (drop-right form 1)) (last form))) + env) + (walk-parts form env))) + ((sizeof) (if (and (= 2 (length form)) (written-type? (second form) env)) (copy-form-source! @@ -753,7 +763,7 @@ ;;; nothing here can count (define (array-length type) (and (array-bound? type) - (let ((bound (last type))) + (let ((bound (array-bound type))) (cond ((and (integer? bound) (exact? bound)) bound) ((symbol? bound) (let ((info (get-type-info bound))) @@ -794,10 +804,10 @@ ;;; there that is a type: ;;; ;;; (* char) (* const char) (* size-t) (unsigned int) types -;;; (* p) (* (g)) (¤ xs 0) expressions +;;; (* p) (* (g)) (¤ xs 0) (¤ m 1 2) expressions (define (written-type? form env) (match form - ((or ('* operand) ('¤ operand _)) + ((or ('* operand) ('¤ operand _ . _)) (if (symbol? operand) (not (or (lookup-name env operand) (get-name-type operand))) (written-type? operand env))) diff --git a/sex-modules.scm b/sex-modules.scm index 5ab1f79..a91da8f 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -227,7 +227,7 @@ ((*) (append-map (lambda (t) (type-uses t #t)) (cdr type))) ((¤) (let ((element (array-element-type type))) (append (if element (type-uses element behind?) (list)) - (if (array-bound? type) (bound-uses (last type)) (list))))) + (if (array-bound? type) (bound-uses (array-bound type)) (list))))) ((fn closure) (if (and (pair? (cdr type)) (list? (second type))) (append-map (lambda (t) (type-uses t #f)) diff --git a/tests/codegen.scm b/tests/codegen.scm index a5b5e17..5e9b4c1 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -735,7 +735,32 @@ (test-assert "after a qualified name too" (emits? (in-fn "(var b [mytype const N])") "mytype const b[N]")) (test-assert "but a qualifier alone still waits for the type" - (emits? "(typedef mytype int) (struct s ((a [const mytype])))" "const mytype a[]"))) + (emits? "(typedef mytype int) (struct s ((a [const mytype])))" "const mytype a[]")) + ;; [m 1 2] is m[1][2], so [int 2 3] declares what it indexes. A + ;; second bound was taken for the last word of the element type + (test-assert "every trailing bound is a dimension" + (emits? (in-fn "(var m [int 2 3])") "int m[2][3];")) + (test-assert "however many there are" + (emits? (in-fn "(var c [u8 2 3 4])") "u8 c[2][3][4];")) + (test-assert "named ones too" + (emits? "(define N 2) (struct s ((a [* char N 3])))" "char * a[N][3]")) + ;; a list after a tag's keyword is the aggregate's body + (test-assert "an inline aggregate's fields are not one" + (emits? "(struct s ((a [struct ((x int)) 2 3])))" "a[2][3]")) + (test-assert "but an expression after a tag is" + (emits? "(define N 2) (struct t ((z int))) (struct s ((a [struct t (* 2 N)])))" + "struct t a[2 * N]"))) + + ;; ...and an index after the first was dropped + (test-group "subscripts" + (test-assert "each index subscripts what the one before it gave" + (emits? (in-fn "(var m [int 2 3]) (= [m 1 2] a)") "m[1][2] = a;")) + (test-assert "which is an element to inference" + (emits? (in-fn "(var m [int 2 3]) (var e _ [m 1 2])") "int e = m[1][2];")) + (test-assert "and an expression to sizeof" + (emits? (in-fn "(var m [int 2 3]) (var n size-t (sizeof [m 1 1]))") "sizeof(m[1][1])")) + (test-assert "nested by hand it is the same" + (emits? (in-fn "(var m [int 2 3]) (= [[m 1] 2] a)") "m[1][2] = a;"))) ;; `sizeof' takes a type or an expression, and `(* x)' is either. ;; What is in scope says which: a name C alone knows is a type diff --git a/tests/sex-programs/type-shapes.sex b/tests/sex-programs/type-shapes.sex index 58f6c25..ebcc036 100644 --- a/tests/sex-programs/type-shapes.sex +++ b/tests/sex-programs/type-shapes.sex @@ -8,7 +8,8 @@ "named bound: 2 4 b" "unnamed parameters: 7 -1 2" "typedefs: hi 4 2" - "sizeof a pointer type: 1 1") + "sizeof a pointer type: 1 1" + "dimensions: 6 12 5") (return 0) ;;; Three questions about a written type that used to be answered in @@ -95,4 +96,9 @@ (printf "sizeof a pointer type: %d %d\n" (== (sizeof (* const char)) (sizeof greeting)) (== (sizeof (* greeting)) 1)) + + ;; [int 2 3] is two rows of three, indexed [g row column] + (var g [int 2 3] #(#(0 1 2) #(3 4 5))) + (printf "dimensions: %zu %zu %d\n" + (/ (sizeof g) (sizeof int)) (sizeof [g 0]) [g 1 2]) (return 0)) diff --git a/types.scm b/types.scm index 9d99c58..8a73ccc 100644 --- a/types.scm +++ b/types.scm @@ -64,7 +64,9 @@ arglist-types strip-pub array-bound? - array-element-type) + array-element-type + array-bound + nest-array-type) ;;; Two namespaces: `struct point' and a `point' typedef are separate ;;; declarations. Tags -- struct, union and enum alike -- share the @@ -486,6 +488,9 @@ (let ((bound (last type)) (preceding (last (drop-right type 1)))) (cond + ((and (pair? bound) (every pair? bound) + (aggregate-head? (drop-right (cdr type) 1))) + #f) ((not (symbol? bound)) #t) ((or (memq bound +c-specifiers+) (memq bound +c-qualifiers+)) #f) ((memq preceding '(* struct union enum)) #f) @@ -496,14 +501,52 @@ (drop-right (cdr type) 2))) (else #t))))) +;;; Do WORDS end the way a struct's head does, so that a list of fields +;;; after them is its body? A list of anything else is a bound, as in +;;; (¤ struct point (* 2 N)): +;;; +;;; (struct) (struct point) heads (* struct point) (int) not +(define (aggregate-head? words) + (let ((tag-words (if (and (pair? words) (symbol? (last words)) + (not (memq (last words) '(struct union enum)))) + (drop-right words 1) + words))) + (and (pair? tag-words) + (memq (last tag-words) '(struct union enum)) + #t))) + +;;; [int 2 3] is two of [int 3], so it declares what [m 1 2] indexes, +;;; m[1][2]. Every trailing bound is a dimension, the first outermost: +;;; +;;; (¤ int 2 3) -> (¤ (¤ int 3) 2) +;;; (¤ char N 3) -> (¤ (¤ char 3) N) +;;; (¤ int 4) -> (¤ int 4) +(define (nest-array-type type) + (let peel ((base type) (bounds (list))) + (if (array-bound? base) + (peel (drop-right base 1) (cons (last base) bounds)) + (if (< (length bounds) 2) + type + (let ((inner-first (reverse bounds))) + (fold (lambda (bound inner) (list '¤ inner bound)) + (append base (list (car inner-first))) + (cdr inner-first))))))) + +;;; How many elements a written array type has, when array-bound? says +;;; it says: (¤ int 4) -> 4, (¤ int 2 3) -> 2 +(define (array-bound type) + (last (nest-array-type type))) + ;;; What one element of a written array type is: -;;; (¤ struct point 2) -> (struct point), (¤ * const char 2) -> (* const char) +;;; (¤ struct point 2) -> (struct point), (¤ * const char 2) -> (* const char), +;;; (¤ int 2 3) -> (¤ int 3) (define (array-element-type type) (and (pair? type) (eq? '¤ (car type)) (pair? (cdr type)) - (let ((words (if (array-bound? type) - (drop-right (cdr type) 1) - (cdr type)))) + (let* ((type (nest-array-type type)) + (words (if (array-bound? type) + (drop-right (cdr type) 1) + (cdr type)))) (and (pair? words) (if (null? (cdr words)) (car words) words))))) -- 2.52.0 From e9ee120383b8e370f8fee18642ddbf0341534fca Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 15:26:31 +0300 Subject: [PATCH 13/74] refuse a comparison of other than two operands (< a b c) reached C as C's own chain, which compares a boolean with c. --- fmt-c-writer.scm | 12 +++++++++++- tests/codegen.scm | 12 ++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 6511f6e..00f337f 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -283,7 +283,17 @@ forms, and what remains." (('default . body) (cons 'default (walk-case-body body))) ;; Drop comments so they will not generate additional comma - (else (map walk-expr (remove comment-form? form))))) + (else + (check-arity form) + (map walk-expr (remove comment-form? form))))) + +;;; Operands past what an operator takes were written as they came: +;;; (< a b c) as C's own chain, which compares a boolean with c +(define (check-arity form) + (when (and (memq (car form) '(< > <= >= == !=)) + (not (= (count (lambda (part) (not (comment-form? part))) (cdr form)) 2))) + (sex-error form "a comparison takes two operands; chain them with &&" + (car form)))) ;;; #(a b c) is a brace initializer. A `:' inside one ends a type and ;;; turns the whole thing into a C99 compound literal: diff --git a/tests/codegen.scm b/tests/codegen.scm index 5e9b4c1..3e22349 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -706,6 +706,18 @@ (test-assert "and negation beside a binary operator" (emits? (in-fn "(var n int (+ (- a) b))") "-a + b"))) + ;; Operands past what an operator takes were written as they came: + ;; (< a b c) as C's own chain, which compares a boolean with c + (test-group "operator arity" + (test-assert "a comparison takes two operands" + (reports? (in-fn "(var x bool (< a b a))") "a comparison takes two operands")) + (test-assert "equality too" + (reports? (in-fn "(var x bool (== a b a))") "a comparison takes two operands")) + (test-assert "and not one" + (reports? (in-fn "(var x bool (>= a))") "a comparison takes two operands")) + (test-assert "two is a comparison" + (emits? (in-fn "(var x bool (<= a b))") "x = a <= b;"))) + ;; An array bound was taken only when it was an integer literal, so a ;; symbolic one fell into the type: `[int N]' came out `int N a[]'. (test-group "array bounds" -- 2.52.0 From 7c62e65eb023014f53fefb7163b0b052cc12b007 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 15:26:49 +0300 Subject: [PATCH 14/74] hold operators to the operands they take Past them an operator was written as it came: (/ a) as /a, (! a b) as a ! b. (++ a b) steps each in turn, through a comma operator the writer lacked: bare in a for header, and in parens wherever else, since bare it would begin another declarator or argument. --- fmt-c-writer.scm | 45 ++++++++++++++++++++++++++++++++++++++------- sex-fmt-c.scm | 21 +++++++++++++++++++-- tests/codegen.scm | 29 ++++++++++++++++++++++++++++- 3 files changed, 85 insertions(+), 10 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 00f337f..c01c61f 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -285,15 +285,46 @@ forms, and what remains." ;; Drop comments so they will not generate additional comma (else (check-arity form) - (map walk-expr (remove comment-form? form))))) + (let ((form (remove comment-form? form))) + (if (and (memq (car form) '(++ --)) (pair? (cdr form)) (pair? (cddr form))) + ;; (++ a b) steps each in turn: statements where it is one, + ;; C's comma where it is a value + (cons '%comma (map (lambda (operand) (walk-expr (list (car form) operand))) + (cdr form))) + (map walk-expr form)))))) + +(define +comparisons+ '(< > <= >= == !=)) + +;;; The operands each operator takes, as (fewest . most), most #f for no +;;; limit. Past them an operator was written as it came: (/ a) as `/a', +;;; (! a b) as `a ! b', (< a b c) as C's own chain, which compares a +;;; boolean with c +(define +operator-arity+ + `((,+comparisons+ 2 . 2) + ((+= -= *= /= %= &= ^= |\|=| <<= >>=) 2 . 2) + ((! ~ bit-not bitwise-not) 1 . 1) + ((- + * & ++ --) 1 . #f) + ((/ % << >> && |\|\|| ^ |\|| = bit-and bit-or bit-xor + bitwise-and bitwise-ior bitwise-xor) + 2 . #f))) + +(define (operator-arity head) + (find (lambda (entry) (memq head (car entry))) +operator-arity+)) -;;; Operands past what an operator takes were written as they came: -;;; (< a b c) as C's own chain, which compares a boolean with c (define (check-arity form) - (when (and (memq (car form) '(< > <= >= == !=)) - (not (= (count (lambda (part) (not (comment-form? part))) (cdr form)) 2))) - (sex-error form "a comparison takes two operands; chain them with &&" - (car form)))) + (let ((entry (operator-arity (car form))) + (given (count (lambda (part) (not (comment-form? part))) (cdr form)))) + (when entry + (let ((fewest (cadr entry)) + (most (cddr entry))) + (unless (and (>= given fewest) (or (not most) (<= given most))) + (sex-error form + (if (eq? (car entry) +comparisons+) + "a comparison takes two operands; chain them with &&" + (string-append "takes " + (if (= fewest 1) "one operand" "two operands") + (if most "" " or more"))) + (car form))))))) ;;; #(a b c) is a brace initializer. A `:' inside one ends a type and ;;; turns the whole thing into a C99 compound literal: diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index a533ad7..f0160cf 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -304,6 +304,7 @@ ((%prototype) ((apply c-prototype (cdr x)) st)) ((%var) ((apply c-var (cdr x)) st)) ((%begin) ((apply c-begin (cdr x)) st)) + ((%comma) ((apply c-comma (cdr x)) st)) ((%attribute) ((apply c-attribute (cdr x)) st)) ((%line) ((apply cpp-line (cdr x)) st)) ((%pragma %error %warning) @@ -628,6 +629,19 @@ (define (c-begin . args) (apply c-begin/aux #f args)) + ;; MODIFIED FROM UPSTREAM fmt-c, which has no comma operator: as a + ;; statement, statements; as a value, the expressions in parens, since + ;; bare they would be an initializer's next declarator or a call's next + ;; argument -- except where a for header says it may stand bare. + (define (c-comma . exprs) + (lambda (st) + ((if (fmt-expression? st) + (let ((joined (fmt-join (lambda (e) (c-with-op 'comma (c-expr e))) + exprs ", "))) + (if (eq? (fmt-op st) 'comma) joined (cat "(" joined ")"))) + (apply c-begin exprs)) + st))) + (define (c-begin/aux ret? body0 . body) (if (null? body) (c-expr body0) @@ -719,13 +733,16 @@ (c-in-stmt (apply c-begin body))) fl)))) + ;; MODIFIED FROM UPSTREAM fmt-c: a header's first and last slots are + ;; the one place a comma expression goes bare, so they say so. (define (c-for init check update . body) (c-reset-newline (cat (c-block (c-in-expr - (cat "for (" (c-expr init) "; " (c-in-test (c-expr check)) "; " - (c-expr update ) ")")) + (cat "for (" (c-with-op 'comma (c-expr init)) "; " + (c-in-test (c-expr check)) "; " + (c-with-op 'comma (c-expr update)) ")")) (c-in-stmt (apply c-begin body))) fl))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 3e22349..24b816b 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -716,7 +716,34 @@ (test-assert "and not one" (reports? (in-fn "(var x bool (>= a))") "a comparison takes two operands")) (test-assert "two is a comparison" - (emits? (in-fn "(var x bool (<= a b))") "x = a <= b;"))) + (emits? (in-fn "(var x bool (<= a b))") "x = a <= b;")) + ;; ...and (/ a) as `/a', (! a b) as `a ! b' + (test-assert "a division takes two or more" + (reports? (in-fn "(var x int (/ a))") "takes two operands or more")) + (test-assert "so does &&" + (reports? (in-fn "(var x bool (&& a))") "takes two operands or more")) + (test-assert "a compound assignment takes two" + (reports? (in-fn "(+= a b a)") "takes two operands")) + (test-assert "a negation takes one" + (reports? (in-fn "(var x bool (! a b))") "takes one operand")) + (test-assert "a bit-not too" + (reports? (in-fn "(var x int (~ a b))") "takes one operand")) + (test-assert "minus takes one or more" + (reports? (in-fn "(var x int (-))") "takes one operand or more")) + (test-assert "and with more than one is still a subtraction" + (emits? (in-fn "(var x int (- a b a))") "x = a - b - a;")) + ;; ++ and -- step each operand in turn + (test-assert "a statement steps each operand" + (followed-by? (in-fn "(++ a b)") "++a;" "++b;")) + (test-assert "so does a for's step, which is one expression" + (emits? (in-fn "(for (var i int 0) (< i a) (++ i b) (g i))") "; ++i, ++b)")) + (test-assert "and a value is one too, in parens" + (emits? (in-fn "(var x int (-- a b))") "x = (--a, --b);")) + ;; a define's body is pasted, not walked, so it is looked at apart + (test-assert "a define's body is held to the same" + (reports? "(define BAD (< 1 2 3))" "a comparison takes two operands")) + (test-assert "and steps each operand the same way" + (emits? "(define (STEP a b) (++ a b))" "#define STEP(a, b) ((++(a), ++(b)))"))) ;; An array bound was taken only when it was an integer literal, so a ;; symbolic one fell into the type: `[int N]' came out `int N a[]'. -- 2.52.0 From 82fa8d196600ee3727a8e30e2eb6da419b38eb50 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 15:27:07 +0300 Subject: [PATCH 15/74] require case labels to be values written once (case (1 2) ...) is a list of labels, so (case (+ 1 1) ...) came out case +: case 1: case 1:, and a value repeated in a switch was left to C to report, without saying where. --- fmt-c-writer.scm | 24 ++++++++++++++++++++++++ tests/codegen.scm | 17 +++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index c01c61f..2b84f11 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -12,6 +12,7 @@ sex-fmt-c matchable (chicken irregex) ; unkebabify + reader ; c-literal? srfi-1 ; lists srfi-13 ; strings types ; array-bound?, named-arg? @@ -269,6 +270,7 @@ forms, and what remains." ;; clause to be a case/default form and errors on anything else. (('switch . rest) (let-values (((comments slots clauses) (take-slots rest 1))) + (check-case-labels form clauses) (with-comments (append comments (filter comment-form? clauses)) (cons* 'switch (walk-expr (car slots)) (map walk-expr (remove comment-form? clauses)))))) @@ -326,6 +328,28 @@ forms, and what remains." (if most "" " or more"))) (car form))))))) +;;; (case (1 2) ...) is two labels, so anything but a value among them +;;; was taken for one: (case (+ 1 1) ...) came out `case +: case 1: +;;; case 1:'. A value written twice in one switch C reports too, but not +;;; where. +(define (check-case-labels form clauses) + (fold (lambda (clause seen) + (let ((parts (and (pair? clause) (memq (car clause) '(case case/fallthrough)) + (remove comment-form? (cdr clause))))) + (if (pair? parts) + (fold (lambda (value seen) + (unless (or (number? value) (char? value) (c-literal? value) + (and (symbol? value) (not (operator-arity value)))) + (sex-error form "a case label is a value" (car parts))) + (when (member value seen) + (sex-error form "case label written twice" value)) + (cons value seen)) + seen + (if (pair? (car parts)) (car parts) (list (car parts)))) + seen))) + (list) + clauses)) + ;;; #(a b c) is a brace initializer. A `:' inside one ends a type and ;;; turns the whole thing into a C99 compound literal: ;;; #(struct point : 1 2) is (struct point){1, 2}, and the type is diff --git a/tests/codegen.scm b/tests/codegen.scm index 24b816b..9beb4eb 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -35,6 +35,23 @@ (not (followed-by? (in-fn "(switch a (case 1 (do (var x int 1) (g x))))") "{" "{")))) + ;; (case (1 2) ...) is two labels, so (case (+ 1 1) ...) came out as + ;; three, the first of them `case +:' + (test-group "case labels" + (test-assert "a list of them is a case each" + (followed-by? (in-fn "(switch a (case (1 B) (g a)))") "case 1:" "case B:")) + (test-assert "an operator is not one" + (reports? (in-fn "(switch a (case (+ 1 1) (g a)))") "a case label is a value")) + (test-assert "nor is an expression in the list" + (reports? (in-fn "(switch a (case (1 (- 2)) (g a)))") "a case label is a value")) + (test-assert "a value is written once" + (reports? (in-fn "(switch a (case (1 2 1) (g a)))") "case label written twice")) + (test-assert "in the whole switch" + (reports? (in-fn "(switch a (case 1 (g a)) (case/fallthrough (2 1)) (default (g b)))") + "case label written twice")) + (test-assert "each switch apart" + (emits? (in-fn "(switch a (case 1 (g a))) (switch b (case 1 (g b)))") "case 1:"))) + ;; c-switch handed its scrutinee straight to `cat', which only works ;; when it is an atom. Anything else was displayed as a raw ;; s-expression: `switch ((%. e type))'. -- 2.52.0 From 47b98e41df922063b9725ab640c89f9a611a97db Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 17:04:20 +0300 Subject: [PATCH 16/74] keep the qualifiers written on a wildcard (const _) parsed to a type variable, which had nowhere to keep the const, so the type it was solved to came out without one -- for (const _) and for the target of (* const _) alike. --- infer.scm | 30 +++++++++++++++++------------- tests/codegen.scm | 9 +++++++++ 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/infer.scm b/infer.scm index 0dfca63..9b6bc13 100644 --- a/infer.scm +++ b/infer.scm @@ -52,11 +52,13 @@ ;;; A type variable is a mutable cell. `ref' is #f while unsolved and ;;; the type it stands for once bound -- union-find, with the path -;;; compression done in `resolve'. +;;; compression done in `resolve'. `quals' are the ones written on it -- +;;; `(const _)' -- and go onto whatever it is bound to. (define-record-type - (%make-tvar ref) + (%make-tvar ref quals) tvar? - (ref tvar-ref tvar-ref-set!)) + (ref tvar-ref tvar-ref-set!) + (quals tvar-quals tvar-quals-set!)) ;;; A primitive or otherwise nominal type. `name' is the list of words ;;; making it up, so `int', `(unsigned int)' and `(long long)' are all @@ -113,7 +115,7 @@ (quals alias-quals)) (define (fresh-tvar) - (%make-tvar #f)) + (%make-tvar #f (list))) ;;; Follow a bound variable to what it stands for, compressing the path ;;; on the way out. Every procedure that looks at a type's shape starts @@ -197,7 +199,7 @@ ;; The type-level wildcard. It is a fresh variable wherever it ;; appears, which is what makes partial types -- `(* _)', `(¤ _ 4)' ;; -- fall out for free rather than needing their own grammar. - ((equal? words '(_)) (fresh-tvar)) + ((equal? words '(_)) (with-quals (fresh-tvar) quals)) ((and (null? (cdr words)) (get-underlying-type (car words))) => (lambda (target) (make-alias (car words) (parse-type target) quals))) @@ -262,20 +264,22 @@ (if (list? s) s (list s)))) ;;; Re-qualify a parsed type, for the grouping case `(const (struct s))' -;;; where the qualifier is read before the thing it qualifies. +;;; where the qualifier is read before the thing it qualifies, and for a +;;; variable solved to a type: `(* const _)' against `(const int)' says +;;; const once. (define (with-quals type quals) + (define (plus written) (append quals (remove (lambda (q) (memq q quals)) written))) (if (null? quals) type - (cond ((prim-type? type) (make-prim (prim-name type) - (append quals (prim-quals type)))) - ((ptr-type? type) (make-ptr (ptr-target type) - (append quals (ptr-quals type)))) + (cond ((prim-type? type) (make-prim (prim-name type) (plus (prim-quals type)))) + ((ptr-type? type) (make-ptr (ptr-target type) (plus (ptr-quals type)))) ((agg-type? type) (make-agg (agg-kind type) (agg-name type) (agg-spelling type) - (append quals (agg-quals type)))) + (plus (agg-quals type)))) ((alias-type? type) (make-alias (alias-name type) (alias-expansion type) - (append quals (alias-quals type)))) + (plus (alias-quals type)))) + ((tvar? type) (tvar-quals-set! type (plus (tvar-quals type))) type) (else type)))) ;;; --------------------------------------------------------------- @@ -406,7 +410,7 @@ ;; Without recursive types this cannot trigger. It is four lines, ;; and the alternative to having it is a hang. ((occurs? v t) (sex-error form "recursive type" (unparse-type v))) - (else (tvar-ref-set! v t) #t))) + (else (tvar-ref-set! v (with-quals t (tvar-quals v))) #t))) (define (occurs? v type) (let ((t (resolve type))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 9beb4eb..588c2f4 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -605,6 +605,15 @@ (emits? "(typedef count int) (fn g () count (return 0)) (fn f () void (var x _ (g)))" "count x = g()")) + ;; a variable had nowhere to keep a qualifier written on it, and + ;; what it was solved to came out without + (test-assert "a qualified wildcard keeps its qualifier" + (emits? (in-fn "(var k (const _) 5)") "const int k = 5")) + (test-assert "behind a pointer too" + (emits? (in-fn "(var p (* const _) (& a))") "const int * p = &a")) + (test-assert "and says it once, solved to a type already saying it" + (emits? (in-fn "(var k (const int) 1) (var p (* const _) (& k))") + "const int * p = &k")) ;; a compound literal carries its own type, where a brace ;; initializer has none and takes one from its context (test-assert "a compound literal answers a bare wildcard" -- 2.52.0 From ad1825e8a8e24fea38d30e533362b95eace437cb Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 17:04:20 +0300 Subject: [PATCH 17/74] type an operator's result without qualifiers The spelling was the first operand's, so (+ k 1) with k const was a const int and (+ 1 k) was not; a value has no qualifiers either way. --- infer.scm | 11 +++++++++++ semen.scm | 9 +++++++-- tests/codegen.scm | 9 +++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/infer.scm b/infer.scm index 9b6bc13..c5f7f12 100644 --- a/infer.scm +++ b/infer.scm @@ -39,6 +39,7 @@ underlying c-primitive? decay + unqualified ;; The boundary parse-type @@ -151,6 +152,16 @@ ((fn-type? t) (make-ptr t (list))) (else (resolve type))))) +;;; TYPE as a value has it: qualifiers belong to an object, not to what +;;; is read out of one. `(const int)' -> `int', `(* const char)' as is. +(define (unqualified type) + (let ((t (resolve type))) + (cond ((prim-type? t) (make-prim (prim-name t) (list))) + ((ptr-type? t) (make-ptr (ptr-target t) (list))) + ((agg-type? t) (make-agg (agg-kind t) (agg-name t) (agg-spelling t) (list))) + ((alias-type? t) (make-alias (alias-name t) (alias-expansion t) (list))) + (else t)))) + ;;; --------------------------------------------------------------- ;;; Surface -> IR ;;; --------------------------------------------------------------- diff --git a/semen.scm b/semen.scm index 7ad2472..d484a54 100644 --- a/semen.scm +++ b/semen.scm @@ -1391,8 +1391,10 @@ ;;; ;;; (var p _ (+ a 1)) a : (¤ int 4) -> int * p = a + 1; ;;; not int p[4] = a + 1; +;;; An operator gives a value, which has no qualifiers: (+ k 1) with +;;; k : (const int) is an int, whichever side k is on (define (decayed written type) - (if (array-type? type) (unparse-type (decay type)) written)) + (if (array-type? type) (unparse-type (decay type)) (value-type written))) (define (promoted-type written) (and written (promoted written (underlying (parse-type written))))) @@ -1402,7 +1404,10 @@ (any (lambda (word) (memq word '(char short bool _Bool))) (prim-name type))) 'int - written)) + (value-type written))) + +(define (value-type written) + (unparse-type (unqualified (parse-type written)))) ;;; `char' and `short' promote to `int', so the ranks start there (define (conversion-rank type) diff --git a/tests/codegen.scm b/tests/codegen.scm index 588c2f4..c39b4b7 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -614,6 +614,15 @@ (test-assert "and says it once, solved to a type already saying it" (emits? (in-fn "(var k (const int) 1) (var p (* const _) (& k))") "const int * p = &k")) + ;; an operator's result is a value, which has no qualifier -- the + ;; spelling was the first operand's, so it had one only that way round + (test-assert "a sum is unqualified" + (emits? (in-fn "(var k (const int) 1) (var j _ (+ k 1))") " int j = k + 1")) + (test-assert "whichever side the qualified operand is on" + (emits? (in-fn "(var k (const int) 1) (var j _ (+ 1 k))") " int j = 1 + k")) + (test-assert "and so is a pointer it gives" + (emits? (in-fn "(var s (* char) 0) (var p (const * char) s) (var q _ (+ p 1))") + "char * q = p + 1")) ;; a compound literal carries its own type, where a brace ;; initializer has none and takes one from its context (test-assert "a compound literal answers a bare wildcard" -- 2.52.0 From f30c0733e39534a388ae8699e577e810b3be73ab Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 17:04:20 +0300 Subject: [PATCH 18/74] type a pointer difference as ptrdiff-t The join took the first pointer, so (- p q) declared the distance between two pointers as a third. --- semen.scm | 14 +++++++++++++- tests/codegen.scm | 9 +++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/semen.scm b/semen.scm index d484a54..74cfc83 100644 --- a/semen.scm +++ b/semen.scm @@ -1308,7 +1308,13 @@ `(closure ,(arglist-types (second expr)) ,(third expr)))) ;; `c-and' and `c-or' are the names from before `&&' and `||' ((== != < > <= >= && |\|\|| ! c-and c-or) 'bool) - ((+ - / %) (arithmetic-type expr env)) + ;; one pointer from another is how far apart they are + ((-) (if (and (= 3 (length expr)) + (every (lambda (operand) (address? (expression-type operand env))) + (cdr expr))) + 'ptrdiff-t + (arithmetic-type expr env))) + ((+ / %) (arithmetic-type expr env)) ;; the bitwise operators join like the arithmetic ones ((^ |\||) (arithmetic-type expr env)) ;; a shift is the promoted left operand, not a join: @@ -1351,6 +1357,12 @@ #f (cdr expr))) +;;; A pointer, or an array that is one as an operand +(define (address? written) + (and written + (let ((type (underlying (parse-type written)))) + (or (ptr-type? type) (array-type? type))))) + (define (arith-join left right) (cond ((not left) right) diff --git a/tests/codegen.scm b/tests/codegen.scm index c39b4b7..e7fa82c 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -623,6 +623,15 @@ (test-assert "and so is a pointer it gives" (emits? (in-fn "(var s (* char) 0) (var p (const * char) s) (var q _ (+ p 1))") "char * q = p + 1")) + ;; the join took the first pointer, and declared the distance one + (test-assert "one pointer from another is a distance" + (emits? (in-fn "(var p (* int) 0) (var q (* int) 0) (var d _ (- p q))") + "ptrdiff_t d = p - q")) + (test-assert "an array decays to one for it" + (emits? (in-fn "(var xs [int 4]) (var p (* int) xs) (var d _ (- p xs))") + "ptrdiff_t d = p - xs")) + (test-assert "a number from a pointer is still a pointer" + (emits? (in-fn "(var p (* int) 0) (var r _ (- p 1))") "int * r = p - 1")) ;; a compound literal carries its own type, where a brace ;; initializer has none and takes one from its context (test-assert "a compound literal answers a bare wildcard" -- 2.52.0 From 9bbf2dcdafdd0de86eb32d8eacea73468c86649e Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 17:04:20 +0300 Subject: [PATCH 19/74] promote a lone arithmetic operand One operand was joined with nothing and came back as it was, so (- c) over a char was a char where C makes it an int. --- semen.scm | 11 +++++++---- tests/codegen.scm | 7 +++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/semen.scm b/semen.scm index 74cfc83..5efc7bd 100644 --- a/semen.scm +++ b/semen.scm @@ -1351,11 +1351,14 @@ ;;; (+ (& p) 1) -> (* (struct point)) ;;; ;;; `unsigned int' against `int' answers `int', where C says otherwise. +;;; One operand is promoted on its own: (- c), c : char -> int (define (arithmetic-type expr env) - (fold (lambda (operand joined) - (arith-join joined (expression-type operand env))) - #f - (cdr expr))) + (if (null? (cddr expr)) + (promoted-type (expression-type (second expr) env)) + (fold (lambda (operand joined) + (arith-join joined (expression-type operand env))) + #f + (cdr expr)))) ;;; A pointer, or an array that is one as an operand (define (address? written) diff --git a/tests/codegen.scm b/tests/codegen.scm index e7fa82c..0f40d62 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -632,6 +632,13 @@ "ptrdiff_t d = p - xs")) (test-assert "a number from a pointer is still a pointer" (emits? (in-fn "(var p (* int) 0) (var r _ (- p 1))") "int * r = p - 1")) + ;; one operand was a join with nothing, which left it unpromoted + (test-assert "a negation promotes its operand" + (emits? (in-fn "(var c char 1) (var n _ (- c))") "int n = -c")) + (test-assert "so does a unary plus" + (emits? (in-fn "(var h short 1) (var n _ (+ h))") "int n = +h")) + (test-assert "and leaves a wide one as it is" + (emits? (in-fn "(var l long 1) (var n _ (- l))") "long n = -l")) ;; a compound literal carries its own type, where a brace ;; initializer has none and takes one from its context (test-assert "a compound literal answers a bare wildcard" -- 2.52.0 From a4ab04995d3086c491792500a1c952b2f732fb03 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 17:04:20 +0300 Subject: [PATCH 20/74] refuse _ in a pub var's type Importers declare a pub var from its type alone, with nothing to solve a wildcard against, so (pub var n _ 42) reached them as extern _ n. --- sex-modules.scm | 15 +++++++++++++++ tests/encapsulation.scm | 9 +++++++++ 2 files changed, 24 insertions(+) diff --git a/sex-modules.scm b/sex-modules.scm index a91da8f..466e8c5 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -138,6 +138,7 @@ (reverse (fold (lambda (form acc) + (check-written-out form) (fold (lambda (use acc) (check-type-use form use visible hidden acc)) acc (append-map (lambda (type) (type-uses type #f)) @@ -145,6 +146,20 @@ (list) forms)))) +;;; Importers declare a pub var from its type, not its initializer, so +;;; there is nothing on their side to solve a `_' with +(define (check-written-out form) + (match form + (('pub 'var . _) + (match (strip-header-comments form 4) + (('pub 'var name type . _) + (when (let wildcard? ((t type)) + (or (eq? t '_) (and (pair? t) (any wildcard? t)))) + (sex-error form "a pub var's type is what importers declare it with; write it out" + name))) + (_ #f))) + (_ #f))) + ;;; USE is (name . behind-a-pointer?) (define (check-type-use form use visible hidden acc) (let* ((name (car use)) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index bff967c..b666c2a 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -530,6 +530,15 @@ ahead of its pub forms." (test "nor a private fn's" '() (interface-of "(record cell ((v int))) (fn f ((c cell)) void)")) + ;; importers are given the declaration, not the initializer, so `_' + ;; reached them unsolved: `extern _ n' + (test-assert "a pub var's type is written out" + (interface-reports? "(pub var n _ 42)" "write it out")) + (test-assert "all of it" + (interface-reports? "(pub var p (* _) 0)" "write it out")) + (test "a private one is solved where it is" + '() + (interface-of "(var n _ 42)")) (test-assert "held by value it is an error" (interface-reports? "(record cell ((v int))) (pub record shape ((c cell)))" "held by value")) -- 2.52.0 From ba08695355c37dee2822a9ff5775a19c9bd71fd8 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 17:04:20 +0300 Subject: [PATCH 21/74] give importers the private macros a pub one expands into Only pub macros crossed, so one built on a private macro expanded in the importer into a call of a C function nothing defines. --- sex-modules.scm | 34 +++++++++++++++++++++++++++++++++- tests/modules/check.scm | 5 +++-- tests/modules/shelf-app.sex | 1 + tests/modules/shelf/page.sex | 5 +++++ 4 files changed, 42 insertions(+), 3 deletions(-) diff --git a/sex-modules.scm b/sex-modules.scm index 466e8c5..ae073d2 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -115,7 +115,39 @@ (interface-forms raw-forms)))) (define (interface-forms raw-forms) - (reverse (fold process-public-interface-form (list) raw-forms))) + (let ((helpers (helper-macros raw-forms))) + (reverse (fold (lambda (form acc) + (if (memq form helpers) + (cons form acc) + (process-public-interface-form form acc))) + (list) + raw-forms)))) + +;;; The private macros a pub one expands into, and the ones those do: +;;; the importer expands them all, the way a C header that defines a +;;; macro has to define what it uses too +(define (helper-macros raw-forms) + (let* ((macro-name (lambda (form) + (match form + (('defmacro (name . _) . _) name) + (('pub 'defmacro (name . _) . _) name) + (_ #f)))) + (private (filter (lambda (form) (and (macro-name form) (not (pub-form? form)))) + raw-forms)) + (mentions (lambda (form name) + (let walk ((x (cdr form))) + (or (eq? x name) (and (pair? x) (or (walk (car x)) (walk (cdr x))))))))) + (let grow ((needed (list)) + (users (filter (lambda (form) (and (macro-name form) (pub-form? form))) + raw-forms))) + (let ((more (filter (lambda (form) + (and (not (memq form needed)) + (any (lambda (user) (mentions user (macro-name form))) + users))) + private))) + (if (null? more) + needed + (grow (append needed more) more)))))) ;;; What importers can see of a module's types ;;; diff --git a/tests/modules/check.scm b/tests/modules/check.scm index b882c74..8aabec4 100644 --- a/tests/modules/check.scm +++ b/tests/modules/check.scm @@ -30,7 +30,8 @@ ;;; ;;; A module in a directory of its own finds its imports beside itself, ;;; not beside the unit importing it: shelf-app imports shelf/book, and -;;; book its siblings page, with `pub', and spine, without. +;;; book its siblings page, with `pub', and spine, without. A pub macro +;;; of page's expands into a private one, which crosses with it. ;;; ;;; make check-modules @@ -95,7 +96,7 @@ "--" (built "book.o") (built "page.o")))) (test "and the app runs through it" - '("pages 2 3") + '("pages 2 3" "number 2") (output-of (built "shelf-app"))) (test "the app runs through both" diff --git a/tests/modules/shelf-app.sex b/tests/modules/shelf-app.sex index d97ca10..5d4977c 100644 --- a/tests/modules/shelf-app.sex +++ b/tests/modules/shelf-app.sex @@ -6,4 +6,5 @@ (printf "pages %d %d\n" (. (second-page (& b)) number) (. (page-after (second-page (& b))) number)) + (printf "number %d\n" (page-number (second-page (& b)))) (return 0)) diff --git a/tests/modules/shelf/page.sex b/tests/modules/shelf/page.sex index 42c9585..0ff9fdf 100644 --- a/tests/modules/shelf/page.sex +++ b/tests/modules/shelf/page.sex @@ -2,3 +2,8 @@ (pub fn page-after ((p page)) page (return #(page : (+ (. p number) 1)))) + +;;; number-of is private, but page-number expands into it, so importers +;;; are given both, the way a C header carries a helper macro too +(defmacro (number-of p) `(. ,p number)) +(pub defmacro (page-number p) `(number-of ,p)) -- 2.52.0 From 41945606f6f7a954b325de2b13c290f32b22395f Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 17:30:47 +0300 Subject: [PATCH 22/74] read a string's escapes the way C spells them An escape the reader did not know lost its backslash, so "\x41" read as "x41" and "\012" as NUL and "12". A string is text, so \x and octal reach only as far as ASCII; past it, \u and \U name the character. --- reader.scm | 63 ++++++++++++++++++++++++++++++++++++++++-------- tests/reader.scm | 23 ++++++++++++++++++ 2 files changed, 76 insertions(+), 10 deletions(-) diff --git a/reader.scm b/reader.scm index 5f75024..f1e15fe 100644 --- a/reader.scm +++ b/reader.scm @@ -468,22 +468,65 @@ (cond ((eof-object? c) (error "Unterminated string literal")) ((char=? c #\") (list->string (reverse chars))) - ((char=? c #\\) (loop (cons (read-escape port) chars))) + ((char=? c #\\) (let ((escaped (read-escape port))) + (loop (if escaped (cons escaped chars) chars)))) (else (loop (cons c chars))))))) +;;; C's escapes, each one character of the string, or #f for a backslash +;;; ending a line, which joins it to the next. A string is text, so \x +;;; and octal, bytes to C, reach only as far as ASCII: past it the +;;; character is written as itself or its \u. +;;; +;;; \x41 \101 A -> A \012 -> newline é -> é (define (read-escape port) (let ((c (get-ch port))) (cond ((eof-object? c) (error "Unterminated string literal")) - ((char=? c #\n) #\newline) - ((char=? c #\t) #\tab) - ((char=? c #\r) #\return) - ((char=? c #\a) #\alarm) - ((char=? c #\b) #\backspace) - ((char=? c #\f) (integer->char 12)) - ((char=? c #\v) (integer->char 11)) - ((char=? c #\0) #\nul) - (else c)))) ; \" \\ and anything else: literal + ((assv c simple-escapes) => cdr) + ((char=? c #\newline) #f) + ((digit-in 8 c) => (lambda (d) (ascii (more-digits port 8 2 d)))) + ((char=? c #\x) + (let ((d (digit-in 16 (peek port)))) + (unless d (error "\\x needs a hex digit")) + (get-ch port) + (ascii (more-digits port 16 #f d)))) + ((char=? c #\u) (code-point port 4)) + ((char=? c #\U) (code-point port 8)) + (else (error "unknown escape" (string #\\ c)))))) + +(define simple-escapes + (list (cons #\n #\newline) (cons #\t #\tab) (cons #\r #\return) + (cons #\a #\alarm) (cons #\b #\backspace) + (cons #\f (integer->char 12)) (cons #\v (integer->char 11)) + (cons #\\ #\\) (cons #\" #\") (cons #\' #\') (cons #\? #\?))) + +(define (digit-in radix c) + (and (char? c) (string->number (string c) radix))) + +;;; N, with up to MOST more digits of RADIX read onto it; any number of +;;; them for MOST #f +(define (more-digits port radix most n) + (let loop ((n n) (left most)) + (let ((d (and (or (not left) (> left 0)) (digit-in radix (peek port))))) + (if d + (begin (get-ch port) (loop (+ (* n radix) d) (and left (- left 1)))) + n)))) + +(define (ascii n) + (if (> n 127) + (error "a byte past ASCII is not text; write the character or \\u, or a [u8 N] array for bytes") + (integer->char n))) + +(define (code-point port digits) + (let loop ((n 0) (left digits)) + (if (= left 0) + (if (or (<= #xD800 n #xDFFF) (> n #x10FFFF)) + (error "no character has this code point") + (integer->char n)) + (let ((d (digit-in 16 (peek port)))) + (unless d (error "\\u takes four hex digits and \\U eight")) + (get-ch port) + (loop (+ (* n 16) d) (- left 1)))))) (define (skip-block-comment port depth) (if (= depth 0) diff --git a/tests/reader.scm b/tests/reader.scm index 82944a1..86412a6 100644 --- a/tests/reader.scm +++ b/tests/reader.scm @@ -92,6 +92,29 @@ ;; a name that only begins like a number is still a name (reader-test '(3dmath.h) "3dmath.h") + ;; A string is text, and an escape is one of its characters, spelled + ;; the way C spells it. An escape the reader did not know lost its + ;; backslash, so "\x41" read as "x41" and "\012" as NUL and "12" + (reader-test '("A" "A" "A" "A") "\"\\x41\" \"\\101\" \"\\u0041\" \"\\U00000041\"") + (reader-test '("\n" "'?" "\x7f;") "\"\\012\" \"\\'\\?\" \"\\x7f\"") + (reader-test '("é" "😀") "\"\\u00e9\" \"\\U0001F600\"") + ;; a backslash ending a line joins it to the next, as in C + (reader-test '("ab") "\"a\\\nb\"") + ;; C reads \xff and \377 as a byte, which text has none of: what is + ;; past ASCII is written as the character, or its \u + (test "a byte past ASCII is not text" + "a byte past ASCII is not text; write the character or \\u, or a [u8 N] array for bytes" + (read-error "\"\\xff\"")) + (test "in octal neither" #t (string? (read-error "\"\\377\""))) + (test "nor is a run of hex digits, which \\x takes all of" + #t (string? (read-error "\"\\x41BC\""))) + (test "an escape C has not is an error" "unknown escape" (read-error "\"\\q\"")) + (test "\\x needs a digit" "\\x needs a hex digit" (read-error "\"\\xg\"")) + (test "\\u takes four" + "\\u takes four hex digits and \\U eight" (read-error "\"\\u41\"")) + (test "a surrogate is no character" + "no character has this code point" (read-error "\"\\uD800\"")) + ;; `;' comments are preserved as (comment "...") forms (reader-test '((comment " hi")) "; hi") (reader-test '((comment ";; Prototypes")) ";;; Prototypes") -- 2.52.0 From 192ed2ba64cc8788a6759a7412b901a8c8299ab9 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 17:30:47 +0300 Subject: [PATCH 23/74] refuse a char literal that is not one byte MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A char is C's, and #\λ came out a multi-character constant whose value is the C compiler's to choose. --- reader.scm | 5 +++++ tests/reader.scm | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/reader.scm b/reader.scm index f1e15fe..af80679 100644 --- a/reader.scm +++ b/reader.scm @@ -445,10 +445,15 @@ ("delete" . #\delete) ("escape" . #\escape) ("alarm" . #\alarm) ("backspace" . #\backspace))) +;;; A char is C's, one byte: #\λ was a multi-character constant, whose +;;; value is the C compiler's to choose (define (read-char-lit port) (let ((first (get-ch port))) (when (eof-object? first) (error "Unexpected end of input in character literal")) + (when (> (char->integer first) 127) + (error "a char is one byte, and this is not: write its code point, or a string" + first)) (if (char-alphabetic? first) (let ((rest (read-atom-string port))) (if (string=? rest "") diff --git a/tests/reader.scm b/tests/reader.scm index 86412a6..dde7bbe 100644 --- a/tests/reader.scm +++ b/tests/reader.scm @@ -115,6 +115,14 @@ (test "a surrogate is no character" "no character has this code point" (read-error "\"\\uD800\"")) + ;; A char is C's, one byte, and #\λ came out a multi-character + ;; constant whose value is the compiler's to choose + (test "a char is one byte" + "a char is one byte, and this is not: write its code point, or a string" + (read-error "#\\λ")) + (test "Latin-1 is no exception" #t (string? (read-error "#\\é"))) + (reader-test '(#\a #\~ #\space) "#\\a #\\~ #\\space") + ;; `;' comments are preserved as (comment "...") forms (reader-test '((comment " hi")) "; hi") (reader-test '((comment ";; Prototypes")) ";;; Prototypes") -- 2.52.0 From 6e4ad81538da29270bd2b0a6dc591c4f86d65286 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 18:59:49 +0300 Subject: [PATCH 24/74] splice a $ nested in a macro's $ Only the outermost was taken apart, so ($ a ($ b c)) left the inner one an unknown toplevel form, and in a body a call of $ in the C. --- semen.scm | 7 ++++++- tests/codegen.scm | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/semen.scm b/semen.scm index 5efc7bd..11d2241 100644 --- a/semen.scm +++ b/semen.scm @@ -71,7 +71,7 @@ ;; the macro was used (cond ((splice-form? res) - (append (map (lambda (f) (stamp-form-source! f src)) (cdr res)) + (append (map (lambda (f) (stamp-form-source! f src)) (spliced res)) rest-forms)) ((null? res) rest-forms) (else @@ -80,6 +80,11 @@ (define (splice-form? form) (and (pair? form) (list? form) (eq? '$ (car form)))) +;;; ($ a ($ b c)) is a, b and c, so a macro may build its splice out of +;;; others' +(define (spliced form) + (append-map (lambda (f) (if (splice-form? f) (spliced f) (list f))) (cdr form))) + (define (match-sex-form sex-form acc) (match sex-form ((or ('fn . _) diff --git a/tests/codegen.scm b/tests/codegen.scm index 0f40d62..f52b6a5 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -719,6 +719,23 @@ (test-assert "and ($) is nothing at all" (emits? "(defmacro (quiet) (list '$)) (quiet) (fn f () int (return 1))" "return 1;")) + ;; only the outermost was spliced: an inner one was an unknown + ;; toplevel form, and in a body a call of `$' + (test-assert "a $ inside one splices too" + (emits? "(defmacro (pairs) (list '$ (list '$ '(fn a () int (return 1))) + '(fn b () int (return 2)))) + (pairs)" + "a (void)")) + (test-assert "in a body as well" + (let ((c (silently + (lambda () + (sex->c "(defmacro (twice) (list '$ (list '$ '(g 1)) '(g 2))) + (fn f () void (twice))"))))) + (and (string-contains c "g(1);") (string-contains c "g(2);") + (not (string-contains c "$"))))) + (test-assert "and an inner ($) is nothing" + (emits? "(defmacro (quiet) (list '$ (list '$))) (quiet) (fn f () int (return 1))" + "return 1;")) ;; without `$' a list is one form, so a head that is itself a form ;; stays a call rather than becoming two statements (test-assert "a computed callee stays one form" -- 2.52.0 From c8a39b7e62788673b498b773cae07c41b8e297df Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 18:59:49 +0300 Subject: [PATCH 25/74] write a #line file name as a C string literal It was pasted between quotes as it came, so a quote in the path ended it, a backslash began an escape, and ?? read as a trigraph. --- fmt-c-writer.scm | 5 +++-- tests/line-directives.scm | 16 ++++++++++++---- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 2b84f11..44ea4da 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -41,8 +41,9 @@ (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 ,(cadr src) ,(fmt #f #\" (car src) #\"))) + ;; second argument verbatim, so the file name arrives as the string + ;; literal C reads it as: a quote, a backslash or a ?? in it escaped. + `(%line ,(cadr src) ,(fmt #f (c-in-expr (c-literal (car src)))))) (define (walk-body stmts) "Walk a statement list, re-anchoring each statement that has a known diff --git a/tests/line-directives.scm b/tests/line-directives.scm index b27286e..877b56b 100644 --- a/tests/line-directives.scm +++ b/tests/line-directives.scm @@ -96,10 +96,10 @@ ;;; ------------------------------------------------------------------ ;;; Pipeline and #line accounting -(define (compile-to-c source) - "Run reader -> semen -> writer on SOURCE, read from fixture.sex, +(define (compile-to-c source #!optional (file "fixture.sex")) + "Run reader -> semen -> writer on SOURCE, read from FILE, returning the generated C." - (let ((forms (read-source source "fixture.sex"))) + (let ((forms (read-source source file))) (with-output-to-string (lambda () (emit-c (semen-process forms)))))) @@ -244,4 +244,12 @@ after that is one more. Lines before the first directive get #f." (delete-duplicates (map (lambda (quoted) (pathname-strip-directory (string-trim-both quoted #\"))) - (filter values (map directive-file (split-lines c-out)))))))) + (filter values (map directive-file (split-lines c-out)))))) + ;; it was pasted between quotes as it came: a quote ended it, a + ;; backslash began an escape, and ??= was a trigraph + (test-assert "and is written the way C writes a string" + (string-suffix? "/we\\\"ird\\\\a?\\?=.sex\"" + (directive-file + (find directive-line + (split-lines (compile-to-c "(fn f () int (return 1))" + "we\"ird\\a??=.sex")))))))) -- 2.52.0 From c7990e6613facf136bf91b8424f724d419ab2f7f Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 19:06:55 +0300 Subject: [PATCH 26/74] rename the reader's number record to number-literal sex-fmt-c exports a c-literal? of its own, and the writer imports both; which one it got depended on the order of its imports. --- fmt-c-writer.scm | 5 +++-- reader.scm | 34 +++++++++++++++++----------------- semen.scm | 11 ++++++----- 3 files changed, 26 insertions(+), 24 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 44ea4da..895d1d3 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -12,7 +12,7 @@ sex-fmt-c matchable (chicken irregex) ; unkebabify - reader ; c-literal? + reader ; number-literal? srfi-1 ; lists srfi-13 ; strings types ; array-bound?, named-arg? @@ -339,7 +339,8 @@ forms, and what remains." (remove comment-form? (cdr clause))))) (if (pair? parts) (fold (lambda (value seen) - (unless (or (number? value) (char? value) (c-literal? value) + (unless (or (number? value) (char? value) + (number-literal? value) (and (symbol? value) (not (operator-arity value)))) (sex-error form "a case label is a value" (car parts))) (when (member value seen) diff --git a/reader.scm b/reader.scm index af80679..162b0b6 100644 --- a/reader.scm +++ b/reader.scm @@ -31,9 +31,9 @@ current-features platform-features - c-literal? - c-literal-value - c-literal-suffix) + number-literal? + number-literal-value + number-literal-suffix) ;;; Sentinels for structural tokens (define close-paren (list '%close-paren)) @@ -223,8 +223,8 @@ (cond ((exact-integer? n) (cond ((> (abs n) +ullong-max+) (error "too large for any C integer type" s)) - ((> n +llong-max+) (make-c-literal n "u" #f)) - ((< n +llong-min+) (list '- (make-c-literal (- n) "u" #f))) + ((> n +llong-max+) (make-number-literal n "u" #f)) + ((< n +llong-min+) (list '- (make-number-literal (- n) "u" #f))) (else n))) ((and (real? n) (inexact? n) (finite? n)) n) (else (error "C has no literal for this number" s)))) @@ -237,19 +237,19 @@ ;;; could round to another float, and 0.1L would ;;; lose all it has over one ;;; -1u -> (- 1u) which is what C reads it as too -(define-record-type - (make-c-literal value suffix digits) - c-literal? - (value c-literal-value) - (suffix c-literal-suffix) - (digits c-literal-digits)) +(define-record-type + (make-number-literal value suffix digits) + number-literal? + (value number-literal-value) + (suffix number-literal-suffix) + (digits number-literal-digits)) -(set-record-printer! +(set-record-printer! (lambda (literal port) - (display (or (c-literal-digits literal) - (number->string (c-literal-value literal))) + (display (or (number-literal-digits literal) + (number->string (number-literal-value literal))) port) - (display (c-literal-suffix literal) port))) + (display (number-literal-suffix literal) port))) (define suffixed-integer (irregex "(0[xX][0-9a-fA-F]+|0[bB][01]+|[0-9]+)([uU](?:ll|LL|l|L)?|(?:ll|LL|l|L)[uU]?)")) @@ -281,7 +281,7 @@ (widest (if (irregex-search "[uU]" suffix) +ullong-max+ +llong-max+))) (when (> n widest) (error "too large for its suffix" s)) - (make-c-literal n suffix #f))))) + (make-number-literal n suffix #f))))) ;;; 0x1.8p3 is 0x18 sixteenths times 2^3 (define (hex-float-literal body s) @@ -310,7 +310,7 @@ (define (float-literal n suffix digits s) (unless (in-range? n suffix) (error "C has no literal for this number" s)) - (make-c-literal n suffix digits)) + (make-number-literal n suffix digits)) ;;; A float overflows where it would round past FLT_MAX; a long double ;;; may be wider than any double, so whatever a double holds it does too diff --git a/semen.scm b/semen.scm index 11d2241..9c7bd2c 100644 --- a/semen.scm +++ b/semen.scm @@ -13,7 +13,7 @@ sex-modules types matchable ; pattern matching - reader ; c-literal + reader ; number-literal srfi-1 ; list routines srfi-69 ; hash tables utils @@ -1240,9 +1240,10 @@ ;;; 4000000000 -> (long long) 10L -> long ;;; 1.5f -> float 0.1L -> (long double) ;;; 0x1.8p3 -> double -(define (c-literal-type literal) - (let ((n (c-literal-value literal)) - (suffix (map char-downcase (string->list (c-literal-suffix literal))))) +(define (number-literal-type literal) + (let ((n (number-literal-value literal)) + (suffix (map char-downcase + (string->list (number-literal-suffix literal))))) (cond ((exact? n) (integer-literal-type n suffix)) ((memv #\f suffix) 'float) ((memv #\l suffix) '(long double)) @@ -1258,7 +1259,7 @@ (define (expression-type expr env) (cond - ((c-literal? expr) (c-literal-type expr)) + ((number-literal? expr) (number-literal-type expr)) ((and (number? expr) (exact? expr)) (integer-literal-type expr '())) ((number? expr) 'double) ((string? expr) '(* const char)) -- 2.52.0 From 04c3267bfe95ef8a4fae6cd75ebc7cc4111e7353 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 17 Oct 2026 17:35:47 +0300 Subject: [PATCH 27/74] type an indexed step of a member path (. q [pts 2] y) looked the step up as a field whole, so its type was lost: the next step guessed a value, and through an array of pointers wrote . for ->. --- semen.scm | 27 +++++++++++++++++++++++---- tests/codegen.scm | 18 ++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/semen.scm b/semen.scm index 9c7bd2c..5faf4e1 100644 --- a/semen.scm +++ b/semen.scm @@ -1180,8 +1180,10 @@ (let ((walked (drop-right (cddr form) (length fields)))) (sex-warning form "cannot type this; `.' reads it as a value" (if (null? walked) base `(|.| ,base ,@walked))))) - (step (list (if target '%-> 'dot-access) expr (car fields)) - (field-type (or target type) (car fields)) + (step (list (if target '%-> 'dot-access) + expr + (nested-step (car fields))) + (step-type (or target type) (car fields)) (cdr fields) (or told? (not type)))))))) @@ -1456,10 +1458,27 @@ (define (member-path-type type fields) (if (null? fields) type - (member-path-type (field-type (or (pointer-target type) type) - (car fields)) + (member-path-type (step-type (or (pointer-target type) type) + (car fields)) (cdr fields)))) +;;; What a step of a path gives: its field, or for [xs i] an element of +;;; the field xs, one for each index +(define (step-type type field) + (let ((t (field-type type (field-name field)))) + (if (and t (pair? field) (eq? '¤ (car field))) + (fold (lambda (index t) + (and t (or (array-element-type t) (pointer-target t)))) + t + (cddr field)) + t))) + +;;; [grid 1 2] as a step is [[grid 1] 2], as it is anywhere else +(define (nested-step field) + (if (and (pair? field) (eq? '¤ (car field)) (> (length field) 3)) + (list '¤ (nested-step (drop-right field 1)) (last field)) + field)) + (define (field-type type field) (let* ((fields (type-fields type)) (entry (and fields (assq field fields)))) diff --git a/tests/codegen.scm b/tests/codegen.scm index f52b6a5..0c6e560 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -4,6 +4,14 @@ (import srfi-13) +;;; Paths through arrays of a struct and of pointers to one +(define poly-src + (string-append + "(struct pt ((x int) (y int)))" + "(struct poly ((pts [(struct pt) 4]) (pp [* struct pt 4]) (grid [(struct pt) 2 3])))" + "(fn f ((q (* struct poly))) int" + " (return (+ (. q [pts 2] y) (. q [pp 0] y) (. q [grid 1 2] x))))")) + (define (in-fn body) (string-append "(fn f ((a int) (b int)) void " body ")")) @@ -971,6 +979,16 @@ (test-group "member access" (test-assert "a value reads with a dot" (emits? (in-line "(= (. p x) 1)") "p.x = 1")) + ;; an indexed step was looked up as a field whole, so its type was + ;; lost and the step after it guessed + (test-assert "an indexed step is its field's element" + (emits? poly-src "q->pts[2].y")) + (test-assert "and says so without a warning" + (not (warns? poly-src "cannot type"))) + (test-assert "so a pointer element is read through" + (emits? poly-src "q->pp[0]->y")) + (test-assert "and every index of one is written" + (emits? poly-src "q->grid[1][2].x")) (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 -- 2.52.0 From 42c76d07e617c4b79ba5a8f2a4430d006d72dd5d Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 17 Oct 2026 17:35:47 +0300 Subject: [PATCH 28/74] see a pointer through a typedef of one Only a written (* T) was a pointer, so with (typedef pt-ref (* pt)) a path read q as a value and a method found no type to dispatch on. --- semen.scm | 9 +++++---- tests/codegen.scm | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/semen.scm b/semen.scm index 5faf4e1..45fad89 100644 --- a/semen.scm +++ b/semen.scm @@ -1446,11 +1446,12 @@ ;;; `(* const char)' is flat: everything after the `*' is the target. ;;; `(& x)' builds the nested `(* (struct point))' and `unparse-type' ;;; writes the flat `(* struct point)', so both spellings turn up. +;;; (* T) -> T, and so for a typedef of one: (typedef pt-ref (* pt)) (define (pointer-target type) - (and (list? type) - (>= (length type) 2) - (eq? '* (car type)) - (unwrap-type (cdr type)))) + (cond ((and (list? type) (>= (length type) 2) (eq? '* (car type))) + (unwrap-type (cdr type))) + ((and (symbol? type) (get-underlying-type type)) => pointer-target) + (else #f))) ;;; 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 diff --git a/tests/codegen.scm b/tests/codegen.scm index 0c6e560..3c40ffe 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -4,6 +4,14 @@ (import srfi-13) +;;; A record reached through a typedef of a pointer to it +(define pt-ref-src + (string-append + "(record pt ((x int)))" + "(ops pt (fn get ((self (* pt))) int (return (. self x))))" + "(typedef pt-ref (* pt))" + "(fn f ((q pt-ref)) int (return (+ (. q x) (. (* q) x) (.get q))))")) + ;;; Paths through arrays of a struct and of pointers to one (define poly-src (string-append @@ -989,6 +997,14 @@ (emits? poly-src "q->pp[0]->y")) (test-assert "and every index of one is written" (emits? poly-src "q->grid[1][2].x")) + ;; only a written (* T) was a pointer, so a typedef of one read as a + ;; value, and a method could not find its receiver's type + (test-assert "a typedef of a pointer reads with an arrow" + (emits? pt-ref-src "q->x")) + (test-assert "dereferences to what it points at" + (not (warns? pt-ref-src "cannot type"))) + (test-assert "and calls its target's methods" + (emits? pt-ref-src "ptːget(q)")) (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 -- 2.52.0 From 32515c0eb8494785ee5e31f3f3698c44b25e17d4 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 17 Oct 2026 17:35:48 +0300 Subject: [PATCH 29/74] keep an array literal a global pointer is set to At file scope every compound literal was cut down to its braces, right for a value and not for an array a pointer points at: the address of a static object is a constant, and its braces alone the pointer's own. --- semen.scm | 61 +++++++++++++++++++++++++++++++++----- tests/codegen.scm | 19 +++++++++++- tests/sex-programs/c11.sex | 7 +++-- 3 files changed, 75 insertions(+), 12 deletions(-) diff --git a/semen.scm b/semen.scm index 45fad89..811f270 100644 --- a/semen.scm +++ b/semen.scm @@ -2042,7 +2042,13 @@ (walk-operands core (drop core 3) env)) core)) env))) - (copy-form-source! solved (map bare-braces solved))))) + (if (> (length solved) 3) + (copy-form-source! + solved + (append (take solved 3) + (map (cut bare-braces <> (third solved)) + (drop solved 3)))) + solved)))) (form (if qualifier (copy-form-source! resolved (cons qualifier core)) core))) @@ -2052,14 +2058,53 @@ ;;; 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: +;;; alone say the same. Not where it is an array a pointer is set to: +;;; that is the address of a static object, which is a constant, and its +;;; braces alone would be the pointer's own. TARGET is what FORM +;;; initializes, #f where nothing says. ;;; -;;; (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)) +;;; (var g t (t/a 1)) -> static t g = {.tag = tǂa, ...} +;;; (var p (* int) #([int 2] : 1 2)) -> static int * p = (int [2]){1, 2} +(define (bare-braces form target) + (if (not (vector? form)) + form + (let* ((parts (list-split (vector->list form) ':)) + (written (and (pair? (cdr parts)) (unwrap-type (car parts))))) + (if (and written (array-form? written) target (pointer-target target)) + form + (let ((elements (last parts))) + (list->vector + (map bare-braces elements + (element-targets (or written target) elements)))))))) + +;;; What each of ELEMENTS, in braces for TYPE, initializes: an element +;;; of an array, the fields of an aggregate in turn, or the one a `.name' +;;; before it names -- and #f where TYPE does not say +(define (element-targets type elements) + (let ((element (and type (array-form? type) (array-element-type type))) + (fields (and type (not (array-form? type)) (type-fields type)))) + (let loop ((es elements) (next (or fields (list))) (acc (list))) + (cond + ((null? es) (reverse acc)) + (element (loop (cdr es) next (cons element acc))) + ((designator-name (car es)) + => (lambda (name) + (let ((at (and fields + (find-tail (lambda (f) (eq? (car f) name)) fields)))) + (if (and at (pair? (cdr es))) + (loop (cddr es) (cdr at) (cons (second (car at)) (cons #f acc))) + (loop (cdr es) (list) (cons #f acc)))))) + (else (loop (cdr es) + (if (pair? next) (cdr next) next) + (cons (and (pair? next) (second (car next))) acc))))))) + +;;; .x -> x, as a designator names a field; #f for anything else +(define (designator-name x) + (and (symbol? x) + (let ((s (symbol->string x))) + (and (> (string-length s) 1) + (char=? #\. (string-ref s 0)) + (string->symbol (substring s 1)))))) ;;; Utils diff --git a/tests/codegen.scm b/tests/codegen.scm index 3c40ffe..89243fa 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -1061,7 +1061,24 @@ (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"))))) + (string-contains c "(*f)(int) = λ0_f")))) + ;; every compound literal lost its type at file scope, which is right + ;; for a value and not for an array a pointer is set to: that is the + ;; address of a static object, and its braces alone the pointer's own + (test-assert "an array a pointer is set to keeps its type" + (emits? "(var gp (* int) #([int 3] : 1 2 3))" "int * gp = (int [3]){1, 2, 3}")) + (test-assert "in a field named for it" + (emits? (string-append "(struct h ((p (* int)) (n int)))" + "(var g (struct h) #(.p #([int 2] : 1 2) .n 3))") + "{.p = (int [2]){1, 2}, .n = 3}")) + (test-assert "or one in its place" + (emits? (string-append "(struct h ((n int) (p (* int))))" + "(var g (struct h) #((struct h) : 3 #([int 2] : 1 2)))") + "{3, (int [2]){1, 2}}")) + (test-assert "while a value is still its braces" + (emits? (string-append "(struct pt ((x int))) (struct h2 ((a (struct pt))))" + "(var g (struct h2) #(#((struct pt) : 1)))") + "h2 g = {{1}}"))) ;; fmt-c kept the first star after a tag and dropped what followed it, ;; and took an enum's star for its list of values diff --git a/tests/sex-programs/c11.sex b/tests/sex-programs/c11.sex index 2081ca9..ad1582f 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 12" +(output "c11: 42 43 6 4 6 12 5" "trigraphs: what??! ??= ???( ??/") (return 0) @@ -29,6 +29,7 @@ (sum shape ((square ((side int))) (dot ()))) (var corner _ #(point : 2 3)) +(var primes (* int) #([int 3] : 2 3 5)) (var unit _ (shape/square 1)) (var pair [_ 2] #(#(point : 1 2) #(point : 3 4))) @@ -44,8 +45,8 @@ (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 %d\n" + (printf "c11: %d %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) (.area [pair 1])) + (sides unit) (.area corner) (.area [pair 1]) [primes 2]) (printf "trigraphs: %s\n" "what??! ??= ???( ??/") (return 0)) -- 2.52.0 From 1b59848b4230c0bfd36e003662785bf5e717f200 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 17 Oct 2026 17:35:48 +0300 Subject: [PATCH 30/74] keep an aggregate written in place behind a pointer A type was flattened word by word, a struct's body included, so (* (struct ((c int)))) came out struct c{ int; } *. --- fmt-c-writer.scm | 24 ++++++++++++++++++------ tests/codegen.scm | 12 ++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 895d1d3..df7f69a 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -7,7 +7,7 @@ (chicken module) (chicken string) (chicken syntax) - brev-separate ; fn, flatten + brev-separate ; fn fmt sex-fmt-c matchable @@ -447,6 +447,7 @@ forms, and what remains." (define (has-pointer-star? form) (and (pair? form) (not (structured-type? form)) + (not (inline-aggregate? form)) (or (memq '* form) (any has-pointer-star? (filter pair? form))))) @@ -476,11 +477,22 @@ forms, and what remains." (sex-error type "a fn type is a function pointer already: write (fn ...), not (* (fn ...))" type) (sex-error type "a pointer to an array is not supported" type)))) (if (atom? type) (atom-to-fmt-c type) - (flatten - (tree-map atom-to-fmt-c - (flatten - (list-join (reverse (list-split type '*)) - '(*))))))) + (type-words (list-join (reverse (list-split type '*)) '(*))))) + +;;; A type's words, flat, except that an aggregate written out in full is +;;; one of them, walked: (* (struct ((c int)))) is `struct {...} *' +(define (type-words items) + (append-map (lambda (item) + (cond ((inline-aggregate? item) (list (walk-type item))) + ((pair? item) (type-words item)) + ((null? item) (list)) + (else (list (atom-to-fmt-c item))))) + items)) + +;;; (struct ((c int))), (union u (...)), (enum (red green)): a body, not +;;; just a tag +(define (inline-aggregate? form) + (and (pair? form) (memq (car form) '(struct union enum)) (any list? (cdr form)))) (define (walk-fn-def form) (match form diff --git a/tests/codegen.scm b/tests/codegen.scm index 89243fa..ad12e28 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -790,6 +790,18 @@ (test-assert "and negation beside a binary operator" (emits? (in-fn "(var n int (+ (- a) b))") "-a + b"))) + ;; A type was flattened word by word, a struct written out in it + ;; included: (* (struct ((c int)))) came out `struct c{ int; } *' + (test-group "a pointer to an aggregate written in place" + (test-assert "keeps its fields" + (followed-by? "(struct h ((b (* (struct ((c int)))))))" "int c;" "} * b;")) + (test-assert "a pointer among them as well" + (emits? "(struct h ((b (* (struct ((p (* int)) (n int)))))))" "int * p;")) + (test-assert "and a qualifier before it" + (emits? "(struct h ((e (* const (union ((u int) (v float)))))))" "const union{")) + (test-assert "behind as many stars as are written" + (emits? "(struct h ((f (* * (struct ((c int)))))))" "} * * f;"))) + ;; Operands past what an operator takes were written as they came: ;; (< a b c) as C's own chain, which compares a boolean with c (test-group "operator arity" -- 2.52.0 From 06bbe4b97d89d3863cd7310ce780dfd7747ce4d4 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 17 Oct 2026 17:35:48 +0300 Subject: [PATCH 31/74] refuse a malformed enumerator Anything in the list but a name or (name value) was taken apart as if it were the pair: (! 1 2) came out ! = 1. --- fmt-c-writer.scm | 10 ++++++++-- tests/codegen.scm | 8 ++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index df7f69a..a40977c 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -574,8 +574,14 @@ forms, and what remains." ;;; red -> red, (wire-varint 0) -> wire_varint = 0 (define (walk-enumerator value) (match value - ((name expr) (list (atom-to-fmt-c name) (walk-expr expr))) - (_ (atom-to-fmt-c value)))) + (((? enumerator-name? name) expr) (list (atom-to-fmt-c name) (walk-expr expr))) + ((? enumerator-name?) (atom-to-fmt-c value)) + ;; anything else was taken apart as if it were the pair: (! 1 2) + ;; came out `! = 1' + (_ (sex-error value "an enumerator is a name, or (name value)" value)))) + +(define (enumerator-name? x) + (and (symbol? x) (not (operator-arity x)))) (define (walk-extern form) (match form diff --git a/tests/codegen.scm b/tests/codegen.scm index ad12e28..5c216c6 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -246,6 +246,14 @@ "enum color m = red")) (test-assert "a malformed enum is rejected with its location" (reports? "(enum)" "codegen.sex:1:")) + ;; anything else in the list was the name its head was and the + ;; value its second element: (! 1 2) came out `! = 1' + (test-assert "an enumerator is a name, or a name and a value" + (reports? "(enum color (red (! 1 2)))" "an enumerator is a name, or (name value)")) + (test-assert "and an operator is no name" + (reports? "(enum color (red (! 1)))" "an enumerator is a name, or (name value)")) + (test-assert "nor a value with no name" + (reports? "(enum color (red 7))" "an enumerator is a name, or (name value)")) ;; c-type handed the declarator's name to c-enum as the enum tag, ;; so this emitted `enum m { up, down }' with no variable at all (test-assert "an anonymous enum keeps the variable" -- 2.52.0 From ffa5e9b02c4068eb7ffac0703cb79a120103b03f Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 17 Oct 2026 17:35:48 +0300 Subject: [PATCH 32/74] write #() as {0} {} is C23's. #() is all zeros, which C11 spells {0}, whatever it initializes. --- fmt-c-writer.scm | 9 ++++++--- tests/codegen.scm | 13 +++++++++++++ tests/sex-programs/c11.sex | 7 ++++--- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index a40977c..776b726 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -359,13 +359,16 @@ forms, and what remains." ;;; language. `:' is the separator because it is the one thing that can ;;; be neither a type word nor an expression -- a named form would be a ;;; C identifier, and so shadowable (see issue #36). +;;; +;;; #() is all zeros, and C11 spells that {0}: {} came in only with C23 (define (walk-initializer elements) - (let ((parts (list-split (remove comment-form? elements) ':))) + (let ((parts (list-split (remove comment-form? elements) ':)) + (filled (lambda (es) (if (null? es) (list 0) (walk-designators es))))) (if (null? (cdr parts)) - (list->vector (walk-designators (car parts))) + (list->vector (filled (car parts))) (cons* '%compound (walk-type (maybe-unwrap-type (car parts))) - (walk-designators (cadr parts)))))) + (filled (cadr parts)))))) ;;; `.field value' is a designated initializer; anything else is ;;; positional. C lets the two be mixed, and nothing here stops it. A diff --git a/tests/codegen.scm b/tests/codegen.scm index 5c216c6..586420f 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -1095,6 +1095,19 @@ (emits? (string-append "(struct h ((n int) (p (* int))))" "(var g (struct h) #((struct h) : 3 #([int 2] : 1 2)))") "{3, (int [2]){1, 2}}")) + ;; #() is all zeros; {} says so only from C23, and {0} in C11 + (test-assert "empty braces are zeros" + (emits? "(struct pt ((x int))) (var g (struct pt) #())" "struct pt g = {0};")) + (test-assert "in a function and in a compound literal as well" + (emits? (string-append "(struct pt ((x int)))" + "(fn f () void (var p (struct pt) #((struct pt) :)))") + "(struct pt){0}")) + (test-assert "inside other braces" + (emits? (string-append "(struct pt ((x int))) (struct h ((a (struct pt)) (n int)))" + "(var g (struct h) #(#() 1))") + "{{0}, 1}")) + (test-assert "and for a scalar" + (emits? (in-fn "(var n int #())") "int n = {0};")) (test-assert "while a value is still its braces" (emits? (string-append "(struct pt ((x int))) (struct h2 ((a (struct pt))))" "(var g (struct h2) #(#((struct pt) : 1)))") diff --git a/tests/sex-programs/c11.sex b/tests/sex-programs/c11.sex index ad1582f..6065ed9 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 12 5" +(output "c11: 42 43 6 4 6 12 5 0" "trigraphs: what??! ??= ???( ??/") (return 0) @@ -30,6 +30,7 @@ (var corner _ #(point : 2 3)) (var primes (* int) #([int 3] : 2 3 5)) +(var origin point #()) (var unit _ (shape/square 1)) (var pair [_ 2] #(#(point : 1 2) #(point : 3 4))) @@ -45,8 +46,8 @@ (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 %d %d\n" + (printf "c11: %d %d %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) (.area [pair 1]) [primes 2]) + (sides unit) (.area corner) (.area [pair 1]) [primes 2] (. origin y)) (printf "trigraphs: %s\n" "what??! ??= ???( ??/") (return 0)) -- 2.52.0 From c0ed7ad9166bcb15ad9e6c1285ad68637b49b6f8 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 17 Oct 2026 17:35:48 +0300 Subject: [PATCH 33/74] write an empty block as {} (do), and a for with no body, gave c-begin nothing to begin with, and the writer died on its arity. --- sex-fmt-c.scm | 31 ++++++++++++++++++------------- tests/codegen.scm | 10 ++++++++++ 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index f0160cf..8a5331b 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -619,11 +619,15 @@ (define (c-braced-block . args) (apply c-braced-block/aux 0 args)) + ;; MODIFIED FROM UPSTREAM fmt-c: a block of nothing is `{}', where + ;; c-begin had nothing to begin with and died on its arity. (define (c-braced-block/aux offset header . body) (lambda (st) - ((cat (if header header "") (c-open-brace st) (c-indent st offset) - (apply c-begin body) fl - (c-current-indent-string st offset) (c-close-brace st)) + ((if (null? body) + (cat (if header (cat header " ") "") "{}") + (cat (if header header "") (c-open-brace st) (c-indent st offset) + (apply c-begin body) fl + (c-current-indent-string st offset) (c-close-brace st))) st))) (define (c-begin . args) @@ -734,17 +738,18 @@ fl)))) ;; MODIFIED FROM UPSTREAM fmt-c: a header's first and last slots are - ;; the one place a comma expression goes bare, so they say so. + ;; the one place a comma expression goes bare, so they say so. And a + ;; loop with no body has the empty block. (define (c-for init check update . body) - (c-reset-newline - (cat - (c-block - (c-in-expr - (cat "for (" (c-with-op 'comma (c-expr init)) "; " - (c-in-test (c-expr check)) "; " - (c-with-op 'comma (c-expr update)) ")")) - (c-in-stmt (apply c-begin body))) - fl))) + (let ((header (c-in-expr + (cat "for (" (c-with-op 'comma (c-expr init)) "; " + (c-in-test (c-expr check)) "; " + (c-with-op 'comma (c-expr update)) ")")))) + (c-reset-newline + (cat (if (null? body) + (c-braced-block header) + (c-block header (c-in-stmt (apply c-begin body)))) + fl)))) (define (c-param x) (cond diff --git a/tests/codegen.scm b/tests/codegen.scm index 586420f..6bcb277 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -336,6 +336,16 @@ (reports? "(fn f () void\n (for ((var i int 0) (< i 4) (++ i)) (g i)))" "codegen.sex:2:"))) + ;; a block of nothing had nothing for c-begin to begin with, and the + ;; writer died on its arity + (test-group "empty bodies" + (test-assert "an empty block is a pair of braces" + (followed-by? (in-fn "(do) (g a)") "{}" "g(a);")) + (test-assert "inside another too" + (followed-by? (in-fn "(do (do) (g a))") "{}" "g(a);")) + (test-assert "and a for with no body has them" + (emits? (in-fn "(for (var i int 0) (< i a) (++ i))") "for (int i = 0; i < a; ++i) {}"))) + ;; A nested pointer chain used to silently lose a level: ;; (var p (* (* char))) emitted `char *p' (test-group "malformed types are rejected" -- 2.52.0 From 8cb141de5dce12401ec70a48e385160c486c6e49 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 17 Oct 2026 17:35:48 +0300 Subject: [PATCH 34/74] leave an empty for slot empty () went to C as NULL, so (for () () ()) tested false and never ran; it is for (;;). --- sex-fmt-c.scm | 15 ++++++++++----- tests/codegen.scm | 8 ++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index 8a5331b..1425880 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -738,13 +738,18 @@ fl)))) ;; MODIFIED FROM UPSTREAM fmt-c: a header's first and last slots are - ;; the one place a comma expression goes bare, so they say so. And a - ;; loop with no body has the empty block. + ;; the one place a comma expression goes bare, so they say so. A slot + ;; written () is empty, where c-expr would say NULL -- for (;;), not a + ;; loop whose test is false. And a loop with no body has the empty + ;; block. (define (c-for init check update . body) + (define (slot x lead show) + (if (null? x) "" (cat lead (show (c-expr x))))) + (define (bare e) (c-with-op 'comma e)) (let ((header (c-in-expr - (cat "for (" (c-with-op 'comma (c-expr init)) "; " - (c-in-test (c-expr check)) "; " - (c-with-op 'comma (c-expr update)) ")")))) + (cat "for (" (slot init "" bare) ";" + (slot check " " c-in-test) ";" + (slot update " " bare) ")")))) (c-reset-newline (cat (if (null? body) (c-braced-block header) diff --git a/tests/codegen.scm b/tests/codegen.scm index 6bcb277..8b3e722 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -346,6 +346,14 @@ (test-assert "and a for with no body has them" (emits? (in-fn "(for (var i int 0) (< i a) (++ i))") "for (int i = 0; i < a; ++i) {}"))) + ;; an empty slot was the empty list, which C was told as NULL: the + ;; test of (for () () ()) was false, and the loop never ran + (test-group "empty for slots" + (test-assert "are empty" + (emits? (in-fn "(for () () () (g a))") "for (;;) {")) + (test-assert "any of them" + (emits? (in-fn "(for () (< a 1) () (g a))") "for (; a < 1;) {"))) + ;; A nested pointer chain used to silently lose a level: ;; (var p (* (* char))) emitted `char *p' (test-group "malformed types are rejected" -- 2.52.0 From befe2ca25b22c13f66c7f251e000aa63ce844171 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 18 Oct 2026 22:02:55 +0300 Subject: [PATCH 35/74] nest a function type's declarator round the name A function type's return was written ahead of its declarator, so one returning a function pointer came out int (*)(int) get (void), and a variable of such a type as void (*)() (*g)(int). --- sex-fmt-c.scm | 25 ++++++++++++++++++------- tests/codegen.scm | 14 ++++++++++++++ tests/sex-programs/type-shapes.sex | 9 ++++++++- 3 files changed, 40 insertions(+), 8 deletions(-) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index 1425880..7bca585 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -788,9 +788,12 @@ (c-in-stmt (apply c-begin body))) fl)) + ;; MODIFIED FROM UPSTREAM fmt-c: the name and parameters are the + ;; return type's declarator, so a function returning a function pointer + ;; is int (*get (void))(int), not int (*)(int) get (void) (define (c-prototype type name params . o) (c-wrap-stmt - (cat (c-type type) " " (c-expr name) " (" (c-param-list params) ")" + (cat (c-type type (cat (c-expr name) " (" (c-param-list params) ")")) (fmt-join/prefix c-expr o " ")))) (define (c-static x) (cat "static " (c-expr x))) @@ -808,10 +811,14 @@ (cond ((pair? type) (case (car type) + ;; MODIFIED FROM UPSTREAM fmt-c: the declarator goes round the + ;; name, inside the return type's own, so a function type + ;; returning one nests: void (*(*g)(int))() ((%fun) - (cat (c-type (cadr type) #f) - " (*" (or name "") ")(" - (fmt-join (lambda (x) (c-type x #f)) (caddr type) ", ") ")")) + (c-type (cadr type) + (cat "(*" (or name "") ")(" + (fmt-join (lambda (x) (c-type x #f)) (caddr type) ", ") + ")"))) ;; MODIFIED FROM UPSTREAM fmt-c: a nameless declarator -- an ;; array parameter of a function type, where C has no room ;; for a name -- arrives as #f, and upstream printed it @@ -847,10 +854,14 @@ (cond ((pair? type) (case (car type) + ;; MODIFIED FROM UPSTREAM fmt-c: the declarator goes round the + ;; name, inside the return type's own, so a function type + ;; returning one nests: void (*(*g)(int))() ((%fun) - (cat (c-type (cadr type) #f) - " (*" (or name "") ")(" - (fmt-join (lambda (x) (c-type x #f)) (caddr type) ", ") ")")) + (c-type (cadr type) + (cat "(*" (or name "") ")(" + (fmt-join (lambda (x) (c-type x #f)) (caddr type) ", ") + ")"))) ;; MODIFIED FROM UPSTREAM fmt-c: a nameless declarator -- an ;; array parameter of a function type, where C has no room ;; for a name -- arrives as #f, and upstream printed it diff --git a/tests/codegen.scm b/tests/codegen.scm index 8b3e722..d998624 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -828,6 +828,20 @@ (test-assert "behind as many stars as are written" (emits? "(struct h ((f (* * (struct ((c int)))))))" "} * * f;"))) +;; A function type's return was written ahead of its declarator, so a + ;; function returning one came out `int (*)(int) get (void)' + (test-group "a function type returning one" + (test-assert "a function returning a function pointer" + (emits? "(fn inc ((x int)) int (return x)) (fn get () (fn ((int)) int) (return inc))" + "int (*get (void))(int)")) + (test-assert "and its prototype" + (emits? "(pub fn get () (fn ((int)) int))" "int (*get (void))(int);")) + (test-assert "a variable of one" + (emits? "(var g (fn ((int)) (fn () void)))" "void (*(*g)(int))()")) + (test-assert "and a parameter" + (emits? "(fn take ((f (fn ((int)) (fn () void)))) void (return))" + "take (void (*(*f)(int))())"))) + ;; Operands past what an operator takes were written as they came: ;; (< a b c) as C's own chain, which compares a boolean with c (test-group "operator arity" diff --git a/tests/sex-programs/type-shapes.sex b/tests/sex-programs/type-shapes.sex index ebcc036..6550ad4 100644 --- a/tests/sex-programs/type-shapes.sex +++ b/tests/sex-programs/type-shapes.sex @@ -9,7 +9,8 @@ "unnamed parameters: 7 -1 2" "typedefs: hi 4 2" "sizeof a pointer type: 1 1" - "dimensions: 6 12 5") + "dimensions: 6 12 5" + "returned function: 42") (return 0) ;;; Three questions about a written type that used to be answered in @@ -29,6 +30,9 @@ (typedef vec4 [float 4]) (typedef unary (fn ((small)) small)) +(fn successor ((n int)) int (return (+ n 1))) +(fn stepper () (fn ((int)) int) (return successor)) + (define CAP 2) ;;; a parameter that names nothing is a type, however many words it @@ -101,4 +105,7 @@ (var g [int 2 3] #(#(0 1 2) #(3 4 5))) (printf "dimensions: %zu %zu %d\n" (/ (sizeof g) (sizeof int)) (sizeof [g 0]) [g 1 2]) + + ;; a function type is a declarator wrapped round the name + (printf "returned function: %d\n" ((stepper) 41)) (return 0)) -- 2.52.0 From 10de092ab0b12f90e62e083517c4b77e53a70272 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 18 Oct 2026 22:02:55 +0300 Subject: [PATCH 36/74] designate an initializer's element by its index [3] in braces reached the writer as a subscript of one operand, and sexc died taking the second. --- fmt-c-writer.scm | 8 +++++++- sex-fmt-c.scm | 5 +++++ tests/codegen.scm | 9 ++++++++- tests/sex-programs/compound-literals.sex | 7 ++++++- 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 776b726..e395d62 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -378,7 +378,7 @@ forms, and what remains." (let loop ((es elements) (acc (list))) (match es (() (reverse acc)) - (((? designator? d)) + (((or (? designator? d) (and ('¤ _) d))) (sex-error elements "designated initializer without a value" d)) (((? designator? d) value . rest) (loop rest @@ -386,6 +386,12 @@ forms, and what remains." (atom-to-fmt-c (designator-field d)) (walk-expr value)) acc))) + ;; [3] 1: an element named by its index. A subscript has two + ;; operands, so one alone can be nothing else + ((('¤ index) value . rest) + (loop rest + (cons (list '%designate-index (walk-expr index) (walk-expr value)) + acc))) ((e . rest) (loop rest (cons (walk-expr e) acc)))))) (define (designator? x) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index 7bca585..71b1900 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -322,6 +322,7 @@ ((%sizeof-type) ((cat "sizeof(" (c-type (cadr x)) ")") st)) ((%compound) ((apply c-compound (cdr x)) st)) ((%designate) ((apply c-designate (cdr x)) st)) + ((%designate-index) ((apply c-designate-index (cdr x)) st)) ((+ - & * / % ! ~ ^ && < > <= >= == != << >> = *= /= %= &= ^= >>= <<=) ; |\|| |\|\|| |\|=| ((apply c-op x) st)) @@ -927,6 +928,10 @@ (define (c-designate field value) (cat "." (c-expr field) " = " (c-expr value))) + ;; MODIFIED FROM UPSTREAM fmt-c, which designates fields only + (define (c-designate-index index value) + (cat "[" (c-expr index) "] = " (c-expr value))) + (define (c-typedef type alias . o) (c-wrap-stmt (cat "typedef " (c-type type alias) (fmt-join/prefix c-expr o " ")))) diff --git a/tests/codegen.scm b/tests/codegen.scm index d998624..4a1ddd1 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -1034,7 +1034,14 @@ "{pp->x, pp->y}")) (test-assert "designated" (emits? (in-line "(var q (struct point) #(.y (. pp x)))") - "{.y = pp->x}"))) + "{.y = pp->x}")) + ;; [3] reached the writer as a subscript of one operand, and died + (test-assert "an element designated by its index" + (emits? (in-fn "(var xs [int 5] #([3] 1 [1] 2))") "{[3] = 1, [1] = 2}")) + (test-assert "among positional ones" + (emits? (in-fn "(var xs [int 5] #(7 [3] 1 9))") "{7, [3] = 1, 9}")) + (test-assert "and one with no value is an error" + (reports? (in-fn "(var xs [int 5] #(1 [3]))") "designated initializer without a value"))) (test-group "member access" (test-assert "a value reads with a dot" diff --git a/tests/sex-programs/compound-literals.sex b/tests/sex-programs/compound-literals.sex index 3aad6c5..0def878 100644 --- a/tests/sex-programs/compound-literals.sex +++ b/tests/sex-programs/compound-literals.sex @@ -6,7 +6,8 @@ "array 10 20 30" "argument 6" "mixed 1 5" - "read through a pointer 1 5") + "read through a pointer 1 5" + "by index 0 2 0 1") (return 0) ;;; `:' inside #(...) ends a type and makes the rest a C99 compound @@ -53,4 +54,8 @@ (var c (struct point) #(struct point : (. pm x) (. pm y))) (printf "read through a pointer %d %d\n" (. c x) (. c y)) + ;; an element may be named by its index, as a field is by its name + (var sparse [int 4] #([3] 1 [1] 2)) + (printf "by index %d %d %d %d\n" [sparse 0] [sparse 1] [sparse 2] [sparse 3]) + (return 0)) -- 2.52.0 From 20311a200d67254a75df97418c1d26817b66dbb3 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 18 Oct 2026 22:02:55 +0300 Subject: [PATCH 37/74] resolve the closure types in a closure's signature The struct, call helper and conversion thunk of a closure type went out with any closure type in its signature as written, which C has no name for; so a closure could neither return nor take one, and no currying. --- semen.scm | 14 +++++++++++++- tests/sex-programs/closure-signatures.sex | 19 ++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/semen.scm b/semen.scm index 811f270..5a3505f 100644 --- a/semen.scm +++ b/semen.scm @@ -1630,7 +1630,17 @@ ;;; The code pointer takes the environment first; everything else is ;;; the closure's own signature. (define (closure-code-type type) - `(fn (((* void)) ,@(second type)) ,(third type))) + (let ((type (signature-resolved type))) + `(fn (((* void)) ,@(second type)) ,(third type)))) + +;;; TYPE with the closure types of its signature made their structs: the +;;; code generated for it goes out as it is, and C has no `closure'. +;;; +;;; (closure ((int)) (closure ((int)) int)) +;;; -> (closure ((int)) (struct ƛint_int)) +(define (signature-resolved type) + `(closure ,(map resolve-closure-types (second type)) + ,(resolve-closure-types (third type)))) ;;; Emitted once per signature, before the toplevel form that first ;;; needed it. @@ -1686,6 +1696,7 @@ ;;; } (define (register-fn-conversion! type src-form) (let* ((closure (closure-struct-name type)) + (type (signature-resolved type)) (convert (suffixed closure "_fromfn")) (record (suffixed closure "_fnptr")) (thunk (suffixed closure "_fnthunk")) @@ -1745,6 +1756,7 @@ ;;; `table[++i].code(&table[++i].env, 10)' and bump `i' twice. (define (register-closure-call! type src-form) (let* ((closure (closure-struct-name type)) + (type (signature-resolved type)) (helper (suffixed closure "_call")) (returns (third type)) (params (map (lambda (arg index) diff --git a/tests/sex-programs/closure-signatures.sex b/tests/sex-programs/closure-signatures.sex index 494bcde..e483e3c 100644 --- a/tests/sex-programs/closure-signatures.sex +++ b/tests/sex-programs/closure-signatures.sex @@ -4,7 +4,9 @@ "unsigned, one argument: 9" "unsigned, two arguments: 3" "captured global: 12" - "captured function: 8") + "captured function: 8" + "curried: 42 42" + "taking one: 21") (return 0) ;;; A closure's struct is named after its signature, so that two @@ -16,6 +18,9 @@ ;;; ;;; A capture that borrows a name reads it from wherever the name is ;;; declared, a global or a function included. +;;; +;;; A closure's signature may name closures in turn: one returned is +;;; currying, one taken is a callback. (include stdio.h) @@ -24,6 +29,10 @@ (fn double-it ((n int)) int (return (* n 2))) +(fn curried-add () (closure ((int)) (closure ((int)) int)) + (return (closure ((a int)) (closure ((int)) int) () + (return (closure ((b int)) int (a) (return (+ a b))))))) + (pub fn main () int (var one-wide (closure ((long long)) int) (closure ((a (long long))) int () (return (cast a int)))) @@ -49,4 +58,12 @@ (var doubled (closure ((int)) int) (closure ((x int)) int (double-it) (return (double-it x)))) (printf "captured function: %d\n" (doubled 4)) + + (var add (closure ((int)) (closure ((int)) int)) (curried-add)) + (var add2 (closure ((int)) int) (add 2)) + (printf "curried: %d %d\n" (add2 40) ((add 1) 41)) + + (var twice (closure (((closure ((int)) int)) (int)) int) + (closure ((f (closure ((int)) int)) (x int)) int () (return (f (f x))))) + (printf "taking one: %d\n" (twice add2 17)) (return 0)) -- 2.52.0 From 3d295f4cd0cadb6bb9e92063a9e68c17613239a9 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 18 Oct 2026 22:02:55 +0300 Subject: [PATCH 38/74] capture an array and a const local C copies an array neither by = nor from another array's initializer, and a const field cannot be assigned: both failed in the C. An array is copied in element by element; a const one is held as its value. --- semen.scm | 50 +++++++++++++++++++++++++++------ tests/sex-programs/closures.sex | 19 ++++++++++++- 2 files changed, 60 insertions(+), 9 deletions(-) diff --git a/semen.scm b/semen.scm index 5a3505f..f0733df 100644 --- a/semen.scm +++ b/semen.scm @@ -1837,17 +1837,14 @@ (append (if (null? caps) (list) - (list `(struct ,record ,caps))) + (list `(struct ,record ,(map capture-field caps)))) (list `(fn ,code ((ƛe (* void)) ,@arglist) ,ret-type ,@(if (null? caps) (list) `((var ƛcaptures (* (struct ,record)) ƛe) - ,@(map (lambda (cap) - `(var ,(first cap) ,(second cap) - (%-> ƛcaptures ,(first cap)))) - caps))) + ,@(append-map (cut capture-local <> form) caps))) ,@body) `(fn ,construct ,caps (struct ,closure) @@ -1863,12 +1860,49 @@ (list) `((var ƛcaptures (* (struct ,record)) (cast (& (dot-access ƛc env)) (* (struct ,record)))) - ,@(map (lambda (cap) - `(= (%-> ƛcaptures ,(first cap)) ,(first cap))) - caps))) + ,@(map (cut capture-store <> form) caps))) (return ƛc)))))))) (else (sex-error form "malformed closure" form)))) +;;; A capture's field is assigned to, so it drops what qualifies the +;;; capture itself: (const int) is held as an int, and read back into a +;;; const one. (* const char) points at const, and is left alone. +(define (capture-field cap) + (let ((type (second cap))) + (list (first cap) + (if (and (pair? type) (memq (car type) '(const volatile))) + (let ((rest (drop-while (cut memq <> '(const volatile)) type))) + (if (null? (cdr rest)) (car rest) rest)) + type)))) + +;;; The code's local for a capture, read back out of the record +(define (capture-local cap form) + (let ((name (first cap)) (type (second cap))) + (if (array-form? type) + `((var ,name ,type) ,(array-copy type name `(%-> ƛcaptures ,name) form)) + `((var ,name ,type (%-> ƛcaptures ,name)))))) + +;;; The constructor's filling of a capture's field +(define (capture-store cap form) + (let ((name (first cap)) (type (second cap))) + (if (array-form? type) + (array-copy type `(%-> ƛcaptures ,name) name form) + `(= (%-> ƛcaptures ,name) ,name)))) + +;;; DEST, an array of TYPE, given SRC's elements one at a time: C copies +;;; an array neither by = nor through an initializer of another +;;; +;;; (for (var ƛi0 int 0) (< ƛi0 3) (++ ƛi0) (= [dest ƛi0] [src ƛi0])) +(define (array-copy type dest src form #!optional (depth 0)) + (unless (array-bound? type) + (sex-error form "a captured array needs its length written" dest)) + (let ((i (string->symbol (string-append "ƛi" (number->string depth)))) + (element (array-element-type type))) + `(for (var ,i int 0) (< ,i ,(array-bound type)) (++ ,i) + ,(if (array-form? element) + (array-copy element `(¤ ,dest ,i) `(¤ ,src ,i) form (+ depth 1)) + `(= (¤ ,dest ,i) (¤ ,src ,i)))))) + ;;; Structs ;;; Record the named structs, unions and enums in the type database diff --git a/tests/sex-programs/closures.sex b/tests/sex-programs/closures.sex index fa20184..adca632 100644 --- a/tests/sex-programs/closures.sex +++ b/tests/sex-programs/closures.sex @@ -10,7 +10,9 @@ "Nested: 33" "Named capture: 7" "Captured pointer: 11 then 12" - "From a bare fn: 20 42 7") + "From a bare fn: 20 42 7" + "Captured array: 6 3, still 6" + "Captured const: 6") (return 0) ;;; A closure is a code pointer beside its captures, so what this @@ -118,4 +120,19 @@ (apply-twice from-fn 5) ((as-closure) 21) (apply-twice (lambda ((n int)) int (return (+ n 1))) 5)) + + ;; an array is copied in, element by element, as C copies one neither + ;; by = nor into a parameter; so are the rows of one of arrays + (var xs [int 3] #(1 2 3)) + (var m [int 2 2] #(#(1 2) #(3 4))) + (var sum3 (closure () int) (closure () int (xs) (return (+ [xs 0] [xs 1] [xs 2])))) + (var corner (closure () int) (closure () int (m) (return [m 1 0]))) + (printf "Captured array: %d %d" (sum3) (corner)) + (= [xs 0] 100) + (printf ", still %d\n" (sum3)) + + ;; a const local is captured as its value, and stays const inside + (var k (const int) 5) + (var plus-k (closure ((int)) int) (closure ((v int)) int (k) (return (+ v k)))) + (printf "Captured const: %d\n" (plus-k 1)) (return 0)) -- 2.52.0 From d9bc8967bac9c14403b943c4fc4d2433fc03757c Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 18 Oct 2026 22:02:55 +0300 Subject: [PATCH 39/74] refuse a capture a parameter or the body names too Captures are a closure's other parameters, and C's redefinition error was the first anyone heard of one sharing a name with a parameter, or being redeclared at the top of the body. --- semen.scm | 19 +++++++++++++++++++ tests/codegen.scm | 12 ++++++++++++ 2 files changed, 31 insertions(+) diff --git a/semen.scm b/semen.scm index f0733df..e7ff9b4 100644 --- a/semen.scm +++ b/semen.scm @@ -1822,6 +1822,7 @@ (define (lift-closure base form env) (match form (('closure arglist ret-type captures . body) + (check-capture-names form arglist (map capture-name captures) body) (let* ((caps (map (lambda (c) (capture-binding c form env)) captures)) (record (suffixed base "_captures")) (code (suffixed base "_code")) @@ -1864,6 +1865,24 @@ (return ƛc)))))))) (else (sex-error form "malformed closure" form)))) +;;; Captures are a closure's other parameters, and C's rule for those +;;; holds of them: no two alike, and none redeclared at the top of the +;;; body. A block inside may shadow one, as it may a parameter. +(define (check-capture-names form arglist names body) + (let ((parameters (filter-map (lambda (arg) (and (named-arg? arg) (car arg))) + (remove comment-form? arglist)))) + (for-each (lambda (name) + (when (memq name parameters) + (sex-error form "a capture and a parameter share a name" name))) + names) + (for-each (lambda (statement) + (match statement + (('var (? symbol? name) . _) + (when (memq name names) + (sex-error statement "the body redeclares a capture" name))) + (_ #f))) + body))) + ;;; A capture's field is assigned to, so it drops what qualifies the ;;; capture itself: (const int) is held as an int, and read back into a ;;; const one. (* const char) points at const, and is left alone. diff --git a/tests/codegen.scm b/tests/codegen.scm index 4a1ddd1..6ec7894 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -421,6 +421,18 @@ (test-assert "the type becomes a struct named for its signature" (emits? "(fn f ((c (closure ((int)) int))) int (return (c 1)))" "struct ƛint_int")) + ;; captures are a closure's other parameters, under C's rule for + ;; those: no two alike, and none redeclared at the body's top level. + ;; Both were C's redefinition errors + (test-assert "a capture named like a parameter is refused" + (reports? (in-fn "(var c (closure ((int)) int) (closure ((a int)) int (a) (return a)))") + "a capture and a parameter share a name")) + (test-assert "so is one redeclared at the top of the body" + (reports? (in-fn "(var c (closure () int) (closure () int (a) (var a int 5) (return a)))") + "the body redeclares a capture")) + (test-assert "while a block inside may shadow it" + (emits? (in-fn "(var c (closure () int) (closure () int (a) (do (var a int 5) (g a)) (return a)))") + "int a = 5;")) ;; The environment is one shared union, declared in the prelude -- ;; its layout is part of the ABI two units agree on, so it cannot ;; depend on what either file contains. `sex->c' has no prelude, so -- 2.52.0 From b3d7decc6bea7a59339f820fa3860b9da63a59d9 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 18 Oct 2026 22:02:55 +0300 Subject: [PATCH 40/74] take an unnamed closure parameter, and refuse a variadic one The closure's type was built from each parameter's second element, so a type alone, or the ..., crashed sexc. A variadic closure cannot work: its call helper would have to forward what C cannot. --- semen.scm | 19 ++++++++++++++++--- tests/codegen.scm | 12 ++++++++++++ tests/sex-programs/closures.sex | 6 +++++- 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/semen.scm b/semen.scm index e7ff9b4..a51ec96 100644 --- a/semen.scm +++ b/semen.scm @@ -1822,13 +1822,15 @@ (define (lift-closure base form env) (match form (('closure arglist ret-type captures . body) + ;; its call helper would have to forward the rest, which C cannot + (when (any (lambda (arg) (or (eq? arg '...) (equal? arg '(...)))) arglist) + (sex-error form "a closure cannot be variadic; a lambda can")) (check-capture-names form arglist (map capture-name captures) body) (let* ((caps (map (lambda (c) (capture-binding c form env)) captures)) (record (suffixed base "_captures")) (code (suffixed base "_code")) (construct (suffixed base "_make")) - (type `(closure ,(map (lambda (p) (list (second p))) arglist) - ,ret-type)) + (type `(closure ,(arglist-types arglist) ,ret-type)) (closure (register-closure-type! type form))) (values construct @@ -1841,7 +1843,7 @@ (list `(struct ,record ,(map capture-field caps)))) (list - `(fn ,code ((ƛe (* void)) ,@arglist) ,ret-type + `(fn ,code ((ƛe (* void)) ,@(named-parameters arglist)) ,ret-type ,@(if (null? caps) (list) `((var ƛcaptures (* (struct ,record)) ƛe) @@ -1865,6 +1867,17 @@ (return ƛc)))))))) (else (sex-error form "malformed closure" form)))) +;;; A definition names every parameter before C23, so one written as a +;;; type alone gets a name nothing reads: ((int) (b int)) -> ((ƛu0 int) (b int)) +(define (named-parameters arglist) + (map (lambda (arg index) + (if (or (named-arg? arg) (comment-form? arg)) + arg + (list (string->symbol (string-append "ƛu" (number->string index))) + (unwrap-type arg)))) + arglist + (iota (length arglist)))) + ;;; Captures are a closure's other parameters, and C's rule for those ;;; holds of them: no two alike, and none redeclared at the top of the ;;; body. A block inside may shadow one, as it may a parameter. diff --git a/tests/codegen.scm b/tests/codegen.scm index 6ec7894..ff51b63 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -433,6 +433,18 @@ (test-assert "while a block inside may shadow it" (emits? (in-fn "(var c (closure () int) (closure () int (a) (do (var a int 5) (g a)) (return a)))") "int a = 5;")) + ;; the closure's type was built from each parameter's second element, + ;; which a type alone has none of + (test-assert "a parameter may name nothing" + (emits? (in-fn "(var c (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b)))") + "struct ƛint__int")) + (test-assert "and its code names it, a definition needing one before C23" + (emits? (in-fn "(var c (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b)))") + "int ƛu0, int b)")) + ;; the call helper would have to forward the rest, which C cannot + (test-assert "a closure cannot be variadic" + (reports? (in-fn "(var c _ (closure ((n int) ...) int () (return n)))") + "a closure cannot be variadic; a lambda can")) ;; The environment is one shared union, declared in the prelude -- ;; its layout is part of the ABI two units agree on, so it cannot ;; depend on what either file contains. `sex->c' has no prelude, so diff --git a/tests/sex-programs/closures.sex b/tests/sex-programs/closures.sex index adca632..9494392 100644 --- a/tests/sex-programs/closures.sex +++ b/tests/sex-programs/closures.sex @@ -12,7 +12,8 @@ "Captured pointer: 11 then 12" "From a bare fn: 20 42 7" "Captured array: 6 3, still 6" - "Captured const: 6") + "Captured const: 6" + "Unnamed parameter: 2") (return 0) ;;; A closure is a code pointer beside its captures, so what this @@ -135,4 +136,7 @@ (var k (const int) 5) (var plus-k (closure ((int)) int) (closure ((v int)) int (k) (return (+ v k)))) (printf "Captured const: %d\n" (plus-k 1)) + + (var second (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b))) + (printf "Unnamed parameter: %d\n" (second 1 2)) (return 0)) -- 2.52.0 From 94f41b5fad59a7b79e5d4ec164579c005df2e3f7 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 18 Oct 2026 22:02:55 +0300 Subject: [PATCH 41/74] define an empty lambda as an empty function A lifted function with no body was a declaration of one, and nothing defined it, so the program did not link. --- fmt-c-writer.scm | 11 ++++++++++- semen.scm | 21 +++++++++++++++------ sex-fmt-c.scm | 7 +++++-- tests/codegen.scm | 7 +++++++ tests/sex-programs/closures.sex | 9 ++++++++- 5 files changed, 45 insertions(+), 10 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index e395d62..9a40dc1 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -511,7 +511,16 @@ forms, and what remains." ,(atom-to-fmt-c name) ,(walk-arglist args) . - ,(walk-body maybe-body))))) + ,(let ((body (walk-body maybe-body))) + ;; one that is empty blocks, and where they were, is nothing: + ;; what a lifted empty lambda is given to be a definition + (if (every (lambda (s) (equal? s '(%block-begin))) + (remove line-directive? body)) + (list) + body)))))) + +(define (line-directive? form) + (and (pair? form) (eq? (car form) '%line))) ;;; The type of one parameter (define (arg-type arg) diff --git a/semen.scm b/semen.scm index a51ec96..d4dd338 100644 --- a/semen.scm +++ b/semen.scm @@ -1505,10 +1505,17 @@ (string->symbol (fmt #f "λ" counter "_" enclosing-fn-name))) +;;; A function with no body is a declaration, and nothing would define +;;; one lifted from an empty lambda; an empty block keeps it a definition, +;;; and the writer leaves the block out +(define (defining body) + (if (every comment-form? body) (append body (list '(do))) body)) + (define (lift-lambda name form) (match form (('lambda arglist ret-type . body) - (process-fn (copy-form-source! form `(fn ,name ,arglist ,ret-type ,@body)) + (process-fn (copy-form-source! form `(fn ,name ,arglist ,ret-type + ,@(defining body))) (list))) (else (sex-error form "malformed lambda" form)))) @@ -1844,11 +1851,13 @@ (list `(fn ,code ((ƛe (* void)) ,@(named-parameters arglist)) ,ret-type - ,@(if (null? caps) - (list) - `((var ƛcaptures (* (struct ,record)) ƛe) - ,@(append-map (cut capture-local <> form) caps))) - ,@body) + ,@(defining + (append + (if (null? caps) + (list) + `((var ƛcaptures (* (struct ,record)) ƛe) + ,@(append-map (cut capture-local <> form) caps))) + body))) `(fn ,construct ,caps (struct ,closure) (var ƛc (struct ,closure)) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index 71b1900..4605102 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -784,9 +784,12 @@ (c-type 'void) (c-in-expr (fmt-join/dot c-param (lambda (dot) (dsp "...")) ls ", ")))) + ;; MODIFIED FROM UPSTREAM fmt-c: a function of no statements is `{}' (define (c-fun type name params . body) - (cat (c-block (c-in-expr (c-prototype type name params)) - (c-in-stmt (apply c-begin body))) + (cat (if (null? body) + (c-braced-block (c-in-expr (c-prototype type name params))) + (c-block (c-in-expr (c-prototype type name params)) + (c-in-stmt (apply c-begin body)))) fl)) ;; MODIFIED FROM UPSTREAM fmt-c: the name and parameters are the diff --git a/tests/codegen.scm b/tests/codegen.scm index ff51b63..0b5cfa9 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -441,6 +441,13 @@ (test-assert "and its code names it, a definition needing one before C23" (emits? (in-fn "(var c (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b)))") "int ƛu0, int b)")) + ;; a lifted function with no body was a declaration of one, and + ;; nothing defined it + (test-assert "an empty lambda is an empty function" + (emits? "(fn f () void (var g (fn () void) (lambda () void)))" + "static void λ0_f (void) {}")) + (test-assert "so is an empty closure's code" + (emits? (in-fn "(var c (closure () void) (closure () void ()))") "(void * ƛe) {}")) ;; the call helper would have to forward the rest, which C cannot (test-assert "a closure cannot be variadic" (reports? (in-fn "(var c _ (closure ((n int) ...) int () (return n)))") diff --git a/tests/sex-programs/closures.sex b/tests/sex-programs/closures.sex index 9494392..e224723 100644 --- a/tests/sex-programs/closures.sex +++ b/tests/sex-programs/closures.sex @@ -13,7 +13,8 @@ "From a bare fn: 20 42 7" "Captured array: 6 3, still 6" "Captured const: 6" - "Unnamed parameter: 2") + "Unnamed parameter: 2" + "Empty bodies: called") (return 0) ;;; A closure is a code pointer beside its captures, so what this @@ -139,4 +140,10 @@ (var second (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b))) (printf "Unnamed parameter: %d\n" (second 1 2)) + + (var nothing (closure () void) (closure () void ())) + (var nothing-either (fn () void) (lambda () void)) + (nothing) + (nothing-either) + (printf "Empty bodies: called\n") (return 0)) -- 2.52.0 From cb37821e3e5a92ef0fd18d19f639b3ebc000b44e Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 18 Oct 2026 22:02:55 +0300 Subject: [PATCH 42/74] let a realization's methods call one another Each was registered as its body was walked, so a method could not call one coming after it -- a default included, defaults coming after the written ones. All are registered first now, as an ops block's are. --- semen.scm | 33 +++++++++++++++++++++++---------- tests/sex-programs/specs.sex | 17 ++++++++++++++++- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/semen.scm b/semen.scm index d4dd338..13878ea 100644 --- a/semen.scm +++ b/semen.scm @@ -340,11 +340,21 @@ (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)))))) + ;; every method is registered before any body is walked, so they + ;; may call one another in any order, as an ops block's may; one + ;; called above its definition is declared ahead of them all + (let* ((methods (map (lambda (entry) + (register-realized-method form name type + (and pub? (cdr entry)) + (car entry))) + (realization-methods type parameter wanted given))) + (bodies (map (lambda (m) (process-fn m (list))) methods)) + (early (filter (lambda (m) (called-before? m methods bodies)) + methods))) + (append (append-map identity (reverse bodies)) + (fold (lambda (m acc) (process-fn (sex-fn-prototype m) acc)) + acc + early))))))) ;;; What is written here, which a pub realization exports, and then ;;; every default nobody overrode, which it does not: a default is @@ -396,16 +406,19 @@ ;;; 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) +;;; the spec already says which of them there are. The method's fn +;;; form, renamed to pointːsizedːtotal, once it is registered under +;;; `total' and its signature known. +(define (register-realized-method form spec type pub? method) (let* ((name (second method)) (qualified (qualify-op (qualify-op type spec) name)) - (renamed (rename-fn method qualified))) + (renamed (copy-form-source! form (rename-fn method qualified))) + (fn (if pub? (copy-form-source! form (cons 'pub renamed)) renamed))) (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))) + (process-fn (sex-fn-prototype fn) (list)) + fn)) ;;; T in a spec's method stands for whatever realizes it (define (substitute-parameter parameter type form) diff --git a/tests/sex-programs/specs.sex b/tests/sex-programs/specs.sex index 93f6680..bfeb7e5 100644 --- a/tests/sex-programs/specs.sex +++ b/tests/sex-programs/specs.sex @@ -2,7 +2,8 @@ (output "$12.34" "(3, 4)" "max 1234" - "realizes ord: money 1, point 0") + "realizes ord: money 1, point 0" + "calls its own: 9") (return 0) ;;; A spec is a contract and emits nothing; a realization is the @@ -53,6 +54,19 @@ (defmacro (ord? type) (if (realizes? 'ord type) 1 0)) +;;; A realization's methods may call one another, whatever order they +;;; come in: `total', written, calls the default `doubled', which calls +;;; the later default `plus-one', which calls `base', written below them +(spec (sized T) + (fn total ((self (* const T))) int) + (fn doubled ((self (* const T))) int (return (* 2 (.plus-one self)))) + (fn plus-one ((self (* const T))) int (return (+ 1 (.base self)))) + (fn base ((self (* const T))) int)) + +(realize (sized point) + (fn total ((self (* const point))) int (return (+ 1 (.doubled self)))) + (fn base ((self (* const point))) int (return (. self x)))) + (pub fn main () int (var m money #(money : 1234)) (var p point #(point : 3 4)) @@ -65,4 +79,5 @@ (printf "max %d\n" (. big cents)) (printf "realizes ord: money %d, point %d\n" (ord? money) (ord? point)) + (printf "calls its own: %d\n" (.total p)) (return 0)) -- 2.52.0 From 3436c4ff3ea02c82fd8820b199df65c4e66ed8da Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 18 Oct 2026 22:02:55 +0300 Subject: [PATCH 43/74] read an array's length as types does Inference took only an integer for a length, and read a name there as part of the element type: [_ N] did not solve, and an array of [int N] decayed to int N *. --- infer.scm | 23 ++++++++++++----------- tests/codegen.scm | 9 +++++++++ 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/infer.scm b/infer.scm index c5f7f12..32300aa 100644 --- a/infer.scm +++ b/infer.scm @@ -78,8 +78,9 @@ (target ptr-target) (quals ptr-quals)) -;;; `size' is an integer, or #f for `(¤ int)' -- an array of unwritten -;;; length. +;;; `size' is the length as written -- 4, N, (* 2 N) -- or #f for +;;; `(¤ int)', an array of unwritten length. Two are one length when +;;; they are written alike. (define-record-type (make-array-type elt size) array-type? @@ -222,15 +223,15 @@ (name (and (pair? (cdr words)) (symbol? (cadr words)) (cadr words)))) (make-agg kind name words quals))) -;;; (¤ elt ... size) -- the size is the last element when it is an -;;; integer, and absent otherwise. The element words are unwrapped the -;;; way the C writer unwraps them, so `[int 16]' and `[(int) 16]' are -;;; one type. +;;; (¤ elt ... size) -- the size is the bound `types' finds there: an +;;; integer, a name, an expression, or absent. The element words are +;;; unwrapped the way the C writer unwraps them, so `[int 16]' and +;;; `[(int) 16]' are one type. (define (parse-array surface) - (let* ((rest (cdr (nest-array-type surface))) - (sized? (and (pair? rest) (integer? (last rest)))) - (size (and sized? (last rest))) - (words (if sized? (drop-right rest 1) rest))) + (let* ((nested (nest-array-type surface)) + (sized? (array-bound? nested)) + (size (and sized? (array-bound nested))) + (words (if sized? (drop-right (cdr nested) 1) (cdr nested)))) (when (null? words) (sex-error surface "array type without an element type" surface)) (make-array-type (parse-type (maybe-unwrap words)) size))) @@ -383,7 +384,7 @@ ;; One of them may be `(¤ int)': an unwritten length constrains ;; nothing, the way it does not in C either. (when (and (array-size a) (array-size b) - (not (= (array-size a) (array-size b)))) + (not (equal? (array-size a) (array-size b)))) (type-mismatch a b form)) (unify (array-elt a) (array-elt b) form)) ((and (fn-type? a) (fn-type? b)) diff --git a/tests/codegen.scm b/tests/codegen.scm index 0b5cfa9..d8853c4 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -678,6 +678,15 @@ (emits? "(typedef count int) (fn g () count (return 0)) (fn f () void (var x _ (g)))" "count x = g()")) + ;; only an integer was taken for a length; a name was read as part + ;; of the element's + (test-assert "of a named length" + (emits? "(define N 3) (fn f () void (var t [_ N] #(1 2 3)))" "int t[N]")) + (test-assert "which an array of decays from as any other" + (emits? "(define N 3) (fn f () void (var a [int N]) (var p _ (+ a 1)))" + "int * p = a + 1")) + (test-assert "while a length left to work out is not one" + (reports? (in-fn "(var t [_ _] #(1 2))") "cannot infer")) ;; a variable had nowhere to keep a qualifier written on it, and ;; what it was solved to came out without (test-assert "a qualified wildcard keeps its qualifier" -- 2.52.0 From 0a0a3f6b2574d73e0f6489b283629d9caf6be2e2 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 18 Oct 2026 22:02:55 +0300 Subject: [PATCH 44/74] decay an array into a wildcard standing alone An array as a value is a pointer to its first element; _ took the array type, and declared a copy that C cannot initialize from it. --- infer.scm | 2 ++ semen.scm | 10 +++++++++- tests/codegen.scm | 12 ++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/infer.scm b/infer.scm index 32300aa..3eb7e68 100644 --- a/infer.scm +++ b/infer.scm @@ -33,9 +33,11 @@ (export ;; The IR + tvar? prim-type? prim-name ptr-type? array-type? array-elt + resolve underlying c-primitive? decay diff --git a/semen.scm b/semen.scm index 13878ea..b0d06d4 100644 --- a/semen.scm +++ b/semen.scm @@ -882,7 +882,15 @@ (sex-error form "cannot infer the type of" (second form))) ;; `(closure ((int)) int)' is spelled `(struct ƛint_int)' ;; everywhere past this point, and is what `parse-type' knows - (unify declared (parse-type (resolve-closure-types type)) form))))) + (let ((given (parse-type (resolve-closure-types type)))) + ;; an array as a value is a pointer to its first element, which + ;; is what a `_' standing alone takes; `[_ 3]' asks for an array + (unify declared + (if (and (tvar? (resolve declared)) + (array-type? (underlying given))) + (decay given) + given) + form)))))) ;;; `#(0 1 4 9)', as against the compound literal `#(T : ...)' (define (brace-initializer? form) diff --git a/tests/codegen.scm b/tests/codegen.scm index d8853c4..172a27a 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -687,6 +687,18 @@ "int * p = a + 1")) (test-assert "while a length left to work out is not one" (reports? (in-fn "(var t [_ _] #(1 2))") "cannot infer")) + ;; an array as a value is a pointer to its first element, where `_' + ;; declared a copy, which C cannot initialize from it + (test-assert "an array decays into `_'" + (emits? (in-fn "(var s [char 6]) (var t _ s)") "char * t = s")) + (test-assert "a row of one too" + (emits? (in-fn "(var m [int 2 3]) (var r _ [m 1])") "int * r = m[1]")) + (test-assert "and a field" + (emits? "(struct h ((xs [int 4]))) (fn f ((v (struct h))) void (var p _ (. v xs)))" + "int * p = v.xs")) + (test-assert "while a function is the pointer it already is" + (emits? "(fn g ((n int)) int (return n)) (fn f () void (var p _ g))" + "int (*p)(int) = g")) ;; a variable had nowhere to keep a qualifier written on it, and ;; what it was solved to came out without (test-assert "a qualified wildcard keeps its qualifier" -- 2.52.0 From e0ecde651724d9f015d2291f57186a87d5a9e979 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 18 Oct 2026 22:02:55 +0300 Subject: [PATCH 45/74] refuse _ in a function's signature Nothing solves it there, and it reached the C as _. --- semen.scm | 8 ++++++++ tests/codegen.scm | 11 +++++++++++ 2 files changed, 19 insertions(+) diff --git a/semen.scm b/semen.scm index b0d06d4..7f06de7 100644 --- a/semen.scm +++ b/semen.scm @@ -279,6 +279,14 @@ ;; be answered from the scope it was written in (expanded (append (macro-expand (take sex-fn boundary)) (drop sex-fn boundary)))) + ;; a `_' is solved from what a variable is set to, and a signature + ;; has nothing it is set to + (when (mentions? (cons (sex-fn-return-type expanded) + (arglist-types (sex-fn-arglist expanded))) + '_) + (sex-error sex-fn-raw + "a function's types are written out; `_' is a variable's" + (sex-fn-name expanded))) (add-name-type! (sex-fn-name expanded) (fn-type-of expanded)) (let* ((env (make-fn-env expanded)) ;; the parameters are the body's outermost scope diff --git a/tests/codegen.scm b/tests/codegen.scm index 172a27a..db3adb4 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -696,6 +696,17 @@ (test-assert "and a field" (emits? "(struct h ((xs [int 4]))) (fn f ((v (struct h))) void (var p _ (. v xs)))" "int * p = v.xs")) + ;; nothing solves a `_' in a signature: it reached C as one + (test-assert "a parameter's type is written out" + (reports? "(fn id ((x _)) int (return x))" "a function's types are written out")) + (test-assert "and so is the return type" + (reports? "(fn id ((x int)) _ (return x))" "a function's types are written out")) + (test-assert "a lambda's as well" + (reports? (in-fn "(var l (fn ((int)) int) (lambda ((x _)) int (return x)))") + "a function's types are written out")) + (test-assert "and a closure's" + (reports? (in-fn "(var c (closure ((int)) int) (closure ((x int)) _ () (return x)))") + "a function's types are written out")) (test-assert "while a function is the pointer it already is" (emits? "(fn g ((n int)) int (return n)) (fn f () void (var p _ g))" "int (*p)(int) = g")) -- 2.52.0 From 4fa8a021de38108ae88e4058efb166463e3c26d9 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 10:23:59 +0300 Subject: [PATCH 46/74] say where a reader error was met Every later stage's error says file:line, and the reader's said only what; an unclosed list, met at the end of the file, now names the line it opened on as well. --- reader.scm | 50 +++++++++++++++++++++++++++++++----------------- tests/reader.scm | 20 +++++++++++++++++-- 2 files changed, 50 insertions(+), 20 deletions(-) diff --git a/reader.scm b/reader.scm index 162b0b6..1858d5e 100644 --- a/reader.scm +++ b/reader.scm @@ -16,6 +16,7 @@ scheme (scheme base) ; make-parameter (chicken base) + (chicken condition) (chicken irregex) (chicken module) (chicken pathname) @@ -99,11 +100,11 @@ ((char=? c #\() (let ((line (current-line))) (get-ch port) - (stamp (read-list port close-paren) line))) + (stamp (read-list port close-paren line) line))) ((char=? c #\[) (let ((line (current-line))) (get-ch port) - (stamp (cons '¤ (read-list port close-bracket)) line))) + (stamp (cons '¤ (read-list port close-bracket line)) line))) ((char=? c #\)) (get-ch port) close-paren) ((char=? c #\]) (get-ch port) close-bracket) ((char=? c #\;) @@ -148,11 +149,14 @@ ;;; Read list elements up to close-paren or close-bracket, ;;; honoring dotted-pair notation (a b . c) -(define (read-list port closer) +(define (read-list port closer opened) (let loop ((acc (list))) (let ((tok (next-token port))) (cond - ((eof-object? tok) (error "Unexpected end of input inside list")) + ((eof-object? tok) + (error (string-append + "Unexpected end of input inside a list opened on line " + (number->string opened)))) ((eq? tok close-paren) (if (eq? closer close-paren) (reverse acc) @@ -357,7 +361,7 @@ ((or (char=? c #\t) (char=? c #\T)) (read-bool port #t)) ((or (char=? c #\f) (char=? c #\F)) (read-bool port #f)) ((char=? c #\\) (read-char-lit port)) - ((char=? c #\() (list->vector (read-list port close-paren))) + ((char=? c #\() (list->vector (read-list port close-paren (current-line)))) ((memv c '(#\x #\X)) (read-radix port 16)) ((memv c '(#\b #\B)) (read-radix port 2)) ((memv c '(#\o #\O)) (read-radix port 8)) @@ -546,21 +550,31 @@ (else (skip-block-comment port depth)))))) ;;; Read every top-level form from `port'. Locations are recorded by -;;; next-token, for every form rather than only these +;;; next-token, for every form rather than only these. An error says +;;; where it was met, the way a later stage's says where its form was +;;; written: file:line: what (define (parse-all port) (parameterize ((current-line 1)) - (let loop ((acc (list))) - (skip-whitespace port) - (let ((tok (next-token port))) - (cond - ((eof-object? tok) (reverse acc)) - ((or (eq? tok close-paren) - (eq? tok close-bracket)) - (error "Unmatched closing bracket at top level")) - ((eq? tok dot-token) - (error "Unexpected . at top level")) - (else - (loop (cons tok acc)))))))) + (handle-exceptions e + (let ((message ((condition-property-accessor 'exn 'message #f) e))) + (if message + (apply error + (string-append (current-source-file) ":" + (number->string (current-line)) ": " message) + ((condition-property-accessor 'exn 'arguments (list)) e)) + (abort e))) + (let loop ((acc (list))) + (skip-whitespace port) + (let ((tok (next-token port))) + (cond + ((eof-object? tok) (reverse acc)) + ((or (eq? tok close-paren) + (eq? tok close-bracket)) + (error "Unmatched closing bracket at top level")) + ((eq? tok dot-token) + (error "Unexpected . at top level")) + (else + (loop (cons tok acc))))))))) ;;; Entry point: read all forms from a file, or from the current input ;;; port when the source is 'stdin diff --git a/tests/reader.scm b/tests/reader.scm index dde7bbe..c32184d 100644 --- a/tests/reader.scm +++ b/tests/reader.scm @@ -1,4 +1,5 @@ (import (chicken condition) + (chicken irregex) (chicken port) reader) @@ -10,12 +11,18 @@ (with-input-from-string string (lambda () (read-raw-forms 'stdin)))))))) -(define (read-error string) - "The message of the error reading STRING raises, or #f if it reads." +(define (read-error-at string) + "The message of the error reading STRING raises, where included, or +#f if it reads." (handle-exceptions e ((condition-property-accessor 'exn 'message) e) (with-input-from-string string (lambda () (read-raw-forms 'stdin))) #f)) +(define (read-error string) + "The message of the error reading STRING raises, or #f if it reads." + (let ((message (read-error-at string))) + (and message (irregex-replace "^[^:]*:[0-9]+: " message "")))) + (define-syntax reader-test (syntax-rules () ((reader-test result string) @@ -123,6 +130,15 @@ (test "Latin-1 is no exception" #t (string? (read-error "#\\é"))) (reader-test '(#\a #\~ #\space) "#\\a #\\~ #\\space") + ;; A reader error said what and not where, which the error of every + ;; later stage does + (test "a reader error says where" + "stdin:2: unknown escape" + (read-error-at "(a)\n\"\\q\"")) + (test "an unclosed list, where it opened" + "stdin:3: Unexpected end of input inside a list opened on line 2" + (read-error-at "(a)\n(b\n (c)")) + ;; `;' comments are preserved as (comment "...") forms (reader-test '((comment " hi")) "; hi") (reader-test '((comment ";; Prototypes")) ";;; Prototypes") -- 2.52.0 From 8e3e6fcdd1257807f4871b2d36f99d4bf4a77588 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 10:23:59 +0300 Subject: [PATCH 47/74] say which macro call an error came from A wrong argument count was CHICKEN's to report, about a procedure with no name, and an error raised in a macro's body said nothing of the call. --- sex-macros.scm | 34 +++++++++++++++++++++++++++++++--- tests/codegen.scm | 17 ++++++++++++++++- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/sex-macros.scm b/sex-macros.scm index 54017df..66906e6 100644 --- a/sex-macros.scm +++ b/sex-macros.scm @@ -2,9 +2,12 @@ scheme (only fmt fmt) (chicken base) + (chicken condition) + (chicken irregex) (chicken module) (chicken plist) - (chicken string)) + (chicken string) + utils) (export cat @@ -55,11 +58,36 @@ (symbol? (car form)) (get (car form) 'sex-macro))) +;;; CHICKEN would report a wrong argument count about a procedure with +;;; no name, and an error raised in a macro's body without the call: both +;;; are told here, where the call is known (define (apply-macro form) (assert (macro? form) (fmt #f (car form) " is not a macro")) - (apply (get-macro (car form)) - (cdr form))) + (let ((name (car form))) + (check-macro-arity form name (cadr (get name 'sex-macro)) (length (cdr form))) + (handle-exceptions e + (let ((message ((condition-property-accessor 'exn 'message #f) e))) + ;; one raised about a form of its own already says where + (if (and message (not (irregex-search "^[^ ]+:[0-9]+: " message))) + (apply sex-error form + (string-append "expanding " (symbol->string name) + ": " message) + ((condition-property-accessor 'exn 'arguments (list)) e)) + (abort e))) + (apply (get-macro name) (cdr form))))) + +;;; (defmacro (one x) ...) takes one; (defmacro (many x . more) ...) one +;;; or more +(define (check-macro-arity form name arglist given) + (let count ((args arglist) (required 0)) + (cond ((pair? args) (count (cdr args) (+ required 1))) + ((null? args) + (unless (= given required) + (sex-error form "macro takes this many arguments" name required))) + ((< given required) + (sex-error form "macro takes at least this many arguments" + name required))))) (define (defmacro form) (let ((arglist (car form)) diff --git a/tests/codegen.scm b/tests/codegen.scm index db3adb4..f647145 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -315,7 +315,22 @@ (test-assert "the offending form is shown too" (reports? "(include stdio.h)\n(wat 1 2)" "(wat 1 2)")) (test-assert "pub with nothing to define" - (reports? "(pub 1)" "codegen.sex:1:"))) + (reports? "(pub 1)" "codegen.sex:1:")) + ;; a macro's arity was CHICKEN's to report, about a procedure with + ;; no name; and an error in its body said nothing of the call + (test-assert "a macro given the wrong number of arguments" + (reports? "(defmacro (one x) x)\n(fn f () int\n (return (one 1 2)))" + "codegen.sex:3: macro takes this many arguments one 1")) + (test-assert "at toplevel too" + (reports? "(defmacro (one x) x)\n(one)" "codegen.sex:2: macro takes this many arguments")) + (test-assert "and one taking the rest, too few" + (reports? "(defmacro (many x . more) x)\n(fn f () int (return (many)))" + "macro takes at least this many arguments many 1")) + (test-assert "while it may take any more" + (emits? "(defmacro (many x . more) x) (fn f () int (return (many 1 2 3)))" "return 1;")) + (test-assert "an error in a macro's body names the call" + (reports? "(defmacro (boom x) (error \"no good\" x))\n(fn f () int (return (boom 1)))" + "codegen.sex:2: expanding boom: no good"))) ;; A grouped header, C's parens carried over, died in the writer with ;; `(caddr) bad argument type' and no location -- 2.52.0 From dd5174f4727422debaa971d0d69e57c4d05b76c4 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 10:23:59 +0300 Subject: [PATCH 48/74] refuse a statement of the wrong shape (goto), (var q), (cast i), (while) and the like died in the writer, in CHICKEN's words about a procedure of its own and with no location; (return 1 2), (break 1) and (sizeof a b) dropped what was extra. --- semen.scm | 26 ++++++++++++++++++++++++++ tests/codegen.scm | 30 ++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/semen.scm b/semen.scm index 7f06de7..9fc4aa7 100644 --- a/semen.scm +++ b/semen.scm @@ -619,6 +619,7 @@ (walk-statement (car expansion) env) (cons walk-embed-result (walk-body expansion env))))) (else + (check-shape form) (case (car form) ((do default) (parameterize ((operand-position? #f)) @@ -735,6 +736,30 @@ (convert-arguments (copy-form-source! form (walk-operands form form env)) env)))))))) +;;; How many operands each of these takes, and how it is written: one +;;; with any other number died in the writer, in CHICKEN's words about a +;;; procedure of the writer's +(define +shapes+ + '((goto 1 1 "(goto label)") + (: 1 1 "(: label)") + (var 2 3 "(var name type value)") + (cast 2 2 "(cast value type)") + (while 1 #f "(while test body ...)") + (if 2 #f "(if test then else)") + (return 0 1 "(return value)") + (break 0 0 "(break)") + (continue 0 0 "(continue)") + (sizeof 1 1 "(sizeof value)"))) + +(define (check-shape form) + (let ((shape (assq (car form) +shapes+)) + (given (count (lambda (part) (not (comment-form? part))) (cdr form)))) + (when (and shape + (not (and (>= given (second shape)) + (or (not (third shape)) (<= given (third shape)))))) + (sex-error form (string-append "malformed " (symbol->string (car form)) + ": write " (fourth shape)))))) + ;;; (shape/circle 1.0) is the value itself, written where it is used: ;;; ;;; (shape){.tag = shapeǂcircle, .u = {.circle = (struct shapeːcircle){1.0}}} @@ -2142,6 +2167,7 @@ ;;; (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) + (check-shape (if (memq (car sex-var) '(pub extern)) (cdr sex-var) sex-var)) (let* ((resolved (resolve-closure-types sex-var)) (qualifier (and (memq (car resolved) '(pub extern)) (car resolved))) (core (if qualifier (cdr resolved) resolved)) diff --git a/tests/codegen.scm b/tests/codegen.scm index f647145..8f7a72a 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -351,6 +351,36 @@ (reports? "(fn f () void\n (for ((var i int 0) (< i 4) (++ i)) (g i)))" "codegen.sex:2:"))) + ;; each of these died in the writer, in CHICKEN's words about a + ;; procedure of the writer's, and with no location + (test-group "malformed forms" + (test-assert "a goto names one label" + (reports? (in-fn "(goto)") "malformed goto: write (goto label)")) + (test-assert "and only one" + (reports? (in-fn "(goto a b)") "malformed goto")) + (test-assert "so does a label" + (reports? (in-fn "(: a b)") "malformed :: write (: label)")) + (test-assert "a var has a name and a type" + (reports? (in-fn "(var q)") "malformed var")) + (test-assert "and a value at most" + (reports? (in-fn "(var q int 1 2)") "malformed var")) + (test-assert "a cast a value and a type" + (reports? (in-fn "(var n int (cast a))") "malformed cast: write (cast value type)")) + (test-assert "a while its test" + (reports? (in-fn "(while)") "malformed while")) + (test-assert "an if its test and what it does" + (reports? (in-fn "(if a)") "malformed if")) + (test-assert "a return one value at most" + (reports? (in-fn "(return 1 2)") "malformed return")) + (test-assert "a break none" + (reports? (in-fn "(while a (break 1))") "malformed break")) + (test-assert "a sizeof one operand" + (reports? (in-fn "(var n size-t (sizeof a b))") "malformed sizeof")) + (test-assert "a global var is held to the same" + (reports? "(var q)" "malformed var")) + (test-assert "each naming its line" + (reports? "(fn f () void\n (goto))" "codegen.sex:2: malformed goto"))) + ;; a block of nothing had nothing for c-begin to begin with, and the ;; writer died on its arity (test-group "empty bodies" -- 2.52.0 From 8220c500dfc37cbd1e6e272acf494956cf7befe2 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 10:23:59 +0300 Subject: [PATCH 49/74] refuse a malformed closure capture ((+ a 1)) was a capture named `+' holding a. --- semen.scm | 5 +++-- tests/codegen.scm | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/semen.scm b/semen.scm index 9fc4aa7..1bad337 100644 --- a/semen.scm +++ b/semen.scm @@ -1863,8 +1863,9 @@ ;;; `(* int)' inside the body and `a' is never mentioned there. (define (capture-binding capture form env) (let ((name (capture-name capture))) - (unless (symbol? name) - (sex-error form "a closure capture needs a name" capture)) + ;; ((+ a 1)) was a capture named `+' holding a + (unless (and (symbol? name) (or (symbol? capture) (= 2 (length capture)))) + (sex-error form "a capture is a name, or (name value)" capture)) ;; the same lookup either way, so `(closure ((x int)) int (scale) ;; ...)' borrows a global's `scale' as readily as a local's (let ((type (expression-type (capture-argument capture) env))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 8f7a72a..2a66f23 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -469,6 +469,10 @@ ;; captures are a closure's other parameters, under C's rule for ;; those: no two alike, and none redeclared at the body's top level. ;; Both were C's redefinition errors + ;; ((+ a 1)) was a capture named `+', holding a + (test-assert "a capture is a name, or a name and a value" + (reports? (in-fn "(var c (closure () int) (closure () int ((+ a 1)) (return 1)))") + "a capture is a name, or (name value)")) (test-assert "a capture named like a parameter is refused" (reports? (in-fn "(var c (closure ((int)) int) (closure ((a int)) int (a) (return a)))") "a capture and a parameter share a name")) -- 2.52.0 From 5afe32a888edc5ea4a410c3d647a56140965baec Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 10:23:59 +0300 Subject: [PATCH 50/74] read a lone - as stdin getopt-long read it as an option it did not know, and died. --- sexc.scm | 13 +++++++++---- tests/exit-code/check.scm | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/sexc.scm b/sexc.scm index 001da07..a7af373 100644 --- a/sexc.scm +++ b/sexc.scm @@ -121,6 +121,12 @@ (loop (cddr as) (cons "--output=-" acc))) (else (loop (cdr as) (cons (car as) acc)))))) +;;; ...and a lone `-' left after that is the input, which is stdin: one +;;; getopt-long would read as an option it did not know, so it is taken +;;; out before +(define (stdin-dash? argv) + (and (member "-" argv) #t)) + (define (get-rest-args args) (cdr (assoc '@ args))) @@ -250,14 +256,13 @@ status, which is ours to pass on." (define (main) (let* ((argv (command-line-arguments)) - (raw-args (args-before-separator argv)) + (raw-args (spell-stdout-output (args-before-separator argv))) (cc-args (args-after-separator argv)) - (args (getopt-long (spell-stdout-output raw-args) - opts-grammar)) + (args (getopt-long (delete "-" raw-args) opts-grammar)) (output (get-arg args 'output 'default)) (help (help-arg? args)) - (input (get-input-file args)) + (input (if (stdin-dash? raw-args) 'stdin (get-input-file args))) (current-dir (current-directory))) (call/cc (lambda (return) diff --git a/tests/exit-code/check.scm b/tests/exit-code/check.scm index b3b31e4..2160bb3 100644 --- a/tests/exit-code/check.scm +++ b/tests/exit-code/check.scm @@ -15,6 +15,7 @@ (import scheme (chicken base) (chicken file) + (chicken io) (chicken pathname) (chicken process) (chicken process-context) @@ -33,6 +34,18 @@ (define out (make-pathname scratch "out")) (set-environment-variable! "TMPDIR" scratch) +;;; (status stdout stderr) of sexc run with ARGS, and INPUT, when one +;;; is given, on its stdin +(define (sexc-run input . args) + (let ((proc (process* sexc args))) + (when input (display input (process-input-port proc))) + (close-output-port (process-input-port proc)) + (let* ((text (lambda (s) (if (eof-object? s) "" s))) + (out (text (read-string #f (process-output-port proc)))) + (err (text (read-string #f (process-error-port proc))))) + (process-wait proc) + (list (process-exit-status proc) out err)))) + ;;; Whether sexc exits 0 when run with ARGS, saying nothing of it (define (sexc-succeeds? . args) (zero? (system (string-append (string-intersperse (map qs (cons sexc args))) @@ -52,6 +65,12 @@ (sexc-succeeds? "hello.sex" "-o" out "--" "-no-such-cc-flag")) (define hello (make-pathname (current-directory) "hello.sex")) +(define hello-source (call-with-input-file hello (lambda (p) (read-string #f p)))) + +;;; getopt-long read a lone `-' as an option it did not know, and died +(test-assert "- is stdin" + (let ((run (sexc-run hello-source "-" "-C" "-o" "-"))) + (and (zero? (car run)) (substring-index "main" (cadr run)) #t))) (change-directory scratch) (test "-o - is refused for an executable" #f -- 2.52.0 From 83282adfb9ada61246471b4944b5736cdd99e336 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 10:23:59 +0300 Subject: [PATCH 51/74] leave none of an output a failure stopped writing A failed -C -o left the file truncated, which make would take for done. --- sexc.scm | 8 ++++++-- tests/exit-code/check.scm | 9 ++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/sexc.scm b/sexc.scm index a7af373..812556c 100644 --- a/sexc.scm +++ b/sexc.scm @@ -164,8 +164,12 @@ (define (write-to-file-or-stdout output what) (if (stdout-output? output) (what) - (with-output-to-file output - (fn (what))))) + ;; a failure part way through leaves none of the file, which make + ;; would take for done + (handle-exceptions exn + (begin (delete-file* output) (abort exn)) + (with-output-to-file output + (fn (what)))))) (define (emit-c-or-sex sex-forms output args) (write-to-file-or-stdout output diff --git a/tests/exit-code/check.scm b/tests/exit-code/check.scm index 2160bb3..5d8a431 100644 --- a/tests/exit-code/check.scm +++ b/tests/exit-code/check.scm @@ -3,7 +3,8 @@ ;;; Each needs a process to show itself, so none fits the unit suite: ;;; sexc has to fail when cc fails -- exiting 0 after a failed compile ;;; makes every driver, sextest included, read it as success -- it has to -;;; clean up its temporary .c when its own emission throws, and it has to +;;; clean up its temporary .c, and any output it began, when its own +;;; emission throws, and it has to ;;; refuse `-o -' for an executable, which cc would write to a file named ;;; `-'. ;;; @@ -61,6 +62,12 @@ (sexc-succeeds? "nested-pointer.sex" "-o" out) (glob (make-pathname scratch "*.c")))) +;; and none of a file it was writing out, which make would take for done +(test "a failed emission leaves no part of its output" #f + (begin + (sexc-succeeds? "nested-pointer.sex" "-C" "-o" (make-pathname scratch "out.c")) + (file-exists? (make-pathname scratch "out.c")))) + (test "a failed cc fails sexc" #f (sexc-succeeds? "hello.sex" "-o" out "--" "-no-such-cc-flag")) -- 2.52.0 From 389e73323f3471e49de9118d40f4fed16a951fb3 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 10:23:59 +0300 Subject: [PATCH 52/74] refuse a second input file It was never read, and nothing said so. --- sexc.scm | 15 +++++++++------ tests/exit-code/check.scm | 12 ++++++++++++ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/sexc.scm b/sexc.scm index 812556c..dad79b8 100644 --- a/sexc.scm +++ b/sexc.scm @@ -146,11 +146,14 @@ (map string->symbol (string-split (cdr entry) ","))) (filter (lambda (entry) (eq? (car entry) 'features)) args))) -(define (get-input-file args) - (let ((rest-args (get-rest-args args))) - (if (null? rest-args) - 'stdin - (car rest-args)))) +(define (get-input-file args dash?) + (let ((inputs (append (if dash? (list "-") (list)) (get-rest-args args)))) + (cond ((null? inputs) 'stdin) + ;; any after the first were never read, and nothing said so + ((pair? (cdr inputs)) + (apply error "sexc compiles one input file at a time; given" inputs)) + (dash? 'stdin) + (else (car inputs))))) (define (stdout-output? output) (or (eq? output 'default) (equal? output "-"))) @@ -266,7 +269,7 @@ status, which is ours to pass on." (output (get-arg args 'output 'default)) (help (help-arg? args)) - (input (if (stdin-dash? raw-args) 'stdin (get-input-file args))) + (input (get-input-file args (stdin-dash? raw-args))) (current-dir (current-directory))) (call/cc (lambda (return) diff --git a/tests/exit-code/check.scm b/tests/exit-code/check.scm index 5d8a431..1faf58b 100644 --- a/tests/exit-code/check.scm +++ b/tests/exit-code/check.scm @@ -80,6 +80,18 @@ (and (zero? (car run)) (substring-index "main" (cadr run)) #t))) (change-directory scratch) +;;; the second was never read, and nothing said so +(test-assert "a second input is refused" + (let ((run (sexc-run #f hello hello "-C" "-o" "-"))) + (and (not (zero? (car run))) + (substring-index "one input file at a time" (caddr run)) + #t))) +(test-assert "stdin besides a file too" + (let ((run (sexc-run hello-source "-" hello "-C" "-o" "-"))) + (and (not (zero? (car run))) + (substring-index "one input file at a time" (caddr run)) + #t))) + (test "-o - is refused for an executable" #f (sexc-succeeds? hello "-o" "-")) -- 2.52.0 From 7649e47297b4e9a3d36b1192f53c6a9103f4dd24 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 10:23:59 +0300 Subject: [PATCH 53/74] refuse an output naming the source -o naming the input wrote over it, whatever was asked for. --- sexc.scm | 9 +++++++++ tests/exit-code/check.scm | 10 ++++++++++ 2 files changed, 19 insertions(+) diff --git a/sexc.scm b/sexc.scm index dad79b8..558d5f0 100644 --- a/sexc.scm +++ b/sexc.scm @@ -5,6 +5,7 @@ (chicken condition) ; handle-exceptions (chicken file) (chicken module) + (only (chicken pathname) normalize-pathname) (chicken plist) (chicken pretty-print) (chicken process) @@ -155,6 +156,12 @@ (dash? 'stdin) (else (car inputs))))) +;;; Whether OUTPUT is the file INPUT, spelled however it is +(define (same-file? input output) + (and (string? input) (string? output) (not (stdout-output? output)) + (equal? (normalize-pathname (to-absolute-pathname input)) + (normalize-pathname (to-absolute-pathname output))))) + (define (stdout-output? output) (or (eq? output 'default) (equal? output "-"))) @@ -278,6 +285,8 @@ status, which is ours to pass on." (return #f)) (when (and (equal? output "-") (not (text-output? args))) (error "-o - is stdout, which takes only -C, -m or --public-interface")) + (when (same-file? input output) + (error "-o names the input, and would overwrite its source" input)) ;; Read time comes before everything, so the features have to be ;; in place before the first form is read (current-features diff --git a/tests/exit-code/check.scm b/tests/exit-code/check.scm index 1faf58b..90307bc 100644 --- a/tests/exit-code/check.scm +++ b/tests/exit-code/check.scm @@ -98,6 +98,16 @@ (test "and leaves no file named -" #f (file-exists? "-")) +;;; -o naming the source overwrote it, whatever was asked for +(call-with-output-file "victim.sex" (lambda (p) (display hello-source p))) +(test-assert "an output naming the source is refused" + (let ((run (sexc-run #f "victim.sex" "-C" "-o" "./victim.sex"))) + (and (not (zero? (car run))) + (substring-index "would overwrite its source" (caddr run)) + #t))) +(test "and the source is as it was" hello-source + (call-with-input-file "victim.sex" (lambda (p) (read-string #f p)))) + (delete-directory scratch #t) (test-exit) -- 2.52.0 From fb26b92fdc77be67e2d04a4284e8e30e797d252e Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 10:23:59 +0300 Subject: [PATCH 54/74] print an error as its message alone Every error ended in CHICKEN's call history, which is for working on sexc itself, and is now asked for by SEXC_DEBUG; a missing input file says so, rather than as an open-input-file error of CHICKEN's. --- sexc.scm | 24 ++++++++++++++++++++++++ tests/exit-code/check.scm | 19 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/sexc.scm b/sexc.scm index 558d5f0..e2a9c71 100644 --- a/sexc.scm +++ b/sexc.scm @@ -268,7 +268,29 @@ status, which is ours to pass on." ;; every module (list (closure-env-declaration)))) +;;; An error is told by its message, file:line first where it has one. +;;; CHICKEN's call history after it is for working on sexc itself, and +;;; SEXC_DEBUG asks for it (define (main) + (if (get-environment-variable "SEXC_DEBUG") + (run) + (handle-exceptions exn + (let ((message ((condition-property-accessor 'exn 'message #f) exn)) + (port (current-error-port))) + (unless message (abort exn)) + (display "Error: " port) + (display message port) + (let ((arguments + ((condition-property-accessor 'exn 'arguments (list)) exn))) + (unless (null? arguments) + (display ":" port) + (for-each (lambda (a) (display " " port) (write a port)) + arguments))) + (newline port) + (exit 70)) + (run)))) + +(define (run) (let* ((argv (command-line-arguments)) (raw-args (spell-stdout-output (args-before-separator argv))) (cc-args (args-after-separator argv)) @@ -287,6 +309,8 @@ status, which is ours to pass on." (error "-o - is stdout, which takes only -C, -m or --public-interface")) (when (same-file? input output) (error "-o names the input, and would overwrite its source" input)) + (when (and (string? input) (not (file-exists? input))) + (error (string-append input ": no such file"))) ;; Read time comes before everything, so the features have to be ;; in place before the first form is read (current-features diff --git a/tests/exit-code/check.scm b/tests/exit-code/check.scm index 90307bc..f35035d 100644 --- a/tests/exit-code/check.scm +++ b/tests/exit-code/check.scm @@ -108,6 +108,25 @@ (test "and the source is as it was" hello-source (call-with-input-file "victim.sex" (lambda (p) (read-string #f p)))) +;;; An error is its message: CHICKEN's call history after it is for +;;; working on sexc itself, and asked for by SEXC_DEBUG +(test-assert "a missing input says so" + (let ((run (sexc-run #f "no-such.sex"))) + (and (not (zero? (car run))) + (substring-index "no-such.sex: no such file" (caddr run)) + (not (substring-index "Call history" (caddr run)))))) +(test-assert "and any error is its message alone" + (let ((run (sexc-run "(fn f () int (return \"\\q\"))" "-C" "-o" "-"))) + (and (= 70 (car run)) + (substring-index "Error: stdin:1: unknown escape" (caddr run)) + (not (substring-index "Call history" (caddr run)))))) +(test-assert "unless the history is asked for" + (begin + (set-environment-variable! "SEXC_DEBUG" "1") + (let ((run (sexc-run "(fn f () int (return \"\\q\"))" "-C" "-o" "-"))) + (unset-environment-variable! "SEXC_DEBUG") + (and (substring-index "Call history" (caddr run)) #t)))) + (delete-directory scratch #t) (test-exit) -- 2.52.0 From 6ad8f8f56babc28f3d772fc36dc9b9043728fc7e Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 13:38:30 +0300 Subject: [PATCH 55/74] keep the writer's own words to the head of a form They were its own wherever they stood, so a name spelled like one -- (var array int), a parameter `define' -- came out %array, %define. --- fmt-c-writer.scm | 39 ++++++++++++++++++++++++--------------- tests/codegen.scm | 17 +++++++++++++++++ 2 files changed, 41 insertions(+), 15 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 9a40dc1..dae2ca4 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -177,6 +177,12 @@ forms, and what remains." (unkebabify atom) atom)))) +;;; A name as C spells it. Only at the head of a form are some words +;;; the writer's own: (array ...) is one, (var array int) declares +;;; `array', where it came out `%array' +(define (name-to-fmt-c atom) + (if (symbol? atom) (unkebabify atom) atom)) + (define (maybe-unwrap-type type) (if (and (list? type) (= 1 (length type))) @@ -221,7 +227,7 @@ forms, and what remains." (match form ((? vector?) (walk-initializer (vector->list form))) ((? atom?) - (atom-to-fmt-c form)) + (name-to-fmt-c form)) ;; (comment "text") -> /* text */. `%comment' is the fmt-c directive. (('comment . text) (walk-comment text)) ;; (dot-access obj field ...) -> obj.field... member access. `%.' @@ -236,7 +242,7 @@ forms, and what remains." (('sizeof ('%type type)) `(%sizeof-type ,(walk-type type))) ;; semen has already put the target first, the way C writes it (('typedef type name) - `(typedef ,(walk-type type) ,(atom-to-fmt-c name))) + `(typedef ,(walk-type type) ,(name-to-fmt-c name))) ;; An expression has no room for a statement, so a comment in a ;; cast is dropped rather than relocated. (('cast . rest) @@ -294,7 +300,10 @@ forms, and what remains." ;; C's comma where it is a value (cons '%comma (map (lambda (operand) (walk-expr (list (car form) operand))) (cdr form))) - (map walk-expr form)))))) + (cons (if (symbol? (car form)) + (atom-to-fmt-c (car form)) + (walk-expr (car form))) + (map walk-expr (cdr form)))))))) (define +comparisons+ '(< > <= >= == !=)) @@ -383,7 +392,7 @@ forms, and what remains." (((? designator? d) value . rest) (loop rest (cons (list '%designate - (atom-to-fmt-c (designator-field d)) + (name-to-fmt-c (designator-field d)) (walk-expr value)) acc))) ;; [3] 1: an element named by its index. A subscript has two @@ -414,7 +423,7 @@ forms, and what remains." (let ((form (cons (car form) (remove comment-form? (cdr form))))) `(%var ,(walk-type (third form)) - ,(atom-to-fmt-c (second form)) + ,(name-to-fmt-c (second form)) . ,(if (null? (drop form 3)) (list) @@ -485,7 +494,7 @@ forms, and what remains." ;; (fn ...) is spelled as the pointer it already is in C (sex-error type "a fn type is a function pointer already: write (fn ...), not (* (fn ...))" type) (sex-error type "a pointer to an array is not supported" type)))) - (if (atom? type) (atom-to-fmt-c type) + (if (atom? type) (name-to-fmt-c type) (type-words (list-join (reverse (list-split type '*)) '(*))))) ;;; A type's words, flat, except that an aggregate written out in full is @@ -495,7 +504,7 @@ forms, and what remains." (cond ((inline-aggregate? item) (list (walk-type item))) ((pair? item) (type-words item)) ((null? item) (list)) - (else (list (atom-to-fmt-c item))))) + (else (list (name-to-fmt-c item))))) items)) ;;; (struct ((c int))), (union u (...)), (enum (red green)): a body, not @@ -508,7 +517,7 @@ forms, and what remains." (('fn name args ret-type . maybe-body) `(%fun ,(walk-type ret-type) - ,(atom-to-fmt-c name) + ,(name-to-fmt-c name) ,(walk-arglist args) . ,(let ((body (walk-body maybe-body))) @@ -559,7 +568,7 @@ forms, and what remains." (define (process-struct-fields fields) (map (fn (let ((type (walk-type (last x)))) - (cons type (map atom-to-fmt-c (drop-right x 1))))) + (cons type (map name-to-fmt-c (drop-right x 1))))) (remove comment-form? fields))) (define (walk-struct form) @@ -568,9 +577,9 @@ forms, and what remains." `(,type ,(process-struct-fields fields) . ,(tree-map atom-to-fmt-c attrs))) ((type name) ; simple 'struct whatever', like in variable def - `(,type ,(atom-to-fmt-c name))) + `(,type ,(name-to-fmt-c name))) ((type name (fields ...) . attrs) - `(,type ,(atom-to-fmt-c name) + `(,type ,(name-to-fmt-c name) ,(process-struct-fields fields) . ,(tree-map atom-to-fmt-c attrs))) (else (sex-error form "malformed aggregate definition" form)))) @@ -582,18 +591,18 @@ forms, and what remains." ;; before the anonymous case, since `(enum (red green))' is also a ;; two-element form (('enum (? symbol? name)) - `(enum ,(atom-to-fmt-c name))) + `(enum ,(name-to-fmt-c name))) (('enum (values ...)) `(enum ,(map walk-enumerator values))) (('enum name (values ...)) - `(enum ,(atom-to-fmt-c name) ,(map walk-enumerator values))) + `(enum ,(name-to-fmt-c name) ,(map walk-enumerator values))) (else (sex-error form "malformed enum" form)))) ;;; red -> red, (wire-varint 0) -> wire_varint = 0 (define (walk-enumerator value) (match value - (((? enumerator-name? name) expr) (list (atom-to-fmt-c name) (walk-expr expr))) - ((? enumerator-name?) (atom-to-fmt-c value)) + (((? enumerator-name? name) expr) (list (name-to-fmt-c name) (walk-expr expr))) + ((? enumerator-name?) (name-to-fmt-c value)) ;; anything else was taken apart as if it were the pair: (! 1 2) ;; came out `! = 1' (_ (sex-error value "an enumerator is a name, or (name value)" value)))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 2a66f23..2303a54 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -954,6 +954,23 @@ (emits? "(fn take ((f (fn ((int)) (fn () void)))) void (return))" "take (void (*(*f)(int))())"))) + ;; the writer's own words were its own wherever they stood, so a + ;; name spelled like one came out `%array' + (test-group "names the writer has words for" + (test-assert "as variables" + (emits? (in-fn "(var array int 1) (var define int 2) (var include int 3) (g array define include)") + "g(array, define, include)")) + (test-assert "as parameters" + (emits? "(fn sum ((array (* int)) (pointer int)) int (return (+ [array 0] pointer)))" + "sum (int * array, int pointer)")) + (test-assert "as fields" + (emits? "(struct s ((prototype int) (attribute int)))" "int prototype;")) + (test-assert "as a typedef's name, and used as a type" + (emits? "(typedef array int) (fn f () void (var a array 1))" " array a = 1;")) + (test-assert "while at a form's head they are the writer's still" + (emits? "(include stdio.h) (fn f () void (static-assert (== 1 1) \"x\"))" + "_Static_assert(1 == 1, \"x\")"))) + ;; Operands past what an operator takes were written as they came: ;; (< a b c) as C's own chain, which compares a boolean with c (test-group "operator arity" -- 2.52.0 From 1bdeda6cc35906e0e327ff22ef8753deb9a5dd33 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 13:38:30 +0300 Subject: [PATCH 56/74] name a lambda's unnamed parameters in its definition A definition names every parameter before C23, as a closure's code already does. --- semen.scm | 9 ++++++--- tests/codegen.scm | 8 ++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/semen.scm b/semen.scm index 1bad337..9871fd1 100644 --- a/semen.scm +++ b/semen.scm @@ -1568,8 +1568,10 @@ (define (lift-lambda name form) (match form (('lambda arglist ret-type . body) - (process-fn (copy-form-source! form `(fn ,name ,arglist ,ret-type - ,@(defining body))) + (process-fn (copy-form-source! + form + `(fn ,name ,(named-parameters arglist) ,ret-type + ,@(defining body))) (list))) (else (sex-error form "malformed lambda" form)))) @@ -1935,7 +1937,8 @@ ;;; type alone gets a name nothing reads: ((int) (b int)) -> ((ƛu0 int) (b int)) (define (named-parameters arglist) (map (lambda (arg index) - (if (or (named-arg? arg) (comment-form? arg)) + (if (or (named-arg? arg) (comment-form? arg) + (eq? arg '...) (equal? arg '(...))) arg (list (string->symbol (string-append "ƛu" (number->string index))) (unwrap-type arg)))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 2303a54..90b26a7 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -490,6 +490,14 @@ (test-assert "and its code names it, a definition needing one before C23" (emits? (in-fn "(var c (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b)))") "int ƛu0, int b)")) + ;; a definition names every parameter before C23, a lambda's as a + ;; closure's code does + (test-assert "a lambda's unnamed parameter is named in its definition" + (emits? "(fn f () void (var g (fn ((int) (int)) int) (lambda ((int) (b int)) int (return b))))" + "λ0_f (int ƛu0, int b)")) + (test-assert "and a variadic one keeps its ..." + (emits? "(fn f () void (var g (fn ((int) ...) int) (lambda ((n int) ...) int (return n))))" + "λ0_f (int n, ...)")) ;; a lifted function with no body was a declaration of one, and ;; nothing defined it (test-assert "an empty lambda is an empty function" -- 2.52.0 From 2024d4d0f433560722ebdff2ef33dcad2b884b92 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 13:38:30 +0300 Subject: [PATCH 57/74] type a call by the type of what it calls Only a function's name was asked what it returns, so a call through a local or a field holding a pointer had no type, a local named like a function took the function's, and a closure's call helper, which nothing registered, left _ nothing to read. --- semen.scm | 20 +++++++++++++++++++- tests/codegen.scm | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/semen.scm b/semen.scm index 9871fd1..aa7eed5 100644 --- a/semen.scm +++ b/semen.scm @@ -1392,7 +1392,19 @@ (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)))))))))) + ;; a function's name, unless a local hides it + ((and (symbol? (car expr)) + (not (lookup-name env (car expr))) + (get-return-type (car expr))) + => identity) + ;; a pointer to one: a local, a parameter, a field, a call's result + (else (function-return (expression-type (car expr) env))))))))) + +;;; (fn ((int)) int) -> int, and through a typedef of one +(define (function-return type) + (cond ((and (pair? type) (eq? (car type) 'fn) (= 3 (length type))) (third type)) + ((and (symbol? type) (get-underlying-type type)) => function-return) + (else #f))) ;;; (.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 @@ -1827,6 +1839,12 @@ (unwrap-type arg))) (second type) (iota (length (second type)))))) + ;; what it returns, for `_' to read: it goes out as written, and + ;; nothing else registers it + (add-name-type! helper + `(fn (((struct ,closure)) + ,@(map (lambda (p) (list (second p))) params)) + ,returns)) (unless (hash-table-ref/default +closure-calls+ helper #f) (hash-table-set! +closure-calls+ helper #t) (let ((call `((dot-access ƛc code) diff --git a/tests/codegen.scm b/tests/codegen.scm index 90b26a7..8704a4a 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -764,6 +764,25 @@ (test-assert "and a closure's" (reports? (in-fn "(var c (closure ((int)) int) (closure ((x int)) _ () (return x)))") "a function's types are written out")) + ;; a call was typed by asking the global table what a function of + ;; that name returns, which a local pointer is not + (test-assert "a call through a local function pointer" + (emits? (string-append "(fn area ((w int) (h int)) int (return (* w h)))" + "(fn f () void (var p (fn ((int) (int)) int) area) (var r _ (p 3 4)))") + "int r = p(3, 4)")) + (test-assert "through a parameter" + (emits? "(fn ap ((g (fn ((int)) double)) (x int)) void (var r _ (g x)))" "double r = g(x)")) + (test-assert "through a field" + (emits? (string-append "(struct ops ((op (fn ((int)) float))))" + "(fn f ((o (struct ops))) void (var r _ ((. o op) 1)))") + "float r = o.op(1)")) + (test-assert "a closure's call, which goes through a helper nothing typed" + (emits? "(fn f ((c (closure ((int)) int))) void (var r _ (c 4)))" + "int r = ƛint_int_call(c, 4)")) + (test-assert "and one returning a closure is called as one" + (emits? (string-append "(fn mk ((k int)) (closure ((int)) int) (return (closure ((b int)) int (k) (return (+ k b)))))" + "(fn f () void (var fp (fn ((int)) (closure ((int)) int)) mk) (var r _ ((fp 3) 4)))") + "int r = ƛint_int_call(fp(3), 4)")) (test-assert "while a function is the pointer it already is" (emits? "(fn g ((n int)) int (return n)) (fn f () void (var p _ g))" "int (*p)(int) = g")) -- 2.52.0 From 4bdc0e57a72c5ca5ae65f4204a538dfb15333c63 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 13:38:30 +0300 Subject: [PATCH 58/74] type #t, an enum's constants and the bitwise names None had a rule. A constant is typed as its enum, where C says int, so that the enum's ops are found through it. And bit-and, bit-not and the rest were respelled bit_and before fmt-c could see them, and called. --- fmt-c-writer.scm | 4 ++++ semen.scm | 18 +++++++++++++++--- tests/codegen.scm | 18 +++++++++++++++++- 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index dae2ca4..fc04467 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -166,6 +166,10 @@ forms, and what remains." ((¤) 'vector-ref) ((include) '%include) ((static-assert) '_Static_assert) + ;; fmt-c's own names for these: respelled bit_and they were calls + ((bit-and bit-or bit-xor bit-not bit-or= + bitwise-and bitwise-ior bitwise-xor bitwise-not bitwise-ior=) + atom) ;; a `|' inside a symbol has to be escaped to be written in ;; a Scheme source, so we just rename it in fmt-c compatible ;; way diff --git a/semen.scm b/semen.scm index aa7eed5..b7ff1e3 100644 --- a/semen.scm +++ b/semen.scm @@ -1320,7 +1320,7 @@ ((number? expr) 'double) ((string? expr) '(* const char)) ((char? expr) 'char) - ((memq expr '(true false)) 'bool) + ((or (boolean? expr) (memq expr '(true false))) 'bool) ;; `#(T : ...)' carries its own type; a bare `#(...)' has none and ;; takes one from whatever it is being written into ((vector? expr) @@ -1378,10 +1378,13 @@ (arithmetic-type expr env))) ((+ / %) (arithmetic-type expr env)) ;; the bitwise operators join like the arithmetic ones - ((^ |\||) (arithmetic-type expr env)) + ((^ |\|| bit-and bit-or bit-xor bitwise-and bitwise-ior bitwise-xor) + (arithmetic-type expr env)) ;; a shift is the promoted left operand, not a join: ;; (<< l b), l : long -> long; (>> c b), c : char -> int ((<< >>) (promoted-type (expression-type (second expr) env))) + ;; a complement is the operand promoted, as a negation is + ((~ bit-not bitwise-not) (promoted-type (expression-type (second expr) env))) ;; ...and an increment is the operand unpromoted: ;; (++ c), c : char -> char ((++ --) (expression-type (second expr) env)) @@ -2169,7 +2172,16 @@ (case (car f) ((struct) (add-struct name form)) ((union) (add-union name form)) - ((enum) (add-enum name form)))))) + ((enum) + (add-enum name form) + ;; a constant is its enum's, which `_' reads and whose ops it + ;; calls -- where C says int, and converts between them + (when (and (pair? (cddr f)) (list? (caddr f))) + (for-each (lambda (value) + (let ((constant (if (pair? value) (car value) value))) + (when (symbol? constant) + (add-name-type! constant `(enum ,name))))) + (remove comment-form? (caddr f))))))))) ;;; No function around a toplevel form, so no scope chain: what a ;;; global's initializer names comes from `get-name-type' alone. diff --git a/tests/codegen.scm b/tests/codegen.scm index 8704a4a..9a0ff8a 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -290,7 +290,14 @@ (test-assert "c-or is still accepted" (emits? (in-fn "(var x int (c-or a b))") "a || b")) (test-assert "c-bit-or is still accepted" - (emits? (in-fn "(var x int (c-bit-or a b))") "a | b"))) + (emits? (in-fn "(var x int (c-bit-or a b))") "a | b")) + ;; the names fmt-c has cases for were respelled bit_and before it + ;; saw them, and called as functions + (test-assert "and so are the named ones" + (emits? (in-fn "(var x _ (bit-and a b)) (var y _ (bit-or a b)) (var z _ (bit-xor a b))") + "int z = a ^ b")) + (test-assert "bit-not among them" + (emits? (in-fn "(var x _ (bit-not a))") "int x = ~a"))) ;; A `;' comment is a form. In a macro body `comment' is a no-op ;; that swallows the comment itself. Inside a quasiquoted payload @@ -766,6 +773,15 @@ "a function's types are written out")) ;; a call was typed by asking the global table what a function of ;; that name returns, which a local pointer is not + ;; none of these had a rule + (test-assert "#t is a bool, as true is" + (emits? (in-fn "(var t _ #t)") "bool t = 1")) + (test-assert "an enum's constant is the enum, whose ops it can call" + (emits? "(enum color (red green)) (fn f () void (var c _ green))" "enum color c = green")) + (test-assert "a bit-not is its operand, promoted" + (emits? (in-fn "(var u (unsigned int) 1) (var v _ (~ u))") "unsigned int v = ~u")) + (test-assert "a char's to an int" + (emits? (in-fn "(var c char 1) (var w _ (bit-not c))") "int w = ~c")) (test-assert "a call through a local function pointer" (emits? (string-append "(fn area ((w int) (h int)) int (return (* w h)))" "(fn f () void (var p (fn ((int) (int)) int) area) (var r _ (p 3 4)))") -- 2.52.0 From b285174a225829fb201b07d9faaaff3dbd3f4a11 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 14:18:56 +0300 Subject: [PATCH 59/74] count a unit among its own imports Two modules importing each other with pub hand the unit its own interface back, and its types were defined twice. --- sex-modules.scm | 12 ++++++++++-- sexc.scm | 2 ++ tests/modules/check.scm | 13 +++++++++++++ tests/modules/cycle-app.sex | 7 +++++++ tests/modules/cycle/a.sex | 8 ++++++++ tests/modules/cycle/b.sex | 5 +++++ 6 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 tests/modules/cycle-app.sex create mode 100644 tests/modules/cycle/a.sex create mode 100644 tests/modules/cycle/b.sex diff --git a/sex-modules.scm b/sex-modules.scm index ae073d2..7e335a3 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -15,6 +15,7 @@ (export get-modules-public-forms + mark-imported! load-persistent-module-paths check-public-interface module-dependencies @@ -26,6 +27,12 @@ ;;; once) (define +imported-modules+ (list)) +;;; The unit is one of its own imports from the start: two modules that +;;; import each other with pub hand it its own interface back otherwise, +;;; and its types are defined twice +(define (mark-imported! path) + (set! +imported-modules+ (cons (normalize-pathname path) +imported-modules+))) + (define (get-modules-public-forms import-form) ;; How Sex handles modules: ;; For each module IMPORT-FORM names, construct path, find module by @@ -40,10 +47,11 @@ (module-path (locate-module name directory))) (unless module-path (sex-error form "Failed to find module" name (get-module-paths directory))) - (if (member module-path +imported-modules+) + (if (member (normalize-pathname module-path) +imported-modules+) (list) (begin - (set! +imported-modules+ (cons module-path +imported-modules+)) + (set! +imported-modules+ (cons (normalize-pathname module-path) + +imported-modules+)) (read-public-interface module-path))))) ;;; An import is looked for beside the file it is written in, so a diff --git a/sexc.scm b/sexc.scm index e2a9c71..1dfe2b2 100644 --- a/sexc.scm +++ b/sexc.scm @@ -243,6 +243,8 @@ status, which is ours to pass on." ;;; The unit's own forms are checked for what its importers will need, ;;; the prelude's not: every unit has those (define (semantic-process-forms unit-forms input-source) + (when (string? input-source) + (mark-imported! (to-absolute-pathname input-source))) (let ((process (lambda () (check-public-interface unit-forms) (semen-process (append prelude unit-forms))))) diff --git a/tests/modules/check.scm b/tests/modules/check.scm index 8aabec4..04ae6e2 100644 --- a/tests/modules/check.scm +++ b/tests/modules/check.scm @@ -33,6 +33,9 @@ ;;; book its siblings page, with `pub', and spine, without. A pub macro ;;; of page's expands into a private one, which crosses with it. ;;; +;;; Two modules may import each other with `pub': cycle/a and cycle/b, +;;; whose interfaces each import the other back. +;;; ;;; make check-modules (import scheme @@ -99,6 +102,16 @@ '("pages 2 3" "number 2") (output-of (built "shelf-app"))) +(test-assert "modules importing each other with pub compile" + (and (output-of sexc "cycle/a.sex" "-c" "-o" (built "cycle-a.o")) + (output-of sexc "cycle/b.sex" "-c" "-o" (built "cycle-b.o")) + (output-of sexc "cycle-app.sex" "-o" (built "cycle-app") + "--" (built "cycle-a.o") (built "cycle-b.o")))) + +(test "and the app runs through them" + '("cycle 1 2") + (output-of (built "cycle-app"))) + (test "the app runs through both" '("hello, world" "hello, sex" diff --git a/tests/modules/cycle-app.sex b/tests/modules/cycle-app.sex new file mode 100644 index 0000000..9159151 --- /dev/null +++ b/tests/modules/cycle-app.sex @@ -0,0 +1,7 @@ +(include stdio.h) +(import cycle/a) + +(pub fn main () int + (var b rb (make-rb 1 2)) + (printf "cycle %d %d\n" (. b a x) (. b y)) + (return 0)) diff --git a/tests/modules/cycle/a.sex b/tests/modules/cycle/a.sex new file mode 100644 index 0000000..b0bc6d5 --- /dev/null +++ b/tests/modules/cycle/a.sex @@ -0,0 +1,8 @@ +;;; Each imports the other with pub, so either one compiled pastes the +;;; other's interface, which imports it back. b holds an ra by value, so +;;; ra is defined before b is imported, as C needs it in one unit +(pub record ra ((x int))) + +(pub import b) + +(pub fn make-ra ((x int)) ra (return #(ra : x))) diff --git a/tests/modules/cycle/b.sex b/tests/modules/cycle/b.sex new file mode 100644 index 0000000..88a7686 --- /dev/null +++ b/tests/modules/cycle/b.sex @@ -0,0 +1,5 @@ +(pub import a) + +(pub record rb ((a ra) (y int))) + +(pub fn make-rb ((x int) (y int)) rb (return #(rb : (make-ra x) y))) -- 2.52.0 From 7c897b6dc62219958ea11372b472436218bdf7f8 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 14:18:56 +0300 Subject: [PATCH 60/74] refuse a pub realization of a spec importers cannot see It failed in whichever importer named the module before the spec's, pointing at the module, where a hidden type is refused in the module already: so is this, the remedy the same. --- sex-modules.scm | 28 ++++++++++++++++++++++++---- tests/encapsulation.scm | 11 +++++++++++ tests/modules/check.scm | 14 ++++++++++++++ tests/modules/specs/money.sex | 9 +++++++++ tests/modules/specs/shown.sex | 2 ++ 5 files changed, 60 insertions(+), 4 deletions(-) create mode 100644 tests/modules/specs/money.sex create mode 100644 tests/modules/specs/shown.sex diff --git a/sex-modules.scm b/sex-modules.scm index 7e335a3..c4b4539 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -179,6 +179,7 @@ (fold (lambda (form acc) (check-written-out form) + (check-realized-spec form visible hidden) (fold (lambda (use acc) (check-type-use form use visible hidden acc)) acc (append-map (lambda (type) (type-uses type #f)) @@ -200,6 +201,22 @@ (_ #f))) (_ #f))) +;;; A pub realization goes to importers, who look its spec up; one they +;;; cannot see failed there, in whichever named this module before the +;;; spec's, and said nothing of where it was written +(define (check-realized-spec form visible hidden) + (match form + (('pub 'realize ((? symbol? spec) _) . _) + (let ((kept (assq spec hidden))) + (when (and kept (not (assq spec visible))) + (sex-error form + (string-append "importers cannot see this spec; " + (if (fourth kept) + "import its module with pub" + "make it pub")) + spec)))) + (_ #f))) + ;;; USE is (name . behind-a-pointer?) (define (check-type-use form use visible hidden acc) (let* ((name (car use)) @@ -300,25 +317,28 @@ ((pair? bound) (append-map bound-uses (cdr bound))) (else (list)))) -;;; The types and constants FORMS declare, as (name kind body?): +;;; The types, constants and specs FORMS declare, as (name kind body?): ;;; ;;; (pub record tally) -> (tally record #f) ;;; (sum colour ((none ()))) -> (colour sum #t) ;;; (define (sq x) (* x x)) -> (sq define #t) +;;; (spec (shown T) ...) -> (shown spec #t) (define (declared-types forms) (filter-map (lambda (form) (and (pair? form) (let* ((core (strip-pub form)) (name (and (pair? core) (pair? (cdr core)) - (if (and (eq? (car core) 'define) (pair? (second core))) + (if (and (memq (car core) '(define spec)) + (pair? (second core))) (car (second core)) (second core))))) - (and (memq (car core) '(record struct union enum sum typedef define)) + (and (memq (car core) + '(record struct union enum sum typedef define spec)) (symbol? name) (list name (car core) - (or (memq (car core) '(typedef define)) + (or (memq (car core) '(typedef define spec)) (any list? (remove comment-form? (cddr core))))))))) forms)) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index b666c2a..a315e81 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -536,6 +536,17 @@ ahead of its pub forms." (interface-reports? "(pub var n _ 42)" "write it out")) (test-assert "all of it" (interface-reports? "(pub var p (* _) 0)" "write it out")) + ;; a spec is seen by importers as a type is: pub, or not at all + (test-assert "a pub realization of a private spec is refused" + (interface-reports? (string-append "(spec (shown T) (fn show ((self (* const T))) int))" + "(pub record m ((c int)))" + "(pub realize (shown m) (fn show ((self (* const m))) int (return 1)))") + "importers cannot see this spec; make it pub")) + (test "and of a pub one is not" + '() + (interface-of (string-append "(pub spec (shown T) (fn show ((self (* const T))) int))" + "(pub record m ((c int)))" + "(pub realize (shown m) (fn show ((self (* const m))) int (return 1)))"))) (test "a private one is solved where it is" '() (interface-of "(var n _ 42)")) diff --git a/tests/modules/check.scm b/tests/modules/check.scm index 04ae6e2..860011d 100644 --- a/tests/modules/check.scm +++ b/tests/modules/check.scm @@ -56,6 +56,14 @@ (define scratch (create-temporary-directory)) (define (built name) (make-pathname scratch name)) +;;; What PROGRAM run with ARGS writes to stderr when it fails, or #f +(define (error-of program . args) + (let* ((proc (process* program args)) + (err (begin (read-string #f (process-output-port proc)) + (read-string #f (process-error-port proc))))) + (process-wait proc) + (and (not (zero? (process-exit-status proc))) (string? err) err))) + ;;; The lines PROGRAM prints when run with ARGS, or #f when it fails (define (output-of program . args) (let* ((proc (process program args)) @@ -112,6 +120,12 @@ '("cycle 1 2") (output-of (built "cycle-app"))) +;;; ...while a realization of a spec importers cannot see is refused by +;;; the module that writes it, not by an importer naming it first +(test-assert "a pub realization of a spec imported without pub is refused" + (let ((err (error-of sexc "specs/money.sex" "-C" "-o" "-"))) + (and err (irregex-search "money.sex:8: importers cannot see this spec" err) #t))) + (test "the app runs through both" '("hello, world" "hello, sex" diff --git a/tests/modules/specs/money.sex b/tests/modules/specs/money.sex new file mode 100644 index 0000000..2fd5d59 --- /dev/null +++ b/tests/modules/specs/money.sex @@ -0,0 +1,9 @@ +;;; Imports shown without pub, so its importers cannot see the spec +;;; this realizes: refused here, rather than in whichever importer +;;; names money before shown +(import shown) + +(pub record money ((cents int))) + +(pub realize (shown money) + (fn show ((self (* const money))) int (return (. self cents)))) diff --git a/tests/modules/specs/shown.sex b/tests/modules/specs/shown.sex new file mode 100644 index 0000000..0c8ce9a --- /dev/null +++ b/tests/modules/specs/shown.sex @@ -0,0 +1,2 @@ +(pub spec (shown T) + (fn show ((self (* const T))) int)) -- 2.52.0 From 1dd1cf0ae92a7e63f71bb8e79f7ed871b9dd2992 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 14:18:56 +0300 Subject: [PATCH 61/74] expand a module's toplevel macro calls for its importers Its interface was read as written, so pub forms a macro wrote never reached them, which list-macros' is-public? flag exists for. The module's macros, and those its imports give it, are lent for the reading and taken back after. One reading a type the module keeps to itself cannot expand there, and gives importers nothing, as before. --- sex-macros.scm | 15 ++++++- sex-modules.scm | 87 +++++++++++++++++++++++++++++++----- tests/modules/check.scm | 18 ++++++++ tests/modules/gen/made.sex | 23 ++++++++++ tests/modules/gen/makers.sex | 3 ++ tests/modules/made-app.sex | 6 +++ 6 files changed, 141 insertions(+), 11 deletions(-) create mode 100644 tests/modules/gen/made.sex create mode 100644 tests/modules/gen/makers.sex create mode 100644 tests/modules/made-app.sex diff --git a/sex-macros.scm b/sex-macros.scm index 66906e6..e1dc2ee 100644 --- a/sex-macros.scm +++ b/sex-macros.scm @@ -14,7 +14,9 @@ comment macro? apply-macro - defmacro) + defmacro + macro-definition + restore-macro!) (define (cat-syms s-1 s-2) (fmt #f s-1 s-2)) @@ -89,6 +91,17 @@ (sex-error form "macro takes at least this many arguments" name required))))) +;;; What a name is defined as a macro to, or #f; and putting that back, +;;; for a macro lent for a while -- a module's, while its interface is +;;; read +(define (macro-definition name) + (get name 'sex-macro)) + +(define (restore-macro! name definition) + (if definition + (put! name 'sex-macro definition) + (remprop! name 'sex-macro))) + (define (defmacro form) (let ((arglist (car form)) (body (cdr form))) diff --git a/sex-modules.scm b/sex-modules.scm index c4b4539..6d83466 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -1,6 +1,7 @@ (import scheme (chicken base) + (chicken condition) (chicken file) (chicken load) (chicken module) @@ -9,6 +10,7 @@ (chicken string) matchable reader + sex-macros srfi-1 types utils) @@ -118,9 +120,78 @@ ;; pub fn taking it has to paste them that way round, or the prototype ;; names a type C has not seen. The declarations of the types its ;; importers see only behind a pointer go first. - (let ((raw-forms (read-module module-path))) - (append (check-public-interface raw-forms) - (interface-forms raw-forms)))) + (let ((forms (module-forms (read-module module-path)))) + (append (check-public-interface forms) + (interface-forms forms)))) + +;;; A module's forms with its toplevel macro calls expanded, so that the +;;; pub forms a macro writes reach importers as written ones do: +;;; (getter forty-two 42) gives them (pub fn forty-two () int). The +;;; macros are the module's own and those its imports give it, lent for +;;; the expanding and taken back after, so the importer is left with the +;;; pub ones alone. One that reads the type database sees what the +;;; importer knows, which a type private to the module is not; a call +;;; that cannot expand for that -- (print-struct box), box being the +;;; module's -- gives importers nothing, as before, and is the module's +;;; own compile's to check +(define +modules-expanded+ (list)) + +(define (module-forms raw-forms) + (cond ((assq raw-forms +modules-expanded+) => cdr) + (else (let ((forms (expanded raw-forms))) + (set! +modules-expanded+ + (cons (cons raw-forms forms) +modules-expanded+)) + forms)))) + +(define (expanded raw-forms) + (let ((lent (list))) + (define (lend! form) + (let ((name (macro-name form))) + (unless (assq name lent) + (set! lent (cons (cons name (macro-definition name)) lent))) + (defmacro (if (pub-form? form) (cddr form) (cdr form))))) + (define (expand form) + (cond ((macro-name form) (lend! form) (list form)) + ((splice? form) (append-map expand (cdr form))) + ((macro? form) + (let ((result (handle-exceptions exn #f (apply-macro form)))) + (cond ((or (not result) (null? result)) (list)) + (else (stamp-form-source! result (form-source form)) + (expand result))))) + (else (list form)))) + (for-each lend! (imported-macro-forms raw-forms)) + (let ((forms (append-map expand raw-forms))) + (for-each (lambda (entry) (restore-macro! (car entry) (cdr entry))) lent) + forms))) + +(define (splice? form) + (and (pair? form) (eq? (car form) '$) (list? form))) + +;;; The macros importing FORMS' modules gives: each one's pub macros and +;;; their helpers, and those of the modules it imports with pub +(define (imported-macro-forms forms) + (let next ((paths (append (imported-modules forms #t) + (imported-modules forms #f))) + (seen (list)) + (acc (list))) + (cond ((null? paths) (concatenate (reverse acc))) + ((member (car paths) seen) (next (cdr paths) seen acc)) + (else + (let* ((raw (read-module (car paths))) + (helpers (helper-macros raw))) + (next (append (cdr paths) (imported-modules raw #t)) + (cons (car paths) seen) + (cons (filter (lambda (form) + (and (macro-name form) + (or (pub-form? form) (memq form helpers)))) + raw) + acc))))))) + +(define (macro-name form) + (match form + (('defmacro (name . _) . _) name) + (('pub 'defmacro (name . _) . _) name) + (_ #f))) (define (interface-forms raw-forms) (let ((helpers (helper-macros raw-forms))) @@ -135,12 +206,8 @@ ;;; the importer expands them all, the way a C header that defines a ;;; macro has to define what it uses too (define (helper-macros raw-forms) - (let* ((macro-name (lambda (form) - (match form - (('defmacro (name . _) . _) name) - (('pub 'defmacro (name . _) . _) name) - (_ #f)))) - (private (filter (lambda (form) (and (macro-name form) (not (pub-form? form)))) + (let* ((private (filter (lambda (form) + (and (macro-name form) (not (pub-form? form)))) raw-forms)) (mentions (lambda (form name) (let walk ((x (cdr form))) @@ -392,7 +459,7 @@ (define (module-exports path) (cond ((assoc path +module-exports+) => cdr) - (else (let* ((forms (interface-forms (read-module path))) + (else (let* ((forms (interface-forms (module-forms (read-module path)))) (exports (cons (declared-types forms) (imported-modules forms #f)))) (set! +module-exports+ (cons (cons path exports) +module-exports+)) diff --git a/tests/modules/check.scm b/tests/modules/check.scm index 860011d..cf2de87 100644 --- a/tests/modules/check.scm +++ b/tests/modules/check.scm @@ -36,6 +36,9 @@ ;;; Two modules may import each other with `pub': cycle/a and cycle/b, ;;; whose interfaces each import the other back. ;;; +;;; gen/made writes its pub forms by macro calls, which are expanded when +;;; its interface is read; the macros it used for that stay its own. +;;; ;;; make check-modules (import scheme @@ -120,6 +123,21 @@ '("cycle 1 2") (output-of (built "cycle-app"))) +;;; ...it lists pub forms a macro wrote, and not the macros that wrote them +(test "a module's interface holds what its macros wrote" + '("(pub fn forty-two () int)" "(pub fn seven () int)" + "(pub fn one () int)" "(pub fn two () int)") + (output-of sexc "--public-interface" "gen/made.sex")) + +(test-assert "and an importer links with them" + (and (output-of sexc "gen/made.sex" "-c" "-o" (built "made.o")) + (output-of sexc "made-app.sex" "-o" (built "made-app") + "--" (built "made.o")))) + +(test "and calls them" + '("made 42 7 1 2") + (output-of (built "made-app"))) + ;;; ...while a realization of a spec importers cannot see is refused by ;;; the module that writes it, not by an importer naming it first (test-assert "a pub realization of a spec imported without pub is refused" diff --git a/tests/modules/gen/made.sex b/tests/modules/gen/made.sex new file mode 100644 index 0000000..f92de7c --- /dev/null +++ b/tests/modules/gen/made.sex @@ -0,0 +1,23 @@ +;;; Its pub forms are written by macro calls -- its own, one it imports +;;; without pub, and a splice of two -- and reach importers as written +;;; ones do. One reading a record kept private here cannot expand for an +;;; importer, who is given nothing of it, as before, and still builds +(import makers) + +(defmacro (getter name value) + `(pub fn ,name () int (return ,value))) + +(defmacro (pair-of a b) + `($ (pub fn ,a () int (return 1)) (pub fn ,b () int (return 2)))) + +(defmacro (field-count name) + (let ((fields (get-fields name))) + (unless fields (error "no such record" name)) + `(pub fn ,(cat name "-fields") () int (return ,(length fields))))) + +(record box ((w int) (h int))) + +(getter forty-two 42) +(field-count box) +(constant seven 7) +(pair-of one two) diff --git a/tests/modules/gen/makers.sex b/tests/modules/gen/makers.sex new file mode 100644 index 0000000..dbafa6c --- /dev/null +++ b/tests/modules/gen/makers.sex @@ -0,0 +1,3 @@ +;;; A macro module: what it writes is up to whoever calls it +(pub defmacro (constant name value) + `(pub fn ,name () int (return ,value))) diff --git a/tests/modules/made-app.sex b/tests/modules/made-app.sex new file mode 100644 index 0000000..9a05df6 --- /dev/null +++ b/tests/modules/made-app.sex @@ -0,0 +1,6 @@ +(include stdio.h) +(import gen/made) + +(pub fn main () int + (printf "made %d %d %d %d\n" (forty-two) (seven) (one) (two)) + (return 0)) -- 2.52.0 From 2fa1ed21d75846cf7a80a67acbe434c3bac419e9 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 14:48:43 +0300 Subject: [PATCH 62/74] take a docstring on a sum record, struct and enum take one; sum read it where its variants go. --- semen.scm | 56 +++++++++++++++++++++++------------------ sex-modules.scm | 3 ++- tests/codegen.scm | 7 ++++++ tests/encapsulation.scm | 3 +++ 4 files changed, 43 insertions(+), 26 deletions(-) diff --git a/semen.scm b/semen.scm index b7ff1e3..7b97f50 100644 --- a/semen.scm +++ b/semen.scm @@ -248,10 +248,10 @@ ;; between name and fields are not skipped, they already confuse the ;; writer (match form - (('pub (and kind (or 'struct 'union 'enum)) + (('pub (and kind (or 'struct 'union 'enum 'sum)) (? symbol? name) (? string? doc) . rest) (values doc (copy-form-source! form `(pub ,kind ,name ,@rest)))) - (((and kind (or 'struct 'union 'enum)) + (((and kind (or 'struct 'union 'enum 'sum)) (? symbol? name) (? string? doc) . rest) (values doc (copy-form-source! form `(,kind ,name ,@rest)))) (_ (values #f form)))) @@ -2045,29 +2045,35 @@ ;;; 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))) - (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 - (sex-error form "variant is declared twice" twice))) - (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)))))) +(define (process-sum written acc) + (let-values (((doc form) (extract-aggregate-docstring written))) + (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))) + (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 + (sex-error form "variant is declared twice" twice))) + (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) + ;; the docstring goes ahead of everything the sum is made of + (fold match-sex-form + (if doc (cons (copy-form-source! form (list 'comment doc)) acc) 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))) diff --git a/sex-modules.scm b/sex-modules.scm index 6d83466..e1021a9 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -332,7 +332,8 @@ (('pub 'define name . body) body) (('pub (or 'record 'struct 'union) name . rest) (field-types (find list? (remove comment-form? rest)))) - (('pub 'sum name (variants ...)) + ((or ('pub 'sum name (variants ...)) + ('pub 'sum name (? string?) (variants ...))) (append-map (lambda (v) (if (and (pair? v) (pair? (cdr v))) (field-types (second v)) (list))) (remove comment-form? variants))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 9a0ff8a..3c51f71 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -422,6 +422,13 @@ ;; A string as the first body form (or after the name of a struct, ;; union or enum) is a docstring: it becomes a comment immediately ;; before the declaration, not a statement inside it. + (test-group "a sum's docstring" + ;; record, struct and enum took one, and sum read it as its variants + (test-assert "is a comment ahead of it" + (emits? "(sum shape \"A shape.\" ((dot ()) (box ((w int)))))" "/* A shape. */")) + (test-assert "and the sum is still one" + (emits? "(sum shape \"A shape.\" ((dot ()) (box ((w int)))))" "shapeǂbox"))) + (test-group "docstrings" (test-assert "appears before the function" (emits? "(fn greet ((name (* char))) void \"Greet NAME.\" (printf \"hi\" name))" diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index a315e81..1c00c97 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -550,6 +550,9 @@ ahead of its pub forms." (test "a private one is solved where it is" '() (interface-of "(var n _ 42)")) + (test-assert "a pub sum's variants are looked at past its docstring" + (interface-reports? "(record cell ((v int))) (pub sum s \"doc\" ((a ((c cell))) (b ())))" + "held by value")) (test-assert "held by value it is an error" (interface-reports? "(record cell ((v int))) (pub record shape ((c cell)))" "held by value")) -- 2.52.0 From f66eaa745417465b5cb2d81e1eca0e9a8d92de4c Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 14:48:43 +0300 Subject: [PATCH 63/74] match a sum through a pointer to it A pointer was refused, where . reads through one; a match now reads through the whole chain of them to the sum. --- semen.scm | 9 ++++++++- tests/encapsulation.scm | 13 +++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/semen.scm b/semen.scm index 7b97f50..3731563 100644 --- a/semen.scm +++ b/semen.scm @@ -1018,7 +1018,7 @@ ;;; 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))) + (let* ((scrutinee (and (pair? (cdr form)) (dereferenced (second form) env form))) ;; a comment between arms goes the way the writer already ;; drops one between switch clauses (arms (remove comment-form? (cddr form))) @@ -1042,6 +1042,13 @@ ,(match-branches name held variants arms)) env))))) +;;; A pointer to a sum is matched as the sum, read through however many +;;; there are, as `.' reads through them: p : (* * shape) -> (* (* p)) +(define (dereferenced expr env form) + (if (pointer-target (expression-type expr env)) + (dereferenced (copy-form-source! form (list '* expr)) env form) + expr)) + (define (match-binders arms) (append-map (lambda (arm) (if (eq? (car arm) 'else) '() (delete '_ (second (car arm))))) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 1c00c97..e3acae4 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -504,6 +504,19 @@ ahead of its pub forms." (emits? (sum-src "(var c (closure () int) (closure () int ((t s))" " (match t ((circle (r)) (return 1)) (else (return 0)))))") "t.tag == shapeǂcircle")) + ;; a pointer to one was refused, where `.' reads through one + (test-assert "a pointer to a sum is matched as the sum" + (emits? (sum-src "(var p (* shape) (& s))" + "(match p ((circle (r)) (= out r)) (else (= out 0.0)))") + "(*p).tag == shapeǂcircle")) + (test-assert "binding through it" + (emits? (sum-src "(var p (* shape) (& s))" + "(match p ((circle (r)) (= out r)) (else (= out 0.0)))") + "float r = (*p).u.circle.r")) + (test-assert "and through a chain of them" + (emits? (sum-src "(var p (* shape) (& s)) (var pp (* * shape) (& p))" + "(match pp ((circle (r)) (= out r)) (else (= out 0.0)))") + "(*(*pp)).tag == shapeǂcircle")) (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 8d6d1855e2cb98dc58248c81bb78bdf314c379f6 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 14:48:43 +0300 Subject: [PATCH 64/74] refuse a variant named like a C keyword One with fields is a member of the sum's union, and C takes no member named int; one without is held to the same, as one rule. --- semen.scm | 12 ++++++++++++ tests/encapsulation.scm | 8 ++++++++ 2 files changed, 20 insertions(+) diff --git a/semen.scm b/semen.scm index 3731563..68b1693 100644 --- a/semen.scm +++ b/semen.scm @@ -2085,8 +2085,20 @@ (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)) + ;; one with fields is a member of the sum's union, and C takes no + ;; member named `int'; one without is held to the same, as one rule + (when (memq (car v) +c-keywords+) + (sex-error form "a variant cannot be named like a C keyword" (car v))) (cons (car v) (normalize-fields (cadr v)))) +;;; C11's, and the ones , in every unit, makes macros of +(define +c-keywords+ + '(auto break case char const continue default do double else enum extern + float for goto if inline int long register restrict return short signed + sizeof static struct switch typedef union unsigned void volatile while + _Alignas _Alignof _Atomic _Bool _Complex _Generic _Imaginary _Noreturn + _Static_assert _Thread_local bool true false)) + ;;; (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. diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index e3acae4..cd04bc9 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -505,6 +505,14 @@ ahead of its pub forms." " (match t ((circle (r)) (return 1)) (else (return 0)))))") "t.tag == shapeǂcircle")) ;; a pointer to one was refused, where `.' reads through one + ;; a variant with fields is a member of the sum's union, which C + ;; would not take named `int' + (test-assert "a variant named like a C keyword is refused" + (reports? "(sum tok ((int ((v int))) (other ())))" "a variant cannot be named like a C keyword")) + (test-assert "one without fields too, to keep one rule" + (reports? "(sum tok ((default ()) (other ())))" "a variant cannot be named like a C keyword")) + (test-assert "and stdbool's names count" + (reports? "(sum b ((true ()) (false ())))" "a variant cannot be named like a C keyword")) (test-assert "a pointer to a sum is matched as the sum" (emits? (sum-src "(var p (* shape) (& s))" "(match p ((circle (r)) (= out r)) (else (= out 0.0)))") -- 2.52.0 From 9505b4f0a0757e8e1b5048a9a2bfb5be1e1eeb15 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 14:48:43 +0300 Subject: [PATCH 65/74] refuse an integer with a leading 0 017 is 17 to Scheme and 15 to C, so whoever reads the Sex and whoever reads the C would each take it for something else. --- reader.scm | 6 ++++++ tests/reader.scm | 9 +++++++++ 2 files changed, 15 insertions(+) diff --git a/reader.scm b/reader.scm index 1858d5e..fa17cc3 100644 --- a/reader.scm +++ b/reader.scm @@ -195,6 +195,12 @@ (define (finish-atom s) (let ((digits (if (substring-index "_" s) (or (ungrouped s (or (c-radix s) 10)) s) s))) + ;; 017 is 17 to Scheme and 15 to C: whoever reads the Sex and whoever + ;; reads the C would each take it for something else + (when (irregex-match "-?0[0-9]+[uUlL]*" digits) + (error + "a leading 0 is octal to C; write the number without it, or #o for octal" + s)) (cond ((string=? s ".") dot-token) ((or (string->number digits) (radix-number digits)) diff --git a/tests/reader.scm b/tests/reader.scm index c32184d..9c6d078 100644 --- a/tests/reader.scm +++ b/tests/reader.scm @@ -74,6 +74,15 @@ "1_000_000 0xFF_FF 0b1010_0101 1_000.5 -1_000 1e0_5 #x80_00") (reader-test '(_1 1_ 1__0 0x_FF 0xF_p) "_1 1_ 1__0 0x_FF 0xF_p") + ;; 017 is 17 to Scheme and 15 to C, so it means one thing to whoever + ;; reads the Sex and another to whoever reads the C + (test "a leading 0 is refused" + "a leading 0 is octal to C; write the number without it, or #o for octal" + (read-error "017")) + (test "with a suffix as well" #t (string? (read-error "017u"))) + (test "or grouped" #t (string? (read-error "0_17"))) + (reader-test '(0 0.5 15) "0 00.5 #o17") + ;; Scheme reads numbers C has no literal for, and they reached C as ;; written: 1/2 is integer division there, and +inf.0 no number at all (test "a ratio is not a C number" -- 2.52.0 From af8e49cdd3c3b667e1b48a3b200384ea449364d1 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 14:48:43 +0300 Subject: [PATCH 66/74] refuse a macro defined after a call to it The call was compiled as a function's, and the macro went unused there without a word. --- semen.scm | 23 ++++++++++++++++++++++- tests/codegen.scm | 8 ++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/semen.scm b/semen.scm index 68b1693..33cf2c8 100644 --- a/semen.scm +++ b/semen.scm @@ -32,8 +32,22 @@ ;;; in auxiliary structures and functions. (define (process raw-sex-forms) (reset-declarations!) + (set! +called-as-functions+ (make-hash-table)) (process-rec raw-sex-forms (list))) +;;; The first call of each name compiled as a function's, so that a macro +;;; of that name defined after it is told of rather than going unused +;;; there without a word +(define +called-as-functions+ (make-hash-table)) + +(define (check-not-called-before form name) + (let ((call (hash-table-ref/default +called-as-functions+ name #f))) + (when call + (sex-error form "a macro defined after a call to it, which is a function's" + name + (string-append "called at " (form-file call) ":" + (number->string (form-line call))))))) + (define (process-rec forms acc) (cond ((null? forms) (reverse acc)) @@ -126,7 +140,11 @@ (process-imports (get-modules-public-forms sex-form) acc)) ((or ('defmacro . rest) - ('pub 'defmacro . rest)) (defmacro rest) acc) + ('pub 'defmacro . rest)) + (when (and (pair? rest) (pair? (car rest))) + (check-not-called-before sex-form (caar rest))) + (defmacro rest) + acc) ((or ('typedef new-type target) ('pub 'typedef new-type target)) @@ -733,6 +751,9 @@ ,receiver ,@(walk-operands form (cdr form) env)))))) (else + (when (and (symbol? (car form)) (form-source form) + (not (hash-table-exists? +called-as-functions+ (car form)))) + (hash-table-set! +called-as-functions+ (car form) form)) (convert-arguments (copy-form-source! form (walk-operands form form env)) env)))))))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 3c51f71..353f1e1 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -335,6 +335,14 @@ "macro takes at least this many arguments many 1")) (test-assert "while it may take any more" (emits? "(defmacro (many x . more) x) (fn f () int (return (many 1 2 3)))" "return 1;")) + ;; a call before the macro is defined is a function call, and the + ;; macro defined after it went unused there without a word + (test-assert "a macro defined after a call to it is refused" + (reports? "(fn f () int (return (later 1)))\n(defmacro (later x) x)" + "codegen.sex:2: a macro defined after a call to it")) + (test-assert "naming where the call is" + (reports? "(fn f () int\n (return (later 1)))\n(defmacro (later x) x)" + "/codegen.sex:2\"")) (test-assert "an error in a macro's body names the call" (reports? "(defmacro (boom x) (error \"no good\" x))\n(fn f () int (return (boom 1)))" "codegen.sex:2: expanding boom: no good"))) -- 2.52.0 From 8c92c245c55d5657f16629c2ebb97d66d7e1f88a Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 14:48:43 +0300 Subject: [PATCH 67/74] read a quoted name as the name '-fields read as (- fields), so (cat name '-fields) built name(- fields). A quoted list keeps the rule: it is code a macro returns as often as not. --- reader.scm | 15 +++++++++++++-- tests/reader.scm | 4 ++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/reader.scm b/reader.scm index fa17cc3..5110972 100644 --- a/reader.scm +++ b/reader.scm @@ -111,7 +111,7 @@ (let ((line (current-line))) (stamp (read-comment port) line))) ((char=? c #\") (read-string-lit port)) - ((char=? c #\') (get-ch port) (list 'quote (read-datum port))) + ((char=? c #\') (get-ch port) (list 'quote (read-quoted port))) ((char=? c #\`) (get-ch port) (list 'quasiquote (read-datum port))) ((char=? c #\,) (get-ch port) @@ -193,6 +193,16 @@ (finish-atom (list->string (reverse chars))) (begin (get-ch port) (loop (cons c chars))))))) +;;; ...except quoted, alone: '-fields is a name, as in (cat name '-fields). +;;; A quoted list is code a macro hands back as often as not, and keeps +;;; the rule +(define negating? (make-parameter #t)) + +(define (read-quoted port) + (if (memv (peek port) '(#\( #\[ #\' #\` #\, #\# #\" #\;)) + (read-datum port) + (parameterize ((negating? #f)) (read-datum port)))) + (define (finish-atom s) (let ((digits (if (substring-index "_" s) (or (ungrouped s (or (c-radix s) 10)) s) s))) ;; 017 is 17 to Scheme and 15 to C: whoever reads the Sex and whoever @@ -353,7 +363,8 @@ ;;; -INFINITY is (- INFINITY), as -1 is minus one. No name begins with ;;; a dash, and an operator that does goes on with a non-letter: -> -- (define (negated-name? s) - (and (> (string-length s) 1) + (and (negating?) + (> (string-length s) 1) (char=? #\- (string-ref s 0)) (let ((c (string-ref s 1))) (or (char-alphabetic? c) (char=? c #\_))))) diff --git a/tests/reader.scm b/tests/reader.scm index 9c6d078..25a6895 100644 --- a/tests/reader.scm +++ b/tests/reader.scm @@ -60,6 +60,10 @@ (reader-test '((- _x)) "-_x") (reader-test '(-1 -1.5) "-1 -1.5") (reader-test '(- -> ->> -- -=) "- -> ->> -- -=") + ;; ...but a quoted name is a name: (cat name '-fields) built `name(- fields)' + (reader-test '((quote -fields)) "'-fields") + ;; while a quoted list is code a macro hands back as often as not + (reader-test '((quote ((- a) b))) "'(-a b)") ;; a number in another radix, spelled the way C does or the way ;; Scheme does; either is an ordinary integer from here on -- 2.52.0 From a53c358113901e173dbbf86cac3ba55590cdc650 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 14:48:43 +0300 Subject: [PATCH 68/74] type a value if as the join of its branches It had no rule, so _ could not be set from one. --- semen.scm | 12 ++++++++++++ tests/codegen.scm | 10 ++++++++++ 2 files changed, 22 insertions(+) diff --git a/semen.scm b/semen.scm index 33cf2c8..e066025 100644 --- a/semen.scm +++ b/semen.scm @@ -1411,6 +1411,12 @@ ;; a shift is the promoted left operand, not a join: ;; (<< l b), l : long -> long; (>> c b), c : char -> int ((<< >>) (promoted-type (expression-type (second expr) env))) + ;; a value if is the join of its values, as an operator is of its + ;; operands -- and nothing when one of them says nothing + ((if) (let ((types (map (cut expression-type <> env) + (if-values (remove comment-form? (cdr expr)))))) + (and (every identity types) + (fold (lambda (t joined) (arith-join joined t)) #f types)))) ;; a complement is the operand promoted, as a negation is ((~ bit-not bitwise-not) (promoted-type (expression-type (second expr) env))) ;; ...and an increment is the operand unpromoted: @@ -1471,6 +1477,12 @@ (let ((type (underlying (parse-type written)))) (or (ptr-type? type) (array-type? type))))) +;;; (if t1 v1 t2 v2 e) -> (v1 v2 e) +(define (if-values parts) + (if (and (pair? parts) (pair? (cdr parts)) (pair? (cddr parts))) + (cons (cadr parts) (if-values (cddr parts))) + parts)) + (define (arith-join left right) (cond ((not left) right) diff --git a/tests/codegen.scm b/tests/codegen.scm index 353f1e1..df1f429 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -788,6 +788,16 @@ "a function's types are written out")) ;; a call was typed by asking the global table what a function of ;; that name returns, which a local pointer is not + ;; a value if had no rule either: it is the join of its values + (test-assert "a value if joins its branches" + (emits? (in-fn "(var x _ (if a 1 2.5))") "double x = a ? 1 : 2.5")) + (test-assert "every one of a chain" + (emits? (in-fn "(var x _ (if a 1 b 2 3.5f))") "float x")) + (test-assert "an aggregate as itself" + (emits? "(struct pt ((x int))) (fn f ((a int) (p (struct pt))) void (var q _ (if a p p)))" + "struct pt q = a ? p : p")) + (test-assert "and none when a branch says nothing" + (reports? (in-fn "(var x _ (if a (unheard-of) 1))") "infer")) ;; none of these had a rule (test-assert "#t is a bool, as true is" (emits? (in-fn "(var t _ #t)") "bool t = 1")) -- 2.52.0 From 7973a4331d98eb226b49b8707525558f37e34f9d Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 14:48:43 +0300 Subject: [PATCH 69/74] split the C compiler's name from its options SEX_CC="ccache cc" went looking for an executable of that whole name; it is read as make reads CC now. --- Readme.org | 3 ++- sexc.scm | 22 +++++++++++++--------- tests/exit-code/check.scm | 19 +++++++++++++++++++ 3 files changed, 34 insertions(+), 10 deletions(-) diff --git a/Readme.org b/Readme.org index 251a2f6..31eec62 100644 --- a/Readme.org +++ b/Readme.org @@ -90,7 +90,8 @@ sexc ./examples/hello-world.sex -o hello That's it. Now you should have executable named ~hello~ in your directory. Sex uses C under the hood, the default C compiler is ~cc~, but you can pass any using ~--c-compiler~ option, or by setting -~SEX_CC~ environment variable. +~SEX_CC~ environment variable. Either may carry the compiler's own +options, as ~make~'s ~CC~ does: ~SEX_CC="ccache cc"~. Everything after ~--~ is handed to the C compiler exactly as written: diff --git a/sexc.scm b/sexc.scm index 1dfe2b2..c084dc6 100644 --- a/sexc.scm +++ b/sexc.scm @@ -213,9 +213,11 @@ (define (compile-to-file sex-forms output args cc-args) "Hand the generated C to the C compiler. Returns the compiler's exit status, which is ours to pass on." - (let ((compiler (or (get-arg args 'c-compiler #f) - (get-env-var "SEX_CC") - "cc")) + ;; named with its own options, as make's CC is: "ccache cc", "cc -O2" + (let ((compiler (let ((words (string-split (or (get-arg args 'c-compiler #f) + (get-env-var "SEX_CC") + "cc")))) + (if (null? words) (list "cc") words))) (out-file (if (eq? output 'default) "a.out" output)) @@ -229,12 +231,14 @@ status, which is ours to pass on." (begin (delete-file* c-file) (abort exn)) (with-output-to-file c-file (lambda () (emit-c sex-forms))) - (let ((proc (process compiler (append (list "-o" out-file) - (if (get-arg args 'compile-object #f) - (list "-c") - (list)) - (list c-file) - cc-args)))) + (let ((proc (process (car compiler) + (append (cdr compiler) + (list "-o" out-file) + (if (get-arg args 'compile-object #f) + (list "-c") + (list)) + (list c-file) + cc-args)))) (call-with-values (lambda () (process-wait proc)) (lambda (pid normal-exit? status) (delete-file* c-file) diff --git a/tests/exit-code/check.scm b/tests/exit-code/check.scm index f35035d..5044912 100644 --- a/tests/exit-code/check.scm +++ b/tests/exit-code/check.scm @@ -47,6 +47,14 @@ (process-wait proc) (list (process-exit-status proc) out err)))) +;;; (status) of PROGRAM run on its own +(define (sexc-run-program program) + (let ((proc (process* program (list)))) + (close-output-port (process-input-port proc)) + (read-string #f (process-output-port proc)) + (process-wait proc) + (list (process-exit-status proc)))) + ;;; Whether sexc exits 0 when run with ARGS, saying nothing of it (define (sexc-succeeds? . args) (zero? (system (string-append (string-intersperse (map qs (cons sexc args))) @@ -108,6 +116,17 @@ (test "and the source is as it was" hello-source (call-with-input-file "victim.sex" (lambda (p) (read-string #f p)))) +;;; A compiler is named with its own options, as make's CC is: SEX_CC +;;; "cc -DCODE=7" went looking for an executable of that whole name +(call-with-output-file "code.sex" (lambda (p) (display "(pub fn main () int (return CODE))" p))) +(test "a compiler given with options takes them" + 7 + (begin + (set-environment-variable! "SEX_CC" "cc -DCODE=7") + (let ((built (sexc-succeeds? "code.sex" "-o" "code"))) + (unset-environment-variable! "SEX_CC") + (and built (car (sexc-run-program "./code")))))) + ;;; An error is its message: CHICKEN's call history after it is for ;;; working on sexc itself, and asked for by SEXC_DEBUG (test-assert "a missing input says so" -- 2.52.0 From acbd4928f5d60dc0c01094c4a6368e33a231bc53 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 14:48:43 +0300 Subject: [PATCH 70/74] read a member path and a receiver through a pointer chain A pointer to a pointer has no fields, so (. pp x) has one meaning, and it came out pp->x; it is (*pp)->x, and a method receiver alike. --- semen.scm | 33 ++++++++++++++++++++++++--------- tests/codegen.scm | 16 ++++++++++++++++ 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/semen.scm b/semen.scm index e066025..a2bba58 100644 --- a/semen.scm +++ b/semen.scm @@ -1195,10 +1195,12 @@ (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)))) + ;; through a pointer chain, as a path reads through one + (let*-values (((receiver written) + (through-pointers (walk-operand (second form) env) + (expression-type (second form) 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))) @@ -1208,7 +1210,7 @@ form `(,method ,(method-receiver method (or target written) (and target #t) - (walk-operand receiver env) form) + receiver form) ,@(walk-operands form (cddr form) env))))))) ;;; A method taking (* Self) wants an address and one taking Self wants @@ -1254,8 +1256,9 @@ (told? #f)) (if (null? fields) (copy-form-source! form expr) - (let* ((target (pointer-target type)) - (known (type-fields (or target type)))) + (let*-values (((expr type) (through-pointers expr type)) + ((target) (pointer-target type)) + ((known) (type-fields (or target type)))) (when (and (pair? known) (not (assq (field-name (car fields)) known))) (sex-error form "no field of this name in" (or target type) (car fields))) (unless (or type told?) @@ -1269,6 +1272,19 @@ (cdr fields) (or told? (not type)))))))) +;;; A pointer to a pointer has no fields: EXPR read through every pointer +;;; but the last, so a step writes -> once. pp : (* * pt) -> (* pp), (* pt) +(define (through-pointers expr type) + (let ((target (pointer-target type))) + (if (and target (pointer-target target)) + (through-pointers (list '* expr) target) + (values expr type)))) + +;;; What a path reads fields of: TYPE, or what its pointers lead to +(define (pointed-through type) + (let ((target (pointer-target type))) + (if target (pointed-through target) type))) + ;;; A field of a path, indexed or not: xs, [xs 0] -> xs (define (field-name field) (if (and (array-form? field) (pair? (cdr field))) @@ -1568,8 +1584,7 @@ (define (member-path-type type fields) (if (null? fields) type - (member-path-type (step-type (or (pointer-target type) type) - (car fields)) + (member-path-type (step-type (pointed-through type) (car fields)) (cdr fields)))) ;;; What a step of a path gives: its field, or for [xs i] an element of diff --git a/tests/codegen.scm b/tests/codegen.scm index df1f429..a4cd699 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -1253,6 +1253,22 @@ (emits? poly-src "q->pp[0]->y")) (test-assert "and every index of one is written" (emits? poly-src "q->grid[1][2].x")) + ;; a pointer to a pointer has no fields, so a path reads through + ;; every pointer to the aggregate, where it wrote pp->x + (test-assert "a pointer to a pointer is read through" + (emits? "(struct pt ((x int))) (fn f ((pp (* * struct pt))) int (return (. pp x)))" + "(*pp)->x")) + (test-assert "however many there are" + (emits? "(struct pt ((x int))) (fn f ((p3 (* * * struct pt))) int (return (. p3 x)))" + "(*(*p3))->x")) + (test-assert "and typed through" + (emits? "(struct pt ((x float))) (fn f ((pp (* * struct pt))) void (var v _ (. pp x)))" + "float v = (*pp)->x")) + (test-assert "a method's receiver too" + (emits? (string-append "(record pt ((x int)))" + "(ops pt (fn get ((self (* pt))) int (return (. self x))))" + "(fn f ((pp (* * pt))) int (return (.get pp)))") + "ptːget(*pp)")) ;; only a written (* T) was a pointer, so a typedef of one read as a ;; value, and a method could not find its receiver's type (test-assert "a typedef of a pointer reads with an arrow" -- 2.52.0 From 28aaaf637c776505c4d2b42e82ffd44ec73f3030 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 27 Oct 2026 22:41:06 +0300 Subject: [PATCH 71/74] refuse a closure capturing one name twice check-capture-names held captures against the parameters and the body, not against each other: (n n) gave C two members and two parameters n. --- semen.scm | 5 +++++ tests/codegen.scm | 3 +++ 2 files changed, 8 insertions(+) diff --git a/semen.scm b/semen.scm index a2bba58..29427e6 100644 --- a/semen.scm +++ b/semen.scm @@ -2031,6 +2031,11 @@ (when (memq name parameters) (sex-error form "a capture and a parameter share a name" name))) names) + (let twice ((names names)) + (when (pair? names) + (when (memq (car names) (cdr names)) + (sex-error form "two captures share a name" (car names))) + (twice (cdr names)))) (for-each (lambda (statement) (match statement (('var (? symbol? name) . _) diff --git a/tests/codegen.scm b/tests/codegen.scm index a4cd699..2b4beab 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -498,6 +498,9 @@ (test-assert "a capture named like a parameter is refused" (reports? (in-fn "(var c (closure ((int)) int) (closure ((a int)) int (a) (return a)))") "a capture and a parameter share a name")) + (test-assert "so is one captured twice" + (reports? (in-fn "(var c (closure () int) (closure () int (a a) (return a)))") + "two captures share a name")) (test-assert "so is one redeclared at the top of the body" (reports? (in-fn "(var c (closure () int) (closure () int (a) (var a int 5) (return a)))") "the body redeclares a capture")) -- 2.52.0 From a2bbb735240f9fc154f754f447c4459227bad62d Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 27 Oct 2026 22:41:06 +0300 Subject: [PATCH 72/74] spell the least long long as C's LLONG_MIN -9223372036854775808 reached C as written, where it negates an unsigned constant, and had no type for inference: it is read as -9223372036854775807 - 1, which is long long on both sides. --- reader.scm | 5 ++++- tests/codegen.scm | 5 ++++- tests/sex-programs/c11.sex | 7 ++++--- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/reader.scm b/reader.scm index 5110972..f998827 100644 --- a/reader.scm +++ b/reader.scm @@ -234,7 +234,9 @@ ;;; Scheme reads numbers C has no literal for -- 1/2, #e1.5, 1e400, ;;; +nan.0, 1+2i -- and they reached C as written. An integer too wide ;;; for long long is unsigned to C, which says so only by a warning -;;; unless it is written with a `u'; so it is. +;;; unless it is written with a `u'; so it is. -9223372036854775808 is +;;; one too: C negates the unsigned 9223372036854775808, so it is +;;; spelled as LLONG_MIN is, -9223372036854775807 - 1. (define +llong-min+ (- (expt 2 63))) (define +llong-max+ (- (expt 2 63) 1)) (define +ullong-max+ (- (expt 2 64) 1)) @@ -245,6 +247,7 @@ (error "too large for any C integer type" s)) ((> n +llong-max+) (make-number-literal n "u" #f)) ((< n +llong-min+) (list '- (make-number-literal (- n) "u" #f))) + ((= n +llong-min+) (list '- (+ n 1) 1)) (else n))) ((and (real? n) (inexact? n) (finite? n)) n) (else (error "C has no literal for this number" s)))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 2b4beab..2044827 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -1190,7 +1190,10 @@ (emits? (in-fn "(var n (unsigned int) -1u)") "n = -1u;")) (test-assert "a number too wide for long long is unsigned, and says so" (emits? (in-fn "(var n (unsigned long long) 0xFFFFFFFFFFFFFFFF)") - "n = 18446744073709551615u;"))) + "n = 18446744073709551615u;")) + (test-assert "the least long long is spelled as LLONG_MIN, and typed" + (emits? (in-fn "(var n _ -9223372036854775808)") + "long long n = -9223372036854775807 - 1;"))) ;; A define's body was pasted unwalked, and unparenthesised: `cast' ;; stayed a call, and (* x D) regrouped with D's own operator diff --git a/tests/sex-programs/c11.sex b/tests/sex-programs/c11.sex index 6065ed9..7739e85 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 12 5 0" +(output "c11: 42 43 6 4 6 12 5 0 -9223372036854775808" "trigraphs: what??! ??= ???( ??/") (return 0) @@ -33,6 +33,7 @@ (var origin point #()) (var unit _ (shape/square 1)) (var pair [_ 2] #(#(point : 1 2) #(point : 3 4))) +(var least _ -9223372036854775808) (fn sides ((s shape)) int (var n int 0) @@ -46,8 +47,8 @@ (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 %d %d %d\n" + (printf "c11: %d %d %d %d %d %d %d %d %lld\n" (.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2) - (sides unit) (.area corner) (.area [pair 1]) [primes 2] (. origin y)) + (sides unit) (.area corner) (.area [pair 1]) [primes 2] (. origin y) least) (printf "trigraphs: %s\n" "what??! ??= ???( ??/") (return 0)) -- 2.52.0 From d8900801031d10b187fb2bc248ab1ad778c645c2 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 27 Oct 2026 22:41:06 +0300 Subject: [PATCH 73/74] find the conditional by tokens a path cannot hold "holds no directive" searched for 123, a digit run the temporary directory in every #line could hold too. --- tests/line-directives.scm | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/line-directives.scm b/tests/line-directives.scm index 877b56b..c067543 100644 --- a/tests/line-directives.scm +++ b/tests/line-directives.scm @@ -231,9 +231,10 @@ after that is one more. Lines before the first directive get #f." ;; an `if' arm is a statement only where the `if' is one: a ;; directive between `?' and `:' does not compile (maps "conditional argument" "123") + ;; a bare 123 may be a digit run of the fixture's path, in every #line (test-assert "holds no directive" - (let ((start (string-contains c-out "123"))) - (not (string-contains (substring c-out start (string-contains c-out "125" start)) + (let ((start (string-contains c-out "mvar < 123"))) + (not (string-contains (substring c-out start (string-contains c-out ": 125" start)) "#line"))))) ;; A location is (file . line); every directive must name the file the -- 2.52.0 From 724f4dd3e9d6b3e09c1e9494813548b6dd8e186a Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 27 Oct 2026 22:41:06 +0300 Subject: [PATCH 74/74] report a module's macro call failing for other than its own names Reading a module's interface dropped any toplevel call that raised, not only one asking after a declaration of the module's, which no importer has yet. Lookups now tell which names they missed, and only those failures give importers nothing. --- sex-modules.scm | 44 ++++++++++++++++++++++++++++-------- tests/modules/check.scm | 7 ++++++ tests/modules/gen/broken.sex | 8 +++++++ types.scm | 19 ++++++++++++---- 4 files changed, 64 insertions(+), 14 deletions(-) create mode 100644 tests/modules/gen/broken.sex diff --git a/sex-modules.scm b/sex-modules.scm index e1021a9..1f325bb 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -130,10 +130,11 @@ ;;; macros are the module's own and those its imports give it, lent for ;;; the expanding and taken back after, so the importer is left with the ;;; pub ones alone. One that reads the type database sees what the -;;; importer knows, which a type private to the module is not; a call -;;; that cannot expand for that -- (print-struct box), box being the -;;; module's -- gives importers nothing, as before, and is the module's -;;; own compile's to check +;;; importer knows, which no declaration of the module's is yet; a call +;;; that fails after asking for one -- (field-count box), box being the +;;; module's record -- gives importers nothing, as before, and is the +;;; module's own compile's to check. Any other failure is the importer's +;;; too: (boom) raising "nope" says so wherever it is read (define +modules-expanded+ (list)) (define (module-forms raw-forms) @@ -144,7 +145,8 @@ forms)))) (define (expanded raw-forms) - (let ((lent (list))) + (let ((lent (list)) + (declared (declared-names raw-forms))) (define (lend! form) (let ((name (macro-name form))) (unless (assq name lent) @@ -154,15 +156,37 @@ (cond ((macro-name form) (lend! form) (list form)) ((splice? form) (append-map expand (cdr form))) ((macro? form) - (let ((result (handle-exceptions exn #f (apply-macro form)))) + (let ((result (expand-call form declared))) (cond ((or (not result) (null? result)) (list)) (else (stamp-form-source! result (form-source form)) (expand result))))) (else (list form)))) - (for-each lend! (imported-macro-forms raw-forms)) - (let ((forms (append-map expand raw-forms))) - (for-each (lambda (entry) (restore-macro! (car entry) (cdr entry))) lent) - forms))) + (dynamic-wind + void + (lambda () + (for-each lend! (imported-macro-forms raw-forms)) + (append-map expand raw-forms)) + (lambda () + (for-each (lambda (entry) (restore-macro! (car entry) (cdr entry))) + lent))))) + +(define (expand-call form declared) + (let ((unknown (list))) + (handle-exceptions exn + (if (any (lambda (name) (memq name declared)) unknown) #f (abort exn)) + (parameterize ((unknown-name (lambda (name) (set! unknown (cons name unknown))))) + (apply-macro form))))) + +;;; The names FORMS declare, types and all +(define (declared-names forms) + (append (map car (declared-types forms)) + (filter-map (lambda (form) + (match form + ((or ('pub (or 'fn 'var) (? symbol? name) . _) + ((or 'fn 'var) (? symbol? name) . _)) + name) + (_ #f))) + forms))) (define (splice? form) (and (pair? form) (eq? (car form) '$) (list? form))) diff --git a/tests/modules/check.scm b/tests/modules/check.scm index cf2de87..3775bc6 100644 --- a/tests/modules/check.scm +++ b/tests/modules/check.scm @@ -38,6 +38,7 @@ ;;; ;;; gen/made writes its pub forms by macro calls, which are expanded when ;;; its interface is read; the macros it used for that stay its own. +;;; gen/broken's call raises, which reading its interface reports. ;;; ;;; make check-modules @@ -138,6 +139,12 @@ '("made 42 7 1 2") (output-of (built "made-app"))) +;;; ...but a call failing for other than a name its module declares fails +;;; there as well +(test-assert "a toplevel macro call that raises fails the interface too" + (let ((err (error-of sexc "--public-interface" "gen/broken.sex"))) + (and err (irregex-search "broken\\.sex:8: expanding boom: nope" err)))) + ;;; ...while a realization of a spec importers cannot see is refused by ;;; the module that writes it, not by an importer naming it first (test-assert "a pub realization of a spec imported without pub is refused" diff --git a/tests/modules/gen/broken.sex b/tests/modules/gen/broken.sex new file mode 100644 index 0000000..b7063f9 --- /dev/null +++ b/tests/modules/gen/broken.sex @@ -0,0 +1,8 @@ +;;; A toplevel macro call failing for what it is, not for asking after a +;;; name declared here: an importer is told so, as this module is +(defmacro (boom) + (error "nope")) + +(pub fn fine () int (return 1)) + +(boom) diff --git a/types.scm b/types.scm index 8a73ccc..035f615 100644 --- a/types.scm +++ b/types.scm @@ -49,6 +49,7 @@ add-name-type! get-name-type + unknown-name type-of current-type-of get-return-type @@ -156,11 +157,21 @@ (define (add-name-type! name type) (hash-table-set! +name-db+ name type)) +;;; Called with each name a lookup finds nothing for. A module's +;;; interface is read before its declarations are, so a macro call there +;;; asking after one -- (field-count box), box being its record -- is +;;; told nothing, and fails for that rather than for being wrong +(define unknown-name (make-parameter void)) + +(define (known name info) + (unless info ((unknown-name) name)) + info) + ;;; #f for a name never declared, which is what `printf' looks like ;;; until something parses stdio.h. Not an error here; the caller ;;; decides. (define (get-name-type name) - (hash-table-ref/default +name-db+ name #f)) + (known name (hash-table-ref/default +name-db+ name #f))) ;;; What `(make-adder 10)' has for a type: `make-adder's return type, ;;; or #f when NAME is not a function with a signature on record @@ -172,7 +183,7 @@ (third type)))) (define (get-tag-info name) - (hash-table-ref/default +tag-db+ name #f)) + (known name (hash-table-ref/default +tag-db+ name #f))) ;;; First look up the ordinary identifier, then tag of that id when ;;; no ordinary one was declared, as C does @@ -296,7 +307,7 @@ (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)) + (known type (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) @@ -338,7 +349,7 @@ ;;; 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)))) + (known 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 -- 2.52.0