Annotate ast with types for adt codegen
[scheme.git] / typecheck.scm
1 (load "ast.scm")
2
3 (define (abs? t)
4   (and (list? t) (eq? (car t) 'abs)))
5
6 (define (tvar? t)
7   (and (not (list? t))
8        (not (concrete? t))
9        (symbol? t)))
10
11 (define (concrete? t)
12   (and (symbol? t)
13        (char-upper-case? (string-ref (symbol->string t) 0))))
14
15 (define (pretty-type t)
16   (cond ((abs? t)
17          (string-append
18           (if (abs? (cadr t))
19               (string-append "(" (pretty-type (cadr t)) ")")
20               (pretty-type (cadr t)))
21           " -> "
22           (pretty-type (caddr t))))
23         (else (symbol->string t))))
24
25 (define (pretty-constraints cs)
26   (string-append "{"
27                  (fold-left string-append
28                             ""
29                             (map (lambda (c)
30                                    (string-append
31                                     (pretty-type (car c))
32                                     ": "
33                                     (pretty-type (cdr c))
34                                     ", "))
35                                  cs))
36                  "}"))
37
38                                         ; ('a, ('b, 'a))
39 (define (env-lookup env n)
40   (if (null? env) (error #f "empty env" env n)                  ; it's a type equality
41       (if (eq? (caar env) n)
42           (cdar env)
43           (env-lookup (cdr env) n))))
44
45 (define (env-insert env n t)
46   (cons (cons n t) env))
47
48 (define abs-arg cadr)
49
50 (define cur-tvar 0)
51 (define (fresh-tvar)
52   (begin
53     (set! cur-tvar (+ cur-tvar 1))
54     (string->symbol
55      (string-append "t" (number->string (- cur-tvar 1))))))
56
57 (define (last xs)
58   (if (null? (cdr xs))
59       (car xs)
60       (last (cdr xs))))
61
62 (define (normalize prog) ; (+ a b) -> ((+ a) b)
63   (case (ast-type prog)
64     ('lambda 
65                                         ; (lambda (x y) (+ x y)) -> (lambda (x) (lambda (y) (+ x y)))
66         (if (> (length (lambda-args prog)) 1)       
67             (list 'lambda (list (car (lambda-args prog)))
68                   (normalize (list 'lambda (cdr (lambda-args prog)) (caddr prog))))
69             (list 'lambda (lambda-args prog) (normalize (caddr prog)))))
70     ('app
71      (if (null? (cddr prog))
72          `(,(normalize (car prog)) ,(normalize (cadr prog))) ; (f a)
73          (normalize `(,(list (normalize (car prog)) (normalize (cadr prog)))
74                       ,@(cddr prog))))) ; (f a b)
75     ('let
76         (append (list 'let
77                       (map (lambda (x) `(,(car x) ,(normalize (cadr x))))
78                            (let-bindings prog)))
79                 (map normalize (let-body prog))))
80     (else (ast-traverse normalize prog))))
81
82 (define (builtin-type x)
83   (case x
84     ('+ '(abs Int (abs Int Int)))
85     ('- '(abs Int (abs Int Int)))
86     ('* '(abs Int (abs Int Int)))
87     ('! '(abs Bool Bool))
88     ('= '(abs Int (abs Int Bool)))
89     ('bool->int '(abs Bool Int))
90     ('print '(abs String Void))
91     (else (error #f "Couldn't find type for builtin" x))))
92
93 (define (check-let env x)
94
95   ; acc is a pair of (env . annotated bindings)
96   (define (process-component acc comps)
97     (let*
98                                         ; create a new env with tvars for each component
99                                         ; e.g. scc of (x y)
100                                         ; scc-env = ((x . t0) (y . t1))
101         ([scc-env
102           (fold-left
103            (lambda (acc c)
104              (env-insert acc c (fresh-tvar)))
105            (car acc) comps)]
106                                         ; typecheck each component
107          [type-results
108           (map
109            (lambda (c)
110              (let ([body (cadr (assoc c (let-bindings x)))])
111                (check scc-env body)))
112            comps)]
113                                         ; collect all the constraints in the scc
114          [cs
115           (fold-left
116            (lambda (acc res c)
117              (constraint-merge
118               (constraint-merge
119                                         ; unify with tvars from scc-env
120                                         ; result ~ tvar
121                (~ (env-lookup scc-env c) (cadr res))
122                (car res))                                 
123               acc))
124            '() type-results comps)]
125                                         ; substitute *only* the bindings in this scc
126          [new-env
127           (map (lambda (x)
128                  (if (memv (car x) comps)
129                      (cons (car x) (substitute cs (cdr x)))
130                      x))
131                scc-env)]
132
133          [annotated-bindings (append (cdr acc) ; the previous annotated bindings
134                                      (map cons
135                                           comps
136                                           (map caddr type-results)))])
137       (cons new-env annotated-bindings)))
138                                         ; takes in the current environment and a scc
139                                         ; returns new environment with scc's types added in
140   (let* ([components (reverse (sccs (graph (let-bindings x))))]
141          [results (fold-left process-component (cons env '()) components)]
142          [new-env (car results)]
143          [annotated-bindings (cdr results)]
144
145          [body-results (map (lambda (body) (check new-env body)) (let-body x))]
146          [let-type (cadr (last body-results))]
147          [cs (fold-left (lambda (acc cs) (constraint-merge acc cs)) '() (map car body-results))]
148
149          [annotated `((let ,annotated-bindings ,@(map caddr body-results)))])
150     (list cs let-type annotated)))
151
152
153 ; returns a list (constraints type annotated)
154 (define (check env x)
155   (define (make-result cs type)
156     (list cs type `(,x : ,type)))
157   ;; (display "check: ")
158   ;; (display x)
159   ;; (display "\n\t")
160   ;; (display env)
161   ;; (newline)
162   (let
163       ((res
164         (case (ast-type x)
165           ('int-literal (make-result '() 'Int))
166           ('bool-literal (make-result '() 'Bool))
167           ('string-literal (make-result '() 'String))
168           ('builtin (make-result '() (builtin-type x)))
169
170           ('if
171            (let* ((cond-type-res (check env (cadr x)))
172                   (then-type-res (check env (caddr x)))
173                   (else-type-res (check env (cadddr x)))
174                   (then-eq-else-cs (~ (cadr then-type-res)
175                                       (cadr else-type-res)))
176                   (cs (constraint-merge
177                        (car then-type-res)
178                        (constraint-merge (~ (cadr cond-type-res) 'Bool)
179                                          (constraint-merge (car else-type-res)
180                                                            then-eq-else-cs))))
181                   (return-type (substitute cs (cadr then-type-res)))          
182                   [annotated `((if ,(caddr cond-type-res)
183                                    ,(caddr then-type-res)
184                                    ,(caddr else-type-res)) : ,return-type)])
185              (list cs return-type annotated)))
186           
187           ('var (make-result '() (env-lookup env x)))
188           ('let (check-let env x))
189
190           
191           ('lambda
192               (let* ([new-env (env-insert env (lambda-arg x) (fresh-tvar))]
193
194                      [body-type-res (check new-env (lambda-body x))]
195                      [cs (car body-type-res)]
196                      [subd-env (substitute-env (car body-type-res) new-env)]
197                      [arg-type (env-lookup subd-env (lambda-arg x))]
198                      [resolved-arg-type (substitute cs arg-type)]
199
200                      [lambda-type `(abs ,resolved-arg-type ,(cadr body-type-res))]
201
202                      ; TODO: do we need to annotate the lambda argument?
203                      [annotated `(lambda (,(lambda-arg x)) ,(caddr body-type-res))])
204                 
205                 (list (car body-type-res) ; constraints
206                       lambda-type  ; type
207                       annotated)))
208
209           
210           ('app ; (f a)
211            (if (eqv? (car x) (cadr x))
212                                         ; recursive function (f f)
213                (let* ([func-type (env-lookup env (car x))]
214                       [return-type (fresh-tvar)]
215                       [other-func-type `(abs ,func-type ,return-type)]
216                       [cs (~ func-type other-func-type)]
217                       [resolved-return-type (substitute cs return-type)]
218
219                       [annotated `(((,(car x) : ,func-type)
220                                     (,(cadr x) : ,func-type)) : ,resolved-return-type)])
221                  (list cs resolved-return-type annotated)))
222
223                                         ; regular function
224            (let* ([arg-type-res (check env (cadr x))]
225                   [arg-type (cadr arg-type-res)]
226                   [func-type-res (check env (car x))]
227                   [func-type (cadr func-type-res)]
228                   
229                                         ; f ~ a -> t0
230                   [func-c (~
231                            (substitute (car arg-type-res) func-type)
232                            `(abs ,arg-type ,(fresh-tvar)))]
233                   [cs (constraint-merge
234                        (constraint-merge func-c (car arg-type-res))
235                        (car func-type-res))]
236                   
237                   [resolved-func-type (substitute cs func-type)]
238                   [resolved-return-type (caddr resolved-func-type)]
239
240                   [annotated `((,(caddr func-type-res)
241                                 ,(caddr arg-type-res)) : ,resolved-return-type)])
242
243              (if (abs? resolved-func-type)
244                  (let ((return-type (substitute cs (caddr resolved-func-type))))
245                    (list cs return-type annotated))
246                  (error #f "not a function")))))))
247     ;; (display "result of ")
248     ;; (display x)
249     ;; (display ":\n\t")
250     ;; (display (pretty-type (cadr res)))
251     ;; (display "\n\t[")
252     ;; (display (pretty-constraints (car res)))
253     ;; (display "]\n")
254     res))
255
256 (define (init-adts-env prog)
257   (flat-map data-tors-env (map data-layout (program-datas prog))))
258
259                                         ; we typecheck the lambda calculus only (only single arg lambdas)
260 (define (typecheck prog)
261   (cadr (check (init-adts-env prog) (normalize (program-body prog)))))
262
263 (define (annotate-types prog)
264   (caddr (check (init-adts-env prog) (normalize (program-body prog)))))
265
266   
267                                         ; returns a list of constraints
268 (define (~ a b)
269   (let ([res (unify? a b)])
270     (if res
271         res
272         (error #f
273                (format "couldn't unify ~a ~~ ~a" a b)))))
274
275 (define (unify? a b)
276   (cond [(eq? a b) '()]
277         [(tvar? a) (list (cons a b))]
278         [(tvar? b) (list (cons b a))]
279         [(and (abs? a) (abs? b))
280          (let* [(arg-cs (unify? (cadr a) (cadr b)))
281                 (body-cs (unify? (substitute arg-cs (caddr a))
282                                  (substitute arg-cs (caddr b))))]
283            (constraint-merge body-cs arg-cs))]
284         [else #f]))
285
286 (define (substitute cs t)
287   (cond
288    [(tvar? t)
289     (if (assoc t cs)
290         (cdr (assoc t cs))
291         t)]
292    [(abs? t) `(abs ,(substitute cs (cadr t))
293                    ,(substitute cs (caddr t)))]
294    [else t]))
295
296                                         ; applies substitutions to all variables in environment
297 (define (substitute-env cs env)
298   (map (lambda (x) (cons (car x) (substitute cs (cdr x)))) env))
299
300                                         ; composes constraints a onto b and merges, i.e. applies a to b
301                                         ; a should be the "more important" constraints
302 (define (constraint-merge a b)
303   (define (f cs constraint)
304     (cons (car constraint)
305           (substitute cs (cdr constraint))))
306   
307   (define (most-concrete a b)
308     (cond
309      [(tvar? a) b]
310      [(tvar? b) a]
311      [(and (abs? a) (abs? b))
312       `(abs ,(most-concrete (cadr a) (cadr b))
313             ,(most-concrete (caddr a) (caddr b)))]
314      [(abs? a) b]
315      [(abs? b) a]
316      [else a]))
317
318                                         ; for any two constraints that clash, e.g. t1 ~ abs t2 t3
319                                         ; and t1 ~ abs int t3
320                                         ; prepend the most concrete version of the type to the
321                                         ; list of constraints
322   (define (clashes)
323     (define (gen acc x)
324       (if (assoc (car x) a)
325           (cons (cons (car x) (most-concrete (cdr (assoc (car x) a))
326                                              (cdr x)))
327                 acc)
328           acc))
329     (fold-left gen '() b))
330
331   (define (union p q)
332     (append (filter (lambda (x) (not (assoc (car x) p)))
333                     q)
334             p))
335   (append (clashes) (union a (map (lambda (z) (f a z)) b))))
336
337
338 ;;                                      ; a1 -> a2 ~ a3 -> a4;
339 ;;                                      ; a1 -> a2 !~ Bool -> Bool
340 ;;                                      ; basically can the tvars be renamed
341 (define (types-equal? x y)
342   (let ([cs (unify? x y)])
343     (if (not cs) #f     
344         (let*
345             ([test (lambda (acc c)
346                      (and acc
347                           (tvar? (car c)) ; the only substitutions allowed are tvar -> tvar
348                           (tvar? (cdr c))))])
349           (fold-left test #t cs)))))
350
351                                         ; input: a list of binds ((x . y) (y . 3))
352                                         ; returns: pair of verts, edges ((x y) . (x . y))
353