-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtlc.lua
More file actions
4708 lines (4076 loc) · 168 KB
/
Copy pathtlc.lua
File metadata and controls
4708 lines (4076 loc) · 168 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--------------------------------------------------------------------------------
-- TINY LUA COMPILER (TLC)
--------------------------------------------------------------------------------
-- URL: https://github.com/bytexenon/tiny-lua-compiler
-- License: MIT (free to use and modify, attribution appreciated)
-- Version: 1.0.1
--------------------------------------------------------------------------------
-- DESCRIPTION:
-- A minimal, educational compiler for Lua 5.1, written in pure Lua 5.1.
-- It allows for dynamic compilation and execution of Lua code within a Lua
-- environment without needing to rely on the `load` or `loadstring`
-- functions.
-- It features a high-performance lexer, a complete parser, proper
-- operator precedence, lexical scoping, a bytecode generator, and a
-- register-based virtual machine.
--
-- Pipeline Stages:
-- 1. Tokenizer: Source Text -> Token Stream
-- 2. Parser: Tokens -> Abstract Syntax Tree (AST)
-- 3. Code Generator: AST -> Function Prototype (proto)
-- 4. Bytecode Emitter: Prototype -> Binary Chunk (bytecode string)
-- 5. Virtual Machine: Prototype -> Execution
--
-- USAGE:
-- local tlc = require("tlc")
-- tlc.run("print('Hello from TLC!')")
--
-- API SUMMARY:
-- High-Level
-- tlc.tokenize(code) ....................... Returns Token List
-- tlc.parse(code) .......................... Returns AST
-- tlc.compileToProto(code) ................. Returns Prototype
-- tlc.compile(code) ........................ Returns Bytecode String
-- tlc.run(code, env?, ...?) ................ Executes Code
--
-- Low-Level (Explicit Stages)
-- tlc.parseTokens(tokens) .................. Returns AST
-- tlc.generate(ast) ........................ Returns Prototype
-- tlc.emit(proto) .......................... Returns Bytecode String
-- tlc.execute(proto, env?, ...?) ........... Executes Prototype
--
-- Manual Pipeline (All Stages)
-- tlc.Tokenizer.new(code):tokenize() -> tokens
-- tlc.Parser.new(tokens):parse() -> ast
-- tlc.CodeGenerator.new(ast):generate() -> proto
-- tlc.BytecodeEmitter.emit(proto) -> bytecode string
-- tlc.VirtualMachine.execute(proto, env?, ...?) -> executes proto
--
-- NOTE:
-- * Internal component classes should be accessed via high-level API.
-- * TLC can run on all Lua versions (5.1 to 5.5), but generated bytecode from
-- BytecodeEmitter is only compatible with Lua 5.1.
--------------------------------------------------------------------------------
-- stylua: ignore start
-- In Lua, iterating over a list to check for existence is slow. By converting
-- the list `{"a", "b"}` into `{a=true, b=true}`, we leverage Lua's internal
-- hash map architecture. This makes checking `if keywords[word]` faster than
-- iterating through the list each time.
local function createLookupTable(list)
local lookup = {}
for _, value in ipairs(list) do
lookup[value] = true
end
return lookup
end
-- A helper function for creating a trie (prefix tree) from a list of strings.
--
-- This structure solves the "Longest Prefix Match" problem. When the tokenizer
-- encounters a character like `>`, it needs to decide if it's a standalone `>`,
-- or part of a longer operator like `>=`.
--
-- Instead of complex lookahead logic, we traverse this tree. If we can travel
-- deeper (e.g., from `>` to `=`), we continue. If we stop, we know we've
-- matched the longest valid operator.
local function createTrie(ops)
local trie = {}
for _, op in ipairs(ops) do
local node = trie
for char in op:gmatch(".") do
node[char] = node[char] or {}
node = node[char]
end
-- Mark this node as a valid ending point for an operator.
node.value = op
end
return trie
end
-- Running `string.match(char, "%d")` on every character of the source code
-- is computationally expensive due to pattern matching overhead.
--
-- Since a byte can only have 256 possible values, we can pre-calculate
-- the result of the pattern match for every possible character (1-255).
-- This transforms a regex operation into a simple array lookup.
local function createPatternLookup(pattern)
local lookup = {}
for code = 1, 255 do
local char = string.char(code)
if string.match(char, pattern) then
lookup[char] = true
end
end
return lookup
end
-- ============================================================================
-- (/^▽^)/
-- THE TOKENIZER!
-- ============================================================================
--
-- The first stage of compilation. The tokenizer (also called a lexer or
-- scanner) reads raw source text character by character and produces a flat
-- stream of labeled tokens - the smallest meaningful units in the language.
--
-- Example:
-- Input: "local x = 42 + y"
-- Output: [Keyword:local] [Identifier:x] [Equals] [Number:42]
-- [Operator:+] [Identifier:y]
--
-- Separating tokenization from parsing keeps both stages simple. The tokenizer
-- only needs to recognize lexical patterns ("is this a number?", "is this a
-- keyword?"). The parser only needs to understand structure ("is this a valid
-- if-statement?"). Neither needs to worry about the other's concerns.
-- In Lua, when you call string.sub with an index beyond the end of the string,
-- it returns an empty string. Storing it as a named constant makes the intent explicit.
local END_OF_FILE = ""
local TOKENIZER_CONFIG = {
DIGIT = createPatternLookup("%d"), -- 0-9
WHITESPACE = createPatternLookup("%s"), -- Whitespace (space, newline, etc.)
IDENTIFIER_START = createPatternLookup("[%a_]"), -- a-z, A-Z, underscore
-- The main lookup table for single-character tokens that can never be part
-- of a longer operator. Splitting them from UNSAFE_PUNCTUATION speeds up
-- common tokens like parentheses and commas: we emit their token immediately
-- without having to attempt an operator trie match first.
SAFE_PUNCTUATION = {
[":"] = "Colon", [";"] = "Semicolon",
["("] = "LeftParen", [")"] = "RightParen",
["{"] = "LeftBrace", ["}"] = "RightBrace",
["]"] = "RightBracket", [","] = "Comma"
-- These three are moved to UNSAFE_PUNCTUATION because they require
-- lookahead to determine their full meaning. We cannot immediately emit
-- a token upon seeing them the way we can for "(" or ",".
--
-- ["["] = "LeftBracket" - Can start long strings
-- ["."] = "Dot" - Can start ".." or "..."
-- ["="] = "Equals" - Can start "=="
},
-- Single-character tokens that may begin a longer operator sequence.
-- These are checked only after the operator trie has had a chance to match
-- a longer form: for example, `[` could start a long string `[[`, and `=`
-- could start `==`. We keep them here as a fallback for when the trie finds
-- no multi-character match.
UNSAFE_PUNCTUATION = {
["["] = "LeftBracket",
["."] = "Dot",
["="] = "Equals"
},
-- This trie allows us to efficiently match operators of varying lengths
-- without hardcoding complex lookahead logic. When we encounter a character
-- that could start an operator, we traverse the trie to find the longest valid
-- match.
OPERATOR_TRIE = createTrie({
"^", "*", "/", "%", "+", "-", "<", ">", "#",
"<=", ">=", "==", "~=", ".."
}),
-- Maps characters following a backslash '\' to their actual byte
-- values. For example, 'n' maps to the newline character '\n'.
ESCAPES = {
["a"] = "\a", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t",
["v"] = "\v", ["\\"] = "\\", ["\""] = "\"",
["\'"] = "\'"
},
-- Words that look like identifiers but carry special grammatical meaning in Lua.
-- The tokenizer first consumes any word as a generic identifier, then performs
-- an O(1) lookup against this table. If the word is found here, its token type
-- is changed from "Identifier" to "Keyword".
KEYWORDS = createLookupTable({
"and", "break", "do", "else",
"elseif", "end", "false", "for",
"function", "if", "in", "local",
"nil", "not", "or", "repeat",
"return", "then", "true", "until",
"while"
})
}
local Tokenizer = {}
Tokenizer.__index = Tokenizer
function Tokenizer.new(code)
assert(
type(code) == "string",
"Tokenizer.new requires a string as input code. Got: " .. type(code)
)
-- Create the instance table and set its metatable to `Tokenizer`.
-- This grants the instance access to all methods defined in the Tokenizer
-- class (like `consume`, `getNextToken`, `tokenize`, etc.) via prototypal
-- inheritance, avoiding the need to copy methods for each instance.
return setmetatable({
code = code,
curChar = code:sub(1, 1),
curCharPos = 1
}, Tokenizer)
end
--// Character Navigation //--
-- Looks ahead by 'n' characters in the character stream without advancing
-- the current position.
function Tokenizer:lookAhead(n)
local targetCharPos = self.curCharPos + n
local lookedAheadChar = self.code:sub(targetCharPos, targetCharPos)
return lookedAheadChar
end
-- Consumes (advances past) 'n' characters in the character stream.
function Tokenizer:consume(n)
if self.curChar == END_OF_FILE then
error("Internal Tokenizer Error: Attempted to consume past end of stream.")
end
local nextCharPos = self.curCharPos + n
local nextChar = self.code:sub(nextCharPos, nextCharPos)
-- Update the tokenizer's state.
self.curCharPos = nextCharPos
self.curChar = nextChar
end
-- When string.find() is used to bulk-consume characters, it returns an end
-- position but doesn't update the tokenizer state. Call this function to
-- synchronize self.curCharPos and self.curChar with the new position.
--
-- NOTE: self.curChar will be stale after string.find() and before calling
-- this function. Don't access self.curChar in that window!
function Tokenizer:setCurrentPosition(pos)
self.curCharPos = pos
self.curChar = self.code:sub(pos, pos)
end
--// Multi-Character Checkers //--
-- Checks if the current character and the next character form the
-- prefix of a hexadecimal number (0x or 0X).
function Tokenizer:isHexadecimalNumberPrefix()
if self.curChar == "0" then
local nextChar = self:lookAhead(1)
return nextChar == "x" or nextChar == "X"
end
return false
end
--// Utils //--
-- Calculates the "depth" of a long string or comment delimiter.
-- This counts how many '=' characters follow the initial '['.
--
-- For example:
-- [==[ -> depth of 2
-- [=[ -> depth of 1
-- [[ -> depth of 0
function Tokenizer:calculateDelimiterDepth()
-- Match a sequence of '=' characters starting from the current position.
-- "^" ensures we match from the current position, and "=*" matches zero or
-- more '=' characters.
local startMatchPos, endMatchPos = string.find(self.code, "^=*", self.curCharPos)
return endMatchPos - startMatchPos + 1
end
--// Consumers //--
function Tokenizer:skipWhitespace()
-- Match optional whitespace characters after the initial whitespace character.
local _, endPos = string.find(self.code, "^%s*", self.curCharPos + 1)
self:setCurrentPosition(endPos + 1)
end
function Tokenizer:consumeIdentifier()
-- The initial character has already been verified to be a
-- valid identifier start. Match any subsequent characters
-- that are valid followers (letters, digits, underscores).
local startPos, endPos = string.find(self.code, "^[0-9a-zA-Z_]*", self.curCharPos)
self:setCurrentPosition(endPos + 1)
return self.code:sub(startPos, endPos)
end
-- Must be called after verifying the hex prefix (0x or 0X) is present.
-- Returns the string representation including the prefix (e.g., "0xFF").
function Tokenizer:consumeHexadecimalNumber()
local startPos = self.curCharPos
-- Find hex digits after the "0x" or "0X" prefix (skip first 2 chars).
-- At least one hex digit is required after the prefix.
local _, endPos = string.find(self.code, "^[0-9a-fA-F]+", self.curCharPos + 2)
if not endPos then
error(string.format(
"malformed number near '%s'",
self.code:sub(startPos, self.curCharPos - 1)
))
end
local nextChar = self.code:sub(endPos + 1, endPos + 1)
-- Is it a hexadecimal literal with an exponent part (e.g., 0x2p4)?
if nextChar == "p" or nextChar == "P" then
local _, exponentEndPos = string.find(self.code, "^[0-9]+", endPos + 2)
if not exponentEndPos then
error(string.format(
"malformed number near '%s'",
self.code:sub(startPos, self.curCharPos - 1)
))
end
endPos = exponentEndPos
end
self:setCurrentPosition(endPos + 1)
return self.code:sub(startPos, self.curCharPos - 1)
end
-- Recognizes all Lua 5.1 number formats:
-- - Decimal integers: 42, 123
-- - Floating point: 3.14, .5, 42. (trailing dot is allowed)
-- - Hexadecimal: 0xFF, 0X1A3, 0x2b, 0x2p4 (delegates to helper)
-- - Scientific notation: 1e10, 3.14E-2, 5e+3
-- - Mixed formats: 1.e3 (1000), .5e-1 (0.05)
function Tokenizer:consumeNumber()
local startPos = self.curCharPos
-- Hexadecimal Case: Check for "0x" or "0X" prefix.
-- Pattern: 0[xX][0-9a-fA-F]+[[pP][0-9]+]? (handled in helper)
if self:isHexadecimalNumberPrefix() then
return self:consumeHexadecimalNumber()
end
-- Decimal Case: Parse the integer part first.
-- Match optional leading digits (e.g., "42" in "42.5" or "0" in "0.5").
local _, endPos = string.find(self.code, "^[0-9]*", startPos)
-- Fractional Part: Check for decimal point followed by optional digits.
local nextChar = self.code:sub(endPos + 1, endPos + 1)
if nextChar == "." then
_, endPos = string.find(self.code, "^[0-9]*", endPos + 2)
end
-- Exponent Part: Check for scientific notation (e.g., 1e10, 3.5E-2).
-- The exponent must have at least one digit after the optional sign.
nextChar = self.code:sub(endPos + 1, endPos + 1)
if nextChar == "e" or nextChar == "E" then
_, endPos = string.find(self.code, "^[+-]?[0-9]+", endPos + 2)
if not endPos then
error(string.format(
"malformed number near '%s'",
self.code:sub(startPos, self.curCharPos - 1)
))
end
end
-- Done parsing the number, update the tokenizer's
-- position to the end of the number.
self:setCurrentPosition(endPos + 1)
-- Lua forbids identifiers immediately after numbers (e.g., "123abc").
-- This prevents ambiguity: is "123abc" a number or an identifier?
-- The official Lua lexer treats this as a malformed number, not an
-- identifier. We replicate this behavior for compatibility.
if TOKENIZER_CONFIG.IDENTIFIER_START[self.curChar] then
error(string.format(
"malformed number near '%s'",
self.code:sub(startPos, self.curCharPos - 1)
))
end
return self.code:sub(startPos, self.curCharPos - 1)
end
-- Called after encountering a backslash (`\`) in a simple string.
-- Returns the resolved character (e.g., `\n` -> newline, `\65` -> `A`).
function Tokenizer:consumeEscapeSequence()
self:consume(1) -- Consume the backslash.
local curChar = self.curChar
-- Named escape? (e.g., \n -> newline, \t -> tab)
local convertedChar = TOKENIZER_CONFIG.ESCAPES[curChar]
if convertedChar then
self:consume(1)
return convertedChar
-- Numeric escape? (e.g., \65 -> `A`, \123 -> `{`)
elseif TOKENIZER_CONFIG.DIGIT[curChar] then
-- Match up to three digits (0-9), but at least one is required.
local pattern = "^[0-9][0-9]?[0-9]?"
local startPos, endPos = string.find(self.code, pattern, self.curCharPos)
local numberString = self.code:sub(startPos, endPos)
local number = tonumber(numberString)
if number > 255 then
error(string.format("escape sequence too large near '\\%s'", numberString))
end
self:setCurrentPosition(endPos + 1)
return string.char(number)
end
-- Unknown escape: Lua's lexer is lenient and passes
-- the character through verbatim (e.g., "\e" -> "e").
-- We replicate this quirk for compatibility.
self:consume(1)
return curChar
end
function Tokenizer:consumeSimpleString()
local quoteChar = self.curChar
local stringTable = {}
local stringIndex = 0
self:consume(1) -- Consume the opening quote.
while self.curChar ~= quoteChar do
if self.curChar == END_OF_FILE then
error("Unclosed string")
elseif self.curChar == "\n" then
error("Unclosed string (newline found)")
-- Is it an escape sequence?
elseif self.curChar == "\\" then
local consumedEscape = self:consumeEscapeSequence()
stringIndex = stringIndex + 1
stringTable[stringIndex] = consumedEscape
else
stringIndex = stringIndex + 1
stringTable[stringIndex] = self.curChar
self:consume(1)
end
end
self:consume(1) -- Consume the closing quote.
return table.concat(stringTable)
end
-- Consumes a long string literal using [[...]] or [=[...]=] syntax.
-- Automatically skips a leading newline if present (Lua 5.1 behavior).
function Tokenizer:consumeLongString()
self:consume(1) -- Consume the first '['.
local depth = self:calculateDelimiterDepth()
self:consume(depth) -- Consume the '=' characters.
if self.curChar ~= "[" then
error("Invalid long string delimiter")
end
self:consume(1)
local firstStringChar = self.curChar
-- Long string starts with a newline?
if firstStringChar == "\n" then
-- If the first character inside the long string is a newline,
-- we skip it entirely. This is an edge case in the official lexer source.
-- Source: https://www.lua.org/source/5.1/llex.c.html#read_long_string
-- Skip it.
self:consume(1)
end
local stringStartPos = self.curCharPos
local closingDelimiter = "%]" .. string.rep("=", depth) .. "%]"
local startPos, endPos = string.find(self.code, closingDelimiter, self.curCharPos)
if not endPos then
error("Unclosed long string")
end
self:setCurrentPosition(endPos + 1)
return self.code:sub(stringStartPos, startPos - 1)
end
-- Uses the operator trie for longest prefix matching.
function Tokenizer:consumeOperator()
local node = TOKENIZER_CONFIG.OPERATOR_TRIE
local operator
-- Walk the trie character by character.
local startPos = self.curCharPos
local newCharPos = startPos
while true do
-- Optimization: Use `sub` instead of `lookAhead` to
-- avoid extra function call overhead in this tight loop.
local character = string.sub(self.code, newCharPos, newCharPos)
node = node[character]
-- If the path doesn't exist in the trie,
-- it means that we've gone as far as we can.
if not node then break end
-- If this node represents a valid operator, remember it.
-- We keep going to see if there's a longer match (greedy matching).
operator = node.value
newCharPos = newCharPos + 1
end
if not operator then return end
self:consume(newCharPos - startPos)
return operator
end
function Tokenizer:skipShortComment()
-- Match anything until the next newline or end of input.
local _, endPos = string.find(self.code, "[^\n]*", self.curCharPos)
self:setCurrentPosition(endPos + 1)
end
-- Consumes a multi-line comment using --[[...]] or --[=[...]=] syntax.
function Tokenizer:skipLongComment()
self:consume(1) -- Consume the first '['.
local depth = self:calculateDelimiterDepth()
self:consume(depth) -- Consume the '=' characters.
-- Not a complete long-comment delimiter - fall through to the short-comment path.
if self.curChar ~= "[" then
self:skipShortComment()
return
end
self:consume(1)
-- Consume the closing delimiter using Lua pattern matching.
-- (We're putting the modulo signs around the `]` to escape it in the pattern).
local closingDelimiter = "%]" .. string.rep("=", depth) .. "%]"
local _, endPos = string.find(self.code, closingDelimiter, self.curCharPos)
if not endPos then
error("Unclosed long comment")
end
self:setCurrentPosition(endPos + 1)
end
function Tokenizer:skipComment()
self:consume(2)
if self.curChar == "[" then
return self:skipLongComment()
end
return self:skipShortComment()
end
--// Token Consumer Handler //--
-- Consumes and returns tokenKind, tokenValue, tokenRaw for the next
-- token in the stream. If it returns a nil "tokenKind", it means that
-- no token was produced (e.g., whitespace or comment), so the caller should
-- call this method again to get the next token.
--
-- Note that "tokenValue" and "tokenRaw" may also be nil for tokens that don't
-- have associated values (e.g., punctuation).
--
-- For optimization, the checks in this function are ordered by expected
-- frequency in typical Lua source code. Whitespace and identifiers come
-- first since they appear most often. Safe punctuation and strings follow.
-- Numbers, comments, dot-prefixed numbers, varargs, and long strings are
-- progressively less common. Symbolic operators are matched via the trie.
-- Unsafe punctuation is handled last as a fallback.
function Tokenizer:getNextToken()
local curChar = self.curChar
if TOKENIZER_CONFIG.WHITESPACE[curChar] then
self:skipWhitespace()
curChar = self.curChar
-- If the stream ends with whitespace, check here to avoid returning
-- a stale token to the caller.
if curChar == END_OF_FILE then
return nil
end
end
if TOKENIZER_CONFIG.IDENTIFIER_START[curChar] then
local identifier = self:consumeIdentifier()
-- Is it a keyword? (E.g., "while", "local", "function", etc.)
if TOKENIZER_CONFIG.KEYWORDS[identifier] then
return "Keyword", identifier
end
return "Identifier", identifier
end
-- Processes "safe" punctuation first (single-character tokens that
-- cannot be part of multi-character tokens).
local safeTokenKind = TOKENIZER_CONFIG.SAFE_PUNCTUATION[curChar]
if safeTokenKind then
self:consume(1)
return safeTokenKind, nil
elseif curChar == '"' or curChar == "'" then
return "String", self:consumeSimpleString()
elseif TOKENIZER_CONFIG.DIGIT[curChar] then
local numberString = self:consumeNumber()
local numberValue = tonumber(numberString)
if not numberValue then
error(string.format(
"malformed number near '%s'",
numberString
))
end
return "Number", numberValue, numberString
elseif curChar == "-" and self:lookAhead(1) == "-" then
self:skipComment()
return nil
-- Handle numbers starting with a decimal point and vararg ("...").
elseif curChar == "." then
local nextChar = self:lookAhead(1)
-- Repeat the number tokenization logic for the case where a number starts
-- with a decimal point (e.g., ".5", ".5e-1", "1.e3").
if TOKENIZER_CONFIG.DIGIT[nextChar] then
local numberString = self:consumeNumber()
local numberValue = tonumber(numberString)
if not numberValue then
error(string.format(
"malformed number near '%s'",
numberString
))
end
return "Number", numberValue, numberString
elseif nextChar == "." and self:lookAhead(2) == "." then
self:consume(3)
return "Vararg", nil
end
-- Handle long string literals (with [[...]] or [=[...]=], etc.).
elseif curChar == "[" then
local nextChar = self:lookAhead(1)
if nextChar == "[" or nextChar == "=" then
return "String", self:consumeLongString()
end
end
-- Symbolic operators like "+", "==", "<=", "..".
local operator = self:consumeOperator()
if operator then
return "Operator", operator
end
-- Handle "unsafe" punctuation (single-character tokens that
-- could be part of multi-character tokens).
local unsafeTokenKind = TOKENIZER_CONFIG.UNSAFE_PUNCTUATION[curChar]
if unsafeTokenKind then
self:consume(1)
return unsafeTokenKind, nil
end
-- If we reach this point, it means the current character doesn't match
-- any known token kind. This is an error condition, as the character
-- is not valid in the Lua language syntax.
error(string.format(
"Unexpected character '%s' at position %d",
tostring(curChar),
self.curCharPos
))
end
--// Tokenizer Main Method //--
function Tokenizer:tokenize()
local tokens, tokenIndex = {}, 0
while self.curChar ~= END_OF_FILE do
local tokenKind, tokenValue, tokenRaw = self:getNextToken()
if tokenKind then
tokenIndex = tokenIndex + 1
tokens[tokenIndex] = {
kind = tokenKind,
value = tokenValue,
raw = tokenRaw
}
end
end
-- Append a sentinel EOF token at the end of the stream. The parser can then
-- assume the current token is always non-nil, removing the need for
-- `if token then` guards on every token check.
table.insert(tokens, {
kind = "EOF",
value = nil,
raw = nil
})
return tokens
end
-- ============================================================================
-- (ノ◕ヮ◕)ノ*:・゚ THE PARSER!
-- ============================================================================
--
-- The parser is the second stage of compilation. It transforms a flat stream
-- of tokens into an Abstract Syntax Tree (AST) - a nested structure that makes
-- the grammatical meaning of the source explicit.
--
-- Where the tokenizer asks "what symbols are present?", the parser asks "how
-- are those symbols related?" A token stream is flat; the AST makes nesting
-- and operator precedence visible through its shape.
--
-- Two complementary techniques are used. Recursive descent handles the top-down
-- structure of statements: each construct (`if`, `while`, `for`, `function`,
-- `local`, and so on) has its own parsing function. Precedence climbing handles
-- expressions, correctly binding `*` tighter than `+` and keeping `^` and `..`
-- right-associative - all without writing a separate grammar rule for each
-- precedence level.
--
-- Example:
-- Input source:
-- local x = 1 + 2 * 3
--
-- Tokens:
-- [
-- { kind = "Keyword", value = "local" },
-- { kind = "Identifier", value = "x" },
-- { kind = "Equals" },
-- { kind = "Number", value = 1 },
-- { kind = "Operator", value = "+" },
-- { kind = "Number", value = 2 },
-- { kind = "Operator", value = "*" },
-- { kind = "Number", value = 3 },
-- { kind = "EOF" }
-- ]
--
-- AST:
-- Program
-- LocalDeclarationStatement
-- variables: ["x"]
-- initializers:
-- BinaryOperator("+")
-- left: NumericLiteral(1)
-- right: BinaryOperator("*")
-- left: NumericLiteral(2)
-- right: NumericLiteral(3)
--
-- Notice the tree shape: `2 * 3` is nested under `+`, reflecting that
-- multiplication binds more tightly and must be evaluated first.
local PARSER_CONFIG = {
-- Operator Precedence & Associativity Table
-- -----------------------------------------
-- This table drives the "Precedence Climbing" algorithm in `parseBinaryExpression`.
-- Each entry is a pair { left_binding_power, right_binding_power } that encodes
-- both the operator's precedence and its associativity.
--
-- Higher numbers mean tighter binding - that is why `*` is evaluated before
-- `+` in `1 + 2 * 3`. Left-associative operators (e.g., `+`, `-`) carry
-- equal left and right powers, so `1 - 2 - 3` parses as `(1 - 2) - 3`.
-- Right-associative operators (e.g., `^`, `..`) carry a slightly higher right
-- power, so `a ^ b ^ c` parses as `a ^ (b ^ c)`.
PRECEDENCE = {
["+"] = {6, 6}, ["-"] = {6, 6}, -- Addition/Subtraction
["*"] = {7, 7}, ["/"] = {7, 7}, -- Multiplication/Division
["%"] = {7, 7}, -- Modulo
["^"] = {10, 9}, -- Exponentiation (Right-associative!)
[".."] = {5, 4}, -- String Concatenation (Right-associative!)
["=="] = {3, 3}, ["~="] = {3, 3}, -- Equality / Inequality
["<"] = {3, 3}, [">"] = {3, 3}, -- Less Than / Greater Than
["<="] = {3, 3}, [">="] = {3, 3}, -- Less Than or Equal / Greater Than or Equal
["and"] = {2, 2}, -- Logical AND (Short-circuiting)
["or"] = {1, 1} -- Logical OR (Short-circuiting)
},
-- Precedence for all unary operators (like `-x` or `not x`).
-- They bind tighter than most binary operators but looser than exponentiation.
-- (e.g., `-2^3` parses as `-(2^3)`, not `(-2)^3`).
UNARY_PRECEDENCE = 8,
-- L-Values (Locator Values).
-- These are the specific node types that are allowed to appear on the
-- LEFT side of an assignment (e.g., `x = 1` or `t.k = 1`).
-- You can't assign to a number (`5 = 1` is invalid), so "NumericLiteral" isn't here.
LVALUE_NODES = createLookupTable({ "Identifier", "IndexExpression" }),
-- Keywords that signal the end of a block. When the parser sees one of
-- these, it stops parsing statements in the current block and returns
-- control to the caller that owns that keyword.
TERMINATION_KEYWORDS = createLookupTable({ "end", "else", "elseif", "until" }),
UNARY_OPERATORS = createLookupTable({ "-", "#", "not" }),
BINARY_OPERATORS = createLookupTable({
"+", "-", "*", "/",
"%", "^", "..", "==",
"~=", "<", ">", "<=",
">=", "and", "or"
})
}
local Parser = {}
Parser.__index = Parser
function Parser.new(tokens)
assert(
type(tokens) == "table",
"Parser.new requires a table of tokens. Got: " .. type(tokens)
)
local self = setmetatable({}, Parser)
self.tokens = tokens
self.currentToken = tokens[1]
self.currentTokenIndex = 1
-- A special flag which gets set to `true` when we encounter either
-- a `break` statement, or a `return` statement. This is used to prevent
-- parsing code that syntactically may be correct, but is semantically invalid.
self.shouldTerminateBlock = false
-- A lookup table that maps statement-starting keywords to their corresponding
-- parsing functions. This allows the main statement parsing loop to quickly
-- dispatch to the correct parser based on the current token.
self.statementHandlers = {
["do"] = self.parseDoStatement,
["break"] = self.parseBreakStatement,
["for"] = self.parseForStatement,
["function"] = self.parseFunctionDeclaration,
["if"] = self.parseIfStatement,
["local"] = self.parseLocalStatement,
["repeat"] = self.parseRepeatStatement,
["return"] = self.parseReturnStatement,
["while"] = self.parseWhileStatement
}
return self
end
--// Token Navigation //--
-- NOTE: This is called only in `:parseTableConstructor`, the one place in the
-- parser that needs to look more than one token ahead.
function Parser:peekNext()
return self.tokens[self.currentTokenIndex + 1]
end
function Parser:advance(n)
local newTokenIndex = self.currentTokenIndex + n
self.currentTokenIndex = newTokenIndex
self.currentToken = self.tokens[newTokenIndex]
end
function Parser:getTokenDescription(token)
if not token.value then return tostring(token.kind) end
return string.format("%s [%s]", tostring(token.kind), tostring(token.value))
end
function Parser:expect(tokenKind, tokenValue)
local token = self.currentToken
if token.kind == tokenKind and token.value == tokenValue then
self:advance(1)
return
end
error(string.format(
"Expected %s [%s] token, got: %s",
tostring(tokenKind),
tostring(tokenValue),
self:getTokenDescription(token)
))
end
-- Conditionally consume the current token by kind.
--
-- This is the parser equivalent of asking "is the next token a comma?" and,
-- if so, advancing past it.
function Parser:advanceIfMatch(tokenKind)
if self.currentToken.kind == tokenKind then
self:advance(1)
return true
end
return false
end
--// Token Checkers //--
-- Lightweight checks to see if a token matches a specific kind and/or value
-- without throwing an error if it doesn't match.
function Parser:isTokenKind(kind)
return self.currentToken.kind == kind
end
function Parser:isKeyword(keyword)
local token = self.currentToken
return token.kind == "Keyword" and token.value == keyword
end
function Parser:isUnaryOperator()
local token = self.currentToken
return (token.kind == "Operator" or token.kind == "Keyword")
and PARSER_CONFIG.UNARY_OPERATORS[token.value]
end
function Parser:isBinaryOperator()
local token = self.currentToken
return (token.kind == "Operator" or token.kind == "Keyword")
and PARSER_CONFIG.BINARY_OPERATORS[token.value]
end
--// Token Expectation //--
-- These functions verify that the current token matches an expected kind or
-- keyword and then consume it. If the check fails, they throw an error.
function Parser:expectKind(expectedKind)
if not self:isTokenKind(expectedKind) then
error(string.format(
"Expected a %s, but found %s",
tostring(expectedKind),
tostring(self.currentToken.kind)
))
end
self:advance(1)
end
function Parser:expectKeyword(keyword)
if not self:isKeyword(keyword) then
error(string.format(
"Expected keyword '%s', but found %s",
keyword,
self:getTokenDescription(self.currentToken)
))
end
self:advance(1)
end
--// AST Node Checkers //--
-- Functions to check properties of already-parsed AST nodes.
-- Valid LValues are single variables or table access expressions.
function Parser:isValidAssignmentLvalue(node)
return node and PARSER_CONFIG.LVALUE_NODES[node.kind]
end
--// Parsers //--
-- These functions are responsible for parsing specific syntactic constructs
-- in the token stream and building the corresponding AST nodes.
-- `(<parameters>) <body> end`
function Parser:parseFunctionExpression()
local parameters, isVararg = self:parseParameterList()
local body = self:parseCodeBlock()
self:expectKeyword("end")
return { kind = "FunctionExpression",
body = body,
parameters = parameters,
isVararg = isVararg
}
end
-- `if/elseif <condition> then <body>`
function Parser:parseIfClause(keyword)
self:expectKeyword(keyword) -- "if" / "elseif"
local condition = self:expectExpression()
self:expectKeyword("then")
local body = self:parseCodeBlock()
return { kind = "IfClause",
condition = condition,
body = body
}
end
-- `do <body> end`
--
-- Used as a utility parser for every statement that opens a `do ... end` block
-- (e.g., `while`, `for`, and standalone `do` statements).
function Parser:parseDoEndLoopBlock()
self:expectKeyword("do")
local body = self:parseCodeBlock()
self:expectKeyword("end")
return body
end
function Parser:expectIdentifier()
local currentToken = self.currentToken
self:expectKind("Identifier")
return currentToken.value
end
-- `<identifier>, <identifier>, ...`
function Parser:parseIdentifierList()
local identifiers = { self:expectIdentifier() }
while self:advanceIfMatch("Comma") do
table.insert(identifiers, self:expectIdentifier())
end