aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/meta/compiler/language/lux/phase/synthesis/variable.lux
blob: 53d9b2117d3b9591e4c263c7a664de4d4e538738 (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
... 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)
   [abstract
    ["[0]" monad (.only do)]]
   [control
    ["[0]" maybe (.use "[1]#[0]" functor)]
    ["[0]" try (.only Try)]
    ["[0]" exception (.only Exception)]]
   [data
    ["[0]" product]
    ["[0]" text (.only)
     ["%" \\format]]
    [collection
     ["[0]" dictionary (.only Dictionary)]
     ["[0]" list (.use "[1]#[0]" functor mix)]
     ["[0]" set]]]
   [math
    [number
     ["n" nat]]]
   [meta
    [macro
     ["^" pattern]]]]]
 [////
  ["[0]" analysis (.only)
   ["[1]/[0]" complex]]
  ["/" synthesis (.only Path)
   ["[1][0]" access]]
  [///
   [arity (.only Arity)]
   ["[0]" reference (.only)
    ["[0]" variable (.only Register Variable)]]]])

(def (prune redundant register)
  (-> Register Register
      Register)
  (if (n.> redundant register)
    (-- register)
    register))

(type (Remover a)
  (-> Register
      (-> a a)))

(def (remove_local_from_path remove_local redundant)
  (-> (Remover /.Term)
      (Remover Path))
  (function (again path)
    (when path
      {/.#Seq {/.#Bind register}
              post}
      (if (n.= redundant register)
        (again post)
        {/.#Seq {/.#Bind (if (n.> redundant register)
                           (-- register)
                           register)}
                (again post)})

      (^.or {/.#Seq {/.#Access {/access.#Member member}}
                    {/.#Seq {/.#Bind register}
                            post}}
            ... This alternative form should never occur in practice.
            ... Yet, it is "technically" possible to construct it.
            {/.#Seq {/.#Seq {/.#Access {/access.#Member member}}
                            {/.#Bind register}}
                    post})
      (if (n.= redundant register)
        (again post)
        {/.#Seq {/.#Access {/access.#Member member}}
                {/.#Seq {/.#Bind (if (n.> redundant register)
                                   (-- register)
                                   register)}
                        (again post)}})

      (^.with_template [<tag>]
        [{<tag> left right}
         {<tag> (again left) (again right)}])
      ([/.#Seq]
       [/.#Alt])

      {/.#Bit_Fork when then else}
      {/.#Bit_Fork when (again then) (maybe#each again else)}

      (^.with_template [<tag>]
        [{<tag> [[test then] tail]}
         {<tag> [[test (again then)]
                 (list#each (function (_ [test' then'])
                              [test' (again then')])
                            tail)]}])
      ([/.#I64_Fork]
       [/.#F64_Fork]
       [/.#Text_Fork])
      
      (^.or {/.#Pop}
            {/.#Access _})
      path

      {/.#Bind register}
      (undefined)
      
      {/.#Then then}
      {/.#Then (remove_local redundant then)}
      )))

(def (remove_local_from_variable redundant variable)
  (Remover Variable)
  (when variable
    {variable.#Local register}
    {variable.#Local (..prune redundant register)}
    
    {variable.#Foreign register}
    variable))

(def (remove_local redundant)
  (Remover /.Term)
  (function (again synthesis)
    (when synthesis
      [@ {/.#Simple _}]
      synthesis
      
      [@ {/.#Structure structure}]
      [@ {/.#Structure (when structure
                         {analysis/complex.#Variant [lefts right value]}
                         {analysis/complex.#Variant [lefts right (again value)]}
                         
                         {analysis/complex.#Tuple tuple}
                         {analysis/complex.#Tuple (list#each again tuple)})}]
      
      [@ {/.#Reference reference}]
      (when reference
        {reference.#Variable variable}
        (/.variable @ (..remove_local_from_variable redundant variable))

        {reference.#Constant constant}
        synthesis)
      
      [@ {/.#Control control}]
      [@ {/.#Control (when control
                       {/.#Branch branch}
                       {/.#Branch (when branch
                                    {/.#Exec this that}
                                    {/.#Exec (again this)
                                             (again that)}
                                    
                                    {/.#Let [register input] output}
                                    {/.#Let [(..prune redundant register)
                                             (again input)]
                                            (again output)}
                                    
                                    {/.#If test then else}
                                    {/.#If (again test) (again then) (again else)}
                                    
                                    {/.#Get path record}
                                    {/.#Get path (again record)}
                                    
                                    {/.#When input path}
                                    {/.#When (again input) (remove_local_from_path remove_local redundant path)})}
                       
                       {/.#Loop loop}
                       {/.#Loop (when loop
                                  {/.#Scope [start inits iteration]}
                                  {/.#Scope [(..prune redundant start)
                                             (list#each again inits)
                                             (again iteration)]}
                                  
                                  {/.#Again resets}
                                  {/.#Again (list#each again resets)})}

                       {/.#Function function}
                       {/.#Function (when function
                                      {/.#Abstraction [environment arity body]}
                                      {/.#Abstraction [(list#each again environment)
                                                       arity
                                                       body]}

                                      {/.#Apply abstraction inputs}
                                      {/.#Apply (again abstraction) (list#each again inputs)})})}]
      
      [@ {/.#Extension name inputs}]
      [@ {/.#Extension name (list#each again inputs)}])))

(type Redundancy
  (Dictionary Register Bit))

(def initial
  Redundancy
  (dictionary.empty n.hash))

(def redundant! true)
(def necessary! false)

(def (extended offset amount redundancy)
  (-> Register Nat Redundancy
      [(List Register) Redundancy])
  (let [extension (|> amount list.indices (list#each (n.+ offset)))]
    [extension
     (list#mix (function (_ register redundancy)
                 (dictionary.has register ..necessary! redundancy))
               redundancy
               extension)]))

(def (default arity)
  (-> Arity
      Redundancy)
  (product.right (..extended 0 (++ arity) ..initial)))

(type (Optimization of)
  (-> [Redundancy of]
      (Try [Redundancy of])))

(def (list_optimization optimization)
  (All (_ of)
    (-> (Optimization of)
        (Optimization (List of))))
  (function (again [redundancy values])
    (when values
      {.#End}
      {try.#Success [redundancy
                     values]}

      {.#Item head tail}
      (do try.monad
        [[redundancy head] (optimization [redundancy head])
         [redundancy tail] (again [redundancy tail])]
        (in [redundancy
             {.#Item head tail}])))))

(with_template [<name>]
  [(exception.def .public (<name> register)
     (Exception Register)
     (exception.report
      (list ["Register" (%.nat register)])))]

  [redundant_declaration]
  [unknown_register]
  )

(def (declare register redundancy)
  (-> Register Redundancy
      (Try Redundancy))
  (when (dictionary.value register redundancy)
    {.#None}
    {try.#Success (dictionary.has register ..redundant! redundancy)}
    
    {.#Some _}
    (exception.except ..redundant_declaration [register])))

(def (observe register redundancy)
  (-> Register Redundancy
      (Try Redundancy))
  (when (dictionary.value register redundancy)
    {.#None}
    (exception.except ..unknown_register [register])
    
    {.#Some _}
    {try.#Success (dictionary.has register ..necessary! redundancy)}))

(def (format redundancy)
  (%.Format Redundancy)
  (|> redundancy
      dictionary.entries
      (list#each (function (_ [register redundant?])
                   (%.format (%.nat register) ": " (%.bit redundant?))))
      (text.interposed ", ")))

(def (path_optimization optimization)
  (-> (Optimization /.Term)
      (Optimization Path))
  (function (again [redundancy path])
    (when path
      (^.or {/.#Pop}
            {/.#Access _})
      {try.#Success [redundancy
                     path]}

      {/.#Bit_Fork test then else}
      (do [! try.monad]
        [[redundancy then] (again [redundancy then])
         [redundancy else] (when else
                             {.#Some else}
                             (of ! each
                                 (function (_ [redundancy else])
                                   [redundancy {.#Some else}])
                                 (again [redundancy else]))

                             {.#None}
                             (in [redundancy {.#None}]))]
        (in [redundancy {/.#Bit_Fork test then else}]))
      
      (^.with_template [<tag> <type>]
        [{<tag> [[test then] elses]}
         (do [! try.monad]
           [[redundancy then] (again [redundancy then])
            [redundancy elses] (..list_optimization (is (Optimization [<type> Path])
                                                        (function (_ [redundancy [else_test else_then]])
                                                          (do !
                                                            [[redundancy else_then] (again [redundancy else_then])]
                                                            (in [redundancy [else_test else_then]]))))
                                                    [redundancy elses])]
           (in [redundancy {<tag> [[test then] elses]}]))])
      ([/.#I64_Fork I64]
       [/.#F64_Fork Frac]
       [/.#Text_Fork Text])
      
      {/.#Bind register}
      (do try.monad
        [redundancy (..declare register redundancy)]
        (in [redundancy
             path]))
      
      {/.#Alt left right}
      (do try.monad
        [[redundancy left] (again [redundancy left])
         [redundancy right] (again [redundancy right])]
        (in [redundancy {/.#Alt left right}]))
      
      {/.#Seq pre post}
      (do try.monad
        [.let [baseline (|> redundancy
                            dictionary.keys
                            (set.of_list n.hash))]
         [redundancy pre] (again [redundancy pre])
         .let [bindings (|> redundancy
                            dictionary.keys
                            (set.of_list n.hash)
                            (set.difference baseline))]
         [redundancy post] (again [redundancy post])
         .let [redundants (|> redundancy
                              dictionary.entries
                              (list.only (function (_ [register redundant?])
                                           (and (set.member? bindings register)
                                                redundant?)))
                              (list#each product.left))]]
        (in [(list#mix dictionary.lacks redundancy (set.list bindings))
             (|> redundants
                 (list.sorted n.>)
                 (list#mix (..remove_local_from_path ..remove_local) {/.#Seq pre post}))]))

      {/.#Then then}
      (do try.monad
        [[redundancy then] (optimization [redundancy then])]
        (in [redundancy {/.#Then then}]))
      )))

(def (optimization' [redundancy synthesis])
  (Optimization /.Term)
  (with_expansions [<no_op> (these {try.#Success [redundancy
                                                  synthesis]})]
    (when synthesis
      [@ {/.#Simple _}]
      <no_op>
      
      [@ {/.#Structure structure}]
      (when structure
        {analysis/complex.#Variant [lefts right value]}
        (do try.monad
          [[redundancy value] (optimization' [redundancy value])]
          (in [redundancy
               [@ {/.#Structure {analysis/complex.#Variant [lefts right value]}}]]))
        
        {analysis/complex.#Tuple tuple}
        (do try.monad
          [[redundancy tuple] (..list_optimization optimization' [redundancy tuple])]
          (in [redundancy
               [@ {/.#Structure {analysis/complex.#Tuple tuple}}]])))
      
      [@ {/.#Reference reference}]
      (when reference
        {reference.#Variable variable}
        (when variable
          {variable.#Local register}
          (do try.monad
            [redundancy (..observe register redundancy)]
            <no_op>)
          
          {variable.#Foreign register}
          <no_op>)

        {reference.#Constant constant}
        <no_op>)
      
      [@ {/.#Control control}]
      (when control
        {/.#Branch branch}
        (when branch
          {/.#Exec this that}
          (do try.monad
            [[redundancy this] (optimization' [redundancy this])
             [redundancy that] (optimization' [redundancy that])]
            (in [redundancy
                 (/.branch/exec @ [this that])]))
          
          {/.#Let [register input] output}
          (do try.monad
            [[redundancy input] (optimization' [redundancy input])
             redundancy (..declare register redundancy)
             [redundancy output] (optimization' [redundancy output])
             .let [redundant? (|> redundancy
                                  (dictionary.value register)
                                  (maybe.else ..necessary!))]]
            (in [(dictionary.lacks register redundancy)
                 [@ {/.#Control {/.#Branch (if redundant?
                                             {/.#Exec input (..remove_local register output)}
                                             {/.#Let [register input] output})}}]]))
          
          {/.#If test then else}
          (do try.monad
            [[redundancy test] (optimization' [redundancy test])
             [redundancy then] (optimization' [redundancy then])
             [redundancy else] (optimization' [redundancy else])]
            (in [redundancy
                 [@ {/.#Control {/.#Branch {/.#If test then else}}}]]))
          
          {/.#Get path record}
          (do try.monad
            [[redundancy record] (optimization' [redundancy record])]
            (in [redundancy
                 [@ {/.#Control {/.#Branch {/.#Get path record}}}]]))
          
          {/.#When input path}
          (do try.monad
            [[redundancy input] (optimization' [redundancy input])
             [redundancy path] (..path_optimization optimization' [redundancy path])]
            (in [redundancy
                 [@ {/.#Control {/.#Branch {/.#When input path}}}]])))
        
        {/.#Loop loop}
        (when loop
          {/.#Scope [start inits iteration]}
          (do try.monad
            [[redundancy inits] (..list_optimization optimization' [redundancy inits])
             .let [[extension redundancy] (..extended start (list.size inits) redundancy)]
             [redundancy iteration] (optimization' [redundancy iteration])]
            (in [(list#mix dictionary.lacks redundancy extension)
                 [@ {/.#Control {/.#Loop {/.#Scope [start inits iteration]}}}]]))
          
          {/.#Again resets}
          (do try.monad
            [[redundancy resets] (..list_optimization optimization' [redundancy resets])]
            (in [redundancy
                 [@ {/.#Control {/.#Loop {/.#Again resets}}}]])))

        {/.#Function function}
        (when function
          {/.#Abstraction [environment arity body]}
          (do [! try.monad]
            [[redundancy environment] (..list_optimization optimization' [redundancy environment])
             [_ body] (optimization' [(..default arity) body])]
            (in [redundancy
                 [@ {/.#Control {/.#Function {/.#Abstraction [environment arity body]}}}]]))
          
          {/.#Apply abstraction inputs}
          (do try.monad
            [[redundancy abstraction] (optimization' [redundancy abstraction])
             [redundancy inputs] (..list_optimization optimization' [redundancy inputs])]
            (in [redundancy
                 [@ {/.#Control {/.#Function {/.#Apply abstraction inputs}}}]]))))
      
      [@ {/.#Extension name inputs}]
      (do try.monad
        [[redundancy inputs] (..list_optimization optimization' [redundancy inputs])]
        (in [redundancy
             [@ {/.#Extension name inputs}]])))))

(def .public optimization
  (-> /.Term
      (Try /.Term))
  (|>> [..initial]
       optimization'
       (of try.monad each product.right)))