aboutsummaryrefslogtreecommitdiff
path: root/lib/control_flow.nom
blob: b7b5f1980d722abd8427d5ea091c4ae49964e2ab (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
require "lib/metaprogramming.nom"
require "lib/operators.nom"
require "lib/utils.nom"

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

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

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

# GOTOs
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]);

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

# While loops
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:
    %continue_labels = (..)
        "\n::continue_repeat::;" if (tree %body has function call \(do next repeat-loop)) else ""
    %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:
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
compile [..]
    for %var from %start to %stop by %step %body
    for %var from %start to %stop via %step %body
..to code:
    %continue_labels = ""
    if (tree %body has function call \(do next for-loop)):
        %continue_labels join= "\n::continue_for::;"
    if (tree %body has function call (nomsu "replaced_vars" [\(do next %), =lua "{['']=\(%var)}"])):
        %continue_labels join= "\n::continue_\(nomsu "var_to_lua_identifier" [%var])::;"
    # This trashes the loop variables, just like in Python.
    %code = ".."
        for i=\(%start as lua),\(%stop as lua),\(%step as lua) do
        \(%var as lua) = i;
        \(%body as lua statements)\(%continue_labels)
        end --numeric for-loop
    %stop_labels = ""
    if (tree %body has function call \(stop for-loop)):
        %stop_labels join= "\n::stop_for::;"
    if (tree %body has function call (nomsu "replaced_vars" [\(stop %), =lua "{['']=\(%var)}"])):
        %stop_labels join= "\n::stop_\(nomsu "var_to_lua_identifier" [%var])::;"
    if (%stop_labels != ""): ".."
        do --for-loop label scope
        \(%code)\(%stop_labels)
        end --for-loop label scope
    ..else: %code
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

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


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

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

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

        if (=lua "vars.condition.type == 'Word' and vars.condition.value == 'else'"):
            %result join= ".."
                
                else
                \(%action as lua statements)
            stop for-loop
        ..else:
            %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)

        %fallthroughs = []
        %first = (no)

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

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

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

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

        if (=lua "vars.condition.type == 'Word' and vars.condition.value == 'else'"):
            %result join= ".."
                
                else
                \(%action as lua statements)
            stop for-loop
        ..else:
            %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)

        %fallthroughs = []
        %first = (no)

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

# Try/except
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, ret1, ret2 = pcall(function(nomsu, vars)
            \(%action as lua statements)
            fell_through = true;
        end, nomsu, vars);
        if ok then
            \(%success as lua statements)
        end
        if not ok then
            \(%fallback as lua statements)
        elseif not fell_through then
            return ret1, ret2;
        end
    end
parse [try %action] as:
    try %action and if it succeeds {pass} or if it fails {pass}
parse [try %action and if it fails %fallback] as:
    try %action and if it succeeds {pass} 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 {pass}

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