85 Commits

Author SHA1 Message Date
5e842c4df6 sex-mode: drop the closure keyword
All checks were successful
Sex CI / build-linux (pull_request) Successful in 5m28s
Sex CI / build-linux (push) Successful in 5m26s
The compiler no longer has it.
2026-11-11 09:17:58 +03:00
be2f4e407b remove closures, keep lambdas
A closure was a code pointer beside an inline environment: capture
records, per-signature structs, conversion thunks and call helpers. It
is gone; a lambda still lifts to an ordinary function and a (fn ...)
value is still a bare code pointer. The capture budget, the environment
union and the closure glyph go with it.

The implementation is kept at tag 0.0.1.
2026-11-11 09:17:54 +03:00
ad37a2492e sex-mode: drop spec and realize keywords
The compiler no longer has them.
2026-11-11 08:54:31 +03:00
2c78756e61 remove spec and realize
They were too much surface for a language this small: a nominal
contract layer, per-type default synthesis and a pub interface of their
own. Type introspection and macros are the intended replacement, so the
storage, the forms and the tests that pin them go; the ops method
registry they leaned on stays.

The implementation is kept at tag 0.0.1.
2026-11-11 08:54:29 +03:00
Pavel Kulyov
7315694faf sex-mode: add supported keywords, drop chicken-*
All checks were successful
Sex CI / build-linux (pull_request) Successful in 5m59s
Sex CI / build-linux (push) Successful in 5m42s
2026-10-30 00:07:43 +03:00
Pavel Kulyov
1214d118e1 readme: add sex-mode.el installation via quelpa 2026-10-29 23:57:50 +03:00
Pavel Kulyov
13be48093b sex-mode: add header and footer, fix lint errors
That makes the package installable via quelpa.
2026-10-29 23:57:45 +03:00
724f4dd3e9 report a module's macro call failing for other than its own names
All checks were successful
Sex CI / build-linux (pull_request) Successful in 5m38s
Sex CI / build-linux (push) Successful in 5m33s
Reading a module's interface dropped any toplevel call that raised, not
only one asking after a declaration of the module's, which no importer
has yet. Lookups now tell which names they missed, and only those failures
give importers nothing.
2026-10-27 23:38:04 +03:00
d890080103 find the conditional by tokens a path cannot hold
"holds no directive" searched for 123, a digit run the temporary
directory in every #line could hold too.
2026-10-27 23:38:04 +03:00
a2bbb73524 spell the least long long as C's LLONG_MIN
-9223372036854775808 reached C as written, where it negates an unsigned
constant, and had no type for inference: it is read as
-9223372036854775807 - 1, which is long long on both sides.
2026-10-27 23:38:04 +03:00
28aaaf637c refuse a closure capturing one name twice
check-capture-names held captures against the parameters and the body,
not against each other: (n n) gave C two members and two parameters n.
2026-10-27 23:38:04 +03:00
acbd4928f5 read a member path and a receiver through a pointer chain
All checks were successful
Sex CI / build-linux (pull_request) Successful in 5m34s
A pointer to a pointer has no fields, so (. pp x) has one meaning, and
it came out pp->x; it is (*pp)->x, and a method receiver alike.
2026-10-27 01:31:37 +03:00
7973a4331d split the C compiler's name from its options
SEX_CC="ccache cc" went looking for an executable of that whole name;
it is read as make reads CC now.
2026-10-27 01:31:37 +03:00
a53c358113 type a value if as the join of its branches
It had no rule, so _ could not be set from one.
2026-10-27 01:31:37 +03:00
8c92c245c5 read a quoted name as the name
'-fields read as (- fields), so (cat name '-fields) built name(- fields).
A quoted list keeps the rule: it is code a macro returns as often as not.
2026-10-27 01:31:37 +03:00
af8e49cdd3 refuse a macro defined after a call to it
The call was compiled as a function's, and the macro went unused there
without a word.
2026-10-27 01:31:37 +03:00
9505b4f0a0 refuse an integer with a leading 0
017 is 17 to Scheme and 15 to C, so whoever reads the Sex and whoever
reads the C would each take it for something else.
2026-10-27 01:31:37 +03:00
8d6d1855e2 refuse a variant named like a C keyword
One with fields is a member of the sum's union, and C takes no member
named int; one without is held to the same, as one rule.
2026-10-27 01:31:37 +03:00
f66eaa7454 match a sum through a pointer to it
A pointer was refused, where . reads through one; a match now reads
through the whole chain of them to the sum.
2026-10-27 01:31:37 +03:00
2fa1ed21d7 take a docstring on a sum
record, struct and enum take one; sum read it where its variants go.
2026-10-27 01:31:37 +03:00
1dd1cf0ae9 expand a module's toplevel macro calls for its importers
Its interface was read as written, so pub forms a macro wrote never
reached them, which list-macros' is-public? flag exists for. The
module's macros, and those its imports give it, are lent for the
reading and taken back after. One reading a type the module keeps to
itself cannot expand there, and gives importers nothing, as before.
2026-10-27 01:31:37 +03:00
7c897b6dc6 refuse a pub realization of a spec importers cannot see
It failed in whichever importer named the module before the spec's,
pointing at the module, where a hidden type is refused in the module
already: so is this, the remedy the same.
2026-10-27 01:31:37 +03:00
b285174a22 count a unit among its own imports
Two modules importing each other with pub hand the unit its own
interface back, and its types were defined twice.
2026-10-27 01:31:37 +03:00
4bdc0e57a7 type #t, an enum's constants and the bitwise names
None had a rule. A constant is typed as its enum, where C says int, so
that the enum's ops are found through it. And bit-and, bit-not and the
rest were respelled bit_and before fmt-c could see them, and called.
2026-10-27 01:31:37 +03:00
2024d4d0f4 type a call by the type of what it calls
Only a function's name was asked what it returns, so a call through a
local or a field holding a pointer had no type, a local named like a
function took the function's, and a closure's call helper, which
nothing registered, left _ nothing to read.
2026-10-27 01:31:37 +03:00
1bdeda6cc3 name a lambda's unnamed parameters in its definition
A definition names every parameter before C23, as a closure's code
already does.
2026-10-27 01:31:37 +03:00
6ad8f8f56b keep the writer's own words to the head of a form
They were its own wherever they stood, so a name spelled like one --
(var array int), a parameter `define' -- came out %array, %define.
2026-10-27 01:31:37 +03:00
fb26b92fdc print an error as its message alone
Every error ended in CHICKEN's call history, which is for working on
sexc itself, and is now asked for by SEXC_DEBUG; a missing input file
says so, rather than as an open-input-file error of CHICKEN's.
2026-10-27 01:31:37 +03:00
7649e47297 refuse an output naming the source
-o naming the input wrote over it, whatever was asked for.
2026-10-27 01:31:37 +03:00
389e73323f refuse a second input file
It was never read, and nothing said so.
2026-10-27 01:31:37 +03:00
83282adfb9 leave none of an output a failure stopped writing
A failed -C -o left the file truncated, which make would take for done.
2026-10-27 01:31:37 +03:00
5afe32a888 read a lone - as stdin
getopt-long read it as an option it did not know, and died.
2026-10-27 01:31:37 +03:00
8220c500df refuse a malformed closure capture
((+ a 1)) was a capture named `+' holding a.
2026-10-27 01:31:37 +03:00
dd5174f472 refuse a statement of the wrong shape
(goto), (var q), (cast i), (while) and the like died in the writer, in
CHICKEN's words about a procedure of its own and with no location;
(return 1 2), (break 1) and (sizeof a b) dropped what was extra.
2026-10-27 01:31:37 +03:00
8e3e6fcdd1 say which macro call an error came from
A wrong argument count was CHICKEN's to report, about a procedure with
no name, and an error raised in a macro's body said nothing of the call.
2026-10-27 01:31:37 +03:00
4fa8a021de say where a reader error was met
Every later stage's error says file:line, and the reader's said only
what; an unclosed list, met at the end of the file, now names the line
it opened on as well.
2026-10-27 01:31:37 +03:00
e0ecde6517 refuse _ in a function's signature
Nothing solves it there, and it reached the C as _.
2026-10-27 01:31:37 +03:00
0a0a3f6b25 decay an array into a wildcard standing alone
An array as a value is a pointer to its first element; _ took the array
type, and declared a copy that C cannot initialize from it.
2026-10-27 01:31:37 +03:00
3436c4ff3e read an array's length as types does
Inference took only an integer for a length, and read a name there as
part of the element type: [_ N] did not solve, and an array of [int N]
decayed to int N *.
2026-10-27 01:31:37 +03:00
cb37821e3e let a realization's methods call one another
Each was registered as its body was walked, so a method could not call
one coming after it -- a default included, defaults coming after the
written ones. All are registered first now, as an ops block's are.
2026-10-27 01:31:37 +03:00
94f41b5fad define an empty lambda as an empty function
A lifted function with no body was a declaration of one, and nothing
defined it, so the program did not link.
2026-10-27 01:31:37 +03:00
b3d7decc6b take an unnamed closure parameter, and refuse a variadic one
The closure's type was built from each parameter's second element, so
a type alone, or the ..., crashed sexc. A variadic closure cannot work:
its call helper would have to forward what C cannot.
2026-10-27 01:31:37 +03:00
d9bc8967ba refuse a capture a parameter or the body names too
Captures are a closure's other parameters, and C's redefinition error
was the first anyone heard of one sharing a name with a parameter, or
being redeclared at the top of the body.
2026-10-27 01:31:37 +03:00
3d295f4cd0 capture an array and a const local
C copies an array neither by = nor from another array's initializer,
and a const field cannot be assigned: both failed in the C. An array is
copied in element by element; a const one is held as its value.
2026-10-27 01:31:37 +03:00
20311a200d resolve the closure types in a closure's signature
The struct, call helper and conversion thunk of a closure type went out
with any closure type in its signature as written, which C has no name
for; so a closure could neither return nor take one, and no currying.
2026-10-27 01:31:37 +03:00
10de092ab0 designate an initializer's element by its index
[3] in braces reached the writer as a subscript of one operand, and
sexc died taking the second.
2026-10-27 01:31:37 +03:00
befe2ca25b nest a function type's declarator round the name
A function type's return was written ahead of its declarator, so one
returning a function pointer came out int (*)(int) get (void), and a
variable of such a type as void (*)() (*g)(int).
2026-10-27 01:31:37 +03:00
8cb141de5d leave an empty for slot empty
() went to C as NULL, so (for () () ()) tested false and never ran; it
is for (;;).
2026-10-27 01:31:37 +03:00
c0ed7ad916 write an empty block as {}
(do), and a for with no body, gave c-begin nothing to begin with, and
the writer died on its arity.
2026-10-27 01:31:37 +03:00
ffa5e9b02c write #() as {0}
{} is C23's. #() is all zeros, which C11 spells {0}, whatever it
initializes.
2026-10-27 01:31:37 +03:00
06bbe4b97d refuse a malformed enumerator
Anything in the list but a name or (name value) was taken apart as if
it were the pair: (! 1 2) came out ! = 1.
2026-10-27 01:31:37 +03:00
1b59848b42 keep an aggregate written in place behind a pointer
A type was flattened word by word, a struct's body included, so
(* (struct ((c int)))) came out struct c{ int; } *.
2026-10-27 01:31:37 +03:00
32515c0eb8 keep an array literal a global pointer is set to
At file scope every compound literal was cut down to its braces, right
for a value and not for an array a pointer points at: the address of a
static object is a constant, and its braces alone the pointer's own.
2026-10-27 01:31:37 +03:00
42c76d07e6 see a pointer through a typedef of one
Only a written (* T) was a pointer, so with (typedef pt-ref (* pt)) a
path read q as a value and a method found no type to dispatch on.
2026-10-27 01:31:37 +03:00
04c3267bfe type an indexed step of a member path
(. q [pts 2] y) looked the step up as a field whole, so its type was
lost: the next step guessed a value, and through an array of pointers
wrote . for ->.
2026-10-27 01:31:37 +03:00
c7990e6613 rename the reader's number record to number-literal
sex-fmt-c exports a c-literal? of its own, and the writer imports both;
which one it got depended on the order of its imports.
2026-10-27 01:31:37 +03:00
c8a39b7e62 write a #line file name as a C string literal
It was pasted between quotes as it came, so a quote in the path ended
it, a backslash began an escape, and ?? read as a trigraph.
2026-10-27 01:31:37 +03:00
6e4ad81538 splice a $ nested in a macro's $
Only the outermost was taken apart, so ($ a ($ b c)) left the inner
one an unknown toplevel form, and in a body a call of $ in the C.
2026-10-27 01:31:37 +03:00
192ed2ba64 refuse a char literal that is not one byte
A char is C's, and #\λ came out a multi-character constant whose value
is the C compiler's to choose.
2026-10-27 01:31:37 +03:00
41945606f6 read a string's escapes the way C spells them
An escape the reader did not know lost its backslash, so "\x41" read
as "x41" and "\012" as NUL and "12". A string is text, so \x and octal
reach only as far as ASCII; past it, \u and \U name the character.
2026-10-27 01:31:37 +03:00
ba08695355 give importers the private macros a pub one expands into
Only pub macros crossed, so one built on a private macro expanded in
the importer into a call of a C function nothing defines.
2026-10-27 01:31:37 +03:00
a4ab04995d refuse _ in a pub var's type
Importers declare a pub var from its type alone, with nothing to solve
a wildcard against, so (pub var n _ 42) reached them as extern _ n.
2026-10-27 01:31:37 +03:00
9bbf2dcdaf promote a lone arithmetic operand
One operand was joined with nothing and came back as it was, so (- c)
over a char was a char where C makes it an int.
2026-10-27 01:31:37 +03:00
f30c0733e3 type a pointer difference as ptrdiff-t
The join took the first pointer, so (- p q) declared the distance
between two pointers as a third.
2026-10-27 01:31:37 +03:00
ad1825e8a8 type an operator's result without qualifiers
The spelling was the first operand's, so (+ k 1) with k const was a
const int and (+ 1 k) was not; a value has no qualifiers either way.
2026-10-27 01:31:37 +03:00
47b98e41df keep the qualifiers written on a wildcard
(const _) parsed to a type variable, which had nowhere to keep the
const, so the type it was solved to came out without one -- for
(const _) and for the target of (* const _) alike.
2026-10-27 01:31:37 +03:00
82fa8d1966 require case labels to be values written once
(case (1 2) ...) is a list of labels, so (case (+ 1 1) ...) came out
case +: case 1: case 1:, and a value repeated in a switch was left to C
to report, without saying where.
2026-10-27 01:31:37 +03:00
7c62e65eb0 hold operators to the operands they take
Past them an operator was written as it came: (/ a) as /a, (! a b) as
a ! b. (++ a b) steps each in turn, through a comma operator the writer
lacked: bare in a for header, and in parens wherever else, since bare
it would begin another declarator or argument.
2026-10-27 01:31:37 +03:00
e9ee120383 refuse a comparison of other than two operands
(< a b c) reached C as C's own chain, which compares a boolean with c.
2026-10-27 01:31:37 +03:00
9d5cd66514 read every trailing array bound as a dimension
[m 1 2] lost its second index, and [int 2 3] came out int 2 x[3]. Each
index now subscripts what the one before it gave, and [int 2 3] declares
what it indexes, int[2][3]. An inline struct's fields, once more than
one bound was looked for, were taken for one; their shape tells them apart.
2026-10-27 01:31:37 +03:00
65aaf69835 refuse an if used as a value with no else
With nothing for the false case the writer made (if c 1) c || 1, a
boolean; and a value if's branches were walked as statements, so one
nested there got through as well.
2026-10-27 01:31:37 +03:00
6b5a712837 read hex floats
0x1.8p3 was no number to the reader, so it became a symbol C got inside
|pipes|, and _ could not type it. It reads now as a literal written as
it was: the digits of a double's own bits, which no decimal rounds to.
2026-10-27 01:31:37 +03:00
4463f796f8 group a number's digits with _
C23 groups them with ', which in Sex is quote, so 1'000 read as 1 and
(quote 0); _ between two digits is dropped instead, and anywhere else
stays part of a name.
2026-10-27 01:31:37 +03:00
8ddeac7bab write number literals the way C reads them
A C suffix was no number to string->number, so 1u and 1.5f became
symbols, and C got them inside the |pipes| CHICKEN writes those with.
They read now into a literal that prints its C spelling and is typed by
its suffix: an integer in decimal, so 0b101u needs no C23, and a float
in the digits it was written with, since through a double 0.1f could
round to another float and 0.1L would lose what it has over one.

