Formulate destructors properly
[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                                         ; takes in the current environment and a scc
95                                         ; returns new environment with scc's types added in
96   (let* ([components (reverse (sccs (graph (let-bindings x))))]
97          [process-component
98           (lambda (acc comps)
99             (let*
100                                         ; create a new env with tvars for each component
101                                         ; e.g. scc of (x y)
102                                         ; scc-env = ((x . t0) (y . t1))
103                 ([scc-env
104                   (fold-left
105                    (lambda (acc c)
106                      (env-insert acc c (fresh-tvar)))
107                    acc comps)]
108                                         ; typecheck each component
109                  [type-results
110                   (map
111                    (lambda (c)
112                      (let ([body (cadr (assoc c (let-bindings x)))])
113                        (check scc-env body)))
114                    comps)]
115                                         ; collect all the constraints in the scc
116                  [cs
117                   (fold-left
118                    (lambda (acc res c)
119                      (constraint-merge
120                       (constraint-merge
121                                         ; unify with tvars from scc-env
122                                         ; result ~ tvar
123                        (~ (env-lookup scc-env c) (cadr res))
124                        (car res))                                 
125                       acc))
126                    '() type-results comps)]
127                                         ; substitute *only* the bindings in this scc
128                  [new-env
129                   (map (lambda (x)
130                          (if (memv (car x) comps)
131                              (cons (car x) (substitute cs (cdr x)))
132                              x))
133                        scc-env)])
134               new-env))]
135          [new-env (fold-left process-component env components)])
136     (check new-env (last (let-body x)))))
137
138 (define (check env x)
139   ;; (display "check: ")
140   ;; (display x)
141   ;; (display "\n\t")
142   ;; (display env)
143   ;; (newline)
144   (let
145       ((res
146         (case (ast-type x)
147           ('int-literal (list '() 'Int))
148           ('bool-literal (list '() 'Bool))
149           ('string-literal (list '() 'String))
150           ('builtin (list '() (builtin-type x)))
151
152           ('if
153            (let* ((cond-type-res (check env (cadr x)))
154                   (then-type-res (check env (caddr x)))
155                   (else-type-res (check env (cadddr x)))
156                   (then-eq-else-cs (~ (cadr then-type-res)
157                                       (cadr else-type-res)))
158                   (cs (constraint-merge
159                        (car then-type-res)
160                        (constraint-merge (~ (cadr cond-type-res) 'Bool)
161                                          (constraint-merge (car else-type-res)
162                                                            then-eq-else-cs))))
163                   (return-type (substitute cs (cadr then-type-res))))
164              (list cs return-type)))
165           
166           ('var (list '() (env-lookup env x)))
167           ('let (check-let env x))
168
169           
170           ('lambda
171               (let* [(new-env (env-insert env (lambda-arg x) (fresh-tvar)))
172
173                      (body-type-res (check new-env (lambda-body x)))
174                      (cs (car body-type-res))
175                      (subd-env (substitute-env (car body-type-res) new-env))
176                      (arg-type (env-lookup subd-env (lambda-arg x)))
177                      (resolved-arg-type (substitute cs arg-type))]
178                 ;; (display "lambda:\n\t")
179                 ;; (display prog)
180                 ;; (display "\n\t")
181                 ;; (display cs)
182                 ;; (display "\n\t")
183                 ;; (display (format "subd-env: ~a\n" subd-env))
184                 ;; (display resolved-arg-type)
185                 ;; (newline)
186                 (list (car body-type-res)
187                       (list 'abs
188                             resolved-arg-type
189                             (cadr body-type-res)))))
190           
191           ('app ; (f a)
192            (if (eqv? (car x) (cadr x))
193                                         ; recursive function (f f)
194                (let* [(func-type (env-lookup env (car x)))
195                       (return-type (fresh-tvar))
196                       (other-func-type `(abs ,func-type ,return-type))
197                       (cs (~ func-type other-func-type))
198                       (resolved-return-type (substitute cs return-type))]
199                  (list cs resolved-return-type)))
200
201                                         ; regular function
202                (let* ((arg-type-res (check env (cadr x)))
203                       (arg-type (cadr arg-type-res))
204                       (func-type-res (check env (car x)))
205                       (func-type (cadr func-type-res))
206                       
207                                         ; f ~ a -> t0
208                       (func-c (~
209                                (substitute (car arg-type-res) func-type)
210                                `(abs ,arg-type ,(fresh-tvar))))
211                       (cs (constraint-merge
212                            (constraint-merge func-c (car arg-type-res))
213                            (car func-type-res)))
214                       
215                       (resolved-func-type (substitute cs func-type))
216                       (resolved-return-type (caddr resolved-func-type)))
217                  ;; (display "app:\n")
218                  ;; (display cs)
219                  ;; (display "\n")
220                  ;; (display func-type)
221                  ;; (display "\n")
222                  ;; (display resolved-func-type)
223                  ;; (display "\n")
224                  ;; (display arg-type-res)
225                  ;; (display "\n")
226                  (if (abs? resolved-func-type)
227                      (let ((return-type (substitute cs (caddr resolved-func-type))))
228                        (list cs return-type))
229                      (error #f "not a function")))))))
230     ;; (display "result of ")
231     ;; (display x)
232     ;; (display ":\n\t")
233     ;; (display (pretty-type (cadr res)))
234     ;; (display "\n\t[")
235     ;; (display (pretty-constraints (car res)))
236     ;; (display "]\n")
237     res))
238
239                                         ; we typecheck the lambda calculus only (only single arg lambdas)
240 (define (typecheck prog)
241
242   (let ([init-env (flat-map data-tors (program-datas prog))])
243     (display init-env)
244     (newline)
245     (cadr (check init-env (normalize (program-body prog))))))
246
247   
248                                         ; returns a list of constraints
249 (define (~ a b)
250   (let ([res (unify? a b)])
251     (if res
252         res
253         (error #f
254                (format "couldn't unify ~a ~~ ~a" a b)))))
255
256 (define (unify? a b)
257   (cond [(eq? a b) '()]
258         [(tvar? a) (list (cons a b))]
259         [(tvar? b) (list (cons b a))]
260         [(and (abs? a) (abs? b))
261          (let* [(arg-cs (unify? (cadr a) (cadr b)))
262                 (body-cs (unify? (substitute arg-cs (caddr a))
263                                  (substitute arg-cs (caddr b))))]
264            (constraint-merge body-cs arg-cs))]
265         [else #f]))
266
267 (define (substitute cs t)
268   (cond
269    [(tvar? t)
270     (if (assoc t cs)
271         (cdr (assoc t cs))
272         t)]
273    [(abs? t) `(abs ,(substitute cs (cadr t))
274                    ,(substitute cs (caddr t)))]
275    [else t]))
276
277                                         ; applies substitutions to all variables in environment
278 (define (substitute-env cs env)
279   (map (lambda (x) (cons (car x) (substitute cs (cdr x)))) env))
280
281                                         ; composes constraints a onto b and merges, i.e. applies a to b
282                                         ; a should be the "more important" constraints
283 (define (constraint-merge a b)
284   (define (f cs constraint)
285     (cons (car constraint)
286           (substitute cs (cdr constraint))))
287   
288   (define (most-concrete a b)
289     (cond
290      [(tvar? a) b]
291      [(tvar? b) a]
292      [(and (abs? a) (abs? b))
293       `(abs ,(most-concrete (cadr a) (cadr b))
294             ,(most-concrete (caddr a) (caddr b)))]
295      [(abs? a) b]
296      [(abs? b) a]
297      [else a]))
298
299                                         ; for any two constraints that clash, e.g. t1 ~ abs t2 t3
300                                         ; and t1 ~ abs int t3
301                                         ; prepend the most concrete version of the type to the
302                                         ; list of constraints
303   (define (clashes)
304     (define (gen acc x)
305       (if (assoc (car x) a)
306           (cons (cons (car x) (most-concrete (cdr (assoc (car x) a))
307                                              (cdr x)))
308                 acc)
309           acc))
310     (fold-left gen '() b))
311
312   (define (union p q)
313     (append (filter (lambda (x) (not (assoc (car x) p)))
314                     q)
315             p))
316   (append (clashes) (union a (map (lambda (z) (f a z)) b))))
317
318
319 ;;                                      ; a1 -> a2 ~ a3 -> a4;
320 ;;                                      ; a1 -> a2 !~ Bool -> Bool
321 ;;                                      ; basically can the tvars be renamed
322 (define (types-equal? x y)
323   (let ([cs (unify? x y)])
324     (if (not cs) #f     
325         (let*
326             ([test (lambda (acc c)
327                      (and acc
328                           (tvar? (car c)) ; the only substitutions allowed are tvar -> tvar
329                           (tvar? (cdr c))))])
330           (fold-left test #t cs)))))
331
332                                         ; input: a list of binds ((x . y) (y . 3))
333                                         ; returns: pair of verts, edges ((x y) . (x . y))
334 (define (graph bs)
335   (define (go bs orig-bs)
336     (define (find-refs prog)
337       (ast-collect
338        (lambda (x)
339          (case (ast-type x)
340                                         ; only count a reference if its a binding
341            ['var (if (assoc x orig-bs) (list x) '())]
342            [else '()]))
343        prog))
344     (if (null? bs)
345         '(() . ())
346         (let* [(bind (car bs))
347
348                (vert (car bind))
349                (refs (find-refs (cdr bind)))
350                (edges (map (lambda (x) (cons vert x))
351                            refs))
352
353                (rest (if (null? (cdr bs))
354                          (cons '() '())
355                          (go (cdr bs) orig-bs)))
356                (total-verts (cons vert (car rest)))
357                (total-edges (append edges (cdr rest)))]
358           (cons total-verts total-edges))))
359   (go bs bs))
360
361 (define (successors graph v)
362   (define (go v E)
363     (if (null? E)
364         '()
365         (if (eqv? v (caar E))
366             (cons (cdar E) (go v (cdr E)))
367             (go v (cdr E)))))
368   (go v (cdr graph)))
369
370                                         ; takes in a graph (pair of vertices, edges)
371                                         ; returns a list of strongly connected components
372
373                                         ; ((x y w) . ((x . y) (x . w) (w . x))
374
375                                         ; =>
376                                         ; .->x->y
377                                         ; |  |
378                                         ; |  v
379                                         ; .--w
380
381                                         ; ((x w) (y))
382
383                                         ; this uses tarjan's algorithm, to get reverse
384                                         ; topological sorting for free
385 (define (sccs graph)
386   
387   (let* ([indices (make-hash-table)]
388          [lowlinks (make-hash-table)]
389          [on-stack (make-hash-table)]
390          [current 0]
391          [stack '()]
392          [result '()])
393
394     (define (index v)
395       (get-hash-table indices v #f))
396     (define (lowlink v)
397       (get-hash-table lowlinks v #f))
398
399     (letrec
400         ([strong-connect
401           (lambda (v)
402             (begin
403               (put-hash-table! indices v current)
404               (put-hash-table! lowlinks v current)
405               (set! current (+ current 1))
406               (push! stack v)
407               (put-hash-table! on-stack v #t)
408
409               (for-each
410                (lambda (w)
411                  (if (not (hashtable-contains? indices w))
412                                         ; successor w has not been visited, recurse
413                      (begin
414                        (strong-connect w)
415                        (put-hash-table! lowlinks
416                                         v
417                                         (min (lowlink v) (lowlink w))))
418                                         ; successor w has been visited
419                      (when (get-hash-table on-stack w #f)
420                        (put-hash-table! lowlinks v (min (lowlink v) (index w))))))
421                (successors graph v))
422
423               (when (= (index v) (lowlink v))
424                 (let ([scc
425                        (let new-scc ()
426                          (let ([w (pop! stack)])
427                            (put-hash-table! on-stack w #f)
428                            (if (eqv? w v)
429                                (list w)
430                                (cons w (new-scc)))))])
431                   (set! result (cons scc result))))))])
432       (for-each
433        (lambda (v)
434          (when (not (hashtable-contains? indices v)) ; v.index == -1
435            (strong-connect v)))
436        (car graph)))
437     result))
438