From 8bc27cba26834a827e5d66c067b0a5b978952c28 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 15:41:43 +0300 Subject: [PATCH 01/43] parenthesise casts and conditionals by precedence Neither took part in it: a cast parenthesised its operand only from a list of binary heads that missed `|', and never itself, so `->' took it apart; `?:' was written bare under any operator, swallowing it into the test. Three of the four still compiled, to wrong values. Fixes #59, #61, #62. --- Makefile | 1 + sex-fmt-c.scm | 48 +++++++++++++++---------------- tests/codegen.scm | 30 ++++++++++++++++++- tests/sex-programs/precedence.sex | 28 ++++++++++++++++++ 4 files changed, 81 insertions(+), 26 deletions(-) create mode 100644 tests/sex-programs/precedence.sex diff --git a/Makefile b/Makefile index 2ba0f4c..08e181e 100644 --- a/Makefile +++ b/Makefile @@ -119,6 +119,7 @@ SEX_TEST_PROGRAMS = c11 \ lists \ operators \ ops \ + precedence \ records \ serialize \ specs \ diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index 89f8835..f0ccde8 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -80,6 +80,7 @@ ((dot arrow post-decrement post-increment) 10) ((**) 15) ; Perl ((unary+ unary- ! ~ cast unary-* unary-& sizeof) 20) ; ++ -- + ((cast-operand) 25) ; see c-cast ((=~ !~) 25) ; Perl ((* / %) 30) ((+ -) 35) @@ -805,32 +806,22 @@ (fmt-join c-expr name ", ") (c-expr name)))))) - ;; MODIFIED FROM UPSTREAM fmt-c: parenthesise a binary operand. + ;; MODIFIED FROM UPSTREAM fmt-c: take part in precedence, both ways. ;; - ;; A cast binds tighter than every binary operator, so upstream's - ;; unparenthesised (cat "(" type ")" expr) silently casts only the - ;; first operand: (cast (* 2 (sizeof GLfloat)) (* void)) came out as - ;; `(void *)2 * sizeof(GLfloat)'. Unary operands -- &x, *p, -n, - ;; sizeof, calls, identifiers, literals -- are already - ;; unary-expressions and are left alone, so this changes nothing that - ;; was previously correct. - (define c-binary-operators - '(+ - * / % << >> < > <= >= == != & ^ && %and %or - = *= /= %= &= ^= <<= >>=)) - - (define (c-binary-expression? expr) - (and (pair? expr) - (memq (car expr) c-binary-operators) - (pair? (cdr expr)) - (pair? (cddr expr)))) ; two or more operands - + ;; Upstream's bare (cat "(" type ")" expr) cast only the first operand + ;; of a looser one -- (cast (* 2 (sizeof GLfloat)) (* void)) came out + ;; `(void *)2 * sizeof(GLfloat)' -- and was itself taken apart by a + ;; tighter operator around it: `(const wanted *)pa->distance'. + ;; + ;; The operand is written at `cast-operand', just looser than a unary + ;; operator, so a unary operand stays bare -- `(int *)&a' -- while + ;; anything looser parenthesises itself. The cast is parenthesised + ;; only under something strictly tighter: `-(int)a', `*(int *)v'. (define (c-cast type expr) - (cat "(" (c-type type) ")" - (if (c-binary-expression? expr) - ;; c-with-op stops the operand from parenthesising itself - ;; a second time inside the parens we just added. - (cat "(" (c-with-op 'paren (c-expr expr)) ")") - (c-expr expr)))) + (lambda (st) + (let ((cast (cat "(" (c-type type) ")" + (c-with-op 'cast-operand (c-expr expr))))) + ((if (c-op< (fmt-op st) 'cast) (c-paren cast) cast) st)))) ;; { a, b, c } -- on one line if it fits, one element per line if not. (define (c-braced-list ls) @@ -881,7 +872,14 @@ tail)))) st)))) - (define (c-if/expr c p . rest) + ;; MODIFIED FROM UPSTREAM fmt-c: parenthesised as the operator it is. + ;; Upstream wrote it bare whatever surrounded it, and `?:' binds + ;; looser than every binary operator: (/ 300 (if c c 1)) came out + ;; `300 / c ? c : 1', a conditional on the quotient. + (define (c-if/expr . args) + (c-maybe-paren '? (apply c-if/expr/aux args))) + + (define (c-if/expr/aux c p . rest) (let lp ((c c) (p p) (ls rest)) (cond ((or (eq? c 'else) (eq? c #t)) diff --git a/tests/codegen.scm b/tests/codegen.scm index 7fe9c25..2a1edd3 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -114,7 +114,35 @@ compiles." "(int *)&a")) (test-assert "sizeof is left bare" (emits? (in-fn "(var n int (cast (sizeof int) int))") - "(int)sizeof(int)"))) + "(int)sizeof(int)")) + ;; `|' reaches fmt-c as a string, which a list of binary heads to + ;; parenthesise did not have + (test-assert "bitwise operand is parenthesised" + (emits? (in-fn "(var f float (cast (| a b) float))") + "(float)(a | b)")) + (test-assert "conditional operand is parenthesised" + (emits? (in-fn "(var f float (cast (if a a b) float))") + "(float)(a ? a : b)")) + ;; A cast is the operand here, and binds looser than `->' + (test-assert "cast under a member access is parenthesised" + (emits? (in-line "(var v (* void) pp) (var x int (. (cast v (* struct point)) x))") + "((struct point*)v)->x")) + (test-assert "cast under a unary operator is left bare" + (emits? (in-line "(var v (* void) pp) (var x int (* (cast v (* int))))") + "*(int *)v"))) + + ;; `?:' binds looser than every binary operator, so as an operand it + ;; has to be parenthesised, or C takes the operator into its test + (test-group "conditional expression precedence" + (test-assert "operand of a binary operator" + (emits? (in-fn "(var x int (/ a (if a a b)))") + "a / (a ? a : b)")) + (test-assert "left bare where it is the whole value" + (emits? (in-fn "(var x int (if a a b))") + "int x = a ? a : b")) + (test-assert "left bare as an argument" + (emits? (in-fn "(g (if a a b) b)") + "g(a ? a : b, b)"))) ;; A comment among a call's arguments used to become an argument, ;; and c-apply put a comma on each side of it -- which does not diff --git a/tests/sex-programs/precedence.sex b/tests/sex-programs/precedence.sex new file mode 100644 index 0000000..4f28409 --- /dev/null +++ b/tests/sex-programs/precedence.sex @@ -0,0 +1,28 @@ +(input) +(output "conditional operand: 75" + "cast as object of .: 7" + "cast of bitwise: 1" + "cast of conditional: 44") +(return 0) + +;;; A Sex form is parenthesised by construction, and C is not: whatever +;;; the writer leaves bare, C regroups by its own precedence. Each line +;;; below came out regrouped, and the first and the last two still +;;; compiled -- computing 4, 257 and 300. + +(include stdio.h) + +(record wanted ((distance int))) + +(pub fn main () int + (var compared int 4) + (printf "conditional operand: %d\n" (/ 300 (if (> compared 0) compared 1))) + + (var w wanted #(wanted : 7)) + (var pa (* const void) (& w)) + (printf "cast as object of .: %d\n" (. (cast pa (* const wanted)) distance)) + + (var x int 1) + (printf "cast of bitwise: %d\n" (cast (| x 256) u8)) + (printf "cast of conditional: %d\n" (cast (if x 300 1) u8)) + (return 0)) -- 2.52.0 From dfdca46e1ebd6bf6b341b89230f3c28618cc6f47 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 15:55:33 +0300 Subject: [PATCH 02/43] tell an array's bound by the shape of its type Whether a trailing name was the bound hinged on the word before it being a typedef Sex had seen, which a header's pthread_t never is, and a grouped (* T) never is either: [pthread-t N] became a two-word type. Fixes #56, #60. --- tests/sex-programs/type-shapes.sex | 10 ++++++++++ tests/types.module.scm | 1 - tests/types.scm | 22 +++++++++++++++++++++- types.module.scm | 1 - types.scm | 30 ++++++++++-------------------- 5 files changed, 41 insertions(+), 23 deletions(-) diff --git a/tests/sex-programs/type-shapes.sex b/tests/sex-programs/type-shapes.sex index 56a99df..1c63b36 100644 --- a/tests/sex-programs/type-shapes.sex +++ b/tests/sex-programs/type-shapes.sex @@ -5,6 +5,7 @@ "through a pointer: 55" "unsized of a typedef: 1 2" "unsized of a pointer: 5" + "named bound: 2 4 b" "unnamed parameters: 7 -1 2") (return 0) @@ -22,6 +23,8 @@ (typedef small int) +(define CAP 2) + ;;; a parameter that names nothing is a type, however many words it ;;; takes: `(unsigned int)' is one of them, not a `unsigned' called ;;; `int' @@ -65,6 +68,13 @@ (var w _ (¤ sizes 0)) (printf "unsized of a pointer: %d\n" (cast (* w) int)) + ;; ...but after a whole type, a name is: `size-t' is a typedef only C + ;; knows of, and `(* const char)' a type grouped into one element + (var ws (¤ size-t CAP) #(3 4)) + (var gs (¤ (* const char) CAP) #("a" "b")) + (printf "named bound: %zu %zu %s\n" + (/ (sizeof ws) (sizeof (¤ ws 0))) (¤ ws 1) (¤ gs 1)) + ;; the same question in type position: `(fn ((unsigned int)) int)' ;; takes one parameter, not two (var fp (fn ((unsigned int)) int) width) diff --git a/tests/types.module.scm b/tests/types.module.scm index 7b0f366..e2fb4bd 100644 --- a/tests/types.module.scm +++ b/tests/types.module.scm @@ -42,7 +42,6 @@ type-head? named-arg? - typedef-name? array-bound? array-element-type) "../types.scm") diff --git a/tests/types.scm b/tests/types.scm index ec17c68..46d098a 100644 --- a/tests/types.scm +++ b/tests/types.scm @@ -217,4 +217,24 @@ (get-name-type 't-never-declared)) (test "nor a return type" #f - (get-return-type 't-never-declared))) + (get-return-type 't-never-declared)) + + ;; Where an array's element type ends is a matter of shape, not of + ;; what the database happens to hold: a typedef from a C header is + ;; never in it + (test-group "array bounds" + (test-assert "a number" (array-bound? '(¤ int 4))) + (test-assert "a name after a specifier" (array-bound? '(¤ int N))) + (test-assert "a name after a type name unknown to Sex" + (array-bound? '(¤ pthread-t N))) + (test-assert "a name after a grouped type" + (array-bound? '(¤ (* t-point) N))) + (test-assert "a name after a tag" (array-bound? '(¤ struct t-point N))) + (test-assert "not a lone type" (not (array-bound? '(¤ pthread-t)))) + (test-assert "not a specifier" (not (array-bound? '(¤ unsigned int)))) + (test-assert "not a qualified name" (not (array-bound? '(¤ const t)))) + (test-assert "not a pointer's target" (not (array-bound? '(¤ * size-t)))) + (test-assert "not a tag" (not (array-bound? '(¤ struct t-point)))) + (test "the element of a grouped type is the group" + '(* t-point) + (array-element-type '(¤ (* t-point) N))))) diff --git a/types.module.scm b/types.module.scm index e2a67c5..95c350a 100644 --- a/types.module.scm +++ b/types.module.scm @@ -42,7 +42,6 @@ type-head? named-arg? - typedef-name? array-bound? array-element-type) "types.scm") diff --git a/types.scm b/types.scm index 78a183c..9ce5dda 100644 --- a/types.scm +++ b/types.scm @@ -388,22 +388,15 @@ (pair? (cdr arg)) ; 1 element args are always type (not (type-head? arg)))) -;;; A typedef and a `define' share +type-db+; only the typedef is part -;;; of a type: +;;; The last element is a bound unless what precedes it is still +;;; waiting for a type name -- a `*', a qualifier, a tag's keyword. C +;;; spells a type with one name at most, so a name after a name, or +;;; after a grouped type, can only be the bound: ;;; -;;; (typedef small int) -> (¤ small N) is N of small -;;; (define CAP 4) -> (¤ int CAP) is CAP of int -(define (typedef-name? name) - (let ((info (and (symbol? name) (get-type-info name)))) - (and info (memq (car info) '(typedef struct union enum)) #t))) - -;;; The last element is a bound only where what precedes it already -;;; spells a whole type -- a specifier, a tag after its keyword, or a -;;; typedef we have seen declared: -;;; -;;; (¤ int 4) four of int (¤ unsigned int) unsized -;;; (¤ mytype CAP) CAP of mytype (¤ struct point) unsized -;;; (¤ const mytype) unsized (¤ * size-t) unsized +;;; (¤ int 4) four of int (¤ unsigned int) unsized +;;; (¤ pthread-t CAP) CAP of pthread-t (¤ struct point) unsized +;;; (¤ (* T) CAP) CAP of (* T) (¤ const mytype) unsized +;;; (¤ * size-t) unsized ;;; ;;; TYPE is the whole `(¤ ...)' form. (define (array-bound? type) @@ -413,11 +406,8 @@ (cond ((not (symbol? bound)) #t) ((or (memq bound +c-specifiers+) (memq bound +c-qualifiers+)) #f) - ((memq preceding +c-specifiers+) #t) - ;; a tag always follows its keyword, so `(¤ * struct tt)' ends - ;; in a name belonging to the type - ((memq preceding '(struct union enum)) #f) - (else (typedef-name? preceding)))))) + (else (not (or (memq preceding '(* struct union enum)) + (memq preceding +c-qualifiers+)))))))) ;;; What one element of a written array type is: ;;; (¤ struct point 2) -> (struct point), (¤ * const char 2) -> (* const char) -- 2.52.0 From bc5f23881f4747227fb6d65d3f1a7a2becd04b04 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 15:56:32 +0300 Subject: [PATCH 03/43] spell an array bound as an expression It went to fmt-c unwalked, so a bound named CHUNK-AREA kept its dash while the same name in an expression became CHUNK_AREA. Fixes #50. --- fmt-c-writer.scm | 2 +- tests/codegen.scm | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 35be150..dec4d6e 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -315,7 +315,7 @@ forms, and what remains." (match form (('¤ . array-type) (if (array-bound? form) - `(%array ,(walk-type (array-element-type form)) ,(last array-type)) + `(%array ,(walk-type (array-element-type form)) ,(walk-expr (last array-type))) ;; 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/tests/codegen.scm b/tests/codegen.scm index 2a1edd3..67d7fb1 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -678,6 +678,11 @@ compiles." (emits? "(define N 4) (struct s ((a (¤ char (* 2 N)))))" "char a[2 * N]")) (test-assert "an integer bound still works" (emits? "(struct s ((a (¤ int 4))))" "int a[4]")) + ;; ...and it is spelled the way the same name is in an expression + (test-assert "a bound's name is converted" + (emits? (in-fn "(var xs (¤ u16 CHUNK-AREA))") "u16 xs[CHUNK_AREA]")) + (test-assert "so is one inside an expression bound" + (emits? (in-fn "(var xs (¤ u16 (* 2 CHUNK-AREA)))") "u16 xs[2 * CHUNK_AREA]")) ;; a multi-word type is keywords all the way down, so a trailing ;; keyword belongs to the type and leaves the array unsized (test-assert "a multi-word type is not a bound" -- 2.52.0 From 6f29a9c2031b0edb196c0671932576c1b29221b1 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 15:58:01 +0300 Subject: [PATCH 04/43] write a typedef's target as a type It fell through to the expression walk, which read (* const char) as a dereference and an array as a subscript, and died on a fn type. Fixes #53. --- fmt-c-writer.scm | 3 +++ tests/codegen.scm | 13 +++++++++++++ tests/sex-programs/type-shapes.sex | 12 +++++++++++- 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index dec4d6e..9db3c92 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -194,6 +194,9 @@ forms, and what remains." ;; path lowers to where the thing it reads from is a pointer (('%-> . rest) (cons '%-> (map walk-expr rest))) (('var . _) (walk-var form)) + ;; semen has already put the target first, the way C writes it + (('typedef type name) + `(typedef ,(walk-type type) ,(atom-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) diff --git a/tests/codegen.scm b/tests/codegen.scm index 67d7fb1..86a76b6 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -693,6 +693,19 @@ compiles." (test-assert "nor one behind a pointer" (emits? "(struct t ((z int))) (struct s ((a (¤ * struct t))))" "struct t* a[]"))) + ;; A typedef's target is a type, and was walked as an expression: a + ;; pointer read as a dereference, an array as a subscript + (test-group "typedefs" + (test-assert "of a name" + (emits? "(typedef small int)" "typedef int small;")) + (test-assert "of a pointer" + (emits? "(typedef cstr (* const char))" "typedef const char * cstr;")) + (test-assert "of an array" + (emits? "(typedef vec4 (¤ float 4))" "typedef float vec4[4];")) + (test-assert "of a function pointer" + (emits? "(typedef colour-fn (fn ((i32)) u32))" + "typedef u32 (*colour_fn)(i32);"))) + ;; `.' is C's `.' or its `->' depending on what is being read from, ;; so a path reads the same however the thing it starts from is held (test-group "member access" diff --git a/tests/sex-programs/type-shapes.sex b/tests/sex-programs/type-shapes.sex index 1c63b36..38d1672 100644 --- a/tests/sex-programs/type-shapes.sex +++ b/tests/sex-programs/type-shapes.sex @@ -6,7 +6,8 @@ "unsized of a typedef: 1 2" "unsized of a pointer: 5" "named bound: 2 4 b" - "unnamed parameters: 7 -1 2") + "unnamed parameters: 7 -1 2" + "typedefs: hi 4 2") (return 0) ;;; Three questions about a written type that used to be answered in @@ -22,6 +23,9 @@ (struct point ((x int) (y int))) (typedef small int) +(typedef cstr (* const char)) +(typedef vec4 (¤ float 4)) +(typedef unary (fn ((small)) small)) (define CAP 2) @@ -79,4 +83,10 @@ ;; takes one parameter, not two (var fp (fn ((unsigned int)) int) width) (printf "unnamed parameters: %d %d %d\n" (fp 7) (sign #\a) (twice 1)) + + ;; a typedef's target is every one of those shapes as well + (var greeting cstr "hi") + (var v vec4 #(1.0 2.0 3.0 4.0)) + (var op unary twice) + (printf "typedefs: %s %zu %d\n" greeting (/ (sizeof v) (sizeof (¤ v 0))) (op 1)) (return 0)) -- 2.52.0 From 8db9246389e4d57c02cb3ae3234cb0d802d85909 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 15:59:16 +0300 Subject: [PATCH 05/43] convert enumerators written with a value (wire-varint 0) is a pair, and both the writer and map-fields only expected a name: the writer passed it out unconverted, and a macro mapping over the enum was handed the pair. Fixes #46. --- fmt-c-writer.scm | 10 ++++++++-- tests/codegen.scm | 10 ++++++++++ tests/types.scm | 4 ++++ types.scm | 6 ++++-- 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 9db3c92..2281f7d 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -449,11 +449,17 @@ forms, and what remains." (('enum (? symbol? name)) `(enum ,(atom-to-fmt-c name))) (('enum (values ...)) - `(enum ,(map atom-to-fmt-c values))) + `(enum ,(map walk-enumerator values))) (('enum name (values ...)) - `(enum ,(atom-to-fmt-c name) ,(map atom-to-fmt-c values))) + `(enum ,(atom-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 + ((name expr) (list (atom-to-fmt-c name) (walk-expr expr))) + (_ (atom-to-fmt-c value)))) + (define (walk-extern form) (match form (('fn . _) diff --git a/tests/codegen.scm b/tests/codegen.scm index 86a76b6..3cb08eb 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -200,6 +200,16 @@ compiles." (emits? "(pub enum color (red green blue))" "enum color")) (test-assert "with its values" (emits? "(pub enum color (red green blue))" "red")) + ;; A value made the enumerator a pair, which went out unconverted + (test-assert "explicit values" + (emits? "(pub enum wire ((wire-varint 0) (wire-fixed64 1)))" + "wire_varint = 0, wire_fixed64 = 1")) + (test-assert "a value is an expression" + (emits? "(enum wire ((wire-last (+ WIRE-BASE 1))))" + "wire_last = WIRE_BASE + 1")) + (test-assert "and an anonymous enum takes them too" + (emits? "(fn f () void (var e (enum ((up-one 1) down)) up-one))" + "up_one = 1, down")) (test-assert "and a non-pub enum still is too" (emits? "(enum color (red green blue))" "enum color")) ;; Naming an enum as a type, rather than defining it, had no diff --git a/tests/types.scm b/tests/types.scm index 46d098a..144e770 100644 --- a/tests/types.scm +++ b/tests/types.scm @@ -139,6 +139,10 @@ (test "enum values are fields whose type is the enum" '((red (enum t-color)) (green (enum t-color)) (blue (enum t-color))) (map-fields 't-color (lambda (name type) (list name type)))) + (add-enum 't-wire '(enum t-wire ((t-varint 0) (t-fixed64 1) t-bytes))) + (test "an enumerator with a value is still named by its name" + '(t-varint t-fixed64 t-bytes) + (map-fields 't-wire (lambda (name type) name))) (test "a typedef has no fields to map" #f (map-fields 't-u8 (lambda (name type) name))) diff --git a/types.scm b/types.scm index 9ce5dda..3d91404 100644 --- a/types.scm +++ b/types.scm @@ -335,7 +335,8 @@ (else (equal? pattern type)))) ;;; Map function to each field/value of a structure/union/enum -;;; For enums, field-type is the type of the enum (since C 23) +;;; For enums, field-type is the type of the enum (since C 23), and +;;; field-name the enumerator's name, (wire-varint 0) or not ;;; (map-fields type-name ;;; (lambda (field-name field-type) ...)) ;;; @@ -351,7 +352,8 @@ ;; declared, since `enum some-typedef' is not a C type. ((enum) (let ((type (list 'enum (cadr info)))) - (map (lambda (value) (fn value type)) + (map (lambda (value) + (fn (if (pair? value) (car value) value) type)) (caddr info)))) (else #f))))) -- 2.52.0 From ba45069484b2cb8d4acc50ad400ef02132f3c454 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 16:00:28 +0300 Subject: [PATCH 06/43] walk a define's body, and parenthesise it The body was pasted as read, so `cast' stayed a call and names kept their dashes; and fmt-c parenthesised only a function-like body, so an object-like one regrouped with the operator it was pasted under. Fixes #55. --- fmt-c-writer.scm | 2 +- sex-fmt-c.scm | 14 +++++++++++--- tests/codegen.scm | 15 +++++++++++++++ tests/sex-programs/precedence.sex | 10 +++++++--- 4 files changed, 34 insertions(+), 7 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 2281f7d..9cc0fcf 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -507,7 +507,7 @@ forms, and what remains." ;; A target is a filename and not an identifier: GL/gl.h is a path, ;; and unkebabify would spell it GLːgl.h (('include target) (list '%include target)) - (('define name . rest) `(%define ,(atom-to-fmt-c name) ,@rest)) + (('define name . body) `(%define ,(walk-expr name) ,@(map walk-expr body))) (else (walk-expr form)))) ;;; Two toplevel forms are separated by a blank line only if they were diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index f0ccde8..c9ef004 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -433,6 +433,15 @@ ((pair? x) (cons (replace (car x)) (replace (cdr x)))) (else x)))) + ;; MODIFIED FROM UPSTREAM fmt-c: an object-like body is parenthesised + ;; as a function-like one is. Upstream left it bare, so with + ;; `#define D -1.0 / 6.0', `x * D' was `(x * -1.0) / 6.0'. Only a + ;; name or a literal that cannot lose its sign to a neighbour is + ;; left as written. + (define (c-atomic-body? x) + (or (symbol? x) + (and (c-literal? x) (not (and (number? x) (negative? x)))))) + (define (cpp-define x . body) (define (name-of x) (c-expr (if (pair? x) (cadr x) x))) (lambda (st) @@ -450,9 +459,8 @@ (cat " " (fmt-let 'writer (make-cpp-writer st) (fmt-let 'macro-params params - ((if (or (not (pair? x)) - (and (null? (cdr body)) - (c-literal? (car body)))) + ((if (and (null? (cdr body)) + (c-atomic-body? (car body))) (lambda (x) x) c-paren) (c-in-expr (apply c-begin body)))))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 3cb08eb..2d4e7e9 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -703,6 +703,21 @@ compiles." (test-assert "nor one behind a pointer" (emits? "(struct t ((z int))) (struct s ((a (¤ * struct t))))" "struct t* a[]"))) + ;; 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" + (test-assert "an atom is left bare" + (emits? "(define N 4)" "#define N 4")) + (test-assert "and its name converted" + (emits? "(define MAX-N MIN-N)" "#define MAX_N MIN_N")) + (test-assert "an expression is walked and parenthesised" + (emits? "(define K (/ (cast 255 float) (cast 60 float)))" + "#define K ((float)255 / (float)60)")) + (test-assert "so is a negative literal" + (emits? "(define NEG -1)" "#define NEG (-1)")) + (test-assert "a function-like one is converted too" + (emits? "(define (sq-of x) (* x x))" "#define sq_of(x) ((x) * (x))"))) + ;; A typedef's target is a type, and was walked as an expression: a ;; pointer read as a dereference, an array as a subscript (test-group "typedefs" diff --git a/tests/sex-programs/precedence.sex b/tests/sex-programs/precedence.sex index 4f28409..7e8ad2e 100644 --- a/tests/sex-programs/precedence.sex +++ b/tests/sex-programs/precedence.sex @@ -2,18 +2,21 @@ (output "conditional operand: 75" "cast as object of .: 7" "cast of bitwise: 1" - "cast of conditional: 44") + "cast of conditional: 44" + "define body: 6") (return 0) ;;; A Sex form is parenthesised by construction, and C is not: whatever ;;; the writer leaves bare, C regroups by its own precedence. Each line -;;; below came out regrouped, and the first and the last two still -;;; compiled -- computing 4, 257 and 300. +;;; below came out regrouped, and all but the member access still +;;; compiled -- computing 4, 257, 300, and 4 from `2 * 1 + 2'. (include stdio.h) (record wanted ((distance int))) +(define SUM (+ 1 2)) + (pub fn main () int (var compared int 4) (printf "conditional operand: %d\n" (/ 300 (if (> compared 0) compared 1))) @@ -25,4 +28,5 @@ (var x int 1) (printf "cast of bitwise: %d\n" (cast (| x 256) u8)) (printf "cast of conditional: %d\n" (cast (if x 300 1) u8)) + (printf "define body: %d\n" (* 2 SUM)) (return 0)) -- 2.52.0 From f0a1b6712f70394d63a35480880d3072f48faecc Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 16:01:32 +0300 Subject: [PATCH 07/43] spell ? and ! in names as letters C takes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Lisp predicate came out as ident_start?, which no C compiler reads. ʔ and ꜝ are letters that look the part; ǃ looks closer, but clang flags it as a homoglyph of `!' at every use. Fixes #49. --- fmt-c-writer.scm | 17 ++++++++++++----- tests/basic.scm | 7 +++++++ tests/sex-programs/unicode.sex | 12 +++++++++++- 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 9cc0fcf..6a8771a 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -102,15 +102,22 @@ forms, and what remains." ;;; hand-written vec2__length would collide, and an identifier holding ;;; `__' is reserved in C++, which a pub header may be included from. ;;; Lifted closures carry a ƛ for the same reason. +;;; +;;; zero? -> zeroʔ, clear! -> clearꜝ: a glottal stop and a raised +;;; exclamation mark, both letters. Not the retroflex click ǃ, which +;;; looks more like `!' -- enough that clang warns at every use. +(define +name-spellings+ + '(("-(?!>)" . "_") ("/" . "ː") ("\\?" . "ʔ") ("!" . "ꜝ"))) + (define (unkebabify sym) (case sym - ((- -- -> -= / /=) sym) ; bare operators, not names + ((- -- -> -= / /= ! != ?) sym) ; bare operators, not names (else (string->symbol - (irregex-replace/all - "/" - (irregex-replace/all "-(?!>)" (symbol->string sym) "_") - "ː"))))) + (fold (lambda (spelling name) + (irregex-replace/all (car spelling) name (cdr spelling))) + (symbol->string sym) + +name-spellings+))))) (define (atom-to-fmt-c atom) (case atom diff --git a/tests/basic.scm b/tests/basic.scm index 3456f0b..f03157d 100644 --- a/tests/basic.scm +++ b/tests/basic.scm @@ -13,6 +13,13 @@ (test '_this_->_member_ (unkebabify '-this-->-member-)) (test '__->>> (unkebabify '--->>>)) + ;; A Lisp predicate and mutator, in letters C takes. The operators + ;; spelled with the same characters are not names + (test 'ident_startʔ (unkebabify 'ident-start?)) + (test 'resetꜝ (unkebabify 'reset!)) + (test '! (unkebabify '!)) + (test '!= (unkebabify '!=)) + ;; Non-ASCII identifiers must survive intact. The `regex' egg's ;; string-substitute drops one trailing character per multi-byte ;; character, which renames things silently -- the C still compiles, diff --git a/tests/sex-programs/unicode.sex b/tests/sex-programs/unicode.sex index 93fa7d3..a89543c 100644 --- a/tests/sex-programs/unicode.sex +++ b/tests/sex-programs/unicode.sex @@ -1,5 +1,5 @@ (input) -(output "café 日本語 🍺" "café1" "naïve: 3") +(output "café 日本語 🍺" "café1" "naïve: 3" "predicate: 1 0") (return 0) ;;; Non-ASCII string literals and identifiers. @@ -13,12 +13,22 @@ ;;; non-ASCII characters must survive unkebabify intact -- getting this ;;; wrong truncates the name silently, and the program still compiles ;;; and runs, just under a different name than the one written. +;;; +;;; `?' and `!' end Lisp predicates and mutators, and C takes neither: +;;; they become the letters ʔ and ꜝ. (include stdio.h) +(fn zero? ((n int)) bool (return (== n 0))) +(fn clear! ((n (* int))) void (= (* n) 0)) + (pub fn main () int (puts "café 日本語 🍺") (puts "café1") (var naïve-count int 3) (printf "naïve: %d\n" naïve-count) + (var n int 5) + (var before bool (zero? n)) + (clear! (& n)) + (printf "predicate: %d %d\n" (zero? n) before) (return 0)) -- 2.52.0 From ab4fdc54f3a46f2ad0ccb66fbcc511fc32d53af1 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 16:04:00 +0300 Subject: [PATCH 08/43] let sizeof take a type that looks like an expression (* char) is a pointer type and (* p) a dereference, and only the names in scope tell them apart, so semen decides and marks a type for the writer. Before, both were walked as expressions: sizeof(*char). Fixes #52. --- fmt-c-writer.scm | 3 +++ semen.scm | 25 +++++++++++++++++++++++++ sex-fmt-c.scm | 1 + tests/codegen.scm | 24 +++++++++++++++++++++++- tests/sex-programs/type-shapes.sex | 8 +++++++- 5 files changed, 59 insertions(+), 2 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 6a8771a..4fe213b 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -201,6 +201,9 @@ forms, and what remains." ;; path lowers to where the thing it reads from is a pointer (('%-> . rest) (cons '%-> (map walk-expr rest))) (('var . _) (walk-var form)) + ;; semen has told a type from an expression; only it knows the names + ;; in scope that make `(* p)' one or the other + (('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))) diff --git a/semen.scm b/semen.scm index 62aba86..e785362 100644 --- a/semen.scm +++ b/semen.scm @@ -668,6 +668,14 @@ ((dot-access) (walk-member-path form env)) + ((sizeof) + (if (and (= 2 (length form)) (written-type? (second form) env)) + (copy-form-source! + form + `(sizeof (%type ,(resolve-closure-types + (expand-type (second form) env))))) + (walk-parts form env))) + (else (cond ((method-head? (car form)) (walk-method-call form env)) @@ -775,6 +783,23 @@ (append (drop-right parts (length elements)) (map (lambda (element) (walk-operand element env)) elements))))) +;;; Is the operand of `sizeof' a type? `(* x)' and `(¤ x i)' are +;;; expressions when x is: a name in scope, or a list that is not +;;; itself a type. A name nothing declared is one only C knows of, and +;;; there that is a type: +;;; +;;; (* char) (* const char) (* size-t) (unsigned int) types +;;; (* p) (* (g)) (¤ xs 0) expressions +(define (written-type? form env) + (and (pair? form) + ;; the length a dereference and a subscript have + (if (= (length form) (case (car form) ((*) 2) ((¤) 3) (else -1))) + (let ((operand (second form))) + (if (symbol? operand) + (not (or (lookup-name env operand) (get-name-type operand))) + (written-type? operand env))) + (type-head? form)))) + ;;; `(var n _ (strlen s))' becomes `(var n size-t (strlen s))'. (define (resolve-wildcard form env) (if (and (>= (length form) 3) (wildcard-type? (third form))) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index c9ef004..e9ae69a 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -288,6 +288,7 @@ ((%comment) ((apply c-comment (cdr x)) st)) ((:) ((apply c-label (cdr x)) st)) ((%cast) ((apply c-cast (cdr x)) st)) + ((%sizeof-type) ((cat "sizeof(" (c-type (cadr x)) ")") st)) ((%compound) ((apply c-compound (cdr x)) st)) ((%designate) ((apply c-designate (cdr x)) st)) ((+ - & * / % ! ~ ^ && < > <= >= == != << >> diff --git a/tests/codegen.scm b/tests/codegen.scm index 2d4e7e9..6155234 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -703,7 +703,29 @@ compiles." (test-assert "nor one behind a pointer" (emits? "(struct t ((z int))) (struct s ((a (¤ * struct t))))" "struct t* a[]"))) - ;; A define's body was pasted unwalked, and unparenthesised: `cast' +;; `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 + (test-group "sizeof" + (test-assert "a pointer type" + (emits? (in-fn "(var n size-t (sizeof (* char)))") "sizeof(char *)")) + (test-assert "a qualified one" + (emits? (in-fn "(var n size-t (sizeof (* const char)))") "sizeof(const char *)")) + (test-assert "to a type only C knows of" + (emits? (in-fn "(var n size-t (sizeof (* size-t)))") "sizeof(size_t *)")) + (test-assert "a multi-word type" + (emits? (in-fn "(var n size-t (sizeof (unsigned int)))") "sizeof(unsigned int)")) + (test-assert "an array type" + (emits? (in-fn "(var n size-t (sizeof (¤ int 4)))") "sizeof(int [4])")) + (test-assert "a dereference of a local" + (emits? (in-fn "(var p (* int) 0) (var n size-t (sizeof (* p)))") "sizeof(*p)")) + (test-assert "of a parameter" + (emits? "(fn f ((p (* int))) void (var n size-t (sizeof (* p))))" "sizeof(*p)")) + (test-assert "of a call" + (emits? (in-fn "(var n size-t (sizeof (* (g))))") "sizeof(*g())")) + (test-assert "a subscript" + (emits? (in-fn "(var xs (¤ int 4)) (var n size-t (sizeof (¤ xs 0)))") "sizeof(xs[0])"))) + + ;; 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" (test-assert "an atom is left bare" diff --git a/tests/sex-programs/type-shapes.sex b/tests/sex-programs/type-shapes.sex index 38d1672..68446e6 100644 --- a/tests/sex-programs/type-shapes.sex +++ b/tests/sex-programs/type-shapes.sex @@ -7,7 +7,8 @@ "unsized of a pointer: 5" "named bound: 2 4 b" "unnamed parameters: 7 -1 2" - "typedefs: hi 4 2") + "typedefs: hi 4 2" + "sizeof a pointer type: 1 1") (return 0) ;;; Three questions about a written type that used to be answered in @@ -89,4 +90,9 @@ (var v vec4 #(1.0 2.0 3.0 4.0)) (var op unary twice) (printf "typedefs: %s %zu %d\n" greeting (/ (sizeof v) (sizeof (¤ v 0))) (op 1)) + + ;; `(* T)' is a type or a dereference, and only what is in scope says + (printf "sizeof a pointer type: %d %d\n" + (== (sizeof (* const char)) (sizeof greeting)) + (== (sizeof (* greeting)) 1)) (return 0)) -- 2.52.0 From cc0f7f91ec3a609017b01d5c28a370b8c6970902 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 16:05:03 +0300 Subject: [PATCH 09/43] read -NAME as the negation of NAME The reader took -INFINITY as one symbol, and the leading dash was then mangled like any other: _INFINITY. -1 was always a number, so a name gets the same reading. Fixes #63. --- reader.scm | 9 +++++++++ tests/codegen.scm | 2 ++ tests/reader.scm | 9 +++++++++ 3 files changed, 20 insertions(+) diff --git a/reader.scm b/reader.scm index 566fd10..d1dd55f 100644 --- a/reader.scm +++ b/reader.scm @@ -179,8 +179,17 @@ (cond ((string=? s ".") dot-token) ((string->number s) => identity) + ((negated-name? s) (list '- (string->symbol (substring s 1)))) (else (string->symbol s)))) +;;; -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) + (char=? #\- (string-ref s 0)) + (let ((c (string-ref s 1))) + (or (char-alphabetic? c) (char=? c #\_))))) + ;;; #-dispatch: booleans, characters, vectors, block/datum comments, ;;; feature expressions (define (read-hash port) diff --git a/tests/codegen.scm b/tests/codegen.scm index 6155234..476ae95 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -735,6 +735,8 @@ compiles." (test-assert "an expression is walked and parenthesised" (emits? "(define K (/ (cast 255 float) (cast 60 float)))" "#define K ((float)255 / (float)60)")) + (test-assert "and a negated name" + (emits? "(define LOWEST -INFINITY)" "#define LOWEST (-INFINITY)")) (test-assert "so is a negative literal" (emits? "(define NEG -1)" "#define NEG (-1)")) (test-assert "a function-like one is converted too" diff --git a/tests/reader.scm b/tests/reader.scm index 7367b48..23627f7 100644 --- a/tests/reader.scm +++ b/tests/reader.scm @@ -38,6 +38,15 @@ ;; a `.'-prefixed symbol is an ordinary symbol, not dot-access (reader-test '((.field obj)) "(.field obj)") + ;; a leading `-' on a name is negation, the way it is on a number: + ;; no name is spelled with one, and -INFINITY otherwise mangled into + ;; _INFINITY. The operators that start with one are left alone + (reader-test '((- INFINITY)) "-INFINITY") + (reader-test '((var best double (- INFINITY))) "(var best double -INFINITY)") + (reader-test '((- _x)) "-_x") + (reader-test '(-1 -1.5) "-1 -1.5") + (reader-test '(- -> ->> -- -=) "- -> ->> -- -=") + ;; `;' comments are preserved as (comment "...") forms (reader-test '((comment " hi")) "; hi") (reader-test '((comment ";; Prototypes")) ";;; Prototypes") -- 2.52.0 From f3d9c95daf541ac04e9be3f9713d82b009a966c2 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 16:06:14 +0300 Subject: [PATCH 10/43] read hex and binary literals 0x80 was not a number to string->number, so it became a symbol the printer escaped as |0x80|, and #x was rejected outright. Both spellings now read as the integer, which the C writes in decimal. Fixes #47. --- reader.scm | 33 ++++++++++++++++++++++++++++++-- tests/reader.scm | 7 +++++++ tests/sex-programs/operators.sex | 7 ++++++- 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/reader.scm b/reader.scm index d1dd55f..42ec90b 100644 --- a/reader.scm +++ b/reader.scm @@ -179,9 +179,27 @@ (cond ((string=? s ".") dot-token) ((string->number s) => identity) + ((radix-number s) => identity) ((negated-name? s) (list '- (string->symbol (substring s 1)))) (else (string->symbol s)))) +;;; 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 ((n (string->number body radix))) + (and (exact-integer? n) (if negative? (- n) n)))))))) + ;;; -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) @@ -190,8 +208,8 @@ (let ((c (string-ref s 1))) (or (char-alphabetic? c) (char=? c #\_))))) -;;; #-dispatch: booleans, characters, vectors, block/datum comments, -;;; feature expressions +;;; #-dispatch: booleans, characters, vectors, numbers in a radix, +;;; block/datum comments, feature expressions (define (read-hash port) (let ((c (get-ch port))) (cond @@ -200,6 +218,9 @@ ((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))) + ((memv c '(#\x #\X)) (read-radix port 16)) + ((memv c '(#\b #\B)) (read-radix port 2)) + ((memv c '(#\o #\O)) (read-radix port 8)) ((char=? c #\|) (skip-block-comment port 1) (next-token port)) ((char=? c #\;) (read-datum port) (next-token port)) ; datum comment ((char=? c #\+) (read-conditional port #t)) @@ -253,6 +274,14 @@ ((datum-token? guarded) (next-token port)) (else guarded)))) +;;; #x80, #b101, #o10 +(define (read-radix port radix) + (let* ((digits (read-atom-string port)) + (n (string->number digits radix))) + (if (exact-integer? n) + n + (error "Malformed number" digits)))) + ;;; #t / #true / #f / #false. `val' is the boolean; consume any ;;; trailing name characters and validate (define (read-bool port val) diff --git a/tests/reader.scm b/tests/reader.scm index 23627f7..a77ca0a 100644 --- a/tests/reader.scm +++ b/tests/reader.scm @@ -47,6 +47,13 @@ (reader-test '(-1 -1.5) "-1 -1.5") (reader-test '(- -> ->> -- -=) "- -> ->> -- -=") + ;; a number in another radix, spelled the way C does or the way + ;; Scheme does; either is an ordinary integer from here on + (reader-test '(224 224 5 5 -16) "0xE0 0Xe0 0b101 0B101 -0x10") + (reader-test '(128 128 5 8 -16) "#x80 #X80 #b101 #o10 #x-10") + ;; ...and only a number: a prefix with nothing after it is a name + (reader-test '(0x 0xg) "0x 0xg") + ;; `;' comments are preserved as (comment "...") forms (reader-test '((comment " hi")) "; hi") (reader-test '((comment ";; Prototypes")) ";;; Prototypes") diff --git a/tests/sex-programs/operators.sex b/tests/sex-programs/operators.sex index bd730bc..b708b83 100644 --- a/tests/sex-programs/operators.sex +++ b/tests/sex-programs/operators.sex @@ -7,7 +7,8 @@ "unsigned wins either way: 4294967295 4294967295" "toplevel: 1 2.5 hi 12" "closure in place: 5" - "a type is not a call: 7") + "a type is not a call: 7" + "radix literals: 224 5 128") (return 0) ;;; The walk types an expression by its head, and the heads it had a @@ -87,4 +88,8 @@ (var f (closure ((int)) int) (make-adder 1)) (var fp (fn ((f int) (g int)) int) area) (printf "a type is not a call: %d\n" (f 6)) + + ;; a mask reads best in the radix it is a mask in + (var lead int 0xE5) + (printf "radix literals: %d %d %d\n" (& lead 0xE0) (& lead 0b111) #x80) (return 0)) -- 2.52.0 From 7532c72dec330c34e12b21bee715124979d2ed03 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 16:32:36 +0300 Subject: [PATCH 11/43] write arrays with brackets in tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tests spelled out (¤ ...), what [...] reads into, which nobody writes. The reader's own tests keep it: there it is the point. --- tests/codegen.scm | 36 ++++++++++++------------ tests/sex-programs/closures.sex | 6 ++-- tests/sex-programs/compound-literals.sex | 2 +- tests/sex-programs/inference.sex | 2 +- tests/sex-programs/operators.sex | 4 +-- tests/sex-programs/type-shapes.sex | 36 ++++++++++++------------ tests/sex-programs/unnamed-params.sex | 8 +++--- tests/sex-programs/wildcards.sex | 16 +++++------ 8 files changed, 55 insertions(+), 55 deletions(-) diff --git a/tests/codegen.scm b/tests/codegen.scm index 476ae95..f8ee091 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -366,7 +366,7 @@ compiles." (emits? "(fn f ((c (closure ((long)) int))) int (return (c 1)))" "ƛc.code(&ƛc.env, ƛa0)")) (test-assert "a subscript receiver is evaluated once" - (emits? "(fn f ((t (¤ (closure ((int)) int) 4)) (i int)) int (return ((¤ t (++ i)) 1)))" + (emits? "(fn f ((t [(closure ((int)) int) 4]) (i int)) int (return ([t (++ i)] 1)))" "ƛint_int_call(t[++i], 1)")) (test-assert "so is a member receiver" (emits? "(struct h ((cb (closure ((int)) int)))) @@ -487,7 +487,7 @@ compiles." (test-group "macro list accessors" (test-assert "third reads an array's length" (emits? "(defmacro (len t) (third t)) - (fn f () int (return (len (¤ int 7))))" + (fn f () int (return (len [int 7])))" "return 7;")) (test-assert "second reads a tag" (emits? "(defmacro (tag t) (symbol->string (second t))) @@ -561,7 +561,7 @@ compiles." (fn f ((s (struct p))) void (var x (* _) (& s)))" "struct p* x = &s")) (test-assert "a wildcard inside an array" - (emits? (in-fn "(var t (¤ _ 3) #((¤ int 3) : 1 2 3))") "int t[3]")) + (emits? (in-fn "(var t [_ 3] #([int 3] : 1 2 3))") "int t[3]")) ;; 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" @@ -572,11 +572,11 @@ compiles." (reports? (in-fn "(var x _ #(1 2))") "cannot infer the type")) ;; ...but its elements still solve the hole in an array type (test-assert "elements solve an array's element type" - (emits? (in-fn "(var t (¤ _ 4) #(0 1 4 9))") "int t[4] = {0, 1, 4, 9}")) + (emits? (in-fn "(var t [_ 4] #(0 1 4 9))") "int t[4] = {0, 1, 4, 9}")) (test-assert "including when there are fewer than the length" - (emits? (in-fn "(var t (¤ _ 10) #(1 2))") "int t[10] = {1, 2}")) + (emits? (in-fn "(var t [_ 10] #(1 2))") "int t[10] = {1, 2}")) (test-assert "and they have to agree with each other" - (reports? (in-fn "(var t (¤ _ 2) #(1 \"s\"))") "type mismatch")) + (reports? (in-fn "(var t [_ 2] #(1 \"s\"))") "type mismatch")) ;; a closure type reaches the solver as the struct that stands for ;; it, which is the spelling `parse-type' knows (test-assert "a closure, from the signature that produced it" @@ -680,28 +680,28 @@ compiles." (emits? (in-fn "(var n int (+ (- 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[]'. + ;; symbolic one fell into the type: `[int N]' came out `int N a[]'. (test-group "array bounds" (test-assert "a symbolic bound" - (emits? "(define N 4) (struct s ((a (¤ int N))))" "int a[N]")) + (emits? "(define N 4) (struct s ((a [int N])))" "int a[N]")) (test-assert "an expression bound" - (emits? "(define N 4) (struct s ((a (¤ char (* 2 N)))))" "char a[2 * N]")) + (emits? "(define N 4) (struct s ((a [char (* 2 N)])))" "char a[2 * N]")) (test-assert "an integer bound still works" - (emits? "(struct s ((a (¤ int 4))))" "int a[4]")) + (emits? "(struct s ((a [int 4])))" "int a[4]")) ;; ...and it is spelled the way the same name is in an expression (test-assert "a bound's name is converted" - (emits? (in-fn "(var xs (¤ u16 CHUNK-AREA))") "u16 xs[CHUNK_AREA]")) + (emits? (in-fn "(var xs [u16 CHUNK-AREA])") "u16 xs[CHUNK_AREA]")) (test-assert "so is one inside an expression bound" - (emits? (in-fn "(var xs (¤ u16 (* 2 CHUNK-AREA)))") "u16 xs[2 * CHUNK_AREA]")) + (emits? (in-fn "(var xs [u16 (* 2 CHUNK-AREA)])") "u16 xs[2 * CHUNK_AREA]")) ;; a multi-word type is keywords all the way down, so a trailing ;; keyword belongs to the type and leaves the array unsized (test-assert "a multi-word type is not a bound" - (emits? "(struct s ((a (¤ unsigned int))))" "unsigned int a[]")) + (emits? "(struct s ((a [unsigned int])))" "unsigned int a[]")) ;; ...and a tag always follows its keyword (test-assert "nor is an aggregate tag" - (emits? "(struct t ((z int))) (struct s ((a (¤ struct t))))" "struct t a[]")) + (emits? "(struct t ((z int))) (struct s ((a [struct t])))" "struct t a[]")) (test-assert "nor one behind a pointer" - (emits? "(struct t ((z int))) (struct s ((a (¤ * struct t))))" "struct t* a[]"))) + (emits? "(struct t ((z int))) (struct s ((a [* struct t])))" "struct t* a[]"))) ;; `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 @@ -715,7 +715,7 @@ compiles." (test-assert "a multi-word type" (emits? (in-fn "(var n size-t (sizeof (unsigned int)))") "sizeof(unsigned int)")) (test-assert "an array type" - (emits? (in-fn "(var n size-t (sizeof (¤ int 4)))") "sizeof(int [4])")) + (emits? (in-fn "(var n size-t (sizeof [int 4]))") "sizeof(int [4])")) (test-assert "a dereference of a local" (emits? (in-fn "(var p (* int) 0) (var n size-t (sizeof (* p)))") "sizeof(*p)")) (test-assert "of a parameter" @@ -723,7 +723,7 @@ compiles." (test-assert "of a call" (emits? (in-fn "(var n size-t (sizeof (* (g))))") "sizeof(*g())")) (test-assert "a subscript" - (emits? (in-fn "(var xs (¤ int 4)) (var n size-t (sizeof (¤ xs 0)))") "sizeof(xs[0])"))) + (emits? (in-fn "(var xs [int 4]) (var n size-t (sizeof [xs 0]))") "sizeof(xs[0])"))) ;; A define's body was pasted unwalked, and unparenthesised: `cast' ;; stayed a call, and (* x D) regrouped with D's own operator @@ -750,7 +750,7 @@ compiles." (test-assert "of a pointer" (emits? "(typedef cstr (* const char))" "typedef const char * cstr;")) (test-assert "of an array" - (emits? "(typedef vec4 (¤ float 4))" "typedef float vec4[4];")) + (emits? "(typedef vec4 [float 4])" "typedef float vec4[4];")) (test-assert "of a function pointer" (emits? "(typedef colour-fn (fn ((i32)) u32))" "typedef u32 (*colour_fn)(i32);"))) diff --git a/tests/sex-programs/closures.sex b/tests/sex-programs/closures.sex index d5d3e06..fa20184 100644 --- a/tests/sex-programs/closures.sex +++ b/tests/sex-programs/closures.sex @@ -66,12 +66,12 @@ (printf "Through a parameter: %d\n" (apply-twice (make-adder 50) 10)) - (var table (¤ (closure ((int)) int) 3)) + (var table [(closure ((int)) int) 3]) (var i int 0) (for (= i 0) (< i 3) (++ i) - (= (¤ table i) (make-adder i))) + (= [table i] (make-adder i))) (printf "From an array: %d %d %d\n" - ((¤ table 0) 1) ((¤ table 1) 1) ((¤ table 2) 1)) + ([table 0] 1) ([table 1] 1) ([table 2] 1)) ;; the index must be evaluated once, so `i' ends at 1 and not 2 -- ;; read in a separate statement, since reading and bumping it in one diff --git a/tests/sex-programs/compound-literals.sex b/tests/sex-programs/compound-literals.sex index ec1e5df..fbe5411 100644 --- a/tests/sex-programs/compound-literals.sex +++ b/tests/sex-programs/compound-literals.sex @@ -38,7 +38,7 @@ ;; an array literal decays the way an array does (var a (* int) #([int 3] : 10 20 30)) - (printf "array %d %d %d\n" (¤ a 0) (¤ a 1) (¤ a 2)) + (printf "array %d %d %d\n" [a 0] [a 1] [a 2]) (printf "argument %d\n" (sum #(struct point : 2 4))) diff --git a/tests/sex-programs/inference.sex b/tests/sex-programs/inference.sex index b5d3f0a..d8b1ae5 100644 --- a/tests/sex-programs/inference.sex +++ b/tests/sex-programs/inference.sex @@ -158,7 +158,7 @@ ;;; ;;; 1. SETTLED. `type-match' took `_' on the pattern side, so ;;; `(closure _ int)' above is one clause rather than one per -;;; signature, and `(* _)' and `(¤ _ _)' say "any pointer" and "any +;;; signature, and `(* _)' and `[_ _]' say "any pointer" and "any ;;; array". A `_' written last takes the rest, since a type's words ;;; are spread and not nested: `(* const char)' is three elements. ;;; Nothing destructures -- a macro body is Scheme and a type is a diff --git a/tests/sex-programs/operators.sex b/tests/sex-programs/operators.sex index b708b83..03baec0 100644 --- a/tests/sex-programs/operators.sex +++ b/tests/sex-programs/operators.sex @@ -62,10 +62,10 @@ (printf "increment: %d\n" inc) ;; an array operand decays, so this is a pointer and not an array - (var xs (¤ int 4) #(1 2 3 4)) + (var xs [int 4] #(1 2 3 4)) (var p _ (+ xs 1)) (var q _ (+ 1 xs)) - (var names (¤ (* const char) 2) #("hi" "there")) + (var names [(* const char) 2] #("hi" "there")) (var np _ (+ names 1)) (printf "decayed: %d %d %s\n" (* p) (* q) (* np)) diff --git a/tests/sex-programs/type-shapes.sex b/tests/sex-programs/type-shapes.sex index 68446e6..58f6c25 100644 --- a/tests/sex-programs/type-shapes.sex +++ b/tests/sex-programs/type-shapes.sex @@ -13,7 +13,7 @@ ;;; Three questions about a written type that used to be answered in ;;; three places and disagreed: is `(a b)' a named parameter or a bare -;;; type, is the last element of a `¤' its bound or the last word of +;;; type, is the last element of a `[...]' its bound or the last word of ;;; its element type, and what is one element of an array. ;;; ;;; They are one question -- where does the type end -- so the answer @@ -25,7 +25,7 @@ (typedef small int) (typedef cstr (* const char)) -(typedef vec4 (¤ float 4)) +(typedef vec4 [float 4]) (typedef unary (fn ((small)) small)) (define CAP 2) @@ -45,40 +45,40 @@ (pub fn main () int ;; an element keeps every word of its type, tag and all - (var pts (¤ (struct point) 2) #(#((struct point) : 1 2) + (var pts [(struct point) 2] #(#((struct point) : 1 2) #((struct point) : 3 4))) - (var p _ (¤ pts 1)) + (var p _ [pts 1]) (printf "aggregate element: %d %d\n" (. p x) (. p y)) - (var names (¤ (* const char) 2) #("hi" "there")) - (var s _ (¤ names 1)) + (var names [(* const char) 2] #("hi" "there")) + (var s _ [names 1]) (printf "pointer element: %s\n" s) - (var nums (¤ unsigned int 3) #(7 8 9)) - (var u _ (¤ nums 2)) + (var nums [unsigned int 3] #(7 8 9)) + (var u _ [nums 2]) (printf "multi-word element: %u\n" u) ;; subscripting a pointer answers the same as subscripting an array - (var q (* (struct point)) (& (¤ pts 0))) - (var r _ (¤ q 1)) + (var q (* (struct point)) (& [pts 0])) + (var r _ [q 1]) (printf "through a pointer: %d\n" (+ (. r x) (* 13 (. r y)))) ;; the last word of an unsized array's type is not its bound: neither ;; a typedef name nor the target of a `*' can be one - (var tail (¤ const small) #(1 2)) - (printf "unsized of a typedef: %d %d\n" (¤ tail 0) (¤ tail 1)) + (var tail [const small] #(1 2)) + (printf "unsized of a typedef: %d %d\n" [tail 0] [tail 1]) (var one size-t 5) - (var sizes (¤ * size-t) #((& one))) - (var w _ (¤ sizes 0)) + (var sizes [* size-t] #((& one))) + (var w _ [sizes 0]) (printf "unsized of a pointer: %d\n" (cast (* w) int)) ;; ...but after a whole type, a name is: `size-t' is a typedef only C ;; knows of, and `(* const char)' a type grouped into one element - (var ws (¤ size-t CAP) #(3 4)) - (var gs (¤ (* const char) CAP) #("a" "b")) + (var ws [size-t CAP] #(3 4)) + (var gs [(* const char) CAP] #("a" "b")) (printf "named bound: %zu %zu %s\n" - (/ (sizeof ws) (sizeof (¤ ws 0))) (¤ ws 1) (¤ gs 1)) + (/ (sizeof ws) (sizeof [ws 0])) [ws 1] [gs 1]) ;; the same question in type position: `(fn ((unsigned int)) int)' ;; takes one parameter, not two @@ -89,7 +89,7 @@ (var greeting cstr "hi") (var v vec4 #(1.0 2.0 3.0 4.0)) (var op unary twice) - (printf "typedefs: %s %zu %d\n" greeting (/ (sizeof v) (sizeof (¤ v 0))) (op 1)) + (printf "typedefs: %s %zu %d\n" greeting (/ (sizeof v) (sizeof [v 0])) (op 1)) ;; `(* T)' is a type or a dereference, and only what is in scope says (printf "sizeof a pointer type: %d %d\n" diff --git a/tests/sex-programs/unnamed-params.sex b/tests/sex-programs/unnamed-params.sex index 34e1940..225b62a 100644 --- a/tests/sex-programs/unnamed-params.sex +++ b/tests/sex-programs/unnamed-params.sex @@ -25,8 +25,8 @@ (fn origin-x ((p (* (struct point)))) int (return (. (* p) x))) -(fn second-of ((xs (¤ float 4))) float - (return (¤ xs 1))) +(fn second-of ((xs [float 4])) float + (return [xs 1])) (fn say ((fmt (* const char)) ...) void (var ap va-list) @@ -43,8 +43,8 @@ (var f (fn ((* (struct point))) int) origin-x) (printf "aggregate: %d\n" (f (& p))) - (var xs (¤ float 4) #(1.5 2.5 3.5 4.5)) - (var g (fn ((¤ float 4)) float) second-of) + (var xs [float 4] #(1.5 2.5 3.5 4.5)) + (var g (fn ([float 4]) float) second-of) (printf "array: %g\n" (g xs)) (say "variadic: %d %s\n" 1 "two") diff --git a/tests/sex-programs/wildcards.sex b/tests/sex-programs/wildcards.sex index 1bf0764..8e813da 100644 --- a/tests/sex-programs/wildcards.sex +++ b/tests/sex-programs/wildcards.sex @@ -44,11 +44,11 @@ (var pp _ (& p)) (printf "pointers: %d %g\n" (. pp x) (. pp y)) - (var table (¤ int 3)) - (= (¤ table 0) 10) - (= (¤ table 1) 20) - (var first _ (¤ table 0)) - (var second _ (¤ table 1)) + (var table [int 3]) + (= [table 0] 10) + (= [table 1] 20) + (var first _ [table 0]) + (var second _ [table 1]) (printf "arrays: %d\n" (+ first second)) ;; a for opens a scope, and its initializer is declared inside it @@ -103,7 +103,7 @@ ;; 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 - (var squares (¤ _ 4) #(0 1 4 9)) - (var sparse (¤ _ 8) #(0 1)) - (printf "from elements: %d %d %d\n" (¤ squares 2) (¤ squares 3) (¤ sparse 7)) + (var squares [_ 4] #(0 1 4 9)) + (var sparse [_ 8] #(0 1)) + (printf "from elements: %d %d %d\n" [squares 2] [squares 3] [sparse 7]) (return 0)) -- 2.52.0 From 7f0b194d2b8a77960c8750fa1a63293d9893b7eb Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 17:23:42 +0300 Subject: [PATCH 12/43] make a declaring case body a block A case body shared the switch's scope, so two cases could not each declare `bits', and a label could not be followed by a declaration before C23; inference shared the scope too, and typed a later case's read of an outer name as the earlier case's local. Fixes #51. --- fmt-c-writer.scm | 13 ++++++++++--- semen.scm | 16 ++++------------ tests/codegen.scm | 25 +++++++++++++++++++++++++ tests/sex-programs/wildcards.sex | 11 ++++++++--- 4 files changed, 47 insertions(+), 18 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 4fe213b..7a1fa17 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -84,6 +84,13 @@ forms, and what remains." form `(%begin ,@(map walk-expr comments) ,form))) +;;; A case body that declares is a block, so two cases can each declare +;;; a `bits', and a declaration can follow the label before C23 +(define (walk-case-body body) + (if (any (lambda (form) (and (pair? form) (eq? 'var (car form)))) body) + (list (cons '%block-begin (walk-body body))) + (walk-body body))) + (define (walk-if-clauses clauses) "(test stmt test stmt ... [else-stmt]) -- tests stay expressions." (let loop ((cs clauses) (acc (list))) @@ -248,12 +255,12 @@ forms, and what remains." (('case . rest) (let-values (((comments slots body) (take-slots rest 1))) (with-comments comments - (cons* 'case (walk-expr (car slots)) (walk-body body))))) + (cons* 'case (walk-expr (car slots)) (walk-case-body body))))) (('case/fallthrough . rest) (let-values (((comments slots body) (take-slots rest 1))) (with-comments comments - (cons* 'case/fallthrough (walk-expr (car slots)) (walk-body body))))) - (('default . body) (cons 'default (walk-body body))) + (cons* 'case/fallthrough (walk-expr (car slots)) (walk-case-body body))))) + (('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))))) diff --git a/semen.scm b/semen.scm index e785362..e8e5c3d 100644 --- a/semen.scm +++ b/semen.scm @@ -501,9 +501,8 @@ ;;; (while (< v 0) (var v char 1) ...) ;;; (var m _ (+ v 1)) ; double, not char ;;; -;;; One frame per form, not one per arm: a `case' label opens no scope -;;; in C, and an `if' arm can only declare inside a `do', which brings -;;; its own. +;;; A `case' body gets one too, being written as a block. An `if' arm +;;; gets none: it can only declare inside a `do', which brings its own. (define (declare-name! env name type) (hash-table-set! (car (hash-table-ref env :scopes)) name type)) @@ -584,20 +583,13 @@ (cons walk-embed-result (walk-body expansion env))))) (else (case (car form) - ((do) + ((do default) (parameterize ((operand-position? #f)) (with-scope env (lambda () (walk-parts form env))))) - ((for while if switch) + ((for while if switch case case/fallthrough) (with-scope env (lambda () (walk-control form env)))) - ((case case/fallthrough) - (walk-control form env)) - - ((default) - (parameterize ((operand-position? #f)) - (walk-parts form env))) - ((lambda) (let ((name (aux-name! env make-lambda-name))) (add-aux-code! env (lift-lambda name form)) diff --git a/tests/codegen.scm b/tests/codegen.scm index f8ee091..db3ba62 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -53,6 +53,15 @@ compiles." (let ((m (error-message source))) (and m (string-contains m fragment) #t))) +(define (followed-by? source first then) + "Is FIRST in the C compiled from SOURCE, and the next thing past it, +whitespace aside, THEN?" + (let* ((c (silently (lambda () (sex->c source)))) + (at (string-contains c first))) + (and at + (let ((next (string-skip c char-whitespace? (+ at (string-length first))))) + (and next (string-prefix? then (substring c next))))))) + (define (in-fn body) (string-append "(fn f ((a int) (b int)) void " body ")")) @@ -78,6 +87,22 @@ compiles." ;; 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))'. + ;; A case body shared the switch's scope, so two cases could not + ;; declare one name, and a label could not be followed by a + ;; declaration before C23. Only a body that declares needs a block + (test-group "case bodies" + (test-assert "are blocks" + (followed-by? (in-fn "(switch a (case 1 (var x int 1) (g x)))") + "case 1:" "{")) + (test-assert "so is a default" + (followed-by? (in-fn "(switch a (default (var x int 1) (g x)))") + "default:" "{")) + (test-assert "where they declare" + (followed-by? (in-fn "(switch a (case 1 (g a)))") "case 1:" "g(a)")) + (test-assert "and one already a block is not wrapped again" + (not (followed-by? (in-fn "(switch a (case 1 (do (var x int 1) (g x))))") + "{" "{")))) + (test-group "switch scrutinee" (test-assert "member access" (emits? "(struct s ((type int))) (fn f ((e (struct s))) void (switch (. e type) (case 1 (g))))" diff --git a/tests/sex-programs/wildcards.sex b/tests/sex-programs/wildcards.sex index 8e813da..558a6d5 100644 --- a/tests/sex-programs/wildcards.sex +++ b/tests/sex-programs/wildcards.sex @@ -7,6 +7,7 @@ "loop: 0 1 2" "shadowed: 9 then 42" "still an int: 200" + "case scope: 200" "partial: 1 2.5" "joined: 43.5 84 49 1" "promoted: 200 60000 3705032704" @@ -67,14 +68,18 @@ (var wide int 200) (while false (var wide char 1) (printf "%d" wide)) (if false (do (var wide char 1) (printf "%d" wide))) - ;; a statement before the declaration: a label may not be followed by - ;; one until C23 - (switch a (case 1 (printf "") (var wide char 1) (printf "%d" wide) (break))) + (switch a (case 1 (var wide char 1) (printf "%d" wide))) ;; a copy, not a sum: an arithmetic result would be promoted to `int' ;; whatever leaked, and say nothing (var copy _ wide) (printf "still an int: %d\n" copy) + ;; each case is a block of its own: the second sees the outer `wide', + ;; not the first one's + (switch 2 + (case 1 (var wide double 1.5) (printf "%g" wide)) + (case 2 (var seen _ wide) (printf "case scope: %d\n" seen))) + ;; a wildcard inside a written type: only it is solved (var pp2 (* _) (& p)) (printf "partial: %d %g\n" (. pp2 x) (. pp2 y)) -- 2.52.0 From 9057cbfcc6ffd7bc3603a6da6e8c75959119f614 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 17:25:09 +0300 Subject: [PATCH 13/43] anchor an if's arms only where the if is a statement Every if had its arms anchored, including one inside an argument that the writer renders as ?:, so a #line landed between its parts and the C did not compile. -C output, with no directives, hid it. Fixes #54. --- fmt-c-writer.scm | 24 ++++++++++++++++-------- tests/line-directives.scm | 14 ++++++++++++-- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 7a1fa17..217ae86 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -46,10 +46,10 @@ source location. Only statement positions may be walked this way: a (append-map (lambda (s) (let ((src (form-source s))) (if src - (list (line-directive src) (walk-expr s)) - (list (walk-expr s))))) + (list (line-directive src) (walk-statement s)) + (list (walk-statement s))))) (pack-comments stmts)) - (map walk-expr (pack-comments stmts)))) + (map walk-statement (pack-comments stmts)))) (define (walk-stmt s) "A statement in a slot that holds exactly one form -- an `if' arm. @@ -59,8 +59,18 @@ as an `else if' chain, so the anchor and the statement are wrapped in surrounding c-block supplies them)." (let ((src (and (pair? s) (anchor-statements?) (form-source s)))) (if src - `(%begin ,(line-directive src) ,(walk-expr s)) - (walk-expr s)))) + `(%begin ,(line-directive src) ,(walk-statement s)) + (walk-statement s)))) + +;;; Only here is an `if' a statement, with statements for arms that can +;;; each be anchored. Anywhere else it is `?:', and a #line between its +;;; parts does not compile +(define (walk-statement s) + (match s + (('if . clauses) + (with-comments (filter comment-form? clauses) + (cons 'if (walk-if-clauses (remove comment-form? clauses))))) + (_ (walk-expr s)))) ;;; A `;' comment reads as a form, so one written inside a construct ;;; with positional slots lands in a slot and shifts everything after @@ -228,9 +238,7 @@ forms, and what remains." ;; and each is spliced or wrapped according to what the ;; corresponding fmt-c procedure accepts. (('do . stmts) (cons '%block-begin (walk-body stmts))) - (('if . clauses) - (with-comments (filter comment-form? clauses) - (cons 'if (walk-if-clauses (remove comment-form? clauses))))) + (('if . clauses) (cons 'if (map walk-expr (remove comment-form? clauses)))) (('while . rest) (let-values (((comments slots body) (take-slots rest 1))) (with-comments comments diff --git a/tests/line-directives.scm b/tests/line-directives.scm index fa11abd..7a82100 100644 --- a/tests/line-directives.scm +++ b/tests/line-directives.scm @@ -86,7 +86,10 @@ " (: done)" ; 52 " (var svar u64 (sizeof (struct pt)))" ; 53 " (var cvar int (cast mvar int))" ; 54 - " (return 122))" ; 55 + " (putchar (if (< mvar 123)" ; 55 a conditional as an + " (putchar 124)" ; 56 argument: an expression, + " 125))" ; 57 so no anchor inside it + " (return 122))" ; 58 )) (define fixture (string-intersperse fixture-lines "\n")) @@ -231,7 +234,14 @@ after that is one more. Lines before the first directive get #f." ;; Expressions that are their own statement (test-group "expressions" (maps/tokens "sizeof" "(var svar" "sizeof") - (maps/tokens "cast" "(var cvar" "(int)mvar")) + (maps/tokens "cast" "(var cvar" "(int)mvar") + ;; an `if' arm is a statement only where the `if' is one: a + ;; directive between `?' and `:' does not compile + (maps "conditional argument" "123") + (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)) + "#line"))))) ;; A location is (file . line); every directive must name the file the ;; form was read from. -- 2.52.0 From b8098f150803401549cc6554c83004d29eeab57f Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 17:26:03 +0300 Subject: [PATCH 14/43] reject a for whose header is grouped C's parens carried over, ((var i int 0) (< i 4) (++ i)), left the writer short of slots, and it died in caddr with no location; with a long enough body it would have compiled the body into the header. Fixes #42. --- fmt-c-writer.scm | 10 ++++++++++ tests/codegen.scm | 16 ++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 217ae86..021a4c2 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -94,6 +94,15 @@ forms, and what remains." form `(%begin ,@(map walk-expr comments) ,form))) +;;; (for init test step body ...). C's parens around the header, carried +;;; over, leave a call of a `var' in init's slot and the body in test's +(define (check-for-header form slots) + (cond ((and (pair? slots) (pair? (car slots)) (pair? (caar slots)) + (eq? 'var (car (caar slots)))) + (sex-error form "a for header is not grouped: write (for init test step body ...)")) + ((< (length slots) 3) + (sex-error form "malformed for: write (for init test step body ...)")))) + ;;; A case body that declares is a block, so two cases can each declare ;;; a `bits', and a declaration can follow the label before C23 (define (walk-case-body body) @@ -245,6 +254,7 @@ forms, and what remains." (cons* 'while (walk-expr (car slots)) (walk-body body))))) (('for . rest) (let-values (((comments slots body) (take-slots rest 3))) + (check-for-header form slots) (with-comments comments (cons* 'for (walk-expr (car slots)) (walk-expr (cadr slots)) (walk-expr (caddr slots)) diff --git a/tests/codegen.scm b/tests/codegen.scm index db3ba62..b4dc339 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -309,6 +309,22 @@ whitespace aside, THEN?" ;; A nested pointer chain used to silently lose a level: ;; (var p (* (* char))) emitted `char *p' + ;; A grouped header, C's parens carried over, died in the writer with + ;; `(caddr) bad argument type' and no location + (test-group "malformed for" + (test-assert "a grouped header is named" + (reports? (in-fn "(for ((var i int 0) (< i 4) (++ i)) (g i))") + "header is not grouped")) + (test-assert "even when the body fills the slots it left" + (reports? (in-fn "(for ((var i int 0) (< i 4) (++ i)) (g i) (g i) (g i))") + "header is not grouped")) + (test-assert "a short one gets the shape" + (reports? (in-fn "(for (var i int 0) (< i 4))") + "(for init test step body ...)")) + (test-assert "and both name the line" + (reports? "(fn f () void\n (for ((var i int 0) (< i 4) (++ i)) (g i)))" + "codegen.sex:2:"))) + (test-group "malformed types are rejected" (test-assert "nested pointer chain" (reports? (in-fn "(var p (* (* char)))") "pointer chains are written flat")) -- 2.52.0 From a5520bf4b98ed4376eba114e26dfb04b7e9b42b3 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 17:27:02 +0300 Subject: [PATCH 15/43] walk what an initializer holds The body walk passed a #(...) by as an atom, so nothing inside one was typed, dispatched or lifted: (. self p) read as self.p with self a pointer, where the same path outside the literal was right. Fixes #45. --- semen.scm | 13 ++++++++++++- tests/codegen.scm | 12 ++++++++++++ tests/sex-programs/compound-literals.sex | 9 ++++++++- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/semen.scm b/semen.scm index e8e5c3d..35f01b1 100644 --- a/semen.scm +++ b/semen.scm @@ -571,7 +571,7 @@ (define (walk-statement form env) (cond - ((vector? form) (walk-literal form env)) + ((vector? form) (walk-initializer form env)) ((not (list? form)) form) ((null? form) form) ;; expanded here rather than before the walk, so the macro body can @@ -775,6 +775,17 @@ (append (drop-right parts (length elements)) (map (lambda (element) (walk-operand element env)) elements))))) +;;; #(struct point : (. p x) 2) -- the values are expressions, and the +;;; words before a `:' a type that is left as written +(define (walk-initializer form env) + (let-values (((prefix rest) (break (lambda (e) (eq? e ':)) + (vector->list form)))) + (let ((walk (lambda (es) (map (lambda (e) (walk-statement e env)) es)))) + (list->vector + (if (null? rest) + (walk prefix) + (append prefix (list ':) (walk (cdr rest)))))))) + ;;; Is the operand of `sizeof' a type? `(* x)' and `(¤ x i)' are ;;; expressions when x is: a name in scope, or a list that is not ;;; itself a type. A name nothing declared is one only C knows of, and diff --git a/tests/codegen.scm b/tests/codegen.scm index b4dc339..d9eeffd 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -798,6 +798,18 @@ whitespace aside, THEN?" ;; `.' is C's `.' or its `->' depending on what is being read from, ;; so a path reads the same however the thing it starts from is held + ;; ...and inside a literal, which the walk used to pass by + (test-group "member access in a literal" + (test-assert "compound" + (emits? (in-line "(var q (struct point) #(struct point : (. pp x) (. pp y)))") + "(struct point){pp->x, pp->y}")) + (test-assert "brace initializer" + (emits? (in-line "(var q (struct point) #((. pp x) (. pp y)))") + "{pp->x, pp->y}")) + (test-assert "designated" + (emits? (in-line "(var q (struct point) #(.y (. pp x)))") + "{.y = pp->x}"))) + (test-group "member access" (test-assert "a value reads with a dot" (emits? (in-line "(= (. p x) 1)") "p.x = 1")) diff --git a/tests/sex-programs/compound-literals.sex b/tests/sex-programs/compound-literals.sex index fbe5411..3aad6c5 100644 --- a/tests/sex-programs/compound-literals.sex +++ b/tests/sex-programs/compound-literals.sex @@ -5,7 +5,8 @@ "through a pointer 9" "array 10 20 30" "argument 6" - "mixed 1 5") + "mixed 1 5" + "read through a pointer 1 5") (return 0) ;;; `:' inside #(...) ends a type and makes the rest a C99 compound @@ -46,4 +47,10 @@ (var m (struct point) #(struct point : 1 .y 5)) (printf "mixed %d %d\n" (. m x) (. m y)) + ;; what a literal holds is walked like any expression, so a path in + ;; it reads through a pointer as it does outside one + (var pm (* (struct point)) (& m)) + (var c (struct point) #(struct point : (. pm x) (. pm y))) + (printf "read through a pointer %d %d\n" (. c x) (. c y)) + (return 0)) -- 2.52.0 From b019da3fb3dd8d49ca66dbc633c1d9f355e74177 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 17:28:20 +0300 Subject: [PATCH 16/43] name what a member path could not type Past a typed base, it is a field of a struct only C knows that has no type, and the warning named the base anyway: `font' for what was (. font handle), with font declared on the line before. Fixes #41. --- semen.scm | 10 ++++++++-- tests/codegen.scm | 8 ++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/semen.scm b/semen.scm index 35f01b1..1eb96cd 100644 --- a/semen.scm +++ b/semen.scm @@ -1113,11 +1113,14 @@ ;;; (. l a x) l : (struct line), l.a : (* struct point) -> l.a->x ;;; ;;; A type we cannot work out is read as a value, which is what the -;;; path would have meant before any of this. +;;; path would have meant before any of this. The warning names what +;;; could not be typed: the base, or the path up to a field of a struct +;;; only C knows -- (. font handle), not font. (define (walk-member-path form env) (let ((base (second form))) (let step ((expr (walk-operand base env)) (type (expression-type base env)) + (read (list)) ; the fields walked, reversed (fields (cddr form)) (told? #f)) (if (null? fields) @@ -1125,9 +1128,12 @@ (let ((target (pointer-target type))) (unless (or type told?) (sex-warning form "cannot type this; `.' reads it as a value" - base)) + (if (null? read) + base + `(|.| ,base ,@(reverse read))))) (step (list (if target '%-> 'dot-access) expr (car fields)) (field-type (or target type) (car fields)) + (cons (car fields) read) (cdr fields) (or told? (not type)))))))) diff --git a/tests/codegen.scm b/tests/codegen.scm index d9eeffd..d2dcf53 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -833,6 +833,14 @@ whitespace aside, THEN?" (emits? (in-line "(= (. (guess) x) 1)") "guess().x = 1")) (test-assert "and said so" (warns? (in-line "(= (. (guess) x) 1)") "cannot type this")) + ;; Past a typed base it is a field that cannot be typed -- one of a + ;; struct only C knows -- and the warning named the base regardless + (test-assert "naming the path read so far" + (warns? (in-fn "(var t (* struct tm) 0) (= (. t a b) 1)") + "as a value (. t a)\n")) + (test-assert "which one step through it does not need" + (not (warns? (in-fn "(var t (* struct tm) 0) (= (. t a) 1)") + "cannot type"))) ;; the arrow is `%->' and nothing else writes one, so a bare `->' ;; is an ordinary head -- a threading macro that nobody imported, ;; and a call like any other unknown -- 2.52.0 From 7abb125932227ea8616b5485b5cc739ff31b9903 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 17:34:02 +0300 Subject: [PATCH 17/43] take -o - as stdout getopt-long reads a lone `-' as an option, so -o - died there asking for a value, and --output=- got through only to create a file named `-'. Fixes #43. --- sexc.scm | 18 +++++++++++++++--- tests/args.scm | 14 +++++++++++++- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/sexc.scm b/sexc.scm index ac612a0..668c092 100644 --- a/sexc.scm +++ b/sexc.scm @@ -59,7 +59,8 @@ (value #f) (single-char #\m)) (output ,(fmt #f "Write output to file. Default file name is a.out." nl - (pad padding) "If -E or -m options are provided, defaults to stdout") + (pad padding) "If -C or -m options are provided, defaults to stdout;" nl + (pad padding) "`-' is stdout too") (required #f) (value #t) (single-char #\o)) @@ -100,6 +101,17 @@ (list) (cdr tail)))) +;;; getopt-long reads a lone `-' as an option, so `-o -' died there as +;;; one missing its value. `--output=-' is the spelling it takes +(define (spell-stdout-output argv) + (let loop ((as argv) (acc (list))) + (cond ((null? as) (reverse acc)) + ((and (member (car as) '("-o" "--output")) + (pair? (cdr as)) + (string=? (cadr as) "-")) + (loop (cddr as) (cons "--output=-" acc))) + (else (loop (cdr as) (cons (car as) acc)))))) + (define (get-rest-args args) (cdr (assoc '@ args))) @@ -126,7 +138,7 @@ (car rest-args)))) (define (write-to-file-or-stdout output what) - (if (eq? output 'default) + (if (or (eq? output 'default) (equal? output "-")) (what) (with-output-to-file output (fn (what))))) @@ -196,7 +208,7 @@ status, which is ours to pass on." (let* ((argv (command-line-arguments)) (raw-args (args-before-separator argv)) (cc-args (args-after-separator argv)) - (args (getopt-long raw-args + (args (getopt-long (spell-stdout-output raw-args) opts-grammar)) (output (get-arg args 'output 'default)) (help (help-arg? args)) diff --git a/tests/args.scm b/tests/args.scm index c4ced0f..b2fc46f 100644 --- a/tests/args.scm +++ b/tests/args.scm @@ -52,4 +52,16 @@ (test "an empty command line is handled" '() - (args-before-separator '()))) + (args-before-separator '())) + + ;; getopt-long reads a lone `-' as an option and refused `-o -', so + ;; it is handed the one spelling it takes a dash in + (test "-o - reaches getopt-long as a value" + '("x.sex" "--output=-" "-C") + (spell-stdout-output '("x.sex" "-o" "-" "-C"))) + (test "and so does --output -" + '("--output=-") + (spell-stdout-output '("--output" "-"))) + (test "any other output is left alone" + '("-o" "out" "-") + (spell-stdout-output '("-o" "out" "-")))) -- 2.52.0 From 9fd40da8b13b7039b2bbc33a88c8778e9bb06d46 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 17:35:05 +0300 Subject: [PATCH 18/43] resolve a relative SEX_MODULE_PATH entry from the working directory make-absolute-pathname with no directory of its own put `src' under the root, so SEX_MODULE_PATH=src searched /src/. Fixes #48. --- sex-modules.scm | 3 +-- tests/Makefile | 2 +- tests/module-path.scm | 22 ++++++++++++++++++++++ tests/run.scm | 1 + 4 files changed, 25 insertions(+), 3 deletions(-) create mode 100644 tests/module-path.scm diff --git a/sex-modules.scm b/sex-modules.scm index c3f1c61..a613cb3 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -159,6 +159,5 @@ (get-env-var "SEX_MODULE_PATH"))) (when sex-module-path-env-var (set! +persistent-module-paths+ - (map (lambda (p) - (make-absolute-pathname p #f #f)) + (map to-absolute-pathname (string-split sex-module-path-env-var ":")))))) diff --git a/tests/Makefile b/tests/Makefile index 1e87b3c..9a4b6c6 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -6,7 +6,7 @@ MODULE_FLAGS = -emit-all-import-libraries -module-registration -c MODULES = utils types infer sex-macros reader sex-modules semen sex-fmt-c fmt-c-writer sexc SEX_OBJ = $(MODULES:%=%.o) -TESTS = basic semen reader fmt-c-writer utils line-directives codegen encapsulation args types infer +TESTS = basic semen reader fmt-c-writer utils line-directives codegen encapsulation args module-path types infer TEST_SRCS = $(TESTS:%=%.scm) sex-tests: run.scm $(TEST_SRCS) $(SEX_OBJ) diff --git a/tests/module-path.scm b/tests/module-path.scm new file mode 100644 index 0000000..fbce788 --- /dev/null +++ b/tests/module-path.scm @@ -0,0 +1,22 @@ +;;; Where imports are looked for. SEX_MODULE_PATH is read once, at the +;;; start, from the directory sexc was started in. + +(import (chicken pathname) + (chicken process-context) + sex-modules) + +(test-group "module path" + ;; make-absolute-pathname took `src' for a directory under the root, + ;; and an import searched /src/ + (set-environment-variable! "SEX_MODULE_PATH" "src:/abs/lib") + (load-persistent-module-paths) + (test "a relative entry is from the working directory" + (make-absolute-pathname (current-directory) "src") + (second (get-module-paths))) + (test "an absolute one is as written" + "/abs/lib" + (third (get-module-paths))) + + (set-environment-variable! "SEX_MODULE_PATH" "") + (load-persistent-module-paths) + (unset-environment-variable! "SEX_MODULE_PATH")) diff --git a/tests/run.scm b/tests/run.scm index d0cc9ca..8464382 100644 --- a/tests/run.scm +++ b/tests/run.scm @@ -10,6 +10,7 @@ (include "codegen.scm") (include "encapsulation.scm") (include "args.scm") +(include "module-path.scm") (include "types.scm") (include "infer.scm") -- 2.52.0 From 19090414b70662e275165ae040c6cb3cf0b8a86b Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 17:37:03 +0300 Subject: [PATCH 19/43] let a method call one written below it Each method was registered just before its own body was walked, so an earlier one could not find it. All are registered first now, and one called above its definition is declared ahead of the bodies, which C needs as well. Fixes #44. --- semen.scm | 46 +++++++++++++++++++++++++++++++++----- tests/encapsulation.scm | 17 +++++++++++++- tests/sex-programs/ops.sex | 8 ++++++- 3 files changed, 63 insertions(+), 8 deletions(-) diff --git a/semen.scm b/semen.scm index 1eb96cd..6beb78c 100644 --- a/semen.scm +++ b/semen.scm @@ -415,17 +415,30 @@ ;;; is (pub fn vec2/length ...) plus a registry entry, so that ;;; (. v length) can find it later. The block itself never reaches the ;;; writer; `pub' inside it means what it means outside. +;;; +;;; Every method is registered before any body is walked, so one may +;;; call another written below it; that one is then declared ahead of +;;; the first body, since C wants it declared before the call. (define (process-ops form acc) (let ((type (and (pair? (cdr form)) (cadr form)))) (unless (symbol? type) (sex-error form "ops needs a type name" form)) - (fold (lambda (method acc) (process-op type method acc)) - acc - (cddr form)))) + (let* ((methods (map (lambda (m) (register-op type m)) (cddr form))) + (fns (remove comment-form? methods)) + (bodies (map (lambda (m) + (if (comment-form? m) (list m) (process-fn m (list)))) + methods)) + (early (filter (lambda (m) + (called-before? (sex-fn-name m) m methods bodies)) + fns))) + (append (append-map identity (reverse bodies)) + (fold (lambda (m acc) (process-fn (fn-prototype m) acc)) acc early))))) -(define (process-op type form acc) +;;; The method's fn form, renamed to vec2/length, once it is registered +;;; under `length'; a comment is passed along +(define (register-op type form) (if (comment-form? form) - (cons form acc) + form (let ((core (and (pair? form) (fn-core form)))) (unless (and (pair? core) (eq? (car core) 'fn) (pair? (cdr core)) (symbol? (second core))) @@ -435,7 +448,28 @@ (sex-error form "method is already defined on" type name)) (let ((qualified (qualify-op type name))) (add-method! type name qualified) - (process-fn (rename-fn form qualified) acc)))))) + ;; its signature too, which a call's receiver is fitted to + (process-fn (fn-prototype (rename-fn form qualified)) (list)) + (rename-fn form qualified)))))) + +;;; Does a body written above METHOD call it? +(define (called-before? name method methods bodies) + (let loop ((ms methods) (bs bodies)) + (and (not (eq? (car ms) method)) + (or (names? (car bs) name) + (loop (cdr ms) (cdr bs)))))) + +;;; NAME anywhere in FORM, a literal's contents included +(define (names? form name) + (cond ((eq? form name) #t) + ((pair? form) (or (names? (car form) name) (names? (cdr form) name))) + ((vector? form) (names? (vector->list form) name)) + (else #f))) + +;;; (pub fn name args ret ...) -> (pub fn name args ret) +(define (fn-prototype form) + (let ((header (strip-fn-header-comments form))) + (copy-form-source! form (take header (fn-header-length header))))) (define (rename-fn form name) (if (memq (first form) '(pub extern)) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 8df2b09..1505153 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -19,6 +19,13 @@ "(fn f () void (var v vec2 #(vec2 : 1.0 2.0)) (var p (* vec2) (& v)) " (apply string-append body) ")")) +(define forward-src + (string-append + "(record pb ((n int)))" + "(ops pb" + " (fn twice ((self (* pb))) int (return (* 2 (.len self))))" + " (pub fn len ((self (* pb))) int (return (. self n))))")) + (define (sum-src . body) (string-append "(sum shape ((circle ((r float))) (rect ((w float) (h float))) (empty ())))" @@ -79,7 +86,15 @@ " (fn g ((s v)) int (return 2)))") "method is already defined on")) (test-assert "pub goes on the methods, not the block" - (reports? "(record v ((x int)))(pub ops v)" "pub belongs on the methods"))) + (reports? "(record v ((x int)))(pub ops v)" "pub belongs on the methods")) + ;; Every method is known before any body is walked, and C is told of + ;; one before a body above it calls it -- and only then + (test-assert "a method can call one written below it" + (emits? forward-src "return 2 * pbːlen(self)")) + (test-assert "which is declared ahead of the call" + (emits? forward-src "int pbːlen (pb * self);")) + (test-assert "and nothing else is" + (not (emits? (ops-src "") "vec2ːsum_of (vec2 self);")))) ;; The method sits in the head, so the shape of a form can be read ;; without knowing the receiver's type. diff --git a/tests/sex-programs/ops.sex b/tests/sex-programs/ops.sex index 12bb812..2a83491 100644 --- a/tests/sex-programs/ops.sex +++ b/tests/sex-programs/ops.sex @@ -2,7 +2,8 @@ (input) (output "5.0 5.0 10.0 14.0 14.0 6.0" "struct receiver: 14" - "private: 8.0") + "private: 8.0" + "forward call: 28.0") (return 0) ;;; An ops block is mangled fns plus a registry entry, so a method is @@ -22,6 +23,10 @@ (record vec2 ((x float) (y float))) (ops vec2 + ;; a method may call one written below it + (fn twice-sum ((self vec2)) float + (return (* 2.0 (.sum-of self)))) + (pub fn length ((self (* const vec2))) float "Pointer self, so (.length v) has to take the address." (return (sqrtf (+ (* (. self x) (. self x)) @@ -55,4 +60,5 @@ (var u vec2 #(vec2 : 8.0 0.0)) (printf "private: %.1f\n" (vec2/sum-of u)) + (printf "forward call: %.1f\n" (.twice-sum v)) (return 0)) -- 2.52.0 From b998d298dd847f868e1718a4a358dd5ad90b68b3 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 17:43:09 +0300 Subject: [PATCH 20/43] check what a module's importers can see of its types An importer is given the pub forms and nothing else, so a pub form naming a private type, or one from an import without pub, compiled in its module and failed in every importer with `unknown type name'. The pub forms are checked as the module itself is compiled. A record, struct, union or sum behind a pointer needs only declaring, so its bodyless declaration goes out ahead of them -- the opaque handle that (pub record T) already gave by hand. Held by value it needs its body, and a typedef or an enum has no declaration short of its definition: those are errors at the pub form, saying what would do instead. A name Sex has no declaration for is left to C. An importer may now be handed a declaration after the definition it declares, so a bodyless aggregate no longer replaces known fields. Fixes #57, #58. --- semen.scm | 4 +- sex-modules.module.scm | 1 + sex-modules.scm | 196 +++++++++++++++++++++++++++++++++++- sexc.scm | 22 ++-- tests/encapsulation.scm | 67 +++++++++++- tests/modules/Makefile | 11 +- tests/modules/greet-app.sex | 5 + tests/modules/greet.sex | 26 +++++ tests/modules/ledger.sex | 8 ++ 9 files changed, 323 insertions(+), 17 deletions(-) create mode 100644 tests/modules/ledger.sex diff --git a/semen.scm b/semen.scm index 6beb78c..87e2e35 100644 --- a/semen.scm +++ b/semen.scm @@ -1912,7 +1912,9 @@ (name (and (pair? (cdr f)) (symbol? (cadr f)) (cadr f)))) ;; An anonymous aggregate has a field list where the name would be, ;; and nothing can refer to it by name anyway - (when name + ;; ...and a bodyless one adds nothing to what is known: an importer + ;; may be handed a declaration after the definition it declares + (when (and name (not (and (null? (cddr f)) (get-tag-info name)))) (case (car f) ((struct) (add-struct name form)) ((union) (add-union name form)) diff --git a/sex-modules.module.scm b/sex-modules.module.scm index 7b56569..eec7ab7 100644 --- a/sex-modules.module.scm +++ b/sex-modules.module.scm @@ -1,5 +1,6 @@ (module sex-modules (get-modules-public-forms load-persistent-module-paths + check-public-interface read-public-interface) "sex-modules.scm") diff --git a/sex-modules.scm b/sex-modules.scm index a613cb3..52391b4 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -82,13 +82,203 @@ ;; pub fns are reduced to prototypes, other pub forms are just pasted. ;; Declaration order is kept: a module that declares a type and then a ;; pub fn taking it has to paste them that way round, or the prototype - ;; names a type C has not seen. + ;; 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-from-file module-path))) + (append (check-public-interface raw-forms) + (interface-forms raw-forms)))) + +(define (interface-forms raw-forms) + (reverse (fold process-public-interface-form (list) raw-forms))) + +;;; What importers can see of a module's types +;;; +;;; They are given the pub forms and nothing else, so a pub form that +;;; names a type not among them compiled here and failed there: +;;; (pub record shape ((cells (* cell)))) with `cell' private told the +;;; importer `unknown type name cell'. A record behind a pointer needs +;;; only declaring, and its declaration goes out with the pub forms. +;;; Held by value it needs its body; and a typedef or an enum has no +;;; declaration short of its definition. Those are errors here, where +;;; they were written. A name Sex has no declaration for is one only C +;;; knows, and is left to C. + +;;; The bodyless declarations FORMS' importers need, in the order the +;;; pub forms ask for them. An error when a pub form needs more than a +;;; declaration of a type they cannot see. +(define (check-public-interface forms) + (let ((visible (visible-types forms)) + (hidden (hidden-types forms))) (reverse (fold - process-public-interface-form + (lambda (form acc) + (fold (lambda (use acc) (check-type-use form use visible hidden acc)) + acc + (append-map (lambda (type) (type-uses type #f)) + (interface-types form)))) (list) - raw-forms)))) + forms)))) + +;;; USE is (name . behind-a-pointer?) +(define (check-type-use form use visible hidden acc) + (let* ((name (car use)) + (seen (assq name visible)) + (kept (assq name hidden))) + (cond + ((and seen (third seen)) acc) ; pub with its body + ((and seen (cdr use)) acc) ; a pub handle, held by one + (seen + (sex-error form "only a handle of this type is pub, so hold it through a pointer" + name)) + ((not kept) acc) + ((not (memq (second kept) '(record struct union sum))) + (sex-error form (string-append "importers cannot see this " + (symbol->string (second kept)) + ", and C declares one only by defining it; " + (if (fourth kept) + "import its module with pub" + "make it pub")) + name)) + ((not (cdr use)) + (sex-error form (string-append "importers cannot see this type, held by value; " + (if (fourth kept) + "import its module with pub" + "make it pub") + ", or hold it through a pointer") + name)) + ((any (lambda (f) (eq? name (cadr f))) acc) acc) + (else + (cons (copy-form-source! + form + (list (if (memq (second kept) '(record sum)) 'record (second kept)) + name)) + acc))))) + +;;; The type forms a pub form shows its importers +;;; +;;; (pub fn f ((c (* cell)) (n int)) shape) -> ((* cell) int shape) +(define (interface-types form) + (match form + (('pub 'fn . _) + (match (strip-header-comments form 5) + (('pub 'fn name (args ...) ret . _) (signature-types args ret)) + (_ (list)))) + (('pub 'var . _) + (match (strip-header-comments form 4) + (('pub 'var name type . _) (list type)) + (_ (list)))) + (('pub 'typedef name target) (list target)) + (('pub (or 'record 'struct 'union) name . rest) + (field-types (find list? (remove comment-form? rest)))) + (('pub 'sum name (variants ...)) + (append-map (lambda (v) + (if (and (pair? v) (pair? (cdr v))) (field-types (second v)) (list))) + (remove comment-form? variants))) + (('ops type . methods) + (append-map interface-types + (filter (lambda (m) (and (pair? m) (eq? (car m) 'pub))) methods))) + (('pub 'realize spec . methods) + (append-map (lambda (m) (interface-types (cons 'pub m))) + (remove comment-form? methods))) + (_ (list)))) + +(define (field-types fields) + (if (list? fields) (map second (normalize-fields fields)) (list))) + +(define (signature-types args ret) + (cons ret (map arg-type (remove comment-form? args)))) + +;;; (f1 float) -> float, (n unsigned int) -> (unsigned int), (int) -> (int) +(define (arg-type arg) + (cond ((not (named-arg? arg)) arg) + ((null? (cddr arg)) (second arg)) + (else (cdr arg)))) + +;;; Each name TYPE mentions, and whether it is behind a pointer: +;;; +;;; (* const cell) -> ((const . #t) (cell . #t)) +;;; [cell 4] -> ((cell . #f)) +;;; (fn ((cell)) int) -> ((cell . #t) (int . #t)) ; declaring is enough +(define (type-uses type behind?) + (cond + ((symbol? type) (list (cons type behind?))) + ((not (pair? type)) (list)) + (else + (case (car type) + ((*) (append-map (lambda (t) (type-uses t #t)) (cdr type))) + ((¤) (let ((element (array-element-type type))) + (if element (type-uses element behind?) (list)))) + ((fn closure) + (if (and (pair? (cdr type)) (list? (second type))) + (append-map (lambda (t) (type-uses t #t)) + (signature-types (second type) (last type))) + (list))) + ((struct union enum) + (if (and (pair? (cdr type)) (symbol? (second type))) + (list (cons (second type) behind?)) + (list))) + (else (append-map (lambda (t) (type-uses t behind?)) type)))))) + +;;; The types FORMS declare, as (name kind body?): +;;; +;;; (pub record tally) -> (tally record #f) +;;; (sum colour ((none ()))) -> (colour sum #t) +(define (declared-types forms) + (filter-map + (lambda (form) + (and (pair? form) + (let ((core (if (pub-form? form) (cdr form) form))) + (and (pair? core) (pair? (cdr core)) + (memq (car core) '(record struct union enum sum typedef)) + (symbol? (second core)) + (list (second core) + (car core) + (or (eq? (car core) 'typedef) + (any list? (remove comment-form? (cddr core))))))))) + forms)) + +(define (pub-form? form) (and (pair? form) (eq? (car form) 'pub))) + +;;; Pub here or through a pub import. A type declared pub both bodyless +;;; and whole is whole +(define (visible-types forms) + (let ((all (append (declared-types (filter pub-form? forms)) + (append-map exported-types (imported-modules forms #t))))) + (map (lambda (entry) + (list (first entry) (second entry) + (any third (filter (lambda (e) (eq? (first e) (first entry))) all)))) + all))) + +;;; Declared here without pub, or brought by an import without it, as +;;; (name kind body? imported?) +(define (hidden-types forms) + (append (map (lambda (entry) (append entry (list #f))) + (declared-types (remove pub-form? forms))) + (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 +(define (imported-modules forms pub?) + (append-map (lambda (form) + (match form + (('pub 'import . modules) (if pub? modules (list))) + (('import . modules) (if pub? (list) modules)) + (_ (list)))) + forms)) + +;;; 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 read ((modules (list module)) (seen (list)) (acc (list))) + (if (null? modules) + acc + (let ((path (locate-module (symbol->string (car modules))))) + (if (or (not path) (member path seen)) + (read (cdr modules) seen acc) + (let ((forms (interface-forms (read-from-file path)))) + (read (append (cdr modules) (imported-modules forms #f)) + (cons path seen) + (append acc (declared-types forms))))))))) (define (public-fn-interface raw-form) ;; (pub fn name args ret . body) -> prototype, keeping a docstring so diff --git a/sexc.scm b/sexc.scm index 668c092..e1ffb05 100644 --- a/sexc.scm +++ b/sexc.scm @@ -180,11 +180,15 @@ status, which is ours to pass on." (delete-file* c-file) (if normal-exit? status 1))))))) -(define (semantic-process-forms raw-forms input-source) - (if (eq? input-source 'stdin) - (semen-process raw-forms) - (with-directory input-source - (semen-process raw-forms)))) +;;; 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) + (let ((process (lambda () + (check-public-interface unit-forms) + (semen-process (append prelude unit-forms))))) + (if (eq? input-source 'stdin) + (process) + (with-directory input-source (process))))) (define prelude (append @@ -228,6 +232,10 @@ status, which is ours to pass on." (platform-features)) (cli-features args))) + ;; before the interface too, which asks the modules it imports + ;; what types they export + (load-persistent-module-paths) + (when (get-arg args 'public-interface #f) (assert (not (eq? input 'stdin)) "Error: --public-interface requires file argument") @@ -237,7 +245,6 @@ status, which is ours to pass on." (map pp (reverse (read-public-interface input))))) (return #f)) - (load-persistent-module-paths) ;; The file name in a #line directive now comes from the form's ;; own recorded location, so imported modules report themselves @@ -247,8 +254,7 @@ status, which is ours to pass on." (not (get-arg args 'line-directives #f))) (sex-line-directives 'none)) - (let* ((raw-forms (append prelude (read-raw-forms input))) - (sex-forms (semantic-process-forms raw-forms input))) + (let ((sex-forms (semantic-process-forms (read-raw-forms input) input))) (if (or (get-arg args 'macro-expand #f) (get-arg args 'emit-c #f)) ;; Emit processed and macro-expanded sex code, or emit C code diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 1505153..060ecef 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -8,6 +8,22 @@ ;;; `sex->c', `emits?', `reports?' and `in-fn' come from codegen.scm, ;;; which run.scm includes first. +(import sex-modules) + +(define (interface-of source) + "The declarations SOURCE, compiled as a module, hands its importers +ahead of its pub forms." + (check-public-interface + (with-input-from-string source + (lambda () + (parameterize ((current-source-file "codegen.sex")) + (parse-all (current-input-port))))))) + +(define (interface-reports? source fragment) + (let ((m (handle-exceptions e ((condition-property-accessor 'exn 'message) e) + (begin (interface-of source) #f)))) + (and m (string-contains m fragment) #t))) + (define (ops-src . body) (string-append "(record vec2 ((x float) (y float)))" @@ -488,4 +504,53 @@ "switch (t.tag)")) (test-assert "and a scrutinee that is not a sum" (reports? "(fn f () void (var n int 1) (match n ((a ()) (= n 2))))" - "match wants a sum")))) + "match wants a sum"))) + + ;; An importer is given the pub forms and nothing else, so a type one + ;; of them names has to be among them, or C is told no more of it + ;; than a declaration can say + (test-group "what importers can see" + (test "a private record behind a pointer is declared for them" + '((record cell)) + (interface-of "(record cell ((v int))) (pub record shape ((c (* cell))))")) + (test "once" + '((record cell)) + (interface-of "(record cell ((v int))) (pub fn f ((a (* cell)) (b (* cell))) void)")) + (test "a struct as a struct" + '((struct cell)) + (interface-of "(struct cell ((v int))) (pub fn f ((a (* struct cell))) void)")) + (test "a pub one needs nothing" + '() + (interface-of "(pub record cell ((v int))) (pub record shape ((c cell)))")) + (test "nor one only C knows" + '() + (interface-of "(pub fn f ((p (* FILE)) (n size-t)) void)")) + (test "nor a private fn's" + '() + (interface-of "(record cell ((v int))) (fn f ((c cell)) void)")) + (test-assert "held by value it is an error" + (interface-reports? "(record cell ((v int))) (pub record shape ((c cell)))" + "held by value")) + (test-assert "naming the line" + (interface-reports? "(record cell ((v int)))\n(pub record shape ((c cell)))" + "codegen.sex:2:")) + (test-assert "in an array too" + (interface-reports? "(record cell ((v int))) (pub record shape ((cs [cell 4])))" + "held by value")) + (test-assert "returned" + (interface-reports? "(record cell ((v int))) (pub fn f () cell)" "held by value")) + (test-assert "or taken by a pub method" + (interface-reports? "(record cell ((v int))) (ops cell (pub fn get ((self cell)) int))" + "held by value")) + (test-assert "a typedef has no declaration to give, pointer or not" + (interface-reports? "(typedef small int) (pub fn f ((p (* small))) void)" + "this typedef, and C declares one only by defining it")) + (test-assert "nor has an enum" + (interface-reports? "(enum mood (up down)) (pub var m (* enum mood))" + "this enum, and C declares")) + (test-assert "a pub handle is held through a pointer" + (interface-reports? "(pub record h) (record h ((n int))) (pub fn f ((x h)) void)" + "only a handle")) + (test "which is all it takes" + '() + (interface-of "(pub record h) (record h ((n int))) (pub fn f ((x (* h))) void)")))) diff --git a/tests/modules/Makefile b/tests/modules/Makefile index 034cd95..e76f6e9 100644 --- a/tests/modules/Makefile +++ b/tests/modules/Makefile @@ -17,15 +17,18 @@ # alone, its fields left behind and its methods still found. # # The public forms carry comments in their headers, which the reduction -# to a prototype and to an extern both have to look past. +# to a prototype and to an extern both have to look past. And a type the +# app cannot see -- private to greet, or from a module greet imports +# without `pub' -- crosses behind a pointer, declared and no more. SEXC ?= ../../sexc -EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7\nvec2(3 4)\ntally 2\ncolour 123 +EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7\nvec2(3 4)\ntally 2\nboard 42\nledger 2\ncolour 123 check: + @$(SEXC) ledger.sex -c -o ledger.o @$(SEXC) greet.sex -c -o greet.o - @$(SEXC) greet-app.sex -o greet-app -- greet.o + @$(SEXC) greet-app.sex -o greet-app -- greet.o ledger.o @if [ "`./greet-app`" = "`printf '$(EXPECTED)\n'`" ]; then \ echo "modules ok"; \ else \ @@ -34,6 +37,6 @@ check: @$(MAKE) --no-print-directory clean clean: - @rm -f greet.o greet-app + @rm -f greet.o ledger.o greet-app .PHONY: check clean diff --git a/tests/modules/greet-app.sex b/tests/modules/greet-app.sex index 7675207..0836313 100644 --- a/tests/modules/greet-app.sex +++ b/tests/modules/greet-app.sex @@ -47,6 +47,11 @@ (printf "tally %d\n" (.count t)) (.drop t) + ;; neither cell nor ledger is visible here, only declared + (var b board (make-board)) + (printf "board %d\n" (board-total (& b))) + (printf "ledger %d\n" (ledger-total (greet-ledger))) + (var c colour (colour/rgb 1 2 3)) (match c ((rgb (r g b)) (printf "colour %d%d%d\n" r g b)) diff --git a/tests/modules/greet.sex b/tests/modules/greet.sex index 3da58b3..575636e 100644 --- a/tests/modules/greet.sex +++ b/tests/modules/greet.sex @@ -8,6 +8,8 @@ (pub include stdio.h) (include stdlib.h) +(import ledger) + (pub var greet-count ;; a comment in the header of a public form is ;; not part of it: what the importer is given has ;; to be `extern int greet-count', not a form @@ -30,12 +32,36 @@ (lambda (name field-type) `(printf "%s " ,(symbol->string name)))))) +(var greetings ledger #(ledger : 0)) + (pub fn greet ;; ...and here the prototype would lose its return type ((name (* const char))) void "Print a greeting for NAME." (++ greet-count) + (ledger-add (& greetings) 1) (printf "hello, %s\n" name)) +;;; Types the importer cannot see, crossing behind a pointer. `cell' is +;;; private and `ledger' was imported without `pub', and the importer +;;; is handed a declaration of each and nothing else. +(record cell ((v int))) + +(var the-cell cell #(cell : 40)) + +(pub record board ((first (* cell)) (size int))) + +(pub fn make-board () board + (return #(board : (& the-cell) 2))) + +(pub fn board-total ((b (* const board))) int + (return (+ (. b first v) (. b size)))) + +(pub fn greet-ledger () (* ledger) + (return (& greetings))) + +(pub fn ledger-total ((l (* const ledger))) int + (return (. l total))) + ;;; A closure type crossing the boundary. Both units generate the ;;; struct for this signature independently, so they have to agree on ;;; its tag and its layout, or the value is passed wrong and nothing diff --git a/tests/modules/ledger.sex b/tests/modules/ledger.sex new file mode 100644 index 0000000..14cbea7 --- /dev/null +++ b/tests/modules/ledger.sex @@ -0,0 +1,8 @@ +;;; A module greet.sex imports without `pub'. greet-app.sex never +;;; imports it, yet holds a (* ledger) that greet hands out: what greet +;;; exports has to declare the type for it. + +(pub record ledger ((total int))) + +(pub fn ledger-add ((l (* ledger)) (n int)) void + (+= (. l total) n)) -- 2.52.0 From dc15aaadabcd8a023b745276e04d10c28f54dd8e Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 17:44:36 +0300 Subject: [PATCH 21/43] write a make rule for the modules a unit reads An import pastes another file's forms into the output, so a Makefile had to make every object depend on every .sex. --depfile names the modules read, including those read only for an import's interface, with an empty rule for each, as cc -MD -MP does. Fixes #40. --- sex-modules.module.scm | 1 + sex-modules.scm | 15 +++++++++++++-- sexc.scm | 30 ++++++++++++++++++++++++++++++ tests/args.scm | 16 ++++++++++++++++ tests/modules/Makefile | 11 +++++++++-- 5 files changed, 69 insertions(+), 4 deletions(-) diff --git a/sex-modules.module.scm b/sex-modules.module.scm index eec7ab7..82f61e7 100644 --- a/sex-modules.module.scm +++ b/sex-modules.module.scm @@ -2,5 +2,6 @@ (get-modules-public-forms load-persistent-module-paths check-public-interface + module-dependencies read-public-interface) "sex-modules.scm") diff --git a/sex-modules.scm b/sex-modules.scm index 52391b4..976e66e 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -78,13 +78,24 @@ (file-readable? module-path) module-path)))) +;;; Every module file read for this unit, first read first: what its +;;; output depends on, besides the unit itself +(define +module-dependencies+ (list)) + +(define (module-dependencies) (reverse +module-dependencies+)) + +(define (read-module path) + (unless (member path +module-dependencies+) + (set! +module-dependencies+ (cons path +module-dependencies+))) + (read-from-file path)) + (define (read-public-interface module-path) ;; pub fns are reduced to prototypes, other pub forms are just pasted. ;; Declaration order is kept: a module that declares a type and then a ;; pub fn taking it has to paste them that way round, or the prototype ;; names a type C has not seen. The declarations of the types its ;; importers see only behind a pointer go first. - (let ((raw-forms (read-from-file module-path))) + (let ((raw-forms (read-module module-path))) (append (check-public-interface raw-forms) (interface-forms raw-forms)))) @@ -275,7 +286,7 @@ (let ((path (locate-module (symbol->string (car modules))))) (if (or (not path) (member path seen)) (read (cdr modules) seen acc) - (let ((forms (interface-forms (read-from-file path)))) + (let ((forms (interface-forms (read-module path)))) (read (append (cdr modules) (imported-modules forms #f)) (cons path seen) (append acc (declared-types forms))))))))) diff --git a/sexc.scm b/sexc.scm index e1ffb05..fb51749 100644 --- a/sexc.scm +++ b/sexc.scm @@ -64,6 +64,11 @@ (required #f) (value #t) (single-char #\o)) + (depfile + ,(fmt #f "Write a make rule for the output to FILE: it depends on" nl + (pad padding) "the source and on every module read for it. Needs -o") + (required #f) + (value #t)) (line-directives ,(fmt #f "How much #line information to emit: statement (default)," nl (pad padding) "toplevel, or none. `statement' is what makes a debugger" nl @@ -150,6 +155,28 @@ (map pp sex-forms) (emit-c sex-forms))))) +;;; app.o: app.sex /m/greet.sex, and an empty rule per module, so that +;;; make takes a module deleted since as out of date rather than as a +;;; file it has no rule to make +(define (dependency-rule target source modules) + (let ((spell (lambda (path) (string-translate* path '((" " . "\\ ")))))) + (apply string-append + (spell target) ":" + (append (map (lambda (path) (string-append " " (spell path))) + (if source (cons source modules) modules)) + (list "\n") + (map (lambda (path) (string-append "\n" (spell path) ":\n")) + modules))))) + +(define (write-dependencies depfile output input) + (when (or (eq? output 'default) (equal? output "-")) + (error "--depfile needs -o, to name what depends on the modules")) + (with-output-to-file depfile + (lambda () + (display (dependency-rule output + (and (not (eq? input 'stdin)) input) + (module-dependencies)))))) + (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." @@ -255,6 +282,9 @@ status, which is ours to pass on." (sex-line-directives 'none)) (let ((sex-forms (semantic-process-forms (read-raw-forms input) input))) + (let ((depfile (get-arg args 'depfile #f))) + (when depfile + (write-dependencies depfile output input))) (if (or (get-arg args 'macro-expand #f) (get-arg args 'emit-c #f)) ;; Emit processed and macro-expanded sex code, or emit C code diff --git a/tests/args.scm b/tests/args.scm index b2fc46f..a757a1b 100644 --- a/tests/args.scm +++ b/tests/args.scm @@ -65,3 +65,19 @@ (test "any other output is left alone" '("-o" "out" "-") (spell-stdout-output '("-o" "out" "-")))) + +;;; --depfile: an import pastes another file's forms into the output, so +;;; the output depends on that file as a C object does on a header +(test-group "dependency rule" + (test "the target, the source and the modules, then a rule per module" + "app.o: app.sex /m/greet.sex /m/ledger.sex\n\n/m/greet.sex:\n\n/m/ledger.sex:\n" + (dependency-rule "app.o" "app.sex" '("/m/greet.sex" "/m/ledger.sex"))) + (test "no modules, no rules of their own" + "app.o: app.sex\n" + (dependency-rule "app.o" "app.sex" '())) + (test "a space is escaped, the way make reads it" + "a\\ b.o: a\\ b.sex\n" + (dependency-rule "a b.o" "a b.sex" '())) + (test "stdin is no file to depend on" + "app.o: /m/greet.sex\n\n/m/greet.sex:\n" + (dependency-rule "app.o" #f '("/m/greet.sex")))) diff --git a/tests/modules/Makefile b/tests/modules/Makefile index e76f6e9..659563e 100644 --- a/tests/modules/Makefile +++ b/tests/modules/Makefile @@ -20,6 +20,10 @@ # to a prototype and to an extern both have to look past. And a type the # app cannot see -- private to greet, or from a module greet imports # without `pub' -- crosses behind a pointer, declared and no more. +# +# The app's dependency rule names both modules: greet, which it imports, +# and ledger, which only greet does but which decides what the app is +# told of it. SEXC ?= ../../sexc @@ -28,7 +32,10 @@ EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood check: @$(SEXC) ledger.sex -c -o ledger.o @$(SEXC) greet.sex -c -o greet.o - @$(SEXC) greet-app.sex -o greet-app -- greet.o ledger.o + @$(SEXC) greet-app.sex -o greet-app --depfile=greet-app.d -- greet.o ledger.o + @if ! head -1 greet-app.d | grep -q '^greet-app: greet-app.sex .*/greet.sex .*/ledger.sex$$'; then \ + echo "modules FAILED, the dependency rule is:"; cat greet-app.d; $(MAKE) clean; exit 1; \ + fi @if [ "`./greet-app`" = "`printf '$(EXPECTED)\n'`" ]; then \ echo "modules ok"; \ else \ @@ -37,6 +44,6 @@ check: @$(MAKE) --no-print-directory clean clean: - @rm -f greet.o ledger.o greet-app + @rm -f greet.o ledger.o greet-app greet-app.d .PHONY: check clean -- 2.52.0 From 981eb6f755f8c10ae540c06a5ca8f933e20ae298 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 17:47:25 +0300 Subject: [PATCH 22/43] print the public interface in declaration order read-public-interface has returned the forms in order since 2512d52, and --public-interface still reversed them as it had to before. --- sexc.scm | 3 +-- tests/modules/Makefile | 6 ++++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/sexc.scm b/sexc.scm index fb51749..793f223 100644 --- a/sexc.scm +++ b/sexc.scm @@ -269,8 +269,7 @@ status, which is ours to pass on." (write-to-file-or-stdout output (fn - (map pp (reverse - (read-public-interface input))))) + (map pp (read-public-interface input)))) (return #f)) ;; The file name in a #line directive now comes from the form's diff --git a/tests/modules/Makefile b/tests/modules/Makefile index 659563e..1bd6210 100644 --- a/tests/modules/Makefile +++ b/tests/modules/Makefile @@ -21,6 +21,9 @@ # app cannot see -- private to greet, or from a module greet imports # without `pub' -- crosses behind a pointer, declared and no more. # +# The interface prints as importers get it: the declarations first, then +# the pub forms in the order they were written. +# # The app's dependency rule names both modules: greet, which it imports, # and ledger, which only greet does but which decides what the app is # told of it. @@ -30,6 +33,9 @@ SEXC ?= ../../sexc EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7\nvec2(3 4)\ntally 2\nboard 42\nledger 2\ncolour 123 check: + @if [ "`$(SEXC) --public-interface greet.sex | head -3`" != "`printf '(record cell)\n(record ledger)\n(include stdio.h)'`" ]; then \ + echo "modules FAILED, the interface begins:"; $(SEXC) --public-interface greet.sex | head -3; exit 1; \ + fi @$(SEXC) ledger.sex -c -o ledger.o @$(SEXC) greet.sex -c -o greet.o @$(SEXC) greet-app.sex -o greet-app --depfile=greet-app.d -- greet.o ledger.o -- 2.52.0 From e29c6ee5c93acb7cebbc109141bef2d4769cbee0 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 18:03:21 +0300 Subject: [PATCH 23/43] parenthesise what a subscript subscripts The array was written at whatever level surrounded it, so [(* q) i] came out *q[i] -- *(q[i]) to C, compiling with q an int ** and reading the wrong int. The index now starts afresh too: inside a cast it had taken the cast's level and gained parens, and so had a chain in the else arm of ?:, which groups to the right and needs none. --- sex-fmt-c.scm | 26 ++++++++++++++++++-------- tests/codegen.scm | 25 ++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 9 deletions(-) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index e9ae69a..215617a 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -97,6 +97,7 @@ ;;((|\|\||) 75) ;;((.. ...) 77) ; Perl ((?) 80) + ((conditional-else) 81) ; see c-if/expr ((= *= /= %= &= ^= <<= >>=) 85) ; |\|=| ; += -= ((comma) 90) ((=>) 90) ; Perl @@ -111,6 +112,13 @@ (define (c-paren x) (cat "(" (c-expr x) ")")) + ;; MODIFIED FROM UPSTREAM fmt-c: a subscript is postfix, tighter than + ;; any operator, so what it subscripts is written at the level of + ;; `.' -- (* q) comes out `(*q)[i]', not `*q[i]', which is *(q[i]). + ;; The index has brackets of its own and starts afresh. + (define (c-subscript array index) + (cat (c-with-op "." (c-expr array)) "[" (c-with-op 'paren (c-expr index)) "]")) + ;; `.' and `->' associate left, and their right operand is always a ;; name, so a member access written inside another is the left one ;; and needs no parens of its own: `s.u.circle.r', not `((s.u).circle).r' @@ -249,12 +257,9 @@ ;; non C-keywords must have some character invalid in a C ;; identifier to avoid conflicts - by default we prefix % ((vector-ref) - ((c-wrap-stmt - (cat (c-expr (cadr x)) "[" (c-expr (caddr x)) "]")) - st)) + ((c-wrap-stmt (c-subscript (cadr x) (caddr x))) st)) ((vector-set!) - ((c= (c-in-expr - (cat (c-expr (cadr x)) "[" (c-expr (caddr x)) "]")) + ((c= (c-in-expr (c-subscript (cadr x) (caddr x))) (c-expr (cadddr x))) st)) ((extern/C) ((apply c-extern/C (cdr x)) st)) @@ -885,6 +890,10 @@ ;; Upstream wrote it bare whatever surrounded it, and `?:' binds ;; looser than every binary operator: (/ 300 (if c c 1)) came out ;; `300 / c ? c : 1', a conditional on the quotient. + ;; + ;; It groups to the right, so its else arm is written at + ;; `conditional-else', just looser: a chain there stays bare, + ;; `a ? x : b ? y : z', and an assignment does not. (define (c-if/expr . args) (c-maybe-paren '? (apply c-if/expr/aux args))) @@ -897,9 +906,10 @@ (c-expr p))) ((pair? ls) (cat (c-in-test (c-expr c)) " ? " (c-expr p) " : " - (if (pair? (cdr ls)) - (lp (car ls) (cadr ls) (cddr ls)) - (lp 'else (car ls) '())))) + (c-with-op 'conditional-else + (if (pair? (cdr ls)) + (lp (car ls) (cadr ls) (cddr ls)) + (lp 'else (car ls) '()))))) (else (c-or (c-in-test (c-expr c)) (c-expr p)))))) diff --git a/tests/codegen.scm b/tests/codegen.scm index d2dcf53..2b5847a 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -167,7 +167,30 @@ whitespace aside, THEN?" "int x = a ? a : b")) (test-assert "left bare as an argument" (emits? (in-fn "(g (if a a b) b)") - "g(a ? a : b, b)"))) + "g(a ? a : b, b)")) + ;; ?: groups to the right, so a chain needs none in its else arm + (test-assert "a chain in the else arm is left bare" + (emits? (in-fn "(var x int (if a a (if b b 0)))") + "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 subscript binds tighter than anything, so what it subscripts is + ;; parenthesised whenever it is an operator: `*q[i]' is *(q[i]) + (test-group "subscript precedence" + (test-assert "a dereference" + (emits? "(fn f ((q (* * int)) (i int)) int (return [(* q) i]))" "(*q)[i]")) + (test-assert "a sum" + (emits? "(fn f ((p (* int))) int (return [(+ p 1) 0]))" "(p + 1)[0]")) + (test-assert "a cast" + (emits? "(fn f ((v (* void))) int (return [(cast v (* int)) 0]))" "((int *)v)[0]")) + (test-assert "a path is left bare" + (emits? (in-line "(var x int [(. p x) 0])") "p.x[0]")) + ;; ...while the index is in brackets of its own + (test-assert "an index is never parenthesised" + (emits? "(fn f ((p (* int)) (i int)) int (return (cast [p (+ i 1)] int)))" + "(int)p[i + 1]"))) ;; A comment among a call's arguments used to become an argument, ;; and c-apply put a comma on each side of it -- which does not -- 2.52.0 From 449a53abf940bdaafe64afd32a7cec486a2dd9f0 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 18:15:54 +0300 Subject: [PATCH 24/43] hand sexc every digit of a test program's doubles sextest prints the program it read back to sexc, and printed doubles in CHICKEN's default 15 digits: 0.16666666666666666 arrived as 0.166666666666667, another number. --- tools/sextest/sextest.scm | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tools/sextest/sextest.scm b/tools/sextest/sextest.scm index 43f3d5f..459a8e5 100644 --- a/tools/sextest/sextest.scm +++ b/tools/sextest/sextest.scm @@ -6,6 +6,7 @@ (chicken io) (chicken pathname) (chicken port) + (chicken flonum) ; flonum-print-precision (chicken process) (chicken process-context) (chicken string) ; string-split @@ -93,6 +94,9 @@ (let* ((proc (process compiler (append (list "-o" compiled-file) flags))) (sexc-stdin (process-input-port proc))) (symbol-escape #f) + ;; ...nor any double in the 15 digits CHICKEN prints by default, + ;; which make 0.16666666666666666 another number + (flonum-print-precision 17) (with-output-to-port sexc-stdin (fn (map (fn (fmt #t x)) src))) (close-output-port sexc-stdin) -- 2.52.0 From 5ccbb5d7e0c7f186415a34746f9da3d3270f72c7 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 18:15:54 +0300 Subject: [PATCH 25/43] write a double in the digits that read back as it CHICKEN prints 15 significant digits unless told otherwise, too few to name every double: 0.9871465422297019 reached the C as 0.987146542229702, a different constant. Found in vs-map-viewer, where 380 literals in a port that has to match .NET bit for bit changed this way. The shortest spelling that reads back is written, up to 17 digits. --- sex-fmt-c.scm | 17 ++++++++++++++++- tests/codegen.scm | 13 ++++++++++++- tests/sex-programs/operators.sex | 7 ++++++- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index 215617a..f07644e 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -36,6 +36,7 @@ scheme (scheme base) ; string->utf8, bytevector accessors (chicken base) + (chicken flonum) ; flonum-print-precision fmt srfi-1 srfi-13) @@ -192,7 +193,21 @@ ((8) (cat "0" (number->string x 8))) (else (dsp (number->string x)))) st)) - (dsp (number->string x)))) + (dsp (c-format-flonum x)))) + + ;; MODIFIED FROM UPSTREAM fmt-c: a double in as few digits as read + ;; back as the same double. number->string stops at + ;; flonum-print-precision, 15 unless set, and 0.16666666666666666 came + ;; out 0.166666666666667: a different double in the C. Seventeen + ;; always do. + (define (c-format-flonum x) + (let ((precision (flonum-print-precision))) + (let try ((digits 15)) + (flonum-print-precision digits) + (let ((written (number->string x))) + (if (or (= digits 17) (= (string->number written) x)) + (begin (flonum-print-precision precision) written) + (try (+ digits 1))))))) (define (c-format-string x) (lambda (st) ((cat #\" (apply-cat (c-string-escaped x)) #\") st))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 2b5847a..03638e4 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -789,7 +789,18 @@ whitespace aside, THEN?" (test-assert "a subscript" (emits? (in-fn "(var xs [int 4]) (var n size-t (sizeof [xs 0]))") "sizeof(xs[0])"))) - ;; A define's body was pasted unwalked, and unparenthesised: `cast' + ;; A double is written in as few digits as read back as the same + ;; double: CHICKEN prints 15 by default, and 0.16666666666666666 came + ;; out 0.166666666666667, another number + (test-group "double literals" + (test-assert "keep every digit they need" + (emits? (in-fn "(var d double 0.16666666666666666)") "d = 0.16666666666666666;")) + (test-assert "and gain none they do not" + (emits? (in-fn "(var d double 0.1)") "d = 0.1;")) + (test-assert "sixteen when that is enough" + (emits? (in-fn "(var d double 0.9871465422297019)") "d = 0.9871465422297019;"))) + + ;; 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" (test-assert "an atom is left bare" diff --git a/tests/sex-programs/operators.sex b/tests/sex-programs/operators.sex index 03baec0..7481f55 100644 --- a/tests/sex-programs/operators.sex +++ b/tests/sex-programs/operators.sex @@ -8,7 +8,8 @@ "toplevel: 1 2.5 hi 12" "closure in place: 5" "a type is not a call: 7" - "radix literals: 224 5 128") + "radix literals: 224 5 128" + "a double reaches C whole: 1") (return 0) ;;; The walk types an expression by its head, and the heads it had a @@ -92,4 +93,8 @@ ;; a mask reads best in the radix it is a mask in (var lead int 0xE5) (printf "radix literals: %d %d %d\n" (& lead 0xE0) (& lead 0b111) #x80) + + ;; ...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)) (return 0)) -- 2.52.0 From 541d9cd610d6a591fa422736ea86851c5a73a788 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 18:21:11 +0300 Subject: [PATCH 26/43] check the constants a module's interface hands its importers An array bound in a pub record, or a name in a pub define's body, is the importer's to resolve too, and a private define, or one from an import without pub, failed there as an undeclared identifier. Found in vs-map-viewer once its units stopped importing everything. A constant has no declaration short of itself, so it is an error at the pub form. --- sex-modules.scm | 28 ++++++++++++++++++++-------- tests/encapsulation.scm | 15 ++++++++++++++- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/sex-modules.scm b/sex-modules.scm index 976e66e..76bc34f 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -179,6 +179,7 @@ (('pub 'var name type . _) (list type)) (_ (list)))) (('pub 'typedef name target) (list target)) + (('pub 'define name . body) body) (('pub (or 'record 'struct 'union) name . rest) (field-types (find list? (remove comment-form? rest)))) (('pub 'sum name (variants ...)) @@ -218,7 +219,8 @@ (case (car type) ((*) (append-map (lambda (t) (type-uses t #t)) (cdr type))) ((¤) (let ((element (array-element-type type))) - (if element (type-uses element behind?) (list)))) + (append (if element (type-uses element behind?) (list)) + (if (array-bound? type) (bound-uses (last type)) (list))))) ((fn closure) (if (and (pair? (cdr type)) (list? (second type))) (append-map (lambda (t) (type-uses t #t)) @@ -230,21 +232,31 @@ (list))) (else (append-map (lambda (t) (type-uses t behind?)) type)))))) -;;; The types FORMS declare, as (name kind body?): +;;; [int (* 2 N)] needs N, as a value: there is no declaring it +(define (bound-uses bound) + (cond ((symbol? bound) (list (cons bound #f))) + ((pair? bound) (append-map bound-uses (cdr bound))) + (else (list)))) + +;;; The types and constants 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) (define (declared-types forms) (filter-map (lambda (form) (and (pair? form) - (let ((core (if (pub-form? form) (cdr form) form))) - (and (pair? core) (pair? (cdr core)) - (memq (car core) '(record struct union enum sum typedef)) - (symbol? (second core)) - (list (second core) + (let* ((core (if (pub-form? form) (cdr form) form)) + (name (and (pair? core) (pair? (cdr core)) + (if (and (eq? (car core) 'define) (pair? (second core))) + (car (second core)) + (second core))))) + (and (memq (car core) '(record struct union enum sum typedef define)) + (symbol? name) + (list name (car core) - (or (eq? (car core) 'typedef) + (or (memq (car core) '(typedef define)) (any list? (remove comment-form? (cddr core))))))))) forms)) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 060ecef..b7566a7 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -553,4 +553,17 @@ ahead of its pub forms." "only a handle")) (test "which is all it takes" '() - (interface-of "(pub record h) (record h ((n int))) (pub fn f ((x (* h))) void)")))) + (interface-of "(pub record h) (record h ((n int))) (pub fn f ((x (* h))) void)")) + ;; A constant has no declaration either, and an array bound or a + ;; pub define's body hands its name to importers all the same + (test-assert "a constant sizing a pub record's array" + (interface-reports? "(define N 4) (pub record r ((xs [int N])))" + "this define, and C declares one only by defining it")) + (test-assert "or used by a pub define" + (interface-reports? "(define N 4) (pub define M (* 2 N))" "this define")) + (test "is fine when pub" + '() + (interface-of "(pub define N 4) (pub record r ((xs [int N])))")) + (test "as is a literal bound" + '() + (interface-of "(pub record r ((xs [int 4])))")))) -- 2.52.0 From 70228366ee4e4f948a4181ae7b4b3b4a811c968a Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 20:05:26 +0300 Subject: [PATCH 27/43] drop walk-literal, which the rebase left without callers walk-initializer took its place, but walked the values as statements; a match among them is refused again wherever the literal stands. --- semen.scm | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/semen.scm b/semen.scm index 87e2e35..e312bc8 100644 --- a/semen.scm +++ b/semen.scm @@ -800,21 +800,12 @@ (unresolve-closure-types (expression-type queried env))))) (macroexpand form (list)))) -;;; `#(v : (.get a))' is `(v){vːget(&a)}': the values are expressions -;;; like any other, and the type before `:' is not one -(define (walk-literal form env) - (let* ((parts (vector->list form)) - (elements (or (and (memq ': parts) (cdr (memq ': parts))) parts))) - (list->vector - (append (drop-right parts (length elements)) - (map (lambda (element) (walk-operand element env)) elements))))) - ;;; #(struct point : (. p x) 2) -- the values are expressions, and the ;;; words before a `:' a type that is left as written (define (walk-initializer form env) (let-values (((prefix rest) (break (lambda (e) (eq? e ':)) (vector->list form)))) - (let ((walk (lambda (es) (map (lambda (e) (walk-statement e env)) es)))) + (let ((walk (lambda (es) (map (lambda (e) (walk-operand e env)) es)))) (list->vector (if (null? rest) (walk prefix) -- 2.52.0 From 049d97b5e1df191219f3194dc2fbd867033eb093 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 20:06:51 +0300 Subject: [PATCH 28/43] declare an ops method ahead through the one prototype accessor fn-prototype repeated sex-fn-prototype, and names? repeated mentions?; each pair kept the better half. --- semen.scm | 47 ++++++++++++++++++----------------------------- 1 file changed, 18 insertions(+), 29 deletions(-) diff --git a/semen.scm b/semen.scm index e312bc8..43e1672 100644 --- a/semen.scm +++ b/semen.scm @@ -428,11 +428,9 @@ (bodies (map (lambda (m) (if (comment-form? m) (list m) (process-fn m (list)))) methods)) - (early (filter (lambda (m) - (called-before? (sex-fn-name m) m methods bodies)) - fns))) + (early (filter (lambda (m) (called-before? m methods bodies)) fns))) (append (append-map identity (reverse bodies)) - (fold (lambda (m acc) (process-fn (fn-prototype m) acc)) acc early))))) + (fold (lambda (m acc) (process-fn (sex-fn-prototype m) acc)) acc early))))) ;;; The method's fn form, renamed to vec2/length, once it is registered ;;; under `length'; a comment is passed along @@ -446,28 +444,23 @@ (let ((name (second core))) (when (get-method type name) (sex-error form "method is already defined on" type name)) - (let ((qualified (qualify-op type name))) + (let* ((qualified (qualify-op type name)) + (renamed (rename-fn form qualified))) (add-method! type name qualified) ;; its signature too, which a call's receiver is fitted to - (process-fn (fn-prototype (rename-fn form qualified)) (list)) - (rename-fn form qualified)))))) + (process-fn (sex-fn-prototype renamed) (list)) + renamed))))) ;;; Does a body written above METHOD call it? -(define (called-before? name method methods bodies) - (let loop ((ms methods) (bs bodies)) - (and (not (eq? (car ms) method)) - (or (names? (car bs) name) - (loop (cdr ms) (cdr bs)))))) - -;;; NAME anywhere in FORM, a literal's contents included -(define (names? form name) - (cond ((eq? form name) #t) - ((pair? form) (or (names? (car form) name) (names? (cdr form) name))) - ((vector? form) (names? (vector->list form) name)) - (else #f))) +(define (called-before? method methods bodies) + (let ((name (sex-fn-name method))) + (let loop ((ms methods) (bs bodies)) + (and (not (eq? (car ms) method)) + (or (mentions? (car bs) name) + (loop (cdr ms) (cdr bs))))))) ;;; (pub fn name args ret ...) -> (pub fn name args ret) -(define (fn-prototype form) +(define (sex-fn-prototype form) (let ((header (strip-fn-header-comments form))) (copy-form-source! form (take header (fn-header-length header))))) @@ -888,9 +881,11 @@ (define (wildcard-type? type) (mentions? type '_)) -(define (mentions? type word) - (cond ((eq? type word) #t) - ((list? type) (any (lambda (part) (mentions? part word)) type)) +;;; WORD anywhere in FORM, a literal's contents included +(define (mentions? form word) + (cond ((eq? form word) #t) + ((pair? form) (or (mentions? (car form) word) (mentions? (cdr form) word))) + ((vector? form) (mentions? (vector->list form) word)) (else #f))) ;;; `(each xs compare)' where `each' takes a closure: the argument is @@ -1996,12 +1991,6 @@ Returns #f if the form is not a function, returns the form otherwise" (fmt #f "Form " fn-form " is not a function")) (fourth (fn-core fn-form))) -(define (sex-fn-prototype fn-form) - "Returns all except body" - (assert (sex-fn? fn-form) - (fmt #f "Form " fn-form " is not a function")) - (take fn-form (fn-header-length fn-form))) - (define (sex-fn-body fn-form) (assert (sex-fn? fn-form) (fmt #f "Form " fn-form " is not a function")) -- 2.52.0 From 11587684464b07faa6790e6be5cb611bd17fb9fa Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 20:06:51 +0300 Subject: [PATCH 29/43] keep the parameter-type rule in types, where both readers find it sex-modules spelled out its own copy of named-arg-type, and its own strip-pub; a parameter shape taught to one would not reach the other. --- semen.scm | 19 ------------------- sex-modules.scm | 10 ++-------- tests/types.module.scm | 3 +++ types.module.scm | 3 +++ types.scm | 19 +++++++++++++++++++ 5 files changed, 27 insertions(+), 27 deletions(-) diff --git a/semen.scm b/semen.scm index 43e1672..dc08160 100644 --- a/semen.scm +++ b/semen.scm @@ -485,25 +485,6 @@ (set! (hash-table-ref env :scopes) (list parameters)) env)) -;;; `(p (* struct point))' writes the type in one piece and -;;; `(p * struct point)' spreads it over the rest; both are -;;; `(* struct point)' -(define (named-arg-type param) - (if (null? (cddr param)) - (second param) - (cdr param))) - -;;; (fn sum ((a int) (b int)) int ...) -> (fn ((int) (int)) int), and -;;; (self * const v) is ((* const v)) just as (self (* const v)) is. -;;; Anything that names nothing -- a variadic tail -- goes through -;;; untouched. -(define (arglist-types arglist) - (map (lambda (param) - (if (named-arg? param) - (list (named-arg-type param)) - param)) - arglist)) - (define (fn-type-of fn-form) `(fn ,(arglist-types (sex-fn-arglist fn-form)) ,(sex-fn-return-type fn-form))) diff --git a/sex-modules.scm b/sex-modules.scm index 76bc34f..1752213 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -198,13 +198,7 @@ (if (list? fields) (map second (normalize-fields fields)) (list))) (define (signature-types args ret) - (cons ret (map arg-type (remove comment-form? args)))) - -;;; (f1 float) -> float, (n unsigned int) -> (unsigned int), (int) -> (int) -(define (arg-type arg) - (cond ((not (named-arg? arg)) arg) - ((null? (cddr arg)) (second arg)) - (else (cdr arg)))) + (cons ret (arglist-types (remove comment-form? args)))) ;;; Each name TYPE mentions, and whether it is behind a pointer: ;;; @@ -247,7 +241,7 @@ (filter-map (lambda (form) (and (pair? form) - (let* ((core (if (pub-form? form) (cdr form) form)) + (let* ((core (strip-pub form)) (name (and (pair? core) (pair? (cdr core)) (if (and (eq? (car core) 'define) (pair? (second core))) (car (second core)) diff --git a/tests/types.module.scm b/tests/types.module.scm index e2fb4bd..d905dff 100644 --- a/tests/types.module.scm +++ b/tests/types.module.scm @@ -42,6 +42,9 @@ type-head? named-arg? + named-arg-type + arglist-types + strip-pub array-bound? array-element-type) "../types.scm") diff --git a/types.module.scm b/types.module.scm index 95c350a..d4b98e1 100644 --- a/types.module.scm +++ b/types.module.scm @@ -42,6 +42,9 @@ type-head? named-arg? + named-arg-type + arglist-types + strip-pub array-bound? array-element-type) "types.scm") diff --git a/types.scm b/types.scm index 3d91404..2fa6098 100644 --- a/types.scm +++ b/types.scm @@ -390,6 +390,25 @@ (pair? (cdr arg)) ; 1 element args are always type (not (type-head? arg)))) +;;; `(p (* struct point))' writes the type in one piece and +;;; `(p * struct point)' spreads it over the rest; both are +;;; `(* struct point)' +(define (named-arg-type param) + (if (null? (cddr param)) + (second param) + (cdr param))) + +;;; (fn sum ((a int) (b int)) int ...) -> (fn ((int) (int)) int), and +;;; (self * const v) is ((* const v)) just as (self (* const v)) is. +;;; Anything that names nothing -- a variadic tail -- goes through +;;; untouched. +(define (arglist-types arglist) + (map (lambda (param) + (if (named-arg? param) + (list (named-arg-type param)) + param)) + arglist)) + ;;; The last element is a bound unless what precedes it is still ;;; waiting for a type name -- a `*', a qualifier, a tag's keyword. C ;;; spells a type with one name at most, so a name after a name, or -- 2.52.0 From 5b3f2bd42198f700b498d53fae50cf1835fad210 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 20:07:03 +0300 Subject: [PATCH 30/43] name the test for output going to stdout -o - was taught to two copies of it. --- sexc.scm | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/sexc.scm b/sexc.scm index 793f223..2d75475 100644 --- a/sexc.scm +++ b/sexc.scm @@ -142,8 +142,11 @@ 'stdin (car rest-args)))) +(define (stdout-output? output) + (or (eq? output 'default) (equal? output "-"))) + (define (write-to-file-or-stdout output what) - (if (or (eq? output 'default) (equal? output "-")) + (if (stdout-output? output) (what) (with-output-to-file output (fn (what))))) @@ -169,7 +172,7 @@ modules))))) (define (write-dependencies depfile output input) - (when (or (eq? output 'default) (equal? output "-")) + (when (stdout-output? output) (error "--depfile needs -o, to name what depends on the modules")) (with-output-to-file depfile (lambda () -- 2.52.0 From dcd93c0d9e0615ec9fc7b3eedf008eb871767ceb Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 20:07:20 +0300 Subject: [PATCH 31/43] compile the name spellings once, and skip a name that has none Read from a table, the patterns were compiled again for every symbol written; that tripled what unkebabify cost. --- fmt-c-writer.scm | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 021a4c2..77e54e6 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -133,17 +133,19 @@ forms, and what remains." ;;; exclamation mark, both letters. Not the retroflex click ǃ, which ;;; looks more like `!' -- enough that clang warns at every use. (define +name-spellings+ - '(("-(?!>)" . "_") ("/" . "ː") ("\\?" . "ʔ") ("!" . "ꜝ"))) + (map (lambda (spelling) (cons (irregex (car spelling)) (cdr spelling))) + '(("-(?!>)" . "_") ("/" . "ː") ("\\?" . "ʔ") ("!" . "ꜝ")))) (define (unkebabify sym) - (case sym - ((- -- -> -= / /= ! != ?) sym) ; bare operators, not names - (else - (string->symbol - (fold (lambda (spelling name) - (irregex-replace/all (car spelling) name (cdr spelling))) - (symbol->string sym) - +name-spellings+))))) + (let ((name (symbol->string sym))) + (if (or (memq sym '(- -- -> -= / /= ! != ?)) ; bare operators, not names + (not (string-index name (lambda (c) (memv c '(#\- #\/ #\? #\!)))))) + sym + (string->symbol + (fold (lambda (spelling name) + (irregex-replace/all (car spelling) name (cdr spelling))) + name + +name-spellings+))))) (define (atom-to-fmt-c atom) (case atom -- 2.52.0 From 70aafb70e66eab28b68c8634fdc32f4992a413c7 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 20:08:16 +0300 Subject: [PATCH 32/43] read each module once per unit A pub import chain had its interface check read every module below again, so the deepest was parsed once per level above it. --- sex-modules.scm | 45 ++++++++++++++++++++------------------------- 1 file changed, 20 insertions(+), 25 deletions(-) diff --git a/sex-modules.scm b/sex-modules.scm index 1752213..199a044 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -78,16 +78,18 @@ (file-readable? module-path) module-path)))) -;;; Every module file read for this unit, first read first: what its -;;; output depends on, besides the unit itself -(define +module-dependencies+ (list)) +;;; Every module file read for this unit, with its forms, last read +;;; first: what its output depends on, besides the unit itself. A module +;;; that an import chain and the interface check both reach is read once +(define +modules-read+ (list)) -(define (module-dependencies) (reverse +module-dependencies+)) +(define (module-dependencies) (reverse (map car +modules-read+))) (define (read-module path) - (unless (member path +module-dependencies+) - (set! +module-dependencies+ (cons path +module-dependencies+))) - (read-from-file path)) + (cond ((assoc path +modules-read+) => cdr) + (else (let ((forms (read-from-file path))) + (set! +modules-read+ (cons (cons path forms) +modules-read+)) + forms)))) (define (read-public-interface module-path) ;; pub fns are reduced to prototypes, other pub forms are just pasted. @@ -134,7 +136,8 @@ (define (check-type-use form use visible hidden acc) (let* ((name (car use)) (seen (assq name visible)) - (kept (assq name hidden))) + (kept (assq name hidden)) + (remedy (if (and kept (fourth kept)) "import its module with pub" "make it pub"))) (cond ((and seen (third seen)) acc) ; pub with its body ((and seen (cdr use)) acc) ; a pub handle, held by one @@ -146,16 +149,11 @@ (sex-error form (string-append "importers cannot see this " (symbol->string (second kept)) ", and C declares one only by defining it; " - (if (fourth kept) - "import its module with pub" - "make it pub")) + remedy) name)) ((not (cdr use)) (sex-error form (string-append "importers cannot see this type, held by value; " - (if (fourth kept) - "import its module with pub" - "make it pub") - ", or hold it through a pointer") + remedy ", or hold it through a pointer") name)) ((any (lambda (f) (eq? name (cadr f))) acc) acc) (else @@ -257,14 +255,11 @@ (define (pub-form? form) (and (pair? form) (eq? (car form) 'pub))) ;;; Pub here or through a pub import. A type declared pub both bodyless -;;; and whole is whole +;;; and whole is whole: its whole entries come first, for `assq' (define (visible-types forms) (let ((all (append (declared-types (filter pub-form? forms)) (append-map exported-types (imported-modules forms #t))))) - (map (lambda (entry) - (list (first entry) (second entry) - (any third (filter (lambda (e) (eq? (first e) (first entry))) all)))) - all))) + (append (filter third all) (remove third all)))) ;;; Declared here without pub, or brought by an import without it, as ;;; (name kind body? imported?) @@ -286,16 +281,16 @@ ;;; 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 read ((modules (list module)) (seen (list)) (acc (list))) + (let next ((modules (list module)) (seen (list)) (acc (list))) (if (null? modules) - acc + (concatenate (reverse acc)) (let ((path (locate-module (symbol->string (car modules))))) (if (or (not path) (member path seen)) - (read (cdr modules) seen acc) + (next (cdr modules) seen acc) (let ((forms (interface-forms (read-module path)))) - (read (append (cdr modules) (imported-modules forms #f)) + (next (append (cdr modules) (imported-modules forms #f)) (cons path seen) - (append acc (declared-types forms))))))))) + (cons (declared-types forms) acc)))))))) (define (public-fn-interface raw-form) ;; (pub fn name args ret . body) -> prototype, keeping a docstring so -- 2.52.0 From 8f152c25933ff451e4719c1458204f7dd9ff3db7 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 20:08:39 +0300 Subject: [PATCH 33/43] tell a grouped for header by its shape, not by a var in it (for ((= s 0) (< s n) (++ s)) ...) passed the check and reached cc as a call of (= s 0). --- fmt-c-writer.scm | 6 +++--- tests/codegen.scm | 3 +++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 77e54e6..c3f6219 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -95,10 +95,10 @@ forms, and what remains." `(%begin ,@(map walk-expr comments) ,form))) ;;; (for init test step body ...). C's parens around the header, carried -;;; over, leave a call of a `var' in init's slot and the body in test's +;;; over, leave all three parts in init's slot and the body in test's (define (check-for-header form slots) - (cond ((and (pair? slots) (pair? (car slots)) (pair? (caar slots)) - (eq? 'var (car (caar slots)))) + (cond ((and (pair? slots) (list? (car slots)) (= 3 (length (car slots))) + (every pair? (car slots))) (sex-error form "a for header is not grouped: write (for init test step body ...)")) ((< (length slots) 3) (sex-error form "malformed for: write (for init test step body ...)")))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 03638e4..6e8855f 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -338,6 +338,9 @@ whitespace aside, THEN?" (test-assert "a grouped header is named" (reports? (in-fn "(for ((var i int 0) (< i 4) (++ i)) (g i))") "header is not grouped")) + (test-assert "whatever its init is" + (reports? (in-fn "(for ((= a 0) (< a 4) (++ a)) (g a))") + "header is not grouped")) (test-assert "even when the body fills the slots it left" (reports? (in-fn "(for ((var i int 0) (< i 4) (++ i)) (g i) (g i) (g i))") "header is not grouped")) -- 2.52.0 From f87e9faa8f18f276b0a4866c82e454583f93a42b Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 20:09:17 +0300 Subject: [PATCH 34/43] parenthesise a conditional without a helper to do it for --- sex-fmt-c.scm | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index f07644e..4be8e0c 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -909,24 +909,23 @@ ;; It groups to the right, so its else arm is written at ;; `conditional-else', just looser: a chain there stays bare, ;; `a ? x : b ? y : z', and an assignment does not. - (define (c-if/expr . args) - (c-maybe-paren '? (apply c-if/expr/aux args))) - - (define (c-if/expr/aux c p . rest) - (let lp ((c c) (p p) (ls rest)) - (cond - ((or (eq? c 'else) (eq? c #t)) - (if (not (null? ls)) - (error "forms after else clause in IF" c p ls) - (c-expr p))) - ((pair? ls) - (cat (c-in-test (c-expr c)) " ? " (c-expr p) " : " - (c-with-op 'conditional-else - (if (pair? (cdr ls)) - (lp (car ls) (cadr ls) (cddr ls)) - (lp 'else (car ls) '()))))) - (else - (c-or (c-in-test (c-expr c)) (c-expr p)))))) + (define (c-if/expr c p . rest) + (c-maybe-paren + '? + (let lp ((c c) (p p) (ls rest)) + (cond + ((or (eq? c 'else) (eq? c #t)) + (if (not (null? ls)) + (error "forms after else clause in IF" c p ls) + (c-expr p))) + ((pair? ls) + (cat (c-in-test (c-expr c)) " ? " (c-expr p) " : " + (c-with-op 'conditional-else + (if (pair? (cdr ls)) + (lp (car ls) (cadr ls) (cddr ls)) + (lp 'else (car ls) '()))))) + (else + (c-or (c-in-test (c-expr c)) (c-expr p))))))) (define (c-if . args) (fmt-if fmt-expression? -- 2.52.0 From c97ae8583baf4070d45f2fd31a8554bb36cbb46f Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 20:09:17 +0300 Subject: [PATCH 35/43] share reading a test source and catching its error encapsulation.scm had copies of both from codegen.scm. --- tests/codegen.scm | 24 +++++++++++++++--------- tests/encapsulation.scm | 13 ++++--------- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/tests/codegen.scm b/tests/codegen.scm index 6e8855f..552c552 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -15,12 +15,15 @@ semen utils) +(define (read-source source) + (with-input-from-string source + (lambda () + (parameterize ((current-source-file "codegen.sex")) + (parse-all (current-input-port)))))) + (define (sex->c source) "Compile SOURCE, a string of Sex, and return the generated C." - (let ((forms (with-input-from-string source - (lambda () - (parameterize ((current-source-file "codegen.sex")) - (parse-all (current-input-port))))))) + (let ((forms (read-source source))) (with-output-to-string (lambda () (parameterize ((sex-line-directives 'none)) @@ -37,17 +40,20 @@ (define (emits? source fragment) (and (string-contains (silently (lambda () (sex->c source))) fragment) #t)) -(define (error-message source) - "Compile SOURCE and return the error text as the user sees it -- -message plus arguments, the way CHICKEN prints it -- or #f if SOURCE -compiles." +(define (failure-message thunk) + "The error THUNK raises as the user sees it -- message plus arguments, +the way CHICKEN prints it -- or #f if it raises none." (handle-exceptions e (with-output-to-string (lambda () (display ((condition-property-accessor 'exn 'message) e)) (for-each (lambda (a) (display " ") (write a)) ((condition-property-accessor 'exn 'arguments) e)))) - (begin (sex->c source) #f))) + (begin (thunk) #f))) + +(define (error-message source) + "Compile SOURCE and return its error text, or #f if it compiles." + (failure-message (lambda () (sex->c source)))) (define (reports? source fragment) (let ((m (error-message source))) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index b7566a7..fd0f72d 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -5,23 +5,18 @@ ;;; is checked here is what the compiler refuses, and that it refuses ;;; it with the name of whatever is wrong. ;;; -;;; `sex->c', `emits?', `reports?' and `in-fn' come from codegen.scm, -;;; which run.scm includes first. +;;; `sex->c', `read-source', `failure-message', `emits?', `reports?' +;;; and `in-fn' come from codegen.scm, which run.scm includes first. (import sex-modules) (define (interface-of source) "The declarations SOURCE, compiled as a module, hands its importers ahead of its pub forms." - (check-public-interface - (with-input-from-string source - (lambda () - (parameterize ((current-source-file "codegen.sex")) - (parse-all (current-input-port))))))) + (check-public-interface (read-source source))) (define (interface-reports? source fragment) - (let ((m (handle-exceptions e ((condition-property-accessor 'exn 'message) e) - (begin (interface-of source) #f)))) + (let ((m (failure-message (lambda () (interface-of source))))) (and m (string-contains m fragment) #t))) (define (ops-src . body) -- 2.52.0 From 44101c0c06b9734df3be87fc0da69f3f5a200678 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 20:09:49 +0300 Subject: [PATCH 36/43] tell what a member path walked from the fields it has left --- semen.scm | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/semen.scm b/semen.scm index dc08160..8dac182 100644 --- a/semen.scm +++ b/semen.scm @@ -1121,20 +1121,17 @@ (let ((base (second form))) (let step ((expr (walk-operand base env)) (type (expression-type base env)) - (read (list)) ; the fields walked, reversed (fields (cddr form)) (told? #f)) (if (null? fields) (copy-form-source! form expr) (let ((target (pointer-target type))) (unless (or type told?) - (sex-warning form "cannot type this; `.' reads it as a value" - (if (null? read) - base - `(|.| ,base ,@(reverse read))))) + (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)) - (cons (car fields) read) (cdr fields) (or told? (not type)))))))) -- 2.52.0 From 2279c371f23893bdd51a6bf66ff9f264a6275197 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Thu, 15 Oct 2026 14:44:34 +0300 Subject: [PATCH 37/43] hold a function type's parameters by value on the interface A record a pub function type took or returned by value was declared only, so an importer could neither define a callback for it nor call one. --- sex-modules.scm | 7 +++++-- tests/encapsulation.scm | 9 +++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/sex-modules.scm b/sex-modules.scm index 199a044..7a68e91 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -202,7 +202,10 @@ ;;; ;;; (* const cell) -> ((const . #t) (cell . #t)) ;;; [cell 4] -> ((cell . #f)) -;;; (fn ((cell)) int) -> ((cell . #t) (int . #t)) ; declaring is enough +;;; (fn ((cell)) int) -> ((cell . #f) (int . #f)) +;;; +;;; A function type takes and returns by value whatever it is held +;;; through: C wants the body to define or call one of its functions. (define (type-uses type behind?) (cond ((symbol? type) (list (cons type behind?))) @@ -215,7 +218,7 @@ (if (array-bound? type) (bound-uses (last type)) (list))))) ((fn closure) (if (and (pair? (cdr type)) (list? (second type))) - (append-map (lambda (t) (type-uses t #t)) + (append-map (lambda (t) (type-uses t #f)) (signature-types (second type) (last type))) (list))) ((struct union enum) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index fd0f72d..1217521 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -534,6 +534,15 @@ ahead of its pub forms." "held by value")) (test-assert "returned" (interface-reports? "(record cell ((v int))) (pub fn f () cell)" "held by value")) + (test-assert "or taken by a function a pub one takes" + (interface-reports? "(record cell ((v int))) (pub fn take ((cb (fn ((c cell)) void))) void)" + "held by value")) + (test-assert "or returned by one" + (interface-reports? "(record cell ((v int))) (pub fn take ((cb (fn () cell))) void)" + "held by value")) + (test "but a pointer there is still a pointer" + '((record cell)) + (interface-of "(record cell ((v int))) (pub fn take ((cb (fn ((c (* cell))) void))) void)")) (test-assert "or taken by a pub method" (interface-reports? "(record cell ((v int))) (ops cell (pub fn get ((self cell)) int))" "held by value")) -- 2.52.0 From f84010eda87b228af83f54a2a317cf8169752c05 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Thu, 15 Oct 2026 14:47:12 +0300 Subject: [PATCH 38/43] refuse a field a struct declared here does not have The path was walked on and handed to cc, which named the missing field only in C; a test leaned on a struct s an earlier test had declared. --- semen.scm | 14 ++++++++++++-- tests/codegen.scm | 11 ++++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/semen.scm b/semen.scm index 8dac182..7d3cfc8 100644 --- a/semen.scm +++ b/semen.scm @@ -1116,7 +1116,8 @@ ;;; A type we cannot work out is read as a value, which is what the ;;; path would have meant before any of this. The warning names what ;;; could not be typed: the base, or the path up to a field of a struct -;;; only C knows -- (. font handle), not font. +;;; only C knows -- (. font handle x) warns of (. font handle), not +;;; font. A field a struct declared here lacks is an error. (define (walk-member-path form env) (let ((base (second form))) (let step ((expr (walk-operand base env)) @@ -1125,7 +1126,10 @@ (told? #f)) (if (null? fields) (copy-form-source! form expr) - (let ((target (pointer-target type))) + (let* ((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?) (let ((walked (drop-right (cddr form) (length fields)))) (sex-warning form "cannot type this; `.' reads it as a value" @@ -1135,6 +1139,12 @@ (cdr fields) (or told? (not type)))))))) +;;; A field of a path, indexed or not: xs, [xs 0] -> xs +(define (field-name field) + (if (and (pair? field) (eq? '¤ (car field)) (pair? (cdr field))) + (second field) + field)) + (define (lvalue? expr) (cond ((symbol? expr) #t) ((vector? expr) #t) ; a compound literal is one diff --git a/tests/codegen.scm b/tests/codegen.scm index 552c552..48cefd4 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -742,7 +742,8 @@ whitespace aside, THEN?" (not (emits? "(struct pt ((x int))) (fn f ((p (* (struct pt)))) int (return (. (* p) x)))" "*(p).x"))) (test-assert "member access through a cast" - (emits? (in-fn "(var n int (. (* (cast a (* (struct s)))) f))") + (emits? (string-append "(struct s ((f int)))" + (in-fn "(var n int (. (* (cast a (* (struct s)))) f))")) "(*(struct s*)a).f")) ;; ...without gaining parens where none are due (test-assert "a bare dereference is left alone" @@ -884,6 +885,14 @@ whitespace aside, THEN?" (test-assert "which one step through it does not need" (not (warns? (in-fn "(var t (* struct tm) 0) (= (. t a) 1)") "cannot type"))) + (test-assert "but a struct declared here has only the fields it names" + (reports? (in-line "(= (. p z) 1)") "no field of this name")) + (test-assert "the last step included" + (reports? (in-line "(= (. lp a z) 1)") "no field of this name")) + (test-assert "an indexed one by its name" + (reports? (string-append "(struct v ((xs [int 2])))" + (in-fn "(var w (struct v)) (= (. w [ys 0]) 1)")) + "no field of this name")) ;; the arrow is `%->' and nothing else writes one, so a bare `->' ;; is an ordinary head -- a threading macro that nobody imported, ;; and a call like any other unknown -- 2.52.0 From 6e150aaaf1b1bbb29e5b31673f7fba862385dc59 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Thu, 15 Oct 2026 14:48:25 +0300 Subject: [PATCH 39/43] take a name after a qualified type as the bound [int const N] read N as the type a trailing const was waiting for, and wrote int const N b[]; a qualifier waits for a name only when no type came before it. --- tests/codegen.scm | 9 ++++++++- types.scm | 17 +++++++++++------ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/tests/codegen.scm b/tests/codegen.scm index 48cefd4..6ba436a 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -775,7 +775,14 @@ whitespace aside, THEN?" (test-assert "nor is an aggregate tag" (emits? "(struct t ((z int))) (struct s ((a [struct t])))" "struct t a[]")) (test-assert "nor one behind a pointer" - (emits? "(struct t ((z int))) (struct s ((a [* struct t])))" "struct t* a[]"))) + (emits? "(struct t ((z int))) (struct s ((a [* struct t])))" "struct t* a[]")) + ;; a qualifier waits for a type name only when none came before it + (test-assert "a name after a qualified type is a bound" + (emits? (in-fn "(var b [int const N])") "int const b[N]")) + (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[]"))) ;; `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/types.scm b/types.scm index 2fa6098..182ddac 100644 --- a/types.scm +++ b/types.scm @@ -410,14 +410,14 @@ arglist)) ;;; The last element is a bound unless what precedes it is still -;;; waiting for a type name -- a `*', a qualifier, a tag's keyword. C -;;; spells a type with one name at most, so a name after a name, or -;;; after a grouped type, can only be the bound: +;;; waiting for a type name -- a `*', a tag's keyword, a qualifier with +;;; no type before it. C spells a type with one name at most, so a name +;;; after a name, or after a grouped type, can only be the bound: ;;; ;;; (¤ int 4) four of int (¤ unsigned int) unsized ;;; (¤ pthread-t CAP) CAP of pthread-t (¤ struct point) unsized ;;; (¤ (* T) CAP) CAP of (* T) (¤ const mytype) unsized -;;; (¤ * size-t) unsized +;;; (¤ int const N) N of const int (¤ * size-t) unsized ;;; ;;; TYPE is the whole `(¤ ...)' form. (define (array-bound? type) @@ -427,8 +427,13 @@ (cond ((not (symbol? bound)) #t) ((or (memq bound +c-specifiers+) (memq bound +c-qualifiers+)) #f) - (else (not (or (memq preceding '(* struct union enum)) - (memq preceding +c-qualifiers+)))))))) + ((memq preceding '(* struct union enum)) #f) + ((memq preceding +c-qualifiers+) + (any (lambda (word) + (not (or (memq word '(* struct union enum)) + (memq word +c-qualifiers+)))) + (drop-right (cdr type) 2))) + (else #t))))) ;;; What one element of a written array type is: ;;; (¤ struct point 2) -> (struct point), (¤ * const char 2) -> (* const char) -- 2.52.0 From 62b1ead3eba6ab9f05ffc8ca72ccb22c3459c018 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Thu, 15 Oct 2026 14:49:46 +0300 Subject: [PATCH 40/43] refuse -o - for an executable or an object Only the text outputs knew `-' as stdout; compiling handed it to cc as a file name, and left a binary called `-' behind. --- sexc.scm | 12 ++++++++++-- tests/exit-code/Makefile | 18 ++++++++++++------ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/sexc.scm b/sexc.scm index 2d75475..9708be3 100644 --- a/sexc.scm +++ b/sexc.scm @@ -59,8 +59,8 @@ (value #f) (single-char #\m)) (output ,(fmt #f "Write output to file. Default file name is a.out." nl - (pad padding) "If -C or -m options are provided, defaults to stdout;" nl - (pad padding) "`-' is stdout too") + (pad padding) "With -C, -m or --public-interface, defaults to stdout," nl + (pad padding) "which `-' names too") (required #f) (value #t) (single-char #\o)) @@ -145,6 +145,12 @@ (define (stdout-output? output) (or (eq? output 'default) (equal? output "-"))) +;;; Whether ARGS ask for text, which `-o -' can send to stdout. An +;;; executable or an object goes to cc's -o, where `-' is a file name +(define (text-output? args) + (any (lambda (option) (get-arg args option #f)) + '(emit-c macro-expand public-interface))) + (define (write-to-file-or-stdout output what) (if (stdout-output? output) (what) @@ -254,6 +260,8 @@ status, which is ours to pass on." (when help (print-help) (return #f)) + (when (and (equal? output "-") (not (text-output? args))) + (error "-o - is stdout, which takes only -C, -m or --public-interface")) ;; 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/Makefile b/tests/exit-code/Makefile index 4dc32f4..79b8837 100644 --- a/tests/exit-code/Makefile +++ b/tests/exit-code/Makefile @@ -1,12 +1,14 @@ # The failure paths. # -# Both need a process to show themselves, so neither 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 -- -# and it has to clean up its temporary .c when its own emission throws. +# 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 +# refuse `-o -' for an executable, which cc would write to a file named +# `-'. # -# Everything is built inside a scratch TMPDIR, so nothing is left here -# to clean up. +# Everything is built inside a scratch directory, so nothing is left +# here to clean up. SEXC ?= ../../sexc @@ -21,6 +23,10 @@ check: echo "exit code FAILED: sexc reported success after cc failed"; \ rm -rf $$d; exit 1; \ fi; \ + if (cd $$d && $(abspath $(SEXC)) $(CURDIR)/hello.sex -o - >/dev/null 2>&1) || [ -e $$d/- ]; then \ + echo "exit code FAILED: -o - built an executable"; \ + rm -rf $$d; exit 1; \ + fi; \ rm -rf $$d; echo "exit code ok" .PHONY: check -- 2.52.0 From 64db505e6baea1f17446b8d74819afb0f09d281f Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 18:21:02 +0300 Subject: [PATCH 41/43] work out what a module exports once per unit Every module's interface check walks the pub imports below it, so a chain reduced each module's interface once per level above it. --- sex-modules.scm | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/sex-modules.scm b/sex-modules.scm index 7a68e91..f2f3a3c 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -290,10 +290,23 @@ (let ((path (locate-module (symbol->string (car modules))))) (if (or (not path) (member path seen)) (next (cdr modules) seen acc) - (let ((forms (interface-forms (read-module path)))) - (next (append (cdr modules) (imported-modules forms #f)) + (let ((exports (module-exports path))) + (next (append (cdr modules) (cdr exports)) (cons path seen) - (cons (declared-types forms) acc)))))))) + (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 +;;; every module above it on a pub import chain walks there +(define +module-exports+ (list)) + +(define (module-exports path) + (cond ((assoc path +module-exports+) => cdr) + (else (let* ((forms (interface-forms (read-module path))) + (exports (cons (declared-types forms) + (imported-modules forms #f)))) + (set! +module-exports+ (cons (cons path exports) +module-exports+)) + exports)))) (define (public-fn-interface raw-form) ;; (pub fn name args ret . body) -> prototype, keeping a docstring so -- 2.52.0 From a4880f1b9694c05b58eff84abf99381e3fdd97be Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 18:21:10 +0300 Subject: [PATCH 42/43] process an ops method's prototype once Registering a method processed its prototype only for the signature it records, and a method called from above was processed again to be declared ahead. --- semen.scm | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/semen.scm b/semen.scm index 7d3cfc8..915b2a3 100644 --- a/semen.scm +++ b/semen.scm @@ -425,12 +425,16 @@ (sex-error form "ops needs a type name" form)) (let* ((methods (map (lambda (m) (register-op type m)) (cddr form))) (fns (remove comment-form? methods)) + ;; the signatures too, which a call's receiver is fitted to + (protos (map (lambda (m) (process-fn (sex-fn-prototype m) (list))) fns)) (bodies (map (lambda (m) (if (comment-form? m) (list m) (process-fn m (list)))) methods)) - (early (filter (lambda (m) (called-before? m methods bodies)) fns))) - (append (append-map identity (reverse bodies)) - (fold (lambda (m acc) (process-fn (sex-fn-prototype m) acc)) acc early))))) + (early (filter-map (lambda (m proto) + (and (called-before? m methods bodies) proto)) + fns protos))) + (append (concatenate (reverse bodies)) + (fold append acc early))))) ;;; The method's fn form, renamed to vec2/length, once it is registered ;;; under `length'; a comment is passed along @@ -447,8 +451,6 @@ (let* ((qualified (qualify-op type name)) (renamed (rename-fn form qualified))) (add-method! type name qualified) - ;; its signature too, which a call's receiver is fitted to - (process-fn (sex-fn-prototype renamed) (list)) renamed))))) ;;; Does a body written above METHOD call it? -- 2.52.0 From 540f5c75cd4d66b30cf8155754f998dd2d6a201d Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 18:21:14 +0300 Subject: [PATCH 43/43] tidy what the fixes wrote around existing helpers written-type? matches the shapes instead of measuring them, array-form? and pub-form? replace their spelled-out copies, both test files share one fails-with?, and moved test comments are back above their groups. --- semen.scm | 16 +++++++--------- sex-modules.scm | 3 +-- tests/codegen.scm | 21 ++++++++++----------- tests/encapsulation.scm | 5 ++--- tests/modules/Makefile | 5 +++-- 5 files changed, 23 insertions(+), 27 deletions(-) diff --git a/semen.scm b/semen.scm index 915b2a3..a60efa5 100644 --- a/semen.scm +++ b/semen.scm @@ -795,14 +795,12 @@ ;;; (* char) (* const char) (* size-t) (unsigned int) types ;;; (* p) (* (g)) (¤ xs 0) expressions (define (written-type? form env) - (and (pair? form) - ;; the length a dereference and a subscript have - (if (= (length form) (case (car form) ((*) 2) ((¤) 3) (else -1))) - (let ((operand (second form))) - (if (symbol? operand) - (not (or (lookup-name env operand) (get-name-type operand))) - (written-type? operand env))) - (type-head? form)))) + (match form + ((or ('* operand) ('¤ operand _)) + (if (symbol? operand) + (not (or (lookup-name env operand) (get-name-type operand))) + (written-type? operand env))) + (_ (type-head? form)))) ;;; `(var n _ (strlen s))' becomes `(var n size-t (strlen s))'. (define (resolve-wildcard form env) @@ -1143,7 +1141,7 @@ ;;; A field of a path, indexed or not: xs, [xs 0] -> xs (define (field-name field) - (if (and (pair? field) (eq? '¤ (car field)) (pair? (cdr field))) + (if (and (array-form? field) (pair? (cdr field))) (second field) field)) diff --git a/sex-modules.scm b/sex-modules.scm index f2f3a3c..428e398 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -185,8 +185,7 @@ (if (and (pair? v) (pair? (cdr v))) (field-types (second v)) (list))) (remove comment-form? variants))) (('ops type . methods) - (append-map interface-types - (filter (lambda (m) (and (pair? m) (eq? (car m) 'pub))) methods))) + (append-map interface-types (filter pub-form? methods))) (('pub 'realize spec . methods) (append-map (lambda (m) (interface-types (cons 'pub m))) (remove comment-form? methods))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 6ba436a..d3cd632 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -51,13 +51,12 @@ the way CHICKEN prints it -- or #f if it raises none." ((condition-property-accessor 'exn 'arguments) e)))) (begin (thunk) #f))) -(define (error-message source) - "Compile SOURCE and return its error text, or #f if it compiles." - (failure-message (lambda () (sex->c source)))) +(define (fails-with? thunk fragment) + (let ((m (failure-message thunk))) + (and m (string-contains m fragment) #t))) (define (reports? source fragment) - (let ((m (error-message source))) - (and m (string-contains m fragment) #t))) + (fails-with? (lambda () (sex->c source)) fragment)) (define (followed-by? source first then) "Is FIRST in the C compiled from SOURCE, and the next thing past it, @@ -90,9 +89,6 @@ whitespace aside, THEN?" (test-group "codegen" - ;; 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))'. ;; A case body shared the switch's scope, so two cases could not ;; declare one name, and a label could not be followed by a ;; declaration before C23. Only a body that declares needs a block @@ -109,6 +105,9 @@ whitespace aside, THEN?" (not (followed-by? (in-fn "(switch a (case 1 (do (var x int 1) (g x))))") "{" "{")))) + ;; 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))'. (test-group "switch scrutinee" (test-assert "member access" (emits? "(struct s ((type int))) (fn f ((e (struct s))) void (switch (. e type) (case 1 (g))))" @@ -336,8 +335,6 @@ whitespace aside, THEN?" (test-assert "pub with nothing to define" (reports? "(pub 1)" "codegen.sex:1:"))) - ;; A nested pointer chain used to silently lose a level: - ;; (var p (* (* char))) emitted `char *p' ;; A grouped header, C's parens carried over, died in the writer with ;; `(caddr) bad argument type' and no location (test-group "malformed for" @@ -357,6 +354,8 @@ whitespace aside, THEN?" (reports? "(fn f () void\n (for ((var i int 0) (< i 4) (++ i)) (g i)))" "codegen.sex:2:"))) + ;; A nested pointer chain used to silently lose a level: + ;; (var p (* (* char))) emitted `char *p' (test-group "malformed types are rejected" (test-assert "nested pointer chain" (reports? (in-fn "(var p (* (* char)))") "pointer chains are written flat")) @@ -784,7 +783,7 @@ whitespace aside, THEN?" (test-assert "but a qualifier alone still waits for the type" (emits? "(typedef mytype int) (struct s ((a [const mytype])))" "const mytype a[]"))) -;; `sizeof' takes a type or an expression, and `(* x)' is either. + ;; `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 (test-group "sizeof" (test-assert "a pointer type" diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 1217521..d4d9a67 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -5,7 +5,7 @@ ;;; is checked here is what the compiler refuses, and that it refuses ;;; it with the name of whatever is wrong. ;;; -;;; `sex->c', `read-source', `failure-message', `emits?', `reports?' +;;; `sex->c', `read-source', `fails-with?', `emits?', `reports?' ;;; and `in-fn' come from codegen.scm, which run.scm includes first. (import sex-modules) @@ -16,8 +16,7 @@ ahead of its pub forms." (check-public-interface (read-source source))) (define (interface-reports? source fragment) - (let ((m (failure-message (lambda () (interface-of source))))) - (and m (string-contains m fragment) #t))) + (fails-with? (lambda () (interface-of source)) fragment)) (define (ops-src . body) (string-append diff --git a/tests/modules/Makefile b/tests/modules/Makefile index 1bd6210..d43c2f1 100644 --- a/tests/modules/Makefile +++ b/tests/modules/Makefile @@ -33,8 +33,9 @@ SEXC ?= ../../sexc EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7\nvec2(3 4)\ntally 2\nboard 42\nledger 2\ncolour 123 check: - @if [ "`$(SEXC) --public-interface greet.sex | head -3`" != "`printf '(record cell)\n(record ledger)\n(include stdio.h)'`" ]; then \ - echo "modules FAILED, the interface begins:"; $(SEXC) --public-interface greet.sex | head -3; exit 1; \ + @head="`$(SEXC) --public-interface greet.sex | head -3`"; \ + if [ "$$head" != "`printf '(record cell)\n(record ledger)\n(include stdio.h)'`" ]; then \ + echo "modules FAILED, the interface begins:"; echo "$$head"; exit 1; \ fi @$(SEXC) ledger.sex -c -o ledger.o @$(SEXC) greet.sex -c -o greet.o -- 2.52.0