aboutsummaryrefslogtreecommitdiff
path: root/core/metaprogramming.nom
blob: 83179f5b5ce804e2d41f02b27d38fe4e6dfcdd44 (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
#
    This File contains actions for making actions and compile-time actions and some helper
    functions to make that easier.

# Compile-time action to make compile-time actions:
immediately
    lua> ".."
        _ENV['ACTION'..string.as_lua_id("compile % to %")] = compile_time(function(tree, \%actions, \%lua)
            local lua = Lua(tree.source)
            local canonical = \%actions[1]
            lua:append("ACTION", string.as_lua_id(canonical.stub), ' = compile_time(function(tree')
            local args = {}
            for i,tok in ipairs(canonical) do
                if tok.type == "Var" then args[#args+1] = tok end
            end
            local canonical_arg_positions = {}
            for i, arg in ipairs(args) do
                canonical_arg_positions[arg[1]] = i
                lua:append(", ", nomsu:tree_to_lua(arg))
            end
            local body_lua = nomsu:tree_to_lua(\%lua):as_statements("return ")
            body_lua:remove_free_vars(args)
            body_lua:declare_locals()
            lua:append(")\n    ", body_lua, "\nend)")

            for i=2,#\%actions do
                local action = \%actions[i]
                lua:append("\n", "ACTION", string.as_lua_id(action.stub), " = ACTION", string.as_lua_id(canonical.stub))

                local arg_positions = {}
                for _,tok in ipairs(action) do
                    if tok.type == 'Var' then
                        arg_positions[#arg_positions+1] = canonical_arg_positions[tok[1]]
                    end
                end
                lua:append("\n", "ARG_ORDERS[", repr(action.stub), "] = ", repr(arg_positions))
            end
            lua:append("\nALIASES[ACTION", string.as_lua_id(canonical.stub), "] = {")
            for i,action in ipairs(\%actions) do
                if i > 1 then lua:append(", ") end
                lua:append(repr(action.stub))
            end
            lua:append("}")
            return lua
        end)

# Compile-time action to make actions
immediately
    compile [action %actions %body] to
        lua> ".."
            local lua = Lua(tree.source)
            local canonical = \%actions[1]
            lua:append("ACTION", string.as_lua_id(canonical.stub), ' = function(')
            local args = {}
            for i,tok in ipairs(canonical) do
                if tok.type == "Var" then args[#args+1] = tok end
            end
            local canonical_arg_positions = {}
            for i, arg in ipairs(args) do
                canonical_arg_positions[arg[1]] = i
                lua:append(nomsu:tree_to_lua(arg))
                if i < #args then lua:append(", ") end
            end
            local body_lua = nomsu:tree_to_lua(\%body):as_statements("return ")
            body_lua:remove_free_vars(args)
            body_lua:declare_locals()
            lua:append(")\n    ", body_lua, "\nend")

            for i=2,#\%actions do
                local action = \%actions[i]
                lua:append("\n", "ACTION", string.as_lua_id(action.stub), " = ACTION", string.as_lua_id(canonical.stub))

                local arg_positions = {}
                for _,tok in ipairs(action) do
                    if tok.type == 'Var' then
                        arg_positions[#arg_positions+1] = canonical_arg_positions[tok[1]]
                    end
                end
                lua:append("\n", "ARG_ORDERS[", repr(action.stub), "] = ", repr(arg_positions))
            end
            lua:append("\nALIASES[ACTION", string.as_lua_id(canonical.stub), "] = {")
            for i,action in ipairs(\%actions) do
                if i > 1 then lua:append(", ") end
                lua:append(repr(action.stub))
            end
            lua:append("}")
            return lua

# Macro to make nomsu macros
immediately
    compile [parse %shorthand as %longhand] to
        lua> ".."
            local lua = Lua(tree.source)
            local canonical = \%shorthand[1]
            lua:append("ACTION", string.as_lua_id(canonical.stub), ' = compile_time(function(tree')
            local args = {}
            for i,tok in ipairs(canonical) do
                if tok.type == "Var" then args[#args+1] = tok end
            end
            local canonical_arg_positions = {}
            for i, arg in ipairs(args) do
                canonical_arg_positions[arg[1]] = i
                lua:append(", ", nomsu:tree_to_lua(arg))
            end

            local replacements = {}
            for i,tok in ipairs(canonical) do
                if tok.type == "Var" then
                    local lua_var = tostring(nomsu:tree_to_lua(tok))
                    replacements[tok[1]] = lua_var
                end
            end
            MANGLE_INDEX = (MANGLE_INDEX or 0) + 1
            local function make_tree(t)
                if type(t) ~= 'table' and type(t) ~= 'userdata' then
                    return repr(t)
                elseif t.type == 'Var' and replacements[t[1]] then
                    return replacements[t[1]]
                elseif t.type == 'Var' then
                    return t.type.."("..repr(tostring(t.source))..", "..repr(t[1].."#"..tostring(MANGLE_INDEX))..")"
                else
                    local bits = {repr(tostring(t.source))}
                    for i, entry in ipairs(t) do
                        bits[#bits+1] = make_tree(entry)
                    end
                    return t.type.."("..table.concat(bits, ", ")..")"
                end
            end
            lua:append(")\n    local tree = ", make_tree(\%longhand), "\n    return nomsu:tree_to_lua(tree)\nend)")

            for i=2,#\%shorthand do
                local action = \%shorthand[i]
                lua:append("\n", "ACTION", string.as_lua_id(action.stub), " = ACTION", string.as_lua_id(canonical.stub))

                local arg_positions = {}
                for _,tok in ipairs(action) do
                    if tok.type == 'Var' then
                        arg_positions[#arg_positions+1] = canonical_arg_positions[tok[1]]
                    end
                end
                lua:append("\n", "ARG_ORDERS[", repr(action.stub), "] = ", repr(arg_positions))
            end
            lua:append("\nALIASES[ACTION", string.as_lua_id(canonical.stub), "] = {")
            for i,action in ipairs(\%shorthand) do
                if i > 1 then lua:append(", ") end
                lua:append(repr(action.stub))
            end
            lua:append("}")
            return lua

compile [remove action %action] to
    Lua ".."
        do
            local fn = ACTION\(=lua "string.as_lua_id(\(%action.stub))")
            for stub in pairs(ALIASES[fn]) do
                _ENV['ACTION'..string.as_lua_id(stub)] = nil
            end
            ARG_ORDERS[fn] = nil
            COMPILE_TIME[fn] = nil
        end

immediately
    action [%tree as nomsu]
        =lua "nomsu:tree_to_nomsu(\%tree)"

    action [%tree as inline nomsu]
        =lua "nomsu:tree_to_nomsu(\%tree, true)"

    action [%tree as lua]
        =lua "nomsu:tree_to_lua(\%tree)"

    action [%tree as lua expr]
        lua> ".."
            local lua = nomsu:tree_to_lua(\%tree)
            if not lua.is_value then
                compile_error(\%tree, "Invalid thing to convert to lua expr:\n%s")
            end
            return lua

    action [%tree as lua statements]
        =lua "nomsu:tree_to_lua(\%tree):as_statements()"

    action [%tree as lua return]
        =lua "nomsu:tree_to_lua(\%tree):as_statements('return ')"
    
immediately
    compile [%tree with vars %vars] to
        barf "Deprecated"

    compile [%tree with %t -> %replacement] to
        Lua value ".."
            \(%tree as lua expr):map(function(\(%t as lua expr))
                \(%replacement as lua return)
            end)
    
    compile [declare locals in %code] to
        Lua value "\(%code as lua expr):declare_locals()"
    
    compile [declare locals %locals in %code] to
        Lua value "\(%code as lua expr):declare_locals(\(%locals as lua expr))"
    
    compile [remove free vars %vars from %code] to
        Lua "\(%code as lua expr):remove_free_vars(\(%vars as lua expr));"

    action [%tree as value]
        lua> ".."
            if \%tree.type == 'Text' and #\%tree == 1 and type(\%tree[1]) == 'string' then
                return \%tree[1]
            end
            local lua = Lua(\%tree.source, "return ",nomsu:tree_to_lua(\%tree))
            return nomsu:run_lua(lua)
    
immediately
    parse [%var <-write %code] as: lua> "\%var:append(\%code);"
    parse [to %var write %code] as: lua> "\%var:append(\%code);"

immediately
    compile [quote %s] to
        Lua value ".."
            ('"'..\(%s as lua expr):gsub("\\\\", "\\\\\\\\"):gsub("\n","\\\\n"):gsub('"', '\\\\"')..'"')
    compile [type of %obj] to: Lua value "type(\(%obj as lua expr))"

immediately
    compile [nomsu] to: Lua value "nomsu"
    compile [%var as lua identifier] to: Lua value "nomsu:tree_to_lua(\(%var as lua expr))"

# Compiler tools
immediately
    compile [run %code] to
        Lua value "nomsu:run(Nomsu(\(quote "\(%code.source)"), \(%code as lua expr)))"

immediately
    compile [show lua %block] to
        lua> ".."
            local \%lua = nomsu:tree_to_lua(\%block);
            return Lua(tree.source, "print(", repr(tostring(\%lua)), ");");

immediately
    compile [say %message] to
        lua> ".."
            if \%message.type == "Text" then
                return Lua(tree.source, "print(", \(%message as lua expr), ");");
            else
                return Lua(tree.source, "print(tostring(", \(%message as lua expr), "));");
            end

# Return
immediately
    # Return statement is wrapped in a do..end block because Lua is unhappy if you
        put code after a return statement, unless you wrap it in a block.
    compile [return] to: Lua "do return; end"
    compile [return %return_value] to: Lua "do return \(%return_value as lua expr); end"

# Error functions
immediately
    compile [traceback] to: Lua value "debug.traceback()"
    compile [traceback %] to: Lua value "debug.traceback('', \(% as lua expr))"
    compile [barf] to: Lua "error(nil, 0);"
    compile [barf %msg] to: Lua "error(\(%msg as lua expr), 0);"
    compile [assume %condition] to
        lua> "local \%assumption = 'Assumption failed: '..tostring(nomsu:tree_to_nomsu(\%condition));"
        return
            Lua ".."
                if not \(%condition as lua expr) then
                    error(\(quote "\%assumption"), 0);
                end
    
    compile [assume %condition or barf %message] to
        Lua ".."
            if not \(%condition as lua expr) then
                error(\(%message as lua expr), 0);
            end

# Literals
immediately
    compile [yes] to: Lua value "true"
    compile [no] to: Lua value "false"
    compile [nothing, nil, null] to: Lua value "nil"