-
Notifications
You must be signed in to change notification settings - Fork 5
/
preprocess.lua
3909 lines (3132 loc) · 125 KB
/
preprocess.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
--[[============================================================
--=
--= LuaPreprocess v1.21-dev - preprocessing library
--= by Marcus 'ReFreezed' Thunström
--=
--= License: MIT (see the bottom of this file)
--= Website: http://refreezed.com/luapreprocess/
--= Documentation: http://refreezed.com/luapreprocess/docs/
--=
--= Tested with Lua 5.1, 5.2, 5.3, 5.4 and LuaJIT.
--=
--==============================================================
API:
Global functions in metaprograms:
- copyTable
- escapePattern
- getIndentation
- isProcessing
- pack
- pairsSorted
- printf
- readFile, writeFile, fileExists
- run
- sortNatural, compareNatural
- tokenize, newToken, concatTokens, removeUselessTokens, eachToken, isToken, getNextUsefulToken
- toLua, serialize, evaluate
Only during processing:
- getCurrentPathIn, getCurrentPathOut
- getOutputSoFar, getOutputSoFarOnLine, getOutputSizeSoFar, getCurrentLineNumberInOutput, getCurrentIndentationInOutput
- loadResource, callMacro
- outputValue, outputLua, outputLuaTemplate
- startInterceptingOutput, stopInterceptingOutput
Macros:
- ASSERT
- LOG
Search this file for 'EnvironmentTable' and 'PredefinedMacros' for more info.
Exported stuff from the library:
- (all the functions above)
- VERSION
- metaEnvironment
- processFile, processString
Search this file for 'ExportTable' for more info.
----------------------------------------------------------------
How to metaprogram:
The exclamation mark (!) is used to indicate what code is part of
the metaprogram. There are 4 main ways to write metaprogram code:
!... The line will simply run during preprocessing. The line can span multiple actual lines if it contains brackets.
!!... The line will appear in both the metaprogram and the final program. The line must be an assignment.
!(...) The result of the parenthesis will be outputted as a literal if it's an expression, otherwise it'll just run.
!!(...) The result of the expression in the parenthesis will be outputted as Lua code. The result must be a string.
Short examples:
!if not isDeveloper then
sendTelemetry()
!end
!!local tau = 2*math.pi -- The expression will be evaluated in the metaprogram and the result will appear in the final program as a literal.
local bigNumber = !(5^10)
local font = !!(isDeveloper and "loadDevFont()" or "loadUserFont()")
-- See the full documentation for additional features (like macros):
-- http://refreezed.com/luapreprocess/docs/extra-functionality/
----------------------------------------------------------------
-- Example program:
-- Normal Lua.
local n = 0
doTheThing()
-- Preprocessor lines.
local n = 0
!if math.random() < 0.5 then
n = n+10 -- Normal Lua.
-- Note: In the final program, this will be in the
-- same scope as 'local n = 0' here above.
!end
!for i = 1, 3 do
print("3 lines with print().")
!end
-- Extended preprocessor line. (Lines are consumed until brackets
-- are balanced when the end of the line has been reached.)
!newClass{ -- Starts here.
name = "Entity",
props = {x=0, y=0},
} -- Ends here.
-- Preprocessor block.
!(
local dogWord = "Woof "
function getDogText()
return dogWord:rep(3)
end
)
-- Preprocessor inline block. (Expression that returns a value.)
local text = !("The dog said: "..getDogText())
-- Preprocessor inline block variant. (Expression that returns a Lua code string.)
_G.!!("myRandomGlobal"..math.random(5)) = 99
-- Dual code (both preprocessor line and final output).
!!local partial = "Hello"
local whole = partial .. !(partial..", world!")
print(whole) -- HelloHello, world!
-- Beware in preprocessor blocks that only call a single function!
!( func() ) -- This will bee seen as an inline block and output whatever value func() returns as a literal.
!( func(); ) -- If that's not wanted then a trailing `;` will prevent that. This line won't output anything by itself.
-- When the full metaprogram is generated, `!(func())` translates into `outputValue(func())`
-- while `!(func();)` simply translates into `func();` (because `outputValue(func();)` would be invalid Lua code).
-- Though in this specific case a preprocessor line (without the parenthesis) would be nicer:
!func()
-- For the full documentation, see:
-- http://refreezed.com/luapreprocess/docs/
--============================================================]]
local PP_VERSION = "1.21.0-dev"
local MAX_DUPLICATE_FILE_INSERTS = 1000 -- @Incomplete: Make this a parameter for processFile()/processString().
local MAX_CODE_LENGTH_IN_MESSAGES = 60
local KEYWORDS = {
"and","break","do","else","elseif","end","false","for","function","if","in",
"local","nil","not","or","repeat","return","then","true","until","while",
-- Lua 5.2
"goto", -- @Incomplete: A parameter to disable this for Lua 5.1?
} for i, v in ipairs(KEYWORDS) do KEYWORDS[v], KEYWORDS[i] = true, nil end
local PREPROCESSOR_KEYWORDS = {
"file","insert","line",
} for i, v in ipairs(PREPROCESSOR_KEYWORDS) do PREPROCESSOR_KEYWORDS[v], PREPROCESSOR_KEYWORDS[i] = true, nil end
local PUNCTUATION = {
"+", "-", "*", "/", "%", "^", "#",
"==", "~=", "<=", ">=", "<", ">", "=",
"(", ")", "{", "}", "[", "]",
";", ":", ",", ".", "..", "...",
-- Lua 5.2
"::",
-- Lua 5.3
"//", "&", "|", "~", ">>", "<<",
} for i, v in ipairs(PUNCTUATION) do PUNCTUATION[v], PUNCTUATION[i] = true, nil end
local ESCAPE_SEQUENCES_EXCEPT_QUOTES = {
["\a"] = [[\a]],
["\b"] = [[\b]],
["\f"] = [[\f]],
["\n"] = [[\n]],
["\r"] = [[\r]],
["\t"] = [[\t]],
["\v"] = [[\v]],
["\\"] = [[\\]],
}
local ESCAPE_SEQUENCES = {
["\""] = [[\"]],
["\'"] = [[\']],
} for k, v in pairs(ESCAPE_SEQUENCES_EXCEPT_QUOTES) do ESCAPE_SEQUENCES[k] = v end
local USELESS_TOKENS = {whitespace=true, comment=true}
local LOG_LEVELS = {
["off" ] = 0,
["error" ] = 1,
["warning"] = 2,
["info" ] = 3,
["debug" ] = 4,
["trace" ] = 5,
}
local metaEnv = nil
local dummyEnv = {}
-- Controlled by processFileOrString():
local current_parsingAndMeta_isProcessing = false
local current_parsingAndMeta_isDebug = false
-- Controlled by _processFileOrString():
local current_anytime_isRunningMeta = false
local current_anytime_pathIn = ""
local current_anytime_pathOut = ""
local current_anytime_fastStrings = false
local current_parsing_insertCount = 0
local current_parsingAndMeta_onInsert = nil
local current_parsingAndMeta_resourceCache = nil
local current_parsingAndMeta_addLineNumbers = false
local current_parsingAndMeta_macroPrefix = ""
local current_parsingAndMeta_macroSuffix = ""
local current_parsingAndMeta_strictMacroArguments = true
local current_meta_pathForErrorMessages = ""
local current_meta_output = nil -- Top item in current_meta_outputStack.
local current_meta_outputStack = nil
local current_meta_canOutputNil = true
local current_meta_releaseMode = false
local current_meta_maxLogLevel = "trace"
local current_meta_locationTokens = nil
--==============================================================
--= Local Functions ============================================
--==============================================================
local assertarg
local countString, countSubString
local getLineNumber
local loadLuaString
local maybeOutputLineNumber
local sortNatural
local tableInsert, tableRemove, tableInsertFormat
local utf8GetCodepointAndLength
local F = string.format
local function tryToFormatError(err0)
local err, path, ln = nil
if type(err0) == "string" then
do path, ln, err = err0:match"^(%a:[%w_/\\.]+):(%d+): (.*)"
if not err then path, ln, err = err0:match"^([%w_/\\.]+):(%d+): (.*)"
if not err then path, ln, err = err0:match"^(%S-):(%d+): (.*)"
end end end
end
if err then
return F("Error @ %s:%s: %s", path, ln, err)
else
return "Error: "..tostring(err0)
end
end
local function printf(s, ...)
print(F(s, ...))
end
-- printTokens( tokens [, filterUselessTokens ] )
local function printTokens(tokens, filter)
for i, tok in ipairs(tokens) do
if not (filter and USELESS_TOKENS[tok.type]) then
printf("%d %-12s '%s'", i, tok.type, (F("%q", tostring(tok.value)):sub(2, -2):gsub("\\\n", "\\n")))
end
end
end
local function printError(s)
io.stderr:write(s, "\n")
end
local function printfError(s, ...)
printError(F(s, ...))
end
-- message = formatTraceback( [ level=1 ] )
local function formatTraceback(level)
local buffer = {}
tableInsert(buffer, "stack traceback:\n")
level = 1 + (level or 1)
local stack = {}
while level < 1/0 do
local info = debug.getinfo(level, "nSl")
if not info then break end
local isFile = info.source:find"^@" ~= nil
local sourceName = (isFile and info.source:sub(2) or info.short_src)
local subBuffer = {"\t"}
tableInsertFormat(subBuffer, "%s:", sourceName)
if info.currentline > 0 then
tableInsertFormat(subBuffer, "%d:", info.currentline)
end
if (info.name or "") ~= "" then
tableInsertFormat(subBuffer, " in '%s'", info.name)
elseif info.what == "main" then
tableInsert(subBuffer, " in main chunk")
elseif info.what == "C" or info.what == "tail" then
tableInsert(subBuffer, " ?")
else
tableInsertFormat(subBuffer, " in <%s:%d>", sourceName:gsub("^.*[/\\]", ""), info.linedefined)
end
tableInsert(stack, table.concat(subBuffer))
level = level + 1
end
while stack[#stack] == "\t[C]: ?" do
stack[#stack] = nil
end
for _, s in ipairs(stack) do
tableInsert(buffer, s)
tableInsert(buffer, "\n")
end
return table.concat(buffer)
end
-- printErrorTraceback( message [, level=1 ] )
local function printErrorTraceback(message, level)
printError(tryToFormatError(message))
printError(formatTraceback(1+(level or 1)))
end
-- debugExit( )
-- debugExit( messageValue )
-- debugExit( messageFormat, ... )
local function debugExit(...)
if select("#", ...) > 1 then
printfError(...)
elseif select("#", ...) == 1 then
printError(...)
end
os.exit(2)
end
-- errorf( [ level=1, ] string, ... )
local function errorf(sOrLevel, ...)
if type(sOrLevel) == "number" then
error(F(...), (sOrLevel == 0 and 0 or 1+sOrLevel))
else
error(F(sOrLevel, ...), 2)
end
end
-- local function errorLine(err) -- Unused.
-- if type(err) ~= "string" then error(err) end
-- error("\0"..err, 0) -- The 0 tells our own error handler not to print the traceback.
-- end
local function errorfLine(s, ...)
errorf(0, (current_parsingAndMeta_isProcessing and "\0" or "")..s, ...) -- The \0 tells our own error handler not to print the traceback.
end
-- errorOnLine( path, lineNumber, agent=nil, s, ... )
local function errorOnLine(path, ln, agent, s, ...)
s = F(s, ...)
if agent then
errorfLine("%s:%d: [%s] %s", path, ln, agent, s)
else
errorfLine("%s:%d: %s", path, ln, s)
end
end
local errorInFile, runtimeErrorInFile
do
local function findStartOfLine(s, pos, canBeEmpty)
while pos > 1 do
if s:byte(pos-1) == 10--[[\n]] and (canBeEmpty or s:byte(pos) ~= 10--[[\n]]) then break end
pos = pos - 1
end
return math.max(pos, 1)
end
local function findEndOfLine(s, pos)
while pos < #s do
if s:byte(pos+1) == 10--[[\n]] then break end
pos = pos + 1
end
return math.min(pos, #s)
end
local function _errorInFile(level, contents, path, pos, agent, s, ...)
s = F(s, ...)
pos = math.min(math.max(pos, 1), #contents+1)
local ln = getLineNumber(contents, pos)
local lineStart = findStartOfLine(contents, pos, true)
local lineEnd = findEndOfLine (contents, pos-1)
local linePre1Start = findStartOfLine(contents, lineStart-1, false)
local linePre1End = findEndOfLine (contents, linePre1Start-1)
local linePre2Start = findStartOfLine(contents, linePre1Start-1, false)
local linePre2End = findEndOfLine (contents, linePre2Start-1)
-- printfError("pos %d | lines %d..%d, %d..%d, %d..%d", pos, linePre2Start,linePre2End+1, linePre1Start,linePre1End+1, lineStart,lineEnd+1) -- DEBUG
errorOnLine(path, ln, agent, "%s\n>\n%s%s%s>-%s^%s",
s,
(linePre2Start < linePre1Start and linePre2Start <= linePre2End) and F("> %s\n", (contents:sub(linePre2Start, linePre2End):gsub("\t", " "))) or "",
(linePre1Start < lineStart and linePre1Start <= linePre1End) and F("> %s\n", (contents:sub(linePre1Start, linePre1End):gsub("\t", " "))) or "",
( lineStart <= lineEnd ) and F("> %s\n", (contents:sub(lineStart, lineEnd ):gsub("\t", " "))) or ">\n",
("-"):rep(pos - lineStart + 3*countSubString(contents, lineStart, lineEnd, "\t", true)),
(level and "\n"..formatTraceback(1+level) or "")
)
end
-- errorInFile( contents, path, pos, agent, s, ... )
--[[local]] function errorInFile(...)
_errorInFile(nil, ...)
end
-- runtimeErrorInFile( level, contents, path, pos, agent, s, ... )
--[[local]] function runtimeErrorInFile(level, ...)
_errorInFile(1+level, ...)
end
end
-- errorAtToken( token, position=token.position, agent, s, ... )
local function errorAtToken(tok, pos, agent, s, ...)
-- printErrorTraceback("errorAtToken", 2) -- DEBUG
errorInFile(current_parsingAndMeta_resourceCache[tok.file], tok.file, (pos or tok.position), agent, s, ...)
end
-- errorAfterToken( token, agent, s, ... )
local function errorAfterToken(tok, agent, s, ...)
-- printErrorTraceback("errorAfterToken", 2) -- DEBUG
errorInFile(current_parsingAndMeta_resourceCache[tok.file], tok.file, tok.position+#tok.representation, agent, s, ...)
end
-- runtimeErrorAtToken( level, token, position=token.position, agent, s, ... )
local function runtimeErrorAtToken(level, tok, pos, agent, s, ...)
-- printErrorTraceback("runtimeErrorAtToken", 2) -- DEBUG
runtimeErrorInFile(1+level, current_parsingAndMeta_resourceCache[tok.file], tok.file, (pos or tok.position), agent, s, ...)
end
-- internalError( [ message|value ] )
local function internalError(message)
message = message and " ("..tostring(message)..")" or ""
error("Internal error."..message, 2)
end
local function cleanError(err)
if type(err) == "string" then
err = err:gsub("%z", "")
end
return err
end
local function formatCodeForShortMessage(lua)
lua = lua:gsub("^%s+", ""):gsub("%s+$", ""):gsub("%s+", " ")
if #lua > MAX_CODE_LENGTH_IN_MESSAGES then
lua = lua:sub(1, MAX_CODE_LENGTH_IN_MESSAGES/2) .. "..." .. lua:sub(-MAX_CODE_LENGTH_IN_MESSAGES/2)
end
return lua
end
local ERROR_UNFINISHED_STRINGLIKE = 1
local function parseStringlikeToken(s, ptr)
local reprStart = ptr
local reprEnd
local valueStart
local valueEnd
local longEqualSigns = s:match("^%[(=*)%[", ptr)
local isLong = longEqualSigns ~= nil
-- Single line.
if not isLong then
valueStart = ptr
local i = s:find("\n", ptr, true)
if not i then
reprEnd = #s
valueEnd = #s
ptr = reprEnd + 1
else
reprEnd = i
valueEnd = i - 1
ptr = reprEnd + 1
end
-- Multiline.
else
ptr = ptr + 1 + #longEqualSigns + 1
valueStart = ptr
local i1, i2 = s:find("]"..longEqualSigns.."]", ptr, true)
if not i1 then
return nil, ERROR_UNFINISHED_STRINGLIKE
end
reprEnd = i2
valueEnd = i1 - 1
ptr = reprEnd + 1
end
local repr = s:sub(reprStart, reprEnd)
local v = s:sub(valueStart, valueEnd)
local tok = {type="stringlike", representation=repr, value=v, long=isLong}
return tok, ptr
end
local NUM_HEX_FRAC_EXP = ("^( 0[Xx] (%x*) %.(%x+) [Pp]([-+]?%x+) )"):gsub(" +", "")
local NUM_HEX_FRAC = ("^( 0[Xx] (%x*) %.(%x+) )"):gsub(" +", "")
local NUM_HEX_EXP = ("^( 0[Xx] (%x+) %.? [Pp]([-+]?%x+) )"):gsub(" +", "")
local NUM_HEX = ("^( 0[Xx] %x+ %.? )"):gsub(" +", "")
local NUM_DEC_FRAC_EXP = ("^( %d* %.%d+ [Ee][-+]?%d+ )"):gsub(" +", "")
local NUM_DEC_FRAC = ("^( %d* %.%d+ )"):gsub(" +", "")
local NUM_DEC_EXP = ("^( %d+ %.? [Ee][-+]?%d+ )"):gsub(" +", "")
local NUM_DEC = ("^( %d+ %.? )"):gsub(" +", "")
-- tokens = _tokenize( luaString, path, allowPreprocessorTokens, allowBacktickStrings, allowJitSyntax )
local function _tokenize(s, path, allowPpTokens, allowBacktickStrings, allowJitSyntax)
s = s:gsub("\r", "") -- Normalize line breaks. (Assume the input is either "\n" or "\r\n".)
local tokens = {}
local ptr = 1
local ln = 1
while ptr <= #s do
local tok
local tokenPos = ptr
-- Whitespace.
if s:find("^%s", ptr) then
local i1, i2, whitespace = s:find("^(%s+)", ptr)
ptr = i2+1
tok = {type="whitespace", representation=whitespace, value=whitespace}
-- Identifier/keyword.
elseif s:find("^[%a_]", ptr) then
local i1, i2, word = s:find("^([%a_][%w_]*)", ptr)
ptr = i2+1
if KEYWORDS[word] then
tok = {type="keyword", representation=word, value=word}
else
tok = {type="identifier", representation=word, value=word}
end
-- Number (binary).
elseif s:find("^0b", ptr) then
if not allowJitSyntax then
errorInFile(s, path, ptr, "Tokenizer", "Encountered binary numeral. (Feature not enabled.)")
end
local i1, i2, numStr = s:find("^(..[01]+)", ptr)
-- @Copypaste from below.
if not numStr then
errorInFile(s, path, ptr, "Tokenizer", "Malformed number.")
end
local numStrFallback = numStr
do
if s:find("^[Ii]", i2+1) then -- Imaginary part of complex number.
numStr = s:sub(i1, i2+1)
i2 = i2 + 1
elseif s:find("^[Uu][Ll][Ll]", i2+1) then -- Unsigned 64-bit integer.
numStr = s:sub(i1, i2+3)
i2 = i2 + 3
elseif s:find("^[Ll][Ll]", i2+1) then -- Signed 64-bit integer.
numStr = s:sub(i1, i2+2)
i2 = i2 + 2
end
end
local n = tonumber(numStr) or tonumber(numStrFallback) or tonumber(numStrFallback:sub(3), 2)
if not n then
errorInFile(s, path, ptr, "Tokenizer", "Invalid number.")
end
if s:find("^[%w_]", i2+1) then
-- This is actually not an error in Lua 5.2 and 5.3. Maybe we should issue a warning instead of an error here?
errorInFile(s, path, i2+1, "Tokenizer", "Malformed number.")
end
ptr = i2 + 1
tok = {type="number", representation=numStrFallback, value=n}
-- Number.
elseif s:find("^%.?%d", ptr) then
local pat, maybeInt, lua52Hex, i1, i2, numStr = NUM_HEX_FRAC_EXP, false, true , s:find(NUM_HEX_FRAC_EXP, ptr)
if not i1 then pat, maybeInt, lua52Hex, i1, i2, numStr = NUM_HEX_FRAC , false, true , s:find(NUM_HEX_FRAC , ptr)
if not i1 then pat, maybeInt, lua52Hex, i1, i2, numStr = NUM_HEX_EXP , false, true , s:find(NUM_HEX_EXP , ptr)
if not i1 then pat, maybeInt, lua52Hex, i1, i2, numStr = NUM_HEX , true , false, s:find(NUM_HEX , ptr)
if not i1 then pat, maybeInt, lua52Hex, i1, i2, numStr = NUM_DEC_FRAC_EXP, false, false, s:find(NUM_DEC_FRAC_EXP, ptr)
if not i1 then pat, maybeInt, lua52Hex, i1, i2, numStr = NUM_DEC_FRAC , false, false, s:find(NUM_DEC_FRAC , ptr)
if not i1 then pat, maybeInt, lua52Hex, i1, i2, numStr = NUM_DEC_EXP , false, false, s:find(NUM_DEC_EXP , ptr)
if not i1 then pat, maybeInt, lua52Hex, i1, i2, numStr = NUM_DEC , true , false, s:find(NUM_DEC , ptr)
end end end end end end end
if not numStr then
errorInFile(s, path, ptr, "Tokenizer", "Malformed number.")
end
local numStrFallback = numStr
if allowJitSyntax then
if s:find("^[Ii]", i2+1) then -- Imaginary part of complex number.
numStr = s:sub(i1, i2+1)
i2 = i2 + 1
elseif not maybeInt or numStr:find(".", 1, true) then
-- void
elseif s:find("^[Uu][Ll][Ll]", i2+1) then -- Unsigned 64-bit integer.
numStr = s:sub(i1, i2+3)
i2 = i2 + 3
elseif s:find("^[Ll][Ll]", i2+1) then -- Signed 64-bit integer.
numStr = s:sub(i1, i2+2)
i2 = i2 + 2
end
end
local n = tonumber(numStr) or tonumber(numStrFallback)
-- Support hexadecimal floats in Lua 5.1.
if not n and lua52Hex then
-- Note: We know we're not running LuaJIT here as it supports hexadecimal floats, thus we use numStrFallback instead of numStr.
local _, intStr, fracStr, expStr
if pat == NUM_HEX_FRAC_EXP then _, intStr, fracStr, expStr = numStrFallback:match(NUM_HEX_FRAC_EXP)
elseif pat == NUM_HEX_FRAC then _, intStr, fracStr = numStrFallback:match(NUM_HEX_FRAC) ; expStr = "0"
elseif pat == NUM_HEX_EXP then _, intStr, expStr = numStrFallback:match(NUM_HEX_EXP) ; fracStr = ""
else internalError() end
n = tonumber(intStr, 16) or 0 -- intStr may be "".
local fracValue = 1
for i = 1, #fracStr do
fracValue = fracValue/16
n = n+tonumber(fracStr:sub(i, i), 16)*fracValue
end
n = n*2^expStr:gsub("^+", "")
end
if not n then
errorInFile(s, path, ptr, "Tokenizer", "Invalid number.")
end
if s:find("^[%w_]", i2+1) then
-- This is actually not an error in Lua 5.2 and 5.3. Maybe we should issue a warning instead of an error here?
errorInFile(s, path, i2+1, "Tokenizer", "Malformed number.")
end
ptr = i2+1
tok = {type="number", representation=numStrFallback, value=n}
-- Comment.
elseif s:find("^%-%-", ptr) then
local reprStart = ptr
ptr = ptr+2
tok, ptr = parseStringlikeToken(s, ptr)
if not tok then
local errCode = ptr
if errCode == ERROR_UNFINISHED_STRINGLIKE then
errorInFile(s, path, reprStart, "Tokenizer", "Unfinished long comment.")
else
errorInFile(s, path, reprStart, "Tokenizer", "Invalid comment.")
end
end
if tok.long then
-- Check for nesting of [[...]], which is deprecated in Lua.
local chunk, err = loadLuaString("--"..tok.representation, "@", nil)
if not chunk then
local lnInString, luaErr = err:match'^:(%d+): (.*)'
if luaErr then
errorOnLine(path, getLineNumber(s, reprStart)+tonumber(lnInString)-1, "Tokenizer", "Malformed long comment. (%s)", luaErr)
else
errorInFile(s, path, reprStart, "Tokenizer", "Malformed long comment.")
end
end
end
tok.type = "comment"
tok.representation = s:sub(reprStart, ptr-1)
-- String (short).
elseif s:find([=[^["']]=], ptr) then
local reprStart = ptr
local reprEnd
local quoteChar = s:sub(ptr, ptr)
ptr = ptr+1
local valueStart = ptr
local valueEnd
while true do
local c = s:sub(ptr, ptr)
if c == "" then
errorInFile(s, path, reprStart, "Tokenizer", "Unfinished string.")
elseif c == quoteChar then
reprEnd = ptr
valueEnd = ptr-1
ptr = reprEnd+1
break
elseif c == "\\" then
-- Note: We don't have to look for multiple characters after
-- the escape, like \nnn - this algorithm works anyway.
if ptr+1 > #s then
errorInFile(s, path, reprStart, "Tokenizer", "Unfinished string after escape.")
end
ptr = ptr+2
elseif c == "\n" then
-- Can't have unescaped newlines. Lua, this is a silly rule! @Ugh
errorInFile(s, path, ptr, "Tokenizer", "Newlines must be escaped in strings.")
else
ptr = ptr+1
end
end
local repr = s:sub(reprStart, reprEnd)
local valueChunk = loadLuaString("return"..repr, nil, nil)
if not valueChunk then
errorInFile(s, path, reprStart, "Tokenizer", "Malformed string.")
end
local v = valueChunk()
assert(type(v) == "string")
tok = {type="string", representation=repr, value=valueChunk(), long=false}
-- Long string.
elseif s:find("^%[=*%[", ptr) then
local reprStart = ptr
tok, ptr = parseStringlikeToken(s, ptr)
if not tok then
local errCode = ptr
if errCode == ERROR_UNFINISHED_STRINGLIKE then
errorInFile(s, path, reprStart, "Tokenizer", "Unfinished long string.")
else
errorInFile(s, path, reprStart, "Tokenizer", "Invalid long string.")
end
end
-- Check for nesting of [[...]], which is deprecated in Lua.
local valueChunk, err = loadLuaString("return"..tok.representation, "@", nil)
if not valueChunk then
local lnInString, luaErr = err:match'^:(%d+): (.*)'
if luaErr then
errorOnLine(path, getLineNumber(s, reprStart)+tonumber(lnInString)-1, "Tokenizer", "Malformed long string. (%s)", luaErr)
else
errorInFile(s, path, reprStart, "Tokenizer", "Malformed long string.")
end
end
local v = valueChunk()
assert(type(v) == "string")
tok.type = "string"
tok.value = v
-- Backtick string.
elseif s:find("^`", ptr) then
if not allowBacktickStrings then
errorInFile(s, path, ptr, "Tokenizer", "Encountered backtick string. (Feature not enabled.)")
end
local i1, i2, repr, v = s:find("^(`([^`]*)`)", ptr)
if not i2 then
errorInFile(s, path, ptr, "Tokenizer", "Unfinished backtick string.")
end
ptr = i2+1
tok = {type="string", representation=repr, value=v, long=false}
-- Punctuation etc.
elseif s:find("^%.%.%.", ptr) then -- 3
local repr = s:sub(ptr, ptr+2)
tok = {type="punctuation", representation=repr, value=repr}
ptr = ptr+#repr
elseif s:find("^%.%.", ptr) or s:find("^[=~<>]=", ptr) or s:find("^::", ptr) or s:find("^//", ptr) or s:find("^<<", ptr) or s:find("^>>", ptr) then -- 2
local repr = s:sub(ptr, ptr+1)
tok = {type="punctuation", representation=repr, value=repr}
ptr = ptr+#repr
elseif s:find("^[+%-*/%%^#<>=(){}[%];:,.&|~]", ptr) then -- 1
local repr = s:sub(ptr, ptr)
tok = {type="punctuation", representation=repr, value=repr}
ptr = ptr+#repr
-- Preprocessor entry.
elseif s:find("^!", ptr) then
if not allowPpTokens then
errorInFile(s, path, ptr, "Tokenizer", "Encountered preprocessor entry. (Feature not enabled.)")
end
local double = s:find("^!", ptr+1) ~= nil
local repr = s:sub(ptr, ptr+(double and 1 or 0))
tok = {type="pp_entry", representation=repr, value=repr, double=double}
ptr = ptr+#repr
-- Preprocessor keyword.
elseif s:find("^@", ptr) then
if not allowPpTokens then
errorInFile(s, path, ptr, "Tokenizer", "Encountered preprocessor keyword. (Feature not enabled.)")
end
if s:find("^@@", ptr) then
ptr = ptr+2
tok = {type="pp_keyword", representation="@@", value="insert"}
else
local i1, i2, repr, word = s:find("^(@([%a_][%w_]*))", ptr)
if not i1 then
errorInFile(s, path, ptr+1, "Tokenizer", "Expected an identifier.")
elseif not PREPROCESSOR_KEYWORDS[word] then
errorInFile(s, path, ptr+1, "Tokenizer", "Invalid preprocessor keyword '%s'.", word)
end
ptr = i2+1
tok = {type="pp_keyword", representation=repr, value=word}
end
-- Preprocessor symbol.
elseif s:find("^%$", ptr) then
if not allowPpTokens then
errorInFile(s, path, ptr, "Tokenizer", "Encountered preprocessor symbol. (Feature not enabled.)")
end
local i1, i2, repr, word = s:find("^(%$([%a_][%w_]*))", ptr)
if not i1 then
errorInFile(s, path, ptr+1, "Tokenizer", "Expected an identifier.")
elseif KEYWORDS[word] then
errorInFile(s, path, ptr+1, "Tokenizer", "Invalid preprocessor symbol '%s'. (Must not be a Lua keyword.)", word)
end
ptr = i2+1
tok = {type="pp_symbol", representation=repr, value=word}
else
errorInFile(s, path, ptr, "Tokenizer", "Unknown character.")
end
tok.line = ln
tok.position = tokenPos
tok.file = path
ln = ln+countString(tok.representation, "\n", true)
tok.lineEnd = ln
tableInsert(tokens, tok)
-- print(#tokens, tok.type, tok.representation) -- DEBUG
end
return tokens
end
-- luaString = _concatTokens( tokens, lastLn=nil, addLineNumbers, fromIndex=1, toIndex=#tokens )
local function _concatTokens(tokens, lastLn, addLineNumbers, i1, i2)
local parts = {}
if addLineNumbers then
for i = (i1 or 1), (i2 or #tokens) do
local tok = tokens[i]
lastLn = maybeOutputLineNumber(parts, tok, lastLn)
tableInsert(parts, tok.representation)
end
else
for i = (i1 or 1), (i2 or #tokens) do
tableInsert(parts, tokens[i].representation)
end
end
return table.concat(parts)
end
local function insertTokenRepresentations(parts, tokens, i1, i2)
for i = i1, i2 do
tableInsert(parts, tokens[i].representation)
end
end
local function readFile(path, isTextFile)
assertarg(1, path, "string")
assertarg(2, isTextFile, "boolean","nil")
local file, err = io.open(path, "r"..(isTextFile and "" or "b"))
if not file then return nil, err end
local contents = file:read"*a"
file:close()
return contents
end
-- success, error = writeFile( path, [ isTextFile=false, ] contents )
local function writeFile(path, isTextFile, contents)
assertarg(1, path, "string")
if type(isTextFile) == "boolean" then
assertarg(3, contents, "string")
else
isTextFile, contents = false, isTextFile
assertarg(2, contents, "string")
end
local file, err = io.open(path, "w"..(isTextFile and "" or "b"))
if not file then return false, err end
file:write(contents)
file:close()
return true
end
local function fileExists(path)
assertarg(1, path, "string")
local file = io.open(path, "r")
if not file then return false end
file:close()
return true
end
-- assertarg( argumentNumber, value, expectedValueType1, ... )
--[[local]] function assertarg(n, v, ...)
local vType = type(v)
for i = 1, select("#", ...) do
if vType == select(i, ...) then return end
end
local fName = debug.getinfo(2, "n").name
local expects = table.concat({...}, " or ")
if fName == "" then fName = "?" end
errorf(3, "bad argument #%d to '%s' (%s expected, got %s)", n, fName, expects, vType)
end
-- count = countString( haystack, needle [, plain=false ] )
--[[local]] function countString(s, needle, plain)
local count = 0
local i = 0
local _
while true do
_, i = s:find(needle, i+1, plain)
if not i then return count end
count = count+1
end
end
-- count = countSubString( string, startPosition, endPosition, needle [, plain=false ] )
--[[local]] function countSubString(s, pos, posEnd, needle, plain)
local count = 0
while true do
local _, i2 = s:find(needle, pos, plain)
if not i2 or i2 > posEnd then return count end
count = count + 1
pos = i2 + 1
end
end
local getfenv = getfenv or function(f) -- Assume Lua is version 5.2+ if getfenv() doesn't exist.
f = f or 1