forked from simplemachines-italy/Alcor6L
-
Notifications
You must be signed in to change notification settings - Fork 0
/
luasrcdiet.lua
executable file
·3725 lines (3428 loc) · 130 KB
/
luasrcdiet.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
#!/usr/bin/env lua
package.preload['llex'] = (function (...)
--[[--------------------------------------------------------------------
llex.lua: Lua 5.1 lexical analyzer in Lua
This file is part of LuaSrcDiet, based on Yueliang material.
Copyright (c) 2008 Kein-Hong Man <khman@users.sf.net>
The COPYRIGHT file describes the conditions
under which this software may be distributed.
See the ChangeLog for more information.
----------------------------------------------------------------------]]
--[[--------------------------------------------------------------------
-- NOTES:
-- * This is a version of the native 5.1.x lexer from Yueliang 0.4.0,
-- with significant modifications to handle LuaSrcDiet's needs:
-- (1) llex.error is an optional error function handler
-- (2) seminfo for strings include their delimiters and no
-- translation operations are performed on them
-- * ADDED shbang handling has been added to support executable scripts
-- * NO localized decimal point replacement magic
-- * NO limit to number of lines
-- * NO support for compatible long strings (LUA_COMPAT_LSTR)
-- * Please read technotes.txt for more technical details.
----------------------------------------------------------------------]]
local base = _G
local string = string
module "llex"
local find = string.find
local match = string.match
local sub = string.sub
----------------------------------------------------------------------
-- initialize keyword list, variables
----------------------------------------------------------------------
local kw = {}
for v in string.gmatch([[
and break do else elseif end false for function if in
local nil not or repeat return then true until while]], "%S+") do
kw[v] = true
end
-- NOTE: see init() for module variables (externally visible):
-- tok, seminfo, tokln
local z, -- source stream
sourceid, -- name of source
I, -- position of lexer
buff, -- buffer for strings
ln -- line number
----------------------------------------------------------------------
-- add information to token listing
----------------------------------------------------------------------
local function addtoken(token, info)
local i = #tok + 1
tok[i] = token
seminfo[i] = info
tokln[i] = ln
end
----------------------------------------------------------------------
-- handles line number incrementation and end-of-line characters
----------------------------------------------------------------------
local function inclinenumber(i, is_tok)
local sub = sub
local old = sub(z, i, i)
i = i + 1 -- skip '\n' or '\r'
local c = sub(z, i, i)
if (c == "\n" or c == "\r") and (c ~= old) then
i = i + 1 -- skip '\n\r' or '\r\n'
old = old..c
end
if is_tok then addtoken("TK_EOL", old) end
ln = ln + 1
I = i
return i
end
----------------------------------------------------------------------
-- initialize lexer for given source _z and source name _sourceid
----------------------------------------------------------------------
function init(_z, _sourceid)
z = _z -- source
sourceid = _sourceid -- name of source
I = 1 -- lexer's position in source
ln = 1 -- line number
tok = {} -- lexed token list*
seminfo = {} -- lexed semantic information list*
tokln = {} -- line numbers for messages*
-- (*) externally visible thru' module
--------------------------------------------------------------------
-- initial processing (shbang handling)
--------------------------------------------------------------------
local p, _, q, r = find(z, "^(#[^\r\n]*)(\r?\n?)")
if p then -- skip first line
I = I + #q
addtoken("TK_COMMENT", q)
if #r > 0 then inclinenumber(I, true) end
end
end
----------------------------------------------------------------------
-- returns a chunk name or id, no truncation for long names
----------------------------------------------------------------------
function chunkid()
if sourceid and match(sourceid, "^[=@]") then
return sub(sourceid, 2) -- remove first char
end
return "[string]"
end
----------------------------------------------------------------------
-- formats error message and throws error
-- * a simplified version, does not report what token was responsible
----------------------------------------------------------------------
function errorline(s, line)
local e = error or base.error
e(string.format("%s:%d: %s", chunkid(), line or ln, s))
end
local errorline = errorline
------------------------------------------------------------------------
-- count separators ("=") in a long string delimiter
------------------------------------------------------------------------
local function skip_sep(i)
local sub = sub
local s = sub(z, i, i)
i = i + 1
local count = #match(z, "=*", i) -- note, take the length
i = i + count
I = i
return (sub(z, i, i) == s) and count or (-count) - 1
end
----------------------------------------------------------------------
-- reads a long string or long comment
----------------------------------------------------------------------
local function read_long_string(is_str, sep)
local i = I + 1 -- skip 2nd '['
local sub = sub
local c = sub(z, i, i)
if c == "\r" or c == "\n" then -- string starts with a newline?
i = inclinenumber(i) -- skip it
end
local j = i
while true do
local p, q, r = find(z, "([\r\n%]])", i) -- (long range)
if not p then
errorline(is_str and "unfinished long string" or
"unfinished long comment")
end
i = p
if r == "]" then -- delimiter test
if skip_sep(i) == sep then
buff = sub(z, buff, I)
I = I + 1 -- skip 2nd ']'
return buff
end
i = I
else -- newline
buff = buff.."\n"
i = inclinenumber(i)
end
end--while
end
----------------------------------------------------------------------
-- reads a string
----------------------------------------------------------------------
local function read_string(del)
local i = I
local find = find
local sub = sub
while true do
local p, q, r = find(z, "([\n\r\\\"\'])", i) -- (long range)
if p then
if r == "\n" or r == "\r" then
errorline("unfinished string")
end
i = p
if r == "\\" then -- handle escapes
i = i + 1
r = sub(z, i, i)
if r == "" then break end -- (EOZ error)
p = find("abfnrtv\n\r", r, 1, true)
------------------------------------------------------
if p then -- special escapes
if p > 7 then
i = inclinenumber(i)
else
i = i + 1
end
------------------------------------------------------
elseif find(r, "%D") then -- other non-digits
i = i + 1
------------------------------------------------------
else -- \xxx sequence
local p, q, s = find(z, "^(%d%d?%d?)", i)
i = q + 1
if s + 1 > 256 then -- UCHAR_MAX
errorline("escape sequence too large")
end
------------------------------------------------------
end--if p
else
i = i + 1
if r == del then -- ending delimiter
I = i
return sub(z, buff, i - 1) -- return string
end
end--if r
else
break -- (error)
end--if p
end--while
errorline("unfinished string")
end
------------------------------------------------------------------------
-- main lexer function
------------------------------------------------------------------------
function llex()
local find = find
local match = match
while true do--outer
local i = I
-- inner loop allows break to be used to nicely section tests
while true do--inner
----------------------------------------------------------------
local p, _, r = find(z, "^([_%a][_%w]*)", i)
if p then
I = i + #r
if kw[r] then
addtoken("TK_KEYWORD", r) -- reserved word (keyword)
else
addtoken("TK_NAME", r) -- identifier
end
break -- (continue)
end
----------------------------------------------------------------
local p, _, r = find(z, "^(%.?)%d", i)
if p then -- numeral
if r == "." then i = i + 1 end
local _, q, r = find(z, "^%d*[%.%d]*([eE]?)", i)
i = q + 1
if #r == 1 then -- optional exponent
if match(z, "^[%+%-]", i) then -- optional sign
i = i + 1
end
end
local _, q = find(z, "^[_%w]*", i)
I = q + 1
local v = sub(z, p, q) -- string equivalent
if not base.tonumber(v) then -- handles hex test also
errorline("malformed number")
end
addtoken("TK_NUMBER", v)
break -- (continue)
end
----------------------------------------------------------------
local p, q, r, t = find(z, "^((%s)[ \t\v\f]*)", i)
if p then
if t == "\n" or t == "\r" then -- newline
inclinenumber(i, true)
else
I = q + 1 -- whitespace
addtoken("TK_SPACE", r)
end
break -- (continue)
end
----------------------------------------------------------------
local r = match(z, "^%p", i)
if r then
buff = i
local p = find("-[\"\'.=<>~", r, 1, true)
if p then
-- two-level if block for punctuation/symbols
--------------------------------------------------------
if p <= 2 then
if p == 1 then -- minus
local c = match(z, "^%-%-(%[?)", i)
if c then
i = i + 2
local sep = -1
if c == "[" then
sep = skip_sep(i)
end
if sep >= 0 then -- long comment
addtoken("TK_LCOMMENT", read_long_string(false, sep))
else -- short comment
I = find(z, "[\n\r]", i) or (#z + 1)
addtoken("TK_COMMENT", sub(z, buff, I - 1))
end
break -- (continue)
end
-- (fall through for "-")
else -- [ or long string
local sep = skip_sep(i)
if sep >= 0 then
addtoken("TK_LSTRING", read_long_string(true, sep))
elseif sep == -1 then
addtoken("TK_OP", "[")
else
errorline("invalid long string delimiter")
end
break -- (continue)
end
--------------------------------------------------------
elseif p <= 5 then
if p < 5 then -- strings
I = i + 1
addtoken("TK_STRING", read_string(r))
break -- (continue)
end
r = match(z, "^%.%.?%.?", i) -- .|..|... dots
-- (fall through)
--------------------------------------------------------
else -- relational
r = match(z, "^%p=?", i)
-- (fall through)
end
end
I = i + #r
addtoken("TK_OP", r) -- for other symbols, fall through
break -- (continue)
end
----------------------------------------------------------------
local r = sub(z, i, i)
if r ~= "" then
I = i + 1
addtoken("TK_OP", r) -- other single-char tokens
break
end
addtoken("TK_EOS", "") -- end of stream,
return -- exit here
----------------------------------------------------------------
end--while inner
end--while outer
end
return base.getfenv()
end)
package.preload['lparser'] = (function (...)
--[[--------------------------------------------------------------------
lparser.lua: Lua 5.1 parser in Lua
This file is part of LuaSrcDiet, based on Yueliang material.
Copyright (c) 2008 Kein-Hong Man <khman@users.sf.net>
The COPYRIGHT file describes the conditions
under which this software may be distributed.
See the ChangeLog for more information.
----------------------------------------------------------------------]]
--[[--------------------------------------------------------------------
-- NOTES:
-- * This is a version of the native 5.1.x parser from Yueliang 0.4.0,
-- with significant modifications to handle LuaSrcDiet's needs:
-- (1) needs pre-built token tables instead of a module.method
-- (2) lparser.error is an optional error handler (from llex)
-- (3) not full parsing, currently fakes raw/unlexed constants
-- (4) parser() returns globalinfo, localinfo tables
-- * Please read technotes.txt for more technical details.
-- * NO support for 'arg' vararg functions (LUA_COMPAT_VARARG)
-- * A lot of the parser is unused, but might later be useful for
-- full-on parsing and analysis for a few measly bytes saved.
----------------------------------------------------------------------]]
local base = _G
local string = string
module "lparser"
local _G = base.getfenv()
--[[--------------------------------------------------------------------
-- variable and data structure initialization
----------------------------------------------------------------------]]
----------------------------------------------------------------------
-- initialization: main variables
----------------------------------------------------------------------
local toklist, -- grammar-only token tables (token table,
seminfolist, -- semantic information table, line number
toklnlist, -- table, cross-reference table)
xreflist,
tpos, -- token position
line, -- start line # for error messages
lastln, -- last line # for ambiguous syntax chk
tok, seminfo, ln, xref, -- token, semantic info, line
nameref, -- proper position of <name> token
fs, -- current function state
top_fs, -- top-level function state
globalinfo, -- global variable information table
globallookup, -- global variable name lookup table
localinfo, -- local variable information table
ilocalinfo, -- inactive locals (prior to activation)
ilocalrefs -- corresponding references to activate
-- forward references for local functions
local explist1, expr, block, exp1, body, chunk
----------------------------------------------------------------------
-- initialization: data structures
----------------------------------------------------------------------
local gmatch = string.gmatch
local block_follow = {} -- lookahead check in chunk(), returnstat()
for v in gmatch("else elseif end until <eof>", "%S+") do
block_follow[v] = true
end
local stat_call = {} -- lookup for calls in stat()
for v in gmatch("if while do for repeat function local return break", "%S+") do
stat_call[v] = v.."_stat"
end
local binopr_left = {} -- binary operators, left priority
local binopr_right = {} -- binary operators, right priority
for op, lt, rt in gmatch([[
{+ 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}
]], "{(%S+)%s(%d+)%s(%d+)}") do
binopr_left[op] = lt + 0
binopr_right[op] = rt + 0
end
local unopr = { ["not"] = true, ["-"] = true,
["#"] = true, } -- unary operators
local UNARY_PRIORITY = 8 -- priority for unary operators
--[[--------------------------------------------------------------------
-- support functions
----------------------------------------------------------------------]]
----------------------------------------------------------------------
-- formats error message and throws error (duplicated from llex)
-- * a simplified version, does not report what token was responsible
----------------------------------------------------------------------
local function errorline(s, line)
local e = error or base.error
e(string.format("(source):%d: %s", line or ln, s))
end
----------------------------------------------------------------------
-- handles incoming token, semantic information pairs
-- * NOTE: 'nextt' is named 'next' originally
----------------------------------------------------------------------
-- reads in next token
local function nextt()
lastln = toklnlist[tpos]
tok, seminfo, ln, xref
= toklist[tpos], seminfolist[tpos], toklnlist[tpos], xreflist[tpos]
tpos = tpos + 1
end
-- peek at next token (single lookahead for table constructor)
local function lookahead()
return toklist[tpos]
end
----------------------------------------------------------------------
-- throws a syntax error, or if token expected is not there
----------------------------------------------------------------------
local function syntaxerror(msg)
local tok = tok
if tok ~= "<number>" and tok ~= "<string>" then
if tok == "<name>" then tok = seminfo end
tok = "'"..tok.."'"
end
errorline(msg.." near "..tok)
end
local function error_expected(token)
syntaxerror("'"..token.."' expected")
end
----------------------------------------------------------------------
-- tests for a token, returns outcome
-- * return value changed to boolean
----------------------------------------------------------------------
local function testnext(c)
if tok == c then nextt(); return true end
end
----------------------------------------------------------------------
-- check for existence of a token, throws error if not found
----------------------------------------------------------------------
local function check(c)
if tok ~= c then error_expected(c) end
end
----------------------------------------------------------------------
-- verify existence of a token, then skip it
----------------------------------------------------------------------
local function checknext(c)
check(c); nextt()
end
----------------------------------------------------------------------
-- throws error if condition not matched
----------------------------------------------------------------------
local function check_condition(c, msg)
if not c then syntaxerror(msg) end
end
----------------------------------------------------------------------
-- verifies token conditions are met or else throw error
----------------------------------------------------------------------
local function check_match(what, who, where)
if not testnext(what) then
if where == ln then
error_expected(what)
else
syntaxerror("'"..what.."' expected (to close '"..who.."' at line "..where..")")
end
end
end
----------------------------------------------------------------------
-- expect that token is a name, return the name
----------------------------------------------------------------------
local function str_checkname()
check("<name>")
local ts = seminfo
nameref = xref
nextt()
return ts
end
----------------------------------------------------------------------
-- adds given string s in string pool, sets e as VK
----------------------------------------------------------------------
local function codestring(e, s)
e.k = "VK"
end
----------------------------------------------------------------------
-- consume a name token, adds it to string pool
----------------------------------------------------------------------
local function checkname(e)
codestring(e, str_checkname())
end
--[[--------------------------------------------------------------------
-- variable (global|local|upvalue) handling
-- * to track locals and globals, we can extend Yueliang's minimal
-- variable management code with little trouble
-- * entry point is singlevar() for variable lookups
-- * lookup tables (bl.locallist) are maintained awkwardly in the basic
-- block data structures, PLUS the function data structure (this is
-- an inelegant hack, since bl is nil for the top level of a function)
----------------------------------------------------------------------]]
----------------------------------------------------------------------
-- register a local variable, create local variable object, set in
-- to-activate variable list
-- * used in new_localvarliteral(), parlist(), fornum(), forlist(),
-- localfunc(), localstat()
----------------------------------------------------------------------
local function new_localvar(name, special)
local bl = fs.bl
local locallist
-- locate locallist in current block object or function root object
if bl then
locallist = bl.locallist
else
locallist = fs.locallist
end
-- build local variable information object and set localinfo
local id = #localinfo + 1
localinfo[id] = { -- new local variable object
name = name, -- local variable name
xref = { nameref }, -- xref, first value is declaration
decl = nameref, -- location of declaration, = xref[1]
}
if special then -- "self" must be not be changed
localinfo[id].isself = true
end
-- this can override a local with the same name in the same scope
-- but first, keep it inactive until it gets activated
local i = #ilocalinfo + 1
ilocalinfo[i] = id
ilocalrefs[i] = locallist
end
----------------------------------------------------------------------
-- actually activate the variables so that they are visible
-- * remember Lua semantics, e.g. RHS is evaluated first, then LHS
-- * used in parlist(), forbody(), localfunc(), localstat(), body()
----------------------------------------------------------------------
local function adjustlocalvars(nvars)
local sz = #ilocalinfo
-- i goes from left to right, in order of local allocation, because
-- of something like: local a,a,a = 1,2,3 which gives a = 3
while nvars > 0 do
nvars = nvars - 1
local i = sz - nvars
local id = ilocalinfo[i] -- local's id
local obj = localinfo[id]
local name = obj.name -- name of local
obj.act = xref -- set activation location
ilocalinfo[i] = nil
local locallist = ilocalrefs[i] -- ref to lookup table to update
ilocalrefs[i] = nil
local existing = locallist[name] -- if existing, remove old first!
if existing then -- do not overlap, set special
obj = localinfo[existing] -- form of rem, as -id
obj.rem = -id
end
locallist[name] = id -- activate, now visible to Lua
end
end
----------------------------------------------------------------------
-- remove (deactivate) variables in current scope (before scope exits)
-- * zap entire locallist tables since we are not allocating registers
-- * used in leaveblock(), close_func()
----------------------------------------------------------------------
local function removevars()
local bl = fs.bl
local locallist
-- locate locallist in current block object or function root object
if bl then
locallist = bl.locallist
else
locallist = fs.locallist
end
-- enumerate the local list at current scope and deactivate 'em
for name, id in base.pairs(locallist) do
local obj = localinfo[id]
obj.rem = xref -- set deactivation location
end
end
----------------------------------------------------------------------
-- creates a new local variable given a name
-- * skips internal locals (those starting with '('), so internal
-- locals never needs a corresponding adjustlocalvars() call
-- * special is true for "self" which must not be optimized
-- * used in fornum(), forlist(), parlist(), body()
----------------------------------------------------------------------
local function new_localvarliteral(name, special)
if string.sub(name, 1, 1) == "(" then -- can skip internal locals
return
end
new_localvar(name, special)
end
----------------------------------------------------------------------
-- search the local variable namespace of the given fs for a match
-- * returns localinfo index
-- * used only in singlevaraux()
----------------------------------------------------------------------
local function searchvar(fs, n)
local bl = fs.bl
local locallist
if bl then
locallist = bl.locallist
while locallist do
if locallist[n] then return locallist[n] end -- found
bl = bl.prev
locallist = bl and bl.locallist
end
end
locallist = fs.locallist
return locallist[n] or -1 -- found or not found (-1)
end
----------------------------------------------------------------------
-- handle locals, globals and upvalues and related processing
-- * search mechanism is recursive, calls itself to search parents
-- * used only in singlevar()
----------------------------------------------------------------------
local function singlevaraux(fs, n, var)
if fs == nil then -- no more levels?
var.k = "VGLOBAL" -- default is global variable
return "VGLOBAL"
else
local v = searchvar(fs, n) -- look up at current level
if v >= 0 then
var.k = "VLOCAL"
var.id = v
-- codegen may need to deal with upvalue here
return "VLOCAL"
else -- not found at current level; try upper one
if singlevaraux(fs.prev, n, var) == "VGLOBAL" then
return "VGLOBAL"
end
-- else was LOCAL or UPVAL, handle here
var.k = "VUPVAL" -- upvalue in this level
return "VUPVAL"
end--if v
end--if fs
end
----------------------------------------------------------------------
-- consume a name token, creates a variable (global|local|upvalue)
-- * used in prefixexp(), funcname()
----------------------------------------------------------------------
local function singlevar(v)
local name = str_checkname()
singlevaraux(fs, name, v)
------------------------------------------------------------------
-- variable tracking
------------------------------------------------------------------
if v.k == "VGLOBAL" then
-- if global being accessed, keep track of it by creating an object
local id = globallookup[name]
if not id then
id = #globalinfo + 1
globalinfo[id] = { -- new global variable object
name = name, -- global variable name
xref = { nameref }, -- xref, first value is declaration
}
globallookup[name] = id -- remember it
else
local obj = globalinfo[id].xref
obj[#obj + 1] = nameref -- add xref
end
else
-- local/upvalue is being accessed, keep track of it
local id = v.id
local obj = localinfo[id].xref
obj[#obj + 1] = nameref -- add xref
end
end
--[[--------------------------------------------------------------------
-- state management functions with open/close pairs
----------------------------------------------------------------------]]
----------------------------------------------------------------------
-- enters a code unit, initializes elements
----------------------------------------------------------------------
local function enterblock(isbreakable)
local bl = {} -- per-block state
bl.isbreakable = isbreakable
bl.prev = fs.bl
bl.locallist = {}
fs.bl = bl
end
----------------------------------------------------------------------
-- leaves a code unit, close any upvalues
----------------------------------------------------------------------
local function leaveblock()
local bl = fs.bl
removevars()
fs.bl = bl.prev
end
----------------------------------------------------------------------
-- opening of a function
-- * top_fs is only for anchoring the top fs, so that parser() can
-- return it to the caller function along with useful output
-- * used in parser() and body()
----------------------------------------------------------------------
local function open_func()
local new_fs -- per-function state
if not fs then -- top_fs is created early
new_fs = top_fs
else
new_fs = {}
end
new_fs.prev = fs -- linked list of function states
new_fs.bl = nil
new_fs.locallist = {}
fs = new_fs
end
----------------------------------------------------------------------
-- closing of a function
-- * used in parser() and body()
----------------------------------------------------------------------
local function close_func()
removevars()
fs = fs.prev
end
--[[--------------------------------------------------------------------
-- other parsing functions
-- * for table constructor, parameter list, argument list
----------------------------------------------------------------------]]
----------------------------------------------------------------------
-- parse a function name suffix, for function call specifications
-- * used in primaryexp(), funcname()
----------------------------------------------------------------------
local function field(v)
-- field -> ['.' | ':'] NAME
local key = {}
nextt() -- skip the dot or colon
checkname(key)
v.k = "VINDEXED"
end
----------------------------------------------------------------------
-- parse a table indexing suffix, for constructors, expressions
-- * used in recfield(), primaryexp()
----------------------------------------------------------------------
local function yindex(v)
-- index -> '[' expr ']'
nextt() -- skip the '['
expr(v)
checknext("]")
end
----------------------------------------------------------------------
-- parse a table record (hash) field
-- * used in constructor()
----------------------------------------------------------------------
local function recfield(cc)
-- recfield -> (NAME | '['exp1']') = exp1
local key, val = {}, {}
if tok == "<name>" then
checkname(key)
else-- tok == '['
yindex(key)
end
checknext("=")
expr(val)
end
----------------------------------------------------------------------
-- emit a set list instruction if enough elements (LFIELDS_PER_FLUSH)
-- * note: retained in this skeleton because it modifies cc.v.k
-- * used in constructor()
----------------------------------------------------------------------
local function closelistfield(cc)
if cc.v.k == "VVOID" then return end -- there is no list item
cc.v.k = "VVOID"
end
----------------------------------------------------------------------
-- parse a table list (array) field
-- * used in constructor()
----------------------------------------------------------------------
local function listfield(cc)
expr(cc.v)
end
----------------------------------------------------------------------
-- parse a table constructor
-- * used in funcargs(), simpleexp()
----------------------------------------------------------------------
local function constructor(t)
-- constructor -> '{' [ field { fieldsep field } [ fieldsep ] ] '}'
-- field -> recfield | listfield
-- fieldsep -> ',' | ';'
local line = ln
local cc = {}
cc.v = {}
cc.t = t
t.k = "VRELOCABLE"
cc.v.k = "VVOID"
checknext("{")
repeat
if tok == "}" then break end
-- closelistfield(cc) here
local c = tok
if c == "<name>" then -- may be listfields or recfields
if lookahead() ~= "=" then -- look ahead: expression?
listfield(cc)
else
recfield(cc)
end
elseif c == "[" then -- constructor_item -> recfield
recfield(cc)
else -- constructor_part -> listfield
listfield(cc)
end
until not testnext(",") and not testnext(";")
check_match("}", "{", line)
-- lastlistfield(cc) here
end
----------------------------------------------------------------------
-- parse the arguments (parameters) of a function declaration
-- * used in body()
----------------------------------------------------------------------
local function parlist()
-- parlist -> [ param { ',' param } ]
local nparams = 0
if tok ~= ")" then -- is 'parlist' not empty?
repeat
local c = tok
if c == "<name>" then -- param -> NAME
new_localvar(str_checkname())
nparams = nparams + 1
elseif c == "..." then
nextt()
fs.is_vararg = true
else
syntaxerror("<name> or '...' expected")
end
until fs.is_vararg or not testnext(",")
end--if
adjustlocalvars(nparams)
end
----------------------------------------------------------------------
-- parse the parameters of a function call
-- * contrast with parlist(), used in function declarations
-- * used in primaryexp()
----------------------------------------------------------------------
local function funcargs(f)
local args = {}
local line = ln
local c = tok
if c == "(" then -- funcargs -> '(' [ explist1 ] ')'
if line ~= lastln then
syntaxerror("ambiguous syntax (function call x new statement)")
end
nextt()
if tok == ")" then -- arg list is empty?
args.k = "VVOID"
else
explist1(args)
end
check_match(")", "(", line)
elseif c == "{" then -- funcargs -> constructor
constructor(args)
elseif c == "<string>" then -- funcargs -> STRING
codestring(args, seminfo)
nextt() -- must use 'seminfo' before 'next'
else
syntaxerror("function arguments expected")
return
end--if c
f.k = "VCALL"
end
--[[--------------------------------------------------------------------
-- mostly expression functions
----------------------------------------------------------------------]]
----------------------------------------------------------------------
-- parses an expression in parentheses or a single variable
-- * used in primaryexp()
----------------------------------------------------------------------
local function prefixexp(v)
-- prefixexp -> NAME | '(' expr ')'
local c = tok
if c == "(" then