Compare commits

..

48 Commits

Author SHA1 Message Date
d8903c38f1 drop the default SEXC from the check scripts' usage 2026-10-15 15:18:17 +03:00
ebe7969553 build the programs the way the modules are built
Each program had its own recipe: a hand-written link list, a cd into
tests/ so its includes would not find the modules' namesakes, and a
renamed output so csc would not overwrite the module sexc.o. Read off
their imports like the modules', and compiled to an object named after
their source, they share one rule; include-relative ends the cd.
2026-10-15 15:18:17 +03:00
2b840eb8c0 take every program in tests/sex-programs as a test
A program left out of the hand-kept list was never run, and nothing said
so; the one module the tests import moves to lib/ instead.
2026-10-15 15:07:52 +03:00
3b717f9634 check modules and exit codes with the test egg
Written as shell inside make, a check said only that it failed and left
the reason to rerunning it by hand; now each says what it expected.
2026-10-15 15:07:52 +03:00
2cd980bdf1 read the module graph off the import forms
Each module's prerequisite line restated its import form, so adding a
module or an import meant editing the Makefile to match, and a missed
line only showed when an object came out of order.
2026-10-15 15:07:04 +03:00
434ac778bf build the unit tests and sextest from the root
Each subdirectory's Makefile repeated the compiler's module list just to
link one program, and its result was copied back to the root anyway.
2026-10-15 15:07:04 +03:00
1a899d9f3c keep the local egg repository in a file of its own
The Makefile was mostly about where the eggs live; what sexc is built
from is easier to find without it.
2026-10-15 15:07:04 +03:00
69b38e7c9f make each compiler module one file, built once
A module was a body plus a (module ...) wrapper naming its exports, and
the wrapper came in up to three copies: the root's, a test one that
exported everything, and sextest's, each recompiling the same body.

csc -module makes a file a module by itself, with export forms in its
body, so the wrappers are gone. tests/ and tools/sextest/ link what the
root built, finding it on the repository path; the tests see what a
module exports, and the names only they need are exported as such.
2026-10-15 15:07:04 +03:00
c317d9950c 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.
2026-10-15 14:49:46 +03:00
6ced17c20e 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.
2026-10-15 14:48:25 +03:00
dd1718dffb 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.
2026-10-15 14:47:12 +03:00
4ac386f373 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.
2026-10-15 14:44:34 +03:00
1599832ece tell what a member path walked from the fields it has left 2026-10-15 13:58:22 +03:00
99a41b9d04 share reading a test source and catching its error
encapsulation.scm had copies of both from codegen.scm.
2026-10-15 13:58:22 +03:00
4d31e2ed9b parenthesise a conditional without a helper to do it for 2026-10-15 13:58:22 +03:00
d0e806bf84 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).
2026-10-15 13:58:22 +03:00
d92b5fc696 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.
2026-10-15 13:58:22 +03:00
fd6520dbe8 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.
2026-10-15 13:58:22 +03:00
4ad4133d92 name the test for output going to stdout
-o - was taught to two copies of it.
2026-10-15 13:58:22 +03:00
6a8c68fe3d 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.
2026-10-15 13:58:22 +03:00
ed7bf0879a 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.
2026-10-15 13:58:22 +03:00
a95e55fddc 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.
2026-10-15 13:58:22 +03:00
9b503c1017 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.
2026-10-15 13:58:22 +03:00
8db435f994 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.
2026-10-15 13:58:22 +03:00
286936488b 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.
2026-10-15 13:58:22 +03:00
86830ee4c9 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.
2026-10-15 13:58:22 +03:00
17badcb966 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.
2026-10-15 13:58:22 +03:00
31d876e30e 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.
2026-10-15 13:58:22 +03:00
d94daa9066 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.
2026-10-15 13:58:21 +03:00
24f11cdcba 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.
2026-10-15 13:58:21 +03:00
acd7010e6b 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.
2026-10-15 13:58:21 +03:00
f8c03d17c0 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.
2026-10-15 13:58:21 +03:00
250713e01d 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.
2026-10-15 13:58:21 +03:00
314bdc4e2d 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.
2026-10-15 13:58:21 +03:00
b9b3f9da5f 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.
2026-10-15 13:58:21 +03:00
2673b25f1d 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.
2026-10-15 13:58:21 +03:00
c162005241 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.
2026-10-15 13:58:21 +03:00
12d0d13a7c write arrays with brackets in tests
The tests spelled out (¤ ...), what [...] reads into, which nobody
writes. The reader's own tests keep it: there it is the point.
2026-10-15 13:58:09 +03:00
36ff456d24 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.
2026-10-15 13:58:09 +03:00
566e8326a3 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.
2026-10-15 13:58:09 +03:00
d41960e407 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.
2026-10-15 13:58:09 +03:00
85511ae037 spell ? and ! in names as letters C takes
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.
2026-10-15 13:58:09 +03:00
1acdd0e708 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.
2026-10-15 13:58:09 +03:00
c06845a80a 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.
2026-10-15 13:58:09 +03:00
816c1db9ed 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.
2026-10-15 13:58:09 +03:00
e465f6892a 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.
2026-10-15 13:58:09 +03:00
3701aeab3f 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.
2026-10-15 13:58:09 +03:00
8d1c12d03b 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.
2026-10-15 13:58:09 +03:00
10 changed files with 164 additions and 167 deletions

