diff --git a/infer.scm b/infer.scm index f719a03..20cc65e 100644 --- a/infer.scm +++ b/infer.scm @@ -1,8 +1,9 @@ ;;; Type inference, layer 0: the type representation and unification. ;;; -;;; Nothing in the compiler calls this unit yet. It is the ground floor -;;; of the pass described in Type-inference.org -- built and tested on -;;; its own before a single form is routed through it. +;;; semen solves the wildcards of a declared type with it -- `(var n _ +;;; (strlen s))', `(var p (* _) (& x))' -- and asks it what an operand +;;; decays or promotes to. It is the ground floor of the pass described +;;; in Type-inference.org. ;;; ;;; Two representations meet here. *Surface* types are the forms the ;;; rest of the compiler passes around -- `int', `(* const char)', @@ -34,48 +35,18 @@ (export ;; The IR - tvar? - tvar-id - tvar-classes - tvar-rigid? - fresh-tvar - fresh-rigid-tvar - - prim-type? prim-name prim-quals make-prim - ptr-type? ptr-target ptr-quals make-ptr - array-type? array-elt array-size make-array-type - fn-type? fn-ret fn-args fn-variadic? make-fn-type - agg-type? agg-kind agg-name agg-spelling agg-quals make-agg - alias-type? alias-name alias-expansion alias-quals make-alias - unknown-type? the-unknown-type - - resolve + prim-type? prim-name + ptr-type? + array-type? array-elt underlying c-primitive? - type-quals - free-tvars decay ;; The boundary parse-type unparse-type - ;; Constraints - register-class! - add-instance! - entails? - default-tvar! - default-type-variables! - - ;; Unification - unify - - ;; Type schemes - scheme? scheme-vars scheme-constraints scheme-type - make-scheme - generalize - instantiate - substitute) + unify) ;;; --------------------------------------------------------------- ;;; The IR @@ -161,18 +132,12 @@ (%make-unknown) unknown-type?) -(define the-unknown-type (%make-unknown)) - (define tvar-counter 0) (define (fresh-tvar . classes) (set! tvar-counter (+ tvar-counter 1)) (%make-tvar tvar-counter #f (if (null? classes) (list) (car classes)) #f)) -(define (fresh-rigid-tvar . classes) - (set! tvar-counter (+ tvar-counter 1)) - (%make-tvar tvar-counter #f (if (null? classes) (list) (car classes)) #t)) - ;;; Follow a bound variable to what it stands for, compressing the path ;;; on the way out. Every procedure that looks at a type's shape starts ;;; here. @@ -207,16 +172,6 @@ ((fn-type? t) (make-ptr t (list))) (else (resolve type))))) -(define (free-tvars type) - (let collect ((t type) (acc (list))) - (let ((t (resolve t))) - (cond ((tvar? t) (if (memq t acc) acc (cons t acc))) - ((ptr-type? t) (collect (ptr-target t) acc)) - ((array-type? t) (collect (array-elt t) acc)) - ((alias-type? t) (collect (alias-expansion t) acc)) - ((fn-type? t) (fold collect (collect (fn-ret t) acc) (fn-args t))) - (else acc))))) - ;;; --------------------------------------------------------------- ;;; Surface -> IR ;;; --------------------------------------------------------------- @@ -400,49 +355,24 @@ ;;; Constraints ;;; --------------------------------------------------------------- -;;; `(numeric a)' is already a type class, so it is written as one from -;;; the start: one representation, one table, one entailment check. A -;;; trait bound `(ord (struct circle))' is the same shape, discharged -;;; the same way, and reported by the same procedure -- which is the -;;; whole reason to build it this way while there is only one kind of -;;; constraint to build. -;;; -;;; `default' is the type an unresolved constraint falls back to, the -;;; way Haskell defaults `Num a' to Integer. `test' is how the built-in -;;; classes say "every arithmetic type" without enumerating twenty -;;; spellings as instances; a user trait has no test and lives entirely -;;; in the instance table. `strict?' marks a class that must not be -;;; guessed at: static dispatch needs a real instance, so `?' fails it. +;;; `(numeric a)' is a type class: one representation, one table, one +;;; entailment check. `test' is how a class says "every arithmetic +;;; type" without enumerating twenty spellings. (define-record-type - (%make-type-class name default test strict?) + (%make-type-class name test) type-class? (name type-class-name) - (default type-class-default) - (test type-class-test) - (strict? type-class-strict?)) + (test type-class-test)) (define +classes+ (make-hash-table)) -(define +instances+ (make-hash-table)) -(define (register-class! name default test strict?) - (hash-table-set! +classes+ name (%make-type-class name default test strict?))) +(define (register-class! name test) + (hash-table-set! +classes+ name (%make-type-class name test))) (define (get-class name) (or (hash-table-ref/default +classes+ name #f) (error "no such type class" name))) -;;; Instances key on the *resolved* type, so `(impl show for size-t)' -;;; and `(impl show for unsigned long)' collide rather than quietly -;;; coexisting as two instances of one C type. -(define (instance-key type) - (unparse-type (underlying type))) - -(define (add-instance! class-name type) - (hash-table-set! +instances+ (cons class-name (instance-key type)) #t)) - -(define (has-instance? class-name type) - (hash-table-exists? +instances+ (cons class-name (instance-key type)))) - ;;; #t, #f, or 'unknown -- and the third answer is the important one. ;;; A C name we never parsed a declaration for might well be numeric; ;;; saying #f there would reject working programs, and saying #t would @@ -453,10 +383,8 @@ (t (underlying type))) (cond ((tvar? t) 'unknown) - ;; `?' is consistent with every type, but it entails nothing: - ;; there is no instance to select and no name to mangle. - ((unknown-type? t) (if (type-class-strict? cls) #f 'unknown)) - ((has-instance? class-name t) #t) + ;; `?' is consistent with every type, and says nothing of one + ((unknown-type? t) 'unknown) ((type-class-test cls) => (lambda (test) (test t))) (else #f)))) @@ -500,36 +428,10 @@ ((fn-type? t) #t) ; likewise (else (arithmetic-type? t)))) -;;; The built-ins. They are ordinary classes, registered the same way a -;;; trait will be -- that is the point. -(register-class! 'numeric 'int arithmetic-type? #f) -(register-class! 'integral 'int integral-type? #f) -(register-class! 'floating 'double floating-type? #f) -(register-class! 'scalar #f scalar-type? #f) - -;;; A constraint that survives to the end of a function is defaulted: -;;; `(numeric a)' with nothing else known is an `int'. A *strict* -;;; class has no default and no business guessing, so an unresolved one -;;; is an error -- the rule is worth stating while there is only one -;;; kind of constraint to state it about. -(define (default-tvar! v form) - (let ((strict (find (lambda (c) (type-class-strict? (get-class c))) - (tvar-classes v)))) - (cond - (strict (sex-error form "unresolved constraint" (list strict (unparse-type v)))) - ((find (lambda (c) (type-class-default (get-class c))) (tvar-classes v)) - => (lambda (c) - (tvar-ref-set! v (parse-type (type-class-default (get-class c)))) - #t)) - (else #f)))) - -;;; Default every variable still open in TYPE. Returns #t when none is -;;; left unsolved, so a caller can tell "inferred" from "give up and -;;; ask for the type in writing". -(define (default-type-variables! type form) - (fold (lambda (v ok) (and (default-tvar! v form) ok)) - #t - (free-tvars type))) +(register-class! 'numeric arithmetic-type?) +(register-class! 'integral integral-type?) +(register-class! 'floating floating-type?) +(register-class! 'scalar scalar-type?) (define (check-classes classes type form) (for-each @@ -634,57 +536,3 @@ ((fn-type? t) (or (occurs? v (fn-ret t)) (any (lambda (a) (occurs? v a)) (fn-args t)))) (else #f)))) - -;;; --------------------------------------------------------------- -;;; Type schemes -;;; --------------------------------------------------------------- - -;;; Nothing generalizes yet -- every `fn' in Sex carries a written -;;; signature and there is no polymorphism to abstract over. These are -;;; here because they are ten lines on top of unification and because -;;; they are exactly what a `fn' with type parameters needs, and -;;; because a scheme without a constraint list is the wrong shape for -;;; every bounded generic. `(forall vars constraints type)' it is, -;;; from the start. -(define-record-type - (make-scheme vars constraints type) - scheme? - (vars scheme-vars) - (constraints scheme-constraints) - (type scheme-type)) - -;;; Quantify over everything free in TYPE that is not also free in the -;;; environment, carrying each variable's class constraints along as -;;; the scheme's context. -(define (generalize type env-tvars) - (let ((vars (lset-difference eq? (free-tvars type) env-tvars))) - (make-scheme vars - (append-map (lambda (v) - (map (lambda (c) (cons c v)) (tvar-classes v))) - vars) - type))) - -(define (instantiate scheme) - (let ((subst (map (lambda (v) (cons v (fresh-tvar (tvar-classes v)))) - (scheme-vars scheme)))) - (substitute (scheme-type scheme) subst))) - -;;; Structural copy with the variables in SUBST replaced. Copying is -;;; how a generic body must be handled anyway -- `form-type' is keyed -;;; by cons cell, one form one type, so an instantiation gets fresh -;;; cells rather than a second type for the same cell. -(define (substitute type subst) - (let ((t (resolve type))) - (cond - ((tvar? t) (let ((hit (assq t subst))) (if hit (cdr hit) t))) - ((ptr-type? t) (make-ptr (substitute (ptr-target t) subst) (ptr-quals t))) - ((array-type? t) (make-array-type (substitute (array-elt t) subst) - (array-size t))) - ((alias-type? t) (make-alias (alias-name t) - (substitute (alias-expansion t) subst) - (alias-quals t))) - ((fn-type? t) (make-fn-type (substitute (fn-ret t) subst) - (map (lambda (a) (substitute a subst)) - (fn-args t)) - (fn-variadic? t))) - (else t)))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 9da8790..83f21bc 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -564,6 +564,19 @@ "struct p* x = &s")) (test-assert "a wildcard inside an array" (emits? (in-fn "(var t [_ 3] #([int 3] : 1 2 3))") "int t[3]")) + ;; each `_' is its own variable: solving one leaves the rest open + (test-assert "every wildcard in a signature is its own" + (emits? "(fn g ((x int)) char (return 0)) + (fn f () void (var h (fn ((_)) _) g))" + "char (*h)(int) = g")) + (test-assert "and the signature's arity has to match" + (reports? "(fn g ((x int) (y int)) int (return 0)) + (fn f () void (var h (fn ((_)) _) g))" + "type mismatch")) + (test-assert "a typedef answers as itself" + (emits? "(typedef count int) (fn g () count (return 0)) + (fn f () void (var x _ (g)))" + "count x = g()")) ;; a compound literal carries its own type, where a brace ;; initializer has none and takes one from its context (test-assert "a compound literal answers a bare wildcard" diff --git a/tests/infer.scm b/tests/infer.scm index 2d13c64..f41d6c3 100644 --- a/tests/infer.scm +++ b/tests/infer.scm @@ -3,7 +3,7 @@ ;;; Names registered in the type database are prefixed, since the ;;; database is one table shared by every suite in the linked binary. -(import infer types (chicken sort)) +(import infer types) ;;; Parse and print a surface type again. Everything in this suite goes ;;; through this pair, which is deliberate: they are the only thing the @@ -85,23 +85,10 @@ ;; Each _ is its own variable: solving one must not solve the rest. (let ((t (parse-type '(fn ((_)) _)))) - (unify (car (fn-args t)) (parse-type 'int) #f) + (unify t (parse-type '(fn ((int)) _)) #f) (test "one hole at a time" '(fn ((int)) _) (unparse-type t)))) - (test-group "structure" - (test-assert "a pointer is a pointer" (ptr-type? (parse-type '(* char)))) - (test "and knows what it points at" 'char - (unparse-type (ptr-target (parse-type '(* char))))) - (test "quals sit on the level they were written at" '(const) - (ptr-quals (parse-type '(const * char)))) - (test "an unsized array has no size" #f (array-size (parse-type '(¤ int)))) - (test "a sized one does" 16 (array-size (parse-type '(¤ int 16)))) - (test "an aggregate is nominal" 'point (agg-name (parse-type '(struct point)))) - (test-assert "a variadic signature says so" - (fn-variadic? (parse-type '(fn ((* const char) (...)) int)))) - (test-assert "and a plain one does not" - (not (fn-variadic? (parse-type '(fn ((int)) int))))) - + (test-group "decay" ;; decay: the conversion C performs at a call site, an operand of ;; `+', or the left half of a subscript. (test "an array decays to a pointer" '(* int) (unparse-type (decay (parse-type '(¤ int 16))))) @@ -115,7 +102,7 @@ (test-error "and not with another one" (unify (parse-type 'int) (parse-type 'char) #f)) - (let ((a (fresh-tvar))) + (let ((a (parse-type '_))) (unify a (parse-type '(* const char)) #f) (test "a variable takes the shape it is unified with" '(* const char) (unparse-type a))) @@ -125,8 +112,8 @@ (unify p (parse-type '(* int)) #f) (test "a partial type is completed by one step" '(* int) (unparse-type p))) - (let ((a (fresh-tvar)) - (b (fresh-tvar))) + (let ((a (parse-type '_)) + (b (parse-type '_))) (unify a b #f) (unify b (parse-type 'double) #f) (test "two variables joined then solved" 'double (unparse-type a))) @@ -152,168 +139,7 @@ (add-typedef 'i-count '(typedef i-count int)) (test-assert "a typedef unifies with its target" (unify (parse-type 'i-count) (parse-type 'int) #f)) - (let ((a (fresh-tvar))) + (let ((a (parse-type '_))) (unify a (parse-type 'i-count) #f) (test "and keeps its name when it is the one printed" - 'i-count (unparse-type a))) - - (test-group "the unknown type" - (test-assert "? is consistent with anything" - (unify the-unknown-type (parse-type '(struct point)) #f)) - (test-assert "in either order" - (unify (parse-type 'int) the-unknown-type #f)) - ;; ...and binds nothing. Degrading to ? is what keeps an - ;; unparsed C declaration from poisoning everything it touches. - (let ((a (fresh-tvar))) - (unify a the-unknown-type #f) - (test "a variable met with ? stays open" '_ (unparse-type a)))) - - (test-group "occurs check" - ;; Unreachable without recursive types, and the alternative to - ;; having it is not an error but a hang. - (let ((a (fresh-tvar))) - (test-error "a variable may not contain itself" - (unify a (make-ptr a (list)) #f)))) - - (test-group "rigid variables" - (let ((r (fresh-rigid-tvar)) - (a (fresh-tvar))) - (test-error "a type parameter does not unify with a type" - (unify r (parse-type 'int) #f)) - (test-assert "an ordinary variable binds to it instead" - (unify a r #f)) - ;; An unsolved variable resolves to itself. - (test-assert "it is still open" (tvar? (resolve r)))) - ;; ...and the same the other way round: it is which side is free - ;; that decides, not which side was written first. - (let ((r (fresh-rigid-tvar)) - (a (fresh-tvar))) - (test-assert "rigid first binds the free one" (unify r a #f)) - (test-assert "to the parameter itself" (eq? r (resolve a)))) - (let ((r1 (fresh-rigid-tvar)) - (r2 (fresh-rigid-tvar))) - (test-error "two parameters do not unify with each other" - (unify r1 r2 #f))))) - - (test-group "constraints" - (test #t (entails? 'numeric (parse-type 'int))) - (test #t (entails? 'numeric (parse-type '(unsigned long)))) - (test #t (entails? 'integral (parse-type 'char))) - (test #f (entails? 'integral (parse-type 'double))) - (test #t (entails? 'floating (parse-type 'double))) - (test #f (entails? 'floating (parse-type 'int))) - (test #f (entails? 'numeric (parse-type '(* char)))) - (test #t (entails? 'scalar (parse-type '(* char)))) - (test #f (entails? 'numeric (parse-type 'void))) - - (add-enum 'i-mood '(enum i-mood (glad sad))) - (test "an enum is an integer" #t (entails? 'integral (parse-type '(enum i-mood)))) - - ;; The third answer, and the important one. A name from a header - ;; might well be numeric; #f would reject working programs and #t - ;; would invent knowledge. - (test "an unparsed C name is not known either way" - 'unknown (entails? 'numeric (parse-type 'size-t))) - (test "nor is an open variable" 'unknown (entails? 'numeric (fresh-tvar))) - (test "? entails nothing, but says so quietly" - 'unknown (entails? 'numeric the-unknown-type)) - - ;; A typedef is entailed by what it resolves to, so an alias cannot - ;; sneak past a constraint its target would fail. - (add-typedef 'i-len '(typedef i-len int)) - (test "a typedef is judged by its target" #t (entails? 'numeric (parse-type 'i-len))) - - ;; A constrained variable checks its classes at the moment it is - ;; solved, not at the end. - (let ((a (fresh-tvar '(numeric)))) - (test-error "solving to a type that fails the class is an error" - (unify a (parse-type '(* char)) #f))) - (let ((a (fresh-tvar '(numeric)))) - (test-assert "and to one that satisfies it is not" - (unify a (parse-type 'double) #f))) - ;; ...but an unparsed name is not a failure, it is an absence of - ;; knowledge, and must stay silent. - (let ((a (fresh-tvar '(numeric)))) - (test-assert "an unparsed C name does not trip a constraint" - (unify a (parse-type 'GLuint) #f))) - - ;; Joining two variables joins what is known about both. - (let ((a (fresh-tvar '(numeric))) - (b (fresh-tvar '(integral)))) - (unify a b #f) - (test "constraints merge when variables do" - '("integral" "numeric") - (sort (map symbol->string (tvar-classes b)) string