Scheme also reads numbers C has none of. 1/2 reached C as integer
division and +inf.0 as no C at all; those, and integers past 64 bits,
are read errors now. An integer is typed by size as well, so 4000000000
is no longer an int, and one past long long gets the u C would
otherwise only warn about.
2026-10-27 01:31:37 +03:00
c05904c15e escape a ? that follows a ? in string literals
Under -std=c11 C reads trigraphs, which Sex has none of: "??=" came out
"#", and "??/" before the closing quote left the string open.
2026-10-27 01:31:37 +03:00
27ef5ac805 look for an import beside the file it is written in
Imports were looked for from the unit's directory, so a module in a
subdirectory could not import its neighbours: a pub import failed, a
private one lost its handle declarations, and --public-interface changed
with where sexc ran.
2026-10-27 01:31:37 +03:00
0cb3956e02 declare a record's typedef ahead of its struct
It came after, so a record pointing at itself, (next (* node)), named a
type C had not been told of yet.
2026-10-27 01:31:37 +03:00
0852079827 parenthesize a negative literal under a unary operator
A negative literal is one token in Sex and two in C, so (- -1) came out
--1, which C reads as decrementing a constant.
2026-10-27 01:31:37 +03:00
5cd931cb4e promote the prelude's integer types like C's own
u8 and i32 are typedefs of <stdint.h> names nothing parses, so they had
no rank: (+ a a) over two u8 200s was a u8 holding 144, and (+ n 1) over
an i32 could not be typed at all.
2026-10-27 01:31:37 +03:00
6d84553652 lower match to an if chain, so break in an arm leaves the loop
The switch it lowered to took a break in an arm for its own, and the
loop around the match went on. With no else the last arm is the chain's
else, which keeps C from warning that a function may return nothing.
2026-10-27 01:31:37 +03:00
00efbc5442 read a match scrutinee before a binder can shadow it
C has a declaration in scope from its own initializer, so in
(match (* e) ((neg (e)) ...)) the binding read the new, uninitialized e.
A binder named like a part of the scrutinee now has it held in a local.
2026-10-27 01:31:37 +03:00
635cc48aa3 drop what infer had for types nothing builds
All checks were successful
Sex CI / build-linux (pull_request) Successful in 5m19s
Sex CI / build-linux (push) Successful in 5m19s
No source makes an unknown type, a rigid variable or a variable with a
class to satisfy, so the branches unify, bind-tvar! and entails? kept for
them never ran, and the classes registered for them were never asked.
2026-10-27 01:23:51 +03:00
d2f36d35c6 delete what nothing calls
walk-generic-toplevel and non-empty-list? had no caller left, a type
variable's id was never read, and every expression's type was recorded
in a table nothing looked up.
2026-10-27 01:23:51 +03:00
eb5bf3688b export only what another module imports
set-working-directory is reached only through with-directory's expansion,
so it is exported as that macro's helper; form-location, form-type,
register-macro and get-macro had no importer.
2026-10-27 01:23:51 +03:00
bc4f9246c2 drop the generics scaffolding from infer, and test what semen uses
Schemes, instances, rigid variables and defaulting were built ahead of
generics and called by the tests alone, which reached into the IR for
them. The suite now goes through what infer exports, the eleven names
semen imports; what a wildcard solves is checked from source as well.
2026-10-27 01:23:51 +03:00
29 changed files with 300 additions and 1646 deletions

View File

@@ -317,8 +317,15 @@ best option.
*** sex-mode.el *** sex-mode.el
To harness the power of sex-mode, add the following lines to your To harness the power of sex-mode, add the following lines to your
~$HOME/.config/emacs/init.el~: ~$HOME/.config/emacs/init.el~:
#+begin_src emacs-lisp #+begin_src emacs-lisp
(use-package sex-mode (use-package sex-mode
:load-path "/path/to/sex" :ensure nil
:mode ("\\.sex\\'")) :quelpa
(sex-mode :fetcher git
:url "https://git.kotobank.ch/alex-eg/sex.git"
:files ("sex-mode.el")
:upgrade t))
#+end_src #+end_src
~.sex~ files then open in ~sex-mode~.

View File

@@ -3,12 +3,6 @@
(fn sum ((a int) (b int)) int (fn sum ((a int) (b int)) int
(return (+ a b))) (return (+ a b)))
;;; A lambda captures nothing and is a bare function pointer; a closure
;;; captures and is a value carrying its own environment
(fn make-adder ((a int)) (closure ((int)) int)
(return (closure ((b int)) int (a)
(return (+ a b)))))
(pub fn main () int (pub fn main () int
(var a int 10) (var a int 10)
(var b int 20) (var b int 20)
@@ -41,8 +35,4 @@
(return (+ 60 a)))) (return (+ 60 a))))
(return (+ 600 (l-2 a))))) (return (+ 600 (l-2 a)))))
(printf "Calling nested lambdas: %d\n" (l-1 6)) (printf "Calling nested lambdas: %d\n" (l-1 6))
(var add-10 (closure ((int)) int) (make-adder 10))
(var add-20 (closure ((int)) int) (make-adder 20))
(printf "Calling closures: %d %d\n" (add-10 24) (add-20 24))
(return 0)) (return 0))

View File

@@ -134,7 +134,7 @@ forms, and what remains."
;;; because the compiler composes these names and the user does not: a ;;; because the compiler composes these names and the user does not: a
;;; hand-written vec2__length would collide, and an identifier holding ;;; hand-written vec2__length would collide, and an identifier holding
;;; `__' is reserved in C++, which a pub header may be included from. ;;; `__' is reserved in C++, which a pub header may be included from.
;;; Lifted closures carry a ƛ for the same reason. ;;; Lifted lambdas carry a λ for the same reason.
;;; ;;;
;;; zero? -> zeroʔ, clear! -> clearꜝ: a glottal stop and a raised ;;; zero? -> zeroʔ, clear! -> clearꜝ: a glottal stop and a raised
;;; exclamation mark, both letters. Not the retroflex click ǃ, which ;;; exclamation mark, both letters. Not the retroflex click ǃ, which

View File

@@ -2,8 +2,7 @@
;;; ;;;
;;; semen solves the wildcards of a declared type with it -- `(var n _ ;;; semen solves the wildcards of a declared type with it -- `(var n _
;;; (strlen s))', `(var p (* _) (& x))' -- and asks it what an operand ;;; (strlen s))', `(var p (* _) (& x))' -- and asks it what an operand
;;; decays or promotes to. It is the ground floor of the pass described ;;; decays or promotes to.
;;; in Type-inference.org.
;;; ;;;
;;; Two representations meet here. *Surface* types are the forms the ;;; Two representations meet here. *Surface* types are the forms the
;;; rest of the compiler passes around -- `int', `(* const char)', ;;; rest of the compiler passes around -- `int', `(* const char)',

View File

@@ -234,7 +234,9 @@
;;; Scheme reads numbers C has no literal for -- 1/2, #e1.5, 1e400, ;;; Scheme reads numbers C has no literal for -- 1/2, #e1.5, 1e400,
;;; +nan.0, 1+2i -- and they reached C as written. An integer too wide ;;; +nan.0, 1+2i -- and they reached C as written. An integer too wide
;;; for long long is unsigned to C, which says so only by a warning ;;; for long long is unsigned to C, which says so only by a warning
;;; unless it is written with a `u'; so it is. ;;; unless it is written with a `u'; so it is. -9223372036854775808 is
;;; one too: C negates the unsigned 9223372036854775808, so it is
;;; spelled as LLONG_MIN is, -9223372036854775807 - 1.
(define +llong-min+ (- (expt 2 63))) (define +llong-min+ (- (expt 2 63)))
(define +llong-max+ (- (expt 2 63) 1)) (define +llong-max+ (- (expt 2 63) 1))
(define +ullong-max+ (- (expt 2 64) 1)) (define +ullong-max+ (- (expt 2 64) 1))
@@ -245,6 +247,7 @@
(error "too large for any C integer type" s)) (error "too large for any C integer type" s))
((> n +llong-max+) (make-number-literal n "u" #f)) ((> n +llong-max+) (make-number-literal n "u" #f))
((< n +llong-min+) (list '- (make-number-literal (- n) "u" #f))) ((< n +llong-min+) (list '- (make-number-literal (- n) "u" #f)))
((= n +llong-min+) (list '- (+ n 1) 1))
(else n))) (else n)))
((and (real? n) (inexact? n) (finite? n)) n) ((and (real? n) (inexact? n) (finite? n)) n)
(else (error "C has no literal for this number" s)))) (else (error "C has no literal for this number" s))))

720
semen.scm
View File

