aboutsummaryrefslogtreecommitdiff
path: root/core/control_flow.nom
blob: 2b53ce7a6e93ea7f4d8a63c6ffcd406cc2aef89a (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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
#!/usr/bin/env nomsu -V4.8.10
#
    This file contains compile-time actions that define basic control flow structures
    like "if" statements and loops.

use "core/metaprogramming.nom"
use "core/text.nom"
use "core/operators.nom"
use "core/errors.nom"

# No-Op
test: do nothing
(do nothing) compiles to (Lua "")

# Conditionals
test:
    if (no):
        barf "conditional fail"
(if %condition %if_body) compiles to:
    %lua = (Lua "if ")
    %lua::append (%condition as lua expr)
    %lua::append " then\n    "
    %lua::append (%if_body as lua statements)
    %lua::append "\nend"
    return %lua

test:
    unless (yes):
        barf "conditional fail"
(unless %condition %unless_body) parses as (if (not %condition) %unless_body)
[..]
    if %condition %if_body else %else_body, unless %condition %else_body else %if_body
..all compile to:
    %lua = (Lua "if ")
    %lua::append (%condition as lua expr)
    %lua::append " then\n    "
    %lua::append (%if_body as lua statements)
    %lua::append "\nelse\n    "
    %lua::append (%else_body as lua statements)
    %lua::append "\nend"
    return %lua

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# 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"
test:
    assume ((1 if (yes) else 2) == 1)
    assume ((1 if (no) else 2) == 2)
[..]
    %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
..all compile to:
    #   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.type):
        return (..)
            Lua value "\
                ..(\(%condition as lua expr) and \(%when_true_expr as lua expr) or \(..)
                    %when_false_expr as lua expr
                ..)"
    ..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 (..)
            Lua value "\
                ..((function()
                    if \(%condition as lua expr) then
                        return \(%when_true_expr as lua expr)
                    else
                        return \(%when_false_expr as lua expr)
                    end
                end)())"

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# GOTOs
test:
    %i = 0
    === %loop ===
    %i += 1
    unless (%i == 10): go to %loop
    assume (%i == 10)
    === (Loop) ===
    %i -= 1
    unless (%i == 0): go to (Loop)
    assume (%i == 0)
[=== %label ===, --- %label ---, *** %label ***] all compile to (..)
    Lua "\
        ..::label_\(..)
            (%label.stub if (%label.type == "Action") else %label) as lua identifier
        ..::"

(go to %label) compiles to (..)
    Lua "\
        ..goto label_\(..)
            (%label.stub if (%label.type == "Action") else %label) as lua identifier
        .."

# Basic loop control
(do next) compiles to (Lua "goto continue")
(stop) compiles to (Lua "break")

# While loops
test:
    %x = 0
    repeat while (%x < 10): %x += 1
    assume (%x == 10)
    repeat while (%x < 20): stop
    repeat while (%x < 20): stop repeating
    assume (%x == 10)
    repeat while (%x < 20):
        %x += 1
        if (yes): do next
        barf "Failed to 'do next'"
    
    assume (%x == 20)
    repeat while (%x < 30):
        %x += 1
        if (yes): do next repeat
        barf "Failed to 'do next repeat'"
    
    assume (%x == 30)
(do next repeat) compiles to (Lua "goto continue_repeat")
(stop repeating) compiles to (Lua "goto stop_repeat")
(repeat while %condition %body) compiles to:
    %lua = (..)
        Lua "\
            ..while \(%condition as lua expr) do
                \(%body as lua statements)"
    
    if (%body has subtree \(do next)):
        %lua::append "\n    ::continue::"
    if (%body has subtree \(do next repeat)):
        %lua::append "\n    ::continue_repeat::"
    %lua::append "\nend --while-loop"
    if (%body has subtree \(stop repeating)):
        %inner_lua = %lua
        %lua = (Lua "do -- scope of 'stop repeating' label\n    ")
        %lua::append %inner_lua
        %lua::append "\
            ..
                ::stop_repeat::
            end -- end of 'stop repeating' label scope"
    
    return %lua

(repeat %body) parses as (repeat while (yes) %body)
(repeat until %condition %body) parses as (repeat while (not %condition) %body)

test:
    %x = 0
    repeat 10 times: %x += 1
    assume (%x == 10)
(repeat %n times %body) compiles to:
    define mangler
    %lua = (..)
        Lua "for \(mangle "i")=1,\(%n as lua expr) do\n    "
    %lua::append (%body as lua statements)
    if (%body has subtree \(do next)):
        %lua::append "\n    ::continue::"
    if (%body has subtree \(do next repeat)):
        %lua::append "\n    ::continue_repeat::"
    %lua::append "\nend --numeric for-loop"
    if (%body has subtree \(stop repeating)):
        %inner_lua = %lua
        %lua = (Lua "do -- scope of 'stop repeating' label\n    ")
        %lua::append %inner_lua
        %lua::append "\
            ..
                ::stop_repeat::
            end -- end of 'stop repeating' label scope"
    
    return %lua

