-
Notifications
You must be signed in to change notification settings - Fork 19
/
minify.lua
3227 lines (3065 loc) · 83.5 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.
]]
function lookupify(tb)
for _, v in pairs(tb) do
tb[v] = true
end
return tb
end
function CountTable(tb)
local c = 0
for _ in pairs(tb) do c = c + 1 end
return c
end
function FormatTableInt(tb, atIndent, ignoreFunc)
if tb.Print then
return tb.Print()
end
atIndent = atIndent or 0
local useNewlines = (CountTable(tb) > 1)
local baseIndent = string.rep(' ', atIndent+1)
local out = "{"..(useNewlines and '\n' or '')
for k, v in pairs(tb) do
if type(v) ~= 'function' and not ignoreFunc(k) then
out = out..(useNewlines and baseIndent or '')
if type(k) == 'number' then
--nothing to do
elseif type(k) == 'string' and k:match("^[A-Za-z_][A-Za-z0-9_]*$") then
out = out..k.." = "
elseif type(k) == 'string' then
out = out.."[\""..k.."\"] = "
else
out = out.."["..tostring(k).."] = "
end
if type(v) == 'string' then
out = out.."\""..v.."\""
elseif type(v) == 'number' then
out = out..v
elseif type(v) == 'table' then
out = out..FormatTableInt(v, atIndent+(useNewlines and 1 or 0), ignoreFunc)
else
out = out..tostring(v)
end
if next(tb, k) then
out = out..","
end
if useNewlines then
out = out..'\n'
end
end
end
out = out..(useNewlines and string.rep(' ', atIndent) or '').."}"
return out
end
function FormatTable(tb, ignoreFunc)
ignoreFunc = ignoreFunc or function()
return false
end
return FormatTableInt(tb, 0, ignoreFunc)
end
local WhiteChars = lookupify{' ', '\n', '\t', '\r'}
local EscapeForCharacter = {['\r'] = '\\r', ['\n'] = '\\n', ['\t'] = '\\t', ['"'] = '\\"', ["'"] = "\\'", ['\\'] = '\\'}
local CharacterForEscape = {['r'] = '\r', ['n'] = '\n', ['t'] = '\t', ['"'] = '"', ["'"] = "'", ['\\'] = '\\'}
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', 'goto', 'if',
'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while',
};
local BlockFollowKeyword = lookupify{'else', 'elseif', 'until', 'end'}
local UnopSet = lookupify{'-', 'not', '#'}
local BinopSet = lookupify{
'+', '-', '*', '/', '%', '^', '#',
'..', '.', ':',
'>', '<', '<=', '>=', '~=', '==',
'and', 'or'
}
local GlobalRenameIgnore = lookupify{
}
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};
['and'] = {2, 2};
['or'] = {1, 1};
};
local UnaryPriority = 8
-- Eof, Ident, Keyword, Number, String, Symbol
function CreateLuaTokenStream(text)
-- Tracking for the current position in the buffer, and
-- the current line / character we are on.
local p = 1
local length = #text
-- Output buffer for tokens
local tokenBuffer = {}
-- Get a character, or '' if at eof
local function look(n)
n = p + (n or 0)
if n <= length then
return text:sub(n, n)
else
return ''
end
end
local function get()
if p <= length then
local c = text:sub(p, p)
p = p + 1
return c
else
return ''
end
end
-- Error
local olderr = error
local function error(str)
local q = 1
local line = 1
local char = 1
while q <= p do
if text:sub(q, q) == '\n' then
line = line + 1
char = 1
else
char = char + 1
end
q = q + 1
end
for _, token in pairs(tokenBuffer) do
print(token.Type.."<"..token.Source..">")
end
olderr("file<"..line..":"..char..">: "..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 i = 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 startp = p
while look() == '=' do
p = p + 1
end
if look() == '[' then
p = p + 1
return p - startp - 1
else
p = startp
return nil
end
end
-- Add token
local whiteStart = 1
local tokenStart = 1
local function token(type)
local tk = {
Type = type;
LeadingWhite = text:sub(whiteStart, tokenStart-1);
Source = text:sub(tokenStart, p-1);
}
table.insert(tokenBuffer, tk)
whiteStart = p
tokenStart = p
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
while true do
local c2 = get()
if c2 == '' or c2 == '\n' then
break
end
end
end
else
-- Normal comment body
while true do
local c2 = get()
if c2 == '' or c2 == '\n' then
break
end
end
end
else
break
end
elseif WhiteChars[c] then
p = p + 1
else
break
end
end
local leadingWhite = text:sub(whiteStart, p-1)
-- 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
while true do
local c2 = get()
if c2 == '\\' then
local c3 = get()
local esc = CharacterForEscape[c3]
if not esc then
error("Invalid Escape Sequence `"..c3.."`.")
end
elseif c2 == c1 then
break
end
end
token('String')
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 Symbols[c1] then
token('Symbol')
else
error("Bad symbol `"..c1.."` in source.")
end
end
return tokenBuffer
end
function CreateLuaParser(text)
-- Token stream and pointer into it
local tokens = CreateLuaTokenStream(text)
-- 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 = 1
local char = 0
local tkNum = 1
while true do
local tk = tokens[tkNum]
local text;
if tk == token then
text = tk.LeadingWhite
else
text = tk.LeadingWhite..tk.Source
end
for i = 1, #text do
local c = text:sub(i, i)
if c == '\n' then
line = line + 1
char = 0
else
char = char + 1
end
end
if tk == token then
break
end
tkNum = tkNum + 1
end
return line..":"..(char+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)
local tk = peek()
if tk.Type == type and (source == nil or tk.Source == source) then
return get()
else
for i = -3, 3 do
print("Tokens["..i.."] = `"..peek(i).Source.."`")
end
if source then
error(getTokenStartPosition(tk)..": `"..source.."` expected.")
else
error(getTokenStartPosition(tk)..": "..type.." expected.")
end
end
end
local function MkNode(node)
local getf = node.GetFirstToken
local getl = node.GetLastToken
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;
local 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();
GetFirstToken = function(self)
return self.Token
end;
GetLastToken = function(self)
return self.Token
end;
}
else
print(debugMark())
error(getTokenStartPosition(tk)..": Unexpected symbol")
end
end
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()
local varList = {}
local commaList = {}
if peek().Type == 'Ident' then
table.insert(varList, get())
end
while peek().Source == ',' do
table.insert(commaList, get())
local id = expect('Ident')
table.insert(varList, id)
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;
local 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()
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 funciton
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();
GetFirstToken = function(self)
return self.Token
end;
GetLastToken = function(self)
return self.Token
end;
}
else
error("Function arguments expected.")
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 = MkNode{
Type = 'CallExpr';
Base = base;
FunctionArguments = functionargs();
GetFirstToken = function(self)
return self.Base:GetFirstToken()
end;
GetLastToken = function(self)
return self.FunctionArguments:GetLastToken()
end;
}
elseif tk.Source == '(' then
base = MkNode{
Type = 'CallExpr';
Base = base;
FunctionArguments = functionargs();
GetFirstToken = function(self)
return self.Base:GetFirstToken()
end;
GetLastToken = function(self)
return self.FunctionArguments:GetLastToken()
end;
}
else
return base
end
end
end
local function simpleexpr()
local tk = peek()
if tk.Type == 'Number' then
return MkNode{
Type = 'NumberLiteral';
Token = get();
GetFirstToken = function(self)
return self.Token
end;
GetLastToken = function(self)
return self.Token
end;
}
elseif tk.Type == 'String' then
return MkNode{
Type = 'StringLiteral';
Token = get();
GetFirstToken = function(self)
return self.Token
end;
GetLastToken = function(self)
return self.Token
end;
}
elseif tk.Source == 'nil' then
return MkNode{
Type = 'NilLiteral';
Token = get();
GetFirstToken = function(self)
return self.Token
end;
GetLastToken = function(self)
return self.Token
end;
}
elseif tk.Source == 'true' or tk.Source == 'false' then
return MkNode{
Type = 'BooleanLiteral';
Token = get();
GetFirstToken = function(self)
return self.Token
end;
GetLastToken = function(self)
return self.Token
end;
}
elseif tk.Source == '...' then
return MkNode{
Type = 'VargLiteral';
Token = get();
GetFirstToken = function(self)
return self.Token
end;
GetLastToken = function(self)
return self.Token
end;
}
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()
end;
}
end
-- Return result
return curNode
end
-- Expression
expr = function()
return subexpr(0)
end
-- Expression statement
local function exprstat()
local ex = primaryexpr()
if ex.Type == 'MethodExpr' or ex.Type == 'CallExpr' then
-- all good, calls can be statements
return MkNode{
Type = 'CallExprStat';
Expression = ex;
GetFirstToken = function(self)
return self.Expression:GetFirstToken()
end;
GetLastToken = function(self)
return self.Expression:GetLastToken()
end;
}
else
-- Assignment expr
local lhs = {ex}
local lhsSeparator = {}
while peek().Source == ',' do
table.insert(lhsSeparator, get())
local lhsPart = primaryexpr()
if lhsPart.Type == 'MethodExpr' or lhsPart.Type == 'CallExpr' then
error("Bad left hand side of assignment")
end
table.insert(lhs, lhsPart)
end
local eq = expect('Symbol', '=')
local rhs = {expr()}
local rhsSeparator = {}
while peek().Source == ',' do
table.insert(rhsSeparator, get())
table.insert(rhs, expr())
end
return MkNode{
Type = 'AssignmentStat';
Rhs = rhs;
Lhs = lhs;
Token_Equals = eq;
Token_LhsSeparatorList = lhsSeparator;
Token_RhsSeparatorList = rhsSeparator;
GetFirstToken = function(self)
return self.Lhs[1]:GetFirstToken()
end;
GetLastToken = function(self)