View File

@@ -176,9 +176,24 @@ same name wins over one of ours.
~sexc~ looks for them beside itself, so a work tree needs nothing set ~sexc~ looks for them beside itself, so a work tree needs nothing set
up; installed, ~$(bindir)/sexc~ finds them under ~$(prefix)/share/sex~. up; installed, ~$(bindir)/sexc~ finds them under ~$(prefix)/share/sex~.
Each module is documented in a file of its own beside it: There is one so far.
- [[file:lib/threading-macros.org][threading-macros]] --- ~->~, threading a value through a chain of calls *** threading-macros
~->~ passes a value through a chain of forms, each step taking what came
before it as its first argument, so the chain reads in the order it
happens instead of inside out. Clojure spells it this way and this is
the same thing:
#+begin_src scheme
(import threading-macros)
(-> 5 double-it (add 3) double-it) ; (double-it (add (double-it 5) 3))
(-> lp (. a x)) ; lp->a->x
(-> q .length-sq) ; a method is a step like any other
#+end_src
A step that is not a list is a call of one argument: ~(-> x f)~ is
~(f x)~.
** Read-time feature expressions ** Read-time feature expressions
Sex is able to use ~#+~ and ~#-~ for conditional compilation: the form that Sex is able to use ~#+~ and ~#-~ for conditional compilation: the form that

View File

