aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/meta/compiler/language/lux/phase/synthesis/when.lux
blob: 080905e7f9a56ebf19ca74a6f6ad46631dad1cbe (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
... This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
... If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.

(.require
 [library
  [lux (.except Pattern)
   [abstract
    [equivalence (.only Equivalence)]
    ["[0]" monad (.only do)]]
   [control
    ["[0]" pipe]]
   [data
    ["[0]" product]
    ["[0]" bit (.use "[1]#[0]" equivalence)]
    ["[0]" text (.use "[1]#[0]" equivalence)]
    [collection
     ["[0]" list (.use "[1]#[0]" functor mix monoid)]
     ["[0]" set (.only Set)]]]
   [math
    [number
     ["n" nat]
     ["[0]" i64]
     ["[0]" frac]]]
   [meta
    [macro
     ["^" pattern]]]]]
 ["[0]" ///
  [//
   ["[0]" phase (.use "[1]#[0]" monad)]
   ["[0]" analysis (.only Match)
    ["[2][0]" simple]
    ["[2][0]" complex]
    ["[2][0]" pattern (.only Pattern)]]
   ["/" synthesis (.only Path Operation Phase)
    ["[1][0]" access (.only)
     ["[2][0]" side]
     ["[2][0]" member (.only Member)]]]
   [///
    ["[1][0]" reference (.only)
     ["[1]/[0]" variable (.only Register Variable)]]
    [meta
     [archive (.only Archive)]]]]])

(def clean_up
  (-> Path
      Path)
  (|>> {/.#Seq {/.#Pop}}))

(def (path' pattern end? thenC)
  (-> Pattern Bit (Operation Path)
      (Operation Path))
  (when pattern
    {///pattern.#Simple simple}
    (when simple
      {///simple.#Unit}
      thenC

      {///simple.#Bit when}
      (phase#each (function (_ then)
                    {/.#Bit_Fork when then {.#None}})
                  thenC)

      (^.with_template [<from> <to> <conversion>]
        [{<from> test}
         (phase#each (function (_ then)
                       {<to> [(<conversion> test) then] (list)})
                     thenC)])
      ([///simple.#Nat  /.#I64_Fork .i64]
       [///simple.#Int  /.#I64_Fork .i64]
       [///simple.#Rev  /.#I64_Fork .i64]
       [///simple.#Frac /.#F64_Fork |>]
       [///simple.#Text /.#Text_Fork |>]))

    {///pattern.#Bind register}
    (<| (of phase.monad each (|>> {/.#Seq {/.#Bind register}}))
        /.with_new_local
        thenC)

    {///pattern.#Complex {///complex.#Variant [lefts right? value_pattern]}}
    (<| (phase#each (|>> {/.#Seq {/.#Access {/access.#Side [/side.#lefts lefts
                                                            /side.#right? right?]}}}))
        (path' value_pattern end?)
        (pipe.if [(pipe.new (not end?) [])]
          [(phase#each ..clean_up)]
          [])
        thenC)

    {///pattern.#Complex {///complex.#Tuple tuple}}
    (let [tuple::last (-- (list.size tuple))]
      (list#mix (function (_ [tuple::lefts tuple::member] nextC)
                  (.when tuple::member
                    {///pattern.#Simple {///simple.#Unit}}
                    nextC

                    _
                    (let [right? (n.= tuple::last tuple::lefts)
                          end?' (and end? right?)]
                      (<| (phase#each (|>> {/.#Seq {/.#Access {/access.#Member [/member.#lefts (if right?
                                                                                                 (-- tuple::lefts)
                                                                                                 tuple::lefts)
                                                                                /member.#right? right?]}}}))
                          (path' tuple::member end?')
                          (pipe.if [(pipe.new (not end?') [])]
                            [(phase#each ..clean_up)]
                            [])
                          nextC))))
                thenC
                (list.reversed (list.enumeration tuple))))
    ))

(def (path archive synthesize pattern bodyA)
  (-> Archive Phase Pattern analysis.Term
      (Operation Path))
  (path' pattern true (phase#each (|>> {/.#Then}) (synthesize archive bodyA))))

(def (weave_branch weave equivalence [new_test new_then] [[old_test old_then] old_tail])
  (All (_ of)
    (-> (-> Path Path Path) (Equivalence of) [of Path] (/.Fork of Path)
        (/.Fork of Path)))
  (if (of equivalence = new_test old_test)
    [[old_test (weave new_then old_then)] old_tail]
    [[old_test old_then]
     (when old_tail
       {.#End}
       (list [new_test new_then])
       
       {.#Item old_item}
       {.#Item (weave_branch weave equivalence [new_test new_then] old_item)})]))

(def (weave_fork weave equivalence new_fork old_fork)
  (All (_ of)
    (-> (-> Path Path Path) (Equivalence of) (/.Fork of Path) (/.Fork of Path)
        (/.Fork of Path)))
  (list#mix (..weave_branch weave equivalence) old_fork {.#Item new_fork}))

(def (weave new old)
  (-> Path Path
      Path)
  (with_expansions [<default> (these {/.#Alt old new})]
    (when [new old]
      [_
       {/.#Alt old_left old_right}]
      {/.#Alt old_left
              (weave new old_right)}

      [{/.#Seq preN postN}
       {/.#Seq preO postO}]
      (when (weave preN preO)
        {/.#Alt _}
        <default>

        woven
        {/.#Seq woven (weave postN postO)})

      [{/.#Pop} {/.#Pop}]
      old

      [{/.#Bit_Fork new_when new_then new_else}
       {/.#Bit_Fork old_when old_then old_else}]
      (if (bit#= new_when old_when)
        {/.#Bit_Fork old_when
                     (weave new_then old_then)
                     (when [new_else old_else]
                       [{.#None} {.#None}]
                       {.#None}

                       (^.or [{.#Some woven_then} {.#None}]
                             [{.#None} {.#Some woven_then}])
                       {.#Some woven_then}

                       [{.#Some new_else} {.#Some old_else}]
                       {.#Some (weave new_else old_else)})}
        {/.#Bit_Fork old_when
                     (when new_else
                       {.#None}
                       old_then

                       {.#Some new_else}
                       (weave new_else old_then))
                     {.#Some (when old_else
                               {.#None}
                               new_then

                               {.#Some old_else}
                               (weave new_then old_else))}})

      (^.with_template [<tag> <equivalence>]
        [[{<tag> new_fork} {<tag> old_fork}]
         {<tag> (..weave_fork weave <equivalence> new_fork old_fork)}])
      ([/.#I64_Fork i64.equivalence]
       [/.#F64_Fork frac.equivalence]
       [/.#Text_Fork text.equivalence])
      
      (^.with_template [<access> <side> <lefts> <right?>]
        [[{/.#Access {<access> [<lefts> newL <right?> <side>]}}
          {/.#Access {<access> [<lefts> oldL <right?> <side>]}}]
         (if (n.= newL oldL)
           old
           <default>)])
      ([/access.#Side .false /side.#lefts /side.#right?]
       [/access.#Side .true /side.#lefts /side.#right?]

       [/access.#Member .false /member.#lefts /member.#right?]
       [/access.#Member .true /member.#lefts /member.#right?])

      [{/.#Bind newR} {/.#Bind oldR}]
      (if (n.= newR oldR)
        old
        <default>)

      _
      <default>)))

(def (get patterns @selection)
  (-> (///complex.Tuple Pattern) Register
      (List Member))
  (loop (again [lefts 0
                patterns patterns])
    (with_expansions [<failure> (these (list))
                      <continue> (these (again (++ lefts)
                                               tail))
                      <member> (these (let [right? (list.empty? tail)]
                                        [/member.#lefts (if right?
                                                          (-- lefts)
                                                          lefts)
                                         /member.#right? right?]))]
      (when patterns
        {.#End}
        <failure>

        {.#Item head tail}
        (when head
          {///pattern.#Simple {///simple.#Unit}}
          <continue>
          
          {///pattern.#Bind register}
          (if (n.= @selection register)
            (list <member>)
            <continue>)

          {///pattern.#Complex {///complex.#Tuple sub_patterns}}
          (when (get sub_patterns @selection)
            {.#End}
            <continue>

            sub_members
            (list.partial <member> sub_members))
          
          _
          <failure>)))))

(def .public (synthesize_when synthesize @ archive input [[headP headA] tailPA+])
  (-> Phase Location Archive /.Term Match
      (Operation /.Term))
  (do [! phase.monad]
    [headSP (path archive synthesize headP headA)
     tailSP+ (monad.each ! (product.uncurried (path archive synthesize)) tailPA+)]
    (in (/.branch/when @ [input (list#mix weave headSP tailSP+)]))))

(def !masking
  (template (_ <@> <variable> <output>)
    [[[{///pattern.#Bind <variable>}
       [<@> {analysis.#Reference (///reference.local <output>)}]]
      (list)]]))

(def .public (synthesize_exec synthesize @ archive before after)
  (-> Phase Location Archive /.Term analysis.Term
      (Operation /.Term))
  (do phase.monad
    [after (synthesize archive after)]
    (in (/.branch/exec @ [before after]))))

(def .public (synthesize_let synthesize @ archive input @variable body)
  (-> Phase Location Archive /.Term Register analysis.Term
      (Operation /.Term))
  (do phase.monad
    [body (/.with_new_local
            (synthesize archive body))]
    (in (/.branch/let @ [[@variable input] body]))))

(def .public (synthesize_masking synthesize @ archive input @variable @output)
  (-> Phase Location Archive /.Term Register Register
      (Operation /.Term))
  (if (n.= @variable @output)
    (phase#in input)
    (..synthesize_let synthesize @ archive input @variable [@ {analysis.#Reference (///reference.local @output)}])))

(def .public (synthesize_if synthesize @ archive test then else)
  (-> Phase Location Archive /.Term analysis.Term analysis.Term
      (Operation /.Term))
  (do phase.monad
    [then (synthesize archive then)
     else (synthesize archive else)]
    (in (/.branch/if @ [test then else]))))

(def !get
  (template (_ <@> <patterns> <output>)
    [[[(///pattern.tuple <patterns>)
       [<@> {analysis.#Reference (///reference.local <output>)}]]
      (.list)]]))

(def .public (synthesize_get synthesize @ archive input patterns @member)
  (-> Phase Location Archive /.Term (///complex.Tuple Pattern) Register
      (Operation /.Term))
  (when (..get patterns @member)
    {.#End}
    (..synthesize_when synthesize @ archive input (!get @ patterns @member))

    path
    (phase#in (when input
                (/.branch/get @ [sub_path sub_input])
                (/.branch/get @ [(list#composite sub_path path) sub_input])

                _
                (/.branch/get @ [path input])))))

(def .public (synthesize @ synthesize^ [headB tailB+] archive inputA)
  (-> Location Phase Match
      Phase)
  (do [! phase.monad]
    [inputS (synthesize^ archive inputA)]
    (when [headB tailB+]
      (!masking @ @variable @output)
      (..synthesize_masking synthesize^ @ archive inputS @variable @output)

      [[(///pattern.unit) body]
       {.#End}]
      (when inputA
        (^.or [@ {analysis.#Simple _}]
              [@ {analysis.#Structure _}]
              [@ {analysis.#Reference _}])
        (synthesize^ archive body)

        _
        (..synthesize_exec synthesize^ @ archive inputS body))

      [[{///pattern.#Bind @variable} body]
       {.#End}]
      (..synthesize_let synthesize^ @ archive inputS @variable body)
      
      (^.or [[(///pattern.bit .true) then]
             (list [(///pattern.bit .false) else])]
            [[(///pattern.bit .true) then]
             (list [(///pattern.unit) else])]

            [[(///pattern.bit .false) else]
             (list [(///pattern.bit .true) then])]
            [[(///pattern.bit .false) else]
             (list [(///pattern.unit) then])])
      (..synthesize_if synthesize^ @ archive inputS then else)
      
      (!get @ patterns @member)
      (..synthesize_get synthesize^ @ archive inputS patterns @member)
      
      match
      (..synthesize_when synthesize^ @ archive inputS match))))

(def .public (count_pops path)
  (-> Path
      [Nat Path])
  (when path
    (/.path/seq {/.#Pop} path')
    (let [[pops post_pops] (count_pops path')]
      [(++ pops) post_pops])

    _
    [0 path]))

(def .public pattern_matching_error
  "Invalid expression for pattern-matching.")

(type .public Storage
  (Record
   [#bindings (Set Register)
    #dependencies (Set Variable)]))

(def empty
  Storage
  [#bindings (set.empty n.hash)
   #dependencies (set.empty ///reference/variable.hash)])

... TODO: Use this to declare all local variables at the beginning of
... script functions.
... That way, it should be possible to do cheap "let" expressions,
... since the variable will exist beforehand, so no closure will need
... to be created for it.
... Apply this trick to JS, Python et al.
(def .public (storage path)
  (-> Path
      Storage)
  (loop (for_path [path path
                   path_storage ..empty])
    (when path
      (^.or {/.#Pop}
            {/.#Access Access})
      path_storage

      (/.path/bind register)
      (revised #bindings (set.has register)
               path_storage)

      {/.#Bit_Fork _ default otherwise}
      (|> (when otherwise
            {.#None}
            path_storage
            
            {.#Some otherwise}
            (for_path otherwise path_storage))
          (for_path default))

      (^.or {/.#I64_Fork forks}
            {/.#F64_Fork forks}
            {/.#Text_Fork forks})
      (|> {.#Item forks}
          (list#each product.right)
          (list#mix for_path path_storage))

      (^.or (/.path/seq left right)
            (/.path/alt left right))
      (list#mix for_path path_storage (list left right))

      (/.path/then bodyS)
      (loop (for_synthesis [bodyS bodyS
                            synthesis_storage path_storage])
        (when bodyS
          (^.or [@ {/.#Simple _}]
                (/.constant @ _))
          synthesis_storage
          
          (/.variant @ [lefts right? valueS])
          (for_synthesis valueS synthesis_storage)

          (/.tuple @ members)
          (list#mix for_synthesis synthesis_storage members)

          [@ {/.#Reference {///reference.#Variable {///reference/variable.#Local register}}}]
          (if (set.member? (the #bindings synthesis_storage) register)
            synthesis_storage
            (revised #dependencies (set.has {///reference/variable.#Local register}) synthesis_storage))

          [@ {/.#Reference {///reference.#Variable var}}]
          (revised #dependencies (set.has var) synthesis_storage)

          (/.function/apply @ [functionS argsS])
          (list#mix for_synthesis synthesis_storage {.#Item functionS argsS})

          (/.function/abstraction @ [environment arity bodyS])
          (list#mix for_synthesis synthesis_storage environment)

          (/.branch/when @ [inputS pathS])
          (revised #dependencies
                   (set.union (the #dependencies (for_path pathS synthesis_storage)))
                   (for_synthesis inputS synthesis_storage))

          (/.branch/exec @ [before after])
          (list#mix for_synthesis synthesis_storage (list before after))

          (/.branch/let @ [[register inputS] exprS])
          (revised #dependencies
                   (set.union (|> synthesis_storage
                                  (revised #bindings (set.has register))
                                  (for_synthesis exprS)
                                  (the #dependencies)))
                   (for_synthesis inputS synthesis_storage))

          (/.branch/if @ [testS thenS elseS])
          (list#mix for_synthesis synthesis_storage (list testS thenS elseS))

          (/.branch/get @ [access whole])
          (for_synthesis whole synthesis_storage)

          (/.loop/scope @ [start initsS+ iterationS])
          (revised #dependencies
                   (set.union (|> synthesis_storage
                                  (revised #bindings (set.union (|> initsS+
                                                                    list.enumeration
                                                                    (list#each (|>> product.left (n.+ start)))
                                                                    (set.of_list n.hash))))
                                  (for_synthesis iterationS)
                                  (the #dependencies)))
                   (list#mix for_synthesis synthesis_storage initsS+))

          (/.loop/again @ replacementsS+)
          (list#mix for_synthesis synthesis_storage replacementsS+)

          [@ {/.#Extension [extension argsS]}]
          (list#mix for_synthesis synthesis_storage argsS)))
      )))