aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/control/parser/type.lux
blob: 6e42cad87db60f6cb2fa0e9c1e0d8d66a81f69a8 (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
(.module:
  [lux (#- function log!)
   [abstract
    ["." monad (#+ do)]]
   [control
    ["." try (#+ Try)]
    ["." exception (#+ exception:)]
    ["." function]]
   [data
    ["." name ("#@." codec)]
    [number
     ["." nat ("#@." decimal)]]
    ["." text ("#@." monoid)
     ["%" format (#+ format)]]
    [collection
     ["." list ("#@." functor)]
     ["." dictionary (#+ Dictionary)]]]
   [macro
    ["." code]]
   ["." type ("#@." equivalence)
    ["." check]]]
  ["." //])

(template [<name>]
  [(exception: #export (<name> {type Type})
     (exception.report
      ["Type" (%.type type)]))]

  [not-existential]
  [not-recursive]
  [not-named]
  [not-parameter]
  [unknown-parameter]
  [not-function]
  [not-application]
  [not-polymorphic]
  [not-variant]
  [not-tuple]
  )

(template [<name>]
  [(exception: #export (<name> {expected Type} {actual Type})
     (exception.report
      ["Expected" (%.type expected)]
      ["Actual" (%.type actual)]))]

  [types-do-not-match]
  [wrong-parameter]
  )

(exception: #export (unconsumed {remaining (List Type)})
  (exception.report
   ["Types" (|> remaining
                (list@map (|>> %.type (format text.new-line "* ")))
                (text.join-with ""))]))

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

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

(def: #export fresh Env (dictionary.new nat.hash))

(def: (run' env types poly)
  (All [a] (-> Env (List Type) (Parser a) (Try a)))
  (case (//.run poly [env types])
    (#try.Failure error)
    (#try.Failure error)

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

      _
      (exception.throw unconsumed remaining))))

(def: #export (run type poly)
  (All [a] (-> Type (Parser a) (Try a)))
  (run' fresh (list type) poly))

(def: #export env
  (Parser Env)
  (.function (_ [env inputs])
    (#try.Success [[env inputs] env])))

(def: (with-env temp poly)
  (All [a] (-> Env (Parser a) (Parser a)))
  (.function (_ [env inputs])
    (case (//.run poly [temp inputs])
      (#try.Failure error)
      (#try.Failure error)

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

(def: #export peek
  (Parser Type)
  (.function (_ [env inputs])
    (case inputs
      #.Nil
      (#try.Failure "Empty stream of types.")

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

(def: #export any
  (Parser Type)
  (.function (_ [env inputs])
    (case inputs
      #.Nil
      (#try.Failure "Empty stream of types.")

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

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

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

(def: (label idx)
  (-> Nat Code)
  (code.local-identifier ($_ text@compose "label" text.tab (nat@encode idx))))

(def: #export (with-extension type poly)
  (All [a] (-> Type (Parser a) (Parser [Code a])))
  (.function (_ [env inputs])
    (let [current-id (dictionary.size env)
          g!var (label current-id)]
      (case (//.run poly
                    [(dictionary.put current-id [type g!var] env)
                     inputs])
        (#try.Failure error)
        (#try.Failure error)

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

(template [<name> <flattener> <tag> <exception>]
  [(def: #export (<name> poly)
     (All [a] (-> (Parser a) (Parser a)))
     (do //.monad
       [headT any]
       (let [members (<flattener> (type.un-name headT))]
         (if (n/> 1 (list.size members))
           (local members poly)
           (//.fail (exception.construct <exception> headT))))))]

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

(def: polymorphic'
  (Parser [Nat Type])
  (do //.monad
    [headT any
     #let [[num-arg bodyT] (type.flatten-univ-q (type.un-name headT))]]
    (if (n/= 0 num-arg)
      (//.fail (exception.construct not-polymorphic headT))
      (wrap [num-arg bodyT]))))

(def: #export (polymorphic poly)
  (All [a] (-> (Parser a) (Parser [Code (List Code) a])))
  (do //.monad
    [headT any
     funcI (:: @ map dictionary.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'
                                               (dictionary.put funcI [headT funcL])
                                               (dictionary.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.indices num-args)
                                                                       (list@map (|>> (n/* 2) inc (n/+ funcI) label))
                                                                       list.reverse))))]
                                    (recur (inc current-arg)
                                           (|> env'
                                               (dictionary.put partialI [.Nothing partialC])
                                               (dictionary.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] (-> (Parser i) (Parser o) (Parser [i o])))
  (do //.monad
    [headT any
     #let [[inputsT outputT] (type.flatten-function (type.un-name headT))]]
    (if (n/> 0 (list.size inputsT))
      (//.and (local inputsT in-poly)
              (local (list outputT) out-poly))
      (//.fail (exception.construct not-function headT)))))

(def: #export (apply poly)
  (All [a] (-> (Parser a) (Parser a)))
  (do //.monad
    [headT any
     #let [[funcT paramsT] (type.flatten-application (type.un-name headT))]]
    (if (n/= 0 (list.size paramsT))
      (//.fail (exception.construct not-application headT))
      (local (#.Cons funcT paramsT) poly))))

(template [<name> <test>]
  [(def: #export (<name> expected)
     (-> Type (Parser Any))
     (do //.monad
       [actual any]
       (if (<test> expected actual)
         (wrap [])
         (//.fail (exception.construct types-do-not-match [expected actual])))))]

  [exactly type@=]
  [sub     check.checks?]
  [super   (function.flip check.checks?)]
  )

(def: #export (adjusted-idx env idx)
  (-> Env Nat Nat)
  (let [env-level (n// 2 (dictionary.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
  (Parser Code)
  (do //.monad
    [env ..env
     headT any]
    (case headT
      (#.Parameter idx)
      (case (dictionary.get (adjusted-idx env idx) env)
        (#.Some [poly-type poly-code])
        (wrap poly-code)

        #.None
        (//.fail (exception.construct unknown-parameter headT)))

      _
      (//.fail (exception.construct not-parameter headT)))))

(def: #export (parameter! id)
  (-> Nat (Parser Any))
  (do //.monad
    [env ..env
     headT any]
    (case headT
      (#.Parameter idx)
      (if (n/= id (adjusted-idx env idx))
        (wrap [])
        (//.fail (exception.construct wrong-parameter [(#.Parameter id) headT])))

      _
      (//.fail (exception.construct not-parameter headT)))))

(def: #export existential
  (Parser Nat)
  (do //.monad
    [headT any]
    (case headT
      (#.Ex ex-id)
      (wrap ex-id)

      _
      (//.fail (exception.construct not-existential headT)))))

(def: #export named
  (Parser [Name Type])
  (do //.monad
    [inputT any]
    (case inputT
      (#.Named name anonymousT)
      (wrap [name anonymousT])

      _
      (//.fail (exception.construct not-named inputT)))))

(def: #export (recursive poly)
  (All [a] (-> (Parser a) (Parser [Code a])))
  (do //.monad
    [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]))

      _
      (//.fail (exception.construct not-recursive headT)))))

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

      _
      (//.fail (exception.construct not-recursive headT)))))

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

(def: #export log!
  (All [a] (Parser a))
  (do //.monad
    [current any
     #let [_ (.log! ($_ text@compose
                        "{" (name@encode (name-of ..log)) "} "
                        (%.type current)))]]
    (//.fail "LOGGING")))