-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy paththe-tiny-lua-compiler.lua
2482 lines (2208 loc) · 88.5 KB
/
the-tiny-lua-compiler.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
--[[
Today we're going to write a compiler for Lua 5.1 in Lua.
But not just any compiler... a super duper easy and teeny tiny
compiler! A compiler that is so small that if you remove all the
comments this file would be ~1700 lines of actual code.
The compiler will be able to tokenize, parse, and compile (almost)
any Lua code you throw at it. It will even be able to compile itself!
So, let's get started!
----------------------------------------------------------------------------
Our journey will cover transforming Lua code into Lua bytecode, which the
Lua Virtual Machine (VM) can understand and execute.
Here's a quick breakdown of what we're doing:
Tokenizer: Breaks down Lua code into tokens, the basic building blocks
like numbers, strings, and keywords.
Parser: Converts tokens into an Abstract Syntax Tree (AST), a tree
representation showing the structure of the code.
Code Generator: Transforms the AST into Lua VM instructions, the
low-level commands that the Lua VM can execute.
Compiler: Turns Lua VM instructions into Lua bytecode, ready for
execution by the Lua VM.
This process is a bit like translating a book from one language to another,
then adapting it into a screenplay. Each step refines and transforms the
content, making it ready for the final audience: the Lua VM.
--]]
--[[
Glossary:
Token:
The smallest element of programming language syntax that the compiler recognizes.
Tokens are the building blocks of code, akin to words in a language, and include
elements like numbers, strings, keywords (e.g., `if`, `while`), identifiers (variable names),
and operators (`+`, `-`, `*`, `/`). The tokenizer, or lexical analyzer, scans the source code
to identify and produce these tokens.
AST (Abstract Syntax Tree):
A hierarchical tree representation that outlines the grammatical structure of the code.
Each node in the tree denotes a construct occurring in the source code. The AST is
generated from the tokens produced by the tokenizer and serves as a crucial structure
for further stages of compilation, such as optimization and code generation. It abstracts
away the syntax details, focusing on the code's logical structure.
VM (Virtual Machine):
In the context of programming languages, a VM specifically refers to a runtime engine
that executes bytecode or intermediate code. This VM is not to be confused with system
virtual machines (like VirtualBox or VMWare) that emulate a full hardware system;
it's a process virtual machine designed to execute code in a high-level, portable format.
Bytecode:
A form of instruction set designed for efficient execution by a software VM. Bytecode
is more abstract than machine code and is not tied to any specific hardware architecture.
It serves as an intermediate representation of the code, optimized for portability and
quick execution. Bytecode is typically generated from the AST and is executed by the VM.
Unlike human-readable source code or assembly language, bytecode is binary and is
intended to be read and understood by the VM rather than humans.
Proto (Function Prototype):
In Lua, a function prototype is a data structure that contains metadata about a function,
including its bytecode, the number of parameters it accepts, its local variables, and its
upvalues (variables captured from the surrounding scope). The Lua VM uses this information
to execute the function and manage its execution context. Each Lua function, whether
defined in Lua or C, is represented internally by a function prototype.
Scope:
Defines the visibility and lifetime of variables and parameters in a program. In Lua,
scope is determined by the location of variable declarations. Variables can be global,
local, or upvalues. Global variables are accessible from anywhere in the code. Local
variables have their visibility limited to the block where they are declared, enhancing
modularity and preventing unintended modifications. Upvalues are local variables from
an enclosing function's scope, which are captured by closures, allowing the closure to
access and modify these variables even when the function is executed outside its original scope.
--]]
--[[
============================================================================
(ノ◕ヮ◕)ノ*:・゚✧
THE HELPER FUNCTIONS!
============================================================================
Building a compiler from scratch necessitates a set of utility functions to
streamline common tasks, enhancing both efficiency and readability. Below,
we introduce two essential helper functions pivotal to our compiler's core
functionality.
--]]
-- Converts a list to a lookup table for O(1) element lookups
local function createLookupTable(list)
local lookup = {}
for _, value in ipairs(list) do
lookup[value] = true
end
return lookup
end
-- Constructs a trie for efficient prefix-based operator searches
local function makeTrie(ops)
-- Initialize the trie
local trie = {}
for _, op in ipairs(ops) do
local node = trie
-- Split the operator into individual characters
for char in op:gmatch(".") do
node[char] = node[char] or {}
node = node[char]
end
node.Value = op
end
return trie
end
-- Converts a string into a list of characters
local function stringToChars(str)
local chars = {}
for char in str:gmatch(".") do
table.insert(chars, char)
end
return chars
end
-- Inserts all methods from a source table into a target table
local function insertValues(target, source)
for key, value in pairs(source) do
target[key] = value
end
end
--[[
============================================================================
(•_•)?!
TOKENIZER CONSTANTS
============================================================================
Before diving into the tokenizer's implementation, let's explore the
essential constants and lookup tables that will guide the tokenization
process. These constants include Lua operators, escaped character
sequences, reserved keywords, and Lua's boolean and nil constants.
By defining these constants upfront, we can streamline the tokenization
logic and ensure accurate identification and classification of tokens
within the Lua code.
--]]
-- Lua operators for tokenization: arithmetic, comparison, logical.
local TOKENIZER_LUA_OPERATORS = {
"^", "*", "/", "%",
"+", "-", "<", ">",
"#",
"<=", ">=", "==", "~=",
"and", "or", "not", ".."
}
-- Maps escaped sequences to characters for string literals.
local TOKENIZER_ESCAPED_CHARACTER_CONVERSIONS = {
["a"] = "\a", -- bell
["b"] = "\b", -- backspace
["f"] = "\f", -- form feed
["n"] = "\n", -- newline
["r"] = "\r", -- carriage return
["t"] = "\t", -- horizontal tab
["v"] = "\v", -- vertical tab
["\\"] = "\\", -- backslash
["\""] = "\"", -- double quote
["\'"] = "\'", -- single quote
}
-- Lookup for Lua's boolean and nil constants.
local TOKENIZER_LUA_CONSTANTS_LOOKUP = createLookupTable({ "true", "false", "nil" })
-- Lookup for Lua's reserved keywords.
local TOKENIZER_RESERVED_KEYWORDS_LOOKUP = createLookupTable({
"while", "do", "end", "for",
"local", "repeat", "until", "return",
"in", "if", "else", "elseif",
"function", "then", "break"
})
-- Lookup for operators.
local TOKENIZER_LUA_OPERATORS_LOOKUP = createLookupTable(TOKENIZER_LUA_OPERATORS)
-- Trie for efficient operator searching.
local TOKENIZER_OPERATOR_TRIE = makeTrie(TOKENIZER_LUA_OPERATORS)
--[[
============================================================================
(/^▽^)/
THE TOKENIZER!
============================================================================
Imagine the tokenizer as a conveyor belt. You put Lua code in one end,
and tokens come out the other end. The tokenizer will convert the input
code into a list of tokens that the parser can understand.
Tokens are the smallest building blocks of a programming language. They can be
anything from a number, a string, a keyword, an identifier, or an operator.
Typically, tokenizers strip out comments and whitespace, as they are not
needed for the parsing phase, our tokenizer follows the same approach.
Here's an example of how the tokenizer breaks down a simple Lua script:
```lua
if (x == 10) then
print("Hello, world!")
end
```
The resulting tokens would look like this:
|-----------------|------------------|
| Type | Value |
|-----------------|------------------|
| Keyword | if |
| Character | ( |
| Identifier | x |
| Operator | == |
| Number | 10 |
| Character | ) |
| Keyword | then |
| Identifier | print |
| Character | ( |
| String | Hello, world! |
| Character | ) |
| Keyword | end |
|-----------------|------------------|
--]]
--* TokenizerMethods *--
local TokenizerMethods = {}
--// Character Navigation //--
-- Looks ahead by n characters in the character stream
function TokenizerMethods:lookAhead(n)
local updatedCharPos = self.curCharPos + n
local updatedChar = self.charStream[updatedCharPos]
return updatedChar
end
-- Consumes (skips) n characters in the character stream
function TokenizerMethods:consume(n)
local updatedCharPos = self.curCharPos + n
local updatedChar = self.charStream[updatedCharPos]
self.curCharPos = updatedCharPos
self.curChar = updatedChar
return updatedChar
end
--// Character Checkers //--
-- Checks if a character is \t (tab), \n (newline), or \r (carriage return)
function TokenizerMethods:isWhitespace(char)
return char:match("%s")
end
-- Checks if a character is a digit (0-9)
function TokenizerMethods:isNumber(char)
return char:match("%d")
end
-- Checks if a number is hexadecimal (0-9, a-f, A-F)
function TokenizerMethods:isHexadecimalNumber(char)
return char:match("[%da-fA-F]")
end
-- Checks if a character is a letter, digit, or underscore
function TokenizerMethods:isIdentifier(char)
return char:match("[%a%d_]")
end
-- Checks if a character is a letter or underscore
function TokenizerMethods:isIdentifierStart(char)
return char:match("[%a_]")
end
function TokenizerMethods:isScientificNotationPrefix(char)
return char == "e" or char == "E"
end
--// Multi-Character Checkers //--
function TokenizerMethods:isHexadecimalNumberPrefix()
local nextChar = self:lookAhead(1)
return self.curChar == "0" and (
nextChar == "x" or nextChar == "X"
)
end
function TokenizerMethods:isVarArg()
return self.curChar == "."
and self:lookAhead(1) == "."
and self:lookAhead(2) == "."
end
function TokenizerMethods:isComment()
return self.curChar == "-"
and self:lookAhead(1) == "-"
end
function TokenizerMethods:isString()
local curChar = self.curChar
local nextChar = self:lookAhead(1)
return (curChar == '"' or curChar == "'")
or (curChar == "[" and (nextChar == "[" or nextChar == "="))
end
--// Consumers //--
function TokenizerMethods:consumeWhitespace()
local startChar = self.curChar
local startPos = self.curCharPos
while self:lookAhead(1) == startChar do
self:consume(1)
end
return self.code:sub(startPos, self.curCharPos)
end
function TokenizerMethods:consumeIdentifier()
local start = self.curCharPos
while self:isIdentifier(self:lookAhead(1)) do
self:consume(1)
end
return self.code:sub(start, self.curCharPos)
end
function TokenizerMethods:consumeInteger(maxLength)
local start = self.curCharPos
while self:lookAhead(1):match("%d") do
if (maxLength and (self.curCharPos - start) >= maxLength) then
break
end
self:consume(1)
end
return self.code:sub(start, self.curCharPos)
end
function TokenizerMethods:consumeNumber()
local start = self.curCharPos
-- Hexadecimal number case
-- 0[xX][0-9a-fA-F]+
if self:isHexadecimalNumberPrefix() then
self:consume(2) -- Consume the "0x" part
while self:isHexadecimalNumber(self:lookAhead(1)) do
self:consume(1) -- Consume hexadecimal digits
end
return self.code:sub(start, self.curCharPos)
end
-- [0-9]*
while self:isNumber(self:lookAhead(1)) do
self:consume(1) -- Consume digits
end
-- Floating point number case
-- \.[0-9]+
if self:lookAhead(1) == "." then
self:consume(1) -- Consume the "."
while self:isNumber(self:lookAhead(1)) do
self:consume(1)
end
end
-- Exponential (scientific) notation case
-- [eE][+-]?[0-9]+
if self:isScientificNotationPrefix(self:lookAhead(1)) then
self:consume(1) -- Consume the "e" or "E"
if self:lookAhead(1) == "+" or self:lookAhead(1) == "-" then
self:consume(1) -- Consume optional sign
end
while self:isNumber(self:lookAhead(1)) do
self:consume(1) -- Consume exponent digits
end
end
return self.code:sub(start, self.curCharPos)
end
function TokenizerMethods:consumeSimpleString()
local delimiter = self.curChar
local newString = {}
self:consume(1) -- Consume the delimiter
while self.curChar ~= delimiter do
if self.curChar == "\\" then
local nextChar = self:consume(1)
if nextChar:match("%d") then -- Numeric escape sequence?
local number = self:consumeInteger(3)
local luaNumber = tonumber(number)
if not luaNumber then
error("invalid escape sequence near '\\" .. number .. "'")
end
table.insert(newString, string.char(luaNumber))
elseif TOKENIZER_ESCAPED_CHARACTER_CONVERSIONS[nextChar] then
table.insert(newString, TOKENIZER_ESCAPED_CHARACTER_CONVERSIONS[nextChar])
else
error("invalid escape sequence near '\\" .. nextChar .. "'")
end
else
table.insert(newString, self.curChar)
end
self:consume(1)
end
return table.concat(newString)
end
function TokenizerMethods:consumeLongString()
self:consume(1) -- Consume the "[" character
local start = self.curCharPos
local depth = 0
while self.curChar == "=" do
self:consume(1) -- Consume the "=" character
depth = depth + 1
end
if self.curChar ~= "[" then
error("invalid long string delimiter")
end
self:consume(1) -- Consume the "[" character
while true do
if self.curChar == "]" then
self:consume(1) -- Consume the "]" character
local closingDepth = 0
while self.curChar == "=" do
self:consume(1) -- Consume the "=" character
closingDepth = closingDepth + 1
end
if closingDepth == depth and self.curChar == "]" then
-- Exit the loop, as the closing delimiter is fully matched
break
end
elseif self.curChar == "\0" then
error("Unclosed long comment")
end
self:consume(1)
end
return self.code:sub(start + depth + 1, self.curCharPos - 2 - depth)
end
function TokenizerMethods:consumeString()
if self.curChar == "[" then
return self:consumeLongString()
end
return self:consumeSimpleString()
end
function TokenizerMethods:consumeOperator()
local node = TOKENIZER_OPERATOR_TRIE
local operator
-- Trie walker
local index = 0
while true do
local character = self:lookAhead(index)
node = node[character] -- Advance to the deeper node
if not node then break end
operator = node.Value
index = index + 1
end
if not operator then return end
self:consume(#operator - 1)
return operator
end
function TokenizerMethods:consumeShortComment()
local curChar = self.curChar
while curChar ~= "\0" and curChar ~= "\n" do
curChar = self:consume(1)
end
end
function TokenizerMethods:consumeLongComment()
self:consume(1) -- Consumes the "[" character
local depth = 0
while self.curChar == "=" do
self:consume(1) -- Consume the "=" character
depth = depth + 1
end
if self.curChar ~= "[" then return self:consumeShortComment() end
while true do
if self.curChar == "]" then
self:consume(1) -- Consume the "]" character
local closingDepth = 0
while self.curChar == "=" do
self:consume(1) -- Consume the "=" character
closingDepth = closingDepth + 1
end
if self.curChar == "]" and closingDepth == depth then
break
end
elseif self.curChar == "\0" then
error("Unclosed long comment")
end
self:consume(1)
end
end
function TokenizerMethods:consumeComment()
self:consume(2) -- Consume the "--"
if self.curChar == "[" then
return self:consumeLongComment()
end
return self:consumeShortComment()
end
--// Token Consumer Handler //--
function TokenizerMethods:getNextToken()
local curChar = self.curChar
if self:isWhitespace(curChar) then
self:consumeWhitespace()
return
elseif self:isComment() then
self:consumeComment()
return
elseif self:isNumber(curChar) then
return { TYPE = "Number", Value = tonumber(self:consumeNumber()) }
elseif self:isIdentifierStart(curChar) then
local identifier = self:consumeIdentifier()
if TOKENIZER_LUA_OPERATORS_LOOKUP[identifier] then
return { TYPE = "Operator", Value = identifier }
elseif TOKENIZER_RESERVED_KEYWORDS_LOOKUP[identifier] then
return { TYPE = "Keyword", Value = identifier }
elseif TOKENIZER_LUA_CONSTANTS_LOOKUP[identifier] then
return { TYPE = "Constant", Value = identifier }
end
return { TYPE = "Identifier", Value = identifier }
elseif self:isString() then
return { TYPE = "String", Value = self:consumeString() }
elseif self:isVarArg() then
self:consume(2)
return { TYPE = "VarArg" }
end
local operator = self:consumeOperator()
if operator then
return { TYPE = "Operator", Value = operator }
end
return { TYPE = "Character", Value = curChar }
end
--// Tokenizer Main Method //--
function TokenizerMethods:tokenize()
local tokens, tokenIndex = {}, 1
while self.curChar do
local token = self:getNextToken()
if token then
tokens[tokenIndex] = token
tokenIndex = tokenIndex + 1
end
self:consume(1)
end
return tokens
end
--* Tokenizer *--
local Tokenizer = {}
function Tokenizer.new(code)
local TokenizerInstance = {}
--// Local Variables //--
local charStream = stringToChars(code)
--// Initialization //--
TokenizerInstance.code = code
TokenizerInstance.charStream = charStream
TokenizerInstance.curCharPos = 1
TokenizerInstance.curChar = charStream[1]
--// Method Binding //--
insertValues(TokenizerInstance, TokenizerMethods)
return TokenizerInstance
end
--[[
============================================================================
(•_•)?
PARSER CONSTANTS
============================================================================
Before diving into the parser's implementation, let's explore the essential
constants and lookup tables that will guide the parsing process. These
constants include Lua operators, unary operators, and stop keywords.
By defining these constants upfront, we can streamline the parsing logic
and ensure accurate identification and classification of tokens within the
Lua code.
--]]
local PARSER_UNARY_OPERATOR_PRECEDENCE = 8
local PARSER_MULTIRET_NODE_TYPES = createLookupTable({ "FunctionCall", "VarArg" })
local PARSER_LVALUE_NODE_TYPES = createLookupTable({ "Variable", "TableIndex" })
local PARSER_STOP_KEYWORDS = createLookupTable({ "end", "else", "elseif", "until" })
--[[
Precedence and associativity of Lua operators.
The lower the number, the lower the priority of the operator.
If the right precedence is higher than the left precedence, the operator is right-associative.
Right-associative operators are evaluated from right to left.
--]]
local PARSER_OPERATOR_PRECEDENCE = {
["+"] = {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 PARSER_LUA_UNARY_OPERATORS = createLookupTable({ "-", "#", "not" })
local PARSER_LUA_BINARY_OPERATORS = createLookupTable({
"+", "-", "*", "/",
"%", "^", "..", "==",
"~=", "<", ">", "<=",
">=", "and", "or"
})
--[[
============================================================================
ヽ/❀o ل͜ o\ノ
THE PARSER!!!
============================================================================
The parser is responsible for converting the list of tokens into an
Abstract Syntax Tree (AST). The AST is a tree representation of the
structure of the code. Each node in the tree represents a different
part of the code. For example, a node could represent a function call,
a binary operation, or a variable declaration. The parser will also
perform some basic syntax checking to ensure the code is valid.
One of the most interesting parts of the parser is the expression parser,
which is responsible for placing operators and operands in the correct
order based on their precedence and associativity.
Here's an example of how the parser converts a simple Lua script into an
Abstract Syntax Tree (AST):
```lua
local x = 10 + 20
```
The resulting AST would look like this:
--]]
--* ParserMethods *--
local ParserMethods = {}
--// Token Navigation //--
function ParserMethods:lookAhead(n)
local updatedTokenIndex = self.currentTokenIndex + n
local updatedToken = self.tokens[updatedTokenIndex]
return updatedToken
end
function ParserMethods:consume(n)
local updatedTokenIndex = self.currentTokenIndex + n
local updatedToken = self.tokens[updatedTokenIndex]
self.currentTokenIndex = updatedTokenIndex
self.currentToken = updatedToken
return updatedToken
end
--// Scope Management //--
function ParserMethods:enterScope(isFunctionScope)
local scope = {
localVariables = {},
isFunctionScope = isFunctionScope
}
table.insert(self.scopeStack, scope)
self.currentScope = scope
return scope
end
function ParserMethods:exitScope()
self.scopeStack[#self.scopeStack] = nil
self.currentScope = self.scopeStack[#self.scopeStack]
end
--// In-Scope Variable Management //--
function ParserMethods:declareLocalVariable(variable)
self.currentScope.localVariables[variable] = true
end
function ParserMethods:declareLocalVariables(variables)
for _, variable in ipairs(variables) do
self:declareLocalVariable(variable)
end
end
function ParserMethods:getVariableType(variableName)
local isUpvalue = false
for scopeIndex = #self.scopeStack, 1, -1 do
local scope = self.scopeStack[scopeIndex]
if scope.localVariables[variableName] then
local variableType = (isUpvalue and "Upvalue") or "Local"
return variableType, scopeIndex
elseif scope.isFunctionScope then
isUpvalue = true
end
end
return "Global"
end
--// Token Checkers //--
function ParserMethods:checkCharacter(character, token)
token = token or self.currentToken
return token
and token.TYPE == "Character"
and token.Value == character
end
function ParserMethods:checkKeyword(keyword, token)
token = token or self.currentToken
return token
and token.TYPE == "Keyword"
and token.Value == keyword
end
function ParserMethods:isComma(token)
return token
and token.TYPE == "Character"
and token.Value == ","
end
function ParserMethods:isUnaryOperator(token)
return token
and token.TYPE == "Operator"
and PARSER_LUA_UNARY_OPERATORS[token.Value]
end
function ParserMethods:isBinaryOperator(token)
return token
and token.TYPE == "Operator"
and PARSER_LUA_BINARY_OPERATORS[token.Value]
end
--// AST Node Checkers //--
function ParserMethods:isValidAssignmentLvalue(node)
return PARSER_LVALUE_NODE_TYPES[node.TYPE]
end
function ParserMethods:isMultiretNode(node)
return PARSER_MULTIRET_NODE_TYPES[node.TYPE]
end
--// Token Expectation //--
function ParserMethods:expectTokenType(expectedType, skipConsume)
local actualType = self.currentToken and self.currentToken.TYPE or "nil"
assert(actualType == expectedType, string.format("Expected a %s, got: %s", expectedType, actualType))
if not skipConsume then self:consume(1) end
return self.currentToken
end
function ParserMethods:expectCharacter(character, skipConsume)
local actualType = self.currentToken and self.currentToken.TYPE or "nil"
assert(self.currentToken and self.currentToken.TYPE == "Character", "Expected a character, got: " .. actualType)
assert(self.currentToken.Value == character, "Expected '" .. character .. "'")
if not skipConsume then self:consume(1) end
return self.currentToken
end
function ParserMethods:expectKeyword(keyword, skipConsume)
local actualType = self.currentToken and self.currentToken.TYPE or "nil"
assert(self.currentToken and self.currentToken.TYPE == "Keyword", "Expected a keyword, got: " .. actualType)
assert(self.currentToken.Value == keyword, "Expected '" .. keyword .. "'")
if not skipConsume then self:consume(1) end
return self.currentToken
end
--// Auxiliary Functions //--
function ParserMethods:createNilNode()
return { TYPE = "Constant", Value = "nil" }
end
function ParserMethods:adjustMultiretNodes(nodeList, expectedReturnAmount)
local lastNode = nodeList[#nodeList]
local extraReturns = expectedReturnAmount - #nodeList
if lastNode and self:isMultiretNode(lastNode) then
extraReturns = math.max(extraReturns + 1, -1)
-- Adjust the return value amount
lastNode.ReturnValueAmount = extraReturns
else
for _ = 1, extraReturns do
table.insert(nodeList, self:createNilNode())
end
end
end
--// Parsers //--
function ParserMethods:consumeIdentifierList()
local identifiers = {}
while self.currentToken.TYPE == "Identifier" do
table.insert(identifiers, self.currentToken.Value)
if not self:isComma(self:lookAhead(1)) then break end
self:consume(2) -- Consume identifier and ","
end
return identifiers
end
function ParserMethods:consumeParameterList()
self:expectCharacter("(")
local parameters, isVarArg = {}, false
while not self:checkCharacter(")") do
if self.currentToken.TYPE == "Identifier" then
table.insert(parameters, self.currentToken.Value)
elseif self.currentToken.TYPE == "VarArg" then
isVarArg = true
self:consume(1) -- Consume the "..."
break
end
self:consume(1) -- Consume the last token of the parameter
if not self:isComma(self.currentToken) then break end
self:consume(1) -- Consume the comma
end
self:expectCharacter(")")
return parameters, isVarArg
end
function ParserMethods:consumeTableIndex(currentExpression)
self:consume(1) -- Consume the "." symbol
local indexToken = { TYPE = "String",
Value = self.currentToken.Value
}
return { TYPE = "TableIndex",
Index = indexToken,
Expression = currentExpression
}
end
function ParserMethods:consumeBracketTableIndex(currentExpression)
self:consume(1) -- Consume the "[" symbol
local indexExpression = self:consumeExpression()
self:consume(1) -- Consume the last token of the index expression
self:expectCharacter("]", true)
return { TYPE = "TableIndex",
Index = indexExpression,
Expression = currentExpression
}
end
function ParserMethods:consumeTable()
self:consume(1) -- Consume the "{" symbol
local elements = {}
local implicitElements = {}
local explicitElements = {}
local internalImplicitKey = 1
-- Loop until we find a "}" (end of the table)
while not self:checkCharacter("}") do
local key, value
local isImplicitKey = false
if self:checkCharacter("[") then
-- [<expression>] = <expression>
self:consume(1) -- Consume "["
key = self:consumeExpression()
self:consume(1) -- Consume the last token of the key
self:expectCharacter("]")
self:expectCharacter("=")
value = self:consumeExpression()
elseif self.currentToken.TYPE == "Identifier"
and self:checkCharacter("=", self:lookAhead(1)) then
-- <identifier> = <expression>
key = { TYPE = "String",
Value = self.currentToken.Value
}
self:consume(2) -- Consume key and "="
value = self:consumeExpression()
else
-- <expression>
key = { TYPE = "Number",
Value = internalImplicitKey
}
internalImplicitKey = internalImplicitKey + 1
isImplicitKey = true
value = self:consumeExpression()
end
local element = { Key = key, Value = value, IsImplicitKey = isImplicitKey }
local tableToInsert = (isImplicitKey and implicitElements) or explicitElements
table.insert(tableToInsert, element)
table.insert(elements, element)
self:consume(1) -- Consume the last token of the expression
-- Table elements can be separated by "," or ";"
local shouldContinue = self:checkCharacter(",") or self:checkCharacter(";")
if not shouldContinue then break end
self:consume(1) -- Consume ","
end
local lastElement = elements[#elements]
if lastElement and lastElement.IsImplicitKey then
local lastElementValue = lastElement.Value.Value
if self:isMultiretNode(lastElementValue) then
lastElementValue.ReturnValueAmount = -1
end
end
return { TYPE = "Table",
Elements = elements,
ImplicitElements = implicitElements,
ExplicitElements = explicitElements }
end
function ParserMethods:consumeFunctionCall(currentExpression)
self:consume(1) -- Consume the "("
local arguments = self:consumeExpressions()
self:adjustMultiretNodes(arguments, -1)
self:consume(1) -- Consume the last token of the expression
return { TYPE = "FunctionCall",
Expression = currentExpression,
Arguments = arguments,
ReturnValueAmount = 1,
WithSelf = false
}
end
function ParserMethods:consumeImplicitFunctionCall(lvalue)
local currentTokenType = self.currentToken.TYPE
-- <string>?
if currentTokenType == "String" then
local arguments = { self.currentToken }
return {
TYPE = "FunctionCall",
Expression = lvalue,
Arguments = arguments,
ReturnValueAmount = 1,
WithSelf = false
}
end
-- <table>
local arguments = { self:consumeTable() }
return { TYPE = "FunctionCall",
Expression = lvalue,
Arguments = arguments,
ReturnValueAmount = 1,
WithSelf = false
}
end
function ParserMethods:consumeMethodCall(currentExpression)
local methodIdentifier = self:consume(1).Value -- Consume the ":" character, and get the method identifier
self:consume(1) -- Consume the method identifier
local methodIndexNode = { TYPE = "TableIndex",
Index = { TYPE = "String",
Value = methodIdentifier
},
Expression = currentExpression
}
local functionCallNode = self:consumeFunctionCall(methodIndexNode)
functionCallNode.WithSelf = true -- Mark the function call as a method call
return functionCallNode
end
function ParserMethods:consumeOptionalSemilcolon()
local nextToken = self:lookAhead(1)
if self:checkCharacter(";", nextToken) then
self:consume(1)
end
end
--// EXPRESSSION PARSERS //--
function ParserMethods:parsePrimaryExpression()
if not self.currentToken then return end
local tokenType = self.currentToken.TYPE
local tokenValue = self.currentToken.Value
if tokenType == "Number" then return { TYPE = "Number", Value = tokenValue }
elseif tokenType == "String" then return { TYPE = "String", Value = tokenValue }
elseif tokenType == "Constant" then return { TYPE = "Constant", Value = tokenValue }
elseif tokenType == "VarArg" then return { TYPE = "VarArg", ReturnValueAmount = 1 }
elseif tokenType == "Identifier" then
local variableType = self:getVariableType(tokenValue)
local variableNode = { TYPE = "Variable",
Value = tokenValue,
VariableType = variableType
}
return variableNode
elseif tokenType == "Character" then
if tokenValue == "(" then -- Parenthesized expression
self:consume(1) -- Consume the parenthesis
local expression = self:consumeExpression()
self:consume(1) -- Consume the last token of the expression
return expression
elseif tokenValue == "{" then -- Table constructor
return self:consumeTable()
end
elseif tokenType == "Keyword" then
if tokenValue == "function" then
self:consume(1) -- Consume the "function" token
local parameters, isVarArg = self:consumeParameterList()
local codeblock = self:parseCodeBlock(true, parameters)
self:expectKeyword("end", true)
return { TYPE = "Function",
CodeBlock = codeblock,
Parameters = parameters,