;;; Sex semantic engine (import scheme (only (scheme base) make-parameter) (chicken base) (chicken condition) (chicken keyword) (chicken string) (chicken module) fmt infer sex-macros sex-modules types matchable ; pattern matching reader ; number-literal srfi-1 ; list routines srfi-69 ; hash tables utils ) (export/rename (process semen-process)) ;;; 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!) (set! +called-as-functions+ (make-hash-table)) (process-rec raw-sex-forms (list))) ;;; The first call of each name compiled as a function's, so that a macro ;;; of that name defined after it is told of rather than going unused ;;; there without a word (define +called-as-functions+ (make-hash-table)) (define (check-not-called-before form name) (let ((call (hash-table-ref/default +called-as-functions+ name #f))) (when call (sex-error form "a macro defined after a call to it, which is a function's" name (string-append "called at " (form-file call) ":" (number->string (form-line call))))))) (define (process-one forms acc) (if (macro? (car forms)) (process-rec (macroexpand (car forms) (cdr forms)) acc) (let* ((processed (match-sex-form (car forms) acc)) (new (take-until processed acc))) (process-rec (cdr forms) (append new acc))))) ;;; One bad toplevel form is one diagnostic. The rest of the unit is ;;; still worth indexing. A compile that is not collecting still stops ;;; at the first error, as it always has. (define (process-rec forms acc) (cond ((null? forms) (reverse acc)) ((sex-diagnostics) (handle-exceptions exn (begin (record-exception! (car forms) exn) (process-rec (cdr forms) acc)) (process-one forms acc))) (else (process-one forms 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)) (spliced 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)))) ;;; ($ a ($ b c)) is a, b and c, so a macro may build its splice out of ;;; others' (define (spliced form) (append-map (lambda (f) (if (splice-form? f) (spliced f) (list f))) (cdr form))) (define (match-sex-form sex-form acc) (match sex-form ((or ('fn . _) ('pub 'fn . _) ('extern 'fn . _)) (process-fn 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: a module may export what its interface needs ((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 . _) ('pub 'import . _)) (process-imports (get-modules-public-forms sex-form) acc)) ((or ('defmacro . rest) ('pub 'defmacro . rest)) (when (and (pair? rest) (pair? (car rest))) (check-not-called-before sex-form (caar 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 ) 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) (record-symbol! 'typedef new-type form target #f #f) (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 'sum)) (? symbol? name) (? string? doc) . rest) (values doc (copy-form-source! form `(pub ,kind ,name ,@rest)))) (((and kind (or 'struct 'union 'enum 'sum)) (? 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)))) ;; a `_' is solved from what a variable is set to, and a signature ;; has nothing it is set to (when (mentions? (cons (sex-fn-return-type expanded) (arglist-types (sex-fn-arglist expanded))) '_) (sex-error sex-fn-raw "a function's types are written out; `_' is a variable's" (sex-fn-name expanded))) (add-name-type! (sex-fn-name expanded) (fn-type-of expanded)) (record-symbol! 'fn (sex-fn-name expanded) sex-fn-raw `(fn ,(sex-fn-name expanded) ,(sex-fn-arglist expanded) ,(sex-fn-return-type expanded)) doc #f) (let* ((env (make-fn-env expanded)) ;; the parameters are the body's outermost scope (header (take expanded boundary)) (body (parameterize ((sex-scope-range (form-line-range sex-fn-raw)) (operand-position? #f)) (for-each (lambda (param) (when (named-arg? param) (record-symbol! 'var (first param) sex-fn-raw (named-arg-type param) #f #t))) (sex-fn-arglist expanded)) (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)))))) ;;; (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. ;;; ;;; Every method is registered before any body is walked, so one may ;;; call another written below it; that one is then declared ahead of ;;; the first body, since C wants it declared before the call. (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)) (let* ((methods (map (lambda (m) (register-op type m)) (cddr form))) (fns (remove comment-form? methods)) ;; the signatures too, which a call's receiver is fitted to (protos (map (lambda (m) (process-fn (sex-fn-prototype m) (list))) fns)) (bodies (map (lambda (m) (if (comment-form? m) (list m) (process-fn m (list)))) methods)) (early (filter-map (lambda (m proto) (and (called-before? m methods bodies) proto)) fns protos))) (append (concatenate (reverse bodies)) (fold append acc early))))) ;;; The method's fn form, renamed to vec2/length, once it is registered ;;; under `length'; a comment is passed along (define (register-op type form) (if (comment-form? form) form (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)) (renamed (rename-fn form qualified))) (add-method! type name qualified) renamed))))) ;;; Does a body written above METHOD call it? (define (called-before? method methods bodies) (let ((name (sex-fn-name method))) (let loop ((ms methods) (bs bodies)) (and (not (eq? (car ms) method)) (or (mentions? (car bs) name) (loop (cdr ms) (cdr bs))))))) ;;; (pub fn name args ret ...) -> (pub fn name args ret) (define (sex-fn-prototype form) (let ((header (strip-fn-header-comments form))) (copy-form-source! form (take header (fn-header-length header))))) (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)) (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 ;;; 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) ...) ;;; (var m _ (+ v 1)) ; double, not char ;;; ;;; A `case' body gets one too, being written as a block. An `if' arm ;;; gets none: it 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 form body) (let ((enclosing (hash-table-ref env :scopes)) (range (or (form-line-range form) (sex-scope-range)))) (set! (hash-table-ref env :scopes) (cons (make-hash-table) enclosing)) (let ((walked (parameterize ((sex-scope-range range)) (body)))) (set! (hash-table-ref env :scopes) enclosing) walked))) ;;; The body walk ;;; ;;; 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)' ;;; 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) { ... ;;; ;;; and in a control form's test, which C reads as an expression too: ;;; ;;; (if (match s ...) ...) -> if (switch (s.tag) { ... (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-initializer 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 (check-shape form) (case (car form) ((do default) (parameterize ((operand-position? #f)) (with-scope env form (lambda () (walk-parts form env))))) ((for while if switch case case/fallthrough) (with-scope env form (lambda () (walk-control form env)))) ((lambda) (let ((name (aux-name! env make-lambda-name))) (add-aux-code! env (lift-lambda name form)) name)) ((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 fp (fn ((c int)) int) ...) ; int (*fp)(int) (let* ((prefix (if (>= (length form) 3) (append (take form 2) (list (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))) (when (>= (length walked) 3) (declare-name! env (second walked) (third walked)) (record-symbol! 'var (second walked) walked (third walked) #f #t)) walked)) ((return) (let ((walked (copy-form-source! form (walk-operands form form env)))) (if (>= (length walked) 2) (copy-form-source! walked (cons 'return (cdr 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)) ;; [m 1 2] is [[m 1] 2], m[1][2] ((¤) (if (> (length form) 3) (walk-statement (copy-form-source! form (list '¤ (copy-form-source! form (drop-right form 1)) (last form))) env) (walk-parts form env))) ((sizeof) (if (and (= 2 (length form)) (written-type? (second form) env)) (copy-form-source! form `(sizeof (%type ,(expand-type (second form) env)))) (walk-parts form env))) (else (cond ((method-head? (car form)) (walk-method-call form env)) ((get-constructor (car form)) => (lambda (constructor) (walk-construction form constructor 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)) (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 ;;; procedure of the writer's (define +shapes+ '((goto 1 1 "(goto label)") (: 1 1 "(: label)") (var 2 3 "(var name type value)") (cast 2 2 "(cast value type)") (while 1 #f "(while test body ...)") (if 2 #f "(if test then else)") (return 0 1 "(return value)") (break 0 0 "(break)") (continue 0 0 "(continue)") (sizeof 1 1 "(sizeof value)"))) (define (check-shape form) (let ((shape (assq (car form) +shapes+)) (given (count (lambda (part) (not (comment-form? part))) (cdr form)))) (when (and shape (not (and (>= given (second shape)) (or (not (third shape)) (<= given (third shape)))))) (sex-error form (string-append "malformed " (symbol->string (car form)) ": write " (fourth shape)))))) ;;; (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)) arg (let ((given (expression-type arg env))) (cond ((brace-initializer? arg) (let ((held (array-length type))) (when (and held (not (= held (length (remove comment-form? (vector->list arg)))))) (sex-error form "array is not as long as its field" (first field)))) 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 (array-bound 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) (expression-type queried env)))) (macroexpand form (list)))) ;;; #(struct point : (. p x) 2) -- the values are expressions, and the ;;; words before a `:' a type that is left as written (define (walk-initializer form env) (let-values (((prefix rest) (break (lambda (e) (eq? e ':)) (vector->list form)))) (let ((walk (lambda (es) (map (lambda (e) (walk-operand e env)) es)))) (list->vector (if (null? rest) (walk prefix) (append prefix (list ':) (walk (cdr rest)))))))) ;;; Is the operand of `sizeof' a type? `(* x)' and `(¤ x i)' are ;;; expressions when x is: a name in scope, or a list that is not ;;; itself a type. A name nothing declared is one only C knows of, and ;;; there that is a type: ;;; ;;; (* char) (* const char) (* size-t) (unsigned int) types ;;; (* p) (* (g)) (¤ xs 0) (¤ m 1 2) expressions (define (written-type? form env) (match form ((or ('* operand) ('¤ operand _ . _)) (if (symbol? operand) (not (or (lookup-name env operand) (get-name-type operand))) (written-type? operand env))) (_ (type-head? form)))) ;;; `(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 type) form)))) (vector->list initializer)))) (else (let ((type (expression-type initializer env))) (unless type (sex-error form "cannot infer the type of" (second form))) ;; 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 (if (and (tvar? (resolve declared)) (array-type? (underlying given))) (decay given) given) 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 '_)) ;;; WORD anywhere in FORM, a literal's contents included (define (mentions? form word) (cond ((eq? form word) #t) ((pair? form) (or (mentions? (car form) word) (mentions? (cdr form) word))) ((vector? form) (mentions? (vector->list form) word)) (else #f))) ;;; What a `fn' header gets, a `var' type gets -- macro expansion, 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) (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))) ;;; A control form, its tests walked as values and the rest as ;;; statements -- but an if that is a value has values for branches, ;;; and one for the false case too, or C has none to give it (define (walk-control form env) (let ((slots (count (lambda (part) (not (comment-form? part))) (cdr form))) (valued? (and (eq? (car form) 'if) (operand-position?)))) (when (and valued? (even? slots)) (sex-error form "an if used as a value needs an else")) (let loop ((parts (cdr form)) (i 0) (acc (list (car form)))) (cond ((null? parts) (copy-form-source! form (reverse acc))) ((comment-form? (car parts)) (loop (cdr parts) i (cons (car parts) acc))) (else (let ((walked (parameterize ((operand-position? (or valued? (test-slot? (car form) i slots)))) (walk-body (list (car parts)) env)))) (loop (cdr parts) (+ i 1) (append-reverse walked acc)))))))) ;;; Whether the Ith of a control form's SLOTS is read as a value: an ;;; `if''s tests but not its trailing else, a `for''s header, the ;;; scrutinee of a `while' or a `switch', a `case''s label (define (test-slot? head i slots) (case head ((if) (and (even? i) (< (+ i 1) slots))) ((for) (< i 3)) (else (= i 0)))) ;;; (match s ((circle (r)) ...) ((empty ()) ...)) is an if 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)) (dereferenced (second form) env 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) ;; the scrutinee is read once per binding, so anything that could ;; read differently the second time is read into a local first -- ;; a binder named like a part of it included, since C has a binder ;; in scope from its own initializer on (if (and (simple-path? scrutinee) (not (any (cut mentions? scrutinee <>) (match-binders arms)))) (walk-statement (match-branches name scrutinee variants arms) env) (let ((held (aux-name! env make-match-name))) (walk-statement `(do (var ,held ,type ,scrutinee) ,(match-branches name held variants arms)) env))))) ;;; A pointer to a sum is matched as the sum, read through however many ;;; there are, as `.' reads through them: p : (* * shape) -> (* (* p)) (define (dereferenced expr env form) (if (pointer-target (expression-type expr env)) (dereferenced (copy-form-source! form (list '* expr)) env form) expr)) (define (match-binders arms) (append-map (lambda (arm) (if (eq? (car arm) 'else) '() (delete '_ (second (car arm))))) arms)) (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))))) ;;; Not a switch, which would take a `break' in an arm for its own: ;;; there is none in the source, so the break is the loop's. With no ;;; else the arms cover every variant, so the last needs no test -- and ;;; C, seeing every path end, does not warn of one returning nothing ;;; ;;; (if (== s.tag shapeǂcircle) (do (var r float s.u.circle.r) ...) ;;; (== s.tag shapeǂrect) (do ...) ;;; (do ...)) ; the else, or else empty's arm (define (match-branches name scrutinee variants arms) (let-values (((otherwise named) (partition (lambda (arm) (eq? (car arm) 'else)) arms))) (let* ((body (lambda (arm) (if (eq? (car arm) 'else) `(do ,@(cdr arm)) (let ((variant (match-arm-variant arm))) `(do ,@(match-bindings scrutinee variant (second (car arm)) (variant-fields variants variant)) ,@(cdr arm)))))) (ordered (append named otherwise)) (tested (drop-right ordered 1)) (final (body (last ordered)))) (if (null? tested) final `(if ,@(append-map (lambda (arm) (list `(== (dot-access ,scrutinee tag) ,(sum-tag-constant name (match-arm-variant arm))) (body arm))) tested) ,final))))) ;;; 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)) ;; through a pointer chain, as a path reads through one (let*-values (((receiver written) (through-pointers (walk-operand (second form) env) (expression-type (second form) 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) receiver 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. The warning names what ;;; could not be typed: the base, or the path up to a field of a struct ;;; only C knows -- (. font handle x) warns of (. font handle), not ;;; font. A field a struct declared here lacks is an error. (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*-values (((expr type) (through-pointers expr type)) ((target) (pointer-target type)) ((known) (type-fields (or target type)))) (when (and (pair? known) (not (assq (field-name (car fields)) known))) (sex-error form "no field of this name in" (or target type) (car fields))) (unless (or type told?) (let ((walked (drop-right (cddr form) (length fields)))) (sex-warning form "cannot type this; `.' reads it as a value" (if (null? walked) base `(|.| ,base ,@walked))))) (step (list (if target '%-> 'dot-access) expr (nested-step (car fields))) (step-type (or target type) (car fields)) (cdr fields) (or told? (not type)))))))) ;;; A pointer to a pointer has no fields: EXPR read through every pointer ;;; but the last, so a step writes -> once. pp : (* * pt) -> (* pp), (* pt) (define (through-pointers expr type) (let ((target (pointer-target type))) (if (and target (pointer-target target)) (through-pointers (list '* expr) target) (values expr type)))) ;;; What a path reads fields of: TYPE, or what its pointers lead to (define (pointed-through type) (let ((target (pointer-target type))) (if target (pointed-through target) type))) ;;; A field of a path, indexed or not: xs, [xs 0] -> xs (define (field-name field) (if (and (array-form? field) (pair? (cdr field))) (second field) field)) (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)))) ;;; 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. ;;; ;;; 42 -> int (. p x) -> that field's type ;;; "hi" -> (* const char) (& p) -> (* (struct point)) ;;; (area 3 4) -> what `area' returns ;;; What C makes of a literal: of the types its suffix allows, the ;;; first that holds it, by the widths every host has -- int and long ;;; of 32 bits, long long of 64 -- so it is never narrower than C's own. ;;; ;;; 1 -> int 1u -> (unsigned int) ;;; 4000000000 -> (long long) 10L -> long ;;; 1.5f -> float 0.1L -> (long double) ;;; 0x1.8p3 -> double (define (number-literal-type literal) (let ((n (number-literal-value literal)) (suffix (map char-downcase (string->list (number-literal-suffix literal))))) (cond ((exact? n) (integer-literal-type n suffix)) ((memv #\f suffix) 'float) ((memv #\l suffix) '(long double)) (else 'double)))) (define (integer-literal-type n suffix) (let ((ranks (drop (if (memv #\u suffix) '(((unsigned int) 32) ((unsigned long) 32) ((unsigned long long) 64)) '((int 31) (long 31) ((long long) 63))) (count (cut eqv? #\l <>) suffix)))) (let ((rank (find (lambda (rank) (< (abs n) (expt 2 (second rank)))) ranks))) (and rank (first rank))))) (define (expression-type expr env) (cond ((number-literal? expr) (number-literal-type expr)) ((and (number? expr) (exact? expr)) (integer-literal-type expr '())) ((number? expr) 'double) ((string? expr) '(* const char)) ((char? expr) 'char) ((or (boolean? expr) (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) ;; `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 ((-) (if (and (= 3 (length expr)) (every (lambda (operand) (address? (expression-type operand env))) (cdr expr))) 'ptrdiff-t (arithmetic-type expr env))) ((+ / %) (arithmetic-type expr env)) ;; the bitwise operators join like the arithmetic ones ((^ |\|| bit-and bit-or bit-xor bitwise-and bitwise-ior bitwise-xor) (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))) ;; a value if is the join of its values, as an operator is of its ;; operands -- and nothing when one of them says nothing ((if) (let ((types (map (cut expression-type <> env) (if-values (remove comment-form? (cdr expr)))))) (and (every identity types) (fold (lambda (t joined) (arith-join joined t)) #f types)))) ;; a complement is the operand promoted, as a negation is ((~ bit-not bitwise-not) (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, anything else with what its signature says (else (cond ((method-head? (car expr)) (method-call-type expr env)) ;; a function's name, unless a local hides it ((and (symbol? (car expr)) (not (lookup-name env (car expr))) (get-return-type (car expr))) => identity) ;; a pointer to one: a local, a parameter, a field, a call's result (else (function-return (expression-type (car expr) env))))))))) ;;; (fn ((int)) int) -> int, and through a typedef of one (define (function-return type) (cond ((and (pair? type) (eq? (car type) 'fn) (= 3 (length type))) (third type)) ((and (symbol? type) (get-underlying-type type)) => function-return) (else #f))) ;;; (.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. ;;; One operand is promoted on its own: (- c), c : char -> int (define (arithmetic-type expr env) (if (null? (cddr expr)) (promoted-type (expression-type (second expr) env)) (fold (lambda (operand joined) (arith-join joined (expression-type operand env))) #f (cdr expr)))) ;;; A pointer, or an array that is one as an operand (define (address? written) (and written (let ((type (underlying (parse-type written)))) (or (ptr-type? type) (array-type? type))))) ;;; (if t1 v1 t2 v2 e) -> (v1 v2 e) (define (if-values parts) (if (and (pair? parts) (pair? (cdr parts)) (pair? (cddr parts))) (cons (cadr parts) (if-values (cddr parts))) parts)) (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; ;;; An operator gives a value, which has no qualifiers: (+ k 1) with ;;; k : (const int) is an int, whichever side k is on (define (decayed written type) (if (array-type? type) (unparse-type (decay type)) (value-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 (value-type written))) (define (value-type written) (unparse-type (unqualified (parse-type 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. ;;; (* T) -> T, and so for a typedef of one: (typedef pt-ref (* pt)) (define (pointer-target type) (cond ((and (list? type) (>= (length type) 2) (eq? '* (car type))) (unwrap-type (cdr type))) ((and (symbol? type) (get-underlying-type type)) => pointer-target) (else #f))) ;;; 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 (step-type (pointed-through type) (car fields)) (cdr fields)))) ;;; What a step of a path gives: its field, or for [xs i] an element of ;;; the field xs, one for each index (define (step-type type field) (let ((t (field-type type (field-name field)))) (if (and t (pair? field) (eq? '¤ (car field))) (fold (lambda (index t) (and t (or (array-element-type t) (pointer-target t)))) t (cddr field)) t))) ;;; [grid 1 2] as a step is [[grid 1] 2], as it is anywhere else (define (nested-step field) (if (and (pair? field) (eq? '¤ (car field)) (> (length field) 3)) (list '¤ (nested-step (drop-right field 1)) (last field)) field)) (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))) ;;; A function with no body is a declaration, and nothing would define ;;; one lifted from an empty lambda; an empty block keeps it a definition, ;;; and the writer leaves the block out (define (defining body) (if (every comment-form? body) (append body (list '(do))) body)) (define (lift-lambda name form) (match form (('lambda arglist ret-type . body) (process-fn (copy-form-source! form `(fn ,name ,(named-parameters arglist) ,ret-type ,@(defining body))) (list))) (else (sex-error form "malformed lambda" form)))) ;;; An argument type is written wrapped: `(int)' in `((int) (float))' (define (unwrap-type type) (if (and (list? type) (= 1 (length type))) (car type) type)) ;;; 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)) (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))) (unwrap-type arg)))) arglist (iota (length arglist)))) ;;; 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))) (let ((core (if (eq? (car form) 'pub) (cdr form) form))) (when (and (pair? (cdr core)) (symbol? (cadr core))) (record-symbol! (car core) (cadr core) sex-struct #f doc #f))) (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 written acc) (let-values (((doc form) (extract-aggregate-docstring written))) (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) (record-symbol! 'sum name written `(struct ,name) doc #f) (for-each (lambda (v) (record-symbol! 'fn (qualify-op name (car v)) written `(fn ,(map second (cdr v)) ,name) #f #f)) variants) ;; the docstring goes ahead of everything the sum is made of. ;; The generated structs and typedefs are the compiler's, and ;; the sum itself is already indexed. (parameterize ((sex-index-suppressed? #t)) (fold match-sex-form (if doc (cons (copy-form-source! form (list 'comment doc)) acc) 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)) ;; one with fields is a member of the sum's union, and C takes no ;; member named `int'; one without is held to the same, as one rule (when (memq (car v) +c-keywords+) (sex-error form "a variant cannot be named like a C keyword" (car v))) (cons (car v) (normalize-fields (cadr v)))) ;;; C11's, and the ones , in every unit, makes macros of (define +c-keywords+ '(auto break case char const continue default do double else enum extern float for goto if inline int long register restrict return short signed sizeof static struct switch typedef union unsigned void volatile while _Alignas _Alignof _Atomic _Bool _Complex _Generic _Imaginary _Noreturn _Static_assert _Thread_local bool true false)) ;;; (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))) ;; the typedef first, so a field may point back at the record, and ;; the docstring ahead of both (let-values (((doc struct) (extract-aggregate-docstring (copy-form-source! form (if (eq? (car form) 'pub) `(pub struct ,@(cdr core)) `(struct ,@(cdr core))))))) (process-struct struct (with-docstring doc (copy-form-source! form `(typedef (struct ,name) ,name)) 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 ;; ...and a bodyless one adds nothing to what is known: an importer ;; may be handed a declaration after the definition it declares (when (and name (not (and (null? (cddr f)) (get-tag-info name)))) (case (car f) ((struct) (add-struct name form)) ((union) (add-union name form)) ((enum) (add-enum name form) ;; a constant is its enum's, which `_' reads and whose ops it ;; calls -- where C says int, and converts between them (when (and (pair? (cddr f)) (list? (caddr f))) (for-each (lambda (value) (let ((constant (if (pair? value) (car value) value))) (when (symbol? constant) (add-name-type! constant `(enum ,name)) (record-symbol! 'const constant form `(enum ,name) #f #f)))) (remove comment-form? (caddr f))))))))) ;;; 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 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* ((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 (core (if (eq? 'extern qualifier) core (let ((solved (resolve-wildcard (copy-form-source! core (if (> (length core) 3) (append (take core 3) (walk-operands core (drop core 3) env)) core)) env))) (if (> (length solved) 3) (copy-form-source! solved (append (take solved 3) (map (cut bare-braces <> (third solved)) (drop solved 3)))) solved)))) (form (if qualifier (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)) (record-symbol! 'var (second core) sex-var (third core) #f #f)) (cons form (append (hash-table-ref env :lambda-aux-code) acc)))) ;;; A compound literal is not a constant, though cc lets one pass at file ;;; scope unless asked to be pedantic; where it initializes, its braces ;;; alone say the same. Not where it is an array a pointer is set to: ;;; that is the address of a static object, which is a constant, and its ;;; braces alone would be the pointer's own. TARGET is what FORM ;;; initializes, #f where nothing says. ;;; ;;; (var g t (t/a 1)) -> static t g = {.tag = tǂa, ...} ;;; (var p (* int) #([int 2] : 1 2)) -> static int * p = (int [2]){1, 2} (define (bare-braces form target) (if (not (vector? form)) form (let* ((parts (list-split (vector->list form) ':)) (written (and (pair? (cdr parts)) (unwrap-type (car parts))))) (if (and written (array-form? written) target (pointer-target target)) form (let ((elements (last parts))) (list->vector (map bare-braces elements (element-targets (or written target) elements)))))))) ;;; What each of ELEMENTS, in braces for TYPE, initializes: an element ;;; of an array, the fields of an aggregate in turn, or the one a `.name' ;;; before it names -- and #f where TYPE does not say (define (element-targets type elements) (let ((element (and type (array-form? type) (array-element-type type))) (fields (and type (not (array-form? type)) (type-fields type)))) (let loop ((es elements) (next (or fields (list))) (acc (list))) (cond ((null? es) (reverse acc)) (element (loop (cdr es) next (cons element acc))) ((designator-name (car es)) => (lambda (name) (let ((at (and fields (find-tail (lambda (f) (eq? (car f) name)) fields)))) (if (and at (pair? (cdr es))) (loop (cddr es) (cdr at) (cons (second (car at)) (cons #f acc))) (loop (cdr es) (list) (cons #f acc)))))) (else (loop (cdr es) (if (pair? next) (cdr next) next) (cons (and (pair? next) (second (car next))) acc))))))) ;;; .x -> x, as a designator names a field; #f for anything else (define (designator-name x) (and (symbol? x) (let ((s (symbol->string x))) (and (> (string-length s) 1) (char=? #\. (string-ref s 0)) (string->symbol (substring s 1)))))) ;;; Utils (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-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)))