@@ -235,7 +235,8 @@ forms, and what remains."
;; is the fmt-c directive for the `.' operator (see sex-fmt-c). ;; is the fmt-c directive for the `.' operator (see sex-fmt-c).
(('dot-access . rest) (cons '%. (map walk-expr rest))) (('dot-access . rest) (cons '%. (map walk-expr rest)))
;; `%->' is the C arrow. Nothing writes it: it is what a member ;; `%->' is the C arrow. Nothing writes it: it is what a member
;; path lowers to where the thing it reads from is a pointer ;; path lowers to where the thing it reads from is a pointer, the
;; name `->' itself being the threading macro
(('%-> . rest) (cons '%-> (map walk-expr rest))) (('%-> . rest) (cons '%-> (map walk-expr rest)))
(('var . _) (walk-var form)) (('var . _) (walk-var form))
;; semen has told a type from an expression; only it knows the names ;; semen has told a type from an expression; only it knows the names

View File

@@ -1,16 +0,0 @@
* threading-macros
~->~ passes a value through a chain of forms, each step taking what came
before it as its first argument, so the chain reads in the order it
happens instead of inside out. Clojure spells it this way and this is
the same thing:
#+begin_src scheme
(import threading-macros)
(-> 5 double-it (add 3) double-it) ; (double-it (add (double-it 5) 3))
(-> lp (. a x)) ; lp->a->x
(-> q .length-sq) ; a method is a step like any other
#+end_src
A step that is not a list is a call of one argument: ~(-> x f)~ is
~(f x)~.

View File

@@ -595,11 +595,11 @@
(cons walk-embed-result (walk-body expansion env))))) (cons walk-embed-result (walk-body expansion env)))))
(else (else
(case (car form) (case (car form)
((do default) ((do case case/fallthrough default)
(parameterize ((operand-position? #f)) (parameterize ((operand-position? #f))
(with-scope env (lambda () (walk-parts form env))))) (with-scope env (lambda () (walk-parts form env)))))
((for while if switch case case/fallthrough) ((for while if switch)
(with-scope env (lambda () (walk-control form env)))) (with-scope env (lambda () (walk-control form env))))
((lambda) ((lambda)
@@ -935,7 +935,7 @@
;;; Whether the Ith of a control form's SLOTS is read as a value: an ;;; Whether the Ith of a control form's SLOTS is read as a value: an
;;; `if''s tests but not its trailing else, a `for''s header, the ;;; `if''s tests but not its trailing else, a `for''s header, the
;;; scrutinee of a `while' or a `switch', a `case''s label ;;; scrutinee of a `while' or a `switch'
(define (test-slot? head i slots) (define (test-slot? head i slots)
(case head (case head
((if) (and (even? i) (< (+ i 1) slots))) ((if) (and (even? i) (< (+ i 1) slots)))
@@ -1924,15 +1924,15 @@
;; from ;; from
(core (if (eq? 'extern qualifier) (core (if (eq? 'extern qualifier)
core core
(let ((solved (resolve-wildcard (resolve-wildcard
(copy-form-source! (copy-form-source!
core core
(if (> (length core) 3) (if (> (length core) 3)
(append (take core 3) (append (take core 3)
(walk-operands core (drop core 3) env)) (map bare-braces
core)) (walk-operands core (drop core 3) env)))
env))) core))
(copy-form-source! solved (map bare-braces solved))))) env)))
(form (if qualifier (form (if qualifier
(copy-form-source! resolved (cons qualifier core)) (copy-form-source! resolved (cons qualifier core))
core))) core)))

View File

