forked from alex-eg/sex
An array field compiled to C that cc refused: an array is neither an initializer of another nor something a payload literal can be built from. Both the constructor and the binder now spell it out element by element, which needs a length sexc can count. A sum holding itself by value is refused at the declaration rather than as cc's incomplete type.
1901 lines
77 KiB
Scheme
1901 lines
77 KiB
Scheme
;;; Sex semantic engine
|
||
|
||
(import
|
||
scheme
|
||
(only (scheme base) make-parameter)
|
||
(chicken base)
|
||
(chicken keyword)
|
||
(chicken string)
|
||
(chicken module)
|
||
fmt
|
||
infer
|
||
sex-macros
|
||
sex-modules
|
||
types
|
||
matchable ; pattern matching
|
||
srfi-1 ; list routines
|
||
srfi-69 ; hash tables
|
||
utils
|
||
)
|
||
|
||
(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
|
||
;;; structurally, add or remove forms
|
||
;;;
|
||
;;; The algorithm: feed toplevel forms to appropriate handlers, then
|
||
;;; append their return to the resulting list. Each handler can return
|
||
;;; multiple forms, e.g. lambdas collected from a function may result
|
||
;;; in auxiliary structures and functions.
|
||
(define (process raw-sex-forms)
|
||
(reset-declarations!)
|
||
(process-rec raw-sex-forms (list)))
|
||
|
||
(define (process-rec forms acc)
|
||
(cond
|
||
((null? forms) (reverse acc))
|
||
((macro? (car forms))
|
||
(process-rec
|
||
(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))))))
|
||
|
||
(define (take-until forms tail)
|
||
(if (eq? forms tail)
|
||
(list)
|
||
(cons (car forms) (take-until (cdr forms) tail))))
|
||
|
||
(define (macroexpand macro-form rest-forms)
|
||
;; `(defmacro (two) 2)' expands to `2', and `($ (fn a ...) (fn b ...))'
|
||
;; to two forms, spliced where the macro was written. `($)' expands to
|
||
;; nothing.
|
||
;;
|
||
;; Everything else is one form, a list whose head is itself a form
|
||
;; included: `((make-adder 10) 5)' calls what `make-adder' returned,
|
||
;; and without `$' to mark a splice there is no telling that from a
|
||
;; list of the two forms `(make-adder 10)' and `5'.
|
||
(let ((res (apply-macro macro-form))
|
||
(src (form-source macro-form)))
|
||
;; An expansion is fresh structure with no location of its own. Give
|
||
;; it the call site's, the way cpp attributes a macro body to where
|
||
;; the macro was used
|
||
(cond
|
||
((splice-form? res)
|
||
(append (map (lambda (f) (stamp-form-source! f src)) (cdr res))
|
||
rest-forms))
|
||
((null? res) rest-forms)
|
||
(else
|
||
(cons (stamp-form-source! res src) rest-forms)))))
|
||
|
||
(define (splice-form? form)
|
||
(and (pair? form) (list? form) (eq? '$ (car form))))
|
||
|
||
(define (match-sex-form sex-form acc)
|
||
(match sex-form
|
||
((or ('fn . _)
|
||
('pub 'fn . _)
|
||
('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))
|
||
(('pub 'ops . _)
|
||
(sex-error sex-form "pub belongs on the methods, not on ops" sex-form))
|
||
((or ('sum . _)
|
||
('pub 'sum . _)) (process-sum sex-form acc))
|
||
((or ('record . _)
|
||
('pub 'record . _)) (process-record sex-form acc))
|
||
((or ('struct . _)
|
||
('pub 'struct . _)) (process-struct sex-form acc))
|
||
((or ('union . _)
|
||
('pub 'union . _)) (process-struct sex-form acc))
|
||
((or ('enum . _)
|
||
('pub 'enum . _)) (process-struct sex-form acc))
|
||
((or ('var . _)
|
||
('pub 'var . _)
|
||
('extern 'var . _)) (process-global-var sex-form acc))
|
||
;; `pub' on either of these is what read-public-interface already
|
||
;; accepts, and a module whose spec defaults call printf has to be
|
||
;; able to say so
|
||
((or ('include . includes)
|
||
('pub 'include . includes)) (process-includes sex-form includes acc))
|
||
((or ('define name . _)
|
||
('pub 'define name . _))
|
||
(add-define name sex-form)
|
||
(cons sex-form acc))
|
||
(('comment . _) (cons sex-form acc))
|
||
|
||
((or ('import . modules)
|
||
('pub 'import . modules))
|
||
(process-imports (get-modules-public-forms modules) acc))
|
||
|
||
((or ('defmacro . rest)
|
||
('pub 'defmacro . rest)) (defmacro rest) acc)
|
||
|
||
((or ('typedef new-type target)
|
||
('pub 'typedef new-type target))
|
||
(add-typedef new-type sex-form)
|
||
(process-typedef sex-form new-type target acc))
|
||
|
||
(else (sex-error sex-form "unknown top level form" sex-form))))
|
||
|
||
(define (process-includes sex-form includes acc)
|
||
;; consume (include ...) form and add to acc
|
||
;; (include <inc>) for each include
|
||
(let process ((includes includes)
|
||
(acc acc))
|
||
(if (null? includes)
|
||
acc
|
||
(process (cdr includes)
|
||
(cons (copy-form-source! sex-form `(include ,(car includes)))
|
||
acc)))))
|
||
|
||
(define (process-imports module-public-forms acc)
|
||
;; consume (import ...) form and process imports so
|
||
;; data types end up in types db
|
||
(fold match-sex-form acc module-public-forms))
|
||
|
||
(define (macro-expand form)
|
||
"Walk the form recursively and expand all macros, until none is left."
|
||
(walk-form
|
||
form
|
||
(lambda (subform env)
|
||
(if (macro? subform)
|
||
(cons walk-embed-result (macroexpand subform (list)))
|
||
subform))
|
||
#f))
|
||
|
||
;;; walk-form and friends: form walker with various abilities.
|
||
;;; By default, replaces walked form with walk-fn result But may
|
||
;;; perform additional operations depending of what the walk function
|
||
;;; has requested.
|
||
|
||
;;; For inspiration, see SBCL's walk.lisp and their template
|
||
;;; system.
|
||
|
||
(define walk-embed-result (gensym)
|
||
;; For cases when result is a list which must be embedded in the
|
||
;; form, e.g. when it returned from a macro
|
||
)
|
||
|
||
(define (walk-form form walk-fn env)
|
||
(if (atom? form) form
|
||
(let ((new-form (walk-fn form env)))
|
||
(if (not (eq? form new-form))
|
||
(walk-form new-form walk-fn env)
|
||
(walk-rest new-form walk-fn env)))))
|
||
|
||
;;; The cdr of a form is a list of forms and not itself one, so it is
|
||
;;; walked without being offered to WALK-FN: otherwise the tail of
|
||
;;; (fn g () t) is the list (t), which reads as a call to a macro
|
||
;;; named t -- and a function whose return type shares a name with a
|
||
;;; macro expanded that tail and died on the arity.
|
||
(define (walk-rest form walk-fn env)
|
||
(if (atom? form) form
|
||
(let ((new-car (walk-form (car form) walk-fn env))
|
||
(new-cdr (walk-rest (cdr form) walk-fn env)))
|
||
(if (and (pair? new-car)
|
||
(eq? (car new-car) walk-embed-result))
|
||
(append (cdr new-car) new-cdr)
|
||
(recons form new-car new-cdr)))))
|
||
|
||
;;; Typdef
|
||
|
||
(define (process-typedef form new-type target acc)
|
||
(cons (copy-form-source! form `(typedef ,target ,new-type)) acc))
|
||
|
||
;;; Fn processing
|
||
;;;
|
||
;;; A string as the first body form is a docstring. In the generated
|
||
;;; C code it will be placed as a C commentary just before the function
|
||
;;; definition (actually that works for all blocky things: enum, struct, union as well).
|
||
|
||
(define (fn-header-length fn-form)
|
||
(if (memq (first fn-form) '(pub extern)) 5 4))
|
||
|
||
(define (fn-core form)
|
||
;; The (fn name args rettype . body) list, without pub/extern
|
||
(if (memq (first form) '(pub extern))
|
||
(cdr form)
|
||
form))
|
||
|
||
(define (take-leading-docstring forms)
|
||
;; If FORMS starts with a string, possibly after comment forms, return
|
||
;; that string and FORMS without it. Otherwise #f and FORMS unchanged
|
||
(let loop ((fs forms) (prefix (list)))
|
||
(match fs
|
||
(() (values #f forms))
|
||
(((and cmt ('comment . _)) . rest)
|
||
(loop rest (cons cmt prefix)))
|
||
(((? string? doc) . rest)
|
||
(values doc (append (reverse prefix) rest)))
|
||
(_ (values #f forms)))))
|
||
|
||
(define (extract-fn-docstring fn-form)
|
||
(let ((lift
|
||
(lambda (proto body)
|
||
(let-values (((doc rest) (take-leading-docstring body)))
|
||
(if doc
|
||
(values doc (copy-form-source! fn-form (append proto rest)))
|
||
(values #f fn-form))))))
|
||
(match fn-form
|
||
(('pub 'fn name args ret . body)
|
||
(lift `(pub fn ,name ,args ,ret) body))
|
||
(('extern 'fn name args ret . body)
|
||
(lift `(extern fn ,name ,args ,ret) body))
|
||
(('fn name args ret . body)
|
||
(lift `(fn ,name ,args ,ret) body))
|
||
(_ (values #f fn-form)))))
|
||
|
||
(define (extract-aggregate-docstring form)
|
||
;; A string immediately after the name is the docstring; comments
|
||
;; between name and fields are not skipped, they already confuse the
|
||
;; writer
|
||
(match form
|
||
(('pub (and kind (or 'struct 'union 'enum))
|
||
(? symbol? name) (? string? doc) . rest)
|
||
(values doc (copy-form-source! form `(pub ,kind ,name ,@rest))))
|
||
(((and kind (or 'struct 'union 'enum))
|
||
(? symbol? name) (? string? doc) . rest)
|
||
(values doc (copy-form-source! form `(,kind ,name ,@rest))))
|
||
(_ (values #f form))))
|
||
|
||
(define (with-docstring doc form acc)
|
||
;; acc is newest-first; FORM is consed last so the final reverse
|
||
;; emits the comment immediately before the declaration
|
||
(cons form
|
||
(if doc
|
||
(cons (copy-form-source! form (list 'comment doc)) acc)
|
||
acc)))
|
||
|
||
(define (strip-fn-header-comments fn-form)
|
||
;; ([pub|extern] fn name arglist rettype). Comments in the body are
|
||
;; left in place as ordinary statements and preserved into the
|
||
;; generated C.
|
||
(strip-header-comments fn-form (fn-header-length fn-form)))
|
||
|
||
(define (process-fn sex-fn-raw acc)
|
||
(let-values (((doc sex-fn)
|
||
(extract-fn-docstring (strip-fn-header-comments sex-fn-raw))))
|
||
(let* ((boundary (fn-header-length sex-fn))
|
||
;; only the header is expanded up front. A macro in the body
|
||
;; is expanded during the walk, where `(type-of x)' can still
|
||
;; be answered from the scope it was written in
|
||
(expanded (append (macro-expand (take sex-fn boundary))
|
||
(drop sex-fn boundary))))
|
||
(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)))
|
||
(body (parameterize ((operand-position? #f))
|
||
(walk-body (drop expanded boundary) env)))
|
||
;; A function is header and body stitched together, so the
|
||
;; result is fresh structure: without this the definition
|
||
;; has no location, and nothing downstream can say where
|
||
;; the function was written
|
||
(processed (copy-form-source! sex-fn-raw (append header body))))
|
||
(with-docstring doc processed
|
||
(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)
|
||
(fold (lambda (entry acc)
|
||
(process-realized-method form name type
|
||
(and pub? (cdr entry)) (car entry) acc))
|
||
acc
|
||
(realization-methods type parameter wanted given))))))
|
||
|
||
;;; 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.
|
||
(define (process-realized-method form spec type pub? method acc)
|
||
(let* ((name (second method))
|
||
(qualified (qualify-op (qualify-op type spec) name))
|
||
(renamed (rename-fn method qualified)))
|
||
(when (get-method type name)
|
||
(sex-error form "method is already defined on" type name))
|
||
(add-method! type name qualified)
|
||
(process-fn (copy-form-source! form (if pub? (cons 'pub renamed) renamed))
|
||
acc)))
|
||
|
||
;;; 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
|
||
;;; (pub fn length ((self (* const vec2))) float ...))
|
||
;;;
|
||
;;; is (pub fn vec2/length ...) plus a registry entry, so that
|
||
;;; (. v length) can find it later. The block itself never reaches the
|
||
;;; writer; `pub' inside it means what it means outside.
|
||
(define (process-ops form acc)
|
||
(let ((type (and (pair? (cdr form)) (cadr form))))
|
||
(unless (symbol? type)
|
||
(sex-error form "ops needs a type name" form))
|
||
(fold (lambda (method acc) (process-op type method acc))
|
||
acc
|
||
(cddr form))))
|
||
|
||
(define (process-op type form acc)
|
||
(if (comment-form? form)
|
||
(cons form acc)
|
||
(let ((core (and (pair? form) (fn-core form))))
|
||
(unless (and (pair? core) (eq? (car core) 'fn)
|
||
(pair? (cdr core)) (symbol? (second core)))
|
||
(sex-error form "ops takes fn forms" form))
|
||
(let ((name (second core)))
|
||
(when (get-method type name)
|
||
(sex-error form "method is already defined on" type name))
|
||
(let ((qualified (qualify-op type name)))
|
||
(add-method! type name qualified)
|
||
(process-fn (rename-fn form qualified) acc))))))
|
||
|
||
(define (rename-fn form name)
|
||
(if (memq (first form) '(pub extern))
|
||
(copy-form-source! form (cons (first form) (rename-fn (cdr form) name)))
|
||
(copy-form-source! form `(fn ,name ,@(cddr form)))))
|
||
|
||
(define (make-fn-env fn-form)
|
||
(let ((env (make-hash-table))
|
||
(parameters (make-hash-table)))
|
||
(for-each (lambda (param)
|
||
(when (named-arg? param)
|
||
(hash-table-set! parameters
|
||
(first param)
|
||
(named-arg-type param))))
|
||
(sex-fn-arglist fn-form))
|
||
(set! (hash-table-ref env :fn-name) (sex-fn-name fn-form))
|
||
(set! (hash-table-ref env :lambda-counter) 0)
|
||
(set! (hash-table-ref env :lambda-aux-code) (list))
|
||
(set! (hash-table-ref env :returns) (sex-fn-return-type fn-form))
|
||
(set! (hash-table-ref env :scopes) (list parameters))
|
||
env))
|
||
|
||
;;; `(p (* struct point))' writes the type in one piece and
|
||
;;; `(p * struct point)' spreads it over the rest; both are
|
||
;;; `(* struct point)'
|
||
(define (named-arg-type param)
|
||
(if (null? (cddr param))
|
||
(second param)
|
||
(cdr param)))
|
||
|
||
;;; (fn sum ((a int) (b int)) int ...) -> (fn ((int) (int)) int), and
|
||
;;; (self * const v) is ((* const v)) just as (self (* const v)) is.
|
||
;;; Anything that names nothing -- a variadic tail -- goes through
|
||
;;; untouched.
|
||
(define (arglist-types arglist)
|
||
(map (lambda (param)
|
||
(if (named-arg? param)
|
||
(list (named-arg-type param))
|
||
param))
|
||
arglist))
|
||
|
||
(define (fn-type-of fn-form)
|
||
`(fn ,(arglist-types (sex-fn-arglist fn-form))
|
||
,(sex-fn-return-type fn-form)))
|
||
|
||
(define (aux-name! env make)
|
||
(let ((counter (hash-table-ref env :lambda-counter)))
|
||
(set! (hash-table-ref env :lambda-counter) (+ counter 1))
|
||
(make (hash-table-ref env :fn-name) counter)))
|
||
|
||
(define (add-aux-code! env forms)
|
||
(set! (hash-table-ref env :lambda-aux-code)
|
||
(append forms (hash-table-ref env :lambda-aux-code))))
|
||
|
||
|
||
;;; 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:
|
||
;;;
|
||
;;; (var v double 3.75)
|
||
;;; (while (< v 0) (var v char 1) ...)
|
||
;;; (var m _ (+ v 1)) ; double, not char
|
||
;;;
|
||
;;; One frame per form, not one per arm: a `case' label opens no scope
|
||
;;; in C, and an `if' arm can only declare inside a `do', which brings
|
||
;;; its own.
|
||
|
||
(define (declare-name! env name type)
|
||
(hash-table-set! (car (hash-table-ref env :scopes)) name type))
|
||
|
||
(define (lookup-name env name)
|
||
(let search ((scopes (hash-table-ref env :scopes)))
|
||
(and (pair? scopes)
|
||
(or (hash-table-ref/default (car scopes) name #f)
|
||
(search (cdr scopes))))))
|
||
|
||
(define (with-scope env body)
|
||
(let ((enclosing (hash-table-ref env :scopes)))
|
||
(set! (hash-table-ref env :scopes) (cons (make-hash-table) enclosing))
|
||
(let ((walked (body)))
|
||
(set! (hash-table-ref env :scopes) enclosing)
|
||
walked)))
|
||
|
||
;;; 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.
|
||
;;;
|
||
;;; 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)'
|
||
;;; arrives as `(f)' and reads as a call of its own.
|
||
|
||
(define (walk-body forms env)
|
||
(append-map (lambda (form)
|
||
(let ((walked (walk-statement form env)))
|
||
(if (and (pair? walked) (eq? (car walked) walk-embed-result))
|
||
(cdr walked)
|
||
(list walked))))
|
||
forms))
|
||
|
||
;;; #t while the walk is inside a value -- an initializer, an argument,
|
||
;;; a returned expression -- where a statement-only form has no C
|
||
;;; spelling:
|
||
;;;
|
||
;;; (var n int (match s ...)) -> int n = switch (s.tag) { ...
|
||
;;;
|
||
;;; A condition is not tracked: `walk-parts' takes every slot of an `if'
|
||
;;; alike.
|
||
(define operand-position? (make-parameter #f))
|
||
|
||
(define (walk-operand form env)
|
||
(parameterize ((operand-position? #t))
|
||
(walk-statement form env)))
|
||
|
||
;;; FORMS are values written inside PARENT, which is what a diagnostic
|
||
;;; about one of them points at -- a bare name has no location of its
|
||
;;; own:
|
||
;;;
|
||
;;; (var f (fn ((r float)) shape) shape/circle)
|
||
(define (walk-operands parent forms env)
|
||
(for-each (lambda (form)
|
||
(when (and (symbol? form) (get-constructor form))
|
||
(sex-error parent
|
||
"a constructor is not a function; call it from a lambda"
|
||
form)))
|
||
forms)
|
||
(parameterize ((operand-position? #t))
|
||
(walk-body forms env)))
|
||
|
||
(define (walk-statement form env)
|
||
(cond
|
||
((vector? form) (walk-literal form env))
|
||
((not (list? form)) form)
|
||
((null? form) form)
|
||
;; expanded here rather than before the walk, so the macro body can
|
||
;; ask `(type-of x)' about a local the walk has already passed
|
||
((macro? form)
|
||
(let ((expansion (expand-call form env)))
|
||
(if (and (pair? expansion) (null? (cdr expansion)))
|
||
(walk-statement (car expansion) env)
|
||
(cons walk-embed-result (walk-body expansion env)))))
|
||
(else
|
||
(case (car form)
|
||
((do for while if switch)
|
||
(parameterize ((operand-position? #f))
|
||
(with-scope env (lambda () (walk-parts form env)))))
|
||
|
||
((case case/fallthrough default)
|
||
(parameterize ((operand-position? #f))
|
||
(walk-parts form env)))
|
||
|
||
((lambda)
|
||
(let ((name (aux-name! env make-lambda-name)))
|
||
(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))))
|
||
form))
|
||
(walked (resolve-wildcard
|
||
(copy-form-source!
|
||
form
|
||
(append prefix
|
||
(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))
|
||
|
||
((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))))
|
||
walked)))
|
||
|
||
((match)
|
||
(when (operand-position?)
|
||
(sex-error form "match is a statement, and has no value"))
|
||
(walk-match form env))
|
||
|
||
((dot-access) (walk-member-path form env))
|
||
|
||
(else
|
||
(cond
|
||
((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
|
||
(convert-arguments (copy-form-source! form (walk-operands form form env))
|
||
env))))))))
|
||
|
||
;;; (shape/circle 1.0) is the value itself, written where it is used:
|
||
;;;
|
||
;;; (shape){.tag = shapeǂcircle, .u = {.circle = (struct shapeːcircle){1.0}}}
|
||
;;;
|
||
;;; so it is a constant where one is wanted, an lvalue a method can take
|
||
;;; the address of, and a pub sum pastes nothing into the importer but
|
||
;;; its declarations. A lambda argument is converted against its field
|
||
;;; the way a call converts one against its parameter.
|
||
(define (walk-construction form constructor env)
|
||
(let* ((name (car constructor))
|
||
(tag (cdr constructor))
|
||
(fields (variant-fields (get-sum name) tag))
|
||
(args (walk-operands form (cdr form) env)))
|
||
(unless (= (length fields) (length args))
|
||
(sex-error form "variant takes this many fields" tag (length fields)))
|
||
(sum-literal name tag
|
||
(map (lambda (field arg) (field-argument field arg env form))
|
||
fields args))))
|
||
|
||
;;; An array field cannot be handed an array, C copying neither, so it
|
||
;;; is handed the array's elements:
|
||
;;;
|
||
;;; (shape/row #(1 2 3 4)) -> ...(struct shapeːrow){{1, 2, 3, 4}}
|
||
;;; (shape/row a) -> ...(struct shapeːrow){{a[0], a[1], a[2], a[3]}}
|
||
(define (field-argument field arg env form)
|
||
(let ((type (second field)))
|
||
(if (not (array-form? type))
|
||
(convert-to-closure type arg env form)
|
||
(let ((given (expression-type arg env)))
|
||
(cond
|
||
((brace-initializer? arg) arg)
|
||
((not (array-form? given))
|
||
(sex-error form "an array field takes an array" (first field)))
|
||
((not (eqv? (array-length given) (array-length type)))
|
||
(sex-error form "array is not as long as its field" (first field)))
|
||
;; `#([int 4] : 1 2 3 4)' is its own elements
|
||
((vector? arg) (list->vector (cdr (memq ': (vector->list arg)))))
|
||
((not (simple-path? arg))
|
||
(sex-error form "an array is read once per element; bind it to a var first"
|
||
(first field)))
|
||
(else (spell-out-array type arg)))))))
|
||
|
||
(define (array-form? type)
|
||
(and (pair? type) (eq? '¤ (car type))))
|
||
|
||
;;; [int 4] -> 4, and [int N] -> 4 after (define N 4); #f for a length
|
||
;;; nothing here can count
|
||
(define (array-length type)
|
||
(and (array-bound? type)
|
||
(let ((bound (last type)))
|
||
(cond ((and (integer? bound) (exact? bound)) bound)
|
||
((symbol? bound)
|
||
(let ((info (get-type-info bound)))
|
||
(and info (eq? 'define (car info))
|
||
(let ((value (caddr info)))
|
||
(and (= 1 (length value))
|
||
(integer? (car value))
|
||
(exact? (car value))
|
||
(car value))))))
|
||
(else #f)))))
|
||
|
||
;;; xs : [int 2] -> #((¤ xs 0) (¤ xs 1))
|
||
(define (spell-out-array type expr)
|
||
(list->vector (map (lambda (i) `(¤ ,expr ,i)) (iota (array-length type)))))
|
||
|
||
;;; The forms a macro call stands for, with `(type-of x)' answered from
|
||
;;; ENV
|
||
(define (expand-call form env)
|
||
(parameterize ((current-type-of
|
||
(lambda (queried)
|
||
(unresolve-closure-types (expression-type queried env)))))
|
||
(macroexpand form (list))))
|
||
|
||
;;; `#(v : (.get a))' is `(v){vːget(&a)}': the values are expressions
|
||
;;; like any other, and the type before `:' is not one
|
||
(define (walk-literal form env)
|
||
(let* ((parts (vector->list form))
|
||
(elements (or (and (memq ': parts) (cdr (memq ': parts))) parts)))
|
||
(list->vector
|
||
(append (drop-right parts (length elements))
|
||
(map (lambda (element) (walk-operand element env)) elements)))))
|
||
|
||
;;; `(var n _ (strlen s))' becomes `(var n size-t (strlen s))'.
|
||
(define (resolve-wildcard form env)
|
||
(if (and (>= (length form) 3) (wildcard-type? (third form)))
|
||
(let ((declared (parse-type (third form))))
|
||
(solve-wildcards! declared
|
||
(and (>= (length form) 4) (fourth form))
|
||
form env)
|
||
(let ((written (unparse-type declared)))
|
||
(cond
|
||
;; `?' is what a name from an unparsed header types as, and
|
||
;; the writer has no spelling for it
|
||
((mentions? written '?)
|
||
(sex-error form "type of this is unknown; write it out"
|
||
(second form)))
|
||
((mentions? written '_)
|
||
(sex-error form "cannot infer the type of" (second form)))
|
||
(else
|
||
(copy-form-source! form
|
||
(cons (first form)
|
||
(cons (second form)
|
||
(cons written (cdddr form)))))))))
|
||
form))
|
||
|
||
;;; `(* _)' against `(* (struct point))' solves only the wildcard inside
|
||
;;; the pointer; a bare `_' is the same with nothing around it.
|
||
;;;
|
||
;;; `#(0 1 4 9)' has no type of its own, so it cannot answer a bare `_',
|
||
;;; but its elements still solve the hole in `(¤ _ 4)' -- each one is
|
||
;;; unified with the element type, which is what makes `(¤ _ 4)' worth
|
||
;;; writing at all.
|
||
(define (solve-wildcards! declared initializer form env)
|
||
(cond
|
||
((not initializer)
|
||
(sex-error form "cannot infer the type of" (second form)))
|
||
((brace-initializer? initializer)
|
||
(let ((element (and (array-type? declared) (array-elt declared))))
|
||
(unless element
|
||
(sex-error form "cannot infer the type of" (second form)))
|
||
(for-each (lambda (written)
|
||
(let ((type (expression-type written env)))
|
||
(when type
|
||
(unify element
|
||
(parse-type (resolve-closure-types 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
|
||
(unify declared (parse-type (resolve-closure-types type)) form)))))
|
||
|
||
;;; `#(0 1 4 9)', as against the compound literal `#(T : ...)'
|
||
(define (brace-initializer? form)
|
||
(and (vector? form)
|
||
(null? (cdr (list-split (vector->list form) ':)))))
|
||
|
||
(define (wildcard-type? type) (mentions? type '_))
|
||
|
||
(define (mentions? type word)
|
||
(cond ((eq? type word) #t)
|
||
((list? type) (any (lambda (part) (mentions? part word)) type))
|
||
(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:
|
||
;;;
|
||
;;; (defmacro (ty) 'int) (var x (ty) 0) -> int x = 0;
|
||
;;;
|
||
;;; and the macro may ask `(type-of x)' while it stands in for a type.
|
||
(define (expand-type type env)
|
||
(let ((expanded
|
||
(parameterize ((current-type-of
|
||
(lambda (queried)
|
||
(unresolve-closure-types
|
||
(expression-type queried env)))))
|
||
(macro-expand (list type)))))
|
||
(if (and (pair? expanded) (null? (cdr expanded)))
|
||
(car expanded)
|
||
expanded)))
|
||
|
||
(define (walk-parts form env)
|
||
(copy-form-source! form (walk-body form env)))
|
||
|
||
;;; (match s ((circle (r)) ...) ((empty ()) ...)) is a switch over the
|
||
;;; tag, each arm a block binding that variant's fields as locals. `_'
|
||
;;; drops one. An arm the sum does not have, a wrong number of
|
||
;;; binders, or a variant left out with no `else' are all errors here:
|
||
;;; a missing case is the thing this form exists to catch.
|
||
(define (walk-match form env)
|
||
(let* ((scrutinee (and (pair? (cdr form)) (second form)))
|
||
;; a comment between arms goes the way the writer already
|
||
;; drops one between switch clauses
|
||
(arms (remove comment-form? (cddr form)))
|
||
(type (expression-type scrutinee env))
|
||
(name (ops-key type))
|
||
(variants (and name (get-sum name))))
|
||
(unless variants
|
||
(sex-error form "match wants a sum, and this is not one"
|
||
(or type 'unknown)))
|
||
(check-match form name variants arms)
|
||
(if (simple-path? scrutinee)
|
||
(walk-statement (match-switch name scrutinee variants arms) env)
|
||
;; the scrutinee is read once per binding, so anything that
|
||
;; could be read twice is read into a local first
|
||
(let ((held (aux-name! env make-match-name)))
|
||
(walk-statement
|
||
`(do (var ,held ,type ,scrutinee)
|
||
,(match-switch name held variants arms))
|
||
env)))))
|
||
|
||
(define (make-match-name fn-name 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
|
||
(define (simple-path? expr)
|
||
(cond ((symbol? expr) #t)
|
||
((not (pair? expr)) #f)
|
||
(else (case (car expr)
|
||
((dot-access %->) (simple-path? (second expr)))
|
||
((*) (and (= 2 (length expr)) (simple-path? (second expr))))
|
||
((¤) (and (= 3 (length expr))
|
||
(simple-path? (second expr))
|
||
(or (symbol? (third expr)) (number? (third expr)))))
|
||
(else #f)))))
|
||
|
||
(define (match-arm-variant arm) (and (pair? (car arm)) (car (car arm))))
|
||
|
||
(define (check-match form name variants arms)
|
||
(for-each
|
||
(lambda (arm)
|
||
(unless (and (pair? arm)
|
||
(or (eq? (car arm) 'else)
|
||
(and (list? (car arm)) (= 2 (length (car arm)))
|
||
(list? (second (car arm))))))
|
||
(sex-error form "an arm is ((variant (binders ...)) body ...)" arm)))
|
||
arms)
|
||
(let* ((else? (lambda (arm) (eq? (car arm) 'else)))
|
||
(named (remove else? arms))
|
||
(covered (map match-arm-variant named)))
|
||
(when (> (count else? arms) 1)
|
||
(sex-error form "match has more than one else"))
|
||
(for-each
|
||
(lambda (arm)
|
||
(let* ((variant (match-arm-variant arm))
|
||
(fields (variant-fields variants variant)))
|
||
(unless fields
|
||
(sex-error form "not a variant of" name variant))
|
||
(unless (= (length fields) (length (second (car arm))))
|
||
(sex-error form "variant takes this many fields" variant
|
||
(length fields)))))
|
||
named)
|
||
(let ((twice (find (lambda (v) (> (count (cut eq? <> v) covered) 1))
|
||
covered)))
|
||
(when twice
|
||
(sex-error form "arm is written twice" twice)))
|
||
(let ((missing (lset-difference eq? (map car variants) covered)))
|
||
(when (and (pair? missing) (not (any else? arms)))
|
||
(apply sex-error form "match leaves a variant out:" missing)))))
|
||
|
||
(define (match-switch name scrutinee variants arms)
|
||
`(switch (dot-access ,scrutinee tag)
|
||
,@(map (lambda (arm)
|
||
(if (eq? (car arm) 'else)
|
||
`(default (do ,@(cdr arm)))
|
||
(let* ((variant (match-arm-variant arm))
|
||
(binders (second (car arm)))
|
||
(fields (variant-fields variants variant)))
|
||
`(case ,(sum-tag-constant name variant)
|
||
(do ,@(match-bindings scrutinee variant binders fields)
|
||
,@(cdr arm))))))
|
||
arms)))
|
||
|
||
;;; A binder is a copy of its field, an array one included:
|
||
;;;
|
||
;;; (var xs [int 2] #((¤ s.u.row.xs 0) (¤ s.u.row.xs 1)))
|
||
(define (match-bindings scrutinee variant binders fields)
|
||
(filter-map
|
||
(lambda (binder field)
|
||
(and (not (eq? binder '_))
|
||
(let ((type (second field))
|
||
(path `(dot-access (dot-access (dot-access ,scrutinee u) ,variant)
|
||
,(first field))))
|
||
`(var ,binder ,type
|
||
,(if (array-form? type) (spell-out-array type path) path)))))
|
||
binders fields))
|
||
|
||
;;; (.length v) is a call to vec2ːlength; (. v length) is the field
|
||
;;; `length', always. Keeping them apart means the shape of a form can
|
||
;;; be read without knowing the receiver's type -- (. a b c d) is a
|
||
;;; path and (.b a c d) is a call, and adding a field named like a
|
||
;;; method cannot quietly turn calls into reads.
|
||
;;;
|
||
;;; (.length v) -> (vec2ːlength (& v))
|
||
;;; (.length p) -> (vec2ːlength p)
|
||
;;; (.sum-of p) -> (vec2ːsum_of (* p))
|
||
;;;
|
||
;;; Which of those is written is decided by the receiver's type against
|
||
;;; the method's own, so the caller never has to match them up.
|
||
(define (method-head? head)
|
||
(and (symbol? head)
|
||
(let ((spelling (symbol->string head)))
|
||
(and (> (string-length spelling) 1)
|
||
(char=? #\. (string-ref spelling 0))))))
|
||
|
||
(define (method-head-name head)
|
||
(string->symbol (substring (symbol->string head) 1)))
|
||
|
||
(define (walk-method-call form env)
|
||
(let ((name (method-head-name (car form))))
|
||
(unless (pair? (cdr form))
|
||
(sex-error form "a method call needs a receiver" form))
|
||
(let* ((receiver (second form))
|
||
(written (expression-type receiver env))
|
||
(target (pointer-target written))
|
||
(key (ops-key (or target written))))
|
||
(unless key
|
||
(sex-error form "receiver of this has no type to dispatch on" name))
|
||
(let ((method (get-method key name)))
|
||
(unless method
|
||
(sex-error form "no such method on" key name))
|
||
(copy-form-source!
|
||
form
|
||
`(,method
|
||
,(method-receiver method (or target written) (and target #t)
|
||
(walk-operand receiver env) form)
|
||
,@(walk-operands form (cddr form) env)))))))
|
||
|
||
;;; A method taking (* Self) wants an address and one taking Self wants
|
||
;;; a value; the receiver is one or the other, so one of the two gets
|
||
;;; `&' or `*' put in front of it.
|
||
;;;
|
||
;;; OBJECT is what the receiver holds or points at: a `(const v)' handed
|
||
;;; to a method taking (* v) would be quietly stripped of its const.
|
||
(define (method-receiver method object pointer? receiver form)
|
||
(let* ((self (method-self-type method))
|
||
(wants-pointer? (and (pair? self) (eq? '* (car self)))))
|
||
(when (and wants-pointer?
|
||
(const-type? object)
|
||
(not (const-type? (pointer-target self))))
|
||
(sex-error form "method may change its receiver, and this one is const"
|
||
method))
|
||
(cond ((eq? wants-pointer? pointer?) receiver)
|
||
((not wants-pointer?) `(* ,receiver))
|
||
;; `&(f())' is not C, and the method cannot be given a
|
||
;; temporary from inside an expression
|
||
((not (lvalue? receiver))
|
||
(sex-error form "receiver is not an lvalue; bind it to a var first"
|
||
method))
|
||
(else `(& ,receiver)))))
|
||
|
||
;;; `(. p x)' is `p->x' when p is a pointer and `p.x' when it is not:
|
||
;;; the receiver's type says which, so a path reads the same however
|
||
;;; what it starts from is held. One step at a time, since only the
|
||
;;; type in hand can answer for the next field:
|
||
;;;
|
||
;;; (. l a x) l : (struct line), l.a : (* struct point) -> l.a->x
|
||
;;;
|
||
;;; A type we cannot work out is read as a value, which is what the
|
||
;;; path would have meant before any of this.
|
||
(define (walk-member-path form env)
|
||
(let ((base (second form)))
|
||
(let step ((expr (walk-operand base env))
|
||
(type (expression-type base env))
|
||
(fields (cddr form))
|
||
(told? #f))
|
||
(if (null? fields)
|
||
(copy-form-source! form expr)
|
||
(let ((target (pointer-target type)))
|
||
(unless (or type told?)
|
||
(sex-warning form "cannot type this; `.' reads it as a value"
|
||
base))
|
||
(step (list (if target '%-> 'dot-access) expr (car fields))
|
||
(field-type (or target type) (car fields))
|
||
(cdr fields)
|
||
(or told? (not type))))))))
|
||
|
||
(define (lvalue? expr)
|
||
(cond ((symbol? expr) #t)
|
||
((vector? expr) #t) ; a compound literal is one
|
||
((not (pair? expr)) #f)
|
||
(else (case (car expr)
|
||
((dot-access %-> ¤) #t)
|
||
((*) (= 2 (length expr)))
|
||
(else #f)))))
|
||
|
||
(define (method-self-type method)
|
||
(let ((signature (get-name-type method)))
|
||
(and (pair? signature)
|
||
(eq? 'fn (car signature))
|
||
(pair? (cdr signature))
|
||
(pair? (second signature))
|
||
(unwrap-type (car (second signature))))))
|
||
|
||
(define (const-type? 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
|
||
;;; what can be reached from one by subscripting, dereferencing and
|
||
;;; member access.
|
||
|
||
;;; The type of an expression as a surface type, or #f when nothing
|
||
;;; here can say. Every form it visits is recorded in `form-type', so
|
||
;;; asking once types the whole subtree.
|
||
;;;
|
||
;;; 42 -> int (. p x) -> that field's type
|
||
;;; "hi" -> (* const char) (& p) -> (* (struct point))
|
||
;;; (area 3 4) -> what `area' returns
|
||
(define (expression-type expr env)
|
||
(set-form-type! expr (compute-expression-type expr env)))
|
||
|
||
(define (compute-expression-type expr env)
|
||
(cond
|
||
((and (number? expr) (exact? expr)) 'int)
|
||
((number? expr) 'double)
|
||
((string? expr) '(* const char))
|
||
((char? expr) 'char)
|
||
((memq expr '(true false)) 'bool)
|
||
;; `#(T : ...)' carries its own type; a bare `#(...)' has none and
|
||
;; takes one from whatever it is being written into
|
||
((vector? expr)
|
||
(let ((parts (list-split (vector->list expr) ':)))
|
||
(and (pair? (cdr parts))
|
||
(let ((written (car parts)))
|
||
(if (= 1 (length written)) (car written) written)))))
|
||
((symbol? expr) (or (lookup-name env expr) (get-name-type expr)))
|
||
;; the walk expands `(the a)' before it gets there, so its type is
|
||
;; that of what it expands to:
|
||
;;
|
||
;; (.len (the a)) (match (the s) ...) (. (the a) x)
|
||
((macro? expr)
|
||
(let ((expansion (expand-call expr env)))
|
||
(and (pair? expansion) (null? (cdr expansion))
|
||
(expression-type (car expansion) env))))
|
||
((not (and (list? expr) (pair? expr))) #f)
|
||
;; (shape/circle 1.0) -> shape
|
||
((and (symbol? (car expr)) (get-constructor (car expr))) => car)
|
||
;; a call of no arguments is still a call
|
||
((< (length expr) 2)
|
||
(and (symbol? (car expr)) (get-return-type (car expr))))
|
||
(else
|
||
(case (car expr)
|
||
;; (¤ pts 1), pts : (¤ struct point 2) -> (struct point)
|
||
;; (¤ p 1), p : (* int) -> int
|
||
((¤) (let ((base (expression-type (second expr) env)))
|
||
(or (array-element-type base) (pointer-target base))))
|
||
;; unary `&' takes an address; with two operands it is bitwise and
|
||
((&) (if (= 2 (length expr))
|
||
(let ((target (expression-type (second expr) env)))
|
||
(and target `(* ,target)))
|
||
(arithmetic-type expr env)))
|
||
;; unary `*' is a dereference; with two operands it is a product
|
||
((*) (if (= 2 (length expr))
|
||
(pointer-target (expression-type (second expr) env))
|
||
(arithmetic-type expr env)))
|
||
((dot-access) (member-path-type (expression-type (second expr) env)
|
||
(cddr expr)))
|
||
((%->) (member-path-type (pointer-target (expression-type (second expr) env))
|
||
(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)
|
||
((+ - / %) (arithmetic-type expr env))
|
||
;; the bitwise operators join like the arithmetic ones
|
||
((^ |\||) (arithmetic-type expr env))
|
||
;; a shift is the promoted left operand, not a join:
|
||
;; (<< l b), l : long -> long; (>> c b), c : char -> int
|
||
((<< >>) (promoted-type (expression-type (second expr) env)))
|
||
;; ...and an increment is the operand unpromoted:
|
||
;; (++ 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
|
||
(else
|
||
(cond
|
||
((method-head? (car expr)) (method-call-type expr env))
|
||
((receiver-closure-type (car expr) env) => third)
|
||
(else (and (symbol? (car expr)) (get-return-type (car expr))))))))))
|
||
|
||
;;; (.length-sq (.sub a b)) types the inner call to find the outer
|
||
;;; one's receiver, so a method call has to answer like any other
|
||
(define (method-call-type expr env)
|
||
(and (pair? (cdr expr))
|
||
(let* ((written (expression-type (second expr) env))
|
||
(target (pointer-target written))
|
||
(key (ops-key (or target written))))
|
||
(and key
|
||
(let ((method (get-method key (method-head-name (car expr)))))
|
||
(and method (get-return-type method)))))))
|
||
|
||
;;; C's usual arithmetic conversions, far enough to answer `_':
|
||
;;;
|
||
;;; (+ i d) i int, d double -> double
|
||
;;; (+ i l) l long -> long
|
||
;;; (+ g d) g float -> double
|
||
;;; (+ (& p) 1) -> (* (struct point))
|
||
;;;
|
||
;;; `unsigned int' against `int' answers `int', where C says otherwise.
|
||
(define (arithmetic-type expr env)
|
||
(fold (lambda (operand joined)
|
||
(arith-join joined (expression-type operand env)))
|
||
#f
|
||
(cdr expr)))
|
||
|
||
(define (arith-join left right)
|
||
(cond
|
||
((not left) right)
|
||
((not right) left)
|
||
(else
|
||
(let ((l (underlying (parse-type left)))
|
||
(r (underlying (parse-type right))))
|
||
(cond
|
||
((or (ptr-type? l) (array-type? l)) (decayed left l))
|
||
((or (ptr-type? r) (array-type? r)) (decayed right r))
|
||
;; one type on both sides needs no ranking:
|
||
;; (+ n n), n : size-t -> size-t
|
||
((and (prim-type? l) (prim-type? r) (equal? (prim-name l) (prim-name r)))
|
||
(promoted left l))
|
||
((or (unrankable? l) (unrankable? r)) '?)
|
||
((< (conversion-rank l) (conversion-rank r)) (promoted right r))
|
||
((> (conversion-rank l) (conversion-rank r)) (promoted left l))
|
||
;; (+ i u) and (+ u i) are both unsigned int
|
||
((unsigned-type? r) (promoted right r))
|
||
(else (promoted left l)))))))
|
||
|
||
;;; `size-t', `GLuint': no declaration parsed, so no rank to compare.
|
||
;;;
|
||
;;; (var m _ (+ 1 n)) n : size-t -> type of this is unknown
|
||
;;; (var m size-t (+ 1 n)) -> size_t m = 1 + n;
|
||
(define (unrankable? type)
|
||
(and (prim-type? type) (not (c-primitive? type))))
|
||
|
||
(define (unsigned-type? type)
|
||
(and (prim-type? type) (memq 'unsigned (prim-name type)) #t))
|
||
|
||
;;; Narrower than `int' promotes to one:
|
||
;;;
|
||
;;; (+ c c) c : char 100 -> int 200, not char -56
|
||
;;; (+ h h) h : short 30000 -> int 60000, not short -5536
|
||
;;; (+ u u) u : unsigned -> unsigned -- `unsigned' is unsigned int
|
||
;;; An array operand is a pointer to its first element:
|
||
;;;
|
||
;;; (var p _ (+ a 1)) a : (¤ int 4) -> int * p = a + 1;
|
||
;;; not int p[4] = a + 1;
|
||
(define (decayed written type)
|
||
(if (array-type? type) (unparse-type (decay type)) written))
|
||
|
||
(define (promoted-type written)
|
||
(and written (promoted written (underlying (parse-type written)))))
|
||
|
||
(define (promoted written type)
|
||
(if (and (prim-type? type)
|
||
(any (lambda (word) (memq word '(char short bool _Bool)))
|
||
(prim-name type)))
|
||
'int
|
||
written))
|
||
|
||
;;; `char' and `short' promote to `int', so the ranks start there
|
||
(define (conversion-rank type)
|
||
(let ((words (and (prim-type? type) (prim-name type))))
|
||
(cond
|
||
((not words) 1)
|
||
((memq 'double words) (if (memq 'long words) 7 6))
|
||
((memq 'float words) 5)
|
||
((memq 'long words) (if (= 2 (count (lambda (w) (eq? w 'long)) words)) 4 3))
|
||
(else 1))))
|
||
|
||
|
||
;;; `(* const char)' is flat: everything after the `*' is the target.
|
||
;;; `(& x)' builds the nested `(* (struct point))' and `unparse-type'
|
||
;;; writes the flat `(* struct point)', so both spellings turn up.
|
||
(define (pointer-target type)
|
||
(and (list? type)
|
||
(>= (length type) 2)
|
||
(eq? '* (car type))
|
||
(unwrap-type (cdr type))))
|
||
|
||
;;; A path looks through a pointer wherever it meets one, the way the
|
||
;;; access itself does: `l.a->x' and `l.b.x' are both (. l a x) and
|
||
;;; both answer with x's type
|
||
(define (member-path-type type fields)
|
||
(if (null? fields)
|
||
type
|
||
(member-path-type (field-type (or (pointer-target type) type)
|
||
(car fields))
|
||
(cdr fields))))
|
||
|
||
(define (field-type type field)
|
||
(let* ((fields (type-fields type))
|
||
(entry (and fields (assq field fields))))
|
||
(and entry (second entry))))
|
||
|
||
;;; `(struct point)' names its fields in the type database. A sum's
|
||
;;; payload writes its union out in place -- `(union ((circle (struct
|
||
;;; shapeːcircle)) ...))' -- and carries them with it, so there is
|
||
;;; nothing to look up
|
||
(define (type-fields type)
|
||
(cond ((and (list? type)
|
||
(= 2 (length type))
|
||
(memq (car type) '(struct union))
|
||
(list? (second type)))
|
||
(second type))
|
||
;; `ops-key' is already the "name of the aggregate" question,
|
||
;; const and all: (* const expr) derefs to (const expr), which
|
||
;; has the fields `expr' has
|
||
((ops-key type) => get-fields)
|
||
(else #f)))
|
||
|
||
(define (make-lambda-name enclosing-fn-name counter)
|
||
(string->symbol
|
||
(fmt #f "λ" counter "_" enclosing-fn-name)))
|
||
|
||
(define (lift-lambda name form)
|
||
(match form
|
||
(('lambda arglist ret-type . body)
|
||
(process-fn (copy-form-source! form `(fn ,name ,arglist ,ret-type ,@body))
|
||
(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)
|
||
`(fn (((* void)) ,@(second type)) ,(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))
|
||
(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))
|
||
(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))))))
|
||
(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)))
|
||
(unless (symbol? name)
|
||
(sex-error form "a closure capture needs a name" 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)
|
||
(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 ,(map (lambda (p) (list (second p))) 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 ,caps)))
|
||
|
||
(list
|
||
`(fn ,code ((ƛe (* void)) ,@arglist) ,ret-type
|
||
,@(if (null? caps)
|
||
(list)
|
||
`((var ƛcaptures (* (struct ,record)) ƛe)
|
||
,@(map (lambda (cap)
|
||
`(var ,(first cap) ,(second cap)
|
||
(%-> ƛcaptures ,(first cap))))
|
||
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 (lambda (cap)
|
||
`(= (%-> ƛcaptures ,(first cap)) ,(first cap)))
|
||
caps)))
|
||
(return ƛc))))))))
|
||
(else (sex-error form "malformed closure" form))))
|
||
|
||
;;; 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))))
|
||
|
||
;;; (sum shape ((circle ((r float))) (rect ((w float) (h float)))))
|
||
;;; is the tag enum, a payload struct per variant that has fields, the
|
||
;;; record holding both, and one constructor per variant:
|
||
;;;
|
||
;;; (var s shape (shape/circle 1.0))
|
||
;;;
|
||
;;; The payload structs are plain structs rather than records on
|
||
;;; purpose: a record would typedef shapeːcircle into the ordinary
|
||
;;; namespace, where the constructor of that name already lives. As a
|
||
;;; tag it shares nothing.
|
||
(define (process-sum form acc)
|
||
(let* ((core (if (eq? (car form) 'pub) (cdr form) form))
|
||
(name (and (pair? (cdr core)) (cadr core)))
|
||
(declared (and (pair? (cddr core)) (caddr core))))
|
||
(unless (and (symbol? name) (list? declared) (pair? declared))
|
||
(sex-error form "sum needs a name and a list of variants" form))
|
||
(let ((variants (map (lambda (v) (parse-variant form v)) declared)))
|
||
(for-each (lambda (v)
|
||
(for-each (lambda (field) (check-variant-field form name field))
|
||
(cdr v)))
|
||
variants)
|
||
(let* ((names (map car variants))
|
||
(twice (find (lambda (v) (> (count (cut eq? <> v) names) 1)) names)))
|
||
(when twice
|
||
(sex-error form "variant is declared twice" twice)))
|
||
(when (get-sum name)
|
||
(sex-error form "sum is already defined" name))
|
||
(add-sum! name variants)
|
||
(for-each (lambda (v) (add-constructor! (qualify-op name (car v)) name (car v)))
|
||
variants)
|
||
(fold match-sex-form acc
|
||
(map (lambda (f) (copy-form-source! form f))
|
||
(sum-forms name variants))))))
|
||
|
||
(define (parse-variant form v)
|
||
(unless (and (list? v) (= 2 (length v)) (symbol? (car v)) (list? (cadr v)))
|
||
(sex-error form "a variant is (name (fields ...))" v))
|
||
(cons (car v) (normalize-fields (cadr v))))
|
||
|
||
;;; (sum expr ((neg ((e expr))))) has no size; (neg ((e (* expr)))) does.
|
||
;;; An array field is spelled out element by element wherever it is
|
||
;;; copied, so its length has to be one sexc can count.
|
||
(define (check-variant-field form name field)
|
||
(let ((type (second field)))
|
||
(when (holds-by-value? type name)
|
||
(sex-error form "a sum holds itself through a pointer" (first field)))
|
||
(when (and (array-form? type) (not (array-length type)))
|
||
(sex-error form "array field needs a length written as a number"
|
||
(first field)))))
|
||
|
||
(define (holds-by-value? type name)
|
||
(cond ((eq? type name) #t)
|
||
((not (pair? type)) #f)
|
||
((memq (car type) '(struct const volatile))
|
||
(and (pair? (cdr type)) (holds-by-value? (cadr type) name)))
|
||
((array-form? type) (holds-by-value? (array-element-type type) name))
|
||
(else #f)))
|
||
|
||
(define (sum-forms name variants)
|
||
(let ((carried (filter (lambda (v) (pair? (cdr v))) variants)))
|
||
`(;; forward, so a variant may hold a pointer back to the sum
|
||
(typedef ,name (struct ,name))
|
||
(enum ,(sum-tag name)
|
||
,(map (lambda (v) (sum-tag-constant name (car v))) variants))
|
||
,@(map (lambda (v) `(struct ,(qualify-op name (car v)) ,(cdr v)))
|
||
carried)
|
||
(struct ,name
|
||
((tag (enum ,(sum-tag name)))
|
||
,@(if (null? carried)
|
||
(list)
|
||
`((u (union ,(map (lambda (v)
|
||
`(,(car v)
|
||
(struct ,(qualify-op name (car v)))))
|
||
carried))))))))))
|
||
|
||
;;; #(shape : .tag shapeǂcircle .u #(.circle #((struct shapeːcircle) : 1.0)))
|
||
(define (sum-literal name tag values)
|
||
(list->vector
|
||
(append (list name ': (dotted 'tag) (sum-tag-constant name tag))
|
||
(if (null? values)
|
||
(list)
|
||
(list (dotted 'u)
|
||
(vector (dotted tag)
|
||
(list->vector
|
||
(append (list (list 'struct (qualify-op name tag)) ':)
|
||
values))))))))
|
||
|
||
(define (dotted name)
|
||
(string->symbol (string-append "." (symbol->string name))))
|
||
|
||
;;; shape -> enum shapeǂ, circle -> shapeǂcircle. Not shapeːtag: that
|
||
;;; is where a variant named `tag' keeps its payload struct, and an enum
|
||
;;; and a struct share C's tag namespace.
|
||
(define (sum-tag name)
|
||
(string->symbol (string-append (symbol->string name) "ǂ")))
|
||
|
||
(define (sum-tag-constant name variant)
|
||
(string->symbol (string-append (symbol->string (sum-tag name))
|
||
(symbol->string variant))))
|
||
|
||
;;; (record point ((x int) (y int))) is a struct that also names
|
||
;;; itself, so `point' alone stands where `(struct point)' had to:
|
||
;;; (var p point ...), (* const point), (sizeof point).
|
||
;;;
|
||
;;; struct, union and enum keep C's meaning, for a type that comes from
|
||
;;; a header or is laid out to match one.
|
||
(define (process-record form acc)
|
||
(let* ((core (if (eq? (car form) 'pub) (cdr form) form))
|
||
(name (and (pair? (cdr core)) (cadr core))))
|
||
(unless (symbol? name)
|
||
(sex-error form "record needs a name" form))
|
||
(add-typedef name `(typedef ,name (struct ,name)))
|
||
(cons (copy-form-source! form `(typedef (struct ,name) ,name))
|
||
(process-struct
|
||
(copy-form-source! form
|
||
(if (eq? (car form) 'pub)
|
||
`(pub struct ,@(cdr core))
|
||
`(struct ,@(cdr core))))
|
||
acc))))
|
||
|
||
(define (register-aggregate! form)
|
||
(let* ((f (if (eq? (car form) 'pub) (cdr form) form))
|
||
(name (and (pair? (cdr f)) (symbol? (cadr f)) (cadr f))))
|
||
;; An anonymous aggregate has a field list where the name would be,
|
||
;; and nothing can refer to it by name anyway
|
||
(when name
|
||
(case (car f)
|
||
((struct) (add-struct name form))
|
||
((union) (add-union name form))
|
||
((enum) (add-enum name form))))))
|
||
|
||
;;; No function around a toplevel form, so no scope chain: what a
|
||
;;; global's initializer names comes from `get-name-type' alone.
|
||
;;; What a global's initializer is walked in: no names but its own,
|
||
;;; and anything it lifts is named after the global
|
||
(define (make-toplevel-env name)
|
||
(let ((env (make-hash-table)))
|
||
(set! (hash-table-ref env :fn-name) name)
|
||
(set! (hash-table-ref env :lambda-counter) 0)
|
||
(set! (hash-table-ref env :lambda-aux-code) (list))
|
||
(set! (hash-table-ref env :scopes) (list))
|
||
env))
|
||
|
||
;;; The writer spells neither `closure' nor `_', and an initializer is
|
||
;;; an expression like any other:
|
||
;;;
|
||
;;; (var n _ 1) -> int n = 1
|
||
;;; (var o v #(v : (.get a))) -> v o = (v){vːget(&a)}
|
||
(define (process-global-var sex-var acc)
|
||
(let* ((resolved (resolve-closure-types sex-var))
|
||
(qualifier (and (memq (car resolved) '(pub extern)) (car resolved)))
|
||
(core (if qualifier (cdr resolved) resolved))
|
||
(env (make-toplevel-env (and (pair? (cdr core)) (second core))))
|
||
;; `(extern var n int)' has no initializer to work a `_' out
|
||
;; from
|
||
(core (if (eq? 'extern qualifier)
|
||
core
|
||
(resolve-wildcard
|
||
(copy-form-source!
|
||
core
|
||
(if (> (length core) 3)
|
||
(append (take core 3)
|
||
(walk-operands core (drop core 3) env))
|
||
core))
|
||
env)))
|
||
(form (if qualifier
|
||
(copy-form-source! resolved (cons qualifier core))
|
||
core)))
|
||
(when (and (pair? (cdr core)) (pair? (cddr core)) (symbol? (second core)))
|
||
(add-name-type! (second core) (third core)))
|
||
(cons form (append (hash-table-ref env :lambda-aux-code) acc))))
|
||
|
||
;;; Utils
|
||
(define (non-empty-list? form)
|
||
(and (list? form)
|
||
(not (null? form))))
|
||
|
||
(define (sex-fn? form)
|
||
"The `form` must be toplevel.
|
||
Returns #f if the form is not a function, returns the form otherwise"
|
||
(match form
|
||
((or ('fn . _)
|
||
('pub 'fn . _)
|
||
('extern 'fn . _)) form)
|
||
(else #f)))
|
||
|
||
(define (sex-fn-public? fn-form)
|
||
(eq? (first fn-form) 'pub))
|
||
|
||
(define (sex-fn-name fn-form)
|
||
(assert (sex-fn? fn-form)
|
||
(fmt #f "Form " fn-form " is not a function"))
|
||
(second (fn-core fn-form)))
|
||
|
||
(define (sex-fn-arglist fn-form)
|
||
(assert (sex-fn? fn-form)
|
||
(fmt #f "Form " fn-form " is not a function"))
|
||
(third (fn-core fn-form)))
|
||
|
||
(define (sex-fn-return-type fn-form)
|
||
(assert (sex-fn? fn-form)
|
||
(fmt #f "Form " fn-form " is not a function"))
|
||
(fourth (fn-core fn-form)))
|
||
|
||
(define (sex-fn-prototype fn-form)
|
||
"Returns all except body"
|
||
(assert (sex-fn? fn-form)
|
||
(fmt #f "Form " fn-form " is not a function"))
|
||
(take fn-form (fn-header-length fn-form)))
|
||
|
||
(define (sex-fn-body fn-form)
|
||
(assert (sex-fn? fn-form)
|
||
(fmt #f "Form " fn-form " is not a function"))
|
||
(drop fn-form (fn-header-length fn-form)))
|