aboutsummaryrefslogtreecommitdiff
path: root/lib/control_flow.nom
blob: 7455ee96f56ee38a214a60583f3e0d2ac3f6b392 (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
#..
    This file contains compile-time actions that define basic control flow structures
    like "if" statements and loops.

use "lib/metaprogramming.nom"
use "lib/text.nom"
use "lib/operators.nom"

# No-Op
immediately:
    compile [do nothing] to code: ""

# Return
immediately:
    compile [return] to code: "do return; end"
    compile [return %return_value] to code: "do return \(%return_value as lua); end"

# Conditionals
immediately:
    compile [if %condition %if_body] to code: ".."
        if \(%condition as lua) then
        \(%if_body as lua statements)
        end --end if
    parse [unless %condition %unless_body] as: if (not %condition) %unless_body

    compile [if %condition %if_body else %else_body, unless %condition %else_body else %if_body] to code: ".."
        if \(%condition as lua) then
        \(%if_body as lua statements)
        else
        \(%else_body as lua statements)
        end --end if

# Conditional expression (ternary operator)
#.. Note: this uses a function instead of "(condition and if_expr or else_expr)"
    because that breaks if %if_expr is falsey, e.g. "x < 5 and false or 99"
immediately:
    compile [..]
        %when_true_expr if %condition else %when_false_expr
        %when_true_expr if %condition otherwise %when_false_expr
        %when_false_expr unless %condition else %when_true_expr
        %when_false_expr unless %condition then %when_true_expr
    ..to:
        local %safe
        #.. If %when_true_expr is guaranteed to be truthy, we can use Lua's idiomatic
            equivalent of a conditional expression: (cond and if_true or if_false)
        if ({Text=yes, List=yes, Dict=yes, Number=yes}->(%when_true_expr's "type")):
            return "(\(%condition as lua) and \(%when_true_expr as lua) or \(%when_false_expr as lua))"
        ..else:
            #.. Otherwise, need to do an anonymous inline function (yuck, too bad lua 
                doesn't have a proper ternary operator!)
                To see why this is necessary consider: (random()<.5 and false or 99)
            return ".."
                (function()
                    if \(%condition as lua) then
                        return \(%when_true_expr as lua);
                    else
                        return \(%when_false_expr as lua);
                    end
                end)()

# GOTOs
immediately:
    compile [-> %label] to code: ".."
        ::label_\(nomsu "var_to_lua_identifier" [%label])::;
    compile [go to %label] to code: ".."
        goto label_\(nomsu "var_to_lua_identifier" [%label]);

# Basic loop control
immediately:
    compile [do next] to code: "continue;"
    compile [stop] to code: "break;"

# Helper function
immediately:
    action [tree %tree has function call %call]:
        lua> ".."
            local target = (\%call).stub;
            for subtree,_ in coroutine.wrap(function() nomsu:walk_tree(\%tree); end) do
                if type(subtree) == 'table' and subtree.type == "FunctionCall"
                and subtree.stub == target then
                    return true;
                end
            end
            return false;

# While loops
immediately:
    compile [do next repeat-loop] to code: "goto continue_repeat;"
    compile [stop repeat-loop] to code: "goto stop_repeat;"
    compile [repeat while %condition %body] to code:
        set %continue_labels = (..)
            "\n::continue_repeat::;"
            ..if (tree %body has function call \(do next repeat-loop)) else ""
        set %code = ".."
            while \(%condition as lua) do
            \(%body as lua statements)\
            ..\%continue_labels
            end --while-loop
        if (tree %body has function call \(stop repeat-loop)):
            return ".."
                do --while-loop label scope
                \%code
                ::stop_repeat::;
                end --while-loop label scope
        return %code
    parse [repeat %body] as: repeat while (true) %body
    parse [repeat until %condition %body] as: repeat while (not %condition) %body

# For loop control flow:
immediately:
    compile [stop for-loop] to code: "goto stop_for;"
    compile [stop %var] to code: ".."
        goto stop_\(nomsu "var_to_lua_identifier" [%var]);
    compile [do next for-loop] to code: "goto continue_for;"
    compile [do next %var] to code: ".."
        goto continue_\(nomsu "var_to_lua_identifier" [%var]);

# Numeric range for loops
immediately:
    compile [..]
        for %var from %start to %stop by %step %body
        for %var from %start to %stop via %step %body
    ..to code:
        local [%continue_labels, %code, %stop_labels, %loop_var, %loop_var_shim]
        set %continue_labels = ""
        if (tree %body has function call \(do next for-loop)):
            %continue_labels join= "\n::continue_for::;"
        if (tree %body has function call (tree \(do next %) with {""=%var})):
            %continue_labels join= "\n::continue_\(nomsu "var_to_lua_identifier" [%var])::;"
        if ((%var's "type") is "Var"):
            set %loop_var = (%var as lua)
            set %loop_var_shim = ""
        ..else:
            set %loop_var = "i"
            set %loop_var_shim = "\n\(%var as lua) = i;"
        # This trashes the loop variables, just like in Python.
        set %code = ".."
            for \(%loop_var)=\(%start as lua),\(%stop as lua),\(%step as lua) do\
            ..\%loop_var_shim
            \(%body as lua statements)\
            ..\%continue_labels
            end --numeric for-loop
        set %stop_labels = ""
        if (tree %body has function call \(stop for-loop)):
            %stop_labels join= "\n::stop_for::;"
        if (tree %body has function call (tree \(stop %) with {""=%var})):
            %stop_labels join= "\n::stop_\(nomsu "var_to_lua_identifier" [%var])::;"
        return (..)
            ".."
                do --for-loop label scope
                \%code\
                ..\%stop_labels
                end --for-loop label scope
            ..if (%stop_labels is not "") else %code

immediately:
    parse [for %var from %start to %stop %body] as: for %var from %start to %stop via 1 %body
    parse [..]
        for all %start to %stop by %step %body
        for all %start to %stop via %step %body
    ..as: for % from %start to %stop via %step %body
    parse [for all %start to %stop %body] as: for all %start to %stop via 1 %body

immediately:
    compile [for %var in %iterable %body] to code:
        local [%continue_labels, %code, %stop_labels, %loop_var, %loop_var_shim]
        set %continue_labels = ""
        if (tree %body has function call \(do next for-loop)):
            %continue_labels join= "\n::continue_for::;"
        if (tree %body has function call (tree \(do next %) with {""=%var})):
            %continue_labels join= "\n::continue_\(nomsu "var_to_lua_identifier" [%var])::;"
        if ((%var's "type") is "Var"):
            set %loop_var = (%var as lua)
            set %loop_var_shim = ""
        ..else:
            set %loop_var = "value"
            set %loop_var_shim = "\n\(%var as lua) = value;"
        # This trashes the loop variables, just like in Python.
        set %code = ".."
            for i,\%loop_var in ipairs(\(%iterable as lua)) do\
            ..\%loop_var_shim
            \(%body as lua statements)\
            ..\%continue_labels
            end --foreach-loop
        set %stop_labels = ""
        if (tree %body has function call \(stop for-loop)):
            %stop_labels join= "\n::stop_for::;"
        if (tree %body has function call (tree \(stop %) with {""=%var})):
            %stop_labels join= "\n::stop_\(nomsu "var_to_lua_identifier" [%var])::;"
        if (%stop_labels is not ""):
            set %code = ".."
                do --for-loop label scope
                \%code\%stop_labels
                end --for-loop label scope
        return %code
    parse [for all %iterable %body] as: for % in %iterable %body

immediately:
    compile [..]
        repeat %n times %body, repeat %n x %body
    ..to code:
        local [%continue_labels, %code, %stop_labels]
        set %continue_labels = ""
        if (tree %body has function call \(do next repeat-loop)):
            %continue_labels join= "\n::continue_repeat::;"
        # This trashes the loop variables, just like in Python.
        set %code = ".."
            for i=1,\(%n as lua) do
            \(%body as lua statements)\
            ..\%continue_labels
            end --numeric for-loop
        set %stop_labels = ""
        if (tree %body has function call \(stop repeat-loop)):
            %stop_labels join= "\n::stop_repeat::;"
        return (..)
            ".."
                do --repeat-loop label scope
                \%code\
                ..\%stop_labels
                end --repeat-loop label scope
            ..if (%stop_labels is not "") else %code

# Dict iteration (lua's "pairs()")
immediately:
    compile [for %key = %value in %iterable %body] to code:
        local [..]
            %continue_labels, %code, %stop_labels, %key_loop_var, %key_loop_var_shim,
            %value_loop_var, %value_loop_var_shim
        set %continue_labels = ""
        if (tree %body has function call \(do next for-loop)):
            %continue_labels join= "\n::continue_for::;"
        if (tree %body has function call (tree \(do next %x) with {x=%key})):
            %continue_labels join= "\n::continue_\(nomsu "var_to_lua_identifier" [%key])::;"
        if (tree %body has function call (tree \(do next %) with {""=%value})):
            %continue_labels join= "\n::continue_\(nomsu "var_to_lua_identifier" [%value])::;"
        if ((%key's "type") is "Var"):
            set %key_loop_var = (%key as lua)
            set %key_loop_var_shim = ""
        ..else:
            set %key_loop_var = "key"
            set %key_loop_var_shim = "\n\(%key as lua) = key;"
        if ((%value's "type") is "Var"):
            set %value_loop_var = (%value as lua)
            set %value_loop_var_shim = ""
        ..else:
            set %value_loop_var = "value"
            set %value_loop_var_shim = "\n\(%value as lua) = value;"
        # This trashes the loop variables, just like in Python.
        set %code = ".."
            for \%key_loop_var,\%value_loop_var in pairs(\(%iterable as lua)) do\
            ..\%key_loop_var_shim\%value_loop_var_shim
            \(%body as lua statements)\
            ..\%continue_labels
            end --foreach-loop
        set %stop_labels = ""
        if (tree %body has function call \(stop for-loop)):
            %stop_labels join= "\n::stop_for::;"
        if (tree %body has function call (tree \(stop %) with {""=%key})):
            %stop_labels join= "\n::stop_\(nomsu "var_to_lua_identifier" [%key])::;"
        if (tree %body has function call (tree \(stop %) with {""=%value})):
            %stop_labels join= "\n::stop_\(nomsu "var_to_lua_identifier" [%value])::;"
        return (..)
            ".."
                do --for-loop label scope
                \%code\
                ..\%stop_labels
                end --for-loop label scope
            ..if (%stop_labels is not "") else %code

# Switch statement/multi-branch if
immediately:
    compile [when %body] to code:
        local [%result, %fallthroughs, %first]
        set %result = ""
        set %fallthroughs = []
        set %first = (yes)
        for %func_call in (%body's "value"):
            local [%tokens, %star, %condition, %action]
            assume ((%func_call's "type") is "FunctionCall") or barf ".."
                Invalid format for 'when' statement. Only '*' blocks are allowed.
            set %tokens = (%func_call's "value")
            set %star = (%tokens -> 1)
            assume (=lua "\%star and \%star.type == 'Word' and \%star.value == '*'") or barf ".."
                Invalid format for 'when' statement. Lines must begin with '*'

            set %condition = (%tokens -> 2)
            assume %condition or barf ".."
                Invalid format for 'when' statement. Lines must begin with '*' and have a condition or the word "else"

            set %action = (%tokens -> 3)
            if (%action is (nil)):
                lua do> "table.insert(\%fallthroughs, \%condition)"
                do next %func_call

            if (=lua "\%condition.type == 'Word' and \%condition.value == 'else'"):
                %result join= ".."
                    
                    else
                    \(%action as lua statements)
                stop for-loop
            ..else:
                set %condition = (%condition as lua)
                for all %fallthroughs:
                    %condition join= " or \(% as lua)"
                %result join= ".."
                    
                    \("if" if %first else "elseif") \%condition then
                    \(%action as lua statements)

            set %fallthroughs = []
            set %first = (no)

        if (%result != ""):
            %result join= "\nend"
        return %result

# Switch statement
immediately:
    compile [when %branch_value = ? %body, when %branch_value is ? %body] to code:
        set %result = ""
        set %fallthroughs = []
        set %first = (yes)
        for %func_call in (%body's "value"):
            assume ((%func_call's "type") is "FunctionCall") or barf ".."
                Invalid format for 'when' statement. Only '*' blocks are allowed.
            set %tokens = (%func_call's "value")
            set %star = (%tokens -> 1)
            assume (=lua "\%star and \%star.type == 'Word' and \%star.value == '*'") or barf ".."
                Invalid format for 'when' statement. Lines must begin with '*'

            set %condition = (%tokens -> 2)
            assume %condition or barf ".."
                Invalid format for 'when' statement. Lines must begin with '*' and have a condition or the word "else"

            set %action = (%tokens -> 3)
            if (%action is (nil)):
                lua> "table.insert(\%fallthroughs, \%condition)"
                do next %func_call

            if (=lua "\%condition.type == 'Word' and \%condition.value == 'else'"):
                %result join= ".."
                    
                    else
                    \(%action as lua statements)
                stop for-loop
            ..else:
                set %condition = "branch_value == (\(%condition as lua))"
                for all %fallthroughs:
                    %condition join= " or (branch_value == \(% as lua))"
                %result join= ".."
                    
                    \("if" if %first else "elseif") \%condition then
                    \(%action as lua statements)

            set %fallthroughs = []
            set %first = (no)

        if (%result != ""):
            set %result = ".."
                do --when % = ?
                local branch_value = \(%branch_value as lua);\
                ..\%result
                end
                end --when % = ?
        return %result

# Try/except
immediately:
    compile [..]
        try %action and if it succeeds %success or if it fails %fallback
        try %action and if it fails %fallback or if it succeeds %success
    ..to code: ".."
        do
            local fell_through = false;
            local ok, ret = pcall(function()
                \(%action as lua statements)
                fell_through = true;
            end);
            if ok then
                \(%success as lua statements)
            end
            if not ok then
                \(%fallback as lua statements)
            elseif not fell_through then
                return ret;
            end
        end
    parse [try %action] as:
        try %action and if it succeeds: do nothing
        ..or if it fails: do nothing
    parse [try %action and if it fails %fallback] as:
        try %action and if it succeeds: do nothing
        ..or if it fails %fallback
    parse [try %action and if it succeeds %success] as:
        try %action and if it succeeds %success or if it fails: do nothing

# Do/finally:
immediately:
    compile [do %action] to code:
        (%action as lua statements) if ((%action's "type") is "Block")
        ..else "(\(%action as lua))(nomsu);"

    compile [do %action then always %final_action] to code: ".."
        do
            local fell_through = false;
            local ok, ret1 = pcall(function()
                \(%action as lua statements)
                fell_through = true;
            end);
            local ok2, ret2 = pcall(function()
                \(%final_action as lua statements)
            end);
            if not ok then error(ret1); end
            if not ok2 then error(ret2); end
            if not fell_through then
                return ret1;
            end
        end

immediately:
    compile [with %assignments %action] to code:
        local [%lua, %olds, %old_vals, %new_vals]
        set {%temp_vars=[], %old_vals=[], %new_vals=[]}
        for %i=%assignment in (%assignments' "value"):
            set (%temp_vars->%i) = "temp\%i"
            set (%old_vals->%i) = ((%assignment's "dict_key") as lua)
            set (%new_vals->%i) = ((%assignment's "dict_value") as lua)
        return ".."
            do
                local \(join %temp_vars with ", ") = \(join %old_vals with ", ");
                \(join %old_vals with ", ") = \(join %new_vals with ", ");
                local fell_through = false;
                local ok, ret = pcall(function()
                    do
                        \(%action as lua statements)
                    end
                    fell_through = true;
                end);
                \(join %old_vals with ", ") = \(join %temp_vars with ", ");
                if not ok then error(ret, 0); end
                if not fell_through then return ret end
            end