aboutsummaryrefslogtreecommitdiff
path: root/nomnom/compile.nom
blob: 70f32b82c9f6c52f1d116dd0cb2e7651e771d1b0 (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
#!/usr/bin/env nomsu -V4.8.10
# This file contains the code to convert syntax trees to Lua code
use "nomnom/code_obj.nom"
use "nomnom/parser.nom"
use "nomnom/pretty_errors.nom"

externally (report compile error at %tree %err) means:
    barf (pretty "Compile Error" error at %tree %err)

externally (report compile error at %pos %err hint %hint) means:
    barf (pretty "Compile Error" error at %tree %err hint %hint)

externally (barf any errors in %t) means:
    assume (%t is a "Syntax Tree")
    %errs = []
    for % in recursive %t:
        if (%.type == "Error"): %errs::add %
        for %k = %v in %:
            if (%v is a "Syntax Tree"): recurse % on %v
    
    sort %errs by % -> %.source
    %errs = ((% as a pretty error) for % in %errs)
    if ((size of %errs) > 0):
        if ((size of %errs) > 3):
            %n = ((size of %errs) - 3)
            for %i in 4 to (size of %errs): %errs.%i = (nil)
            %errs::add "\027[31;1m +\%n additional errors...\027[0m\n"
        barf (%errs::joined with "\n\n")

externally (%tree compiled with %compile_actions) means:
    assume (%tree is a "Syntax Tree")
    if all of [..]
        %tree.version, ((Nomsu version)'s meaning) != (nil), %tree.version != (Nomsu version)
        ((1 upgraded from 2 to 3)'s meaning) != (nil)
    ..then:
        %tree = (upgrade %tree from %tree.version to (Nomsu version))
    
    if %tree.type is:
        "Action":
            %stub = %tree.stub
            %compile_action = %compile_actions.%stub
            
            # Don't apply compiler actions to methods
            if (%compile_action and (not %tree.target)):
                # TODO: restore this:
                #%args = [%tree, %compile_actions]
                %args = [%nomsu, %tree]
                for % in (%tree::get args): %args::add %
                %result = (call %compile_action with %args)
                if (%result == (nil)):
                    report compile error at %tree "\
                        ..The compile-time action here (\(%tree.stub)) failed to return any value."
                    ..hint "\
                        ..Look at the implementation of (\(%tree.stub)) and make sure it's returning something."
                
                if (%result is a "Syntax Tree"):
                    if (%result == %tree):
                        report compile error at %tree "\
                            ..The compile-time action here (\(%tree.stub)) is producing an endless loop."
                        ..hint "\
                            ..Look at the implementation of (\(%tree.stub)) and make sure it's not just returning the original tree."
                    
                    return (%result compiled with %compile_actions)
                
                return %result
            
            %lua = (Lua Value from %tree)
            if %tree.target:
                # Method call
                %target_lua = (%tree.target compiled with %compile_actions)
                if (..)
                    ((%target_lua::as smext)::matches "^%(.*%)$") or (..)
                        (%target_lua::as smext)::matches "^[_a-zA-Z][_a-zA-Z0-9]*$"
                ..:
                    %lua::add [%target_lua, ":"]
                ..else:
                    %lua::add ["(", %target_lua, "):"]
            
            %lua::add [%stub as lua id, "("]
            %args = []
            for %tok in %tree at %i:
                if (%tok is text): do next %tok
                
                # TODO: maybe don't translate Lua comments
                #if (%tok.type == "Comment"): do next %tok
                if (%tok.type == "Block"):
                    %values = []
                    for %line in %tok:
                        #unless (%line.type == "Comment"):
                        %values::add (%line compiled with %compile_actions)
                    
                    if all of (%.is_value for % in %values):
                        if ((size of %values) == 1):
                            %arg_lua = %values.1
                        ..else:
                            %arg_lua = (Lua Value from %tok ["("])
                            %arg_lua::add %values joined with " and nil or "
                            %arg_lua::add ")"
                    ..else:
                        %arg_lua = (Lua Value from %tok ["((function()"])
                        for %v in %values at %i:
                            if %v.is_value:
                                %v = (%v::as statements ("return " if (%i == (size of %values) else "")))
                            %arg_lua::add ["\n    ", %v]
                        
                        %arg_lua::add "\nend)())"
                ..else:
                    %arg_lua = (%tok compiled with %compile_actions)
                    unless %arg_lua.is_value:
                        if (%tok.type == "Action"):
                            report compile error at %tok "\
                                ..Can't use this as an argument to (\%stub), since it's not an expression, it produces: \%arg_lua"
                            ..hint "\
                                ..Check the implementation of (\(%tok.stub)) to see if it is actually meant to produce an expression."
                        ..else:
                            report compile error at %tok "\
                                ..Can't use this as an argument to (\%stub), since it's not an expression, it produces: \%arg_lua"
                
                assume (%arg_lua != %lua) or barf "Huh? \%tree .\%i = \%tok -> \%arg_lua"
                %args::add %arg_lua
            
            %lua::add %args joined with ", "
            %lua::add ")"
            return %lua
        
        "EscapedNomsu":
            #return (Lua Value from %tree ((%tree.1)::as lua))
            %lua = (Lua Value from %tree ["a_Syntax_Tree_with_1{type=", quote %tree.(1).type])
            set {%needs_comma:no, %i:1}
            (% as shmua) means:
                if (% is a "Lua number"): return "\%"
                if (% is a "Syntax Tree"):
                    return (% compiled with %compile_actions)
                if (% is text): return (quote %)
                return (%::as lua)
            
            for %k = %v in (((%tree.(1).type == "EscapedNomsu") and %tree) or %tree.1):
                %lua::add ", "
                if:
                    (%k == %i): %i += 1
                    ((%k is text) and (%k::is a lua identifier)):
                        %lua::add [%k, "= "]
                    else:
                        %lua::add ["[", % as shmua, "]= "]
                
                if (%k == "source"):
                    %lua::add (quote "\%v")
                ..else:
                    %lua::add (%v as shmua)
            
            %lua::add "}"
            return %lua
        
        "Block":
            %lua = (Lua Code from %tree)
            %lua::add (..)
                ((%line compiled with %compile_actions)::as statements) for %line in %tree
            ..joined with "\n"
            
            return %lua
        
        "Text":
            %lua = (Lua Value from %tree)
            %lua_bits = []
            %string_buffer = ""
            for % in %tree:
                if (% is text):
                    %string_buffer = "\%string_buffer\%"
                    do next %
                
                if (%string_buffer != ""):
                    %lua_bits::add (%string_buffer::as lua)
                    %string_buffer = ""
                
                %bit_lua = (% compiled with %compile_actions)
                unless %bit_lua.is_value:
                    report compile error at % "\
                        ..Can't use this as a string interpolation value, since it doesn't have a value."
                
                if (%.type != "Text"):
                    %bit_lua = (Lua Value from % ["tostring(", %bit_lua, ")"])
                %lua_bits::add %bit_lua
            
            if ((%string_buffer != "") or ((size of %lua_bits) == 0)):
                %lua_bits::add (%string_buffer::as lua)
            %lua::add %lua_bits joined with ".."
            if ((size of %lua_bits) > 1): %lua::parenthesize
            return %lua
        
        "List":
            %lua = (Lua Value from %tree ["List{"])
            %lua::add ((% compiled with %compile_actions) for % in %tree) joined with ", " or ",\n  "
            %lua::add "}"
            return %lua
        
        "Dict":
            %lua = (Lua Value from %tree ["Dict{"])
            %lua::add ((% compiled with %compile_actions) for % in %tree) joined with ", " or ",\n  "
            %lua::add "}"
            return %lua
        
        "DictEntry":
            set {%key:%tree.1, %value:%tree.2}
            %key_lua = (%key compiled with %compile_actions)
            unless %key_lua.is_value:
                report compile error at %tree.1 "\
                    ..Can't use this as a dict key, since it's not an expression."
            
            %value_lua = (..)
                (%value compiled with %compile_actions) if %value else (..)
                    Lua Value from %key ["true"]
            
            unless %value_lua.is_value:
                report compile error at %tree.2 "\
                    ..Can't use this as a dict value, since it's not an expression."
            
            %key_str = ((%key_lua::as smext)::matching "^[\"']([a-zA-Z_][a-zA-Z0-9_]*)['\"]$")
            if:
                %key_str:
                    return (Lua Code from %tree [%key_str, "=", %value_lua])
                ((%key_lua::as smext).1 == "["):
                    # NOTE: this *must* use a space after the [ to avoid freaking out
                        Lua's parser if the inner expression is a long string. Lua
                        parses x[[[y]]] as x("[y]"), not as x["y"]
                    return (Lua Code from %tree ["[ ", %key_lua, "]=", %value_lua])
                
                else:
                    return (Lua Code from %tree ["[", %key_lua, "]=", %value_lua])
        
        "IndexChain":
            %lua = (%tree.1 compiled with %compile_actions)
            unless %lua.is_value:
                report compile error at %tree.1 "\
                    ..Can't index into this, since it's not an expression."
            
            %first_char = (%lua::as smext).1
            if (any of [%first_char == "{", %first_char == "\"", %first_char == "["]):
                %lua::parenthesize
            for %i in 2 to (size of %tree):
                %key = %tree.%i
                %key_lua = (%key compiled with %compile_actions)
                unless %key_lua.is_value:
                    report compile error at %key "\
                        ..Can't use this as an index, since it's not an expression."
                
                %key_lua_str = (%key_lua::as smext)
                %lua_id = (%key_lua_str::matching "^['\"]([a-zA-Z_][a-zA-Z0-9_]*)['\"]$")
                if:
                    %lua_id:
                        %lua::add [".", %lua_id]
                    (%key_lua_str.1 == "["):
                        # NOTE: this *must* use a space after the [ to avoid freaking out
                            Lua's parser if the inner expression is a long string. Lua
                            parses x[[[y]]] as x("[y]"), not as x["y"]
                        %lua::add ["[ ", %key_lua, " ]"]
                    
                    else:
                        %lua::add ["[", %key_lua, "]"]
            
            return %lua
        
        "Number":
            return (Lua Value from %tree ["\(%tree.1)"])
        "Var":
            return (Lua Variable from %tree [%tree.1::as lua id])
        "FileChunks":
            barf "\
                ..Can't convert FileChunks to a single block of lua, since each chunk's compilation depends on the earlier chunks"
        
        "Comment":
            # TODO: de-implement?
            return (Lua Code from %tree "-- \(%tree.1::with "\n" -> "\n-- ")")
        
        "Error":
            barf (%tree as a pretty error)
        else:
            barf "Unknown type: \(%tree.type)"