-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmain.lua
More file actions
1454 lines (1333 loc) · 81.7 KB
/
Copy pathmain.lua
File metadata and controls
1454 lines (1333 loc) · 81.7 KB
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
DEBUG = not fengari
package.path = "scripts/?.lua"
js = nil
if fengari then
js = require "js"
end
local line_number_start, line_number_end
local compile_file
local _cache = {}
-- Aliases for lookup speed
local find, match, sub, byte, format = string.find, string.match, string.sub, string.byte, string.format
local concat = table.concat
local co_resume, co_create, yield = coroutine.resume, coroutine.create, coroutine.yield
-- Defined here to pick up compile_file and line_number
function error_lexer(msg)
if type(msg) ~= "table" then
msg = {msg = msg}
end
local err_msg
if line_number_start == line_number_end then
err_msg = format("%s:%s: %s", compile_file, line_number_start, msg.msg)
else
err_msg = format("%s:%s-%s: %s", compile_file, line_number_start, line_number_end, msg.msg)
end
msg.msg = err_msg -- OK to modify arg because we're erroring away
error(msg)
end
function assert_parser(test, line, msg, ...)
if test then
return test
end
-- Have to convert the positions from 1-based to 0-based, which is what is
-- expected upstream.
local pos = {...}
for i = 1, #pos do
pos[i] = pos[i] - 1
end
error_lexer({msg = msg, line = line, markers = pos})
end
for _, lib in ipairs {"base64", "lexer-functions", "lexer-operators", "lexer-tokens", "lexer-debug", "lexer", "stdlib"} do
if DEBUG then
dofile(package.path:gsub("?", lib))
else
require(lib)
end
end
do
local assert_old = assert
local function assert_lexer(test, msg)
if not test then
error_lexer(msg)
end
return test
end
function pcallCompile(...)
local status, ret = pcall(compile, ...)
if status then
return status, ret
end
local data
if type(ret) == "userdata" then
-- Fengari has bugs where it can return a native JS exception object
ret = js.tostring(ret)
end
if type(ret) == "table" then
data = ret
else
data = {msg = ret}
end
data.file = ...
return false, data
end
function lua_main(func, arg1, arg2, arg3)
local status, ret
if func == "compile" then
assert = assert_lexer
local exported = {}
for i = 1, #arg1 do
local pair = arg1[i]
status, ret = pcallCompile(pair.name, pair.text, arg2, arg3)
if not status then
assert = assert_old
return status, ret
end
exported[i] = ret
end
assert = assert_old
return true, exported
elseif func == "import" then
status, ret = pcall(import, arg1)
if status then
return true, ret[1], ret[2]
end
elseif func == "unittest" then
status, ret = pcall(unittest)
else
assert(false, "BUG REPORT: unknown lua_main function: " .. func)
end
return status, ret
end
end
local function cache(line, variables)
local key = {}
for _, v in pairs(variables) do
key[#key+1] = format("%s.%s.%s.%s", v.scope, v.type, v.name, v.value)
end
table.sort(key)
key[#key+1] = line
key = concat(key, "¤")
if not _cache[key] then
_cache[key] = lexer(line, variables)
end
return _cache[key]
end
local parseMacro
local function handleOpenBrace(pattern, macroLine, pos, result, depth, opts)
while true do
local _, npos, res, pChar = find(macroLine, "^([^" .. pattern .. "]*)([" .. pattern .. "])", pos)
result[#result+1] = res or sub(macroLine, pos)
pos = (npos or #macroLine) + 1
if pChar ~= "{" then
return pChar, macroLine, pos
end
local orig_start = line_number_start
line_number_start = line_number_end
macroLine, pos = parseMacro(macroLine, pos, result, depth + 1, opts)
line_number_start = orig_start
end
end
-- Skip "offset" characters at the end and then trim a preceding newline iff
-- there is only whitespace between it and the last char.
-- This is used to trim the trailing newline on multiline macro defs and
-- calls, so that
-- {macro(
-- arg1,
-- arg2,
-- arg3)}
-- and
-- {macro(
-- arg1,
-- arg2,
-- arg3
-- )}
-- evaluate the same.
local function trimEndNl(str, offset)
str = sub(str, 1, -1 + offset)
local start = find(str, "\n[\t \v-\r]*$")
if start then
return sub(str, 1, start - 1)
end
return str
end
-- Returns the pair (macroLine, pos) containing the new line and parsing position.
-- The line is typically the same, but may have been advanced.
parseMacro = function(macroLine, pos, output, depth, opts)
assert_parser(depth < 100, macroLine, "macro expansion depth reached " .. depth .. ", probable infinite loop in:")
local result = {}
local macroName
local function evalMacro(macro_obj, ...)
local args = {...}
if #macro_obj.args ~= #args then
assert_parser(
false,
macroLine,
format("macro call {%s} has wrong number of args, expected %s but got %s", macroName, #macro_obj.args, #args),
pos - 1)
end
if macro_obj.raw then
output[#output+1] = macro_obj.raw
elseif macro_obj.func then
output[#output+1] = macro_obj.func(...)
else
local tmp_args = {}
for i = 1, #args do
tmp_args[macro_obj.args[i]] = {raw=args[i], args={}}
end
local posm = 1
local text = macro_obj.text
while posm <= #text do
local nposm = find(text, "{", posm, true)
output[#output+1] = sub(text, posm, (nposm or 0) - 1)
if not nposm then
break end
local orig_start = line_number_start
line_number_start = line_number_end
text, posm = parseMacro(text, nposm + 1, output, depth + 1, {
macros=opts.macros,
arg_macros=tmp_args,
get_input=function() end,
no_eval=opts.no_eval,
})
line_number_start = orig_start
end
end
end
local pChar
pChar, macroLine, pos = handleOpenBrace("{(}\n", macroLine, pos, result, depth, opts)
if not pChar or pChar == "\n" then
-- End of line. Unterminated macro is just returned as a literal text,
-- which is copied to the output buffer. We have to add the { that
-- *wasn't* included as part of our parsed text.
local off = #output + 1
output[off] = "{"
for i = 1, #result do
output[off + i] = result[i]
end
if pChar == "\n" then
-- Rewind because we have to parse this as part of the stream still
pos = pos - 1
end
return macroLine, pos
end
-- pChar is "}" or "(", either way we have the complete macro name.
macroName = concat(result)
result = {}
local macro_obj = opts.arg_macros[macroName] or opts.macros[macroName]
assert_parser(opts.no_eval or macro_obj, macroLine, "macro does not exist: {" .. macroName .. "}", pos - 1)
if pChar == "}" then
if opts.no_eval then
output[#output+1] = "{" .. macroName .. "}"
else
evalMacro(macro_obj)
end
return macroLine, pos
end
-- pChar is "(", we are parsing paramaters
local args = {}
local nesting = 1
-- Cache this to handle the no_eval case where we don't have a macro_obj
local rawarg = macro_obj and macro_obj.rawarg
while true do
-- The rawarg parsing mode does not count matching parens and always has
-- only a single arg. The same code handles both modes, we simply don't go
-- down the branches to handle parens by never matching those characters.
pChar, macroLine, pos = handleOpenBrace(rawarg and "{}" or "{(,)}", macroLine, pos, result, depth, opts)
if not pChar then
-- End of line. Get more input, since non-simple macros can span lines.
local nextline = opts.get_input()
assert_parser(nextline, macroLine, "unexpected EOF getting args for {" .. macroName .. "}", #macroLine + 1)
macroLine = nextline
pos = 1
else
if pChar == "}" then
if not rawarg and nesting > 0 then
assert_parser(
false,
macroLine,
format("%s unclosed parenthesis inside macro {%s}", nesting, macroName),
pos - 1)
end
-- The empty macroName here implies the {(} macro, or at least the
-- beginning of it. It doesn't close in the usual way.
if macroName == "" then
local arg = concat(result)
assert_parser(#arg == 0, macroLine, "{(} macro has extra junk in it", pos - 2)
if opts.no_eval then
output[#output+1] = "{(}"
else
evalMacro(opts.macros["("])
end
else
if rawarg then
if byte(macroLine, pos - 2, pos - 2) ~= 0x29 then
-- Not an error, for rawarg continue until we find ")}"
result[#result+1] = "}"
goto continue
end
end
local arg = concat(result)
if not rawarg then
assert_parser(sub(arg, -1) == ")", macroLine, "trailing junk after macro call {" .. macroName .. "}", pos - 2)
end
arg = trimEndNl(arg, -1) -- Also trims the closing paren off
if byte(arg, 1, 1) == 0xa and not opts.no_eval then
-- If a new param (open paren or comma) is immediately followed by
-- newline, we want to swallow the initial newline.
arg = sub(arg, 2)
end
args[#args+1] = arg
if opts.no_eval then
output[#output+1] = "{" .. macroName .. "(" .. concat(args, ",") .. ")}"
else
evalMacro(macro_obj, table.unpack(args))
end
end
return macroLine, pos
elseif pChar == "(" then
assert_parser(nesting > 0, macroLine, "tried to re-open macro args calling {" .. macroName .. "}", pos - 1)
nesting = nesting + 1
result[#result+1] = "("
elseif pChar == "," then
if nesting == 1 then
local arg = concat(result)
if byte(arg, 1, 1) == 0xa and not opts.no_eval then
-- If a new param (open paren or comma) is immediately followed by
-- newline, we want to swallow the initial newline.
arg = sub(arg, 2)
end
args[#args+1] = arg
result = {}
else
result[#result+1] = ","
end
elseif pChar == ")" then
assert_parser(nesting > 0, macroLine, "extra closing parens calling {" .. macroName .. "}", pos - 1)
nesting = nesting - 1
result[#result+1] = ")"
-- We always add the paren to args here. This allows both the rawarg
-- and regular code to follow the same path for adding the final
-- arg. This also means that any text that comes *after* this paren
-- will get added to the last arg, but that's an error we check for.
else
assert_parser(false, macroLine, "BUG_REPORT: unhandled case in parseMacro {" .. macroName .. "}", pos - 1)
end
::continue::
end
end
end
-- Whitelist of functions and tables that are allowed in the lua() macro. We
-- store this as a string, so that we can bind the names properly.
local globals_whitelist = {}
for k in string.gmatch([[assert
error
getmetatable
ipairs
load
next
pairs
pcall
print
rawequal
rawget
rawlen
rawset
select
setmetatable
tonumber
tostring
type
_VERSION
xpcall
coroutine
string
utf8
table
math]], "%g+") do globals_whitelist[#globals_whitelist+1] = k end
local os_whitelist = {'clock', 'date', 'difftime', 'time'}
local function filter_table(table_in, whitelist)
res = {}
for i = 1, #whitelist do
local k = whitelist[i]
local v = table_in[k]
if type(v) == 'table' then
local new_tab = {}
for k2, v2 in pairs(v) do
new_tab[k2] = v2
end
v = new_tab
end
res[k] = v
end
return res
end
local function clone_global()
local new_g = filter_table(_G, globals_whitelist)
new_g.os = filter_table(_G.os, os_whitelist)
new_g._G = new_g
return new_g
end
local function is_empty(line)
return find(line, "^%s*$") or find(line, "^%s*;.*$")
end
local json_escape_table = {["\\"]=[[\\]], ['"']=[[\"]]}
for i = 0, 31 do
json_escape_table[string.char(i)] = format([[\u%04x]], i)
end
json_escape_table["\b"] = [[\b]]
json_escape_table["\f"] = [[\f]]
json_escape_table["\n"] = [[\n]]
json_escape_table["\r"] = [[\r]]
json_escape_table["\t"] = [[\t]]
local line_encode_table = {}
local utf_decode_table = {}
for k, v in pairs(json_escape_table) do
line_encode_table[k] = v
end
for i = 0x80, 0xff do
line_encode_table[string.char(i)] = utf8.char(i)
utf_decode_table[utf8.char(i)] = string.char(i)
end
-- importFunc takes a string (filename) and returns a pair of (status, string)
-- (the content of the imported file on success, an error message on failure).
function compile(name, input, options, importFunc)
local variables, impulses, conditions, actions = {}, {}, {}, {}
local budget, use_budget
local env = clone_global()
local macros, native_create_get_line
local set_native_compile_file = function() end
if native_macros and options.fastMacro then
native_create_get_line, set_native_compile_file = native_macros(env)
else
macros = {
-- This entry is also used for {(} since that looks like an argument-macro
-- with no name, depending on how it is parsed. An expression like {{(}}
-- will parse one way for the inner macro and another (using the later
-- entry) for the outer macro, since the substituted paren doesn't act
-- like a delimiter and instead forms part of the name of a simple macro.
[""] = {args = {}, raw = "{}", rawarg = true},
["["] = {args = {}, raw = "{"},
["]"] = {args = {}, raw = "}"},
["("] = {args = {}, raw = "("},
[")"] = {args = {}, raw = ")"},
[","] = {args = {}, raw = ","},
len = {args = {"#"}, rawarg = true, func = function(arg_body)
return tostring(#arg_body)
end},
lua = {args = {"#"}, rawarg = true, func = function(lua_text)
local chunk, err = load(lua_text, lua_text, "t", env)
assert(chunk, err)
local status, result = pcall(chunk)
if status then
return tostring(result or "")
end
error_lexer(result)
end},
}
end
local imported = {}
local ret = {}
local function import(filename, input, isImport)
if imported[filename] then
return {}
end
imported[filename] = true
line_number_end = 0
compile_file = filename
local lines = {}
local labelCache = {}
local function create_get_line(__, input)
local input_it = string.gmatch(input, "([^\n]*(\n?))")
-- Handles stripping backslashes and tracking line-numbers
local function get_input_line()
local inp, last = input_it()
if not inp then
return end
line_number_end = line_number_end + 1
if last ~= "\n" or byte(inp, -2) ~= 0x5c then
return inp end
return sub(inp, 1, -3)
end
local in_macro_def = false
local parse_macro_opts = {
macros = macros,
arg_macros = {},
get_input = get_input_line,
no_eval = false,
}
-- Handles incremental macro expansion
-- There is feedback between this function and the next stage, via in_macro_def.
-- This is because this function parses macros, but the next stage handles
-- macro definitions. It *must* be arranged this way, because macro
-- definitions can be started from within (the expanded text of) a macro.
-- Why? Because I like making things hard for myself.
-- Since macros aren't parsed when defining a macro, this (earlier) stage
-- needs feedback from the later stage to know when it is or isn't
-- expanding macros. This function passes all the text needed to make that
-- determination (right up to the opening "{"), and then the next part
-- sets the flag appropriately so that parsing can proceed.
local get_chunk
do
local pos, line
get_chunk = function()
if not line or pos > #line then
pos = 1
line = get_input_line()
end
if not line then
return nil, line_number_end
end
local npos = find(line, "{", pos + 1, true)
if not npos then
npos = #line + 1
end
local start = line_number_end
if in_macro_def or byte(line, pos, pos) ~= 0x7b then -- {
local ret = sub(line, pos, npos - 1)
pos = npos
return ret, start
else
local output = {}
local orig_start = line_number_start
line_number_start = start
line, pos = parseMacro(line, pos + 1, output, 1, parse_macro_opts)
line_number_start = orig_start
return concat(output), start
end
end
end
local line, next_start, pos
local output = {}
local function read_until(pattern)
while true do
if not line then
return end
local npos = find(line, pattern, pos)
if npos then
output[#output+1] = sub(line, pos, npos - 1)
pos = npos
return byte(line, pos, pos)
end
output[#output+1] = sub(line, pos)
line, next_start = get_chunk()
pos = 1
end
end
return function()
repeat
local _, npos, rest
in_macro_def = false
if not line then
line, next_start = get_chunk()
pos = 1
end
line_number_start = next_start
local pChar = read_until("[^\t \v-\r]")
if not pChar then
return nil, line_number_start, line_number_end
end
in_macro_def = (pChar == 0x23) -- #
output = {}
if not in_macro_def then
read_until("\n")
pos = pos + 1
else
-- We're not sure what type of macro def we have yet, so we can
-- only parse as far as we're sure will remain in the def.
-- At the same time, we need enough to be *able* to match the
-- macro pattern and recognize the type. Looking at the minimum
-- of "to newline" and "to closing brace" meets this condition.
pChar = read_until("[\n{]")
-- We need the character that we stopped on, as well. Being at the
-- end of the input is a valid case here.
if pChar then
output[#output+1] = string.char(pChar)
end
pos = pos + 1
local result = concat(output)
local _, apos, name = find(result, TOKEN.identifier.pattern, 2)
assert_parser(name, result, "macro definition: #name <text> or #name(args...) <text> or #name(args...)={<text>}", 2)
apos = apos + 1
local macro_args = match(result, "^%([%w%._$\x80-\xff%s,]+%)", apos) or ""
apos = apos + #macro_args
local macro_type = sub(result, apos, apos + 1)
if macro_type ~= "={" then
macro_type = sub(macro_type, 1, 1)
apos = apos + 1
assert_parser(find(" \t\v\f\r", macro_type, 1, true), result, "macro definition: #name <text> or #name(args...) <text> or #name(args...)={<text>}", 2)
else
apos = apos + 2
end
local args = {}
local arg_begin = 2
local macro = {args = args, rawarg = false}
while arg_begin <= #macro_args do
local apos = find(macro_args, ",", arg_begin, true)
if not apos then
apos = #macro_args
end
local arg_string = sub(macro_args, arg_begin, apos - 1)
local arg = match(arg_string, "^%s*([%a_$\x80-\xff][%w._\x80-\xff]*)%s*$")
assert_parser(arg, result, "bad macro function argument name: " .. arg_string, #name + 2 + arg_begin)
if byte(arg, 1, 1) == 0x24 then -- $
macro.rawarg = true
arg = sub(arg, 2)
end
assert_parser(#arg > 0, result, "empty macro function argument name", #name + 2 + arg_begin)
assert_parser(
not macro.rawarg or #args == 0,
result,
"$rawarg parsing has multiple arguments: " .. arg,
#name + 2 + arg_begin)
for i=1, #args do
if arg == args[i] then
assert_parser(false, result, "duplicate function argument name: " .. arg, #name + 2 + arg_begin)
end
end
args[#args+1] = arg
arg_begin = apos + 1
end
assert_parser(not macros[name], result, "macro already exists: " .. name, 2)
output = {sub(result, apos)}
-- Now that we have checked the header info and know the type, read the full body.
if macro_type ~= "={" then
if pChar ~= 0xa then -- \n
pChar = read_until("\n")
end
pos = pos + 1
-- For compatibility with previous implementations of this code,
-- the non-braced version trims whitespace at the end of the body.
-- To keep significant whitespace, use the braced form.
macro.text = concat(output):gsub("%s+$", "")
else
local opts = {
macros = macros,
arg_macros = {},
get_input = function()
local r
r, next_start = get_chunk()
return r
end,
no_eval = true,
}
pChar = nil
while pChar ~= "}" do
pChar, line, pos = handleOpenBrace("{}", line, pos, output, 1, opts)
if not pChar then
-- End of line. Get more input, since the point of the
-- multiline macro def is to span lines.
local nextline
nextline, next_start = get_chunk()
if not nextline then
local res = concat(output)
assert_parser(
false,
res,
"unexpected EOF looking for end of multiline macro {" .. name .. "}",
#res + 1)
end
line = nextline
pos = 1
end
end
result = concat(output)
result = trimEndNl(result, 0)
if byte(result, 1, 1) == 0xa then -- \n
-- If the openeing brace is immediately followed by
-- newline, we want to swallow the initial newline.
result = sub(result, 2)
end
macro.text = result
-- Leftover text forms the beginning of a new syntactic line
end
macros[name] = macro
end
if line and pos > #line then
line = nil
end
until not in_macro_def
return concat(output):gsub("%s+$", ""), line_number_start, line_number_end
end -- get_line
end -- create_get_line
local get_line = native_create_get_line and native_create_get_line(compile_file, input) or create_get_line(compile_file, input)
while true do
local line
line, line_number_start, line_number_end = get_line()
if not line then
break
end
if find(line, "^:") then
local token = line:match("^:" .. TOKEN.identifier.patternAnywhere)
if token == "const" then
local _, type, name, value = line:sub(2):match("^(%a+) (%a+) " .. TOKEN.identifier.patternAnywhere .. " (.+)$")
assert(type, "constant definition: const [int/double/string/bool/vector] name value")
assert(({bool=true, int=true, double=true, string=true, vector=true})[type], "constant types are 'int', 'double', 'string', 'bool', and 'vector'")
if (type == "int" or type == "double") then
local x = tonumber(value)
assert(x, "Can't convert '" .. value .. "' to a number")
local vtype = math.type(x) == "integer" and "int" or "double"
assert(vtype == type, "bad argument, " .. type .. " expected, got " .. vtype .. " " .. value)
value = x
elseif (type == "bool") then
assert(value:match"^true$" or value:match"^false$", "bool values are 'true' or 'false'")
if value:match"^true$" then
value = true
else
value = false
end
elseif (type == "string") then
value = value:match"^%b''$" or value:match'^%b""$'
assert(value, "strings must be enclosed in either single quotes or double quotes")
value = value:sub(2,-2)
elseif type == "vector" then
local matches = table.pack(value:match"^vec%((.+),(.+)%)$")
assert(matches.n > 1, "vector constants must use vec(x, y) syntax")
local x = tonumber(matches[1])
assert(x, "Can't convert '" .. matches[1] .. "' to a number")
local y = tonumber(matches[2])
assert(y, "Can't convert '" .. matches[2] .. "' to a number")
value = {x = x, y = y}
end
assert(not variables[name], "variable/label/constant already exists: " .. name)
variables[name] = {name = name, scope = "constant", type = type, value = value}
elseif token == "import" then
local import_name = line:match("^:%a+ +(.+)")
assert(import_name, "import directive: :import file")
local status, import_result = importFunc(import_name)
assert(status, "Import failed: " .. import_result)
local saved = {line_number_start, line_number_end, compile_file}
import(import_name, import_result, true)
-- These got stomped by the import, re-set them
line_number_start, line_number_end, compile_file = table.unpack(saved)
set_native_compile_file(compile_file)
elseif token == "global" or token == "local" then
local scope, type, name = line:sub(2):gsub(" *;.*", ""):match("^(%a+) +(%a+) +" .. TOKEN.identifier.patternAnywhere .."$")
assert(scope, "variable definition: [global/local] [bool/int/double/string/vector] name")
assert(({bool=true, int=true, double=true, string=true, vector=true})[type], "variable types are 'bool', 'int', 'double', 'string', and 'vector'")
assert(not variables[name], "variable/label already exists: " .. name)
variables[name] = {name = name, scope = scope, type = type}
elseif token == "name" then
local name = line:match("^:%a+ +(.+)")
assert(name, "name directive: :name script_name")
compile_file = name
set_native_compile_file(name)
elseif token == "budget_cap" then
local cost = line:match("^:budget_cap +(.+)")
if cost and cost ~= "max" then
cost = tonumber(cost)
if cost then
assert(-2147483648 <= cost and cost < 2147483648,
"budget_cap must fit in an integer (-2^31 <= cost < 2^31), got " .. cost)
end
end
assert(cost, "budget_cap directive: :budget_cap [max/<integer>]")
budget = cost
elseif token == "use_budget" then
use_budget = line:match("^:use_budget +(.+)")
assert(use_budget == "true" or use_budget == "false" or use_budget == "default",
"use_budget directive: :use_budget [true/false/default]")
else
assert(false, "Unrecognized directive :" .. (token or line:sub(2)))
end
else
line = line
:gsub(TOKEN.identifier.pattern .. ":", function(name)
assert(not variables[name] or labelCache[name], "variable/label already exists: " .. name)
variables[name] = {name = name, scope = "local", type = "int", label = 0}
table.insert(labelCache, name)
return ""
end)
if not is_empty(line) then
assert_parser(not isImport, line,
"Imported files can't produce output, they must only contain variable and macro declarations")
table.insert(lines, {text = line, num_start = line_number_start, num_end = line_number_end, label = labelCache})
labelCache = {}
end
end
end
-- anything left in the label cache points to the end of the script
for _, label in ipairs (labelCache) do
variables[label].label = 99
end
return lines
end -- function import
import("__stdlib__", STDLIB, true)
local lines = import(name, input, false)
for _, line in ipairs (lines) do
line_number_start = line.num_start
line_number_end = line.num_end
local node = cache(line.text, variables)
if node and node.func then
if node.func.ret == "void" then
table.insert(actions, node)
if #(line.label) > 0 then
for _, label in ipairs (line.label) do
variables[label].label = #actions
end
end
else
assert(#(line.label) == 0, "labels cannot be placed before impulses/conditions")
if node.func.ret == "impulse" then
table.insert(impulses, node)
else
table.insert(conditions, node)
end
end
end
end
local function ins(frmt, val)
ret[#ret+1] = string.pack(frmt, val)
end
local function prefix_code(size)
while size >= 0x80 do
ret[#ret+1] = string.pack("B", 0x80 + (size & 0x7F))
size = size >> 7
end
ret[#ret+1] = string.pack("B", size)
end
local function encode(node)
if node.func then
if node.func.name == "label" then
local var = node.args[1].value
assert(variables[var] and variables[var].label, "why are you calling the label function manually?")
encode{type = "number", value = variables[var].label}
return
end
prefix_code(#node.func.name)
ret[#ret+1] = node.func.name
for _, arg in ipairs (node.args) do
encode(arg)
end
else
ins("s1", "constant")
if node.type == "bool" then
ins("b", 1)
ins("b", node.value and 1 or 0)
elseif node.type == "number" then
if math.type(node.value) == "integer" then
ins("b", 2)
ins("i4", node.value)
else
ins("b", 3)
ins("d", node.value)
end
elseif node.type == "string" then
ins("b", 4)
prefix_code(#node.value)
ret[#ret+1] = node.value
elseif node.type == "vector" then
ins("b", 5)
ins("f", node.value.x)
ins("f", node.value.y)
elseif node.type == "operator" then
ins("b", 4)
if node.value == "%" then
node.value = "mod"
elseif node.value == "^" then
node.value = "pow"
elseif node.value == "//" then
node.value = "log"
elseif node.value == "%&" then
node.value = "and"
elseif node.value == "%^" then
node.value = "xor"
elseif node.value == "%|" then
node.value = "or"
end
ins("s1", node.value)
else
assert(false, "BUG REPORT: unknown compile type: " .. node.type)
end
end
end
local gsub = string.gsub
local function json_encode(node)
local current_pos = #ret
encode(node)
for i = current_pos+1, #ret do
-- Need to JSON-escape control characters, backslash and double-quote,
-- and also UTF-8 encode high-byte chars
ret[i] = gsub(ret[i], '[\0-\x1f\\"\x80-\xff]', line_encode_table)
end
end
local function json_escape(str)
ret[#ret+1] = gsub(str, '[\0-\x1f\\"]', json_escape_table)
end
local package_name, script_name = compile_file:match("([^:]*):(.*)")
if not script_name then
script_name = compile_file
end
if options.format ~= "v2" then
prefix_code(#compile_file)
ret[#ret+1] = compile_file
for _, tbl in ipairs {impulses, conditions, actions} do
ins("i4", #tbl)
for _, line in ipairs (tbl) do
encode(line)
end
end
ret = base64.encode(table.concat(ret))
else
for num, pair in ipairs({
{name="actions", tbl=actions},
{name="conditions", tbl=conditions},
{name="impulses", tbl=impulses}
}) do
ret[#ret+1] = num == 1 and [[{"]] or [[],"]]
ret[#ret+1] = pair.name
ret[#ret+1] = [[":[]]
for num, line in ipairs(pair.tbl) do
if num ~= 1 then
ret[#ret+1] = [[,]]
end
ret[#ret+1] = [["]]
if pair.name == "impulses" then
ret[#ret+1] = line.func.name -- Impulses are no-arg functions with straight ASCII names
else
json_encode(line)
end
ret[#ret+1] = [["]]
end
end
ret[#ret+1] = [[],"name":"]]
json_escape(script_name)
ret[#ret+1] = [[","package":"]]
json_escape(package_name or "")
ret[#ret+1] = [["]]
if budget then
ret[#ret+1] = [[,"budget":]]
-- No quotes because budget is a number in the JSON
ret[#ret+1] = budget == "max" and "-1" or string.format("%d", budget)
end
if use_budget ~= "default" and (use_budget or budget) then
ret[#ret+1] = [[,"useBudget":]]
-- No quotes because useBudget is a boolean in the JSON
ret[#ret+1] = use_budget or "true"
end
ret[#ret+1] = [[}]]
ret = table.concat(ret)
end
package_name = package_name and package_name:sub(1, 24) .. ":" or ""
script_name = script_name:sub(1, 24)
return {
name = package_name .. script_name,
type = "script",
impulses = #impulses,
conditions = #conditions,
actions = #actions,
code = ret,
}
end
function import(input)
local data
local pos = 1
local variables = {}
local num_vars = 0
local ret = {}
local function read(frmt)
local ret, new = string.unpack(frmt, data, pos)
pos = new
return ret
end