Compare commits

..

37 Commits

Author SHA1 Message Date
ae9cdbbf31 check the constants a module's interface hands its importers
An array bound in a pub record, or a name in a pub define's body, is
the importer's to resolve too, and a private define, or one from an
import without pub, failed there as an undeclared identifier. Found in
vs-map-viewer once its units stopped importing everything. A constant
has no declaration short of itself, so it is an error at the pub form.
2026-10-14 19:22:34 +03:00
66d088f6fc write a double in the digits that read back as it
CHICKEN prints 15 significant digits unless told otherwise, too few to
name every double: 0.9871465422297019 reached the C as
0.987146542229702, a different constant. Found in vs-map-viewer, where
380 literals in a port that has to match .NET bit for bit changed this
way. The shortest spelling that reads back is written, up to 17 digits.
2026-10-14 19:22:34 +03:00
3737f90641 hand sexc every digit of a test program's doubles
sextest prints the program it read back to sexc, and printed doubles
in CHICKEN's default 15 digits: 0.16666666666666666 arrived as
0.166666666666667, another number.
2026-10-14 19:22:34 +03:00
58f145bd95 parenthesise what a subscript subscripts
The array was written at whatever level surrounded it, so [(* q) i]
came out *q[i] -- *(q[i]) to C, compiling with q an int ** and reading
the wrong int. The index now starts afresh too: inside a cast it had
taken the cast's level and gained parens, and so had a chain in the
else arm of ?:, which groups to the right and needs none.
2026-10-14 19:22:34 +03:00
e6b6ca799d print the public interface in declaration order
read-public-interface has returned the forms in order since 2512d52,
and --public-interface still reversed them as it had to before.
2026-10-14 19:22:34 +03:00
a6689b8c81 write a make rule for the modules a unit reads
An import pastes another file's forms into the output, so a Makefile
had to make every object depend on every .sex. --depfile names the
modules read, including those read only for an import's interface,
with an empty rule for each, as cc -MD -MP does.

Fixes #40.
2026-10-14 19:22:34 +03:00
b717aa808d check what a module's importers can see of its types
An importer is given the pub forms and nothing else, so a pub form
naming a private type, or one from an import without pub, compiled in
its module and failed in every importer with `unknown type name'.

The pub forms are checked as the module itself is compiled. A record,
struct, union or sum behind a pointer needs only declaring, so its
bodyless declaration goes out ahead of them -- the opaque handle that
(pub record T) already gave by hand. Held by value it needs its body,
and a typedef or an enum has no declaration short of its definition:
those are errors at the pub form, saying what would do instead. A name
Sex has no declaration for is left to C.

An importer may now be handed a declaration after the definition it
declares, so a bodyless aggregate no longer replaces known fields.

Fixes #57, #58.
2026-10-14 19:22:34 +03:00
b49bb8f716 let a method call one written below it
Each method was registered just before its own body was walked, so an
earlier one could not find it. All are registered first now, and one
called above its definition is declared ahead of the bodies, which C
needs as well.

Fixes #44.
2026-10-14 19:22:34 +03:00
a048925c7a resolve a relative SEX_MODULE_PATH entry from the working directory
make-absolute-pathname with no directory of its own put `src' under
the root, so SEX_MODULE_PATH=src searched /src/.

Fixes #48.
2026-10-14 19:22:34 +03:00
a14484d1dc take -o - as stdout
getopt-long reads a lone `-' as an option, so -o - died there asking
for a value, and --output=- got through only to create a file named
`-'.

Fixes #43.
2026-10-14 19:22:34 +03:00
42fe477e35 name what a member path could not type
Past a typed base, it is a field of a struct only C knows that has no
type, and the warning named the base anyway: `font' for what was
(. font handle), with font declared on the line before.

Fixes #41.
2026-10-14 19:22:34 +03:00
062cb18c60 walk what an initializer holds
The body walk passed a #(...) by as an atom, so nothing inside one was
typed, dispatched or lifted: (. self p) read as self.p with self a
pointer, where the same path outside the literal was right.

Fixes #45.
2026-10-14 19:22:32 +03:00
4e0938ab1f reject a for whose header is grouped
C's parens carried over, ((var i int 0) (< i 4) (++ i)), left the
writer short of slots, and it died in caddr with no location; with a
long enough body it would have compiled the body into the header.

Fixes #42.
2026-10-14 19:21:16 +03:00
2bad5db114 anchor an if's arms only where the if is a statement
Every if had its arms anchored, including one inside an argument that
the writer renders as ?:, so a #line landed between its parts and the
C did not compile. -C output, with no directives, hid it.

Fixes #54.
2026-10-14 19:21:16 +03:00
3e01fe41e8 make a declaring case body a block
A case body shared the switch's scope, so two cases could not each
declare `bits', and a label could not be followed by a declaration
before C23; inference shared the scope too, and typed a later case's
read of an outer name as the earlier case's local.

Fixes #51.
2026-10-14 19:21:13 +03:00
52228e6fc6 write arrays with brackets in tests
The tests spelled out (¤ ...), what [...] reads into, which nobody
writes. The reader's own tests keep it: there it is the point.
2026-10-14 19:12:47 +03:00
08853d2c77 read hex and binary literals
0x80 was not a number to string->number, so it became a symbol the
printer escaped as |0x80|, and #x was rejected outright. Both spellings
now read as the integer, which the C writes in decimal.

Fixes #47.
2026-10-14 19:12:47 +03:00
6fbeaedbe6 read -NAME as the negation of NAME
The reader took -INFINITY as one symbol, and the leading dash was then
mangled like any other: _INFINITY. -1 was always a number, so a name
gets the same reading.

Fixes #63.
2026-10-14 19:12:47 +03:00
9d4454afe3 let sizeof take a type that looks like an expression
(* char) is a pointer type and (* p) a dereference, and only the names
in scope tell them apart, so semen decides and marks a type for the
writer. Before, both were walked as expressions: sizeof(*char).

Fixes #52.
2026-10-14 19:12:47 +03:00
5a887c0654 spell ? and ! in names as letters C takes
A Lisp predicate came out as ident_start?, which no C compiler reads.
ʔ and ꜝ are letters that look the part; ǃ looks closer, but clang flags
it as a homoglyph of `!' at every use.

Fixes #49.
2026-10-14 19:12:47 +03:00
b5de28342b walk a define's body, and parenthesise it
The body was pasted as read, so `cast' stayed a call and names kept
their dashes; and fmt-c parenthesised only a function-like body, so
an object-like one regrouped with the operator it was pasted under.

Fixes #55.
2026-10-14 19:12:47 +03:00
dff4a5af53 convert enumerators written with a value
(wire-varint 0) is a pair, and both the writer and map-fields only
expected a name: the writer passed it out unconverted, and a macro
mapping over the enum was handed the pair.

Fixes #46.
2026-10-14 19:12:47 +03:00
f24adfa2db write a typedef's target as a type
It fell through to the expression walk, which read (* const char) as a
dereference and an array as a subscript, and died on a fn type.

Fixes #53.
2026-10-14 19:12:47 +03:00
82629867c1 spell an array bound as an expression
It went to fmt-c unwalked, so a bound named CHUNK-AREA kept its dash
while the same name in an expression became CHUNK_AREA.

Fixes #50.
2026-10-14 19:12:47 +03:00
b0dd2d9f94 tell an array's bound by the shape of its type
Whether a trailing name was the bound hinged on the word before it
being a typedef Sex had seen, which a header's pthread_t never is, and
a grouped (* T) never is either: [pthread-t N] became a two-word type.

