aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/type/check.lux
blob: 6538af56b3aadb082e213a2afd82ae7c92162474 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
(;module: {#;doc "Type-checking functionality.

                  Very useful for writing advanced macros."}
  lux
  (lux (control functor
                applicative
                monad)
       (data [text "Text/" Monoid<Text> Eq<Text>]
             text/format
             [number]
             maybe
             [product]
             (coll [list]
                   [dict])
             [error #- fail])
       [type "Type/" Eq<Type>]
       ))

(type: #export Id Nat)

(type: #export Fixpoints (List [[Type Type] Bool]))

(type: #export Context
  {#var-counter Id
   #ex-counter Id
   #bindings (dict;Dict Id (Maybe Type))
   #fixpoints Fixpoints
   })

(type: #export (Check a)
  (-> Context (Error [Context a])))

(struct: #export _ (Functor Check)
  (def: (map f fa)
    (function [context]
      (case (fa context)
        (#;Left error)
        (#;Left error)

        (#;Right [context' output])
        (#;Right [context' (f output)])
        ))))

(struct: #export _ (Applicative Check)
  (def: functor Functor<Check>)

  (def: (wrap x)
    (function [context]
      (#;Right [context x])))

  (def: (apply ff fa)
    (function [context]
      (case (ff context)
        (#;Right [context' f])
        (case (fa context')
          (#;Right [context'' a])
          (#;Right [context'' (f a)])

          (#;Left error)
          (#;Left error))

        (#;Left error)
        (#;Left error)
        )))
  )

(struct: #export _ (Monad Check)
  (def: applicative Applicative<Check>)

  (def: (join ffa)
    (function [context]
      (case (ffa context)
        (#;Right [context' fa])
        (case (fa context')
          (#;Right [context'' a])
          (#;Right [context'' a])

          (#;Left error)
          (#;Left error))

        (#;Left error)
        (#;Left error)
        )))
  )

(open Monad<Check> "Check/")

## [[Logic]]
(def: #export (run context proc)
  (All [a] (-> Context (Check a) (Error a)))
  (case (proc context)
    (#;Left error)
    (#;Left error)

    (#;Right [context' output])
    (#;Right output)))

(def: (apply-type! t-func t-arg)
  (-> Type Type (Check Type))
  (function [context]
    (case (type;apply-type t-func t-arg)
      #;None
      (#;Left (format "Invalid type application: " (%type t-func) " on " (%type t-arg)))

      (#;Some output)
      (#;Right [context output]))))

(def: #export existential
  {#;doc "A producer of existential types."}
  (Check [Id Type])
  (function [context]
    (let [id (get@ #ex-counter context)]
      (#;Right [(update@ #ex-counter n.inc context)
                [id (#;ExT id)]]))))

(def: (bound? id)
  (-> Id (Check Bool))
  (function [context]
    (case (|> context (get@ #bindings) (dict;get id))
      (#;Some (#;Some _))
      (#;Right [context true])

      (#;Some #;None)
      (#;Right [context false])
      
      #;None
      (#;Left (format "Unknown type-var: " (%n id))))))

(def: #export (read-var id)
  (-> Id (Check Type))
  (function [context]
    (case (|> context (get@ #bindings) (dict;get id))
      (#;Some (#;Some type))
      (#;Right [context type])

      (#;Some #;None)
      (#;Left (format "Unbound type-var: " (%n id)))
      
      #;None
      (#;Left (format "Unknown type-var: " (%n id))))))

(def: #export (write-var id type)
  (-> Id Type (Check Unit))
  (function [context]
    (case (|> context (get@ #bindings) (dict;get id))
      (#;Some (#;Some bound))
      (#;Left (format "Can't rebind type-var: " (%n id) " | Current type: " (%type bound)))
      
      (#;Some #;None)
      (#;Right [(update@ #bindings (dict;put id (#;Some type)) context)
                []])

      #;None
      (#;Left (format "Unknown type-var: " (%n id))))))

(def: (rewrite-var id type)
  (-> Id Type (Check Unit))
  (function [context]
    (case (|> context (get@ #bindings) (dict;get id))
      (#;Some _)
      (#;Right [(update@ #bindings (dict;put id (#;Some type)) context)
                []])
      
      #;None
      (#;Left (format "Unknown type-var: " (%n id))))))

(def: #export (clear-var id)
  (-> Id (Check Unit))
  (function [context]
    (case (|> context (get@ #bindings) (dict;get id))
      (#;Some _)
      (#;Right [(update@ #bindings (dict;put id #;None) context)
                []])
      
      #;None
      (#;Left (format "Unknown type-var: " (%n id))))))

(def: (clean t-id type)
  (-> Id Type (Check Type))
  (case type
    (#;VarT id)
    (if (n.= t-id id)
      (do Monad<Check>
        [? (bound? id)]
        (if ?
          (read-var id)
          (wrap type)))
      (do Monad<Check>
        [? (bound? id)]
        (if ?
          (do Monad<Check>
            [=type (read-var id)
             ==type (clean t-id =type)]
            (case ==type
              (#;VarT =id)
              (if (n.= t-id =id)
                (do Monad<Check>
                  [_ (clear-var id)]
                  (wrap type))
                (do Monad<Check>
                  [_ (rewrite-var id ==type)]
                  (wrap type)))

              _
              (do Monad<Check>
                [_ (rewrite-var id ==type)]
                (wrap type))))
          (wrap type))))

    (#;HostT name params)
    (do Monad<Check>
      [=params (mapM @ (clean t-id) params)]
      (wrap (#;HostT name =params)))
    
    (^template [<tag>]
      (<tag> left right)
      (do Monad<Check>
        [=left (clean t-id left)
         =right (clean t-id right)]
        (wrap (<tag> =left =right))))
    ([#;FunctionT]
     [#;AppT]
     [#;ProdT]
     [#;SumT])

    (^template [<tag>]
      (<tag> env body)
      (do Monad<Check>
        [=env (mapM @ (clean t-id) env)
         =body (clean t-id body)] ## TODO: DON'T CLEAN THE BODY
        (wrap (<tag> =env =body))))
    ([#;UnivQ]
     [#;ExQ])
    
    _
    (:: Monad<Check> wrap type)
    ))

(def: #export create-var
  (Check [Id Type])
  (function [context]
    (let [id (get@ #var-counter context)]
      (#;Right [(|> context
                    (update@ #var-counter n.inc)
                    (update@ #bindings (dict;put id #;None)))
                [id (#;VarT id)]]))))

(do-template [<get> <set> <tag> <type>]
  [(def: <get>
     (Check <type>)
     (function [context]
       (#;Right [context
                 (get@ <tag> context)])))

   (def: (<set> value)
     (-> <type> (Check Unit))
     (function [context]
       (#;Right [(set@ <tag> value context)
                 []])))]

  [get-bindings  set-bindings  #bindings  (dict;Dict Id (Maybe Type))]
  [get-fixpoints set-fixpoints #fixpoints Fixpoints]
  )

(def: #export (delete-var id)
  (-> Id (Check Unit))
  (do Monad<Check>
    [? (bound? id)
     _ (if ?
         (wrap [])
         (do Monad<Check>
           [[ex-id ex] existential]
           (write-var id ex)))
     bindings get-bindings
     bindings' (mapM @
                     (function [(^@ binding [b-id b-type])]
                       (if (n.= id b-id)
                         (wrap binding)
                         (case b-type
                           #;None
                           (wrap binding)

                           (#;Some b-type')
                           (case b-type'
                             (#;VarT t-id)
                             (if (n.= id t-id)
                               (wrap [b-id #;None])
                               (wrap binding))

                             _
                             (do Monad<Check>
                               [b-type'' (clean id b-type')]
                               (wrap [b-id (#;Some b-type'')])))
                           )))
                     (dict;entries bindings))]
    (set-bindings (|> bindings' (dict;from-list number;Hash<Nat>) (dict;remove id)))))

(def: #export (with-var k)
  (All [a] (-> (-> [Id Type] (Check a)) (Check a)))
  (do Monad<Check>
    [[id var] create-var
     output (k [id var])
     _ (delete-var id)]
    (wrap output)))

(def: #export fresh-context
  Context
  {#var-counter +0
   #ex-counter +0
   #bindings (dict;new number;Hash<Nat>)
   #fixpoints (list)
   })

(def: (attempt op)
  (All [a] (-> (Check a) (Check (Maybe a))))
  (function [context]
    (case (op context)
      (#;Right [context' output])
      (#;Right [context' (#;Some output)])

      (#;Left _)
      (#;Right [context #;None]))))

(def: #export (fail message)
  (All [a] (-> Text (Check a)))
  (function [context]
    (#;Left message)))

(def: (fail-check expected actual)
  (-> Type Type (Check Unit))
  (fail (format "Expected: " (%type expected) "\n\n"
                "Actual:   " (%type actual))))

(def: success (Check Unit) (Check/wrap []))

(def: (either left right)
  (All [a] (-> (Check a) (Check a) (Check a)))
  (function [context]
    (case (left context)
      (#;Right [context' output])
      (#;Right [context' output])

      (#;Left _)
      (right context))))

(def: (fp-get [e a] fixpoints)
  (-> [Type Type] Fixpoints (Maybe Bool))
  (:: Monad<Maybe> map product;right
      (list;find (function [[[fe fa] status]]
                   (and (Type/= e fe)
                        (Type/= a fa)))
                 fixpoints)))

(def: (fp-put ea status fixpoints)
  (-> [Type Type] Bool Fixpoints Fixpoints)
  (#;Cons [ea status] fixpoints))

(def: #export (check expected actual)
  {#;doc "Type-check to ensure that the 'expected' type subsumes the 'actual' type."}
  (-> Type Type (Check Unit))
  (if (is expected actual)
    success
    (case [expected actual]
      [(#;VarT e-id) (#;VarT a-id)]
      (if (n.= e-id a-id)
        success
        (do Monad<Check>
          [ebound (attempt (read-var e-id))
           abound (attempt (read-var a-id))]
          (case [ebound abound]
            [#;None #;None]
            (write-var e-id actual)
            
            [(#;Some etype) #;None]
            (check etype actual)

            [#;None (#;Some atype)]
            (check expected atype)

            [(#;Some etype) (#;Some atype)]
            (check etype atype))))
      
      [(#;VarT id) _]
      (either (write-var id actual)
              (do Monad<Check>
                [bound (read-var id)]
                (check bound actual)))
      
      [_ (#;VarT id)]
      (either (write-var id expected)
              (do Monad<Check>
                [bound (read-var id)]
                (check expected bound)))

      [(#;AppT (#;ExT eid) eA) (#;AppT (#;ExT aid) aA)]
      (if (n.= eid aid)
        (check eA aA)
        (fail-check expected actual))

      [(#;AppT (#;VarT id) A1) (#;AppT F2 A2)]
      (either (do Monad<Check>
                [F1 (read-var id)]
                (check (#;AppT F1 A1) actual))
              (do Monad<Check>
                [_ (check (#;VarT id) F2)
                 e' (apply-type! F2 A1)
                 a' (apply-type! F2 A2)]
                (check e' a')))
      
      [(#;AppT F1 A1) (#;AppT (#;VarT id) A2)]
      (either (do Monad<Check>
                [F2 (read-var id)]
                (check expected (#;AppT F2 A2)))
              (do Monad<Check>
                [_ (check F1 (#;VarT id))
                 e' (apply-type! F1 A1)
                 a' (apply-type! F1 A2)]
                (check e' a')))

      [(#;AppT F A) _]
      (do Monad<Check>
        [#let [fp-pair [expected actual]]
         fixpoints get-fixpoints]
        (case (fp-get fp-pair fixpoints)
          (#;Some ?)
          (if ?
            success
            (fail-check expected actual))

          #;None
          (do Monad<Check>
            [expected' (apply-type! F A)
             _ (set-fixpoints (fp-put fp-pair true fixpoints))]
            (check expected' actual))))

      [_ (#;AppT F A)]
      (do Monad<Check>
        [actual' (apply-type! F A)]
        (check expected actual'))

      [(#;UnivQ _) _]
      (do Monad<Check>
        [[ex-id ex] existential
         expected' (apply-type! expected ex)]
        (check expected' actual))

      [_ (#;UnivQ _)]
      (with-var
        (function [[var-id var]]
          (do Monad<Check>
            [actual' (apply-type! actual var)
             =output (check expected actual')
             _ (clean var-id expected)]
            success)))

      [(#;ExQ e!env e!def) _]
      (with-var
        (function [[var-id var]]
          (do Monad<Check>
            [expected' (apply-type! expected var)
             =output (check expected' actual)
             _ (clean var-id actual)]
            success)))

      [_ (#;ExQ a!env a!def)]
      (do Monad<Check>
        [[ex-id ex] existential
         actual' (apply-type! actual ex)]
        (check expected actual'))

      [(#;HostT e-name e-params) (#;HostT a-name a-params)]
      (if (Text/= e-name a-name)
        (do Monad<Check>
          [_ (mapM Monad<Check>
                   (function [[e a]] (check e a))
                   (list;zip2 e-params a-params))]
          success)
        (fail-check expected actual))

      (^template [<unit> <append>]
        [<unit> <unit>]
        success
        
        [(<append> eL eR) (<append> aL aR)]
        (do Monad<Check>
          [_ (check eL aL)]
          (check eR aR)))
      ([#;VoidT #;SumT]
       [#;UnitT #;ProdT])
      
      [(#;FunctionT eI eO) (#;FunctionT aI aO)]
      (do Monad<Check>
        [_ (check aI eI)]
        (check eO aO))

      [(#;ExT e!id) (#;ExT a!id)]
      (if (n.= e!id a!id)
        success
        (fail-check expected actual))

      [(#;NamedT _ ?etype) _]
      (check ?etype actual)

      [_ (#;NamedT _ ?atype)]
      (check expected ?atype)

      _
      (fail-check expected actual))))

(def: #export (checks? expected actual)
  {#;doc "A simple type-checking function that just returns a yes/no answer."}
  (-> Type Type Bool)
  (case (run fresh-context (check expected actual))
    (#;Left error)
    false

    (#;Right _)
    true))

(def: #export get-context
  (Check Context)
  (function [context]
    (#;Right [context context])))