# For loop control flow
(stop %var) compiles to (..)
    Lua "goto stop_\((%var.stub if (%var.type == "Action") else %var) as lua identifier)"
(do next %var) compiles to (..)
    Lua "goto continue_\((%var.stub if (%var.type == "Action") else %var) as lua identifier)"
[===stop %var ===, ---stop %var ---, ***stop %var ***] all compile to (..)
    Lua "::stop_\((%var.stub if (%var.type == "Action") else %var) as lua identifier)::"
[===next %var ===, ---next %var ---, ***next %var ***] all compile to (..)
    Lua "::continue_\((%var.stub if (%var.type == "Action") else %var) as lua identifier)::"

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

test:
    %nums = []
    for %x in 1 to 5: %nums::add %x
    assume (%nums == [1, 2, 3, 4, 5])
    %nums = []
    for %x in 1 to 5 via 2: %nums::add %x
    assume (%nums == [1, 3, 5])
    %nums = []
    for %outer in 1 to 100:
        for %inner in %outer to (%outer + 2):
            if (%inner == 2):
                %nums::add -2
                do next %inner
            
            %nums::add %inner
            if (%inner == 5): stop %outer
    
    assume (%nums == [1, -2, 3, -2, 3, 4, 3, 4, 5])

# Numeric range for loops
[..]
    for %var in %start to %stop by %step %body
    for %var in %start to %stop via %step %body
..all compile to:
    # This uses Lua's approach of only allowing loop-scoped variables in a loop
    unless (%var.type is "Var"):
        compile error at %var "Expected a variable here, not a \(%var.type)"
    %lua = (..)
        Lua "\
            ..for \(%var as lua expr)=\(%start as lua expr),\(%stop as lua expr),\(..)
                %step as lua expr
            .. do"
    
    %lua::append "\n    "
    %lua::append (%body as lua statements)
    if (%body has subtree \(do next)):
        %lua::append "\n    ::continue::"
    if (%body has subtree \(do next %var)):
        %lua::append "\n    "
        %lua::append (what (===next %var ===) compiles to)
    
    %lua::append "\nend --numeric for-loop"
    if (%body has subtree \(stop %var)):
        %inner_lua = %lua
        %lua = (Lua "do -- scope for stopping for-loop\n    ")
        %lua::append %inner_lua
        %lua::append "\n    "
        %lua::append (what (===stop %var ===) compiles to)
        %lua::append "\nend -- end of scope for stopping for-loop"
    
    return %lua

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

(for %var in %start to %stop %body) parses as (..)
    for %var in %start to %stop via 1 %body

test:
    %a = [10, 20, 30, 40, 50]
    %b = []
    for %x in %a: %b::add %x
    assume (%a == %b)
    %b = []
    for %x in %a:
        if (%x == 10): do next %x
        if (%x == 50): stop %x
        %b::add %x
    
    assume (%b == [20, 30, 40])

# For-each loop (lua's "ipairs()")
(for %var in %iterable %body) compiles to:
    define mangler
    # This uses Lua's approach of only allowing loop-scoped variables in a loop
    %lua = (..)
        Lua "for \(mangle "i"),\(%var as lua identifier) in ipairs(\(%iterable as lua expr)) do\n    "
    %lua::append (%body as lua statements)
    if (%body has subtree \(do next)):
        %lua::append "\n    ::continue::"
    if (%body has subtree \(do next %var)):
        %lua::append "\n    "
        %lua::append (what (===next %var ===) compiles to)
    
    %lua::append "\nend --foreach-loop"
    if (%body has subtree \(stop %var)):
        %inner_lua = %lua
        %lua = (Lua "do -- scope for stopping for-loop\n    ")
        %lua::append %inner_lua
        %lua::append "\n    "
        %lua::append (what (===stop %var ===) compiles to)
        %lua::append "\nend -- end of scope for stopping for-loop"
    
    return %lua

# TODO: reduce code duplication
(for %var in %iterable at %i %body) compiles to:
    # This uses Lua's approach of only allowing loop-scoped variables in a loop
    %lua = (..)
        Lua "for \(%i as lua identifier),\(%var as lua identifier) in ipairs(\(%iterable as lua expr)) do\n    "
    %lua::append (%body as lua statements)
    if (%body has subtree \(do next)):
        %lua::append "\n    ::continue::"
    if (%body has subtree \(do next %var)):
        %lua::append "\n    "
        %lua::append (what (===next %var ===) compiles to)
    
    %lua::append "\nend --foreach-loop"
    if (%body has subtree \(stop %var)):
        %inner_lua = %lua
        %lua = (Lua "do -- scope for stopping for-loop\n    ")
        %lua::append %inner_lua
        %lua::append "\n    "
        %lua::append (what (===stop %var ===) compiles to)
        %lua::append "\nend -- end of scope for stopping for-loop"
    
    return %lua