Fixes #56, #60.
2026-10-14 19:12:47 +03:00
169933ff2e parenthesise casts and conditionals by precedence
Neither took part in it: a cast parenthesised its operand only from a
list of binary heads that missed `|', and never itself, so `->' took
it apart; `?:' was written bare under any operator, swallowing it into
the test. Three of the four still compiled, to wrong values.

Fixes #59, #61, #62.
2026-10-14 19:12:47 +03:00
0a565046af say that a binder is a copy, and where %-> is
All checks were successful
Sex CI / build-linux (pull_request) Successful in 5m40s
A match binder looks like a reference to its field and is not one. And
with `.' reading an untyped receiver as a value, nothing said how to
write the arrow by hand.
2026-10-14 17:27:52 +03:00
b51cda0af3 highlight ops and match 2026-10-14 17:27:52 +03:00
9c5f678830 hand an array field its elements
An array field compiled to C that cc refused: an array is neither an
initializer of another nor something a payload literal can be built
from. Both the constructor and the binder now spell it out element by
element, which needs a length sexc can count. A sum holding itself by
value is refused at the declaration rather than as cc's incomplete type.
2026-10-14 17:14:36 +03:00
427177d50f write a sum's constructors in place
A constructor was a static function per variant. One taking an array
field cannot exist, its parameter being a pointer, and building some
variants in place and others by call would make two kinds of
constructor. In place, every one is a constant where one is wanted, an
lvalue a method can take the address of, and nothing a pub sum has to
paste into its importer.

What the function did for free is done here instead: arity is checked,
since a short compound literal zero-fills quietly, and an argument is
converted against its field's closure type. The price is that a
constructor is no longer a function value; a lambda makes one.
2026-10-14 17:11:38 +03:00
e91b44dbe1 walk a global's initializer like a local's
Only a local's initializer was walked, so at file scope a path was not
dispatched, a lambda was never lifted, and a constructor written in
place would have been left a call to nothing.
2026-10-14 17:08:42 +03:00
9af9113bf5 walk the values of a brace literal
The walk stopped at a vector, so whatever a literal held reached the
writer as written: #(v : (.get a)) was (v){.get(a)}, and a path through
a pointer inside one read it as a value.
2026-10-14 17:07:20 +03:00
224ef8fb6b file methods, realizations and sums under what a typedef names
A typedef had the fields of its record but none of its methods, and a
typedef of a sum was not a sum to match. A typedef that ends in a
scalar still keeps its own, so (typedef meters float) does not lend
its methods to every float.
2026-10-14 16:54:16 +03:00
bb2f05fa36 type a macro call by what it expands to
A receiver, a scrutinee or the start of a path was typed before the
walk had expanded it, so (.len (the a)) had no type to dispatch on and
(. (the p) x) read a pointer as a value.
2026-10-14 16:40:37 +03:00
3baaafafc3 refuse the matches and sums cc would refuse
Two else arms, a variant declared twice, and a match standing where a
value is wanted all reached cc as broken C; an arm that is not a list
crashed sexc. A variant called tag collided with the tag enum, now
spelled shapeǂ so no variant name can reach it.
2026-10-14 16:37:51 +03:00
5ba55f05a5 read a spread self as the pointer it is
(self * const v) typed the method's self as `self', so a call passed a
value where the method took a pointer, and a spec written one way
refused a realization written the other. A const receiver handed to a
method taking (* v) is now refused rather than left to cc's warning.
2026-10-14 16:24:00 +03:00
f5c53cdd41 tell a spec default by its body, not its length
A required method with a docstring or a comment counted as a default:
the realization could leave it out, and got a prototype with no
definition or a function with no return.
2026-10-14 15:54:07 +03:00
11 changed files with 549 additions and 104 deletions

View File

@@ -150,7 +150,8 @@ may be both:
#+end_src #+end_src
A receiver whose type cannot be worked out --- something out of a header A receiver whose type cannot be worked out --- something out of a header
nothing has parsed --- is read as a value, with a warning saying so. nothing has parsed --- is read as a value, with a warning saying so. For a
pointer there, ~(%-> p x)~ writes ~p->x~ whatever ~p~ is.
A method is ~(.name receiver args ...)~ and a field is ~(. receiver A method is ~(.name receiver args ...)~ and a field is ~(. receiver
name)~, so the shape of a form says which of the two it is without name)~, so the shape of a form says which of the two it is without

369
semen.scm
View File

