aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/tool/compiler/language/lux/phase/generation/python/case.lux
blob: ddaf1fe5b6e0a8f2eaeee2b3ed4eb947f5f319e4 (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
(.module:
  [lux (#- case let if)
   [abstract
    ["." monad (#+ do)]]
   [control
    [exception (#+ exception:)]]
   [data
    ["." text
     ["%" format (#+ format)]]
    [collection
     ["." list ("#\." functor fold)]
     ["." set]]]
   [math
    [number
     ["n" nat]
     ["i" int]]]
   [target
    ["_" python (#+ Expression SVar Statement)]]]
  ["." // #_
   ["#." runtime (#+ Operation Phase Generator Phase! Generator!)]
   ["#." reference]
   ["#." primitive]
   ["/#" // #_
    ["#." reference]
    ["/#" // #_
     [synthesis
      ["." case]]
     ["/#" // #_
      ["#." synthesis (#+ Member Synthesis Path)]
      ["#." generation]
      ["//#" /// #_
       [reference
        ["#." variable (#+ Register)]]
       ["#." phase ("#\." monad)]
       [meta
        [archive (#+ Archive)]]]]]]])

(def: #export register
  (-> Register SVar)
  (|>> (///reference.local //reference.system) :assume))

(def: #export capture
  (-> Register SVar)
  (|>> (///reference.foreign //reference.system) :assume))

(def: #export (let expression archive [valueS register bodyS])
  (Generator [Synthesis Register Synthesis])
  (do ///////phase.monad
    [valueO (expression archive valueS)
     bodyO (expression archive bodyS)]
    ## TODO: Find some way to do 'let' without paying the price of the closure.
    (wrap (_.apply/* (_.lambda (list (..register register))
                               bodyO)
                     (list valueO)))))

(def: #export (let! statement expression archive [valueS register bodyS])
  (Generator! [Synthesis Register Synthesis])
  (do ///////phase.monad
    [valueO (expression archive valueS)
     bodyO (statement expression archive bodyS)]
    (wrap ($_ _.then
              (_.set (list (..register register)) valueO)
              bodyO))))

(def: #export (if expression archive [testS thenS elseS])
  (Generator [Synthesis Synthesis Synthesis])
  (do ///////phase.monad
    [testO (expression archive testS)
     thenO (expression archive thenS)
     elseO (expression archive elseS)]
    (wrap (_.? testO thenO elseO))))

(def: #export (if! statement expression archive [testS thenS elseS])
  (Generator! [Synthesis Synthesis Synthesis])
  (do ///////phase.monad
    [test! (expression archive testS)
     then! (statement expression archive thenS)
     else! (statement expression archive elseS)]
    (wrap (_.if test!
            then!
            else!))))

(def: #export (get expression archive [pathP valueS])
  (Generator [(List Member) Synthesis])
  (do ///////phase.monad
    [valueO (expression archive valueS)]
    (wrap (list\fold (function (_ side source)
                       (.let [method (.case side
                                       (^template [<side> <accessor>]
                                         [(<side> lefts)
                                          (<accessor> (_.int (.int lefts)))])
                                       ([#.Left //runtime.tuple//left]
                                        [#.Right //runtime.tuple//right]))]
                         (method source)))
                     valueO
                     pathP))))

(def: @savepoint (_.var "lux_pm_savepoint"))
(def: @cursor (_.var "lux_pm_cursor"))
(def: @temp (_.var "lux_pm_temp"))

(def: (push! value)
  (-> (Expression Any) (Statement Any))
  (_.statement (|> @cursor (_.do "append" (list value)))))

(def: peek_and_pop
  (Expression Any)
  (|> @cursor (_.do "pop" (list))))

(def: pop!
  (Statement Any)
  (_.statement ..peek_and_pop))

(def: peek
  (Expression Any)
  (_.nth (_.int -1) @cursor))

(def: save!
  (Statement Any)
  (.let [cursor (_.slice_from (_.int +0) @cursor)]
    (_.statement (|> @savepoint (_.do "append" (list cursor))))))

(def: restore!
  (Statement Any)
  (_.set (list @cursor) (|> @savepoint (_.do "pop" (list)))))

(def: fail_pm! _.break)

(def: (multi_pop! pops)
  (-> Nat (Statement Any))
  (_.delete (_.slice_from (_.int (i.* -1 (.int pops))) @cursor)))

(template [<name> <flag> <prep>]
  [(def: (<name> simple? idx)
     (-> Bit Nat (Statement Any))
     ($_ _.then
         (_.set (list @temp) (|> idx <prep> .int _.int (//runtime.sum//get ..peek <flag>)))
         (.if simple?
           (_.when (_.= _.none @temp)
                   fail_pm!)
           (_.if (_.= _.none @temp)
             fail_pm!
             (..push! @temp))
           )))]

  [left_choice  _.none        (<|)]
  [right_choice (_.string "") inc]
  )

(def: (alternation pre! post!)
  (-> (Statement Any) (Statement Any) (Statement Any))
  ($_ _.then
      (_.while (_.bool true)
               ($_ _.then
                   ..save!
                   pre!))
      ($_ _.then
          ..restore!
          post!)))

(def: (pattern_matching' statement expression archive)
  (-> Phase! Phase Archive Path (Operation (Statement Any)))
  (function (recur pathP)
    (.case pathP
      (^ (/////synthesis.path/then bodyS))
      (statement expression archive bodyS)

      #/////synthesis.Pop
      (///////phase\wrap ..pop!)

      (#/////synthesis.Bind register)
      (///////phase\wrap (_.set (list (..register register)) ..peek))

      (#/////synthesis.Bit_Fork when thenP elseP)
      (do {! ///////phase.monad}
        [then! (recur thenP)
         else! (.case elseP
                 (#.Some elseP)
                 (recur elseP)

                 #.None
                 (wrap ..fail_pm!))]
        (wrap (.if when
                (_.if ..peek
                  then!
                  else!)
                (_.if ..peek
                  else!
                  then!))))

      (#/////synthesis.I64_Fork cons)
      (do {! ///////phase.monad}
        [clauses (monad.map ! (function (_ [match then])
                                (do !
                                  [then! (recur then)]
                                  (wrap [(_.= (//primitive.i64 (.int match))
                                              ..peek)
                                         then!])))
                            (#.Cons cons))]
        (wrap (_.cond clauses
                      ..fail_pm!)))

      (^template [<tag> <format>]
        [(<tag> cons)
         (do {! ///////phase.monad}
           [clauses (monad.map ! (function (_ [match then])
                                   (\ ! map
                                      (|>> [(_.= (<format> match)
                                                 ..peek)])
                                      (recur then)))
                               (#.Cons cons))]
           (wrap (_.cond clauses
                         ..fail_pm!)))])
      ([#/////synthesis.F64_Fork //primitive.f64]
       [#/////synthesis.Text_Fork //primitive.text])

      (^template [<complex> <simple> <choice>]
        [(^ (<complex> idx))
         (///////phase\wrap (<choice> false idx))

         (^ (<simple> idx nextP))
         (|> nextP
             recur
             (///////phase\map (_.then (<choice> true idx))))])
      ([/////synthesis.side/left  /////synthesis.simple_left_side  ..left_choice]
       [/////synthesis.side/right /////synthesis.simple_right_side ..right_choice])

      (^ (/////synthesis.member/left 0))
      (///////phase\wrap (|> ..peek (_.nth (_.int +0)) ..push!))
      
      (^template [<pm> <getter>]
        [(^ (<pm> lefts))
         (///////phase\wrap (|> ..peek (<getter> (_.int (.int lefts))) ..push!))])
      ([/////synthesis.member/left  //runtime.tuple//left]
       [/////synthesis.member/right //runtime.tuple//right])

      (^ (/////synthesis.!bind_top register thenP))
      (do ///////phase.monad
        [then! (recur thenP)]
        (///////phase\wrap ($_ _.then
                               (_.set (list (..register register)) ..peek_and_pop)
                               then!)))

      (^ (/////synthesis.!multi_pop nextP))
      (.let [[extra_pops nextP'] (case.count_pops nextP)]
        (do ///////phase.monad
          [next! (recur nextP')]
          (///////phase\wrap ($_ _.then
                                 (..multi_pop! (n.+ 2 extra_pops))
                                 next!))))

      (^template [<tag> <combinator>]
        [(^ (<tag> preP postP))
         (do ///////phase.monad
           [pre! (recur preP)
            post! (recur postP)]
           (wrap (<combinator> pre! post!)))])
      ([/////synthesis.path/seq _.then]
       [/////synthesis.path/alt ..alternation]))))

(def: (pattern_matching statement expression archive pathP)
  (-> Phase! Phase Archive Path (Operation (Statement Any)))
  (do ///////phase.monad
    [pattern_matching! (pattern_matching' statement expression archive pathP)]
    (wrap ($_ _.then
              (_.while (_.bool true)
                       pattern_matching!)
              (_.raise (_.Exception/1 (_.string case.pattern_matching_error)))))))

(def: #export dependencies
  (-> Path (List SVar))
  (|>> case.storage
       (get@ #case.dependencies)
       set.to_list
       (list\map (function (_ variable)
                   (.case variable
                     (#///////variable.Local register)
                     (..register register)
                     
                     (#///////variable.Foreign register)
                     (..capture register))))))

(def: #export (gensym prefix)
  (-> Text (Operation SVar))
  (///////phase\map (|>> %.nat (format prefix) _.var) /////generation.next))

(def: #export (case! statement expression archive [valueS pathP])
  (Generator! [Synthesis Path])
  (do ///////phase.monad
    [stack_init (expression archive valueS)
     pattern_matching! (pattern_matching statement expression archive pathP)]
    (wrap ($_ _.then
              (_.set (list @cursor) (_.list (list stack_init)))
              (_.set (list @savepoint) (_.list (list)))
              pattern_matching!
              ))))

(def: #export (case statement expression archive [valueS pathP])
  (-> Phase! (Generator [Synthesis Path]))
  (do ///////phase.monad
    [[[case_module case_artifact] pattern_matching!] (/////generation.with_new_context archive
                                                       (case! statement expression archive [valueS pathP]))
     #let [@case (_.var (///reference.artifact [case_module case_artifact]))
           @dependencies+ (..dependencies (/////synthesis.path/seq (/////synthesis.path/then valueS)
                                                                   pathP))
           directive (_.def @case @dependencies+
                            pattern_matching!)]
     _ (/////generation.execute! directive)
     _ (/////generation.save! (%.nat case_artifact) directive)]
    (wrap (_.apply/* @case @dependencies+))))