test:
    %d = {a:10, b:20, c:30, d:40, e:50}
    %result = []
    for %k = %v in %d:
        if (%k == "a"): do next %k
        if (%v == 20): do next %v
        %result::add "\%k = \%v"
    
    assume ((%result sorted) == ["c = 30", "d = 40", "e = 50"])

# Dict iteration (lua's "pairs()")
[..]
    for %key = %value in %iterable %body, for %key %value in %iterable %body
..all compile to:
    # This uses Lua's approach of only allowing loop-scoped variables in a loop
    unless (%key.type is "Var"):
        compile error at %key "Expected a variable here, not a \(%key.type)"
    unless (%value.type is "Var"):
        compile error at %value "Expected a variable here, not a \(%value.type)"
    %lua = (..)
        Lua "\
            ..for \(%key as lua identifier),\(%value as lua identifier) in pairs(\(..)
                %iterable as lua expr
            ..) do"
    
    %lua::append "\n    "
    %lua::append (%body as lua statements)
    if (%body has subtree \(do next)):
        %lua::append "\n    ::continue::"
    if (%body has subtree \(do next %key)):
        %lua::append "\n    "
        %lua::append (what (===next %key ===) compiles to)
    
    if (%body has subtree \(do next %value)):
        %lua::append "\n    "
        %lua::append (what (===next %value ===) compiles to)
    
    %lua::append "\nend --foreach-loop"
    %stop_labels = (Lua "")
    if (%body has subtree \(stop %key)):
        %stop_labels::append "\n"
        %stop_labels::append (what (===stop %key ===) compiles to)
    
    if (%body has subtree \(stop %value)):
        %stop_labels::append "\n"
        %stop_labels::append (what (===stop %value ===) compiles to)
    
    if ((size of "\%stop_labels") > 0):
        %inner_lua = %lua
        %lua = (Lua "do -- scope for stopping for % = % loop\n    ")
        %lua::append %inner_lua
        %lua::append %stop_labels
        %lua::append "\nend"
    
    return %lua

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

test:
    if:
        (1 == 2) (100 < 0):
            barf "bad conditional"
        (1 == 0) (1 == 1) %not_a_variable.x: do nothing
        (1 == 1):
            barf "bad conditional"
        (1 == 2):
            barf "bad conditional"
        else:
            barf "bad conditional"

# Multi-branch conditional (if..elseif..else)
[if %body, when %body] all compile to:
    %code = (Lua "")
    %clause = "if"
    %else_allowed = (yes)
    unless (%body.type is "Block"):
        compile error at %body "'if' expected a Block, but got a \(%body.type)."
        ..hint "Perhaps you forgot to put a ':' after 'if'?"
    
    for %line in %body:
        unless (..)
            ((%line.type is "Action") and ((size of %line) >= 2)) and (..)
                %line.(size of %line) is "Block" syntax tree
        ..:
            compile error at %line "Invalid line for the body of an 'if' block."
            ..hint "Each line should contain one or more conditional expressions \
                ..followed by a block, or "else" followed by a block."
        
        %action = %line.(size of %line)
        if ((%line.1 is "else") and ((size of %line) == 2)):
            unless %else_allowed:
                compile error at %line "You can't have two 'else' blocks."
                ..hint "Merge all of the 'else' blocks together."
            
            unless ((size of "\%code") > 0):
                compile error at %line "\
                    ..You can't have an 'else' block without a preceeding condition"
                ..hint "If you want the code in this block to always execute, you don't \
                    ..need a conditional block around it. Otherwise, make sure the 'else' \
                    ..block comes last."

            %code::append "\nelse\n    "
            %code::append (%action as lua statements)
            %else_allowed = (no)
        ..else:
            %code::append %clause
            %code::append " "
            for %i in 1 to ((size of %line) - 1):
                if (%i > 1):
                    %code::append " or "
                %code::append (%line.%i as lua expr)
            
            %code::append " then\n    "
            %code::append (%action as lua statements)
            %clause = "\nelseif"
    
    if ((size of "\%code") == 0):
        compile error at %body "'if' block has an empty body."
        ..hint "This means nothing would happen, so the 'if' block should be deleted."
    %code::append "\nend --when"
    return %code

test:
    if 5 is:
        1 2 3:
            barf "bad switch statement"
        4 5: do nothing
        5 6:
            barf "bad switch statement"
        else:
            barf "bad switch statement"

