aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/parser/lux/meta/type.lux
blob: 1dec4fbb1cc17f7cca3f6a33d9640830785c78ef (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
(.require
 [library
  [lux (.except function local parameter)
   [abstract
    ["[0]" monad (.only do)]]
   [control
    ["//" parser]
    ["[0]" try (.only Try)]
    ["[0]" exception (.only Exception)]
    ["[0]" function]]
   [data
    ["[0]" text (.use "[1]#[0]" monoid)
     ["%" \\format (.only format)]]
    [collection
     ["[0]" list (.use "[1]#[0]" functor)]
     ["[0]" dictionary (.only Dictionary)]]]
   [math
    [number
     ["n" nat (.use "[1]#[0]" decimal)]]]
   [meta
    ["[0]" code]
    [macro
     ["^" pattern]]]]]
 [\\library
  ["[0]" / (.use "[1]#[0]" equivalence)
   ["[0]" check]]])

(def |recursion_dummy|
  (template (|recursion_dummy|)
    [{.#Primitive "" {.#End}}]))

(with_template [<name>]
  [(exception.def .public (<name> type)
     (Exception Type)
     (exception.report
      (list ["Type" (%.type type)])))]

  [not_existential]
  [not_recursive]
  [not_named]
  [not_parameter]
  [unknown_parameter]
  [not_function]
  [not_application]
  [not_polymorphic]
  [not_variant]
  [not_tuple]
  )

(with_template [<name>]
  [(exception.def .public (<name> [expected actual])
     (Exception [Type Type])
     (exception.report
      (list ["Expected" (%.type expected)]
            ["Actual" (%.type actual)])))]

  [types_do_not_match]
  [wrong_parameter]
  )

(exception.def .public empty_input)

(exception.def .public (unconsumed_input remaining)
  (Exception (List Type))
  (exception.report
   (list ["Types" (|> remaining
                      (list#each (|>> %.type (format text.new_line "* ")))
                      (text.interposed ""))])))

(type .public Env
  (Dictionary Nat [Type Code]))

(type .public (Parser a)
  (//.Parser [Env (List Type)] a))

(def .public fresh
  Env
  (dictionary.empty n.hash))

(def (result' env poly types)
  (All (_ a) (-> Env (Parser a) (List Type) (Try a)))
  (when (//.result poly [env types])
    {try.#Failure error}
    {try.#Failure error}

    {try.#Success [[env' remaining] output]}
    (when remaining
      {.#End}
      {try.#Success output}

      _
      (exception.except ..unconsumed_input remaining))))

(def .public (result poly type)
  (All (_ a) (-> (Parser a) Type (Try a)))
  (result' ..fresh poly (list type)))

(def .public 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])
    (when (//.result poly [temp inputs])
      {try.#Failure error}
      {try.#Failure error}

      {try.#Success [[_ remaining] output]}
      {try.#Success [[env remaining] output]})))

(def .public next
  (Parser Type)
  (.function (_ [env inputs])
    (when inputs
      {.#End}
      (exception.except ..empty_input [])

      {.#Item headT tail}
      {try.#Success [[env inputs] headT]})))

(def .public any
  (Parser Type)
  (.function (_ [env inputs])
    (when inputs
      {.#End}
      (exception.except ..empty_input [])

      {.#Item headT tail}
      {try.#Success [[env tail] headT]})))

(def .public (local types poly)
  (All (_ a) (-> (List Type) (Parser a) (Parser a)))
  (.function (_ [env pass_through])
    (when (result' env poly types)
      {try.#Failure error}
      {try.#Failure error}

      {try.#Success output}
      {try.#Success [[env pass_through] output]})))

(def (label idx)
  (-> Nat Code)
  (code.local (all text#composite "label" text.tab (n#encoded idx))))

(def .public (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)]
      (when (//.result poly
                       [(dictionary.has current_id [type g!var] env)
                        inputs])
        {try.#Failure error}
        {try.#Failure error}

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

(with_template [<name> <flattener> <exception>]
  [(`` (def .public (<name> poly)
         (All (_ a) (-> (Parser a) (Parser a)))
         (do //.monad
           [headT ..any]
           (let [members (<flattener> (/.anonymous headT))]
             (if (n.> 1 (list.size members))
               (local members poly)
               (//.failure (exception.error <exception> headT)))))))]

  [variant /.flat_variant ..not_variant]
  [tuple   /.flat_tuple   ..not_tuple]
  )

(def polymorphic'
  (Parser [Nat Type])
  (do //.monad
    [headT any
     .let [[num_arg bodyT] (/.flat_univ_q (/.anonymous headT))]]
    (if (n.= 0 num_arg)
      (//.failure (exception.error ..not_polymorphic headT))
      (in [num_arg bodyT]))))

(def .public (polymorphic poly)
  (All (_ a) (-> (Parser a) (Parser [Code (List Code) a])))
  (do [! //.monad]
    [headT any
     funcI (at ! each dictionary.size ..env)
     [num_args non_poly] (local (list headT) ..polymorphic')
     env ..env
     .let [funcL (label funcI)
           [all_varsL env'] (loop (again [current_arg 0
                                          env' env
                                          all_varsL (is (List Code) (list))])
                              (if (n.< num_args current_arg)
                                (if (n.= 0 current_arg)
                                  (let [varL (label (++ funcI))]
                                    (again (++ current_arg)
                                           (|> env'
                                               (dictionary.has funcI [headT funcL])
                                               (dictionary.has (++ funcI) [{.#Parameter (++ funcI)} varL]))
                                           {.#Item varL all_varsL}))
                                  (let [partialI (|> current_arg (n.* 2) (n.+ funcI))
                                        partial_varI (++ partialI)
                                        partial_varL (label partial_varI)
                                        partialC (` ((, funcL) (,* (|> (list.indices num_args)
                                                                       (list#each (|>> (n.* 2) ++ (n.+ funcI) label))
                                                                       list.reversed))))]
                                    (again (++ current_arg)
                                           (|> env'
                                               (dictionary.has partialI [(|recursion_dummy|) partialC])
                                               (dictionary.has partial_varI [{.#Parameter partial_varI} partial_varL]))
                                           {.#Item partial_varL all_varsL})))
                                [all_varsL env']))]]
    (<| (with_env env')
        (local (list non_poly))
        (do !
          [output poly]
          (in [funcL all_varsL output])))))

(def .public (function in_poly out_poly)
  (All (_ i o) (-> (Parser i) (Parser o) (Parser [i o])))
  (do //.monad
    [headT any
     .let [[inputsT outputT] (/.flat_function (/.anonymous headT))]]
    (if (n.> 0 (list.size inputsT))
      (//.and (local inputsT in_poly)
              (local (list outputT) out_poly))
      (//.failure (exception.error ..not_function headT)))))

(def .public (applied poly)
  (All (_ a) (-> (Parser a) (Parser a)))
  (do //.monad
    [headT any
     .let [[funcT paramsT] (/.flat_application (/.anonymous headT))]]
    (if (n.= 0 (list.size paramsT))
      (//.failure (exception.error ..not_application headT))
      (..local {.#Item funcT paramsT} poly))))

(with_template [<name> <test>]
  [(def .public (<name> expected)
     (-> Type (Parser Any))
     (do //.monad
       [actual any]
       (if (<test> expected actual)
         (in [])
         (//.failure (exception.error ..types_do_not_match [expected actual])))))]

  [exactly /#=]
  [sub     check.subsumes?]
  [super   (function.flipped check.subsumes?)]
  )

(def .public (argument 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 -- (n.- parameter_level) (n.* 2) (n.+ parameter_idx))))

(def .public parameter
  (Parser Code)
  (do //.monad
    [env ..env
     headT any]
    (when headT
      {.#Parameter idx}
      (when (dictionary.value (..argument env idx) env)
        {.#Some [poly_type poly_code]}
        (in poly_code)

        {.#None}
        (//.failure (exception.error ..unknown_parameter headT)))

      _
      (//.failure (exception.error ..not_parameter headT)))))

(def .public (this_parameter id)
  (-> Nat (Parser Any))
  (do //.monad
    [env ..env
     headT any]
    (when headT
      {.#Parameter idx}
      (if (n.= id (..argument env idx))
        (in [])
        (//.failure (exception.error ..wrong_parameter [{.#Parameter id} headT])))

      _
      (//.failure (exception.error ..not_parameter headT)))))

(def .public existential
  (Parser Nat)
  (do //.monad
    [headT any]
    (when headT
      {.#Ex ex_id}
      (in ex_id)

      _
      (//.failure (exception.error ..not_existential headT)))))

(def .public named
  (Parser [Symbol Type])
  (do //.monad
    [inputT any]
    (when inputT
      {.#Named name anonymousT}
      (in [name anonymousT])

      _
      (//.failure (exception.error ..not_named inputT)))))

(def .public (recursive poly)
  (All (_ a) (-> (Parser a) (Parser [Code a])))
  (do [! //.monad]
    [headT any]
    (when (/.anonymous headT)
      {.#Apply (|recursion_dummy|) {.#UnivQ _ headT'}}
      (do !
        [[recT _ output] (|> poly
                             (with_extension (|recursion_dummy|))
                             (with_extension headT)
                             (local (list headT')))]
        (in [recT output]))

      _
      (//.failure (exception.error ..not_recursive headT)))))

(def .public recursive_self
  (Parser Code)
  (do //.monad
    [env ..env
     headT any]
    (when (/.anonymous headT)
      (^.multi {.#Apply (|recursion_dummy|) {.#Parameter funcT_idx}}
               (n.= 0 (..argument env funcT_idx))
               [(dictionary.value 0 env) {.#Some [self_type self_call]}])
      (in self_call)

      _
      (//.failure (exception.error ..not_recursive headT)))))

(def .public recursive_call
  (Parser Code)
  (do [! //.monad]
    [env ..env
     [funcT argsT] (..applied (//.and any (//.many any)))
     _ (local (list funcT) (..this_parameter 0))
     allC (let [allT (list.partial funcT argsT)]
            (|> allT
                (monad.each ! (function.constant ..parameter))
                (local allT)))]
    (in (` ((,* allC))))))