aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/type/implicit.lux
blob: f8be1a83fd4cfac0dbecc7b4be74021ad3e51759 (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
(.module:
  [lux #*
   [control
    ["." monad (#+ do Monad)]
    ["eq" equivalence]
    ["p" parser]]
   [data
    ["." product]
    ["." maybe]
    ["." number]
    ["." text ("text/." Equivalence<Text>)
     format]
    [collection
     ["." list ("list/." Monad<List> Fold<List>)]
     ["dict" dictionary (#+ Dictionary)]]]
   ["." macro (#+ Monad<Meta>)
    ["." code]
    ["s" syntax (#+ syntax: Syntax)]]
   ["." type
    ["." check (#+ Check)]]])

(def: (find-type-var id env)
  (-> Nat Type-Context (Meta Type))
  (case (list.find (|>> product.left (n/= id))
                   (get@ #.var-bindings env))
    (#.Some [_ (#.Some type)])
    (case type
      (#.Var id')
      (find-type-var id' env)

      _
      (:: Monad<Meta> wrap type))

    (#.Some [_ #.None])
    (macro.fail (format "Unbound type-var " (%n id)))

    #.None
    (macro.fail (format "Unknown type-var " (%n id)))
    ))

(def: (resolve-type var-name)
  (-> Ident (Meta Type))
  (do Monad<Meta>
    [raw-type (macro.find-type var-name)
     compiler macro.get-compiler]
    (case raw-type
      (#.Var id)
      (find-type-var id (get@ #.type-context compiler))

      _
      (wrap raw-type))))

(def: (find-member-type idx sig-type)
  (-> Nat Type (Check Type))
  (case sig-type
    (#.Named _ sig-type')
    (find-member-type idx sig-type')

    (#.Apply arg func)
    (case (type.apply (list arg) func)
      #.None
      (check.fail (format "Cannot apply type " (%type func) " to type " (%type arg)))

      (#.Some sig-type')
      (find-member-type idx sig-type'))

    (#.Product left right)
    (if (n/= +0 idx)
      (:: check.Monad<Check> wrap left)
      (find-member-type (dec idx) right))

    _
    (if (n/= +0 idx)
      (:: check.Monad<Check> wrap sig-type)
      (check.fail (format "Cannot find member type " (%n idx) " for " (%type sig-type))))))

(def: (find-member-name member)
  (-> Ident (Meta Ident))
  (case member
    ["" simple-name]
    (macro.either (do Monad<Meta>
                    [member (macro.normalize member)
                     _ (macro.resolve-tag member)]
                    (wrap member))
                  (do Monad<Meta>
                    [this-module-name macro.current-module-name
                     imp-mods (macro.imported-modules this-module-name)
                     tag-lists (monad.map @ macro.tag-lists imp-mods)
                     #let [tag-lists (|> tag-lists list/join (list/map product.left) list/join)
                           candidates (list.filter (|>> product.right (text/= simple-name))
                                                   tag-lists)]]
                    (case candidates
                      #.Nil
                      (macro.fail (format "Unknown tag: " (%ident member)))
                      
                      (#.Cons winner #.Nil)
                      (wrap winner)
                      
                      _
                      (macro.fail (format "Too many candidate tags: " (%list %ident candidates))))))

    _
    (:: Monad<Meta> wrap member)))

(def: (resolve-member member)
  (-> Ident (Meta [Nat Type]))
  (do Monad<Meta>
    [member (find-member-name member)
     [idx tag-list sig-type] (macro.resolve-tag member)]
    (wrap [idx sig-type])))

(def: (prepare-definitions this-module-name definitions)
  (-> Text (List [Text Definition]) (List [Ident Type]))
  (|> definitions
      (list.filter (function (_ [name [def-type def-anns def-value]])
                     (macro.struct? def-anns)))
      (list/map (function (_ [name [def-type def-anns def-value]])
                  [[this-module-name name] def-type]))))

(def: local-env
  (Meta (List [Ident Type]))
  (do Monad<Meta>
    [local-batches macro.locals
     #let [total-locals (list/fold (function (_ [name type] table)
                                     (dict.put~ name type table))
                                   (: (Dictionary Text Type)
                                      (dict.new text.Hash<Text>))
                                   (list/join local-batches))]]
    (wrap (|> total-locals
              dict.entries
              (list/map (function (_ [name type]) [["" name] type]))))))

(def: local-structs
  (Meta (List [Ident Type]))
  (do Monad<Meta>
    [this-module-name macro.current-module-name
     definitions (macro.definitions this-module-name)]
    (wrap (prepare-definitions this-module-name definitions))))

(def: import-structs
  (Meta (List [Ident Type]))
  (do Monad<Meta>
    [this-module-name macro.current-module-name
     imp-mods (macro.imported-modules this-module-name)
     export-batches (monad.map @ (function (_ imp-mod)
                                   (do @
                                     [exports (macro.exports imp-mod)]
                                     (wrap (prepare-definitions imp-mod exports))))
                               imp-mods)]
    (wrap (list/join export-batches))))

(def: (apply-function-type func arg)
  (-> Type Type (Check Type))
  (case func
    (#.Named _ func')
    (apply-function-type func' arg)

    (#.UnivQ _)
    (do check.Monad<Check>
      [[id var] check.var]
      (apply-function-type (maybe.assume (type.apply (list var) func))
                           arg))

    (#.Function input output)
    (do check.Monad<Check>
      [_ (check.check input arg)]
      (wrap output))

    _
    (check.fail (format "Invalid function type: " (%type func)))))

(def: (concrete-type type)
  (-> Type (Check [(List Nat) Type]))
  (case type
    (#.UnivQ _)
    (do check.Monad<Check>
      [[id var] check.var
       [ids final-output] (concrete-type (maybe.assume (type.apply (list var) type)))]
      (wrap [(#.Cons id ids)
             final-output]))
    
    _
    (:: check.Monad<Check> wrap [(list) type])))

(def: (check-apply member-type input-types output-type)
  (-> Type (List Type) Type (Check []))
  (do check.Monad<Check>
    [member-type' (monad.fold check.Monad<Check>
                              (function (_ input member)
                                (apply-function-type member input))
                              member-type
                              input-types)]
    (check.check output-type member-type')))

(type: #rec Instance
  {#constructor Ident
   #dependencies (List Instance)})

(def: (test-provision provision context dep alts)
  (-> (-> Lux Type-Context Type (Check Instance))
      Type-Context Type (List [Ident Type])
      (Meta (List Instance)))
  (do Monad<Meta>
    [compiler macro.get-compiler]
    (case (|> alts
              (list/map (function (_ [alt-name alt-type])
                          (case (check.run context
                                           (do check.Monad<Check>
                                             [[tvars alt-type] (concrete-type alt-type)
                                              #let [[deps alt-type] (type.flatten-function alt-type)]
                                              _ (check.check dep alt-type)
                                              context' check.context
                                              =deps (monad.map @ (provision compiler context') deps)]
                                             (wrap =deps)))
                            (#.Left error)
                            (list)

                            (#.Right =deps)
                            (list [alt-name =deps]))))
              list/join)
      #.Nil
      (macro.fail (format "No candidates for provisioning: " (%type dep)))

      found
      (wrap found))))

(def: (provision compiler context dep)
  (-> Lux Type-Context Type (Check Instance))
  (case (macro.run compiler
                   ($_ macro.either
                       (do Monad<Meta> [alts local-env] (test-provision provision context dep alts))
                       (do Monad<Meta> [alts local-structs] (test-provision provision context dep alts))
                       (do Monad<Meta> [alts import-structs] (test-provision provision context dep alts))))
    (#.Left error)
    (check.fail error)

    (#.Right candidates)
    (case candidates
      #.Nil
      (check.fail (format "No candidates for provisioning: " (%type dep)))

      (#.Cons winner #.Nil)
      (:: check.Monad<Check> wrap winner)

      _
      (check.fail (format "Too many candidates for provisioning: " (%type dep) " --- " (%list (|>> product.left %ident) candidates))))
    ))

(def: (test-alternatives sig-type member-idx input-types output-type alts)
  (-> Type Nat (List Type) Type (List [Ident Type]) (Meta (List Instance)))
  (do Monad<Meta>
    [compiler macro.get-compiler
     context macro.type-context]
    (case (|> alts
              (list/map (function (_ [alt-name alt-type])
                          (case (check.run context
                                           (do check.Monad<Check>
                                             [[tvars alt-type] (concrete-type alt-type)
                                              #let [[deps alt-type] (type.flatten-function alt-type)]
                                              _ (check.check alt-type sig-type)
                                              member-type (find-member-type member-idx alt-type)
                                              _ (check-apply member-type input-types output-type)
                                              context' check.context
                                              =deps (monad.map @ (provision compiler context') deps)]
                                             (wrap =deps)))
                            (#.Left error)
                            (list)

                            (#.Right =deps)
                            (list [alt-name =deps]))))
              list/join)
      #.Nil
      (macro.fail (format "No alternatives for " (%type (type.function input-types output-type))))

      found
      (wrap found))))

(def: (find-alternatives sig-type member-idx input-types output-type)
  (-> Type Nat (List Type) Type (Meta (List Instance)))
  (let [test (test-alternatives sig-type member-idx input-types output-type)]
    ($_ macro.either
        (do Monad<Meta> [alts local-env] (test alts))
        (do Monad<Meta> [alts local-structs] (test alts))
        (do Monad<Meta> [alts import-structs] (test alts)))))

(def: (var? input)
  (-> Code Bit)
  (case input
    [_ (#.Symbol _)]
    #1

    _
    #0))

(def: (join-pair [l r])
  (All [a] (-> [a a] (List a)))
  (list l r))

(def: (instance$ [constructor dependencies])
  (-> Instance Code)
  (case dependencies
    #.Nil
    (code.symbol constructor)

    _
    (` ((~ (code.symbol constructor)) (~+ (list/map instance$ dependencies))))))

(syntax: #export (:::
                   {member s.symbol}
                   {args (p.alt (p.seq (p.some s.symbol) s.end!)
                                (p.seq (p.some s.any) s.end!))})
  {#.doc (doc "Automatic structure selection (for type-class style polymorphism)."
              "This feature layers type-class style polymorphism on top of Lux's signatures and structures."
              "When calling a polymorphic function, or using a polymorphic constant,"
              "this macro will check the types of the arguments, and the expected type for the whole expression"
              "and it will search in the local scope, the module's scope and the imports' scope"
              "in order to find suitable structures to satisfy those requirements."
              "If a single alternative is found, that one will be used automatically."
              "If no alternative is found, or if more than one alternative is found (ambiguity)"
              "a compile-time error will be raised, to alert the user."
              "Examples:"
              "Nat equivalence"
              (:: number.Equivalence<Nat> = x y)
              (::: = x y)
              "Can optionally add the prefix of the module where the signature was defined."
              (::: eq.= x y)
              "(List Nat) equivalence"
              (::: =
                (list.n/range +1 +10)
                (list.n/range +1 +10))
              "(Functor List) map"
              (::: map inc (list.n/range +0 +9))
              "Caveat emptor: You need to make sure to import the module of any structure you want to use."
              "Otherwise, this macro will not find it.")}
  (case args
    (#.Left [args _])
    (do @
      [[member-idx sig-type] (resolve-member member)
       input-types (monad.map @ resolve-type args)
       output-type macro.expected-type
       chosen-ones (find-alternatives sig-type member-idx input-types output-type)]
      (case chosen-ones
        #.Nil
        (macro.fail (format "No structure option could be found for member: " (%ident member)))

        (#.Cons chosen #.Nil)
        (wrap (list (` (:: (~ (instance$ chosen))
                           (~ (code.local-symbol (product.right member)))
                           (~+ (list/map code.symbol args))))))

        _
        (macro.fail (format "Too many options available: "
                            (|> chosen-ones
                                (list/map (|>> product.left %ident))
                                (text.join-with ", "))
                            " --- for type: " (%type sig-type)))))

    (#.Right [args _])
    (do @
      [labels (|> (macro.gensym "") (list.repeat (list.size args)) (monad.seq @))]
      (wrap (list (` (let [(~+ (|> (list.zip2 labels args) (list/map join-pair) list/join))]
                       (..::: (~ (code.symbol member)) (~+ labels)))))))
    ))