-
Notifications
You must be signed in to change notification settings - Fork 3
/
testsuite.lua
1382 lines (1161 loc) · 43.8 KB
/
testsuite.lua
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
--
-- Test suite for Dumb Lua Parser
--
local PRETTY_OUTPUT = 1==1
local PRINT_IDS = 1==1
local PRINT_LOCATIONS = 1==1
local EXIT_ON_ERROR = 1==0
collectgarbage("stop")
io.stdout:setvbuf("no")
io.stderr:setvbuf("no")
local loadstring = loadstring or load
local parser = require"dumbParser"
parser.printIds = PRINT_IDS
parser.printLocations = PRINT_LOCATIONS
local testCount = 0
local failCount = 0
local results = {}
local function assert(v, err)
if v then return v end
err = tostring(err or "Assertion failed!")
error(debug.traceback(err, 2), (err:find"^Error @" and 0 or 2))
end
-- assertLua( lua, expectedLua [, expectedLuaAlt ] [, level=1 ] )
local function assertLua(lua, expectedLua, expectedLuaAlt, level)
if type(expectedLuaAlt) ~= "string" then
expectedLuaAlt, level = nil, expectedLuaAlt
end
lua = lua :gsub("^%s+", ""):gsub("%s+$", "")
expectedLua = expectedLua :gsub("^%s+", ""):gsub("%s+$", "")
expectedLuaAlt = expectedLuaAlt and expectedLuaAlt:gsub("^%s+", ""):gsub("%s+$", "")
if lua == expectedLua then return end
if lua == expectedLuaAlt then return end
error(string.format(
"Unexpected Lua output.\n%s\nExpected:\n%s\n%s\nGot:\n%s\n%s",
("-"):rep(64),
expectedLua,
("-"):rep(64),
lua,
("-"):rep(64)
), 1+(level or 1))
end
local function debugExit()
print("!!! DEBUG EXIT !!!")
os.exit(2)
end
local function where(node, message)
print(parser.formatMessage(node, tostring(message or node.type)))
end
local function printStats(stats, locLevel)
print("Stats:")
print(" nodeRemoveCount: "..stats.nodeRemoveCount)
print(" renameCount: "..stats.renameCount)
print(" generatedNameCount: "..stats.generatedNameCount)
if locLevel == 1 then
print(" nodeReplacements: "..#stats.nodeReplacements)
print(" nodeRemovals: "..#stats.nodeRemovals)
else
print(" nodeReplacements:")
for i, loc in ipairs(stats.nodeReplacements) do
if locLevel == 2 then
print(" "..loc.sourcePath..":"..loc.line)
else
print(" "..parser.formatMessage(
loc, "Node replacement %d/%d (%s -> %s)",
i, #stats.nodeReplacements, loc.node.type, (loc.replacement and loc.replacement.type or "?")
):gsub("\n", "\n "))
end
end
print(" nodeRemovals:")
for i, loc in ipairs(stats.nodeRemovals) do
if locLevel == 2 then
print(" "..loc.sourcePath..":"..loc.line)
else
print(" "..parser.formatMessage(
loc, "Node removal %d/%d (%s)",
i, #stats.nodeRemovals, loc.node.type
):gsub("\n", "\n "))
end
end
end
end
local function test(label, f)
testCount = testCount + 1
print("Running test: "..label)
-- f() -- DEBUG
local ok, err = pcall(f)
if ok then
print("Test succeeded!")
else
io.stderr:write(err, "\n")
if EXIT_ON_ERROR then os.exit(1) end
failCount = failCount + 1
print("Test failed!")
end
table.insert(results, {label=label, ok=ok, err=err})
end
--[[ Benchmark.
do
local PATH = "dumbParser.lua"
-- local PATH = "test.lua"
local file = assert(io.open(PATH, "r"))
local lua = file:read("*a")
file:close()
local time, tokens = os.clock()
for i = 1, 10 do
tokens = assert(parser.tokenize(lua, PATH))
end
local timeTokenize = os.clock() - time
local time, ast = os.clock()
for i = 1, 10 do
ast = assert(parser.parse(tokens))
end
local timeParse = os.clock() - time
print("tokenize="..timeTokenize.." parse="..timeParse)
debugExit()
end
--]]
test("Test file / misc.", function()
local PATH = "test.lua"
-- local PATH = "dumbParser.lua"
if _VERSION >= "Lua 5.4" then
assert(loadfile("test.lua"))
end
local tokens = assert(parser.tokenizeFile(PATH))
local ast = assert(parser.parse(tokens))
-- parser.printTree(ast)
-- debugExit()
assert(parser.validateTree(ast))
--[[
parser.traverseTree(ast, function(node, parent, container, k)
io.write(tostring(container), ".", tostring(k), " ")
parser.printNode(node)
-- if container then
-- container[k] = parser.newNode("call")
-- container[k].callee = parser.newNode("identifier", "foo")
-- end
end)
--]]
parser.traverseTree(ast, function(node)
if node.type == "identifier" and node.name == "foo" then
node.name = "dog"
end
end)
parser.updateReferences(ast)
-- parser.printTree(ast)
-- print(parser.toLua(ast, 1==1))
-- debugExit()
-- local stats = parser.optimize(ast) ; printStats(stats, 3)
-- parser.printTree(ast)
-- print(parser.toLua(ast, 1==1))
-- debugExit()
-- local stats = parser.minify(ast, 1==1) ; printStats(stats, 3)
-- parser.printTree(ast)
-- print(parser.toLua(ast, 1==1))
-- debugExit()
local lua = assert(parser.toLua(ast, PRETTY_OUTPUT))
if 1==1 then
local luaEdit = lua
-- luaEdit = luaEdit:gsub(("."):rep(250), "%0\0")
-- luaEdit = luaEdit:gsub("([%w_]+)%z([%w_]+)", "%1%2\n")
-- luaEdit = luaEdit:gsub("%z", "\n")
print(luaEdit)
-- debugExit()
end
if _VERSION >= "Lua 5.4" then
assert(loadstring(lua, "@<luastring>"))
end
-- Round-trip.
local tripAst = assert(parser.parse(lua))
local tripLua = assert(parser.toLua(tripAst, PRETTY_OUTPUT))
if tripLua ~= lua then
print(("-"):rep(64))
print(lua)
print(("-"):rep(64))
print(tripLua)
print(("-"):rep(64))
error("Failed AST round-trip.")
end
-- Callback for toLua().
do
local visited = {}
local ok = true
local luaWithExtras = assert(parser.toLua(ast, true, function(node, buffer)
if visited[node] then
ok = false
io.write("Multiple visits for: ")
parser.printNode(node)
else
visited[node] = true
if (buffer[#buffer] or ""):find"%-$" then table.insert(buffer, " ") end
table.insert(buffer, "--[[")
table.insert(buffer, node.type)
table.insert(buffer, "]]")
end
end))
parser.traverseTree(ast, function(node)
if visited[node] then return end
ok = false
io.write("No callack for: ")
parser.printNode(node)
end)
-- print(luaWithExtras)
assert(ok)
if _VERSION >= "Lua 5.4" then
assert(loadstring(luaWithExtras, "@<luastring>"))
end
end
end)
test("Tokens", function()
do
local tokens = assert(parser.tokenizeFile("test.lua"))
-- parser.printTokens(tokens)
local concatted = parser.concatTokens(tokens)
-- print(concatted)
-- Round-trip.
local tripTokens = assert(parser.tokenize(concatted))
local tripConcatted = parser.concatTokens(tripTokens)
if concatted ~= tripConcatted then
print(("-"):rep(64))
print((concatted:gsub("\n", "\\n")))
print(("-"):rep(64))
print((tripConcatted:gsub("\n", "\\n")))
print(("-"):rep(64))
error("Failed token round-trip.")
end
end
do
local tokens = {}
-- Construct a call.
table.insert(tokens, parser.newToken("identifier", "lib"))
table.insert(tokens, parser.newToken("punctuation", "."))
table.insert(tokens, parser.newToken("identifier", "doThing"))
table.insert(tokens, parser.newToken("whitespace", " "))
table.insert(tokens, parser.newToken("punctuation", "("))
table.insert(tokens, parser.newToken("punctuation", "-"))
table.insert(tokens, parser.newToken("number", 1.75))
table.insert(tokens, parser.newToken("punctuation", ","))
table.insert(tokens, parser.newToken("string", "foo"))
table.insert(tokens, parser.newToken("punctuation", ")"))
table.insert(tokens, parser.newToken("comment", "Blah!"))
-- Add the call to a declaration, but with an error.
table.insert(tokens, 1, parser.newToken("keyword", "local"))
table.insert(tokens, 2, parser.newToken("identifier", "x"))
table.insert(tokens, 3, parser.newToken("punctuation", "="))
table.insert(tokens, 4, parser.newToken("punctuation", "/")) -- Error!
-- Remove the error.
table.remove(tokens, 4)
-- Update all tokens (with no modifications).
for _, tok in ipairs(tokens) do
parser.updateToken(parser.cloneToken(tok), tok.value)
end
local ast = assert(parser.parse(tokens))
local lua = assert(parser.toLua(ast))
-- print(lua)
assertLua(lua, [[ local x=lib.doThing(-1.75,"foo"); ]])
end
do
-- Test keepWhitespaceTokens flag.
local tokens = assert(parser.tokenize([[ local x --[=[ ]=] = foo ; ]], true))
local concatted = parser.concatTokens(tokens)
assert(concatted == [[ local x --[=[ ]=] = foo ; ]], concatted)
end
end)
test("AST manipulation", function()
-- Basics.
do
local block = assert(parser.parse([[
local x = 49
]], "<luastring>"))
assert(block.type == "block")
assert(block.statements[1])
assert(block.statements[1].type == "declaration")
assert(block.statements[1].names[1])
assert(block.statements[1].names[1].type == "identifier")
assert(block.statements[1].names[1].name == "x")
assert(block.statements[1].values[1])
assert(block.statements[1].values[1].type == "literal")
assert(block.statements[1].values[1].value == 49)
assert(not parser.isExpression(block))
assert( parser.isExpression(block.statements[1].names[1]))
block.statements[1].names[1] = parser.newNode("identifier", "foo")
block.statements[1].values[1] = parser.newNode("literal", 8.125)
local lua = assert(parser.toLua(block, PRETTY_OUTPUT))
print(lua)
assert(loadstring(lua, "@<luastring>"))
end
do
local binary = assert(parser.parseExpression([[
x + y ^ 49
]], "<luastring>"))
assert(binary.type == "binary")
assert(binary.left.type == "identifier")
assert(binary.left.name == "x")
assert(binary.right.type == "binary")
assert(binary.right.left.type == "identifier")
assert(binary.right.left.name == "y")
assert(binary.right.right.type == "literal")
assert(binary.right.right.value == 49)
local lua = assert(parser.toLua(binary, PRETTY_OUTPUT))
print(lua)
assert(loadstring("return "..lua, "@<luastring>"))
end
-- Node creation.
do
local identifier1 = parser.newNode("identifier", "foo")
local identifier2 = parser.newNode("identifier", "foo", "const")
local vararg = parser.newNode("vararg")
local literal1 = parser.newNode("literal", 8.125)
local literal2 = parser.newNode("literal", "foo")
local literal3 = parser.newNode("literal", true)
local literal4 = parser.newNode("literal", nil)
local tableNode = parser.newNode("table")
local lookup = parser.newNode("lookup")
local unary1 = parser.newNode("unary", "#")
local unary2 = parser.newNode("unary", "not")
local binary1 = parser.newNode("binary", "/")
local binary2 = parser.newNode("binary", "<<")
local call = parser.newNode("call")
local functionNode = parser.newNode("function")
local breakNode = parser.newNode("break")
local returnNode = parser.newNode("return")
local label = parser.newNode("label", "foo")
local gotoNode = parser.newNode("goto", "foo")
local block = parser.newNode("block")
local declaration = parser.newNode("declaration")
local assignment = parser.newNode("assignment")
local ifNode = parser.newNode("if")
local whileLoop = parser.newNode("while")
local repeatLoop = parser.newNode("repeat")
local forLoop = parser.newNode("for", "numeric")
assert( parser.isExpression(identifier1))
assert(not parser.isStatement (identifier1))
assert(not parser.isExpression(block))
assert( parser.isStatement (block))
assert( parser.isExpression(call))
assert( parser.isStatement (call))
parser.setChild(call, "callee", identifier1)
parser.setChild(declaration, "names", 1, identifier2)
parser.addChild(tableNode, "fields", literal2, literal1)
local node = parser.getChild(call, "callee") ; parser.printNode(node)
local node = parser.getChild(declaration, "names", 1) ; parser.printNode(node)
local node = parser.getChild(tableNode, "fields", 1, "value") ; parser.printNode(node)
parser.removeChild(tableNode, "fields", 1)
end
-- Cloning.
do
local ast = assert(parser.parseFile("test.lua"))
do
local clone = parser.cloneNode(ast)
assert(clone.type == "block")
parser.traverseTree(clone, function(node)
assert(node == clone)
end)
end
local lua1 = assert(parser.toLua(ast))
local clone = parser.cloneTree(ast)
parser.traverseTreeReverse(ast, true, function(node, parent, container, key)
if container then
container[key] = nil -- This should not affect the clone.
end
end)
local lua2 = assert(parser.toLua(clone))
assertLua(lua1, lua2)
end
-- Value to AST.
do
local expr = parser.valueToAst({
foo = "bar",
[3] = {"Abc.", left="right"},
{123, {x=-8}},
}, true)
-- parser.printLocations = false
parser.printTree(expr)
local lua = parser.toLua(expr)
-- print(lua)
assertLua(lua, [[ {[3]={left="right","Abc."},foo="bar",{123,{x=-8}}} ]])
-- debugExit()
end
end)
test("Call and lookup parsing", function()
assert( parser.parse([[ x = tbl () ]], "<luastring>"))
assert( parser.parse([[ x = tbl "" ]], "<luastring>"))
assert( parser.parse([[ x = tbl .m() ]], "<luastring>"))
assert( parser.parse([[ x = tbl :m"" ]], "<luastring>"))
assert( parser.parse([[ x = (tbl) () ]], "<luastring>"))
assert( parser.parse([[ x = (tbl) "" ]], "<luastring>"))
assert( parser.parse([[ x = (tbl).m() ]], "<luastring>"))
assert( parser.parse([[ x = (tbl):m"" ]], "<luastring>"))
assert(not parser.parse([[ x = " " () ]], "<luastring>"))
assert(not parser.parse([[ x = " " "" ]], "<luastring>"))
assert(not parser.parse([[ x = " " .m() ]], "<luastring>"))
assert(not parser.parse([[ x = " " :m"" ]], "<luastring>"))
assert( parser.parse([[ x = (" ") () ]], "<luastring>"))
assert( parser.parse([[ x = (" ") "" ]], "<luastring>"))
assert( parser.parse([[ x = (" ").m() ]], "<luastring>"))
assert( parser.parse([[ x = (" "):m"" ]], "<luastring>"))
assert(not parser.parse([[ x = { } () ]], "<luastring>"))
assert(not parser.parse([[ x = { } "" ]], "<luastring>"))
assert(not parser.parse([[ x = { } .m() ]], "<luastring>"))
assert(not parser.parse([[ x = { } :m"" ]], "<luastring>"))
assert( parser.parse([[ x = ({ }) () ]], "<luastring>"))
assert( parser.parse([[ x = ({ }) "" ]], "<luastring>"))
assert( parser.parse([[ x = ({ }).m() ]], "<luastring>"))
assert( parser.parse([[ x = ({ }):m"" ]], "<luastring>"))
assert(not parser.parse([[ x = 123 () ]], "<luastring>"))
assert(not parser.parse([[ x = 123 "" ]], "<luastring>"))
assert(not parser.parse([[ x = 123 .m() ]], "<luastring>"))
assert(not parser.parse([[ x = 123 :m"" ]], "<luastring>"))
assert( parser.parse([[ x = (123) () ]], "<luastring>"))
assert( parser.parse([[ x = (123) "" ]], "<luastring>"))
assert( parser.parse([[ x = (123).m() ]], "<luastring>"))
assert( parser.parse([[ x = (123):m"" ]], "<luastring>"))
assert(not parser.parse([[ x = nil () ]], "<luastring>"))
assert(not parser.parse([[ x = nil "" ]], "<luastring>"))
assert(not parser.parse([[ x = nil .m() ]], "<luastring>"))
assert(not parser.parse([[ x = nil :m"" ]], "<luastring>"))
assert( parser.parse([[ x = (nil) () ]], "<luastring>"))
assert( parser.parse([[ x = (nil) "" ]], "<luastring>"))
assert( parser.parse([[ x = (nil).m() ]], "<luastring>"))
assert( parser.parse([[ x = (nil):m"" ]], "<luastring>"))
end)
test("Simplify", function()
local function testSimplify(lua, expectedLua, expectedLuaAlt)
local ast = assert(parser.parse(lua, "<luastring>"))
parser.simplify(ast)
if expectedLuaAlt then
assertLua(assert(parser.toLua(ast)), expectedLua, expectedLuaAlt, 2)
else
assertLua(assert(parser.toLua(ast)), expectedLua, 2)
end
end
local ast = assert(parser.parseFile("test.lua"))
parser.simplify(ast)
assert(parser.toLua(ast))
local ast = assert(parser.parseFile("dumbParser.lua"))
parser.simplify(ast)
assert(parser.toLua(ast))
testSimplify([[ x = -0 ]], [[ x=0; ]])
testSimplify([[ x = 1+2 ]], [[ x=3; ]])
testSimplify([[ x = 1+2^3 ]], [[ x=9; ]], [[ x=9.0; ]]) -- In Lua 5.3+ the result of x^y is always a float.
testSimplify([[ x = 1 << 8 ]], [[ x=256; ]])
testSimplify([[ x = 2^99999 ]], [[ x=(1/0); ]])
-- Negative.
testSimplify([[ x = 5 - - - -5 ]], [[ x=10; ]])
testSimplify([[ x = 5 - - - -"5" ]], (_VERSION == "Lua 5.3" and [[ x=10.0; ]] or [[ x=10; ]])) -- Apparently -"5" and -tonumber"5" don't result in the same math type in Lua 5.3. Ugh...
testSimplify([[ x = 5 - -"a" ]], [[ x=5- -"a"; ]]) -- Runtime error, but not an error for us.
-- Bitwise.
testSimplify([[ x = 2779 ]], [[ x=2779; ]])
testSimplify([[ x = ~2779 ]], [[ x=-2780; ]])
testSimplify([[ x = 2779 & 0x1011 ]], [[ x=17; ]])
testSimplify([[ x = 2779 ~ 0x1011 ]], [[ x=6858; ]])
testSimplify([[ x = 2779 | 0x1011 ]], [[ x=6875; ]])
-- >> / <<
testSimplify([[ x = 2 ]], [[ x=2; ]])
testSimplify([[ x = 2 >> 1 ]], [[ x=1; ]])
testSimplify([[ x = 2 << 1 ]], [[ x=4; ]])
testSimplify([[ x = -2 ]], [[ x=-2; ]])
testSimplify([[ x = -2 >> 1 ]], (parser.INT_SIZE == 32 and [[ x=2147483647; ]] or [[ x=9223372036854775807; ]]))
testSimplify([[ x = -2 << 1 ]], [[ x=-4; ]])
testSimplify([[ x = 2 >> 0 ]], [[ x=2; ]])
testSimplify([[ x = 2 << 0 ]], [[ x=2; ]])
testSimplify([[ x = -2 << -1 ]], (parser.INT_SIZE == 32 and [[ x=2147483647; ]] or [[ x=9223372036854775807; ]]))
testSimplify([[ x = -2 >> -1 ]], [[ x=-4; ]])
-- &
testSimplify([[ x = 1/0 & 2 ]], [[ x=(1/0)&2; ]])
-- Equality.
testSimplify([[ x = "yes" == "no" ]], [[ x=false; ]])
testSimplify([[ x = 5 ~= nil ]], [[ x=true; ]])
testSimplify([[ x = 80.6 >= 34 ]], [[ x=true; ]])
-- Relativeness.
testSimplify([[ x = 1 < 1 ]], [[ x=false; ]])
testSimplify([[ x = 1 < 99 ]], [[ x=true; ]])
testSimplify([[ x = 99 < 1 ]], [[ x=false; ]])
testSimplify([[ x = 1 > 1 ]], [[ x=false; ]])
testSimplify([[ x = 1 > 99 ]], [[ x=false; ]])
testSimplify([[ x = 99 > 1 ]], [[ x=true; ]])
testSimplify([[ x = 1 <= 1 ]], [[ x=true; ]])
testSimplify([[ x = 1 <= 99 ]], [[ x=true; ]])
testSimplify([[ x = 99 <= 1 ]], [[ x=false; ]])
testSimplify([[ x = 1 >= 1 ]], [[ x=true; ]])
testSimplify([[ x = 1 >= 99 ]], [[ x=false; ]])
testSimplify([[ x = 99 >= 1 ]], [[ x=true; ]])
testSimplify([[ x = "" < "" ]], [[ x=false; ]])
testSimplify([[ x = "" < "a" ]], [[ x=true; ]])
testSimplify([[ x = "a" < "" ]], [[ x=false; ]])
testSimplify([[ x = "" > "" ]], [[ x=false; ]])
testSimplify([[ x = "" > "a" ]], [[ x=false; ]])
testSimplify([[ x = "a" > "" ]], [[ x=true; ]])
testSimplify([[ x = "" <= "" ]], [[ x=true; ]])
testSimplify([[ x = "" <= "a" ]], [[ x=true; ]])
testSimplify([[ x = "a" <= "" ]], [[ x=false; ]])
testSimplify([[ x = "" >= "" ]], [[ x=true; ]])
testSimplify([[ x = "" >= "a" ]], [[ x=false; ]])
testSimplify([[ x = "a" >= "" ]], [[ x=true; ]])
testSimplify([[ x = 1 < "a" ]], [[ x=1<"a"; ]]) -- Runtime error, but not an error for us.
testSimplify([[ x = 1 > "a" ]], [[ x=1>"a"; ]])
testSimplify([[ x = 1 <= "a" ]], [[ x=1<="a"; ]])
testSimplify([[ x = 1 >= "a" ]], [[ x=1>="a"; ]])
-- ..
testSimplify([[ x = "one" .. 2 .. "three" ]], [[ x="one2three"; ]])
-- #
testSimplify([[ x = #"föö" ]], [[ x=5; ]])
-- and / or
testSimplify([[ x = true and always1() ]], [[ x=always1(); ]])
testSimplify([[ x = true or never1() ]], [[ x=true; ]])
testSimplify([[ x = 0 and always2() ]], [[ x=always2(); ]])
testSimplify([[ x = 0 or never2() ]], [[ x=0; ]])
testSimplify([[ x = false and never3() ]], [[ x=false; ]])
testSimplify([[ x = false or always3() ]], [[ x=always3(); ]])
testSimplify([[ x = nil and never4() ]], [[ x=nil; ]])
testSimplify([[ x = nil or always4() ]], [[ x=always4(); ]])
-- not
testSimplify([[ x = not true ]], [[ x=false; ]])
testSimplify([[ x = not 0 ]], [[ x=false; ]])
testSimplify([[ x = not false ]], [[ x=true; ]])
testSimplify([[ x = not nil ]], [[ x=true; ]])
testSimplify([[ x = not y ]], [[ x=not y; ]])
testSimplify([[ x = not (a == b) ]], [[ x=a~=b; ]])
testSimplify([[ x = not (a ~= b) ]], [[ x=a==b; ]])
-- Conditionals.
testSimplify(
[[
if 9 > 1 then
ifYes()
if 1 == "foo" then ifNo() end
end
]],
[[ ifYes(); ]]
)
testSimplify(
[[
while 9 > 1 do
whileYes()
while 1 == "foo" do whileNo() end
end
]],
[[ while true do whileYes();end ]]
)
testSimplify(
[[
repeat
repeatYes()
repeat repeatOnce() until 1 ~= "foo"
until 9 <= 1
]],
[[ repeat repeatYes();repeatOnce();until false ]]
)
testSimplify(
[[
for x = 1, 2 do
forYes()
for y = 1, 2, -1 do forNo() end
for y = 2, 1 do forNo() end
for y = 2, 1, 1 do forNo() end
end
]],
[[ for x=1,2 do forYes();end ]]
)
end)
test("Optimize", function()
local function testOptimize(lua, expectedLua, expectedLuaAlt)
local ast = assert(parser.parse(lua, "<luastring>"))
parser.optimize(ast)
lua = assert(parser.toLua(ast))
-- print(lua)
if expectedLuaAlt then
assertLua(lua, expectedLua, expectedLuaAlt, 2)
else
assertLua(lua, expectedLua, 2)
end
end
local ast = assert(parser.parseFile("test.lua"))
parser.optimize(ast)
assert(parser.toLua(ast))
-- local ast = assert(parser.parseFile("dumbParser.lua"))
-- parser.optimize(ast)
-- assert(parser.toLua(ast))
-- Unpack 'do' block.
testOptimize(
[[
do
globalFunc()
end
]],
[[ globalFunc(); ]]
)
--
-- Names.
--
-- Declarations.
testOptimize(
[[
local useless, keep, remove = globalFunc1()
globalFunc2(keep)
]],
[[ local useless,keep=globalFunc1();globalFunc2(keep); ]]
)
testOptimize(
[[
local useless, keep, remove
useless, keep, remove = globalFunc1()
globalFunc2(keep)
]],
[[ local useless,keep;useless,keep=globalFunc1();globalFunc2(keep); ]]
)
testOptimize(
[[
local useless, keep, remove = globalFunc()
local function keepCalled()
keep = global1
end
local function removeNotCalled()
keep = global2
return global3
end
useless, keep, remove = globalFunc()
keepCalled()
print(keep)
]],
[[ local useless,keep=globalFunc();local function keepCalled()keep=global1;end useless,keep=globalFunc();keepCalled();print(keep); ]]
)
-- Example from real code.
testOptimize(
[[
local forward
local function localFunc() return forward() end
function globalFunc() return localFunc() end
do
local n = 0
function forward() n = n + 1 ; return n end
end
]],
[[ local forward;local function localFunc()return forward();end function globalFunc()return localFunc();end do local n=0;function forward()n=n+1;return n;end end ]]
)
-- Functions.
testOptimize(
[[
function globalFunc(useless, keep, remove)
global = keep
end
]],
[[ function globalFunc(useless,keep)global=keep;end ]]
)
testOptimize(
[[
function globalFunc(useless1, useless2, ...)
global = ...
end
]],
[[ function globalFunc(useless1,useless2,...)global=...;end ]]
)
testOptimize(
[[
function globalFunc(useless1, useless2, ...)
-- void
end
]],
[[ function globalFunc()end ]]
)
-- For-loops (generic).
testOptimize(
[[
for useless, keep, remove in iterator() do
global = keep
end
]],
[[ for useless,keep in iterator()do global=keep;end ]]
)
testOptimize(
[[
for useless in iterator() do
-- void
end
]],
[[ for useless in iterator()do end ]]
)
-- Complete removal.
testOptimize(
[[
local unused1 = 1 + 2
local function unusedFunc()
local unused2 = global
end
unusedFunc = nil
]],
[[ ]]
)
-- Complex removals.
testOptimize( -- Remove everything.
[[
local unused1 = 1
local unused1 = 1, 2
local unused1, unused2 = 1
local unused1, unused2 = 1, 2
]],
[[ ]]
)
testOptimize( -- Keep calls.
[[
local unused = globalFunc11()
local unused = globalFunc12(), 2
local unused = globalFunc13(), 2, 3
local unused = 1, globalFunc21()
local unused = 1, globalFunc22(), 3
local unused = 1, 2, globalFunc31()
]],
[[ globalFunc11();globalFunc12();globalFunc13();globalFunc21();globalFunc22();globalFunc31(); ]]
)
testOptimize( -- Keep all calls.
[[
before()
local unused = globalFunc1(), globalFunc2()
after()
]],
[[ before();globalFunc1();globalFunc2();after(); ]]
)
testOptimize( -- Assignments, keep all calls.
[[
before()
local useless = 1
useless = globalFunc1(), globalFunc2()
after()
]],
[[ before();globalFunc1();globalFunc2();after(); ]]
)
testOptimize( -- Keep call.
[[
local unused1, unused2, useless = 1, globalFunc2(), 3, 4
useless = 1
]],
[[ globalFunc2(); ]]
)
testOptimize( -- Keep call, 'THREE' must be 3.
[[
local unused1, unused2, THREE = 1, globalFunc2(), 3, 4
global = THREE
]],
[[ globalFunc2();global=3; ]]
)
testOptimize( -- 'third' must be third value returned from call.
[[
local useless1, useless2, third = globalFunc123()
global = third
]],
[[ local useless1,useless2,third=globalFunc123();global=third; ]]
)
testOptimize( -- Keep call, 'NIL' must be nil.
[[
local unused1, unused2, NIL = globalFunc1(), 2
global = NIL
]],
[[ globalFunc1();global=nil; ]]
)
testOptimize( -- Assignments, keep call.
[[
local useless = 11, 12
useless = 21, globalFunc2(), 23
]],
[[ globalFunc2(); ]]
)
testOptimize( -- Keep all calls, 'x' must be what globalFunc2() returns.
[[
local unused, x = globalFunc1(), globalFunc2(), globalFunc3()
globalFuncX(x)
]],
[[ local unused,x=globalFunc1(),globalFunc2(),globalFunc3();globalFuncX(x); ]]
)
--
-- Constants.
--
-- Zero and the elusive minus. (Coming to all theaters next summer!)
testOptimize(
[[
local n = -0 -- The value will get normalized to 0.
global(n)
]],
[[ global(0); ]]
)
testOptimize(
[[
local n = 0
global(-n)
]],
_VERSION >= "Lua 5.3"
and [[ global(0); ]] -- '-0' is not a thing in Lua 5.3+.
or [[ local n=0;global(-n); ]]
)
end)
test("Minify", function()
local function testMinify(lua, expectedLua, expectedLuaAlt)
local ast = assert(parser.parse(lua, "<luastring>"))
parser.minify(ast)
lua = assert(parser.toLua(ast))
-- print(lua)
if expectedLuaAlt then
assertLua(lua, expectedLua, expectedLuaAlt, 2)
else
assertLua(lua, expectedLua, 2)
end
end
local ast = assert(parser.parseFile("test.lua"))
parser.minify(ast)
assert(parser.toLua(ast))
-- local ast = assert(parser.parseFile("dumbParser.lua"))
-- parser.minify(ast)
-- assert(parser.toLua(ast))
-- Letter frequencies: etaoinshrdlcumwfgypbvkxjqz
testMinify(
[[
local x, y = 1, 2
global = x + y
]],
[[ local e,t=1,2;global=e+t; ]]
)
testMinify(
[[
function globalFunc(unused, x, ...)
return x + ...
end
]],
[[ function globalFunc(e,e,...)return e+...;end ]]
)
testMinify(
[[
function globalFunc(x, unused, ...)
return x + ...
end
]],
[[ function globalFunc(e,t,...)return e+...;end ]]
)
testMinify(
[[
for i, v in ipairs(global) do
globalFunc1(v)
for i = i, #global do
globalFunc2(i)
end
end
]],
[[ for e,t in ipairs(global)do globalFunc1(t);for e=e,#global do globalFunc2(e);end end ]]
)
-- Make sure we minify multi-name declaration-likes as much as possible without shadowing too much.
testMinify(
[[ local x, y = 1, 2 ; return x ]],
[[ local e,t=1,2;return e; ]]
)
testMinify(
[[ local x, y = 1, 2 ; return y ]],
[[ local e,e=1,2;return e; ]]
)
testMinify(
[[ for x, y in 1, 2 do return x end ]],
[[ for e,t in 1,2 do return e;end ]]
)
testMinify(
[[ for x, y in 1, 2 do return y end ]],
[[ for e,e in 1,2 do return e;end ]]
)
testMinify(