@@ -478,13 +478,6 @@ ahead of its pub forms."
(reports? (sum-src "(for (var i int 0) (match s ((circle (r)) 1) (else 0)) (++ i)" (reports? (sum-src "(for (var i int 0) (match s ((circle (r)) 1) (else 0)) (++ i)"
" (= out 1.0))") " (= out 1.0))")
"match is a statement")) "match is a statement"))
(test-assert "nor as a case label"
(reports? (sum-src "(switch 1 (case (match s ((circle (r)) 1) (else 0)) (= out 1.0)))")
"match is a statement"))
(test-assert "nor as a case/fallthrough's"
(reports? (sum-src "(switch 1 (case/fallthrough (match s ((circle (r)) 1) (else 0))"
" (= out 1.0)))")
"match is a statement"))
(test-assert "but an if's branches are statements, the else among them" (test-assert "but an if's branches are statements, the else among them"
(emits? (sum-src "(if (== out 0.0) (match s ((circle (r)) (= out r)) (else (= out 1.0)))" (emits? (sum-src "(if (== out 0.0) (match s ((circle (r)) (= out r)) (else (= out 1.0)))"
" (match s ((circle (r)) (= out 2.0)) (else (= out 3.0))))") " (match s ((circle (r)) (= out 2.0)) (else (= out 3.0))))")

View File

@@ -1,6 +1,6 @@
(compilation "-- -std=c11 -pedantic-errors") (compilation "-- -std=c11 -pedantic-errors")
(input) (input)
(output "c11: 42 43 6 4 6 12") (output "c11: 42 43 6 4 6")
(return 0) (return 0)
;;; C11 is the floor, and this is the program that holds it there: the ;;; C11 is the floor, and this is the program that holds it there: the
@@ -23,9 +23,8 @@
(sum shape ((square ((side int))) (dot ()))) (sum shape ((square ((side int))) (dot ())))
(var corner _ #(point : 2 3)) (var corner point #(point : 2 3))
(var unit _ (shape/square 1)) (var unit shape (shape/square 1))
(var pair [_ 2] #(#(point : 1 2) #(point : 3 4)))
(fn sides ((s shape)) int (fn sides ((s shape)) int
(var n int 0) (var n int 0)
@@ -39,7 +38,7 @@
(var k int 1) (var k int 1)
(var add-k (closure ((int)) int) (var add-k (closure ((int)) int)
(closure ((v int)) int (k) (return (+ v k)))) (closure ((v int)) int (k) (return (+ v k))))
(printf "c11: %d %d %d %d %d %d\n" (printf "c11: %d %d %d %d %d\n"
(.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2) (.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2)
(sides unit) (.area corner) (.area [pair 1])) (sides unit) (.area corner))
(return 0)) (return 0))

View File

@@ -12,8 +12,7 @@
(record point ((x int) (y int))) (record point ((x int) (y int)))
(record named (record named "Fields of more than one kind, and a docstring."
"Fields of more than one kind, and a docstring."
((id int) (first-name (* const char)))) ((id int) (first-name (* const char))))
(struct raw ((a int) (b int))) (struct raw ((a int) (b int)))

View File

@@ -6,8 +6,14 @@
"one step is just the value: 7") "one step is just the value: 7")
(return 0) (return 0)
;;; A step may be a call, a bare name, a member path or a method, and ;;; `->' used to be C's arrow. The arrow is what `.' writes now when
;;; the value goes in as its first argument. ;;; the thing it reads from is a pointer, which left the name free for
;;; threading -- the first module of the standard library.
;;;
;;; What this pins is that a step may be a call, a bare name or a
;;; method, that the value is threaded into the *first* argument, and
;;; that the compiler's own generated arrows survived the rename --
;;; `ops' below lifts a method, which is where the captures live.
(include stdio.h) (include stdio.h)
(import threading-macros) (import threading-macros)

View File

@@ -3,8 +3,9 @@
"-5") "-5")
(return 0) (return 0)
;;; A recursive sum, an inherent method on it, and a spec realized for ;;; The worked example from Encapsulation.org, kept here so it stays
;;; it: every layer of encapsulation in one program, built at once. ;;; true: a recursive sum, an inherent method on it, and a spec
;;; realized for it, which is every layer that is built at once.
(include stdio.h) (include stdio.h)

233
types.scm
View File

@@ -141,6 +141,122 @@
(define (type-of form) ((current-type-of) form)) (define (type-of form) ((current-type-of) form))
;;; A sum's variants, in declaration order:
;;;
;;; (sum shape ((circle ((r float))) (empty ())))
;;; -> shape -> ((circle (r float)) (empty))
;;;
;;; Fields are normalized, so a caller counts them and reads their
;;; types without re-parsing the declaration.
(define +sum-db+ (make-hash-table))
(define (add-sum! name variants)
(hash-table-set! +sum-db+ (type-key name) variants))
(define (get-sum name)
(hash-table-ref/default +sum-db+ (type-key name) #f))
;;; shape/circle -> (shape . circle), for each variant of each sum
(define +constructor-db+ (make-hash-table))
(define (add-constructor! constructor sum variant)
(hash-table-set! +constructor-db+ constructor (cons sum variant)))
(define (get-constructor name)
(hash-table-ref/default +constructor-db+ name #f))
(define (variant-fields variants name)
(let ((entry (assq name variants)))
(and entry (cdr entry))))
;;; A spec is a parameter and a list of methods, each of which either
;;; declares a signature or also carries a default body:
;;;
;;; (spec (printable T) (fn show ((self (* const T))) void))
;;; -> printable -> (T (fn show ((self (* const T))) void))
;;;
;;; And a realization is only ever asked whether it exists -- the
;;; methods it provides land in +ops-db+ like any others.
(define +spec-db+ (make-hash-table))
(define +realize-db+ (make-hash-table))
(define (add-spec! name parameter methods)
(hash-table-set! +spec-db+ name (cons parameter methods)))
(define (get-spec name)
(hash-table-ref/default +spec-db+ name #f))
(define (spec-parameter spec) (car spec))
(define (spec-methods spec) (cdr spec))
(define (add-realization! spec type)
(hash-table-set! +realize-db+ (cons spec (type-key type)) #t))
;;; What a generic macro asks before it expands: (realizes? 'ord 'circle)
(define (realizes? spec type)
(hash-table-exists? +realize-db+ (cons spec (type-key type))))
;;; Both of these refuse a second declaration of the same name, which
;;; is per translation unit rather than per process -- so a process
;;; that compiles two units has to start the second one clean.
(define (reset-declarations!)
(set! +sum-db+ (make-hash-table))
(set! +constructor-db+ (make-hash-table))
(set! +ops-db+ (make-hash-table))
(set! +spec-db+ (make-hash-table))
(set! +realize-db+ (make-hash-table)))
;;; Methods of an `ops' block: (type . method) -> the qualified name
;;; the call is rewritten to.
;;;
;;; (ops vec2 (fn length ((self (* const vec2))) float ...))
;;; -> (vec2 . length) -> vec2/length
;;;
;;; The signature is not kept here; `vec2/length' is an ordinary
;;; function by the time anything asks, so +name-db+ already has it.
(define +ops-db+ (make-hash-table))
(define (add-method! type method qualified)
(hash-table-set! +ops-db+ (cons (type-key type) method) qualified))
(define (get-method type method)
(hash-table-ref/default +ops-db+ (cons (type-key type) method) #f))
;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength
(define (qualify-op type name)
(string->symbol
(string-append (symbol->string type) "/" (symbol->string name))))
;;; The name an `ops' block was written against: `(struct point)' and a
;;; `const' wrapper both name `point', and anything else names nothing.
(define (ops-key type)
(cond ((symbol? type) (type-key type))
((not (and (pair? type) (symbol? (car type)))) #f)
((memq (car type) '(struct union enum))
(and (pair? (cdr type)) (symbol? (cadr type)) (cadr type)))
((memq (car type) '(const volatile)) (ops-key (cadr type)))
(else #f)))
;;; The name methods, realizations and sums are filed under. A typedef
;;; is followed to the aggregate it names, and one that ends in anything
;;; else stops at the last typedef, so a scalar does not share them:
;;;
;;; (record v ...) (typedef alias v) alias -> v
;;; (typedef meters float) meters -> meters
;;; (typedef km meters) km -> meters
(define (type-key name)
(let follow ((name name) (seen (list)))
(let ((target (and (not (memq name seen)) (typedef-target name))))
(cond ((not target) name)
((symbol? target)
(if (typedef-target target) (follow target (cons name seen)) name))
((target-tag target))
(else name)))))
(define (typedef-target name)
(let ((info (and (symbol? name) (get-type-info name))))
(and info (eq? (car info) 'typedef) (caddr info))))
(define (add-name-type! name type) (define (add-name-type! name type)
(hash-table-set! +name-db+ name type)) (hash-table-set! +name-db+ name type))
@@ -222,123 +338,6 @@
(and tag (or (get-tag-info tag) (get-type-info tag)))) (and tag (or (get-tag-info tag) (get-type-info tag))))
info)))) info))))
;;; The name methods, realizations and sums are filed under. A typedef
;;; is followed to the aggregate it names, and one that ends in anything
;;; else stops at the last typedef, so a scalar does not share them:
;;;
;;; (record v ...) (typedef alias v) alias -> v
;;; (typedef meters float) meters -> meters
;;; (typedef km meters) km -> meters
(define (type-key name)
(let follow ((name name) (seen (list)))
(let ((target (and (not (memq name seen)) (typedef-target name))))
(cond ((not target) name)
((symbol? target)
(if (typedef-target target) (follow target (cons name seen)) name))
((target-tag target))
(else name)))))
(define (typedef-target name)
(let ((info (and (symbol? name) (get-type-info name))))
(and info (eq? (car info) 'typedef) (caddr info))))
;;; A sum's variants, in declaration order:
;;;
;;; (sum shape ((circle ((r float))) (empty ())))
;;; -> shape -> ((circle (r float)) (empty))
;;;
;;; Fields are normalized, so a caller counts them and reads their
;;; types without re-parsing the declaration.
(define +sum-db+ (make-hash-table))
(define (add-sum! name variants)
(hash-table-set! +sum-db+ (type-key name) variants))
(define (get-sum name)
(hash-table-ref/default +sum-db+ (type-key name) #f))
;;; shape/circle -> (shape . circle), for each variant of each sum
(define +constructor-db+ (make-hash-table))
(define (add-constructor! constructor sum variant)
(hash-table-set! +constructor-db+ constructor (cons sum variant)))
(define (get-constructor name)
(hash-table-ref/default +constructor-db+ name #f))
(define (variant-fields variants name)
(let ((entry (assq name variants)))
(and entry (cdr entry))))
;;; Methods of an `ops' block: (type . method) -> the qualified name
;;; the call is rewritten to.
;;;
;;; (ops vec2 (fn length ((self (* const vec2))) float ...))
;;; -> (vec2 . length) -> vec2/length
;;;
;;; The signature is not kept here; `vec2/length' is an ordinary
;;; function by the time anything asks, so +name-db+ already has it.
(define +ops-db+ (make-hash-table))
(define (add-method! type method qualified)
(hash-table-set! +ops-db+ (cons (type-key type) method) qualified))
(define (get-method type method)
(hash-table-ref/default +ops-db+ (cons (type-key type) method) #f))
;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength
(define (qualify-op type name)
(string->symbol
(string-append (symbol->string type) "/" (symbol->string name))))
;;; The name an `ops' block was written against: `(struct point)' and a
;;; `const' wrapper both name `point', and anything else names nothing.
(define (ops-key type)
(cond ((symbol? type) (type-key type))
((not (and (pair? type) (symbol? (car type)))) #f)
((memq (car type) '(struct union enum))
(and (pair? (cdr type)) (symbol? (cadr type)) (cadr type)))
((memq (car type) '(const volatile)) (ops-key (cadr type)))
(else #f)))
;;; A spec is a parameter and a list of methods, each of which either
;;; declares a signature or also carries a default body:
;;;
;;; (spec (printable T) (fn show ((self (* const T))) void))
;;; -> printable -> (T (fn show ((self (* const T))) void))
;;;
;;; And a realization is only ever asked whether it exists -- the
;;; methods it provides land in +ops-db+ like any others.
(define +spec-db+ (make-hash-table))
(define +realize-db+ (make-hash-table))
(define (add-spec! name parameter methods)
(hash-table-set! +spec-db+ name (cons parameter methods)))
(define (get-spec name)
(hash-table-ref/default +spec-db+ name #f))
(define (spec-parameter spec) (car spec))
(define (spec-methods spec) (cdr spec))
(define (add-realization! spec type)
(hash-table-set! +realize-db+ (cons spec (type-key type)) #t))
;;; What a generic macro asks before it expands: (realizes? 'ord 'circle)
(define (realizes? spec type)
(hash-table-exists? +realize-db+ (cons spec (type-key type))))
;;; Sums, constructors, methods and specs refuse a second declaration
;;; of the same name, which is per translation unit rather than per
;;; process -- so a process that compiles two units has to start the
;;; second one clean.
(define (reset-declarations!)
(set! +sum-db+ (make-hash-table))
(set! +constructor-db+ (make-hash-table))
(set! +ops-db+ (make-hash-table))
(set! +spec-db+ (make-hash-table))
(set! +realize-db+ (make-hash-table)))
;;; Type matcher macro ;;; Type matcher macro
;;; (type-match type ;;; (type-match type
;;; (int ...) ;;; (int ...)