# Switch statement
[if %branch_value is %body, when %branch_value is %body] all compile to:
    %code = (Lua "")
    %clause = "if"
    %else_allowed = (yes)
    define mangler
    unless (%body.type is "Block"):
        compile error at %body "'if' expected a Block, but got a \(%body.type)"
        ..hint "Perhaps you forgot to put a ':' after the 'is'?"
    for %line in %body:
        unless (..)
            ((%line.type is "Action") and ((size of %line) >= 2)) and (..)
                %line.(size of %line) is "Block" syntax tree
        ..:
            compile error at %line "Invalid line for 'if' block."
            ..hint "Each line should contain expressions \
                ..followed by a block, or "else" followed by a block"
        
        %action = %line.(size of %line)
        if ((%line.1 is "else") and ((size of %line) == 2)):
            unless %else_allowed:
                compile error at %line "You can't have two 'else' blocks."
                ..hint "Merge all of the 'else' blocks together."
            unless ((size of "\%code") > 0):
                compile error at %line "\
                    ..You can't have an 'else' block without a preceeding condition"
                ..hint "If you want the code in this block to always execute, you don't \
                    ..need a conditional block around it. Otherwise, make sure the 'else' \
                    ..block comes last."
            
            %code::append "\nelse\n    "
            %code::append (%action as lua statements)
            %else_allowed = (no)
        ..else:
            %code::append %clause
            %code::append " "
            for %i in 1 to ((size of %line) - 1):
                if (%i > 1):
                    %code::append " or "
                %code::append "\(mangle "branch value") == "
                %code::append (%line.%i as lua expr)
            
            %code::append " then\n    "
            %code::append (%action as lua statements)
            %clause = "\nelseif"
    
    if ((size of "\%code") == 0):
        compile error at %body "'if' block has an empty body."
        ..hint "This means nothing would happen, so the 'if' block should be deleted."
    %code::append "\nend --when"
    %lua = (..)
        Lua "\
            ..do --if % is...
                local \(mangle "branch value") = "
    %lua::append (%branch_value as lua expr)
    %lua::append "\n    "
    %lua::append %code
    %lua::append "\nend --if % is..."
    return %lua

# Do/finally
(do %action) compiles to:
    %lua = (Lua "do\n    ")
    %lua::append (%action as lua statements)
    %lua::append "\nend -- do"
    return %lua

test:
    %d = {}
    try:
        do:
            %d.x = "bad"
            barf
        ..then always: %d.x = "good"
    ..and if it barfs: do nothing
    
    assume (%d.x == "good")
(do %action then always %final_action) compiles to:
    define mangler
    %lua = (..)
        Lua "\
            ..do
                local \(mangle "fell_through") = false
                local \(mangle "ok"), \(mangle "ret") = pcall(function()"
    %lua::append "\n        "
    %lua::append (%action as lua statements)
    %lua::append "\
        ..        \(mangle "fell_through") = true
            end)"
    %lua::append "\n    "
    %lua::append (%final_action as lua statements)
    %lua::append "\
        ..    if not \(mangle "ok") then error(ret, 0) end
            if not \(mangle "fell_through") then return ret end
        end"
    return %lua

test:
    assume ((result of (: return 99)) == 99)

# Inline thunk:
(result of %body) compiles to (Lua value "\(what ([] -> %body) compiles to)()")

test:
    %t = [1, [2, [[3], 4], 5, [[[6]]]]]
    %flat = []
    for % in recursive %t:
        if ((lua type of %) is "table"):
            for %2 in %: recurse % on %2
        ..else: %flat::add %
    
    assume (sorted %flat) == [1, 2, 3, 4, 5, 6]

# Recurion control flow
(for %var in recursive %structure %body) compiles to:
    with local compile actions:
        define mangler
        (recurse %v on %x) compiles to (..)
            Lua "table.insert(\(mangle "stack \(%v.1)"), \(%x as lua expr))"
        %lua = (..)
            Lua "\
                ..do
                    local \(mangle "stack \(%var.1)") = _List{\(%structure as lua expr)}
                    while #\(mangle "stack \(%var.1)") > 0 do
                        \(%var as lua expr) = table.remove(\(mangle "stack \(%var.1)"), 1)"
        %lua::append "\n        "
        %lua::append (%body as lua statements)
        if (%body has subtree \(do next)):
            %lua::append "\n        ::continue::"
        if (%body has subtree \(do next %var)):
            %lua::append "\n        \(what (===next %var ===) compiles to)"
        %lua::append "\n    end -- Recursive loop"
        if (%body has subtree \(stop %var)):
            %lua::append "\n        \(what (===stop %var ===) compiles to)"
        %lua::append "\nend -- Recursive scope"
        return %lua