@@ -2,6 +2,7 @@
(import (import
scheme scheme
(only (scheme base) make-parameter)
(chicken base) (chicken base)
(chicken keyword) (chicken keyword)
(chicken string) (chicken string)
@@ -276,7 +277,8 @@
(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 (map resolve-closure-types (take expanded boundary)))
(body (walk-body (drop expanded boundary) env)) (body (parameterize ((operand-position? #f))
(walk-body (drop expanded boundary) env)))
;; A function is header and body stitched together, so the ;; A function is header and body stitched together, so the
;; result is fresh structure: without this the definition ;; result is fresh structure: without this the definition
;; has no location, and nothing downstream can say where ;; has no location, and nothing downstream can say where
@@ -346,11 +348,21 @@
(append (map (lambda (g) (cons g #t)) given) (append (map (lambda (g) (cons g #t)) given)
(filter-map (filter-map
(lambda (w) (lambda (w)
(and (> (length w) 4) ; carries a body, so a default (and (spec-default? w)
(not (find (lambda (g) (eq? (second g) (second w))) given)) (not (find (lambda (g) (eq? (second g) (second w))) given))
(cons (substitute-parameter parameter type w) #f))) (cons (substitute-parameter parameter type w) #f)))
wanted))) 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) (define (check-realization form name type parameter wanted given)
(for-each (for-each
(lambda (g) (lambda (g)
@@ -369,7 +381,7 @@
given) given)
(let ((missing (filter-map (let ((missing (filter-map
(lambda (w) (lambda (w)
(and (= (length w) 4) ; no body, so required (and (not (spec-default? w))
(not (find (lambda (g) (eq? (second g) (second w))) given)) (not (find (lambda (g) (eq? (second g) (second w))) given))
(second w))) (second w)))
wanted))) wanted)))
@@ -467,17 +479,11 @@
(define (make-fn-env fn-form) (define (make-fn-env fn-form)
(let ((env (make-hash-table)) (let ((env (make-hash-table))
(parameters (make-hash-table))) (parameters (make-hash-table)))
;; `(p (* struct point))' writes the type in one piece and
;; `(p * struct point)' spreads it over the rest, so the type is
;; the whole tail whenever there is more of it than one element
(for-each (lambda (param) (for-each (lambda (param)
(when (and (pair? param) (pair? (cdr param)) (when (named-arg? param)
(named-arg? param))
(hash-table-set! parameters (hash-table-set! parameters
(first param) (first param)
(if (null? (cddr param)) (named-arg-type param))))
(second param)
(cdr param)))))
(sex-fn-arglist fn-form)) (sex-fn-arglist fn-form))
(set! (hash-table-ref env :fn-name) (sex-fn-name fn-form)) (set! (hash-table-ref env :fn-name) (sex-fn-name fn-form))
(set! (hash-table-ref env :lambda-counter) 0) (set! (hash-table-ref env :lambda-counter) 0)
@@ -486,13 +492,22 @@
(set! (hash-table-ref env :scopes) (list parameters)) (set! (hash-table-ref env :scopes) (list parameters))
env)) env))
;;; (fn sum ((a int) (b int)) int ...) -> (fn ((int) (int)) int). ;;; `(p (* struct point))' writes the type in one piece and
;;; Anything that is not a plain (name type) -- a variadic tail -- goes ;;; `(p * struct point)' spreads it over the rest; both are
;;; through untouched. ;;; `(* struct point)'
(define (named-arg-type param)
(if (null? (cddr param))
(second param)
(cdr param)))
;;; (fn sum ((a int) (b int)) int ...) -> (fn ((int) (int)) int), and
;;; (self * const v) is ((* const v)) just as (self (* const v)) is.
;;; Anything that names nothing -- a variadic tail -- goes through
;;; untouched.
(define (arglist-types arglist) (define (arglist-types arglist)
(map (lambda (param) (map (lambda (param)
(if (and (pair? param) (= 2 (length param)) (named-arg? param)) (if (named-arg? param)
(list (second param)) (list (named-arg-type param))
param)) param))
arglist)) arglist))
@@ -558,6 +573,35 @@
(list walked)))) (list walked))))
forms)) forms))
;;; #t while the walk is inside a value -- an initializer, an argument,
;;; a returned expression -- where a statement-only form has no C
;;; spelling:
;;;
;;; (var n int (match s ...)) -> int n = switch (s.tag) { ...
;;;
;;; A condition is not tracked: `walk-parts' takes every slot of an `if'
;;; alike.
(define operand-position? (make-parameter #f))
(define (walk-operand form env)
(parameterize ((operand-position? #t))
(walk-statement form env)))
;;; FORMS are values written inside PARENT, which is what a diagnostic
;;; about one of them points at -- a bare name has no location of its
;;; own:
;;;
;;; (var f (fn ((r float)) shape) shape/circle)
(define (walk-operands parent forms env)
(for-each (lambda (form)
(when (and (symbol? form) (get-constructor form))
(sex-error parent
"a constructor is not a function; call it from a lambda"
form)))
forms)
(parameterize ((operand-position? #t))
(walk-body forms env)))
(define (walk-statement form env) (define (walk-statement form env)
(cond (cond
((vector? form) (walk-initializer form env)) ((vector? form) (walk-initializer form env))
@@ -566,19 +610,15 @@
;; expanded here rather than before the walk, so the macro body can ;; expanded here rather than before the walk, so the macro body can
;; ask `(type-of x)' about a local the walk has already passed ;; ask `(type-of x)' about a local the walk has already passed
((macro? form) ((macro? form)
(let ((expansion (parameterize (let ((expansion (expand-call form env)))
((current-type-of
(lambda (queried)
(unresolve-closure-types
(expression-type queried env)))))
(macroexpand form (list)))))
(if (and (pair? expansion) (null? (cdr expansion))) (if (and (pair? expansion) (null? (cdr expansion)))
(walk-statement (car expansion) env) (walk-statement (car expansion) env)
(cons walk-embed-result (walk-body expansion env))))) (cons walk-embed-result (walk-body expansion env)))))
(else (else
(case (car form) (case (car form)
((do for while if switch case case/fallthrough default) ((do for while if switch case case/fallthrough default)
(with-scope env (lambda () (walk-parts form env)))) (parameterize ((operand-position? #f))
(with-scope env (lambda () (walk-parts form env)))))
((lambda) ((lambda)
(let ((name (aux-name! env make-lambda-name))) (let ((name (aux-name! env make-lambda-name)))
@@ -595,8 +635,8 @@
(copy-form-source! (copy-form-source!
form form
`(,construct ,@(map (lambda (capture) `(,construct ,@(map (lambda (capture)
(walk-statement (capture-argument capture) (walk-operand (capture-argument capture)
env)) env))
(fourth form)))))))) (fourth form))))))))
((var) ((var)
@@ -616,7 +656,7 @@
form form
(append prefix (append prefix
(if (> (length form) 3) (if (> (length form) 3)
(walk-body (drop form 3) env) (walk-operands form (drop form 3) env)
(list)))) (list))))
env)) env))
(bound (if (>= (length walked) 4) (bound (if (>= (length walked) 4)
@@ -633,7 +673,7 @@
bound)) bound))
((return) ((return)
(let ((walked (walk-parts 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 walked
@@ -643,7 +683,10 @@
(cddr walked)))) (cddr walked))))
walked))) walked)))
((match) (walk-match form env)) ((match)
(when (operand-position?)
(sex-error form "match is a statement, and has no value"))
(walk-match form env))
((dot-access) (walk-member-path form env)) ((dot-access) (walk-member-path form env))
@@ -656,21 +699,106 @@
(walk-parts form env))) (walk-parts form env)))
(else (else
(if (method-head? (car form)) (cond
(walk-method-call form env) ((method-head? (car form)) (walk-method-call form env))
(let ((closure (receiver-closure-type (car form) env))) ((get-constructor (car form))
(if closure => (lambda (constructor) (walk-construction form constructor env)))
;; the receiver is walked first: `((closure ((x int)) ((receiver-closure-type (car form) env)
;; int () ...) 5)' registers `struct ƛint_int' on the => (lambda (closure)
;; way, and the call helper's signature names it ;; the receiver is walked first: `((closure ((x int))
(let ((receiver (walk-statement (car form) env))) ;; int () ...) 5)' registers `struct ƛint_int' on the
(copy-form-source! ;; way, and the call helper's signature names it
form (let ((receiver (walk-operand (car form) env)))
`(,(register-closure-call! closure form) (copy-form-source!
,receiver form
,@(map (lambda (a) (walk-statement a env)) `(,(register-closure-call! closure form)
(cdr form))))) ,receiver
(convert-arguments (walk-parts form env) env))))))))) ,@(walk-operands form (cdr form) env))))))
(else
(convert-arguments (copy-form-source! form (walk-operands form form env))
env))))))))
;;; (shape/circle 1.0) is the value itself, written where it is used:
;;;
;;; (shape){.tag = shapeǂcircle, .u = {.circle = (struct shapeːcircle){1.0}}}
;;;
;;; so it is a constant where one is wanted, an lvalue a method can take
;;; the address of, and a pub sum pastes nothing into the importer but
;;; its declarations. A lambda argument is converted against its field
;;; the way a call converts one against its parameter.
(define (walk-construction form constructor env)
(let* ((name (car constructor))
(tag (cdr constructor))
(fields (variant-fields (get-sum name) tag))
(args (walk-operands form (cdr form) env)))
(unless (= (length fields) (length args))
(sex-error form "variant takes this many fields" tag (length fields)))
(sum-literal name tag
(map (lambda (field arg) (field-argument field arg env form))
fields args))))
;;; An array field cannot be handed an array, C copying neither, so it
;;; is handed the array's elements:
;;;
;;; (shape/row #(1 2 3 4)) -> ...(struct shapeːrow){{1, 2, 3, 4}}
;;; (shape/row a) -> ...(struct shapeːrow){{a[0], a[1], a[2], a[3]}}
(define (field-argument field arg env form)
(let ((type (second field)))
(if (not (array-form? type))
(convert-to-closure type arg env form)
(let ((given (expression-type arg env)))
(cond
((brace-initializer? arg) arg)
((not (array-form? given))
(sex-error form "an array field takes an array" (first field)))
((not (eqv? (array-length given) (array-length type)))
(sex-error form "array is not as long as its field" (first field)))
;; `#([int 4] : 1 2 3 4)' is its own elements
((vector? arg) (list->vector (cdr (memq ': (vector->list arg)))))
((not (simple-path? arg))
(sex-error form "an array is read once per element; bind it to a var first"
(first field)))
(else (spell-out-array type arg)))))))
(define (array-form? type)
(and (pair? type) (eq? '¤ (car type))))
;;; [int 4] -> 4, and [int N] -> 4 after (define N 4); #f for a length
;;; nothing here can count
(define (array-length type)
(and (array-bound? type)
(let ((bound (last type)))
(cond ((and (integer? bound) (exact? bound)) bound)
((symbol? bound)
(let ((info (get-type-info bound)))
(and info (eq? 'define (car info))
(let ((value (caddr info)))
(and (= 1 (length value))
(integer? (car value))
(exact? (car value))
(car value))))))
(else #f)))))
;;; xs : [int 2] -> #((¤ xs 0) (¤ xs 1))
(define (spell-out-array type expr)
(list->vector (map (lambda (i) `(¤ ,expr ,i)) (iota (array-length type)))))
;;; The forms a macro call stands for, with `(type-of x)' answered from
;;; ENV
(define (expand-call form env)
(parameterize ((current-type-of
(lambda (queried)
(unresolve-closure-types (expression-type queried env)))))
(macroexpand form (list))))
;;; `#(v : (.get a))' is `(v){vːget(&a)}': the values are expressions
;;; like any other, and the type before `:' is not one
(define (walk-literal form env)
(let* ((parts (vector->list form))
(elements (or (and (memq ': parts) (cdr (memq ': parts))) parts)))
(list->vector
(append (drop-right parts (length elements))
(map (lambda (element) (walk-operand element env)) elements)))))
;;; #(struct point : (. p x) 2) -- the values are expressions, and the ;;; #(struct point : (. p x) 2) -- the values are expressions, and the
;;; words before a `:' a type that is left as written ;;; words before a `:' a type that is left as written
@@ -849,20 +977,31 @@
(else (case (car expr) (else (case (car expr)
((dot-access %->) (simple-path? (second expr))) ((dot-access %->) (simple-path? (second expr)))
((*) (and (= 2 (length expr)) (simple-path? (second expr)))) ((*) (and (= 2 (length expr)) (simple-path? (second expr))))
((¤) (and (= 3 (length expr))
(simple-path? (second expr))
(or (symbol? (third expr)) (number? (third expr)))))
(else #f))))) (else #f)))))
(define (match-arm-variant arm) (and (pair? (car arm)) (car (car arm)))) (define (match-arm-variant arm) (and (pair? (car arm)) (car (car arm))))
(define (check-match form name variants arms) (define (check-match form name variants arms)
(for-each
(lambda (arm)
(unless (and (pair? arm)
(or (eq? (car arm) 'else)
(and (list? (car arm)) (= 2 (length (car arm)))
(list? (second (car arm))))))
(sex-error form "an arm is ((variant (binders ...)) body ...)" arm)))
arms)
(let* ((else? (lambda (arm) (eq? (car arm) 'else))) (let* ((else? (lambda (arm) (eq? (car arm) 'else)))
(named (remove else? arms)) (named (remove else? arms))
(covered (map match-arm-variant named))) (covered (map match-arm-variant named)))
(when (> (count else? arms) 1)
(sex-error form "match has more than one else"))
(for-each (for-each
(lambda (arm) (lambda (arm)
(let* ((variant (match-arm-variant arm)) (let* ((variant (match-arm-variant arm))
(fields (variant-fields variants variant))) (fields (variant-fields variants variant)))
(unless (and (list? (car arm)) (= 2 (length (car arm))))
(sex-error form "an arm is ((variant (binders ...)) body ...)" arm))
(unless fields (unless fields
(sex-error form "not a variant of" name variant)) (sex-error form "not a variant of" name variant))
(unless (= (length fields) (length (second (car arm)))) (unless (= (length fields) (length (second (car arm))))
@@ -890,13 +1029,18 @@
,@(cdr arm)))))) ,@(cdr arm))))))
arms))) arms)))
;;; A binder is a copy of its field, an array one included:
;;;
;;; (var xs [int 2] #((¤ s.u.row.xs 0) (¤ s.u.row.xs 1)))
(define (match-bindings scrutinee variant binders fields) (define (match-bindings scrutinee variant binders fields)
(filter-map (filter-map
(lambda (binder field) (lambda (binder field)
(and (not (eq? binder '_)) (and (not (eq? binder '_))
`(var ,binder ,(second field) (let ((type (second field))
(dot-access (dot-access (dot-access ,scrutinee u) ,variant) (path `(dot-access (dot-access (dot-access ,scrutinee u) ,variant)
,(first field))))) ,(first field))))
`(var ,binder ,type
,(if (array-form? type) (spell-out-array type path) path)))))
binders fields)) binders fields))
;;; (.length v) is a call to vec2ːlength; (. v length) is the field ;;; (.length v) is a call to vec2ːlength; (. v length) is the field
@@ -936,17 +1080,24 @@
(copy-form-source! (copy-form-source!
form form
`(,method `(,method
,(method-receiver method (and target #t) ,(method-receiver method (or target written) (and target #t)
(walk-statement receiver env) form) (walk-operand receiver env) form)
,@(map (lambda (argument) (walk-statement argument env)) ,@(walk-operands form (cddr form) env)))))))
(cddr form))))))))
;;; A method taking (* Self) wants an address and one taking Self wants ;;; A method taking (* Self) wants an address and one taking Self wants
;;; a value; the receiver is one or the other, so one of the two gets ;;; a value; the receiver is one or the other, so one of the two gets
;;; `&' or `*' put in front of it ;;; `&' or `*' put in front of it.
(define (method-receiver method pointer? receiver form) ;;;
(let ((wants-pointer? (let ((self (method-self-type method))) ;;; OBJECT is what the receiver holds or points at: a `(const v)' handed
(and (pair? self) (eq? '* (car self)))))) ;;; to a method taking (* v) would be quietly stripped of its const.
(define (method-receiver method object pointer? receiver form)
(let* ((self (method-self-type method))
(wants-pointer? (and (pair? self) (eq? '* (car self)))))
(when (and wants-pointer?
(const-type? object)
(not (const-type? (pointer-target self))))
(sex-error form "method may change its receiver, and this one is const"
method))
(cond ((eq? wants-pointer? pointer?) receiver) (cond ((eq? wants-pointer? pointer?) receiver)
((not wants-pointer?) `(* ,receiver)) ((not wants-pointer?) `(* ,receiver))
;; `&(f())' is not C, and the method cannot be given a ;; `&(f())' is not C, and the method cannot be given a
@@ -969,7 +1120,7 @@
;;; only C knows -- (. font handle), not font. ;;; only C knows -- (. font handle), not font.
(define (walk-member-path form env) (define (walk-member-path form env)
(let ((base (second form))) (let ((base (second form)))
(let step ((expr (walk-statement base env)) (let step ((expr (walk-operand base env))
(type (expression-type base env)) (type (expression-type base env))
(read (list)) ; the fields walked, reversed (read (list)) ; the fields walked, reversed
(fields (cddr form)) (fields (cddr form))
@@ -1003,8 +1154,10 @@
(eq? 'fn (car signature)) (eq? 'fn (car signature))
(pair? (cdr signature)) (pair? (cdr signature))
(pair? (second signature)) (pair? (second signature))
(let ((self (car (second signature)))) (unwrap-type (car (second signature))))))
(if (pair? self) (car self) self)))))
(define (const-type? type)
(and (pair? type) (eq? 'const (car type))))
(define (as-closure-type type) (define (as-closure-type type)
@@ -1046,7 +1199,17 @@
(let ((written (car parts))) (let ((written (car parts)))
(if (= 1 (length written)) (car written) written))))) (if (= 1 (length written)) (car written) written)))))
((symbol? expr) (or (lookup-name env expr) (get-name-type expr))) ((symbol? expr) (or (lookup-name env expr) (get-name-type expr)))
;; the walk expands `(the a)' before it gets there, so its type is
;; that of what it expands to:
;;
;; (.len (the a)) (match (the s) ...) (. (the a) x)
((macro? expr)
(let ((expansion (expand-call expr env)))
(and (pair? expansion) (null? (cdr expansion))
(expression-type (car expansion) env))))
((not (and (list? expr) (pair? expr))) #f) ((not (and (list? expr) (pair? expr))) #f)
;; (shape/circle 1.0) -> shape
((and (symbol? (car expr)) (get-constructor (car expr))) => car)
;; a call of no arguments is still a call ;; a call of no arguments is still a call
((< (length expr) 2) ((< (length expr) 2)
(and (symbol? (car expr)) (get-return-type (car expr)))) (and (symbol? (car expr)) (get-return-type (car expr))))
@@ -1609,9 +1772,19 @@
(unless (and (symbol? name) (list? declared) (pair? declared)) (unless (and (symbol? name) (list? declared) (pair? declared))
(sex-error form "sum needs a name and a list of variants" form)) (sex-error form "sum needs a name and a list of variants" form))
(let ((variants (map (lambda (v) (parse-variant form v)) declared))) (let ((variants (map (lambda (v) (parse-variant form v)) declared)))
(for-each (lambda (v)
(for-each (lambda (field) (check-variant-field form name field))
(cdr v)))
variants)
(let* ((names (map car variants))
(twice (find (lambda (v) (> (count (cut eq? <> v) names) 1)) names)))
(when twice
(sex-error form "variant is declared twice" twice)))
(when (get-sum name) (when (get-sum name)
(sex-error form "sum is already defined" name)) (sex-error form "sum is already defined" name))
(add-sum! name variants) (add-sum! name variants)
(for-each (lambda (v) (add-constructor! (qualify-op name (car v)) name (car v)))
variants)
(fold match-sex-form acc (fold match-sex-form acc
(map (lambda (f) (copy-form-source! form f)) (map (lambda (f) (copy-form-source! form f))
(sum-forms name variants)))))) (sum-forms name variants))))))
@@ -1621,6 +1794,25 @@
(sex-error form "a variant is (name (fields ...))" v)) (sex-error form "a variant is (name (fields ...))" v))
(cons (car v) (normalize-fields (cadr v)))) (cons (car v) (normalize-fields (cadr v))))
;;; (sum expr ((neg ((e expr))))) has no size; (neg ((e (* expr)))) does.
;;; An array field is spelled out element by element wherever it is
;;; copied, so its length has to be one sexc can count.
(define (check-variant-field form name field)
(let ((type (second field)))
(when (holds-by-value? type name)
(sex-error form "a sum holds itself through a pointer" (first field)))
(when (and (array-form? type) (not (array-length type)))
(sex-error form "array field needs a length written as a number"
(first field)))))
(define (holds-by-value? type name)
(cond ((eq? type name) #t)
((not (pair? type)) #f)
((memq (car type) '(struct const volatile))
(and (pair? (cdr type)) (holds-by-value? (cadr type) name)))
((array-form? type) (holds-by-value? (array-element-type type) name))
(else #f)))
(define (sum-forms name variants) (define (sum-forms name variants)
(let ((carried (filter (lambda (v) (pair? (cdr v))) variants))) (let ((carried (filter (lambda (v) (pair? (cdr v))) variants)))
`(;; forward, so a variant may hold a pointer back to the sum `(;; forward, so a variant may hold a pointer back to the sum
@@ -1636,39 +1828,32 @@
`((u (union ,(map (lambda (v) `((u (union ,(map (lambda (v)
`(,(car v) `(,(car v)
(struct ,(qualify-op name (car v))))) (struct ,(qualify-op name (car v)))))
carried))))))) carried))))))))))
,@(map (lambda (v) (sum-constructor name v)) variants))))
;;; (shape/circle 1.0) builds the value in one compound literal, so a ;;; #(shape : .tag shapeǂcircle .u #(.circle #((struct shapeːcircle) : 1.0)))
;;; constructor is an expression and not three statements (define (sum-literal name tag values)
;;; Static even when the sum is pub: a pub sum is pasted whole into
;;; the importer, and two units defining shapeːcircle would not link.
(define (sum-constructor name variant)
(let* ((tag (car variant))
(fields (cdr variant))
(payload (qualify-op name tag)))
`(fn ,payload ,fields ,name
(return ,(sum-literal name tag payload fields)))))
;;; #(shape : .tag shapeːtagːcircle .u #(.circle #((struct shapeːcircle) : r)))
(define (sum-literal name tag payload fields)
(list->vector (list->vector
(append (list name ': (dotted 'tag) (sum-tag-constant name tag)) (append (list name ': (dotted 'tag) (sum-tag-constant name tag))
(if (null? fields) (if (null? values)
(list) (list)
(list (dotted 'u) (list (dotted 'u)
(vector (dotted tag) (vector (dotted tag)
(list->vector (list->vector
(append (list (list 'struct payload) ':) (append (list (list 'struct (qualify-op name tag)) ':)
(map car fields))))))))) values))))))))
(define (dotted name) (define (dotted name)
(string->symbol (string-append "." (symbol->string name)))) (string->symbol (string-append "." (symbol->string name))))
(define (sum-tag name) (qualify-op name 'tag)) ;;; shape -> enum shapeǂ, circle -> shapeǂcircle. Not shapeːtag: that
;;; is where a variant named `tag' keeps its payload struct, and an enum
;;; and a struct share C's tag namespace.
(define (sum-tag name)
(string->symbol (string-append (symbol->string name) "ǂ")))
(define (sum-tag-constant name variant) (define (sum-tag-constant name variant)
(qualify-op (sum-tag name) variant)) (string->symbol (string-append (symbol->string (sum-tag name))
(symbol->string variant))))
;;; (record point ((x int) (y int))) is a struct that also names ;;; (record point ((x int) (y int))) is a struct that also names
;;; itself, so `point' alone stands where `(struct point)' had to: ;;; itself, so `point' alone stands where `(struct point)' had to:
@@ -1705,28 +1890,44 @@
;;; No function around a toplevel form, so no scope chain: what a ;;; No function around a toplevel form, so no scope chain: what a
;;; global's initializer names comes from `get-name-type' alone. ;;; global's initializer names comes from `get-name-type' alone.
(define (make-toplevel-env) ;;; What a global's initializer is walked in: no names but its own,
;;; and anything it lifts is named after the global
(define (make-toplevel-env name)
(let ((env (make-hash-table))) (let ((env (make-hash-table)))
(set! (hash-table-ref env :fn-name) name)
(set! (hash-table-ref env :lambda-counter) 0)
(set! (hash-table-ref env :lambda-aux-code) (list))
(set! (hash-table-ref env :scopes) (list)) (set! (hash-table-ref env :scopes) (list))
env)) env))
;;; The writer spells neither `closure' nor `_', and an initializer is
;;; an expression like any other:
;;;
;;; (var n _ 1) -> int n = 1
;;; (var o v #(v : (.get a))) -> v o = (v){vːget(&a)}
(define (process-global-var sex-var acc) (define (process-global-var sex-var acc)
;; A global is not walked for lambdas, but the writer spells neither
;; `closure' nor `_': `(var n _ 1)' has to reach it as `int n = 1'
(let* ((resolved (resolve-closure-types sex-var)) (let* ((resolved (resolve-closure-types sex-var))
(qualifier (and (memq (car resolved) '(pub extern)) (car resolved))) (qualifier (and (memq (car resolved) '(pub extern)) (car resolved)))
(core (if qualifier (cdr resolved) resolved)) (core (if qualifier (cdr resolved) resolved))
(env (make-toplevel-env (and (pair? (cdr core)) (second core))))
;; `(extern var n int)' has no initializer to work a `_' out ;; `(extern var n int)' has no initializer to work a `_' out
;; from ;; from
(core (if (eq? 'extern qualifier) (core (if (eq? 'extern qualifier)
core core
(resolve-wildcard core (make-toplevel-env)))) (resolve-wildcard
(copy-form-source!
core
(if (> (length core) 3)
(append (take core 3)
(walk-operands core (drop core 3) env))
core))
env)))
(form (if qualifier (form (if qualifier
(copy-form-source! resolved (cons qualifier core)) (copy-form-source! resolved (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)))
(cons form acc))) (cons form (append (hash-table-ref env :lambda-aux-code) acc))))
;;; Utils ;;; Utils
(define (non-empty-list? form) (define (non-empty-list? form)

View File

@@ -38,6 +38,7 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
"import" "import"
"include" "include"
"fn" "fn"
"ops"
"pub" "pub"
"record" "record"
"realize" "realize"
@@ -62,6 +63,7 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
"if" "if"
"for" "for"
"goto" "goto"
"match"
"return" "return"
"switch" "switch"
"var" "var"

View File

@@ -881,6 +881,22 @@ whitespace aside, THEN?"
(test-assert "a bare -> is not the arrow" (test-assert "a bare -> is not the arrow"
(emits? (in-line "(= (-> pp x) 1)") "->(pp, x) = 1"))) (emits? (in-line "(= (-> pp x) 1)") "->(pp, x) = 1")))
;; A global's initializer is an expression like a local's, and walked
;; the same way
(test-group "global initializers"
(test-assert "a path is dispatched on its type"
(emits? (string-append "(struct pt ((x int)))"
"(var a (struct pt) #((struct pt) : 1))"
"(var q (* int) (& (. a x)))")
"int * q = &a.x"))
(test-assert "a lambda is lifted, and named after the global"
(emits? "(var f (fn ((x int)) int) (lambda ((x int)) int (return x)))"
"int (*f)(int) = λ0_f"))
(test-assert "ahead of it"
(let ((c (sex->c "(var f (fn ((x int)) int) (lambda ((x int)) int (return x)))")))
(< (string-contains c "static int λ0_f (int x)")
(string-contains c "(*f)(int) = λ0_f")))))
;; Toplevel forms used to be separated by a blank line unconditionally, ;; Toplevel forms used to be separated by a blank line unconditionally,
;; which spread a block of adjacent typedefs over twice the lines its ;; which spread a block of adjacent typedefs over twice the lines its
;; author wrote ;; author wrote

View File

@@ -29,7 +29,8 @@ ahead of its pub forms."
"(record vec2 ((x float) (y float)))" "(record vec2 ((x float) (y float)))"
"(ops vec2" "(ops vec2"
" (pub fn length ((self (* const vec2))) float (return 1.0))" " (pub fn length ((self (* const vec2))) float (return 1.0))"
" (fn sum-of ((self vec2)) float (return (. self x))))" " (fn sum-of ((self vec2)) float (return (. self x)))"
" (fn scale ((self (* vec2))) void (= (. self x) 2.0)))"
"(fn mk () vec2 (return #(vec2 : 1.0 2.0)))" "(fn mk () vec2 (return #(vec2 : 1.0 2.0)))"
"(fn f () void (var v vec2 #(vec2 : 1.0 2.0)) (var p (* vec2) (& v)) " "(fn f () void (var v vec2 #(vec2 : 1.0 2.0)) (var p (* vec2) (& v)) "
(apply string-append body) ")")) (apply string-append body) ")"))
@@ -142,6 +143,60 @@ ahead of its pub forms."
(reports? (ops-src "(.nope v)") "no such method on")) (reports? (ops-src "(.nope v)") "no such method on"))
(test-assert "and so is a receiver with no type to dispatch on" (test-assert "and so is a receiver with no type to dispatch on"
(reports? "(fn f () void (var n int 1) (.get n))" "no such method on")) (reports? "(fn f () void (var n int 1) (.get n))" "no such method on"))
(test-assert "a self spread over the parameter is a pointer self too"
(emits? (string-append
"(record w ((x int)))"
"(ops w (fn get ((self * const w)) int (return (. self x))))"
"(fn f () int (var a w #(w : 1)) (var p (* const w) (& a))"
" (return (+ (.get a) (.get p))))")
"wːget(&a) + wːget(p)"))
(test-assert "a const receiver is not handed to a method that may change it"
(reports? (ops-src "(var c (* const vec2) p) (.scale c)")
"this one is const"))
(test-assert "one that cannot change it takes it"
(emits? (ops-src "(var c (* const vec2) p) (var n float (.length c))")
"vec2ːlength(c)"))
(test-assert "a macro receiver is typed by what it expands to"
(emits? (string-append "(defmacro (the a) a)"
(ops-src "(var n float (.length (the v)))"))
"vec2ːlength(&v)"))
(test-assert "and so is the start of a path"
(emits? (string-append "(defmacro (the a) a)"
(ops-src "(var q float (. (the p) x))"))
"p->x"))
(test-assert "a typedef of the type has its methods"
(emits? (string-append
"(record w ((x int)))"
"(typedef alias w)"
"(ops w (fn get ((self (* const w))) int (return (. self x))))"
"(fn f () int (var a alias #(alias : 1)) (return (.get a)))")
"wːget(&a)"))
(test-assert "and a method written on the typedef is the type's"
(emits? (string-append
"(record w ((x int)))"
"(typedef alias w)"
"(ops alias (fn get ((self (* const alias))) int (return 1)))"
"(fn f () int (var a w #(w : 1)) (return (.get a)))")
"aliasːget(&a)"))
(test-assert "a typedef of a scalar keeps its own"
(reports? (string-append
"(typedef meters float)"
"(ops meters (fn half ((self meters)) meters (return self)))"
"(fn f () void (var x float 1.0) (.half x))")
"no such method on"))
(test-assert "which a typedef of it shares"
(emits? (string-append
"(typedef meters float)"
"(typedef km meters)"
"(ops meters (fn half ((self meters)) meters (return self)))"
"(fn f () void (var x km 1.0) (var y km (.half x)))")
"metersːhalf(x)"))
(test-assert "a method call inside a literal is still a call"
(emits? (ops-src "(var w vec2 #(vec2 : (.length v) 1.0))")
"(vec2){vec2ːlength(&v), 1.0}"))
(test-assert "however deep"
(emits? (ops-src "(var ws [vec2 1] #(#(vec2 : (.length p) 1.0)))")
"{(vec2){vec2ːlength(p), 1.0}}"))
(test-assert "an address cannot be taken of a call" (test-assert "an address cannot be taken of a call"
(reports? (ops-src "(.length (mk))") "receiver is not an lvalue")) (reports? (ops-src "(.length (mk))") "receiver is not an lvalue"))
;; the inner call has to be typed to find the outer one's receiver ;; the inner call has to be typed to find the outer one's receiver
@@ -157,7 +212,11 @@ ahead of its pub forms."
;; fields, the record holding both, and a constructor each. ;; fields, the record holding both, and a constructor each.
(test-group "sum" (test-group "sum"
(test-assert "the tag enum is named after the sum" (test-assert "the tag enum is named after the sum"
(emits? (sum-src "") "enum shapeːtag")) (emits? (sum-src "") "enum shapeǂ {"))
(test-assert "and its constants after the sum and the variant"
(emits? (sum-src "") "shapeǂcircle"))
(test-assert "a variant may be called tag"
(emits? "(sum t ((tag ((x int))) (none ())))" "struct tːtag {"))
(test-assert "a variant with fields gets a payload struct" (test-assert "a variant with fields gets a payload struct"
(emits? (sum-src "") "struct shapeːcircle {")) (emits? (sum-src "") "struct shapeːcircle {"))
(test-assert "the sum is typedef'd" (test-assert "the sum is typedef'd"
@@ -168,8 +227,61 @@ ahead of its pub forms."
(test-assert "the typedef comes before the payloads, for a recursive sum" (test-assert "the typedef comes before the payloads, for a recursive sum"
(emits? "(sum expr ((lit ((v float))) (neg ((e (* const expr))))))" (emits? "(sum expr ((lit ((v float))) (neg ((e (* const expr))))))"
"typedef struct expr expr;")) "typedef struct expr expr;"))
(test-assert "constructors are static even when the sum is pub" (test-assert "a constructor is written in place"
(emits? "(pub sum t ((a ((x int)))))" "static t tːa")) (emits? "(pub sum t ((a ((x int)))))(fn f () t (return (t/a 1)))"
"(struct tːa){1}"))
(test-assert "and is no function"
(not (emits? "(pub sum t ((a ((x int)))))(fn f () t (return (t/a 1)))"
"t tːa (")))
(test-assert "so it is a constant at file scope"
(emits? "(sum t ((a ((x int)))))(var g t (t/a 1))" "static t g = (t){"))
(test-assert "and an lvalue a method can take the address of"
(emits? (string-append
"(sum t ((a ((x int)))))"
"(ops t (fn get ((self (* const t))) int (return 1)))"
"(fn f () int (return (.get (t/a 1))))")
"tːget(&(t){"))
(test-assert "a constructor takes as many arguments as its variant has fields"
(reports? "(sum t ((a ((x int)))))(fn f () t (return (t/a 1 2)))"
"variant takes this many fields"))
(test-assert "and is not a function value"
(reports? "(sum t ((a ((x int)))))(fn f () void (var g (fn ((x int)) t) t/a))"
"a constructor is not a function"))
(test-assert "an array field takes a brace literal as it is"
(emits? "(sum t ((a ((xs [int 2])))))(fn f () t (return (t/a #(1 2))))"
"(struct tːa){{1, 2}}"))
(test-assert "and an array by its elements"
(emits? "(sum t ((a ((xs [int 2])))))(fn f () t (var v [int 2] #(1 2)) (return (t/a v)))"
"(struct tːa){{v[0], v[1]}}"))
(test-assert "which have to be countable"
(reports? "(fn n () int (return 2))(sum t ((a ((xs [int (n)])))))"
"array field needs a length"))
(test-assert "and as many as the field holds"
(reports? "(sum t ((a ((xs [int 2])))))(fn f () t (var v [int 3] #(1 2 3)) (return (t/a v)))"
"array is not as long as its field"))
(test-assert "an array field takes an array"
(reports? "(sum t ((a ((xs [int 2])))))(fn f () t (var p (* int) 0) (return (t/a p)))"
"an array field takes an array"))
(test-assert "read from a path, not from a call"
(reports? (string-append "(sum t ((a ((xs [int 2])))))(fn g () int (return 0))"
"(fn f () t (var m [t 2]) (return (t/a (. [m (g)] u a xs))))")
"bind it to a var first"))
(test-assert "an array binder is a copy of each element"
(emits? (string-append "(sum t ((a ((xs [int 2])))))"
"(fn f ((s t)) int (match s ((a (xs)) (return [xs 0]))))")
"int xs[2] = {s.u.a.xs[0], s.u.a.xs[1]}"))
(test-assert "a sum cannot hold itself"
(reports? "(sum box ((inner ((x box)))))" "a sum holds itself through a pointer"))
(test-assert "nor an array of itself"
(reports? "(sum box ((inner ((x [box 2])))))" "a sum holds itself through a pointer"))
(test-assert "though it can point at itself"
(emits? "(sum box ((inner ((x (* box))))))" "box * x;"))
(test-assert "a function argument becomes the closure its field holds"
(emits? (string-append
"(fn g ((n int)) int (return n))"
"(sum t ((a ((k (closure ((int)) int))))))"
"(fn f () t (return (t/a g)))")
"ƛint_int_fromfn(g)"))
(test-assert "a tag-only sum has no union at all" (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"
@@ -177,7 +289,9 @@ ahead of its pub forms."
(test-assert "and needs variants" (test-assert "and needs variants"
(reports? "(sum t)" "sum needs a name and a list of variants")) (reports? "(sum t)" "sum needs a name and a list of variants"))
(test-assert "a variant is a name and a field list" (test-assert "a variant is a name and a field list"
(reports? "(sum t (a))" "a variant is"))) (reports? "(sum t (a))" "a variant is"))
(test-assert "and is declared once"
(reports? "(sum t ((a ((x int))) (a ())))" "variant is declared twice")))
;; A spec is a contract that emits nothing; a realization is its ;; A spec is a contract that emits nothing; a realization is its
;; methods for one type. The refusals are what make it a contract. ;; methods for one type. The refusals are what make it a contract.
@@ -211,6 +325,9 @@ ahead of its pub forms."
(test-assert "a spec is declared once" (test-assert "a spec is declared once"
(reports? "(spec (p T) (fn s ((a T)) void))(spec (p T) (fn q ((a T)) void))" (reports? "(spec (p T) (fn s ((a T)) void))(spec (p T) (fn q ((a T)) void))"
"spec is already declared")) "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" (test-assert "a type realizes a spec once"
(reports? (string-append (spec-src "") "(realize (p v)" (reports? (string-append (spec-src "") "(realize (p v)"
" (fn s ((a (* const v))) void (return)))") " (fn s ((a (* const v))) void (return)))")
@@ -229,6 +346,23 @@ ahead of its pub forms."
" (fn q ((a (* const T))) void))" " (fn q ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) void (return)))") "(realize (p v) (fn s ((a (* const v))) void (return)))")
"q")) "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" (test-assert "a method the spec has not got is refused"
(reports? (string-append "(record v ((x int)))" (reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void))" "(spec (p T) (fn s ((a (* const T))) void))"
@@ -245,6 +379,11 @@ ahead of its pub forms."
"(spec (p T) (fn s ((a (* const T))) void))" "(spec (p T) (fn s ((a (* const T))) void))"
"(realize (p v) (fn s ((a v)) void (return)))") "(realize (p v) (fn s ((a v)) void (return)))")
"arguments do not match")) "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" (test-assert "a method name already taken on the type is refused"
(reports? (string-append "(record v ((x int)))" (reports? (string-append "(record v ((x int)))"
"(ops v (fn s ((a (* const v))) void (return)))" "(ops v (fn s ((a (* const v))) void (return)))"
@@ -274,6 +413,18 @@ ahead of its pub forms."
(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 "a macro scrutinee is typed by what it expands to"
(emits? (string-append "(defmacro (the a) a)"
(sum-src "(match (the s) ((circle (r)) (= out r))"
" (else (= out 0.0)))"))
"shape ƛm0 = s"))
(test-assert "a typedef of a sum is matched as the sum"
(emits? (string-append
"(sum shape ((circle ((r int))) (empty ())))"
"(typedef alias shape)"
"(fn f () int (var s alias (shape/circle 1))"
" (match s ((circle (r)) (return r)) ((empty ()) (return 0))))")
"case shapeǂcircle"))
(test-assert "else becomes default" (test-assert "else becomes default"
(emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))") (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))")
"default:")) "default:"))
@@ -300,6 +451,26 @@ ahead of its pub forms."
(reports? (sum-src "(match s ((circle (r)) (= out r)) ((circle (q)) (= out q))" (reports? (sum-src "(match s ((circle (r)) (= out r)) ((circle (q)) (= out q))"
" (else (= out 0.0)))") " (else (= out 0.0)))")
"arm is written twice")) "arm is written twice"))
(test-assert "so is a second else"
(reports? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0))"
" (else (= out 1.0)))")
"more than one else"))
(test-assert "so is an arm that is not one"
(reports? (sum-src "(match s foo)") "an arm is"))
(test-assert "match has no value"
(reports? (sum-src "(var n float (match s ((circle (r)) r) (else 0.0)))")
"match is a statement"))
(test-assert "not even as an argument"
(reports? (sum-src "(= out (match s ((circle (r)) r) (else 0.0)))")
"match is a statement"))
(test-assert "but a case body is a statement"
(emits? (sum-src "(switch 1 (case 1 (match s ((circle (r)) (= out r))"
" (else (= out 0.0)))))")
"switch (s.tag)"))
(test-assert "and so is a closure's, wherever the closure stands"
(emits? (sum-src "(var c (closure () int) (closure () int ((t s))"
" (match t ((circle (r)) (return 1)) (else (return 0)))))")
"switch (t.tag)"))
(test-assert "and a scrutinee that is not a sum" (test-assert "and a scrutinee that is not a sum"
(reports? "(fn f () void (var n int 1) (match n ((a ()) (= n 2))))" (reports? "(fn f () void (var n int 1) (match n ((a ()) (= n 2))))"
"match wants a sum"))) "match wants a sum")))

View File

@@ -106,8 +106,8 @@
(free self))) (free self)))
;;; A pub sum is pasted whole, so the importer builds its own copy of ;;; A pub sum is pasted whole, so the importer builds its own copy of
;;; the declarations -- and of the constructors, which is why those are ;;; the declarations; a constructor is written in place where it is
;;; static: two units defining colourːrgb would not link. ;;; 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 ;;; A spec and a realization over the boundary. The written method

View File

@@ -2,14 +2,15 @@
(output "3.14 12.00 0.00" (output "3.14 12.00 0.00"
"held once: a 1" "held once: a 1"
"nested: -(2 + 3) = -5" "nested: -(2 + 3) = -5"
"tagged only: 1") "tagged only: 1"
"rows: 18 5")
(return 0) (return 0)
;;; A sum is a tag enum, a payload struct per variant that carries ;;; A sum is a tag enum, a payload struct per variant that carries
;;; fields, the record holding both, and a constructor each. match is ;;; fields, and the record holding both; a constructor is the value
;;; a switch over the tag whose arms bind the payload as locals, and ;;; itself, written in place. match is a switch over the tag whose arms
;;; the compiler refuses one that leaves a variant out -- which is the ;;; bind the payload as locals, and the compiler refuses one that leaves
;;; thing the form exists for. ;;; a variant out -- which is the thing the form exists for.
(include stdio.h) (include stdio.h)
@@ -52,6 +53,12 @@
(sum held ((a ((x int) (y int))) (b ()))) (sum held ((a ((x int) (y int))) (b ())))
(fn mk-held () held (return (held/a 1 2))) (fn mk-held () held (return (held/a 1 2)))
;;; An array field is handed elements, never an array: C copies neither
;;; into a parameter nor into another array, so both the constructor
;;; and the binder spell it out
(define N 4)
(sum row ((cells ((xs [int N]))) (none ())))
(pub fn main () int (pub fn main () int
(printf "%.2f %.2f %.2f\n" (printf "%.2f %.2f %.2f\n"
(area (mk-shape)) (area (mk-shape))
@@ -75,4 +82,16 @@
(match l (match l
((red ()) (printf "tagged only: 0\n")) ((red ()) (printf "tagged only: 0\n"))
((green ()) (printf "tagged only: 1\n"))) ((green ()) (printf "tagged only: 1\n")))
(var a [int N] #(5 6 7 8))
(var rows [row 2] #((row/cells a) (row/cells #(1 2 3 4))))
(= [a 0] 50) ; the row holds a copy
(var sum int 0)
(for (var i int 0) (< i 2) (++ i)
(match [rows i]
((cells (xs))
(= [xs 0] 100) ; and so does the binder
(+= sum (+ [xs 1] [xs 2])))
((none ()) (+= sum 0))))
(printf "rows: %d %d\n" sum (. [rows 0] u cells [xs 0]))
(return 0)) (return 0))

View File

@@ -16,6 +16,7 @@
(ops expr (ops expr
(pub fn eval ((self (* const expr))) float (pub fn eval ((self (* const expr))) float
;; v, e, l and r are copies of the fields, not references to them
(match (* self) (match (* self)
((lit (v)) (return v)) ((lit (v)) (return v))
((neg (e)) (return (- (.eval e)))) ((neg (e)) (return (- (.eval e))))

View File

@@ -11,6 +11,8 @@
add-sum! add-sum!
get-sum get-sum
add-constructor!
get-constructor
variant-fields variant-fields
reset-declarations! reset-declarations!

View File

@@ -11,6 +11,8 @@
add-sum! add-sum!
get-sum get-sum
add-constructor!
get-constructor
variant-fields variant-fields
reset-declarations! reset-declarations!

View File

@@ -100,10 +100,19 @@
(define +sum-db+ (make-hash-table)) (define +sum-db+ (make-hash-table))
(define (add-sum! name variants) (define (add-sum! name variants)
(hash-table-set! +sum-db+ name variants)) (hash-table-set! +sum-db+ (type-key name) variants))
(define (get-sum name) (define (get-sum name)
(hash-table-ref/default +sum-db+ name #f)) (hash-table-ref/default +sum-db+ (type-key name) #f))
;;; shape/circle -> (shape . circle), for each variant of each sum
(define +constructor-db+ (make-hash-table))
(define (add-constructor! constructor sum variant)
(hash-table-set! +constructor-db+ constructor (cons sum variant)))
(define (get-constructor name)
(hash-table-ref/default +constructor-db+ name #f))
(define (variant-fields variants name) (define (variant-fields variants name)
(let ((entry (assq name variants))) (let ((entry (assq name variants)))
@@ -130,17 +139,18 @@
(define (spec-methods spec) (cdr spec)) (define (spec-methods spec) (cdr spec))
(define (add-realization! spec type) (define (add-realization! spec type)
(hash-table-set! +realize-db+ (cons spec type) #t)) (hash-table-set! +realize-db+ (cons spec (type-key type)) #t))
;;; What a generic macro asks before it expands: (realizes? 'ord 'circle) ;;; What a generic macro asks before it expands: (realizes? 'ord 'circle)
(define (realizes? spec type) (define (realizes? spec type)
(hash-table-exists? +realize-db+ (cons spec type))) (hash-table-exists? +realize-db+ (cons spec (type-key type))))
;;; Both of these refuse a second declaration of the same name, which ;;; Both of these refuse a second declaration of the same name, which
;;; is per translation unit rather than per process -- so a process ;;; is per translation unit rather than per process -- so a process
;;; that compiles two units has to start the second one clean. ;;; that compiles two units has to start the 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! +ops-db+ (make-hash-table)) (set! +ops-db+ (make-hash-table))
(set! +spec-db+ (make-hash-table)) (set! +spec-db+ (make-hash-table))
(set! +realize-db+ (make-hash-table))) (set! +realize-db+ (make-hash-table)))
@@ -156,10 +166,10 @@
(define +ops-db+ (make-hash-table)) (define +ops-db+ (make-hash-table))
(define (add-method! type method qualified) (define (add-method! type method qualified)
(hash-table-set! +ops-db+ (cons type method) qualified)) (hash-table-set! +ops-db+ (cons (type-key type) method) qualified))
(define (get-method type method) (define (get-method type method)
(hash-table-ref/default +ops-db+ (cons type method) #f)) (hash-table-ref/default +ops-db+ (cons (type-key type) method) #f))
;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength ;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength
(define (qualify-op type name) (define (qualify-op type name)
@@ -169,13 +179,33 @@
;;; The name an `ops' block was written against: `(struct point)' and a ;;; The name an `ops' block was written against: `(struct point)' and a
;;; `const' wrapper both name `point', and anything else names nothing. ;;; `const' wrapper both name `point', and anything else names nothing.
(define (ops-key type) (define (ops-key type)
(cond ((symbol? type) type) (cond ((symbol? type) (type-key type))
((not (and (pair? type) (symbol? (car type)))) #f) ((not (and (pair? type) (symbol? (car type)))) #f)
((memq (car type) '(struct union enum)) ((memq (car type) '(struct union enum))
(and (pair? (cdr type)) (symbol? (cadr type)) (cadr type))) (and (pair? (cdr type)) (symbol? (cadr type)) (cadr type)))
((memq (car type) '(const volatile)) (ops-key (cadr type))) ((memq (car type) '(const volatile)) (ops-key (cadr type)))
(else #f))) (else #f)))
;;; The name methods, realizations and sums are filed under. A typedef
;;; is followed to the aggregate it names, and one that ends in anything
;;; else stops at the last typedef, so a scalar does not share them:
;;;
;;; (record v ...) (typedef alias v) alias -> v
;;; (typedef meters float) meters -> meters
;;; (typedef km meters) km -> meters
(define (type-key name)
(let follow ((name name) (seen (list)))
(let ((target (and (not (memq name seen)) (typedef-target name))))
(cond ((not target) name)
((symbol? target)
(if (typedef-target target) (follow target (cons name seen)) name))
((target-tag target))
(else name)))))
(define (typedef-target name)
(let ((info (and (symbol? name) (get-type-info name))))
(and info (eq? (car info) 'typedef) (caddr info))))
(define (add-name-type! name type) (define (add-name-type! name type)
(hash-table-set! +name-db+ name type)) (hash-table-set! +name-db+ name type))