aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/macro/poly.lux
blob: 7c86a952ae298e1165e157e3cac060d28d3a609f (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
(.module:
  [lux (#- function)
   [control
    [monad (#+ do Monad)]
    [equivalence]
    ["p" parser]
    ["ex" exception (#+ exception:)]]
   [function]
   [data
    [text ("text/" Monoid<Text>)]
    [collection
     [list ("list/" Fold<List> Monad<List> Monoid<List>)]
     ["dict" dictionary (#+ Dictionary)]]
    [number ("nat/" Codec<Text,Nat>)]
    [product]
    [bit]
    [maybe]
    [ident ("ident/" Equivalence<Ident> Codec<Text,Ident>)]
    ["e" error]]
   [macro (#+ with-gensyms)
    [code]
    ["s" syntax (#+ syntax: Syntax)]
    [syntax
     ["cs" common]
     [common
      ["csr" reader]
      ["csw" writer]]]]
   [language
    [type ("type/" Equivalence<Type>)
     [check]]]
   ])

(type: #export Env (Dictionary Nat [Type Code]))

(type: #export (Poly a)
  (p.Parser [Env (List Type)] a))

(def: #export fresh Env (dict.new number.Hash<Nat>))

(def: (run' env types poly)
  (All [a] (-> Env (List Type) (Poly a) (e.Error a)))
  (case (p.run [env types] poly)
    (#e.Error error)
    (#e.Error error)

    (#e.Success [[env' remaining] output])
    (case remaining
      #.Nil
      (#e.Success output)

      _
      (#e.Error (|> remaining
                    (list/map type.to-text)
                    (text.join-with ", ")
                    (text/compose "Unconsumed types: "))))))

(def: #export (run type poly)
  (All [a] (-> Type (Poly a) (e.Error a)))
  (run' fresh (list type) poly))

(def: #export env
  (Poly Env)
  (.function (_ [env inputs])
    (#e.Success [[env inputs] env])))

(def: (with-env temp poly)
  (All [a] (-> Env (Poly a) (Poly a)))
  (.function (_ [env inputs])
    (case (p.run [temp inputs] poly)
      (#e.Error error)
      (#e.Error error)

      (#e.Success [[_ remaining] output])
      (#e.Success [[env remaining] output]))))

(def: #export peek
  (Poly Type)
  (.function (_ [env inputs])
    (case inputs
      #.Nil
      (#e.Error "Empty stream of types.")

      (#.Cons headT tail)
      (#e.Success [[env inputs] headT]))))

(def: #export any
  (Poly Type)
  (.function (_ [env inputs])
    (case inputs
      #.Nil
      (#e.Error "Empty stream of types.")

      (#.Cons headT tail)
      (#e.Success [[env tail] headT]))))

(def: #export (local types poly)
  (All [a] (-> (List Type) (Poly a) (Poly a)))
  (.function (_ [env pass-through])
    (case (run' env types poly)
      (#e.Error error)
      (#e.Error error)

      (#e.Success output)
      (#e.Success [[env pass-through] output]))))

(def: (label idx)
  (-> Nat Code)
  (code.local-symbol (text/compose "label\u0000" (nat/encode idx))))

(def: #export (with-extension type poly)
  (All [a] (-> Type (Poly a) (Poly [Code a])))
  (.function (_ [env inputs])
    (let [current-id (dict.size env)
          g!var (label current-id)]
      (case (p.run [(dict.put current-id [type g!var] env)
                    inputs]
                   poly)
        (#e.Error error)
        (#e.Error error)

        (#e.Success [[_ inputs'] output])
        (#e.Success [[env inputs'] [g!var output]])))))

(do-template [<name> <flattener> <tag>]
  [(def: #export (<name> poly)
     (All [a] (-> (Poly a) (Poly a)))
     (do p.Monad<Parser>
       [headT any]
       (let [members (<flattener> (type.un-name headT))]
         (if (n/> +1 (list.size members))
           (local members poly)
           (p.fail ($_ text/compose "Not a " (ident/encode (ident-for <tag>)) " type: " (type.to-text headT)))))))]

  [variant type.flatten-variant #.Sum]
  [tuple   type.flatten-tuple   #.Product]
  )

(def: polymorphic'
  (Poly [Nat Type])
  (do p.Monad<Parser>
    [headT any
     #let [[num-arg bodyT] (type.flatten-univ-q (type.un-name headT))]]
    (if (n/= +0 num-arg)
      (p.fail ($_ text/compose "Non-polymorphic type: " (type.to-text headT)))
      (wrap [num-arg bodyT]))))

(def: #export (polymorphic poly)
  (All [a] (-> (Poly a) (Poly [Code (List Code) a])))
  (do p.Monad<Parser>
    [headT any
     funcI (:: @ map dict.size ..env)
     [num-args non-poly] (local (list headT) polymorphic')
     env ..env
     #let [funcL (label funcI)
           [all-varsL env'] (loop [current-arg +0
                                   env' env
                                   all-varsL (: (List Code) (list))]
                              (if (n/< num-args current-arg)
                                (if (n/= +0 current-arg)
                                  (let [varL (label (inc funcI))]
                                    (recur (inc current-arg)
                                           (|> env'
                                               (dict.put funcI [headT funcL])
                                               (dict.put (inc funcI) [(#.Parameter (inc funcI)) varL]))
                                           (#.Cons varL all-varsL)))
                                  (let [partialI (|> current-arg (n/* +2) (n/+ funcI))
                                        partial-varI (inc partialI)
                                        partial-varL (label partial-varI)
                                        partialC (` ((~ funcL) (~+ (|> (list.n/range +0 (dec num-args))
                                                                       (list/map (|>> (n/* +2) inc (n/+ funcI) label))
                                                                       list.reverse))))]
                                    (recur (inc current-arg)
                                           (|> env'
                                               (dict.put partialI [.Nothing partialC])
                                               (dict.put partial-varI [(#.Parameter partial-varI) partial-varL]))
                                           (#.Cons partial-varL all-varsL))))
                                [all-varsL env']))]]
    (|> (do @
          [output poly]
          (wrap [funcL all-varsL output]))
        (local (list non-poly))
        (with-env env'))))

(def: #export (function in-poly out-poly)
  (All [i o] (-> (Poly i) (Poly o) (Poly [i o])))
  (do p.Monad<Parser>
    [headT any
     #let [[inputsT outputT] (type.flatten-function (type.un-name headT))]]
    (if (n/> +0 (list.size inputsT))
      (p.seq (local inputsT in-poly)
             (local (list outputT) out-poly))
      (p.fail ($_ text/compose "Non-function type: " (type.to-text headT))))))

(def: #export (apply poly)
  (All [a] (-> (Poly a) (Poly a)))
  (do p.Monad<Parser>
    [headT any
     #let [[funcT paramsT] (type.flatten-application (type.un-name headT))]]
    (if (n/= +0 (list.size paramsT))
      (p.fail ($_ text/compose "Non-application type: " (type.to-text headT)))
      (local (#.Cons funcT paramsT) poly))))

(do-template [<name> <test>]
  [(def: #export (<name> expected)
     (-> Type (Poly Any))
     (do p.Monad<Parser>
       [actual any]
       (if (<test> expected actual)
         (wrap [])
         (p.fail ($_ text/compose
                     "Types do not match." "\n"
                     "Expected: " (type.to-text expected) "\n"
                     "  Actual: " (type.to-text actual))))))]

  [exactly type/=]
  [similar check.checks?]
  )

(def: (adjusted-idx env idx)
  (-> Env Nat Nat)
  (let [env-level (n// +2 (dict.size env))
        parameter-level (n// +2 idx)
        parameter-idx (n/% +2 idx)]
    (|> env-level dec (n/- parameter-level) (n/* +2) (n/+ parameter-idx))))

(def: #export parameter
  (Poly Code)
  (do p.Monad<Parser>
    [env ..env
     headT any]
    (case headT
      (#.Parameter idx)
      (case (dict.get (adjusted-idx env idx) env)
        (#.Some [poly-type poly-code])
        (wrap poly-code)

        #.None
        (p.fail ($_ text/compose "Unknown parameter type: " (type.to-text headT))))

      _
      (p.fail ($_ text/compose "Not a parameter type: " (type.to-text headT))))))

(def: #export (var id)
  (-> Nat (Poly Any))
  (do p.Monad<Parser>
    [env ..env
     headT any]
    (case headT
      (#.Parameter idx)
      (if (n/= id (adjusted-idx env idx))
        (wrap [])
        (p.fail ($_ text/compose "Wrong parameter type.\n"
                    "Expected: " (nat/encode id) "\n"
                    "  Actual: " (nat/encode idx))))

      _
      (p.fail ($_ text/compose "Not a parameter type: " (type.to-text headT))))))

(exception: #export (not-existential-type {type Type})
  (type.to-text type))

(def: #export existential
  (Poly Nat)
  (do p.Monad<Parser>
    [headT any]
    (case headT
      (#.Ex ex-id)
      (wrap ex-id)

      _
      (p.fail (ex.construct not-existential-type headT)))))

(def: #export named
  (Poly [Ident Type])
  (do p.Monad<Parser>
    [inputT any]
    (case inputT
      (#.Named name anonymousT)
      (wrap [name anonymousT])

      _
      (p.fail ($_ text/compose "Not a named type: " (type.to-text inputT))))))

(def: #export (recursive poly)
  (All [a] (-> (Poly a) (Poly [Code a])))
  (do p.Monad<Parser>
    [headT any]
    (case (type.un-name headT)
      (#.Apply (#.Named ["lux" "Nothing"] _) (#.UnivQ _ headT'))
      (do @
        [[recT _ output] (|> poly
                             (with-extension .Nothing)
                             (with-extension headT)
                             (local (list headT')))]
        (wrap [recT output]))

      _
      (p.fail ($_ text/compose "Not a recursive type: " (type.to-text headT))))))

(def: #export recursive-self
  (Poly Code)
  (do p.Monad<Parser>
    [env ..env
     headT any]
    (case (type.un-name headT)
      (^multi (#.Apply (#.Named ["lux" "Nothing"] _) (#.Parameter funcT-idx))
              (n/= +0 (adjusted-idx env funcT-idx))
              [(dict.get +0 env) (#.Some [self-type self-call])])
      (wrap self-call)

      _
      (p.fail ($_ text/compose "Not a recursive type: " (type.to-text headT))))))

(def: #export recursive-call
  (Poly Code)
  (do p.Monad<Parser>
    [env ..env
     [funcT argsT] (apply (p.seq any (p.many any)))
     _ (local (list funcT) (var +0))
     allC (let [allT (list& funcT argsT)]
            (|> allT
                (monad.map @ (function.constant parameter))
                (local allT)))]
    (wrap (` ((~+ allC))))))

(def: #export log
  (All [a] (Poly a))
  (do p.Monad<Parser>
    [current any
     #let [_ (log! ($_ text/compose
                       "{" (ident/encode (ident-for ..log)) "} "
                       (type.to-text current)))]]
    (p.fail "LOGGING")))

## [Syntax]
(syntax: #export (poly: {export csr.export}
                   {name s.local-symbol}
                   body)
  (with-gensyms [g!_ g!type g!output]
    (let [g!name (code.symbol ["" name])]
      (wrap (.list (` (syntax: (~+ (csw.export export)) ((~ g!name) {(~ g!type) s.symbol})
                        (do macro.Monad<Meta>
                          [(~ g!type) (macro.find-type-def (~ g!type))]
                          (case (|> (~ body)
                                    (.function ((~ g!_) (~ g!name)))
                                    p.rec
                                    (do p.Monad<Parser> [])
                                    (..run (~ g!type))
                                    (: (.Either .Text .Code)))
                            (#.Left (~ g!output))
                            (macro.fail (~ g!output))

                            (#.Right (~ g!output))
                            ((~' wrap) (.list (~ g!output))))))))))))

(def: (common-poly-name? poly-func)
  (-> Text Bit)
  (text.contains? "?" poly-func))

(def: (derivation-name poly args)
  (-> Text (List Text) (Maybe Text))
  (if (common-poly-name? poly)
    (#.Some (list/fold (text.replace-once "?") poly args))
    #.None))

(syntax: #export (derived: {export csr.export}
                   {?name (p.maybe s.local-symbol)}
                   {[poly-func poly-args] (s.form (p.seq s.symbol (p.many s.symbol)))}
                   {?custom-impl (p.maybe s.any)})
  (do @
    [poly-args (monad.map @ macro.normalize poly-args)
     name (case ?name
            (#.Some name)
            (wrap name)

            (^multi #.None
                    [(derivation-name (product.right poly-func) (list/map product.right poly-args))
                     (#.Some derived-name)])
            (wrap derived-name)

            _
            (p.fail "derived: was given no explicit name, and cannot generate one from given information."))
     #let [impl (case ?custom-impl
                  (#.Some custom-impl)
                  custom-impl

                  #.None
                  (` ((~ (code.symbol poly-func)) (~+ (list/map code.symbol poly-args)))))]]
    (wrap (.list (` (def: (~+ (csw.export export))
                      (~ (code.symbol ["" name]))
                      {#.struct? true}
                      (~ impl)))))))

## [Derivers]
(def: #export (to-code env type)
  (-> Env Type Code)
  (case type
    (#.Primitive name params)
    (` (#.Primitive (~ (code.text name))
                    (list (~+ (list/map (to-code env) params)))))

    (^template [<tag>]
      (<tag> idx)
      (` (<tag> (~ (code.nat idx)))))
    ([#.Var] [#.Ex])

    (#.Parameter idx)
    (let [idx (adjusted-idx env idx)]
      (if (n/= +0 idx)
        (|> (dict.get idx env) maybe.assume product.left (to-code env))
        (` (.$ (~ (code.nat (dec idx)))))))

    (#.Apply (#.Named ["lux" "Nothing"] _) (#.Parameter idx))
    (let [idx (adjusted-idx env idx)]
      (if (n/= +0 idx)
        (|> (dict.get idx env) maybe.assume product.left (to-code env))
        (undefined)))
    
    (^template [<tag>]
      (<tag> left right)
      (` (<tag> (~ (to-code env left))
                (~ (to-code env right)))))
    ([#.Function] [#.Apply])

    (^template [<tag> <macro> <flattener>]
      (<tag> left right)
      (` (<macro> (~+ (list/map (to-code env) (<flattener> type))))))
    ([#.Sum  | type.flatten-variant]
     [#.Product & type.flatten-tuple])

    (#.Named name sub-type)
    (code.symbol name)

    (^template [<tag>]
      (<tag> scope body)
      (` (<tag> (list (~+ (list/map (to-code env) scope)))
                (~ (to-code env body)))))
    ([#.UnivQ] [#.ExQ])
    ))