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.
This commit is contained in:
2026-11-11 09:17:54 +03:00
parent ad37a2492e
commit be2f4e407b
18 changed files with 118 additions and 1127 deletions

585
semen.scm
View File

@@ -20,7 +20,6 @@
)
(export/rename (process semen-process))
(export closure-env-declaration)
;;; for lambda extraction, docstring processing, macro expansion,
;;; injection of module headers, i.e. all things that rearrange code
@@ -56,13 +55,10 @@
(macroexpand (car forms) (cdr forms))
acc))
(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))
(new (take-until processed acc)))
(process-rec (cdr forms)
(append new (flush-closure-structs!) acc))))))
(append new acc))))))
(define (take-until forms tail)
(if (eq? forms tail)
@@ -303,7 +299,7 @@
(add-name-type! (sex-fn-name expanded) (fn-type-of expanded))
(let* ((env (make-fn-env expanded))
;; 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))
(walk-body (drop expanded boundary) env)))
;; A function is header and body stitched together, so the
@@ -409,8 +405,8 @@
;;; The scope chain
;;;
;;; `(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
;;; form whose body C brackets opens a frame; innermost first:
;;; an outer `c' is in scope after it. Every form whose body C brackets
;;; opens a frame; innermost first:
;;;
;;; (var v double 3.75)
;;; (while (< v 0) (var v char 1) ...)
@@ -437,10 +433,9 @@
;;; The body walk
;;;
;;; One pass in statement order: lifts lambdas and closures out,
;;; resolves closure types to the struct that stands for them, records
;;; what each declaration binds, and rewrites a call whose head is a
;;; closure.
;;; One pass in statement order: lifts lambdas out, records what each
;;; declaration binds, and rewrites a call whose head is a function
;;; value.
;;;
;;; 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)'
@@ -511,31 +506,15 @@
(add-aux-code! env (lift-lambda name form))
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)
;; the initializer is walked before the name it binds is in
;; scope; the type is resolved rather than walked, a parameter
;; list being shaped like a call:
;;
;; (var c (closure ((int)) int) ...)
;; (var fp (fn ((c int)) int) ...) ; int (*fp)(int)
(let* ((prefix (if (>= (length form) 3)
(append (take form 2)
(list (resolve-closure-types
(expand-type (third form) env))))
(list (expand-type (third form) env)))
form))
(walked (resolve-wildcard
(copy-form-source!
@@ -544,29 +523,15 @@
(if (> (length form) 3)
(walk-operands form (drop form 3) env)
(list))))
env))
(bound (if (>= (length walked) 4)
(copy-form-source!
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))
env)))
(when (>= (length walked) 3)
(declare-name! env (second walked) (third walked)))
walked))
((return)
(let ((walked (copy-form-source! form (walk-operands form form env))))
(if (>= (length walked) 2)
(copy-form-source!
walked
(cons 'return
(cons (convert-to-closure (hash-table-ref env :returns)
(second walked) env walked)
(cddr walked))))
(copy-form-source! walked (cons 'return (cdr walked)))
walked)))
((match)
@@ -590,8 +555,7 @@
(if (and (= 2 (length form)) (written-type? (second form) env))
(copy-form-source!
form
`(sizeof (%type ,(resolve-closure-types
(expand-type (second form) env)))))
`(sizeof (%type ,(expand-type (second form) env))))
(walk-parts form env)))
(else
@@ -599,23 +563,11 @@
((method-head? (car form)) (walk-method-call form env))
((get-constructor (car form))
=> (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
(when (and (symbol? (car form)) (form-source form)
(not (hash-table-exists? +called-as-functions+ (car form))))
(hash-table-set! +called-as-functions+ (car form) form))
(convert-arguments (copy-form-source! form (walk-operands form form env))
env))))))))
(copy-form-source! form (walk-operands form form env)))))))))
;;; 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
@@ -668,7 +620,7 @@
(define (field-argument field arg env form)
(let ((type (second field)))
(if (not (array-form? type))
(convert-to-closure type arg env form)
arg
(let ((given (expression-type arg env)))
(cond
((brace-initializer? arg)
@@ -716,7 +668,7 @@
(define (expand-call form env)
(parameterize ((current-type-of
(lambda (queried)
(unresolve-closure-types (expression-type queried env)))))
(expression-type queried env))))
(macroexpand form (list))))
;;; #(struct point : (. p x) 2) -- the values are expressions, and the
@@ -787,16 +739,15 @@
(let ((type (expression-type written env)))
(when type
(unify element
(parse-type (resolve-closure-types type))
(parse-type type)
form))))
(vector->list initializer))))
(else
(let ((type (expression-type initializer env)))
(unless type
(sex-error form "cannot infer the type of" (second form)))
;; `(closure ((int)) int)' is spelled `(struct ƛint_int)'
;; everywhere past this point, and is what `parse-type' knows
(let ((given (parse-type (resolve-closure-types type))))
;; a type is what `parse-type' knows
(let ((given (parse-type type)))
;; an array as a value is a pointer to its first element, which
;; is what a `_' standing alone takes; `[_ 3]' asks for an array
(unify declared
@@ -820,34 +771,8 @@
((vector? form) (mentions? (vector->list form) word))
(else #f)))
;;; `(each xs compare)' where `each' takes a closure: the argument is
;;; checked against the parameter that signature wrote.
(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:
;;; What a `fn' header gets, a `var' type gets -- macro expansion, no
;;; walk:
;;;
;;; (defmacro (ty) 'int) (var x (ty) 0) -> int x = 0;
;;;
@@ -856,8 +781,7 @@
(let ((expanded
(parameterize ((current-type-of
(lambda (queried)
(unresolve-closure-types
(expression-type queried env)))))
(expression-type queried env))))
(macro-expand (list type)))))
(if (and (pair? expanded) (null? (cdr expanded)))
(car expanded)
@@ -936,7 +860,7 @@
arms))
(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
;;; in there does not
@@ -1172,16 +1096,6 @@
(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
;;; what can be reached from one by subscripting, dereferencing and
;;; member access.
@@ -1268,10 +1182,6 @@
(cddr expr)))
((cast) (and (= 3 (length expr)) (third expr)))
((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 c-or) 'bool)
;; one pointer from another is how far apart they are
@@ -1299,12 +1209,10 @@
;; (++ c), c : char -> char
((++ --) (expression-type (second expr) env))
;; otherwise a call: a method answers for the name it resolves
;; to, a closure with its own return type, anything else with
;; what its signature says
;; to, anything else with what its signature says
(else
(cond
((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
((and (symbol? (car expr))
(not (lookup-name env (car expr)))
@@ -1505,455 +1413,31 @@
(list)))
(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))'
(define (unwrap-type type)
(if (and (list? type) (= 1 (length type)))
(car 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
;;; 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)
(map (lambda (arg index)
(if (or (named-arg? arg) (comment-form? arg)
(eq? arg '...) (equal? arg '(...)))
arg
(list (string->symbol (string-append "ƛu" (number->string index)))
(list (string->symbol (string-append "λu" (number->string index)))
(unwrap-type arg))))
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
;;; Record the named structs, unions and enums in the type database
(define (process-struct sex-struct acc)
(let-values (((doc form) (extract-aggregate-docstring sex-struct)))
;; Resolve before registering: a field of closure type has to reach
;; the type database as the struct it becomes, or member access
;; through it finds nothing
(let ((form (resolve-closure-types form)))
(register-aggregate! form)
(with-docstring doc form acc))))
(register-aggregate! form)
(with-docstring doc form acc)))
;;; (sum shape ((circle ((r float))) (rect ((w float) (h float)))))
;;; is the tag enum, a payload struct per variant that has fields, the
@@ -2133,16 +1617,15 @@
(set! (hash-table-ref env :scopes) (list))
env))
;;; The writer spells neither `closure' nor `_', and an initializer is
;;; an expression like any other:
;;; The writer spells no `_', and an initializer is an expression like
;;; any other:
;;;
;;; (var n _ 1) -> int n = 1
;;; (var o v #(v : (.get a))) -> v o = (v){vːget(&a)}
(define (process-global-var sex-var acc)
(check-shape (if (memq (car sex-var) '(pub extern)) (cdr sex-var) sex-var))
(let* ((resolved (resolve-closure-types sex-var))
(qualifier (and (memq (car resolved) '(pub extern)) (car resolved)))
(core (if qualifier (cdr resolved) resolved))
(let* ((qualifier (and (memq (car sex-var) '(pub extern)) (car sex-var)))
(core (if qualifier (cdr sex-var) sex-var))
(env (make-toplevel-env (and (pair? (cdr core)) (second core))))
;; `(extern var n int)' has no initializer to work a `_' out
;; from
@@ -2164,7 +1647,7 @@
(drop solved 3))))
solved))))
(form (if qualifier
(copy-form-source! resolved (cons qualifier core))
(copy-form-source! sex-var (cons qualifier core))
core)))
(when (and (pair? (cdr core)) (pair? (cddr core)) (symbol? (second core)))
(add-name-type! (second core) (third core)))