forked from n1tehawk/lua-minify
-
Notifications
You must be signed in to change notification settings - Fork 1
/
minify.lua
3534 lines (3349 loc) · 93.8 KB
/
minify.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
--[[
MIT License
Copyright (c) 2017 Mark Langen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
-- eyecandy to increase readability for empty if branches and keep luacheck happy
local function do_nothing() end
local function lookupify(tb)
local t = {}
for _, v in pairs(tb) do
t[v] = true
end
return t
end
local function CountTable(tb, limit)
local c, k = 0, next(tb, nil)
while k ~= nil do
c = c + 1
if limit and (c >= limit) then
break
end
k = next(tb, k)
end
return c
end
local indentation = ' ' -- normally either multiple spaces or "\t"
local function indentStr(level)
return string.rep(indentation, level or 0)
end
local function FormatTable(tb, atIndent, ignoreFunc)
-- Note: This is currently unused,
-- and it might be better to check for a __tostring metamethod instead
if type(tb.Print) == 'function' then
return tb.Print()
end
-- set parameter defaults
atIndent = atIndent or 0
ignoreFunc = ignoreFunc or function()
return false
end
local consecutiveIndex, useNewlines = 1, CountTable(tb, 2) > 1
local baseIndent = indentStr(atIndent + 1)
local out = {'{'} -- table of output strings
if useNewlines then
table.insert(out, '\n')
end
for k, v in pairs(tb) do
local type_k, type_v = type(k), type(v) -- cache types, used multiple times
if type_v ~= 'function' and not ignoreFunc(k) then
if useNewlines then
table.insert(out, baseIndent)
end
-- key
if type_k == 'string' then
if k:match("^[A-Za-z_][A-Za-z0-9_]*$") then
table.insert(out, k) -- plain identifier key, no need to quote
else
-- bracket and quote key
table.insert(out, '["')
table.insert(out, k)
table.insert(out, '"]')
end
table.insert(out, " = ")
elseif type_k == 'number' and k == consecutiveIndex then
-- as long as a "list"-type table has consecutive entries,
-- there's no need to output the key
consecutiveIndex = consecutiveIndex + 1
else
-- non-consecutive indices and non-string keys
table.insert(out, '[')
table.insert(out, tostring(k))
table.insert(out, '] = ')
end
-- value
if type_v == 'string' then
table.insert(out, '"')
table.insert(out, v)
table.insert(out, '"')
elseif type_v == 'table' then
-- recursive output of table-type values
table.insert(out,
FormatTable(v, atIndent + (useNewlines and 1 or 0), ignoreFunc))
else
table.insert(out, tostring(v))
end
if next(tb, k) then
table.insert(out, ',')
end
if useNewlines then
table.insert(out, '\n')
end
end
end
if useNewlines then
table.insert(out, indentStr(atIndent))
end
table.insert(out, '}')
return table.concat(out)
end
local WhiteChars = lookupify{' ', '\n', '\t', '\r', '\a', '\b', string.char(11), string.char(12)}
-- '\f', '\v', '\z' are not whitechars in original lua 5.1, they're equals to ♀, ♂, z | glua translate them to char(11), char(12) and zero len string like latest lua
local EscapeForCharacter = {['\r'] = '\\r', ['\a'] = '\\a', ['\b'] = '\\b', ['\f'] = '\\f', ['\v'] = '\\v', ['\n'] = '\\n', ['\t'] = '\\t', ['"'] = '\\"', ["'"] = "\\'", ['\\'] = '\\'}
local CharacterForEscape = {['r'] = '\r', ['a'] = '\a', ['b'] = '\b', ['f'] = '\f', ['v'] = '\v', ['n'] = '\n', ['t'] = '\t', ['z'] = '\z', ['"'] = '"', ["'"] = "'", ['\\'] = '\\'}
local AllIdentStartChars = lookupify{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_'}
local AllIdentChars = lookupify{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
local Digits = lookupify{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
local HexDigits = lookupify{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f'}
local Symbols = lookupify{'+', '-', '*', '/', '^', '%', ',', '{', '}', '[', ']', '(', ')', ';', '#', '.', ':'}
local EqualSymbols = lookupify{'~', '!', '=', '>', '<'}
local Keywords = lookupify{
'and', 'break', 'do', 'else', 'elseif',
'end', 'false', 'for', 'function', 'if',
'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while',
'continue', '&&', '||'
}
local BlockFollowKeyword = lookupify{'else', 'elseif', 'until', 'end'}
local UnopSet = lookupify{'-', 'not', '#', '!'}
local BinopSet = lookupify{
'+', '-', '*', '/', '%', '^', '..',
'>', '<', '<=', '>=', '~=', '==', '!=',
'and', 'or', '&&', '||'
}
local BinaryPriority = {
['+'] = {6, 6};
['-'] = {6, 6};
['*'] = {7, 7};
['/'] = {7, 7};
['%'] = {7, 7};
['^'] = {10, 9};
['..'] = {5, 4};
['=='] = {3, 3};
['~='] = {3, 3};
['!='] = {3, 3};
['>'] = {3, 3};
['<'] = {3, 3};
['>='] = {3, 3};
['<='] = {3, 3};
['and'] = {2, 2};
['&&'] = {2, 2};
['or'] = {1, 1};
['||'] = {1, 1};
}
local UnaryPriority = 8
-- Eof, Ident, Keyword, Number, String, Symbol
-- decode string position to line and column number, with optional start values
local function _decode_position(text, pos, line, col)
line, col = line or 1, col or 0
if pos > 0 then
if pos > text:len() then
pos = text:len()
end
for i = 1, pos do
col = col + 1
if text:sub(i, i) == '\n' then
line = line + 1
col = 0
end
end
if col == 0 then
col = 1
end
end
return line, col
end
local BOM = lookupify{
string.char(0xEF, 0xBB, 0xBF), -- UTF-8
string.char(0xFE, 0xFF), -- UTF-16 (BE)
string.char(0xFF, 0xFE), -- UTF-16 (LE)
string.char(0x00, 0x00, 0xFE, 0xFF), -- UTF-32 (BE)
string.char(0xFF, 0xFE, 0x00, 0x00), -- UTF-32 (LE)
string.char(0x2B, 0x2F, 0x76), -- UTF-7
string.char(0xF7, 0x64, 0x4C), -- UTF-1
string.char(0xDD, 0x73, 0x66, 0x73), -- UTF-EBCDIC
string.char(0x0E, 0xFE, 0xFF), -- SCSU
string.char(0xFB, 0xEE, 0x28), -- BOCU-1
string.char(0x84, 0x31, 0x95, 0x33) -- GB-18030
}
local function CreateLuaTokenStream(text)
-- UTF with BOM fix
local byte2, byte3, byte4 = text:sub(0,2), text:sub(0,3), text:sub(0,4)
if BOM[byte2] then
text = text:sub(3)
elseif BOM[byte3] then
text = text:sub(4)
elseif BOM[byte4] then
text = text:sub(5)
end
--text = text:gsub('\r', '\r\n') -- Macintosh (CR) fix
-- Tracking for the current position in the buffer, and
-- the current line / character we are on.
local p = 1
-- Output buffer for tokens
local tokenBuffer = {}
-- Get a character, or '' if at eof
local function look(n)
n = p + (n or 0)
return text:sub(n, n)
end
local function get()
local c = text:sub(p, p)
p = p + 1
return c
end
-- Error
local function _error(str)
local line, col = _decode_position(text, p)
for _, token in pairs(tokenBuffer) do
print(token.Type.."<"..token.Source..">")
end
error("file<"..line..":"..col..">: "..str)
end
-- Consume a long data with equals count of `eqcount'
local function longdata(eqcount)
while true do
local c = get()
if c == '' then
_error("Unfinished long string.")
elseif c == ']' then
local done = true -- Until contested
for _ = 1, eqcount do
if look() == '=' then
p = p + 1
else
done = false
break
end
end
if done and get() == ']' then
return
end
end
end
end
-- Get the opening part for a long data `[` `=`* `[`
-- Precondition: The first `[` has been consumed
-- Return: nil or the equals count
local function getopen()
local eqcount = 0
while look(eqcount) == '=' do
eqcount = eqcount + 1
end
if look(eqcount) == '[' then
p = p + eqcount + 1
return eqcount
end
return nil
end
local whiteStart, tokenStart -- used in main loop, upvalues for token()
-- Add token
local function token(type)
local tk = {
Type = type;
LeadingWhite = text:sub(whiteStart, tokenStart-1);
Source = text:sub(tokenStart, p-1);
}
table.insert(tokenBuffer, tk)
return tk
end
-- Parse tokens loop
while true do
-- Mark the whitespace start
whiteStart = p
-- Get the leading whitespace + comments
while true do
local c = look()
if c == '' then
break
elseif c == '-' then
if look(1) == '-' then
p = p + 2
-- Consume comment body
if look() == '[' then
p = p + 1
local eqcount = getopen()
if eqcount then
-- Long comment body
longdata(eqcount)
else
-- Normal comment body
local c2
repeat
c2 = get()
until c2 == '' or c2 == '\n'
end
else
-- Normal comment body
local c2
repeat
c2 = get()
until c2 == '' or c2 == '\n'
end
else
break
end
elseif c == '/' then
local c2 = look(1)
if c2 == '*' then
p = p + 2
-- Long comment body without levels
repeat
c2 = get()
if c2 == '*' and look() =='/' then
get()
break
end
until c2 == ''
elseif c2 == '/' then
p = p + 2
-- Normal comment body
repeat
c2 = get()
until c2 == '' or c2 == '\n'
else
break
end
elseif WhiteChars[c] then
p = p + 1
else
break
end
end
-- Mark the token start
tokenStart = p
-- Switch on token type
local c1 = get()
if c1 == '' then
-- End of file
token('Eof')
break
elseif c1 == '\'' or c1 == '\"' then
-- String constant
local c2
repeat
c2 = get()
if c2 == '' then
_error("Unfinished string.")
elseif c2 == '\\' then
local c3 = get()
if c3 == 'x' then -- hexademical char
local d1, d2 = look(), look()
if not HexDigits[d1] or not HexDigits[d2] then
error('Hexadecimal digit(-s) expected near `"..c3.."`.')
end
elseif not Digits[c3] and not CharacterForEscape[c3] then
error("Invalid Escape Sequence `"..c3.."`.")
end
end
until c2 == c1
token('String')
elseif c1 == ':' and look() == ':' then
local c2 = get()
-- label ::= ‘::’ Name ‘::’
c2 = get() -- first char for lexical name
if not AllIdentStartChars[c2] then
error('Bad identifier for goto label.')
end
repeat
c2 = get()
if c2 == '' then
_error('Unfinished identifier')
elseif c2 == ':' then
break
end
if not AllIdentChars[c2] then
error('Bad identifier for goto label.')
end
until c2 == c1 -- when we reach next :
local c3 = get() -- next char should be :
if c3 ~= ':' then
error('Invalid goto label.')
end
if Keywords[text:sub(tokenStart + 2, p - 3)] then
error('Goto label cannot be keyword')
end
token('GotoLabel')
elseif AllIdentStartChars[c1] then
-- Ident or Keyword
while AllIdentChars[look()] do
p = p + 1
end
if Keywords[text:sub(tokenStart, p-1)] then
token('Keyword')
else
token('Ident')
end
elseif Digits[c1] or (c1 == '.' and Digits[look()]) then
-- Number
if c1 == '0' and look() == 'x' then
p = p + 1
-- Hex number
while HexDigits[look()] do
p = p + 1
end
else
-- Normal Number
while Digits[look()] do
p = p + 1
end
if look() == '.' then
-- With decimal point
p = p + 1
while Digits[look()] do
p = p + 1
end
end
if look() == 'e' or look() == 'E' then
-- With exponent
p = p + 1
if look() == '-' then
p = p + 1
end
while Digits[look()] do
p = p + 1
end
end
end
token('Number')
elseif c1 == '[' then
-- '[' Symbol or Long String
local eqCount = getopen()
if eqCount then
-- Long string
longdata(eqCount)
token('String')
else
-- Symbol
token('Symbol')
end
elseif c1 == '.' then
-- Greedily consume up to 3 `.` for . / .. / ... tokens
if look() == '.' then
get()
if look() == '.' then
get()
end
end
token('Symbol')
elseif EqualSymbols[c1] then
if look() == '=' then
p = p + 1
end
token('Symbol')
elseif (c1 == '&' and look() == '&') or (c1 == '|' and look() == '|') then
get()
token('Keyword')
elseif Symbols[c1] then
token('Symbol')
else
_error("Bad symbol `"..c1.."` in source. Debug: " .. string.sub(text, math.max(p - 50, 0), p + 50))
end
end
return tokenBuffer
end
local function CreateLuaParser(tokens)
if type(tokens) == "string" then
-- tokenize from string first
tokens = CreateLuaTokenStream(tokens)
end
-- Token stream and pointer into it
assert(type(tokens) == "table")
-- for _, tok in pairs(tokens) do
-- print(tok.Type..": "..tok.Source)
-- end
local p = 1
local function get()
local tok = tokens[p]
if p < #tokens then
p = p + 1
end
return tok
end
local function peek(n)
n = p + (n or 0)
return tokens[n] or tokens[#tokens]
end
local function getTokenStartPosition(token)
local line, col = 1, 0
local tkNum = 1
repeat
local tk = tokens[tkNum]
tkNum = tkNum + 1
local text = tk.LeadingWhite
if tk ~= token then
text = text .. tk.Source
end
line, col = _decode_position(text, #text, line, col)
until tk == token
return line..":"..(col+1)
end
local function debugMark()
local tk = peek()
return "<"..tk.Type.." `"..tk.Source.."`> at: "..getTokenStartPosition(tk)
end
local function isBlockFollow()
local tok = peek()
return tok.Type == 'Eof' or (tok.Type == 'Keyword' and BlockFollowKeyword[tok.Source])
end
local function isUnop()
return UnopSet[peek().Source] or false
end
local function isBinop()
return BinopSet[peek().Source] or false
end
local function expect(type, source, type2, source2)
local tk = peek()
if tk.Type == type and (source == nil or tk.Source == source) then
return get()
elseif tk.Type == type2 and (source2 == nil or tk.Source == source2) then
return get()
else
for i = -3, 3 do
print("Tokens["..i.."] = `"..peek(i).Source.."`")
end
if source then
error(getTokenStartPosition(tk)..": `"..source.."` expected, got "..tk.Type..".")
else
error(getTokenStartPosition(tk)..": "..type
..(type2 and (" or "..type2) or "")
.." expected, got "..tk.Type..".")
end
end
end
local function MkNode(node)
local function _GetSelfToken(self)
return self.Token
end
local getf = node.GetFirstToken or _GetSelfToken
local getl = node.GetLastToken or _GetSelfToken
function node:GetFirstToken()
local t = getf(self)
assert(t)
return t
end
function node:GetLastToken()
local t = getl(self)
assert(t)
return t
end
return node
end
-- Forward decls
local block, expr
-- Expression list
local function exprlist()
local exprList = {}
local commaList = {}
table.insert(exprList, expr())
while peek().Source == ',' do
table.insert(commaList, get())
table.insert(exprList, expr())
end
return exprList, commaList
end
local function prefixexpr()
local tk = peek()
if tk.Source == '(' then
local oparenTk = get()
local inner = expr()
local cparenTk = expect('Symbol', ')')
return MkNode{
Type = 'ParenExpr';
Expression = inner;
Token_OpenParen = oparenTk;
Token_CloseParen = cparenTk;
GetFirstToken = function(self)
return self.Token_OpenParen
end;
GetLastToken = function(self)
return self.Token_CloseParen
end;
}
elseif tk.Type == 'Ident' then
return MkNode{
Type = 'VariableExpr';
Token = get();
}
else
print(debugMark())
error(getTokenStartPosition(tk)..": Unexpected symbol")
end
end
local function tableexpr()
local obrace = expect('Symbol', '{')
local entries = {}
local separators = {}
while peek().Source ~= '}' do
if peek().Source == '[' then
-- Index
local obrac = get()
local index = expr()
local cbrac = expect('Symbol', ']')
local eq = expect('Symbol', '=')
local value = expr()
table.insert(entries, {
EntryType = 'Index';
Index = index;
Value = value;
Token_OpenBracket = obrac;
Token_CloseBracket = cbrac;
Token_Equals = eq;
})
elseif peek().Type == 'Ident' and peek(1).Source == '=' then
-- Field
local field = get()
local eq = get()
local value = expr()
table.insert(entries, {
EntryType = 'Field';
Field = field;
Value = value;
Token_Equals = eq;
})
else
-- Value
local value = expr()
table.insert(entries, {
EntryType = 'Value';
Value = value;
})
end
-- Comma or Semicolon separator
if peek().Source == ',' or peek().Source == ';' then
table.insert(separators, get())
else
break
end
end
local cbrace = expect('Symbol', '}')
return MkNode{
Type = 'TableLiteral';
EntryList = entries;
Token_SeparatorList = separators;
Token_OpenBrace = obrace;
Token_CloseBrace = cbrace;
GetFirstToken = function(self)
return self.Token_OpenBrace
end;
GetLastToken = function(self)
return self.Token_CloseBrace
end;
}
end
-- List of identifiers
local function varlist(isFuncDecl)
local varList, commaList, token = {}, {}, peek()
if token.Type == 'Ident' then
table.insert(varList, get())
elseif isFuncDecl and (token.Source == '...') then
table.insert(varList, get())
end
while peek().Source == ',' do
table.insert(commaList, get())
if isFuncDecl then
token = expect('Ident', nil, 'Symbol', '...')
else
token = expect('Ident')
end
table.insert(varList, token)
end
return varList, commaList
end
-- Body
local function blockbody(terminator)
local body = block()
local after = peek()
if after.Type == 'Keyword' and after.Source == terminator then
get()
return body, after
else
print(after.Type, after.Source)
error(getTokenStartPosition(after)..": "..terminator.." expected.")
end
end
-- Function declaration
local function funcdecl(isAnonymous)
local functionKw = get()
--
local nameChain, nameChainSeparator
--
if not isAnonymous then
nameChain = {}
nameChainSeparator = {}
--
table.insert(nameChain, expect('Ident'))
--
while peek().Source == '.' do
table.insert(nameChainSeparator, get())
table.insert(nameChain, expect('Ident'))
end
if peek().Source == ':' then
table.insert(nameChainSeparator, get())
table.insert(nameChain, expect('Ident'))
end
end
--
local oparenTk = expect('Symbol', '(')
local argList, argCommaList = varlist(true)
local cparenTk = expect('Symbol', ')')
local fbody, enTk = blockbody('end')
--
return MkNode{
Type = (isAnonymous and 'FunctionLiteral' or 'FunctionStat');
NameChain = nameChain;
ArgList = argList;
Body = fbody;
--
Token_Function = functionKw;
Token_NameChainSeparator = nameChainSeparator;
Token_OpenParen = oparenTk;
Token_ArgCommaList = argCommaList;
Token_CloseParen = cparenTk;
Token_End = enTk;
GetFirstToken = function(self)
return self.Token_Function
end;
GetLastToken = function(self)
return self.Token_End;
end;
}
end
-- Argument list passed to a function
local function functionargs()
local tk = peek()
if tk.Source == '(' then
local oparenTk = get()
local argList = {}
local argCommaList = {}
while peek().Source ~= ')' do
table.insert(argList, expr())
if peek().Source == ',' then
table.insert(argCommaList, get())
else
break
end
end
local cparenTk = expect('Symbol', ')')
return MkNode{
CallType = 'ArgCall';
ArgList = argList;
--
Token_CommaList = argCommaList;
Token_OpenParen = oparenTk;
Token_CloseParen = cparenTk;
GetFirstToken = function(self)
return self.Token_OpenParen
end;
GetLastToken = function(self)
return self.Token_CloseParen
end;
}
elseif tk.Source == '{' then
return MkNode{
CallType = 'TableCall';
TableExpr = expr();
GetFirstToken = function(self)
return self.TableExpr:GetFirstToken()
end;
GetLastToken = function(self)
return self.TableExpr:GetLastToken()
end;
}
elseif tk.Type == 'String' then
return MkNode{
CallType = 'StringCall';
Token = get();
}
else
error("Function arguments expected.")
end
end
local function callexpr(base)
return MkNode{
Type = 'CallExpr';
Base = base;
FunctionArguments = functionargs();
GetFirstToken = function(self)
return self.Base:GetFirstToken()
end;
GetLastToken = function(self)
return self.FunctionArguments:GetLastToken()
end;
}
end
local function primaryexpr()
local base = prefixexpr()
assert(base, "nil prefixexpr")
while true do
local tk = peek()
if tk.Source == '.' then
local dotTk = get()
local fieldName = expect('Ident')
base = MkNode{
Type = 'FieldExpr';
Base = base;
Field = fieldName;
Token_Dot = dotTk;
GetFirstToken = function(self)
return self.Base:GetFirstToken()
end;
GetLastToken = function(self)
return self.Field
end;
}
elseif tk.Source == ':' then
local colonTk = get()
local methodName = expect('Ident')
local fargs = functionargs()
base = MkNode{
Type = 'MethodExpr';
Base = base;
Method = methodName;
FunctionArguments = fargs;
Token_Colon = colonTk;
GetFirstToken = function(self)
return self.Base:GetFirstToken()
end;
GetLastToken = function(self)
return self.FunctionArguments:GetLastToken()
end;
}
elseif tk.Source == '[' then
local obrac = get()
local index = expr()
local cbrac = expect('Symbol', ']')
base = MkNode{
Type = 'IndexExpr';
Base = base;
Index = index;
Token_OpenBracket = obrac;
Token_CloseBracket = cbrac;
GetFirstToken = function(self)
return self.Base:GetFirstToken()
end;
GetLastToken = function(self)
return self.Token_CloseBracket
end;
}
elseif tk.Source == '{' then
base = callexpr(base) -- TableCall
elseif tk.Source == '(' then
base = callexpr(base) -- ArgCall
elseif tk.Type == 'String' then
base = callexpr(base) -- StringCall
else
return base
end
end
end
-- Create a "literal" node with a given type (string)
local function literal(_type)
return MkNode{
Type = _type;
Token = get();
}
end
local function simpleexpr()
local tk = peek()
if tk.Type == 'Number' then
return literal('NumberLiteral')
elseif tk.Type == 'String' then
return literal('StringLiteral')
elseif tk.Source == 'nil' then
return literal('NilLiteral')
elseif tk.Source == 'true' or tk.Source == 'false' then
return literal('BooleanLiteral')
elseif tk.Source == '...' then
return literal('VargLiteral')
elseif tk.Source == '{' then
return tableexpr()
elseif tk.Source == 'function' then
return funcdecl(true)
else
return primaryexpr()
end
end
local function subexpr(limit)
local curNode
-- Initial Base Expression
if isUnop() then
local opTk = get()
local ex = subexpr(UnaryPriority)
curNode = MkNode{
Type = 'UnopExpr';
Token_Op = opTk;
Rhs = ex;
GetFirstToken = function(self)
return self.Token_Op
end;
GetLastToken = function(self)
return self.Rhs:GetLastToken()
end;
}
else
curNode = simpleexpr()
assert(curNode, "nil simpleexpr")
end
-- Apply Precedence Recursion Chain
while isBinop() and BinaryPriority[peek().Source][1] > limit do
local opTk = get()
local rhs = subexpr(BinaryPriority[opTk.Source][2])
assert(rhs, "RhsNeeded")
curNode = MkNode{
Type = 'BinopExpr';
Lhs = curNode;
Rhs = rhs;
Token_Op = opTk;
GetFirstToken = function(self)
return self.Lhs:GetFirstToken()
end;
GetLastToken = function(self)
return self.Rhs:GetLastToken()