@@ -20,7 +20,6 @@
) )
(export/rename (process semen-process)) (export/rename (process semen-process))
(export closure-env-declaration)
;;; for lambda extraction, docstring processing, macro expansion, ;;; for lambda extraction, docstring processing, macro expansion,
;;; injection of module headers, i.e. all things that rearrange code ;;; injection of module headers, i.e. all things that rearrange code
@@ -56,13 +55,10 @@
(macroexpand (car forms) (cdr forms)) (macroexpand (car forms) (cdr forms))
acc)) acc))
(else (else
;; `struct ƛint_int' has to be declared before the function whose
;; signature first mentioned it, so the forms that function produced
;; are lifted off and the structs slid underneath them
(let* ((processed (match-sex-form (car forms) acc)) (let* ((processed (match-sex-form (car forms) acc))
(new (take-until processed acc))) (new (take-until processed acc)))
(process-rec (cdr forms) (process-rec (cdr forms)
(append new (flush-closure-structs!) acc)))))) (append new acc))))))
(define (take-until forms tail) (define (take-until forms tail)
(if (eq? forms tail) (if (eq? forms tail)
@@ -104,10 +100,6 @@
((or ('fn . _) ((or ('fn . _)
('pub 'fn . _) ('pub 'fn . _)
('extern 'fn . _)) (process-fn sex-form acc)) ('extern 'fn . _)) (process-fn sex-form acc))
((or ('spec . _)
('pub 'spec . _)) (process-spec sex-form acc))
((or ('realize . _)
('pub 'realize . _)) (process-realize sex-form acc))
(('ops . _) (process-ops sex-form acc)) (('ops . _) (process-ops sex-form acc))
(('pub 'ops . _) (('pub 'ops . _)
(sex-error sex-form "pub belongs on the methods, not on ops" sex-form)) (sex-error sex-form "pub belongs on the methods, not on ops" sex-form))
@@ -125,8 +117,7 @@
('pub 'var . _) ('pub 'var . _)
('extern 'var . _)) (process-global-var sex-form acc)) ('extern 'var . _)) (process-global-var sex-form acc))
;; `pub' on either of these is what read-public-interface already ;; `pub' on either of these is what read-public-interface already
;; accepts, and a module whose spec defaults call printf has to be ;; accepts: a module may export what its interface needs
;; able to say so
((or ('include . includes) ((or ('include . includes)
('pub 'include . includes)) (process-includes sex-form includes acc)) ('pub 'include . includes)) (process-includes sex-form includes acc))
((or ('define name . _) ((or ('define name . _)
@@ -308,7 +299,7 @@
(add-name-type! (sex-fn-name expanded) (fn-type-of expanded)) (add-name-type! (sex-fn-name expanded) (fn-type-of expanded))
(let* ((env (make-fn-env expanded)) (let* ((env (make-fn-env expanded))
;; the parameters are the body's outermost scope ;; the parameters are the body's outermost scope
(header (map resolve-closure-types (take expanded boundary))) (header (take expanded boundary))
(body (parameterize ((operand-position? #f)) (body (parameterize ((operand-position? #f))
(walk-body (drop expanded boundary) env))) (walk-body (drop expanded boundary) env)))
;; A function is header and body stitched together, so the ;; A function is header and body stitched together, so the
@@ -319,141 +310,6 @@
(with-docstring doc processed (with-docstring doc processed
(append (hash-table-ref env :lambda-aux-code) acc)))))) (append (hash-table-ref env :lambda-aux-code) acc))))))
;;; (spec (printable T) (fn show ((self (* const T))) void))
;;;
;;; declares a contract and emits nothing: a spec method only exists
;;; once some type realizes it, and then once per type.
(define (process-spec form acc)
(let* ((core (if (eq? (car form) 'pub) (cdr form) form))
(head (and (pair? (cdr core)) (cadr core)))
(methods (remove comment-form? (cddr core))))
(unless (and (list? head) (= 2 (length head))
(symbol? (car head)) (symbol? (cadr head)))
(sex-error form "a spec is (spec (name T) methods ...)" form))
(let ((name (car head)))
(when (get-spec name)
(sex-error form "spec is already declared" name))
(for-each (lambda (m)
(unless (and (pair? m) (eq? (car m) 'fn)
(pair? (cdr m)) (symbol? (second m)))
(sex-error form "a spec takes fn forms" m)))
methods)
(add-spec! name (cadr head) methods)
acc)))
;;; (realize (printable expr) (fn show ((self (* const expr))) void ...))
;;;
;;; is the spec's methods for one type: the ones written here, plus a
;;; copy of every default the spec carries, each with the parameter
;;; substituted and the name mangled to exprːprintableːshow. They land
;;; in the ops registry beside inherent methods, so (.show e) finds
;;; them and a name used twice on one type is caught either way.
(define (process-realize form acc)
(let* ((pub? (eq? (car form) 'pub))
(core (if pub? (cdr form) form))
(head (and (pair? (cdr core)) (cadr core)))
(given (remove comment-form? (cddr core))))
(unless (and (list? head) (= 2 (length head))
(symbol? (car head)) (symbol? (cadr head)))
(sex-error form "a realization is (realize (spec type) methods ...)" form))
(let* ((name (car head))
(type (cadr head))
(spec (or (get-spec name)
(sex-error form "no such spec" name))))
(when (realizes? name type)
(sex-error form "spec is already realized for" name type))
(add-realization! name type)
(let ((wanted (spec-methods spec))
(parameter (spec-parameter spec)))
(check-realization form name type parameter wanted given)
;; every method is registered before any body is walked, so they
;; may call one another in any order, as an ops block's may; one
;; called above its definition is declared ahead of them all
(let* ((methods (map (lambda (entry)
(register-realized-method form name type
(and pub? (cdr entry))
(car entry)))
(realization-methods type parameter wanted given)))
(bodies (map (lambda (m) (process-fn m (list))) methods))
(early (filter (lambda (m) (called-before? m methods bodies))
methods)))
(append (append-map identity (reverse bodies))
(fold (lambda (m acc) (process-fn (sex-fn-prototype m) acc))
acc
early)))))))
;;; What is written here, which a pub realization exports, and then
;;; every default nobody overrode, which it does not: a default is
;;; synthesized again in every unit that imports the realization, so
;;; exporting one too would be a second definition of one symbol.
(define (realization-methods type parameter wanted given)
(append (map (lambda (g) (cons g #t)) given)
(filter-map
(lambda (w)
(and (spec-default? w)
(not (find (lambda (g) (eq? (second g) (second w))) given))
(cons (substitute-parameter parameter type w) #f)))
wanted)))
;;; A docstring or a comment is not a body, so
;;;
;;; (fn s ((self (* const T))) void "what s is for")
;;;
;;; is still a method every realization has to write.
(define (spec-default? method)
(let-values (((doc fn) (extract-fn-docstring (strip-fn-header-comments method))))
(any (lambda (form) (not (comment-form? form)))
(drop fn (fn-header-length fn)))))
(define (check-realization form name type parameter wanted given)
(for-each
(lambda (g)
(unless (and (pair? g) (eq? (car g) 'fn) (pair? (cdr g)) (symbol? (second g)))
(sex-error form "a realization takes fn forms" g))
(let ((w (find (lambda (w) (eq? (second w) (second g))) wanted)))
(unless w
(sex-error form "spec has no such method" name (second g)))
(let ((expected (substitute-parameter parameter type w)))
(unless (equal? (arglist-types (sex-fn-arglist expected))
(arglist-types (sex-fn-arglist g)))
(sex-error form "method's arguments do not match the spec" (second g)))
(unless (equal? (sex-fn-return-type expected) (sex-fn-return-type g))
(sex-error form "method's return type does not match the spec"
(second g))))))
given)
(let ((missing (filter-map
(lambda (w)
(and (not (spec-default? w))
(not (find (lambda (g) (eq? (second g) (second w))) given))
(second w)))
wanted)))
(when (pair? missing)
(apply sex-error form "realization is missing a method of" name missing))))
;;; A realization is public or private as a unit -- its methods do
;;; not carry `pub' of their own, the way an ops block's do, because
;;; the spec already says which of them there are. The method's fn
;;; form, renamed to pointːsizedːtotal, once it is registered under
;;; `total' and its signature known.
(define (register-realized-method form spec type pub? method)
(let* ((name (second method))
(qualified (qualify-op (qualify-op type spec) name))
(renamed (copy-form-source! form (rename-fn method qualified)))
(fn (if pub? (copy-form-source! form (cons 'pub renamed)) renamed)))
(when (get-method type name)
(sex-error form "method is already defined on" type name))
(add-method! type name qualified)
(process-fn (sex-fn-prototype fn) (list))
fn))
;;; T in a spec's method stands for whatever realizes it
(define (substitute-parameter parameter type form)
(cond ((eq? form parameter) type)
((pair? form) (recons form
(substitute-parameter parameter type (car form))
(substitute-parameter parameter type (cdr form))))
(else form)))
;;; (ops vec2 ;;; (ops vec2
;;; (pub fn length ((self (* const vec2))) float ...)) ;;; (pub fn length ((self (* const vec2))) float ...))
;;; ;;;
@@ -549,8 +405,8 @@
;;; The scope chain ;;; The scope chain
;;; ;;;
;;; `(do (var c int 9) ...)' declares a `c' that ends with the block, so ;;; `(do (var c int 9) ...)' declares a `c' that ends with the block, so
;;; a closure-typed `c' outside it is still a closure after it. Every ;;; an outer `c' is in scope after it. Every form whose body C brackets
;;; form whose body C brackets opens a frame; innermost first: ;;; opens a frame; innermost first:
;;; ;;;
;;; (var v double 3.75) ;;; (var v double 3.75)
;;; (while (< v 0) (var v char 1) ...) ;;; (while (< v 0) (var v char 1) ...)
@@ -577,10 +433,9 @@
;;; The body walk ;;; The body walk
;;; ;;;
;;; One pass in statement order: lifts lambdas and closures out, ;;; One pass in statement order: lifts lambdas out, records what each
;;; resolves closure types to the struct that stands for them, records ;;; declaration binds, and rewrites a call whose head is a function
;;; what each declaration binds, and rewrites a call whose head is a ;;; value.
;;; closure.
;;; ;;;
;;; Not `walk-form': it has no event for leaving a scope, and it hands ;;; Not `walk-form': it has no event for leaving a scope, and it hands
;;; the walk function every cdr-tail as well, so the `f' in `(g f)' ;;; the walk function every cdr-tail as well, so the `f' in `(g f)'
@@ -651,31 +506,15 @@
(add-aux-code! env (lift-lambda name form)) (add-aux-code! env (lift-lambda name form))
name)) name))
((closure)
(if (closure-type? form)
;; a type, not an expression: the struct for its signature
(copy-form-source! form `(struct ,(register-closure-type! form form)))
(let ((base (aux-name! env make-closure-name)))
(let-values (((construct lifted) (lift-closure base form env)))
(add-aux-code! env (fold match-sex-form (list) lifted))
(copy-form-source!
form
`(,construct ,@(map (lambda (capture)
(walk-operand (capture-argument capture)
env))
(fourth form))))))))
((var) ((var)
;; the initializer is walked before the name it binds is in ;; the initializer is walked before the name it binds is in
;; scope; the type is resolved rather than walked, a parameter ;; scope; the type is resolved rather than walked, a parameter
;; list being shaped like a call: ;; list being shaped like a call:
;; ;;
;; (var c (closure ((int)) int) ...)
;; (var fp (fn ((c int)) int) ...) ; int (*fp)(int) ;; (var fp (fn ((c int)) int) ...) ; int (*fp)(int)
(let* ((prefix (if (>= (length form) 3) (let* ((prefix (if (>= (length form) 3)
(append (take form 2) (append (take form 2)
(list (resolve-closure-types (list (expand-type (third form) env)))
(expand-type (third form) env))))
form)) form))
(walked (resolve-wildcard (walked (resolve-wildcard
(copy-form-source! (copy-form-source!
@@ -684,29 +523,15 @@
(if (> (length form) 3) (if (> (length form) 3)
(walk-operands form (drop form 3) env) (walk-operands form (drop form 3) env)
(list)))) (list))))
env)) env)))
(bound (if (>= (length walked) 4) (when (>= (length walked) 3)
(copy-form-source! (declare-name! env (second walked) (third walked)))
walked walked))
(append (take walked 3)
(cons (convert-to-closure (third walked)
(fourth walked)
env walked)
(drop walked 4))))
walked)))
(when (>= (length bound) 3)
(declare-name! env (second bound) (third bound)))
bound))
((return) ((return)
(let ((walked (copy-form-source! form (walk-operands form form env)))) (let ((walked (copy-form-source! form (walk-operands form form env))))
(if (>= (length walked) 2) (if (>= (length walked) 2)
(copy-form-source! (copy-form-source! walked (cons 'return (cdr walked)))
walked
(cons 'return
(cons (convert-to-closure (hash-table-ref env :returns)
(second walked) env walked)
(cddr walked))))
walked))) walked)))
((match) ((match)
@@ -730,8 +555,7 @@
(if (and (= 2 (length form)) (written-type? (second form) env)) (if (and (= 2 (length form)) (written-type? (second form) env))
(copy-form-source! (copy-form-source!
form form
`(sizeof (%type ,(resolve-closure-types `(sizeof (%type ,(expand-type (second form) env))))
(expand-type (second form) env)))))
(walk-parts form env))) (walk-parts form env)))
(else (else
@@ -739,23 +563,11 @@
((method-head? (car form)) (walk-method-call form env)) ((method-head? (car form)) (walk-method-call form env))
((get-constructor (car form)) ((get-constructor (car form))
=> (lambda (constructor) (walk-construction form constructor env))) => (lambda (constructor) (walk-construction form constructor env)))
((receiver-closure-type (car form) env)
=> (lambda (closure)
;; the receiver is walked first: `((closure ((x int))
;; int () ...) 5)' registers `struct ƛint_int' on the
;; way, and the call helper's signature names it
(let ((receiver (walk-operand (car form) env)))
(copy-form-source!
form
`(,(register-closure-call! closure form)
,receiver
,@(walk-operands form (cdr form) env))))))
(else (else
(when (and (symbol? (car form)) (form-source form) (when (and (symbol? (car form)) (form-source form)
(not (hash-table-exists? +called-as-functions+ (car form)))) (not (hash-table-exists? +called-as-functions+ (car form))))
(hash-table-set! +called-as-functions+ (car form) form)) (hash-table-set! +called-as-functions+ (car form) form))
(convert-arguments (copy-form-source! form (walk-operands form form env)) (copy-form-source! form (walk-operands form form env)))))))))
env))))))))
;;; How many operands each of these takes, and how it is written: one ;;; How many operands each of these takes, and how it is written: one
;;; with any other number died in the writer, in CHICKEN's words about a ;;; with any other number died in the writer, in CHICKEN's words about a
@@ -808,7 +620,7 @@
(define (field-argument field arg env form) (define (field-argument field arg env form)
(let ((type (second field))) (let ((type (second field)))
(if (not (array-form? type)) (if (not (array-form? type))
(convert-to-closure type arg env form) arg
(let ((given (expression-type arg env))) (let ((given (expression-type arg env)))
(cond (cond
((brace-initializer? arg) ((brace-initializer? arg)
@@ -856,7 +668,7 @@
(define (expand-call form env) (define (expand-call form env)
(parameterize ((current-type-of (parameterize ((current-type-of
(lambda (queried) (lambda (queried)
(unresolve-closure-types (expression-type queried env))))) (expression-type queried env))))
(macroexpand form (list)))) (macroexpand form (list))))
;;; #(struct point : (. p x) 2) -- the values are expressions, and the ;;; #(struct point : (. p x) 2) -- the values are expressions, and the
@@ -927,16 +739,15 @@
(let ((type (expression-type written env))) (let ((type (expression-type written env)))
(when type (when type
(unify element (unify element
(parse-type (resolve-closure-types type)) (parse-type type)
form)))) form))))
(vector->list initializer)))) (vector->list initializer))))
(else (else
(let ((type (expression-type initializer env))) (let ((type (expression-type initializer env)))
(unless type (unless type
(sex-error form "cannot infer the type of" (second form))) (sex-error form "cannot infer the type of" (second form)))
;; `(closure ((int)) int)' is spelled `(struct ƛint_int)' ;; a type is what `parse-type' knows
;; everywhere past this point, and is what `parse-type' knows (let ((given (parse-type type)))
(let ((given (parse-type (resolve-closure-types type))))
;; an array as a value is a pointer to its first element, which ;; an array as a value is a pointer to its first element, which
;; is what a `_' standing alone takes; `[_ 3]' asks for an array ;; is what a `_' standing alone takes; `[_ 3]' asks for an array
(unify declared (unify declared
@@ -960,34 +771,8 @@
((vector? form) (mentions? (vector->list form) word)) ((vector? form) (mentions? (vector->list form) word))
(else #f))) (else #f)))
;;; `(each xs compare)' where `each' takes a closure: the argument is ;;; What a `fn' header gets, a `var' type gets -- macro expansion, no
;;; checked against the parameter that signature wrote. ;;; walk:
(define (convert-arguments form env)
(let ((signature (and (symbol? (car form)) (get-name-type (car form)))))
(if (and (list? signature) (= 3 (length signature)) (eq? 'fn (car signature)))
(copy-form-source!
form
(cons (car form)
(map (lambda (argument expected)
(if expected
(convert-to-closure expected argument env form)
argument))
(cdr form)
(parameter-types signature (length (cdr form))))))
form)))
;;; One per argument, #f past the end of the parameter list -- a
;;; variadic tail has nothing written to check against
(define (parameter-types signature count)
(let pair ((params (second signature)) (remaining count) (acc (list)))
(cond
((zero? remaining) (reverse acc))
((null? params) (pair params (- remaining 1) (cons #f acc)))
(else (pair (cdr params) (- remaining 1)
(cons (unwrap-type (car params)) acc))))))
;;; What a `fn' header gets, a `var' type gets -- macro expansion and
;;; closure resolution, no walk:
;;; ;;;
;;; (defmacro (ty) 'int) (var x (ty) 0) -> int x = 0; ;;; (defmacro (ty) 'int) (var x (ty) 0) -> int x = 0;
;;; ;;;
@@ -996,8 +781,7 @@
(let ((expanded (let ((expanded
(parameterize ((current-type-of (parameterize ((current-type-of
(lambda (queried) (lambda (queried)
(unresolve-closure-types (expression-type queried env))))
(expression-type queried env)))))
(macro-expand (list type))))) (macro-expand (list type)))))
(if (and (pair? expanded) (null? (cdr expanded))) (if (and (pair? expanded) (null? (cdr expanded)))
(car expanded) (car expanded)
@@ -1076,7 +860,7 @@
arms)) arms))
(define (make-match-name fn-name counter) (define (make-match-name fn-name counter)
(string->symbol (string-append "ƛm" (number->string counter)))) (string->symbol (string-append "λm" (number->string counter))))
;;; A path of names reads the same however often it is written; a call ;;; A path of names reads the same however often it is written; a call
;;; in there does not ;;; in there does not
@@ -1312,16 +1096,6 @@
(and (pair? type) (eq? 'const (car type)))) (and (pair? type) (eq? 'const (car type))))
(define (as-closure-type type)
(cond
((closure-type? type) type)
((and (list? type) (= 2 (length type)) (eq? 'struct (car type)))
(hash-table-ref/default +closure-structs+ (second type) #f))
(else #f)))
(define (receiver-closure-type expr env)
(as-closure-type (expression-type expr env)))
;;; The type of an lvalue path, from known declarations -- a name, and ;;; The type of an lvalue path, from known declarations -- a name, and
;;; what can be reached from one by subscripting, dereferencing and ;;; what can be reached from one by subscripting, dereferencing and
;;; member access. ;;; member access.
@@ -1408,10 +1182,6 @@
(cddr expr))) (cddr expr)))
((cast) (and (= 3 (length expr)) (third expr))) ((cast) (and (= 3 (length expr)) (third expr)))
((sizeof) 'size-t) ((sizeof) 'size-t)
;; `(closure ((x int)) int () ...)' is a `(closure ((int)) int)',
;; so `((closure ((x int)) int () (return x)) 5)' is a call
((closure) (and (closure-expression? expr)
`(closure ,(arglist-types (second expr)) ,(third expr))))
;; `c-and' and `c-or' are the names from before `&&' and `||' ;; `c-and' and `c-or' are the names from before `&&' and `||'
((== != < > <= >= && |\|\|| ! c-and c-or) 'bool) ((== != < > <= >= && |\|\|| ! c-and c-or) 'bool)
;; one pointer from another is how far apart they are ;; one pointer from another is how far apart they are
@@ -1439,12 +1209,10 @@
;; (++ c), c : char -> char ;; (++ c), c : char -> char
((++ --) (expression-type (second expr) env)) ((++ --) (expression-type (second expr) env))
;; otherwise a call: a method answers for the name it resolves ;; otherwise a call: a method answers for the name it resolves
;; to, a closure with its own return type, anything else with ;; to, anything else with what its signature says
;; what its signature says
(else (else
(cond (cond
((method-head? (car expr)) (method-call-type expr env)) ((method-head? (car expr)) (method-call-type expr env))
((receiver-closure-type (car expr) env) => third)
;; a function's name, unless a local hides it ;; a function's name, unless a local hides it
((and (symbol? (car expr)) ((and (symbol? (car expr))
(not (lookup-name env (car expr))) (not (lookup-name env (car expr)))
@@ -1645,450 +1413,31 @@
(list))) (list)))
(else (sex-error form "malformed lambda" form)))) (else (sex-error form "malformed lambda" form))))
;;; Closures
;;;
;;; A closure is a function pointer and an inline environment, so the
;;; value owns its captures and nothing is allocated. The type
;;; `(closure ((int)) int)' becomes one struct per signature, shared by
;;; every closure with that signature. The captures live in `env' as a record
;;; only the lifted body knows the shape of, which is why `env' is
;;; max_align_t rather than char -- it has to be aligned for whatever
;;; ends up in it.
;;;
;;; The expression becomes three hoisted definitions -- the capture
;;; struct, the lifted body, and a constructor -- and is replaced by a
;;; call to the constructor, so the captures are evaluated as ordinary
;;; arguments at the point the closure is written.
;;; How much of a closure is environment, in bytes. Counted in bytes
;;; so a closure that fits where it was written will also fit
;;; elsewhere. Captures are only by value, and never allocated on
;;; heap. Anything that is more than 16 bytes should be stored as a
;;; pointer, and memory management is entirely up to caller
(define +closure-env-bytes+ 16)
;;; +closure-env-bytes+ for capacity, max_align_t for alignment, hence
;;; union -- a union takes the strictest alignment of its members.
(define +closure-env-type+ 'ƛenv)
(define (closure-env-declaration)
`(union ,+closure-env-type+ ((align max-align-t)
(bytes (¤ char ,+closure-env-bytes+)))))
(define +closure-structs+ (make-hash-table))
(define +closure-forwards+ (make-hash-table))
(define *pending-closure-structs* (list))
(define (closure-expression? form)
(and (list? form)
(pair? form)
(eq? 'closure (car form))
(>= (length form) 4)))
(define (closure-type? form)
(and (pair? form)
(eq? 'closure (car form))
(= 3 (length form))))
;;; A type spelling becomes an identifier deterministically, so two
;;; translation units have the same signatures for the same closure
;;; types: (* const char) -> p_const_char, (closure ((int)) int) ->
;;; closure_int_int.
(define (mangle-type type)
(cond
((symbol? type) (mangle-word (symbol->string type)))
((number? type) (number->string type))
((null? type) "void")
((pair? type) (string-intersperse (map mangle-type (mangle-head type)) "_"))
(else (sex-error type "cannot mangle type" type))))
(define (mangle-head type)
(case (car type)
((*) (cons 'p (cdr type)))
((¤) (cons 'a (cdr type)))
(else type)))
(define (mangle-word word)
(list->string
(map (lambda (c)
(if (or (char-alphabetic? c) (char-numeric? c)) c #\_))
(string->list word))))
(define (aggregates-in type)
(cond
((not (list? type)) (list))
((and (= 2 (length type))
(memq (car type) '(struct union))
(symbol? (second type)))
(list type))
(else (append-map aggregates-in type))))
;;; Extract aggregate types from the closure's signature to forward
;;; declare them before the closure, so they can be referenced in the
;;; closure. Particularly useful for complex cases like fixed point
;;; combinator, etc.
(define (forward-declare-aggregates! type src-form)
(for-each
(lambda (aggregate)
(let ((name (second aggregate)))
(unless (or (hash-table-exists? +closure-forwards+ name)
(get-tag-info name))
(hash-table-set! +closure-forwards+ name #t)
(set! *pending-closure-structs*
(cons (copy-form-source! src-form aggregate)
*pending-closure-structs*)))))
(delete-duplicates (aggregates-in type))))
;;; The words inside an argument take the single separator, the
;;; arguments a doubled one:
;;;
;;; (closure ((long long)) int) -> ƛlong_long_int
;;; (closure ((long) (long)) int) -> ƛlong__long_int
;;;
;;; A word whose first character mangles to `_' still aliases the
;;; doubled separator: `((a -b))' and `((a) (b))' are both `a__b'.
(define (mangle-arglist args)
(if (null? args)
"void"
(string-intersperse (map mangle-type args) "__")))
(define (closure-struct-name type)
;; the glyph says `closure' already, so the tag is just the signature
(string->symbol (string-append "ƛ"
(mangle-arglist (second type))
"_"
(mangle-type (third type)))))
;;; The code pointer takes the environment first; everything else is
;;; the closure's own signature.
(define (closure-code-type type)
(let ((type (signature-resolved type)))
`(fn (((* void)) ,@(second type)) ,(third type))))
;;; TYPE with the closure types of its signature made their structs: the
;;; code generated for it goes out as it is, and C has no `closure'.
;;;
;;; (closure ((int)) (closure ((int)) int))
;;; -> (closure ((int)) (struct ƛint_int))
(define (signature-resolved type)
`(closure ,(map resolve-closure-types (second type))
,(resolve-closure-types (third type))))
;;; Emitted once per signature, before the toplevel form that first
;;; needed it.
(define (register-closure-type! type src-form)
(let ((name (closure-struct-name type)))
(unless (hash-table-exists? +closure-structs+ name)
(forward-declare-aggregates! type src-form)
(hash-table-set! +closure-structs+ name type)
(let ((form (copy-form-source!
src-form
`(struct ,name ((code ,(closure-code-type type))
(env (union ,+closure-env-type+)))))))
(register-aggregate! form)
(set! *pending-closure-structs*
(cons form *pending-closure-structs*))))
name))
;;; Every closure type in FORM becomes the struct for its signature,
;;; registering it on the way. The walker does this for function bodies
;;; and headers; globals come through here instead.
;;; The inverse of `resolve-closure-types', for what a macro is shown:
;;; `(struct ƛint_int)' is a generated name, and `(closure ((int)) int)'
;;; is what was written and what a `type-match' pattern says.
(define (unresolve-closure-types type)
(or (as-closure-type type)
(if (list? type)
(map unresolve-closure-types type)
type)))
(define (resolve-closure-types form)
(cond
;; `(closure args ret captures . body)' is an expression, and one is
;; lifted into the function it was written in. At toplevel, or in a
;; struct field, there is none
((closure-expression? form)
(sex-error form "a closure can only be written inside a function" form))
((closure-type? form)
(copy-form-source! form `(struct ,(register-closure-type! form form))))
((list? form)
(copy-form-source! form (map resolve-closure-types form)))
(else form)))
(define +closure-conversions+ (make-hash-table))
;;; `(var c (closure ((int)) int) sum)' becomes `ƛint_int_fromfn(sum)'.
;;; The function pointer goes in the environment and a thunk reads it
;;; back out, so one thunk serves every function of that signature:
;;;
;;; struct ƛint_int_fnptr { int (*f)(int); };
;;; static int ƛint_int_fnthunk (void *ƛe, int ƛa0) {
;;; struct ƛint_int_fnptr *ƛcaptures = ƛe;
;;; return ƛcaptures->f(ƛa0);
;;; }
(define (register-fn-conversion! type src-form)
(let* ((closure (closure-struct-name type))
(type (signature-resolved type))
(convert (suffixed closure "_fromfn"))
(record (suffixed closure "_fnptr"))
(thunk (suffixed closure "_fnthunk"))
(returns (third type))
(pointer `(fn ,(second type) ,returns))
(params (map (lambda (argument index)
(list (string->symbol (fmt #f "ƛa" index))
(unwrap-type argument)))
(second type)
(iota (length (second type))))))
(unless (hash-table-exists? +closure-conversions+ convert)
(hash-table-set! +closure-conversions+ convert #t)
(let ((call `((%-> ƛcaptures f) ,@(map first params))))
(for-each
(lambda (emitted)
(set! *pending-closure-structs*
(cons (copy-form-source! src-form emitted)
*pending-closure-structs*)))
(list
`(struct ,record ((f ,pointer)))
`(fn ,thunk ((ƛe (* void)) ,@params) ,returns
(var ƛcaptures (* (struct ,record)) ƛe)
,(if (eq? 'void returns) call `(return ,call)))
`(fn ,convert ((f ,pointer)) (struct ,closure)
(var ƛc (struct ,closure))
(= (dot-access ƛc code) ,thunk)
(var ƛcaptures (* (struct ,record))
(cast (& (dot-access ƛc env)) (* (struct ,record))))
(= (%-> ƛcaptures f) f)
(return ƛc))))))
convert))
;;; A bare function is a closure that captures nothing, so it converts
;;; wherever one is expected. The reverse cannot: a closure has an
;;; environment and a function pointer has nowhere to put it.
(define (convert-to-closure expected value env form)
(let ((closure (as-closure-type expected))
(actual (expression-type value env)))
(if (and closure
(list? actual)
(= 3 (length actual))
(eq? 'fn (car actual))
(equal? (cdr actual) (cdr closure)))
(copy-form-source! form
(list (register-fn-conversion! closure form) value))
value)))
(define +closure-calls+ (make-hash-table))
;;; The helper a closure call is routed through: `(f 1)' becomes
;;; `ƛint_int_call(f, 1)', which unpacks the receiver into
;;; `ƛc.code(&ƛc.env, ƛa0)' inside. The receiver arrives as an argument,
;;; so it is evaluated once: unpacked at the call site instead,
;;; `([table (++ i)] 10)' would read
;;; `table[++i].code(&table[++i].env, 10)' and bump `i' twice.
(define (register-closure-call! type src-form)
(let* ((closure (closure-struct-name type))
(type (signature-resolved type))
(helper (suffixed closure "_call"))
(returns (third type))
(params (map (lambda (arg index)
(list (string->symbol (fmt #f "ƛa" index))
(unwrap-type arg)))
(second type)
(iota (length (second type))))))
;; what it returns, for `_' to read: it goes out as written, and
;; nothing else registers it
(add-name-type! helper
`(fn (((struct ,closure))
,@(map (lambda (p) (list (second p))) params))
,returns))
(unless (hash-table-ref/default +closure-calls+ helper #f)
(hash-table-set! +closure-calls+ helper #t)
(let ((call `((dot-access ƛc code)
(& (dot-access ƛc env))
,@(map first params))))
(set! *pending-closure-structs*
(cons (copy-form-source!
src-form
`(fn ,helper ((ƛc (struct ,closure)) ,@params) ,returns
,(if (eq? 'void returns) call `(return ,call))))
*pending-closure-structs*))))
helper))
;;; An argument type is written wrapped: `(int)' in `((int) (float))' ;;; An argument type is written wrapped: `(int)' in `((int) (float))'
(define (unwrap-type type) (define (unwrap-type type)
(if (and (list? type) (= 1 (length type))) (if (and (list? type) (= 1 (length type)))
(car type) (car type)
type)) type))
(define (flush-closure-structs!)
(let ((pending *pending-closure-structs*))
(set! *pending-closure-structs* (list))
pending))
;;; Lowering
(define (make-closure-name enclosing-fn-name counter)
(string->symbol (fmt #f "ƛ" counter "_" enclosing-fn-name)))
(define (suffixed name suffix)
(string->symbol (string-append (symbol->string name) suffix)))
;;; `(closure ((b int)) int (n) ...)' captures `n' under its own name
;;; and takes its type from wherever it was declared. `((pa (& a)))'
;;; names the capture and gives the expression it holds, so `pa' is a
;;; `(* int)' inside the body and `a' is never mentioned there.
(define (capture-binding capture form env)
(let ((name (capture-name capture)))
;; ((+ a 1)) was a capture named `+' holding a
(unless (and (symbol? name) (or (symbol? capture) (= 2 (length capture))))
(sex-error form "a capture is a name, or (name value)" capture))
;; the same lookup either way, so `(closure ((x int)) int (scale)
;; ...)' borrows a global's `scale' as readily as a local's
(let ((type (expression-type (capture-argument capture) env)))
(unless type
(sex-error form "cannot infer what is captured as" name))
(list name type))))
(define (capture-name capture)
(if (pair? capture) (first capture) capture))
;;; What the constructor is handed: the name itself, or the expression
;;; written beside it
(define (capture-argument capture)
(if (pair? capture) (second capture) capture))
(define (lift-closure base form env)
(match form
(('closure arglist ret-type captures . body)
;; its call helper would have to forward the rest, which C cannot
(when (any (lambda (arg) (or (eq? arg '...) (equal? arg '(...)))) arglist)
(sex-error form "a closure cannot be variadic; a lambda can"))
(check-capture-names form arglist (map capture-name captures) body)
(let* ((caps (map (lambda (c) (capture-binding c form env)) captures))
(record (suffixed base "_captures"))
(code (suffixed base "_code"))
(construct (suffixed base "_make"))
(type `(closure ,(arglist-types arglist) ,ret-type))
(closure (register-closure-type! type form)))
(values
construct
(map (lambda (f) (copy-form-source! form f))
;; C has no empty struct, and a closure over nothing needs
;; no record to point at
(append
(if (null? caps)
(list)
(list `(struct ,record ,(map capture-field caps))))
(list
`(fn ,code ((ƛe (* void)) ,@(named-parameters arglist)) ,ret-type
,@(defining
(append
(if (null? caps)
(list)
`((var ƛcaptures (* (struct ,record)) ƛe)
,@(append-map (cut capture-local <> form) caps)))
body)))
`(fn ,construct ,caps (struct ,closure)
(var ƛc (struct ,closure))
,@(if (null? caps)
(list)
`((static-assert
(<= (sizeof (struct ,record))
(sizeof (dot-access ƛc env)))
"closure captures do not fit the inline environment")))
(= (dot-access ƛc code) ,code)
,@(if (null? caps)
(list)
`((var ƛcaptures (* (struct ,record))
(cast (& (dot-access ƛc env)) (* (struct ,record))))
,@(map (cut capture-store <> form) caps)))
(return ƛc))))))))
(else (sex-error form "malformed closure" form))))
;;; A definition names every parameter before C23, so one written as a ;;; A definition names every parameter before C23, so one written as a
;;; type alone gets a name nothing reads: ((int) (b int)) -> ((ƛu0 int) (b int)) ;;; type alone gets a name nothing reads: ((int) (b int)) -> ((λu0 int) (b int))
(define (named-parameters arglist) (define (named-parameters arglist)
(map (lambda (arg index) (map (lambda (arg index)
(if (or (named-arg? arg) (comment-form? arg) (if (or (named-arg? arg) (comment-form? arg)
(eq? arg '...) (equal? arg '(...))) (eq? arg '...) (equal? arg '(...)))
arg arg
(list (string->symbol (string-append "ƛu" (number->string index))) (list (string->symbol (string-append "λu" (number->string index)))
(unwrap-type arg)))) (unwrap-type arg))))
arglist arglist
(iota (length arglist)))) (iota (length arglist))))
;;; Captures are a closure's other parameters, and C's rule for those
;;; holds of them: no two alike, and none redeclared at the top of the
;;; body. A block inside may shadow one, as it may a parameter.
(define (check-capture-names form arglist names body)
(let ((parameters (filter-map (lambda (arg) (and (named-arg? arg) (car arg)))
(remove comment-form? arglist))))
(for-each (lambda (name)
(when (memq name parameters)
(sex-error form "a capture and a parameter share a name" name)))
names)
(for-each (lambda (statement)
(match statement
(('var (? symbol? name) . _)
(when (memq name names)
(sex-error statement "the body redeclares a capture" name)))
(_ #f)))
body)))
;;; A capture's field is assigned to, so it drops what qualifies the
;;; capture itself: (const int) is held as an int, and read back into a
;;; const one. (* const char) points at const, and is left alone.
(define (capture-field cap)
(let ((type (second cap)))
(list (first cap)
(if (and (pair? type) (memq (car type) '(const volatile)))
(let ((rest (drop-while (cut memq <> '(const volatile)) type)))
(if (null? (cdr rest)) (car rest) rest))
type))))
;;; The code's local for a capture, read back out of the record
(define (capture-local cap form)
(let ((name (first cap)) (type (second cap)))
(if (array-form? type)
`((var ,name ,type) ,(array-copy type name `(%-> ƛcaptures ,name) form))
`((var ,name ,type (%-> ƛcaptures ,name))))))
;;; The constructor's filling of a capture's field
(define (capture-store cap form)
(let ((name (first cap)) (type (second cap)))
(if (array-form? type)
(array-copy type `(%-> ƛcaptures ,name) name form)
`(= (%-> ƛcaptures ,name) ,name))))
;;; DEST, an array of TYPE, given SRC's elements one at a time: C copies
;;; an array neither by = nor through an initializer of another
;;;
;;; (for (var ƛi0 int 0) (< ƛi0 3) (++ ƛi0) (= [dest ƛi0] [src ƛi0]))
(define (array-copy type dest src form #!optional (depth 0))
(unless (array-bound? type)
(sex-error form "a captured array needs its length written" dest))
(let ((i (string->symbol (string-append "ƛi" (number->string depth))))
(element (array-element-type type)))
`(for (var ,i int 0) (< ,i ,(array-bound type)) (++ ,i)
,(if (array-form? element)
(array-copy element `(¤ ,dest ,i) `(¤ ,src ,i) form (+ depth 1))
`(= (¤ ,dest ,i) (¤ ,src ,i))))))
;;; Structs ;;; Structs
;;; Record the named structs, unions and enums in the type database ;;; Record the named structs, unions and enums in the type database
(define (process-struct sex-struct acc) (define (process-struct sex-struct acc)
(let-values (((doc form) (extract-aggregate-docstring sex-struct))) (let-values (((doc form) (extract-aggregate-docstring sex-struct)))
;; Resolve before registering: a field of closure type has to reach
;; the type database as the struct it becomes, or member access
;; through it finds nothing
(let ((form (resolve-closure-types form)))
(register-aggregate! form) (register-aggregate! form)
(with-docstring doc form acc)))) (with-docstring doc form acc)))
;;; (sum shape ((circle ((r float))) (rect ((w float) (h float))))) ;;; (sum shape ((circle ((r float))) (rect ((w float) (h float)))))
;;; is the tag enum, a payload struct per variant that has fields, the ;;; is the tag enum, a payload struct per variant that has fields, the
@@ -2268,16 +1617,15 @@
(set! (hash-table-ref env :scopes) (list)) (set! (hash-table-ref env :scopes) (list))
env)) env))
;;; The writer spells neither `closure' nor `_', and an initializer is ;;; The writer spells no `_', and an initializer is an expression like
;;; an expression like any other: ;;; any other:
;;; ;;;
;;; (var n _ 1) -> int n = 1 ;;; (var n _ 1) -> int n = 1
;;; (var o v #(v : (.get a))) -> v o = (v){vːget(&a)} ;;; (var o v #(v : (.get a))) -> v o = (v){vːget(&a)}
(define (process-global-var sex-var acc) (define (process-global-var sex-var acc)
(check-shape (if (memq (car sex-var) '(pub extern)) (cdr sex-var) sex-var)) (check-shape (if (memq (car sex-var) '(pub extern)) (cdr sex-var) sex-var))
(let* ((resolved (resolve-closure-types sex-var)) (let* ((qualifier (and (memq (car sex-var) '(pub extern)) (car sex-var)))
(qualifier (and (memq (car resolved) '(pub extern)) (car resolved))) (core (if qualifier (cdr sex-var) sex-var))
(core (if qualifier (cdr resolved) resolved))
(env (make-toplevel-env (and (pair? (cdr core)) (second core)))) (env (make-toplevel-env (and (pair? (cdr core)) (second core))))
;; `(extern var n int)' has no initializer to work a `_' out ;; `(extern var n int)' has no initializer to work a `_' out
;; from ;; from
@@ -2299,7 +1647,7 @@
(drop solved 3)))) (drop solved 3))))
solved)))) solved))))
(form (if qualifier (form (if qualifier
(copy-form-source! resolved (cons qualifier core)) (copy-form-source! sex-var (cons qualifier core))
core))) core)))
(when (and (pair? (cdr core)) (pair? (cddr core)) (symbol? (second core))) (when (and (pair? (cdr core)) (pair? (cddr core)) (symbol? (second core)))
(add-name-type! (second core) (third core))) (add-name-type! (second core) (third core)))

View File

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

View File

@@ -1,8 +1,40 @@
;;; sex-mode.el --- Major mode for Sex code -*- lexical-binding: t -*-
;; Copyright (C) 2025-2026 alex-eg
;; Author: alex-eg <alexey.e.egorov@gmail.com>
;; Version: 0.1.0
;; Package-Requires: ((emacs "28.1"))
;; Keywords: languages
;; URL: https://git.kotobank.ch/alex-eg/sex
;; This file is not part of GNU Emacs.
;;; Commentary:
;; Major mode for Sex, a compiled language with S-expression syntax.
;; The mode derives from `lisp-data-mode' and fontifies Sex
;; declarations and keywords.
;;
;; `sex-mode' is one file in the Sex repository. Quelpa installs it
;; from that git remote:
;;
;; (use-package sex-mode
;; :ensure nil
;; :quelpa
;; (sex-mode :fetcher git
;; :url "https://git.kotobank.ch/alex-eg/sex.git"
;; :files ("sex-mode.el")
;; :upgrade t))
;;
;; Visiting a .sex file turns the mode on.
;;; Code:
(require 'scheme) (require 'scheme)
(defgroup sex-mode nil (defgroup sex-mode nil
"Major mode for Sex code." "Major mode for Sex code."
:prefix 'sex- :prefix "sex-"
:group 'languages) :group 'languages)
(define-abbrev-table 'sex-mode-abbrev-table () (define-abbrev-table 'sex-mode-abbrev-table ()
@@ -11,8 +43,8 @@ It has `scheme-mode-abbrev-table' as its parent."
:parents (list scheme-mode-abbrev-table)) :parents (list scheme-mode-abbrev-table))
(defvar sex-mode-syntax-table (defvar sex-mode-syntax-table
(let ((table (make-syntax-table lisp-data-mode-syntax-table))) (make-syntax-table lisp-data-mode-syntax-table)
table)) "Syntax table used in Sex mode.")
(defvar sex-mode-map (defvar sex-mode-map
(let ((map (make-sparse-keymap))) (let ((map (make-sparse-keymap)))
@@ -21,58 +53,72 @@ It has `scheme-mode-abbrev-table' as its parent."
"Keymap for Sex mode. "Keymap for Sex mode.
All commands in `lisp-mode-shared-map' are inherited by this map.") All commands in `lisp-mode-shared-map' are inherited by this map.")
(defvar sex-mode-line-process "") (defvar sex-mode-line-process ""
"Mode-line process string for Sex mode.")
(defconst sex-font-lock-keywords (defconst sex-font-lock-keywords
(eval-when-compile (eval-when-compile
(list (list
;; Declarations ;; Declarations. `pub' and `extern' are optional prefixes, so
;; `(pub fn main' highlights both keywords and the name.
(list (concat "(" (list (concat "("
(regexp-opt '("chicken-define" "\\(?:\\(pub\\|extern\\)[[:space:]]+\\)?"
"chicken-define-syntax" (regexp-opt '("define"
"chicken-import"
"chicken-load"
"define"
"defmacro" "defmacro"
"extern" "enum"
"fn"
"import" "import"
"include" "include"
"fn"
"ops" "ops"
"pub"
"record" "record"
"realize"
"spec"
"struct" "struct"
"sum" "sum"
"var" "typedef"
"union") "union"
'word) "var")
"\\>" 'words)
"[[:space:]]*" "[[:space:]]*"
"\\([[:word:]]*\\)") "\\([[:word:]]*\\)")
'(1 font-lock-keyword-face) '(1 font-lock-keyword-face nil t)
'(2 font-lock-function-name-face)) '(2 font-lock-keyword-face)
;; Keywords '(3 font-lock-function-name-face nil t))
;; Statement and expression heads, plus the macro-language forms
;; that appear in `defmacro' bodies.
(list (concat "(" (list (concat "("
(regexp-opt '( (regexp-opt '("break"
"do" "c-bit-or"
"c-bit-or="
"c-or"
"case" "case"
"case/fallthrough"
"cast"
"continue"
"default" "default"
"do" "do"
"if" "else"
"for" "for"
"get-method"
"goto" "goto"
"if"
"lambda"
"map-fields"
"match" "match"
"return" "return"
"sizeof"
"static-assert"
"switch" "switch"
"var" "type-match"
"while") "type-of"
'word) "while"
"\\>") "$"
'(1 'font-lock-builtin-face))))) "."
":")
'words))
'(1 font-lock-builtin-face))))
"Font-lock keywords for Sex mode.")
(defun sex-mode-set-variables () (defun sex-mode-set-variables ()
"Set up buffer-local variables for Sex mode."
(set-syntax-table sex-mode-syntax-table) (set-syntax-table sex-mode-syntax-table)
(setq local-abbrev-table sex-mode-abbrev-table) (setq local-abbrev-table sex-mode-abbrev-table)
(setq mode-line-process '("" sex-mode-line-process)) (setq mode-line-process '("" sex-mode-line-process))
@@ -89,8 +135,6 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
(put 'defmacro 'lisp-indent-function 'defun) (put 'defmacro 'lisp-indent-function 'defun)
(put 'record 'lisp-indent-function 'defun) (put 'record 'lisp-indent-function 'defun)
(put 'sum 'lisp-indent-function 'defun) (put 'sum 'lisp-indent-function 'defun)
(put 'spec 'lisp-indent-function 'defun)
(put 'realize 'lisp-indent-function 'defun)
(put 'ops 'lisp-indent-function 'defun) (put 'ops 'lisp-indent-function 'defun)
(put 'match 'lisp-indent-function 1) (put 'match 'lisp-indent-function 1)
(put 'struct 'lisp-indent-function 'defun) (put 'struct 'lisp-indent-function 'defun)
@@ -113,6 +157,8 @@ Blank lines separate paragraphs. Semicolons start comments.
(sex-mode-set-variables)) (sex-mode-set-variables))
;;;###autoload ;;;###autoload
(add-to-list 'auto-mode-alist '("\\.\\(sex\\|hsex\\)\\'" . sex-mode)) (add-to-list 'auto-mode-alist '("\\.sex\\'" . sex-mode))
(provide 'sex-mode) (provide 'sex-mode)
;;; sex-mode.el ends here

View File

@@ -130,10 +130,11 @@
;;; macros are the module's own and those its imports give it, lent for ;;; macros are the module's own and those its imports give it, lent for
;;; the expanding and taken back after, so the importer is left with the ;;; the expanding and taken back after, so the importer is left with the
;;; pub ones alone. One that reads the type database sees what the ;;; pub ones alone. One that reads the type database sees what the
;;; importer knows, which a type private to the module is not; a call ;;; importer knows, which no declaration of the module's is yet; a call
;;; that cannot expand for that -- (print-struct box), box being the ;;; that fails after asking for one -- (field-count box), box being the
;;; module's -- gives importers nothing, as before, and is the module's ;;; module's record -- gives importers nothing, as before, and is the
;;; own compile's to check ;;; module's own compile's to check. Any other failure is the importer's
;;; too: (boom) raising "nope" says so wherever it is read
(define +modules-expanded+ (list)) (define +modules-expanded+ (list))
(define (module-forms raw-forms) (define (module-forms raw-forms)
@@ -144,7 +145,8 @@
forms)))) forms))))
(define (expanded raw-forms) (define (expanded raw-forms)
(let ((lent (list))) (let ((lent (list))
(declared (declared-names raw-forms)))
(define (lend! form) (define (lend! form)
(let ((name (macro-name form))) (let ((name (macro-name form)))
(unless (assq name lent) (unless (assq name lent)
@@ -154,14 +156,36 @@
(cond ((macro-name form) (lend! form) (list form)) (cond ((macro-name form) (lend! form) (list form))
((splice? form) (append-map expand (cdr form))) ((splice? form) (append-map expand (cdr form)))
((macro? form) ((macro? form)
(let ((result (handle-exceptions exn #f (apply-macro form)))) (let ((result (expand-call form declared)))
(cond ((or (not result) (null? result)) (list)) (cond ((or (not result) (null? result)) (list))
(else (stamp-form-source! result (form-source form)) (else (stamp-form-source! result (form-source form))
(expand result))))) (expand result)))))
(else (list form)))) (else (list form))))
(dynamic-wind
void
(lambda ()
(for-each lend! (imported-macro-forms raw-forms)) (for-each lend! (imported-macro-forms raw-forms))
(let ((forms (append-map expand raw-forms))) (append-map expand raw-forms))
(for-each (lambda (entry) (restore-macro! (car entry) (cdr entry))) lent) (lambda ()
(for-each (lambda (entry) (restore-macro! (car entry) (cdr entry)))
lent)))))
(define (expand-call form declared)
(let ((unknown (list)))
(handle-exceptions exn
(if (any (lambda (name) (memq name declared)) unknown) #f (abort exn))
(parameterize ((unknown-name (lambda (name) (set! unknown (cons name unknown)))))
(apply-macro form)))))
;;; The names FORMS declare, types and all
(define (declared-names forms)
(append (map car (declared-types forms))
(filter-map (lambda (form)
(match form
((or ('pub (or 'fn 'var) (? symbol? name) . _)
((or 'fn 'var) (? symbol? name) . _))
name)
(_ #f)))
forms))) forms)))
(define (splice? form) (define (splice? form)
@@ -246,7 +270,6 @@
(fold (fold
(lambda (form acc) (lambda (form acc)
(check-written-out form) (check-written-out form)
(check-realized-spec form visible hidden)
(fold (lambda (use acc) (check-type-use form use visible hidden acc)) (fold (lambda (use acc) (check-type-use form use visible hidden acc))
acc acc
(append-map (lambda (type) (type-uses type #f)) (append-map (lambda (type) (type-uses type #f))
@@ -268,22 +291,6 @@
(_ #f))) (_ #f)))
(_ #f))) (_ #f)))
;;; A pub realization goes to importers, who look its spec up; one they
;;; cannot see failed there, in whichever named this module before the
;;; spec's, and said nothing of where it was written
(define (check-realized-spec form visible hidden)
(match form
(('pub 'realize ((? symbol? spec) _) . _)
(let ((kept (assq spec hidden)))
(when (and kept (not (assq spec visible)))
(sex-error form
(string-append "importers cannot see this spec; "
(if (fourth kept)
"import its module with pub"
"make it pub"))
spec))))
(_ #f)))
;;; USE is (name . behind-a-pointer?) ;;; USE is (name . behind-a-pointer?)
(define (check-type-use form use visible hidden acc) (define (check-type-use form use visible hidden acc)
(let* ((name (car use)) (let* ((name (car use))
@@ -339,9 +346,6 @@
(remove comment-form? variants))) (remove comment-form? variants)))
(('ops type . methods) (('ops type . methods)
(append-map interface-types (filter pub-form? 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)))
(_ (list)))) (_ (list))))
(define (field-types fields) (define (field-types fields)
@@ -368,7 +372,7 @@
((¤) (let ((element (array-element-type type))) ((¤) (let ((element (array-element-type type)))
(append (if element (type-uses element behind?) (list)) (append (if element (type-uses element behind?) (list))
(if (array-bound? type) (bound-uses (array-bound type)) (list))))) (if (array-bound? type) (bound-uses (array-bound type)) (list)))))
((fn closure) ((fn)
(if (and (pair? (cdr type)) (list? (second type))) (if (and (pair? (cdr type)) (list? (second type)))
(append-map (lambda (t) (type-uses t #f)) (append-map (lambda (t) (type-uses t #f))
(signature-types (second type) (last type))) (signature-types (second type) (last type)))
@@ -385,24 +389,23 @@
((pair? bound) (append-map bound-uses (cdr bound))) ((pair? bound) (append-map bound-uses (cdr bound)))
(else (list)))) (else (list))))
;;; The types, constants and specs FORMS declare, as (name kind body?): ;;; The types and constants FORMS declare, as (name kind body?):
;;; ;;;
;;; (pub record tally) -> (tally record #f) ;;; (pub record tally) -> (tally record #f)
;;; (sum colour ((none ()))) -> (colour sum #t) ;;; (sum colour ((none ()))) -> (colour sum #t)
;;; (define (sq x) (* x x)) -> (sq define #t) ;;; (define (sq x) (* x x)) -> (sq define #t)
;;; (spec (shown T) ...) -> (shown spec #t)
(define (declared-types forms) (define (declared-types forms)
(filter-map (filter-map
(lambda (form) (lambda (form)
(and (pair? form) (and (pair? form)
(let* ((core (strip-pub form)) (let* ((core (strip-pub form))
(name (and (pair? core) (pair? (cdr core)) (name (and (pair? core) (pair? (cdr core))
(if (and (memq (car core) '(define spec)) (if (and (eq? (car core) 'define)
(pair? (second core))) (pair? (second core)))
(car (second core)) (car (second core))
(second core))))) (second core)))))
(and (memq (car core) (and (memq (car core)
'(record struct union enum sum typedef define spec)) '(record struct union enum sum typedef define))
(symbol? name) (symbol? name)
(list name (list name
(car core) (car core)
@@ -496,19 +499,6 @@
(copy-form-source! form (copy-form-source! form
`(ops ,type ,@(map public-fn-interface methods)))))) `(ops ,type ,@(map public-fn-interface methods))))))
;;; A realization leaves with the methods written in it, reduced to
;;; prototypes. Its defaults do not travel: the importer synthesizes
;;; its own static copies from the spec, which is why a default is
;;; static even when the realization is pub.
(define (realize-public-interface form)
(let ((core (cdr form)))
(copy-form-source!
form
`(pub realize ,(second core)
;; pub goes back on at the realize, not on its methods
,@(map (lambda (m) (cdr (public-fn-interface (cons 'pub m))))
(remove comment-form? (cddr core)))))))
;;; TODO: use semen facilities to analyze modules ;;; TODO: use semen facilities to analyze modules
(define (process-public-interface-form form acc) (define (process-public-interface-form form acc)
(match form (match form
@@ -519,13 +509,11 @@
(('pub 'var . _) (('pub 'var . _)
(match-let ((('pub 'var name type . _) (strip-header-comments form 4))) (match-let ((('pub 'var name type . _) (strip-header-comments form 4)))
(cons (copy-form-source! form `(extern var ,name ,type)) acc))) (cons (copy-form-source! form `(extern var ,name ,type)) acc)))
(('pub (or 'define 'defmacro 'enum 'import 'include 'record 'spec 'struct 'sum 'typedef 'union) . _) (('pub (or 'define 'defmacro 'enum 'import 'include 'record 'struct 'sum 'typedef 'union) . _)
(cons (copy-form-source! form (cdr form)) acc)) (cons (copy-form-source! form (cdr form)) acc))
(('ops . _) (('ops . _)
(let ((exported (ops-public-interface form))) (let ((exported (ops-public-interface form)))
(if exported (cons exported acc) acc))) (if exported (cons exported acc) acc)))
(('pub 'realize . _)
(cons (realize-public-interface form) acc))
(('pub . _) (('pub . _)
(sex-error form "pub must be followed by a definition" form)) (sex-error form "pub must be followed by a definition" form))
(_ acc))) (_ acc)))

View File

@@ -257,10 +257,9 @@ status, which is ours to pass on."
(with-directory input-source (process))))) (with-directory input-source (process)))))
(define prelude (define prelude
(append
'((include inttypes.h) '((include inttypes.h)
(include stdbool.h) (include stdbool.h)
(include stddef.h) ; max_align_t, for closure environments (include stddef.h)
(typedef u8 uint8-t) (typedef u8 uint8-t)
(typedef i8 int8-t) (typedef i8 int8-t)
(typedef u16 uint16-t) (typedef u16 uint16-t)
@@ -268,11 +267,7 @@ status, which is ours to pass on."
(typedef u32 uint32-t) (typedef u32 uint32-t)
(typedef i32 int32-t) (typedef i32 int32-t)
(typedef u64 uint64-t) (typedef u64 uint64-t)
(typedef i64 int64-t)) (typedef i64 int64-t)))
;; The closure environment is the part of the ABI, so include it in
;; every module
(list (closure-env-declaration))))
;;; An error is told by its message, file:line first where it has one. ;;; An error is told by its message, file:line first where it has one.
;;; CHICKEN's call history after it is for working on sexc itself, and ;;; CHICKEN's call history after it is for working on sexc itself, and

View File

@@ -474,49 +474,12 @@
(not (emits? (in-fn "(static-assert (== (sizeof int) 4) \"x\")") (not (emits? (in-fn "(static-assert (== (sizeof int) 4) \"x\")")
"static_assert(")))) "static_assert("))))
;; A closure is a code pointer beside its captures. The struct is (test-group "lambdas"
;; named from the signature, so separate translation units agree on ;; a definition names every parameter before C23, so one written as a
;; it, and calling one goes through `code' with `env' passed first. ;; type alone gets a name nothing reads
;;
;; A closure struct, and the helper its calls go through, are each
;; emitted once per signature; the registries deciding that are
;; compile-time state like the type databases, and outlive a single
;; `sex->c' here. So every case below that looks for a *definition*
;; uses a signature of its own -- cases looking at a call site can
;; share one.
(test-group "closures"
(test-assert "the type becomes a struct named for its signature"
(emits? "(fn f ((c (closure ((int)) int))) int (return (c 1)))"
"struct ƛint_int"))
;; captures are a closure's other parameters, under C's rule for
;; those: no two alike, and none redeclared at the body's top level.
;; Both were C's redefinition errors
;; ((+ a 1)) was a capture named `+', holding a
(test-assert "a capture is a name, or a name and a value"
(reports? (in-fn "(var c (closure () int) (closure () int ((+ a 1)) (return 1)))")
"a capture is a name, or (name value)"))
(test-assert "a capture named like a parameter is refused"
(reports? (in-fn "(var c (closure ((int)) int) (closure ((a int)) int (a) (return a)))")
"a capture and a parameter share a name"))
(test-assert "so is one redeclared at the top of the body"
(reports? (in-fn "(var c (closure () int) (closure () int (a) (var a int 5) (return a)))")
"the body redeclares a capture"))
(test-assert "while a block inside may shadow it"
(emits? (in-fn "(var c (closure () int) (closure () int (a) (do (var a int 5) (g a)) (return a)))")
"int a = 5;"))
;; the closure's type was built from each parameter's second element,
;; which a type alone has none of
(test-assert "a parameter may name nothing"
(emits? (in-fn "(var c (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b)))")
"struct ƛint__int"))
(test-assert "and its code names it, a definition needing one before C23"
(emits? (in-fn "(var c (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b)))")
"int ƛu0, int b)"))
;; a definition names every parameter before C23, a lambda's as a
;; closure's code does
(test-assert "a lambda's unnamed parameter is named in its definition" (test-assert "a lambda's unnamed parameter is named in its definition"
(emits? "(fn f () void (var g (fn ((int) (int)) int) (lambda ((int) (b int)) int (return b))))" (emits? "(fn f () void (var g (fn ((int) (int)) int) (lambda ((int) (b int)) int (return b))))"
"λ0_f (int ƛu0, int b)")) "λ0_f (int λu0, int b)"))
(test-assert "and a variadic one keeps its ..." (test-assert "and a variadic one keeps its ..."
(emits? "(fn f () void (var g (fn ((int) ...) int) (lambda ((n int) ...) int (return n))))" (emits? "(fn f () void (var g (fn ((int) ...) int) (lambda ((n int) ...) int (return n))))"
"λ0_f (int n, ...)")) "λ0_f (int n, ...)"))
@@ -524,120 +487,7 @@
;; nothing defined it ;; nothing defined it
(test-assert "an empty lambda is an empty function" (test-assert "an empty lambda is an empty function"
(emits? "(fn f () void (var g (fn () void) (lambda () void)))" (emits? "(fn f () void (var g (fn () void) (lambda () void)))"
"static void λ0_f (void) {}")) "static void λ0_f (void) {}")))
(test-assert "so is an empty closure's code"
(emits? (in-fn "(var c (closure () void) (closure () void ()))") "(void * ƛe) {}"))
;; the call helper would have to forward the rest, which C cannot
(test-assert "a closure cannot be variadic"
(reports? (in-fn "(var c _ (closure ((n int) ...) int () (return n)))")
"a closure cannot be variadic; a lambda can"))
;; The environment is one shared union, declared in the prelude --
;; its layout is part of the ABI two units agree on, so it cannot
;; depend on what either file contains. `sex->c' has no prelude, so
;; what is visible here is the member
(test-assert "whose environment is the shared union"
(emits? "(fn f ((c (closure ((float)) int))) int (return (c 1.0)))"
"union ƛenv env;"))
;; The receiver goes through a helper rather than being written
;; out twice, so that `[table (++ i)]' evaluates its index once,
;; exactly as it would for an array of function pointers
(test-assert "a call passes the receiver to a helper"
(emits? "(fn f ((c (closure ((int)) int))) int (return (c 1)))"
"ƛint_int_call(c, 1)"))
(test-assert "and the helper is what dereferences it"
(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)))"
"ƛint_int_call(t[++i], 1)"))
(test-assert "so is a member receiver"
(emits? "(struct h ((cb (closure ((int)) int))))
(fn f ((s (struct h))) int (return ((. s cb) 1)))"
"ƛint_int_call(s.cb, 1)"))
(test-assert "a captured name is rebound in the lifted body"
(emits? "(fn f ((n int)) (closure ((char)) int) (return (closure ((x char)) int (n) (return n))))"
"int n = ƛcaptures->n;"))
(test-assert "captures are checked against the environment"
(emits? "(fn f ((n int)) (closure ((short)) int) (return (closure ((x short)) int (n) (return n))))"
"_Static_assert(sizeof(struct"))
;; A closure over nothing has no record to point at, and C has no
;; empty struct to declare for it
(test-assert "no captures means no capture record"
(not (emits? "(fn f () (closure () int) (return (closure () int () (return 7))))"
"_captures {")))
;; `(name expr)' names a capture and gives what it holds, so the
;; expression is evaluated once, where the closure is written
(test-assert "a named capture takes its type from the expression"
(emits? "(struct p ((x int) (y int)))
(fn f ((s (struct p))) (closure () int)
(return (closure () int ((sum (+ (. s x) (. s y)))) (return sum))))"
"int sum;"))
(test-assert "and the constructor is handed the expression"
(emits? "(struct p ((x int) (y int)))
(fn f ((s (struct p))) (closure () int)
(return (closure () int ((sum (+ (. s x) (. s y)))) (return sum))))"
"_make(s.x + s.y)"))
(test-assert "capturing a pointer is how by-reference is spelled"
(emits? "(struct p ((x int)))
(fn f ((s (* (struct p)))) (closure () int)
(return (closure () int ((q s)) (return (-> q x)))))"
"struct p* q;"))
;; A bare function is a closure that captures nothing, so it
;; converts wherever one is expected -- the pointer goes in the
;; environment and one thunk per signature reads it back out
(test-assert "a named function in a var initializer"
(emits? "(fn g ((n int)) int (return n))
(fn f () void (var c (closure ((int)) int) g))"
"ƛint_int_fromfn(g)"))
(test-assert "a lambda, which is a bare function too"
(emits? "(fn f () void (var c (closure ((int)) int)
(lambda ((n int)) int (return n))))"
"ƛint_int_fromfn(λ0_f)"))
(test-assert "an argument, against the parameter that signature wrote"
(emits? "(fn g ((n int)) int (return n))
(fn h ((c (closure ((int)) int))) int (return (c 1)))
(fn f () int (return (h g)))"
"h(ƛint_int_fromfn(g))"))
(test-assert "a return, against the declared return type"
(emits? "(fn g ((n int)) int (return n))
(fn f () (closure ((int)) int) (return g))"
"return ƛint_int_fromfn(g)"))
(test-assert "the thunk reads the pointer out of the environment"
(emits? "(fn g ((n float)) int (return 1))
(fn f () void (var c (closure ((float)) int) g))"
"return ƛcaptures->f(ƛa0)"))
;; a signature that does not match is left alone, and C rejects it
(test-assert "a function of the wrong signature does not convert"
(not (emits? "(fn g ((n float)) int (return 1))
(fn f () void (var c (closure ((int)) int) g))"
"_fromfn(g)")))
;; a closure is lifted into the function it was written in, so
;; there has to be one
(test-assert "a closure at toplevel is refused"
(reports? "(var c (closure () int) (closure () int () (return 1)))"
"only be written inside a function"))
(test-assert "and so is one in a struct field"
(reports? "(struct s ((f (closure () int) (closure () int () (return 1)))))"
"only be written inside a function"))
;; A block opens a scope, so what it declares ends with it
(test-assert "a name shadowed in a block does not escape it"
(emits? "(fn mk () (closure () int) (return (closure () int () (return 1))))
(fn f () int (var c (closure () int) (mk))
(do (var c int 9) (g c))
(return (c)))"
"ƛvoid_int_call(c)"))
(test-assert "and the shadowing declaration is what the block sees"
(emits? "(fn mk () (closure () int) (return (closure () int () (return 1))))
(fn f () int (var c (closure () int) (mk))
(do (var c int 9) (g c))
(return (c)))"
"g(c)"))
;; The receiver is written twice, so a name used as an argument
;; must not be mistaken for a call of its own
(test-assert "a closure passed as an argument stays a value"
(emits? "(fn g ((c (closure ((int)) int))) int (return 0))
(fn f ((c (closure ((int)) int))) int (return (g c)))"
"g(c)")))
;; An include target is a path, so none of the identifier mangling ;; An include target is a path, so none of the identifier mangling
;; applies to it: GL/gl.h is a file and GLːgl.h is not. ;; applies to it: GL/gl.h is a file and GLːgl.h is not.
@@ -693,16 +543,16 @@
(defmacro (t x) (type-match (type-of x) (float 1) (else 0))) (defmacro (t x) (type-match (type-of x) (float 1) (else 0)))
(fn f () int (return (t (g))))" (fn f () int (return (t (g))))"
"return 1;")) "return 1;"))
;; a macro is shown the written spelling, not the generated struct ;; a macro is shown the written spelling, not a generated name
(test-assert "a closure, spelled the way it was written" (test-assert "a function pointer, spelled the way it was written"
(emits? "(fn mk () (closure ((int)) int) (emits? "(fn mk () (fn ((int)) int)
(return (closure ((b int)) int () (return b)))) (return (lambda ((b int)) int (return b))))
(defmacro (t x) (type-match (type-of x) ((closure _ _) 1) (else 0))) (defmacro (t x) (type-match (type-of x) ((fn _ _) 1) (else 0)))
(fn f () int (var c _ (mk)) (return (t c)))" (fn f () int (var c _ (mk)) (return (t c)))"
"return 1;")) "return 1;"))
(test-assert "and calling one has the closure's return type" (test-assert "and calling one has the function's return type"
(emits? "(fn mk () (closure ((int)) int) (emits? "(fn mk () (fn ((int)) int)
(return (closure ((b int)) int () (return b)))) (return (lambda ((b int)) int (return b))))
(defmacro (t x) (type-match (type-of x) (int 1) (else 0))) (defmacro (t x) (type-match (type-of x) (int 1) (else 0)))
(fn f () int (var c _ (mk)) (return (t (c 1))))" (fn f () int (var c _ (mk)) (return (t (c 1))))"
"return 1;")) "return 1;"))
@@ -783,9 +633,6 @@
(test-assert "a lambda's as well" (test-assert "a lambda's as well"
(reports? (in-fn "(var l (fn ((int)) int) (lambda ((x _)) int (return x)))") (reports? (in-fn "(var l (fn ((int)) int) (lambda ((x _)) int (return x)))")
"a function's types are written out")) "a function's types are written out"))
(test-assert "and a closure's"
(reports? (in-fn "(var c (closure ((int)) int) (closure ((x int)) _ () (return x)))")
"a function's types are written out"))
;; a call was typed by asking the global table what a function of ;; a call was typed by asking the global table what a function of
;; that name returns, which a local pointer is not ;; that name returns, which a local pointer is not
;; a value if had no rule either: it is the join of its values ;; a value if had no rule either: it is the join of its values
@@ -817,13 +664,6 @@
(emits? (string-append "(struct ops ((op (fn ((int)) float))))" (emits? (string-append "(struct ops ((op (fn ((int)) float))))"
"(fn f ((o (struct ops))) void (var r _ ((. o op) 1)))") "(fn f ((o (struct ops))) void (var r _ ((. o op) 1)))")
"float r = o.op(1)")) "float r = o.op(1)"))
(test-assert "a closure's call, which goes through a helper nothing typed"
(emits? "(fn f ((c (closure ((int)) int))) void (var r _ (c 4)))"
"int r = ƛint_int_call(c, 4)"))
(test-assert "and one returning a closure is called as one"
(emits? (string-append "(fn mk ((k int)) (closure ((int)) int) (return (closure ((b int)) int (k) (return (+ k b)))))"
"(fn f () void (var fp (fn ((int)) (closure ((int)) int)) mk) (var r _ ((fp 3) 4)))")
"int r = ƛint_int_call(fp(3), 4)"))
(test-assert "while a function is the pointer it already is" (test-assert "while a function is the pointer it already is"
(emits? "(fn g ((n int)) int (return n)) (fn f () void (var p _ g))" (emits? "(fn g ((n int)) int (return n)) (fn f () void (var p _ g))"
"int (*p)(int) = g")) "int (*p)(int) = g"))
@@ -876,18 +716,17 @@
(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" (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 ;; a function pointer type reaches the solver as itself
;; it, which is the spelling `parse-type' knows (test-assert "a lambda, from the signature that produced it"
(test-assert "a closure, from the signature that produced it" (emits? "(fn mk () (fn ((int)) int)
(emits? "(fn mk () (closure ((int)) int) (return (lambda ((b int)) int (return b))))
(return (closure ((b int)) int () (return b))))
(fn f () void (var c _ (mk)))" (fn f () void (var c _ (mk)))"
"struct ƛint_int c = mk()")) "int (*c)(int) = mk()"))
(test-assert "and it is callable once inferred" (test-assert "and it is callable once inferred"
(emits? "(fn mk () (closure ((int)) int) (emits? "(fn mk () (fn ((int)) int)
(return (closure ((b int)) int () (return b)))) (return (lambda ((b int)) int (return b))))
(fn f () int (var c _ (mk)) (return (c 1)))" (fn f () int (var c _ (mk)) (return (c 1)))"
"ƛint_int_call(c, 1)")) "return c(1)"))
;; C's usual arithmetic conversions, far enough to answer `_' ;; C's usual arithmetic conversions, far enough to answer `_'
(test-assert "floating beats integral" (test-assert "floating beats integral"
(emits? (in-fn "(var d double 1.0) (var x _ (+ a d))") "double x = a + d")) (emits? (in-fn "(var d double 1.0) (var x _ (+ a d))") "double x = a + d"))
@@ -961,16 +800,16 @@
;; without `$' a list is one form, so a head that is itself a form ;; without `$' a list is one form, so a head that is itself a form
;; stays a call rather than becoming two statements ;; stays a call rather than becoming two statements
(test-assert "a computed callee stays one form" (test-assert "a computed callee stays one form"
(emits? "(fn mk () (closure ((int)) int) (emits? "(fn mk () (fn ((int)) int)
(return (closure ((b int)) int () (return b)))) (return (lambda ((b int)) int (return b))))
(defmacro (apply-it x) `((mk) ,x)) (defmacro (apply-it x) `((mk) ,x))
(fn f () int (return (apply-it 5)))" (fn f () int (return (apply-it 5)))"
"ƛint_int_call(mk(), 5)")) "mk()(5)"))
;; spliced, it would have become two forms in the `return' -- the ;; spliced, it would have become two forms in the `return' -- the
;; comma operator, and the wrong answer ;; comma operator, and the wrong answer
(test-assert "rather than two forms in its context" (test-assert "rather than two forms in its context"
(not (emits? "(fn mk () (closure ((int)) int) (not (emits? "(fn mk () (fn ((int)) int)
(return (closure ((b int)) int () (return b)))) (return (lambda ((b int)) int (return b))))
(defmacro (apply-it x) `((mk) ,x)) (defmacro (apply-it x) `((mk) ,x))
(fn f () int (return (apply-it 5)))" (fn f () int (return (apply-it 5)))"
"return mk(), 5")))) "return mk(), 5"))))
@@ -1187,7 +1026,10 @@
(emits? (in-fn "(var n (unsigned int) -1u)") "n = -1u;")) (emits? (in-fn "(var n (unsigned int) -1u)") "n = -1u;"))
(test-assert "a number too wide for long long is unsigned, and says so" (test-assert "a number too wide for long long is unsigned, and says so"
(emits? (in-fn "(var n (unsigned long long) 0xFFFFFFFFFFFFFFFF)") (emits? (in-fn "(var n (unsigned long long) 0xFFFFFFFFFFFFFFFF)")
"n = 18446744073709551615u;"))) "n = 18446744073709551615u;"))
(test-assert "the least long long is spelled as LLONG_MIN, and typed"
(emits? (in-fn "(var n _ -9223372036854775808)")
"long long n = -9223372036854775807 - 1;")))
;; A define's body was pasted unwalked, and unparenthesised: `cast' ;; A define's body was pasted unwalked, and unparenthesised: `cast'
;; stayed a call, and (* x D) regrouped with D's own operator ;; stayed a call, and (* x D) regrouped with D's own operator

View File

@@ -42,16 +42,6 @@ ahead of its pub forms."
"(fn f () void (var s shape (shape/circle 1.0)) (var out float 0.0) " "(fn f () void (var s shape (shape/circle 1.0)) (var out float 0.0) "
(apply string-append body) ")")) (apply string-append body) ")"))
(define (spec-src . body)
(string-append
"(record v ((x int)))"
"(spec (p T)"
" (fn s ((self (* const T))) void)"
" (fn both ((self (* const T))) void (.s self)))"
"(realize (p v)"
" (fn s ((self (* const v))) void (return)))"
(apply string-append body)))
(test-group "encapsulation" (test-group "encapsulation"
;; A record is a struct plus a typedef of its own name, so the bare ;; A record is a struct plus a typedef of its own name, so the bare
@@ -279,12 +269,12 @@ ahead of its pub forms."
(reports? "(sum box ((inner ((x [box 2])))))" "a sum holds itself through a pointer")) (reports? "(sum box ((inner ((x [box 2])))))" "a sum holds itself through a pointer"))
(test-assert "though it can point at itself" (test-assert "though it can point at itself"
(emits? "(sum box ((inner ((x (* box))))))" "box * x;")) (emits? "(sum box ((inner ((x (* box))))))" "box * x;"))
(test-assert "a function argument becomes the closure its field holds" (test-assert "a function fills a function-pointer field"
(emits? (string-append (emits? (string-append
"(fn g ((n int)) int (return n))" "(fn g ((n int)) int (return n))"
"(sum t ((a ((k (closure ((int)) int))))))" "(sum t ((a ((k (fn ((int)) int))))))"
"(fn f () t (return (t/a g)))") "(fn f () t (return (t/a g)))")
"ƛint_int_fromfn(g)")) "(struct tːa){g}"))
(test-assert "a tag-only sum has no union at all" (test-assert "a tag-only sum has no union at all"
(not (emits? "(sum light ((red ()) (green ())))" "union"))) (not (emits? "(sum light ((red ()) (green ())))" "union")))
(test-assert "a sum is declared once" (test-assert "a sum is declared once"
@@ -296,104 +286,6 @@ ahead of its pub forms."
(test-assert "and is declared once" (test-assert "and is declared once"
(reports? "(sum t ((a ((x int))) (a ())))" "variant is declared twice"))) (reports? "(sum t ((a ((x int))) (a ())))" "variant is declared twice")))
;; A spec is a contract that emits nothing; a realization is its
;; methods for one type. The refusals are what make it a contract.
(test-group "spec and realize"
(test-assert "a spec on its own emits nothing"
(not (emits? "(spec (p T) (fn s ((a (* const T))) void))" "p")))
(test-assert "a realization mangles type, spec and method"
(emits? (spec-src "") "void vːpːs"))
(test-assert "a default is copied per realizing type"
(emits? (spec-src "") "vːpːboth"))
(test-assert "and its parameter is substituted"
(emits? (spec-src "") "void vːpːboth (const v * self)"))
(test-assert "a default calls that type's own required method"
(emits? (spec-src "") "vːpːs(self)"))
(test-assert "a default is static even when the realization is pub"
(emits? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void)"
" (fn d ((a (* const T))) void (.s a)))"
"(pub realize (p v)"
" (fn s ((a (* const v))) void (return)))")
"static void vːpːd"))
(test-assert "but a written method is not"
(not (emits? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(pub realize (p v)"
" (fn s ((a (* const v))) void (return)))")
"static void vːpːs")))
(test-assert "a spec method answers to .method"
(emits? (spec-src "(fn f () void (var a v #(v : 1)) (.s (& a)))") "vːpːs(&a)"))
(test-assert "a spec is declared once"
(reports? "(spec (p T) (fn s ((a T)) void))(spec (p T) (fn q ((a T)) void))"
"spec is already declared"))
(test-assert "a typedef realizes what its type does"
(reports? (string-append (spec-src "") "(typedef alias v)(realize (p alias))")
"spec is already realized for"))
(test-assert "a type realizes a spec once"
(reports? (string-append (spec-src "") "(realize (p v)"
" (fn s ((a (* const v))) void (return)))")
"spec is already realized for"))
(test-assert "a realization names a spec that exists"
(reports? "(record v ((x int)))(realize (nope v))" "no such spec"))
(test-assert "every required method is provided"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void)"
" (fn q ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) void (return)))")
"realization is missing a method of"))
(test-assert "and the missing one is named"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void)"
" (fn q ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) void (return)))")
"q"))
(test-assert "a docstring is not a body"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void \"doc\"))"
"(realize (p v))")
"realization is missing a method of"))
(test-assert "nor is a comment"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) int\n"
" ;; must be implemented\n"
" ))"
"(realize (p v))")
"realization is missing a method of"))
(test-assert "a documented default is still a default"
(emits? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) int \"doc\" (return 1)))"
"(realize (p v))")
"/* doc */"))
(test-assert "a method the spec has not got is refused"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) void (return))"
" (fn z ((a (* const v))) void (return)))")
"spec has no such method"))
(test-assert "a return type has to match the spec"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) int (return 1)))")
"return type does not match"))
(test-assert "so do the arguments"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(realize (p v) (fn s ((a v)) void (return)))")
"arguments do not match"))
(test-assert "but not on how a pointer is spelled"
(emits? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a * const T)) void))"
"(realize (p v) (fn s ((a (* const v))) void (return)))")
"void vːpːs (const v * a)"))
(test-assert "a method name already taken on the type is refused"
(reports? (string-append "(record v ((x int)))"
"(ops v (fn s ((a (* const v))) void (return)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) void (return)))")
"method is already defined on")))
;; match is an if over the tag whose arms bind the payload. What ;; match is an if over the tag whose arms bind the payload. What
;; it refuses is why it exists. ;; it refuses is why it exists.
(test-group "match" (test-group "match"
@@ -416,18 +308,18 @@ ahead of its pub forms."
").h"))) ").h")))
(test-assert "a scrutinee that is not a path is read once" (test-assert "a scrutinee that is not a path is read once"
(emits? (sum-src "(match (mk) ((circle (r)) (= out r)) (else (= out 0.0)))") (emits? (sum-src "(match (mk) ((circle (r)) (= out r)) (else (= out 0.0)))")
"shape ƛm0 = mk()")) "shape λm0 = mk()"))
(test-assert "a path scrutinee is not copied" (test-assert "a path scrutinee is not copied"
(not (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))") (not (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))")
"ƛm0"))) "λm0")))
(test-assert "unless a binder is named like a part of it" (test-assert "unless a binder is named like a part of it"
(emits? (sum-src "(match s ((circle (s)) (= out s)) (else (= out 0.0)))") (emits? (sum-src "(match s ((circle (s)) (= out s)) (else (= out 0.0)))")
"shape ƛm0 = s")) "shape λm0 = s"))
(test-assert "a macro scrutinee is typed by what it expands to" (test-assert "a macro scrutinee is typed by what it expands to"
(emits? (string-append "(defmacro (the a) a)" (emits? (string-append "(defmacro (the a) a)"
(sum-src "(match (the s) ((circle (r)) (= out r))" (sum-src "(match (the s) ((circle (r)) (= out r))"
" (else (= out 0.0)))")) " (else (= out 0.0)))"))
"shape ƛm0 = s")) "shape λm0 = s"))
(test-assert "a typedef of a sum is matched as the sum" (test-assert "a typedef of a sum is matched as the sum"
(emits? (string-append (emits? (string-append
"(sum shape ((circle ((r int))) (empty ())))" "(sum shape ((circle ((r int))) (empty ())))"
@@ -500,10 +392,10 @@ ahead of its pub forms."
(emits? (sum-src "(switch 1 (case 1 (match s ((circle (r)) (= out r))" (emits? (sum-src "(switch 1 (case 1 (match s ((circle (r)) (= out r))"
" (else (= out 0.0)))))") " (else (= out 0.0)))))")
"s.tag == shapeǂcircle")) "s.tag == shapeǂcircle"))
(test-assert "and so is a closure's, wherever the closure stands" (test-assert "and so is a lambda's, wherever the lambda stands"
(emits? (sum-src "(var c (closure () int) (closure () int ((t s))" (emits? (sum-src "(var c (fn ((shape)) int) (lambda ((v shape)) int"
" (match t ((circle (r)) (return 1)) (else (return 0)))))") " (match v ((circle (r)) (return 1)) (else (return 0)))))")
"t.tag == shapeǂcircle")) "v.tag == shapeǂcircle"))
;; a pointer to one was refused, where `.' reads through one ;; a pointer to one was refused, where `.' reads through one
;; a variant with fields is a member of the sum's union, which C ;; a variant with fields is a member of the sum's union, which C
;; would not take named `int' ;; would not take named `int'
@@ -557,17 +449,6 @@ ahead of its pub forms."
(interface-reports? "(pub var n _ 42)" "write it out")) (interface-reports? "(pub var n _ 42)" "write it out"))
(test-assert "all of it" (test-assert "all of it"
(interface-reports? "(pub var p (* _) 0)" "write it out")) (interface-reports? "(pub var p (* _) 0)" "write it out"))
;; a spec is seen by importers as a type is: pub, or not at all
(test-assert "a pub realization of a private spec is refused"
(interface-reports? (string-append "(spec (shown T) (fn show ((self (* const T))) int))"
"(pub record m ((c int)))"
"(pub realize (shown m) (fn show ((self (* const m))) int (return 1)))")
"importers cannot see this spec; make it pub"))
(test "and of a pub one is not"
'()
(interface-of (string-append "(pub spec (shown T) (fn show ((self (* const T))) int))"
"(pub record m ((c int)))"
"(pub realize (shown m) (fn show ((self (* const m))) int (return 1)))")))
(test "a private one is solved where it is" (test "a private one is solved where it is"
'() '()
(interface-of "(var n _ 42)")) (interface-of "(var n _ 42)"))

View File

@@ -231,9 +231,10 @@ after that is one more. Lines before the first directive get #f."
;; an `if' arm is a statement only where the `if' is one: a ;; an `if' arm is a statement only where the `if' is one: a
;; directive between `?' and `:' does not compile ;; directive between `?' and `:' does not compile
(maps "conditional argument" "123") (maps "conditional argument" "123")
;; a bare 123 may be a digit run of the fixture's path, in every #line
(test-assert "holds no directive" (test-assert "holds no directive"
(let ((start (string-contains c-out "123"))) (let ((start (string-contains c-out "mvar < 123")))
(not (string-contains (substring c-out start (string-contains c-out "125" start)) (not (string-contains (substring c-out start (string-contains c-out ": 125" start))
"#line"))))) "#line")))))
;; A location is (file . line); every directive must name the file the ;; A location is (file . line); every directive must name the file the

View File

@@ -10,11 +10,8 @@
;;; ;;;
;;; It also checks what only a second translation unit can check: that an ;;; It also checks what only a second translation unit can check: that an
;;; imported type reaches the type database, by expanding a macro that ;;; imported type reaches the type database, by expanding a macro that
;;; reads the imported struct's fields; and that a closure type crossing ;;; reads the imported struct's fields; and that a record can cross as a
;;; the boundary works both ways -- one built in the module and called ;;; handle alone, its fields left behind and its methods still found.
;;; here, one built here and called there, through a code pointer that is
;;; static in the other object. And that a record can cross as a handle
;;; alone, its fields left behind and its methods still found.
;;; ;;;
;;; The public forms carry comments in their headers, which the reduction ;;; The public forms carry comments in their headers, which the reduction
;;; to a prototype and to an extern both have to look past. And a type the ;;; to a prototype and to an extern both have to look past. And a type the
@@ -38,6 +35,7 @@
;;; ;;;
;;; gen/made writes its pub forms by macro calls, which are expanded when ;;; gen/made writes its pub forms by macro calls, which are expanded when
;;; its interface is read; the macros it used for that stay its own. ;;; its interface is read; the macros it used for that stay its own.
;;; gen/broken's call raises, which reading its interface reports.
;;; ;;;
;;; make check-modules ;;; make check-modules
@@ -138,11 +136,11 @@
'("made 42 7 1 2") '("made 42 7 1 2")
(output-of (built "made-app"))) (output-of (built "made-app")))
;;; ...while a realization of a spec importers cannot see is refused by ;;; ...but a call failing for other than a name its module declares fails
;;; the module that writes it, not by an importer naming it first ;;; there as well
(test-assert "a pub realization of a spec imported without pub is refused" (test-assert "a toplevel macro call that raises fails the interface too"
(let ((err (error-of sexc "specs/money.sex" "-C" "-o" "-"))) (let ((err (error-of sexc "--public-interface" "gen/broken.sex")))
(and err (irregex-search "money.sex:8: importers cannot see this spec" err) #t))) (and err (irregex-search "broken\\.sex:8: expanding boom: nope" err))))
(test "the app runs through both" (test "the app runs through both"
'("hello, world" '("hello, world"
@@ -151,9 +149,7 @@
"text times " "text times "
"text times " "text times "
"mood 1" "mood 1"
"closure 15 21 201"
"vec2 7 7" "vec2 7 7"
"vec2(3 4)"
"tally 2" "tally 2"
"board 42" "board 42"
"ledger 2" "ledger 2"

View File

@@ -0,0 +1,8 @@
;;; A toplevel macro call failing for what it is, not for asking after a
;;; name declared here: an importer is told so, as this module is
(defmacro (boom)
(error "nope"))
(pub fn fine () int (return 1))
(boom)

View File

@@ -27,19 +27,10 @@
(var m (enum mood) grumpy) (var m (enum mood) grumpy)
(printf "mood %d\n" m) (printf "mood %d\n" m)
(var add-10 (closure ((int)) int) (make-adder 10))
(printf "closure %d %d" (add-10 5) (apply-twice add-10 1))
(var base int 100)
(var here (closure ((int)) int)
(closure ((x int)) int (base) (return (+ base x))))
(printf " %d\n" (apply-twice here 1))
;; the bare record name, then the method both ways round ;; the bare record name, then the method both ways round
(var v vec2 #(vec2 : 3 4)) (var v vec2 #(vec2 : 3 4))
(printf "vec2 %d %d\n" (.manhattan v) (vec2/manhattan (& v))) (printf "vec2 %d %d\n" (.manhattan v) (vec2/manhattan (& v)))
(.show-line v)
;; only the handle crossed: (. t n) here is an incomplete type ;; only the handle crossed: (. t n) here is an incomplete type
(var t (* tally) (tally/make)) (var t (* tally) (tally/make))
(.bump t) (.bump t)

View File

@@ -62,19 +62,6 @@
(pub fn ledger-total ((l (* const ledger))) int (pub fn ledger-total ((l (* const ledger))) int
(return (. l total))) (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
;;; says so.
(pub fn make-adder ((n int)) (closure ((int)) int)
(return (closure ((b int)) int (n)
(return (+ n b)))))
;;; The other direction: a closure built by the importer, whose code
;;; pointer is static in *its* object, called from here
(pub fn apply-twice ((f (closure ((int)) int)) (x int)) int
(return (f (f x))))
;;; A record and an ops block crossing the boundary. The record has to ;;; A record and an ops block crossing the boundary. The record has to
;;; arrive as the struct *and* its typedef, or the bare name does not ;;; arrive as the struct *and* its typedef, or the bare name does not
;;; work there; the ops block has to arrive as a block rather than as ;;; work there; the ops block has to arrive as a block rather than as
@@ -110,20 +97,6 @@
;;; called, so there is no function for two units to both define. ;;; called, so there is no function for two units to both define.
(pub sum colour ((rgb ((r int) (g int) (b int))) (none ()))) (pub sum colour ((rgb ((r int) (g int) (b int))) (none ())))
;;; A spec and a realization over the boundary. The written method
;;; travels as a prototype and keeps external linkage; the default
;;; does not travel at all -- the importer synthesizes its own static
;;; copy from the spec, which is why a default is static even here.
(pub spec (printable T)
(fn show ((self (* const T))) void)
(fn show-line ((self (* const T))) void
(.show self)
(printf "\n")))
(pub realize (printable vec2)
(fn show ((self (* const vec2))) void
(printf "vec2(%d %d)" (. self x) (. self y))))
;;; Not `pub': invisible to importers, and static in the generated C. ;;; Not `pub': invisible to importers, and static in the generated C.
(fn unused-helper () void (fn unused-helper () void
(printf "private\n")) (printf "private\n"))

View File

@@ -1,9 +0,0 @@
;;; Imports shown without pub, so its importers cannot see the spec
;;; this realizes: refused here, rather than in whichever importer
;;; names money before shown
(import shown)
(pub record money ((cents int)))
(pub realize (shown money)
(fn show ((self (* const money))) int (return (. self cents))))

View File

@@ -1,2 +0,0 @@
(pub spec (shown T)
(fn show ((self (* const T))) int))

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 5 0" (output "c11: 42 43 6 4 6 12 5 0 -9223372036854775808"
"trigraphs: what??! ??= ???( ??/") "trigraphs: what??! ??= ???( ??/")
(return 0) (return 0)
@@ -9,10 +9,10 @@
;;; one that reaches past it -- a GNU statement expression, a C23 ;;; one that reaches past it -- a GNU statement expression, a C23
;;; keyword -- fails here rather than on a user's compiler. ;;; keyword -- fails here rather than on a user's compiler.
;;; ;;;
;;; A capturing closure is the one that leans on C11 itself, through ;;; A lifted lambda is the one that leans on C11 itself, through
;;; max_align_t in the environment and `_Static_assert' on its size; ;;; `_Static_assert'; the record, the method and the match are here for
;;; the record, the method and the match are here for what they emit, ;;; what they emit, and the globals for initializers that have to be
;;; and the globals for initializers that have to be constants. ;;; constants.
;;; ;;;
;;; It is also the one mode where C still reads trigraphs, which Sex has ;;; It is also the one mode where C still reads trigraphs, which Sex has
;;; none of: a string says what was written, `??/' before its closing ;;; none of: a string says what was written, `??/' before its closing
@@ -33,6 +33,7 @@
(var origin point #()) (var origin point #())
(var unit _ (shape/square 1)) (var unit _ (shape/square 1))
(var pair [_ 2] #(#(point : 1 2) #(point : 3 4))) (var pair [_ 2] #(#(point : 1 2) #(point : 3 4)))
(var least _ -9223372036854775808)
(fn sides ((s shape)) int (fn sides ((s shape)) int
(var n int 0) (var n int 0)
@@ -43,11 +44,10 @@
(pub fn main () int (pub fn main () int
(var p point #(point : 6 7)) (var p point #(point : 6 7))
(var k int 1) (var add-k (fn ((int)) int)
(var add-k (closure ((int)) int) (lambda ((v int)) int (return (+ v 1))))
(closure ((v int)) int (k) (return (+ v k)))) (printf "c11: %d %d %d %d %d %d %d %d %lld\n"
(printf "c11: %d %d %d %d %d %d %d %d\n"
(.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2) (.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2)
(sides unit) (.area corner) (.area [pair 1]) [primes 2] (. origin y)) (sides unit) (.area corner) (.area [pair 1]) [primes 2] (. origin y) least)
(printf "trigraphs: %s\n" "what??! ??= ???( ??/") (printf "trigraphs: %s\n" "what??! ??= ???( ??/")
(return 0)) (return 0))

View File

@@ -1,69 +0,0 @@
(input)
(output "one argument of two words: 7"
"two arguments of one: 7"
"unsigned, one argument: 9"
"unsigned, two arguments: 3"
"captured global: 12"
"captured function: 8"
"curried: 42 42"
"taking one: 21")
(return 0)
;;; A closure's struct is named after its signature, so that two
;;; translation units agree on it without sharing a header. The name is
;;; built by flattening the argument list, and flattening loses where one
;;; argument ends and the next begins: `((long long))' and
;;; `((long) (long))' are different signatures that used to mangle alike,
;;; and the second quietly reused the first one's struct.
;;;
;;; A capture that borrows a name reads it from wherever the name is
;;; declared, a global or a function included.
;;;
;;; A closure's signature may name closures in turn: one returned is
;;; currying, one taken is a callback.
(include stdio.h)
(var scale int 3)
(fn double-it ((n int)) int
(return (* n 2)))
(fn curried-add () (closure ((int)) (closure ((int)) int))
(return (closure ((a int)) (closure ((int)) int) ()
(return (closure ((b int)) int (a) (return (+ a b)))))))
(pub fn main () int
(var one-wide (closure ((long long)) int)
(closure ((a (long long))) int () (return (cast a int))))
(printf "one argument of two words: %d\n" (one-wide 7))
(var two-longs (closure ((long) (long)) int)
(closure ((a long) (b long)) int () (return (cast (+ a b) int))))
(printf "two arguments of one: %d\n" (two-longs 3 4))
(var one-unsigned (closure ((unsigned int)) int)
(closure ((a (unsigned int))) int () (return (cast a int))))
(printf "unsigned, one argument: %d\n" (one-unsigned 9))
(var two-unsigned (closure ((unsigned) (int)) int)
(closure ((a unsigned) (b int)) int () (return (+ (cast a int) b))))
(printf "unsigned, two arguments: %d\n" (two-unsigned 1 2))
;; a capture names what it borrows, and the name need not be a local
(var scaled (closure ((int)) int)
(closure ((x int)) int (scale) (return (* x scale))))
(printf "captured global: %d\n" (scaled 4))
(var doubled (closure ((int)) int)
(closure ((x int)) int (double-it) (return (double-it x))))
(printf "captured function: %d\n" (doubled 4))
(var add (closure ((int)) (closure ((int)) int)) (curried-add))
(var add2 (closure ((int)) int) (add 2))
(printf "curried: %d %d\n" (add2 40) ((add 1) 41))
(var twice (closure (((closure ((int)) int)) (int)) int)
(closure ((f (closure ((int)) int)) (x int)) int () (return (f (f x)))))
(printf "taking one: %d\n" (twice add2 17))
(return 0))

View File

@@ -1,149 +0,0 @@
(input)
(output "Adders: 15 25"
"Two captures: 47"
"No captures: 7"
"Through a parameter: 110"
"From an array: 1 2 3"
"Index evaluated once: 21 i 1"
"Through a struct member: 8"
"Shadowed in a block: 9 then 15"
"Nested: 33"
"Named capture: 7"
"Captured pointer: 11 then 12"
"From a bare fn: 20 42 7"
"Captured array: 6 3, still 6"
"Captured const: 6"
"Unnamed parameter: 2"
"Empty bodies: called")
(return 0)
;;; A closure is a code pointer beside its captures, so what this
;;; checks is that the captures survive the lifting -- that two
;;; closures of one shape keep their own environments, that a closure
;;; outlives the call that built it, and that calling one through a
;;; parameter, an array element or a struct member resolves the same
;;; way as through a local.
;;;
;;; A receiver is also an ordinary expression: `[table (++ i)]' has to
;;; evaluate its index exactly once, the way it would for an array of
;;; function pointers.
(include stdio.h)
(fn double-it ((n int)) int
(return (* n 2)))
;;; a bare function is a closure that captures nothing, so it converts
;;; wherever one is expected -- here a declared return type
(fn as-closure () (closure ((int)) int)
(return double-it))
(fn make-adder ((n int)) (closure ((int)) int)
(return (closure ((b int)) int (n)
(return (+ n b)))))
(fn make-affine ((k int) (b int)) (closure ((int)) int)
(return (closure ((x int)) int (k b)
(return (+ (* k x) b)))))
(fn make-const-7 () (closure () int)
(return (closure () int ()
(return 7))))
;;; A closure arriving as a parameter: its type is written, so the call
;;; resolves without knowing where it came from
(fn apply-twice ((f (closure ((int)) int)) (x int)) int
(return (f (f x))))
(struct handlers ((on-tick (closure ((int)) int))))
(pub fn main () int
(var add-10 (closure ((int)) int) (make-adder 10))
(var add-20 (closure ((int)) int) (make-adder 20))
(printf "Adders: %d %d\n" (add-10 5) (add-20 5))
(var affine (closure ((int)) int) (make-affine 5 2))
(printf "Two captures: %d\n" (affine 9))
(var seven (closure () int) (make-const-7))
(printf "No captures: %d\n" (seven))
(printf "Through a parameter: %d\n" (apply-twice (make-adder 50) 10))
(var table [(closure ((int)) int) 3])
(var i int 0)
(for (= i 0) (< i 3) (++ i)
(= [table i] (make-adder i)))
(printf "From an array: %d %d %d\n"
([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
;; printf would be unsequenced whatever the closure did
(= i 0)
(var once int ([table (++ i)] 20))
(printf "Index evaluated once: %d i %d\n" once i)
(var h (struct handlers) #((struct handlers) : .on-tick (make-adder 5)))
(printf "Through a struct member: %d\n" ((. h on-tick) 3))
;; a block opens a scope: the inner `add-10' ends with it, and the
;; call after it is the closure again
(do (var add-10 int 9)
(printf "Shadowed in a block: %d then " add-10))
(printf "%d\n" (add-10 5))
;; a closure built inside a closure, capturing that one's capture
(var outer (closure ((int)) int)
(closure ((x int)) int ()
(var inner (closure ((int)) int) (make-adder x))
(return (inner 3))))
(printf "Nested: %d\n" (outer 30))
;; a capture can name what it holds rather than borrow a variable's
;; name, and the expression is evaluated where the closure is written
(var pt (struct handlers))
(var sum-once (closure () int)
(closure () int ((sum (+ 3 4))) (return sum)))
(printf "Named capture: %d\n" (sum-once))
;; capturing a pointer is how by-reference is spelled; the caller owns
;; what it points at
(var counter int 11)
(var peek (closure () int)
(closure () int ((at (& counter))) (return (* at))))
(printf "Captured pointer: %d then " (peek))
(++ counter)
(printf "%d\n" (peek))
;; ...and in an initializer, as an argument, and as a return
(var from-fn (closure ((int)) int) double-it)
(printf "From a bare fn: %d %d %d\n"
(apply-twice from-fn 5)
((as-closure) 21)
(apply-twice (lambda ((n int)) int (return (+ n 1))) 5))
;; an array is copied in, element by element, as C copies one neither
;; by = nor into a parameter; so are the rows of one of arrays
(var xs [int 3] #(1 2 3))
(var m [int 2 2] #(#(1 2) #(3 4)))
(var sum3 (closure () int) (closure () int (xs) (return (+ [xs 0] [xs 1] [xs 2]))))
(var corner (closure () int) (closure () int (m) (return [m 1 0])))
(printf "Captured array: %d %d" (sum3) (corner))
(= [xs 0] 100)
(printf ", still %d\n" (sum3))
;; a const local is captured as its value, and stays const inside
(var k (const int) 5)
(var plus-k (closure ((int)) int) (closure ((v int)) int (k) (return (+ v k))))
(printf "Captured const: %d\n" (plus-k 1))
(var second (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b)))
(printf "Unnamed parameter: %d\n" (second 1 2))
(var nothing (closure () void) (closure () void ()))
(var nothing-either (fn () void) (lambda () void))
(nothing)
(nothing-either)
(printf "Empty bodies: called\n")
(return 0))

View File

@@ -3,8 +3,8 @@
"-5") "-5")
(return 0) (return 0)
;;; A recursive sum, an inherent method on it, and a spec realized for ;;; A recursive sum and an inherent method on it: every layer of
;;; it: every layer of encapsulation in one program, built at once. ;;; encapsulation in one program, built at once.
(include stdio.h) (include stdio.h)
@@ -19,20 +19,15 @@
(match (* self) (match (* self)
((lit (v)) (return v)) ((lit (v)) (return v))
((neg (e)) (return (- (.eval e)))) ((neg (e)) (return (- (.eval e))))
((add (l r)) (return (+ (.eval l) (.eval r))))))) ((add (l r)) (return (+ (.eval l) (.eval r))))))
(pub fn show ((self (* const expr))) void
(spec (printable T)
(fn show ((self (* const T))) void)
(fn show-line ((self (* const T))) void ; default, calls the required one
(.show self)
(printf "\n")))
(realize (printable expr)
(fn show ((self (* const expr))) void
(match (* self) (match (* self)
((lit (v)) (printf "%g" v)) ((lit (v)) (printf "%g" v))
((neg (e)) (printf "-") (.show e)) ((neg (e)) (printf "-") (.show e))
((add (l r)) (printf "(") (.show l) (printf " + ") (.show r) (printf ")"))))) ((add (l r)) (printf "(") (.show l) (printf " + ") (.show r) (printf ")"))))
(pub fn show-line ((self (* const expr))) void
(.show self)
(printf "\n")))
(pub fn main () int (pub fn main () int
(var two expr (expr/lit 2.0)) (var two expr (expr/lit 2.0))

View File

@@ -1,61 +0,0 @@
(input)
(output "direct: 120"
"fac: 120 3628800"
"fib: 55 6765"
"applied on the spot: 120")
(return 0)
;;; A fixed point built out of closures, which is the hardest thing to
;;; ask of them: recursion with no recursive function anywhere, only
;;; self-application.
;;;
;;; Self-application needs `x x' and so a recursive type, which is
;;; spelled here by routing it through a named struct whose field is a
;;; closure whose own signature mentions that struct. The generated
;;; closure struct is written before `struct rec' is, so this only
;;; compiles because a forward declaration is emitted ahead of both.
;;;
;;; Note what `fix' captures: a *pointer* to the knot, not the knot. A
;;; closure is a code pointer beside N bytes of environment, so
;;; capturing one by value would need N >= 8 + N. No budget makes that
;;; true, and the static assertion says so rather than letting it
;;; corrupt anything.
(include stdio.h)
(struct rec ((f (closure (((* (struct rec))) (int)) int))))
;;; Takes a step that expects itself, returns an ordinary closure with
;;; the self-application hidden inside
(fn fix ((step (* (struct rec)))) (closure ((int)) int)
(return (closure ((n int)) int (step)
(return ((. step f) step n)))))
(pub fn main () int
(var fac-knot (struct rec))
(= (. fac-knot f)
(closure ((self (* (struct rec))) (n int)) int ()
(if (<= n 1) (return 1))
(return (* n ((. self f) self (- n 1))))))
;; the knot applied to itself directly, without fix
(printf "direct: %d\n" ((. fac-knot f) (& fac-knot) 5))
(var fib-knot (struct rec))
(= (. fib-knot f)
(closure ((self (* (struct rec))) (n int)) int ()
(if (< n 2) (return n))
(return (+ ((. self f) self (- n 1))
((. self f) self (- n 2))))))
;; one combinator, two different recursions
(var fac (closure ((int)) int) (fix (& fac-knot)))
(var fib (closure ((int)) int) (fix (& fib-knot)))
(printf "fac: %d %d\n" (fac 5) (fac 10))
(printf "fib: %d %d\n" (fib 10) (fib 20))
;; the combinator's result invoked where it is returned, with no
;; intervening `var' -- the receiver's type is the return type of the
;; signature it came from, which is what the name table records
(printf "applied on the spot: %d\n" ((fix (& fac-knot)) 5))
(return 0))

View File

@@ -8,8 +8,8 @@
"0 1 4 9 " "0 1 4 9 "
"4" "4"
"42" "42"
"<closure of 0: 10>" "<fn of 0: 10>"
"42" "32"
"2 1" "2 1"
"Hello from Sex!") "Hello from Sex!")
(return 0) (return 0)
@@ -47,11 +47,11 @@
(= (. m y) (/ (+ (. a y) (. b y)) 2)) (= (. m y) (/ (+ (. a y) (. b y)) 2))
(return m)) (return m))
;;; The closure's type is written once, in the signature; `_' reads it ;;; A lambda's type is written once, in the signature; `_' reads it
;;; from there at every use. ;;; from there wherever the function is called.
(fn make-adder ((n int)) (closure ((int)) int) (fn make-adder () (fn ((int)) int)
(return (closure ((b int)) int (n) (return (lambda ((b int)) int
(return (+ n b))))) (return (+ b 10)))))
;;; A macro that asks what it was handed. ;;; A macro that asks what it was handed.
;;; ;;;
@@ -68,9 +68,9 @@
;; NOTE: ,x twice -- a macro that duplicates its argument still has ;; NOTE: ,x twice -- a macro that duplicates its argument still has
;; to think about evaluating it twice. Inference does not fix that. ;; to think about evaluating it twice. Inference does not fix that.
((struct point) `(printf "(%d, %d)\n" (. ,x x) (. ,x y))) ((struct point) `(printf "(%d, %d)\n" (. ,x x) (. ,x y)))
;; a closure is a type like any other, so it dispatches like one -- ;; a function type is a type like any other, so it dispatches like
;; and `_' saves a clause per signature ;; one -- and `_' saves a clause per signature
((closure _ int) `(printf "<closure of 0: %d>\n" (,x 0))) ((fn _ int) `(printf "<fn of 0: %d>\n" (,x 0)))
(else (error "print: don't know how to print" (type-of x))))) (else (error "print: don't know how to print" (type-of x)))))
;;; The temporary's type is the thing the macro could not write down ;;; The temporary's type is the thing the macro could not write down
@@ -136,14 +136,14 @@
(var squares [_ 4] #(0 1 4 9)) (var squares [_ 4] #(0 1 4 9))
(print [squares 2]) (print [squares 2])
;; A closure's type comes from the signature that produced it, and ;; A function pointer's type comes from the signature that produced
;; calling one needs that type and nothing else. ;; it, and calling one needs that type and nothing else.
(var add-10 _ (make-adder 10)) (var add-10 _ (make-adder))
(print (add-10 32)) (print (add-10 32))
(print add-10) (print add-10)
;; ...including where it is returned, with no name in between. ;; ...including where it is returned, with no name in between.
(print ((make-adder 20) 22)) (print ((make-adder) 22))
;; A macro writing a declaration it could not have written before. ;; A macro writing a declaration it could not have written before.
(var a _ 1) (var a _ 1)
@@ -157,12 +157,12 @@
;;; Open questions this draft raises, to settle before Layer 2 ships: ;;; Open questions this draft raises, to settle before Layer 2 ships:
;;; ;;;
;;; 1. SETTLED. `type-match' took `_' on the pattern side, so ;;; 1. SETTLED. `type-match' took `_' on the pattern side, so
;;; `(closure _ int)' above is one clause rather than one per ;;; `(fn _ int)' above is one clause rather than one per signature,
;;; signature, and `(* _)' and `[_ _]' say "any pointer" and "any ;;; and `(* _)' and `[_ _]' say "any pointer" and "any array". A `_'
;;; array". A `_' written last takes the rest, since a type's words ;;; written last takes the rest, since a type's words are spread and
;;; are spread and not nested: `(* const char)' is three elements. ;;; not nested: `(* const char)' is three elements. Nothing
;;; Nothing destructures -- a macro body is Scheme and a type is a ;;; destructures -- a macro body is Scheme and a type is a list, so
;;; list, so `(caddr (type-of x))' reads an array's length. ;;; `(caddr (type-of x))' reads an array's length.
;;; ;;;
;;; 2. SETTLED, allowed. `[_ 4]' against `#(0 1 4 9)' unifies each ;;; 2. SETTLED, allowed. `[_ 4]' against `#(0 1 4 9)' unifies each
;;; element with the hole, so the element type comes from the ;;; element with the hole, so the element type comes from the

View File

@@ -6,7 +6,6 @@
"decayed: 2 2 there" "decayed: 2 2 there"
"unsigned wins either way: 4294967295 4294967295" "unsigned wins either way: 4294967295 4294967295"
"toplevel: 1 2.5 hi 12" "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" "radix literals: 224 5 128"
"a double reaches C whole: 1" "a double reaches C whole: 1"
@@ -35,9 +34,6 @@
(var s _ "hi") (var s _ "hi")
(var a _ (+ 3 (* 3 3))) (var a _ (+ 3 (* 3 3)))
(fn make-adder ((k int)) (closure ((int)) int)
(return (closure ((b int)) int (k) (return (+ k b)))))
(pub fn main () int (pub fn main () int
(var x int 6) (var x int 6)
(var y int 3) (var y int 3)
@@ -80,14 +76,9 @@
(printf "toplevel: %d %g %s %d\n" n d s a) (printf "toplevel: %d %g %s %d\n" n d s a)
;; a closure literal is its own type, so it can be called where it is
;; written, the way a lambda already could
(printf "closure in place: %d\n"
((closure ((v int)) int () (return v)) 5))
;; a `fn' type's parameter list looks exactly like a call; with a ;; a `fn' type's parameter list looks exactly like a call; with a
;; closure named `f' in scope it used to be read as one ;; function named `f' in scope it used to be read as one
(var f (closure ((int)) int) (make-adder 1)) (var f (fn ((int)) int) (lambda ((v int)) int (return (+ v 1))))
(var fp (fn ((f int) (g int)) int) area) (var fp (fn ((f int) (g int)) int) area)
(printf "a type is not a call: %d\n" (f 6)) (printf "a type is not a call: %d\n" (f 6))

View File

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

View File

@@ -189,8 +189,8 @@
'yes (type-match '(struct point) ((struct _) 'yes) (else 'no))) 'yes (type-match '(struct point) ((struct _) 'yes) (else 'no)))
(test "and the keyword still has to agree" (test "and the keyword still has to agree"
'no (type-match '(union point) ((struct _) 'yes) (else 'no))) 'no (type-match '(union point) ((struct _) 'yes) (else 'no)))
(test "a closure of any signature" (test "a function of any signature"
'yes (type-match '(closure ((float)) int) ((closure _ _) 'yes) (else 'no))) 'yes (type-match '(fn ((float)) int) ((fn _ _) 'yes) (else 'no)))
(test "an exact pattern is still exact" (test "an exact pattern is still exact"
'no (type-match '(* int) ((* const char) 'yes) (else 'no))) 'no (type-match '(* int) ((* const char) 'yes) (else 'no)))

View File

@@ -34,12 +34,6 @@
variant-fields variant-fields
reset-declarations! reset-declarations!
add-spec!
get-spec
spec-parameter
spec-methods
add-realization!
realizes?
normalize-fields normalize-fields
add-method! add-method!
@@ -49,6 +43,7 @@
add-name-type! add-name-type!
get-name-type get-name-type
unknown-name
type-of type-of
current-type-of current-type-of
get-return-type get-return-type
@@ -156,11 +151,21 @@
(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))
;;; Called with each name a lookup finds nothing for. A module's
;;; interface is read before its declarations are, so a macro call there
;;; asking after one -- (field-count box), box being its record -- is
;;; told nothing, and fails for that rather than for being wrong
(define unknown-name (make-parameter void))
(define (known name info)
(unless info ((unknown-name) name))
info)
;;; #f for a name never declared, which is what `printf' looks like ;;; #f for a name never declared, which is what `printf' looks like
;;; until something parses stdio.h. Not an error here; the caller ;;; until something parses stdio.h. Not an error here; the caller
;;; decides. ;;; decides.
(define (get-name-type name) (define (get-name-type name)
(hash-table-ref/default +name-db+ name #f)) (known name (hash-table-ref/default +name-db+ name #f)))
;;; What `(make-adder 10)' has for a type: `make-adder's return type, ;;; What `(make-adder 10)' has for a type: `make-adder's return type,
;;; or #f when NAME is not a function with a signature on record ;;; or #f when NAME is not a function with a signature on record
@@ -172,7 +177,7 @@
(third type)))) (third type))))
(define (get-tag-info name) (define (get-tag-info name)
(hash-table-ref/default +tag-db+ name #f)) (known name (hash-table-ref/default +tag-db+ name #f)))
;;; First look up the ordinary identifier, then tag of that id when ;;; First look up the ordinary identifier, then tag of that id when
;;; no ordinary one was declared, as C does ;;; no ordinary one was declared, as C does
@@ -296,7 +301,7 @@
(hash-table-set! +ops-db+ (cons (type-key type) method) qualified)) (hash-table-set! +ops-db+ (cons (type-key type) method) qualified))
(define (get-method type method) (define (get-method type method)
(hash-table-ref/default +ops-db+ (cons (type-key type) method) #f)) (known type (hash-table-ref/default +ops-db+ (cons (type-key type) method) #f)))
;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength ;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength
(define (qualify-op type name) (define (qualify-op type name)
@@ -313,43 +318,14 @@
((memq (car type) '(const volatile)) (ops-key (cadr type))) ((memq (car type) '(const volatile)) (ops-key (cadr type)))
(else #f))) (else #f)))
;;; A spec is a parameter and a list of methods, each of which either ;;; Sums, constructors and methods refuse a second declaration
;;; 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 ;;; of the same name, which is per translation unit rather than per
;;; process -- so a process that compiles two units has to start the ;;; process -- so a process that compiles two units has to start the
;;; second one clean. ;;; second one clean.
(define (reset-declarations!) (define (reset-declarations!)
(set! +sum-db+ (make-hash-table)) (set! +sum-db+ (make-hash-table))
(set! +constructor-db+ (make-hash-table)) (set! +constructor-db+ (make-hash-table))
(set! +ops-db+ (make-hash-table)) (set! +ops-db+ (make-hash-table)))
(set! +spec-db+ (make-hash-table))
(set! +realize-db+ (make-hash-table)))
;;; Type matcher macro ;;; Type matcher macro
;;; (type-match type ;;; (type-match type
@@ -367,8 +343,8 @@
;;; ;;;
;;; `_' in a pattern matches anything in that position, the same thing ;;; `_' in a pattern matches anything in that position, the same thing
;;; it means in a type. Without it every spelling has to be enumerated: ;;; it means in a type. Without it every spelling has to be enumerated:
;;; `(closure ((int)) int)' and `(closure ((float)) int)' are separate ;;; `(fn ((int)) int)' and `(fn ((float)) int)' are separate clauses for
;;; clauses for what is one case. ;;; what is one case.
;;; ;;;
;;; A `_' written last takes everything that remains, because a type's ;;; A `_' written last takes everything that remains, because a type's
;;; words are spread rather than nested -- `(* const char)' is three ;;; words are spread rather than nested -- `(* const char)' is three