4 Commits
0.0.1 ... main

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
24 changed files with 134 additions and 1604 deletions

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

727
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,455 +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)
(let twice ((names names))
(when (pair? names)
(when (memq (car names) (cdr names))
(sex-error form "two captures share a name" (car names)))
(twice (cdr names))))
(for-each (lambda (statement)
(match statement
(('var (? symbol? name) . _)
(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 (register-aggregate! form)
;; the type database as the struct it becomes, or member access (with-docstring doc form acc)))
;; through it finds nothing
(let ((form (resolve-closure-types form)))
(register-aggregate! form)
(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
@@ -2273,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
@@ -2304,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

@@ -70,9 +70,7 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
"import" "import"
"include" "include"
"ops" "ops"
"realize"
"record" "record"
"spec"
"struct" "struct"
"sum" "sum"
"typedef" "typedef"
@@ -94,7 +92,6 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
"case" "case"
"case/fallthrough" "case/fallthrough"
"cast" "cast"
"closure"
"continue" "continue"
"default" "default"
"do" "do"
@@ -106,7 +103,6 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
"lambda" "lambda"
"map-fields" "map-fields"
"match" "match"
"realizes?"
"return" "return"
"sizeof" "sizeof"
"static-assert" "static-assert"
@@ -139,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)

View File

@@ -270,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))
@@ -292,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))
@@ -363,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)
@@ -392,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)))
@@ -409,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)
@@ -520,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
@@ -543,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,22 +257,17 @@ 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)
(include stddef.h) ; max_align_t, for closure environments (typedef u8 uint8-t)
(typedef u8 uint8-t) (typedef i8 int8-t)
(typedef i8 int8-t) (typedef u16 uint16-t)
(typedef u16 uint16-t) (typedef i16 int16-t)
(typedef i16 int16-t) (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,52 +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 captured twice"
(reports? (in-fn "(var c (closure () int) (closure () int (a a) (return a)))")
"two captures share a name"))
(test-assert "so is one redeclared at the top of the body"
(reports? (in-fn "(var c (closure () int) (closure () int (a) (var a int 5) (return a)))")
"the body redeclares a capture"))
(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, ...)"))
@@ -527,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.
@@ -696,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;"))
@@ -786,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
@@ -820,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"))
@@ -879,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"))
@@ -964,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"))))

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

@@ -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
@@ -145,12 +142,6 @@
(let ((err (error-of sexc "--public-interface" "gen/broken.sex"))) (let ((err (error-of sexc "--public-interface" "gen/broken.sex")))
(and err (irregex-search "broken\\.sex:8: expanding boom: nope" err)))) (and err (irregex-search "broken\\.sex:8: expanding boom: nope" err))))
;;; ...while a realization of a spec importers cannot see is refused by
;;; the module that writes it, not by an importer naming it first
(test-assert "a pub realization of a spec imported without pub is refused"
(let ((err (error-of sexc "specs/money.sex" "-C" "-o" "-")))
(and err (irregex-search "money.sex:8: importers cannot see this spec" err) #t)))
(test "the app runs through both" (test "the app runs through both"
'("hello, world" '("hello, world"
"hello, sex" "hello, sex"
@@ -158,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

@@ -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

@@ -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
@@ -44,9 +44,8 @@
(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 %lld\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) least) (sides unit) (.area corner) (.area [pair 1]) [primes 2] (. origin y) least)

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!
@@ -324,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)
(known type (hash-table-exists? +realize-db+ (cons spec (type-key type)))))
;;; Sums, constructors, methods and specs refuse a second declaration
;;; of the same name, which is per translation unit rather than per ;;; 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
@@ -378,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