-
Notifications
You must be signed in to change notification settings - Fork 0
/
vmake.lua
8189 lines (6198 loc) · 243 KB
/
vmake.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
--[[
Copyright (c) 2016 Alexandru-Mihai Maftei. All rights reserved.
Developed by: Alexandru-Mihai Maftei
aka Vercas
http://vercas.com | https://github.com/vercas/vMake
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal with the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimers.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimers in the
documentation and/or other materials provided with the distribution.
* Neither the names of Alexandru-Mihai Maftei, Vercas, nor the names of
its contributors may be used to endorse or promote products derived from
this Software without specific prior written permission.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
WITH THE SOFTWARE.
---
You may also find the text of this license in "LICENSE.md".
]]
local arg = _G.arg
if arg ~= nil and type(arg) ~= "table" then
error("vMake error: 'arg' global variable, if present, must be a table containing command-line arguments as strings.")
end
if arg then
for i = 1, #arg do
if type(arg[i]) ~= "string" then
error("vMake error: 'arg' table must be nil or a table containing command-line arguments as strnigs; it contains a "
.. tostring(type(args[i])) .. " at position #" .. i .. ".")
end
end
end
local ______f, _____________t = function()return function()end end, {nil,
[false] = 'Lua 5.1',
[true] = 'Lua 5.2',
[1/'-0'] = 'Lua 5.3',
[1] = 'LuaJIT' }
local luaVersion = _____________t[1] or _____________t[1/0] or _____________t[______f()==______f()]
-- Taken from http://lua-users.org/lists/lua-l/2016-05/msg00297.html
local vmake, vmake__call, getEnvironment, withEnvironment = {
Version = "3.2.0",
VersionNumber = 3002000,
Debug = false,
Silent = false,
Verbose = false,
Jobs = false,
GlobalDataContainer = false,
ShouldComputeGraph = true,
ShouldDoWork = true,
ShouldPrintGraph = false,
ShouldClean = false,
ShouldGenerateMakefile = false,
ShouldGenerateCompilationDatabase = false,
FullBuild = false,
WorkGraph = false,
MaxLevel = false,
Capturing = false,
CommandLog = false,
JobsDir = false,
ParallelOpts = false,
HasGnuParallel = false,
HasMake = false,
Target = false,
TargetPath = false,
Combinations = false,
TransferredArguments = false,
ItemFilter = false,
}
local baseEnvironment = {
["_G"] = _G, -- No need to hide this.
tonumber = tonumber,
tostring = tostring,
error = error,
}
local codeLoc = 0
local LOC_DATA_EXP, LOC_RULE_SRC, LOC_RULE_FLT, LOC_RULE_ACT = 1, 2, 3, 4
local LOC_CMDO_HAN, LOC_CMDO_ACP = 5, 6
local curWorkItem = nil
vmake.Description = "vMake " .. vmake.Version .. " [" .. vmake.VersionNumber
.. "] (c) 2016 Alexandru-Mihai Maftei, running under " .. luaVersion
pcall(require, "lfs")
SH_AND, SH_SEP, SH_RAW = {}, {}, {}
baseEnvironment.SH_AND, baseEnvironment.SH_SEP, baseEnvironment.SH_RAW = SH_AND, SH_SEP, SH_RAW
local targetData = {
[false] = { },
["full"] = { Full = true },
["generate-makefile"] = { Full = true },
["generate-shell-script"] = { Full = true, Capturing = true },
["generate-compilation-database"] = { Full = true, Capturing = true },
["extract-commands"] = { Full = true, Capturing = true },
["single-item"] = { },
["lint"] = { Full = true },
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- Top-level Declarations
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- Declared configurations, architectures and projects.
local configs, archs, projects, comps, rules, cmdlopts = {}, {}, {}, {}, {}, {}
local defaultProj, defaultArch, defaultConf, outDir = false, false, false, false
local checkName, normalizeName
function Default(name, tolerant)
assertType("string", name, "named default", 2)
assertType({"nil", "boolean"}, tolerant, "tolerant", 2)
if #name < 1 then
error("vMake error: Name must be non-empty.", 2)
end
local nname = normalizeName(name)
if nname[1] == "-" or nname[#nname] == "-" then
error("vMake error: Name (\"" .. name .. "\") needs to begin and end with alphanumeric characters.", 2)
end
local proj, arch, conf = projects[nname], archs[nname], configs[nname]
if proj then
if defaultProj then
error("vMake error: Default project is already chosen to be " .. tostring(defaultProj) .. "; cannot set it to " .. tostring(proj) .. ".", 2)
end
defaultProj = proj
elseif arch then
if defaultArch then
error("vMake error: Default architecture is already chosen to be " .. tostring(defaultArch) .. "; cannot set it to " .. tostring(arch) .. ".", 2)
end
defaultArch = arch
elseif conf then
if defaultConf then
error("vMake error: Default configuration is already chosen to be " .. tostring(defaultConf) .. "; cannot set it to " .. tostring(conf) .. ".", 2)
end
defaultConf = conf
else
error("vMake error: There is no project, architecture or configuration named \"" .. name .. "\".", 2)
end
return Default
end
function OutputDirectory(val, forbidFunc)
if outDir then
error("vMake error: Output directory is already defined.", 2)
end
local allowedTypes = {"string", "Path", "function"}
if forbidFunc then allowedTypes[3] = nil end
local valType = assertType(allowedTypes, val, 2)
if valType == "string" then
val = vmake.Classes.Path(val, "d")
end
outDir = val
return val
end
local validFileTypes = { f = true, d = true, U = true }
function Path(val, type)
assertType("string", val, "path", 2)
assertType({"nil", "string"}, type, "path type", 2)
if #val < 1 then
error("vMake error: Path string must be non-empty.", 2)
end
if type and not validFileTypes[type] then
error("vMake error: Path type \"" .. type .. "\" is invalid.", 2)
end
return vmake.Classes.Path(val, type or 'U')
end
baseEnvironment.Path = Path
function FilePath(val)
assertType("string", val, "path", 2)
if #val < 1 then
error("vMake error: Path string must be non-empty.", 2)
end
return vmake.Classes.Path(val, "f")
end
baseEnvironment.FilePath = FilePath
function DirPath(val)
assertType("string", val, "path", 2)
if #val < 1 then
error("vMake error: Path string must be non-empty.", 2)
end
return vmake.Classes.Path(val, "d")
end
baseEnvironment.DirPath = DirPath
function Configuration(name)
local nname = checkName(name, "configuration", 2)
local res = vmake.Classes.Configuration(name, nname)
configs[nname] = res
configs[#configs + 1] = res
return function(tab)
assertType("table", tab, "configuration table", 2)
for k, v in pairs(tab) do
assertType("string", k, "table key", 2)
res[k] = v
end
return res
end
end
function GetConfiguration(name)
return configs[checkName(name, "configuration", 2, true)]
end
baseEnvironment.GetConfiguration = GetConfiguration
function Architecture(name)
local nname = checkName(name, "architecture", 2)
local res = vmake.Classes.Architecture(name, nname)
archs[nname] = res
archs[#archs + 1] = res
return function(tab)
assertType("table", tab, "architecture table", 2)
for k, v in pairs(tab) do
assertType("string", k, "table key", 2)
res[k] = v
end
return res
end
end
function GetArchitecture(name)
return archs[checkName(name, "architecture", 2, true)]
end
baseEnvironment.GetArchitecture = GetArchitecture
local function spawnProjectFunction(pType, tName, topLevel)
return function(name)
local nname = checkName(name, tName, 2)
local res = vmake.Classes.Project(name, nname, pType)
if topLevel then
projects[nname] = res
projects[#projects + 1] = res
else
comps[#comps + 1] = res
end
return function(tab)
assertType("table", tab, tName .. " table", 2)
for k, v in pairs(tab) do
assertType({"string", "integer"}, k, tName .. " table key", 2)
if type(k) == "string" then
res[k] = v
end
end
for i = 1, #tab do
res:AddMember(tab[i])
end
return res
end
end
end
Project = spawnProjectFunction("proj", "project", true)
Component = spawnProjectFunction("comp", "component")
function Rule(name)
checkName(name, "rule", 2)
local res = vmake.Classes.Rule(name)
rules[#rules + 1] = res
return function(tab)
assertType("table", tab, "rule table", 2)
for k, v in pairs(tab) do
assertType("string", k, "table key", 2)
res[k] = v
end
return res
end
end
function CmdOpt(name)
assertType("string", name, "command-line option long name", 2)
if #name < 2 then
error("vMake error: Command-line option long name must be at least two characters long.", 2)
end
if cmdlopts[name] then
error("vMake error: Command-line option long name \"" .. name .. "\" conflicts with another.", 2)
end
local res = vmake.Classes.CmdOpt(name)
cmdlopts[#cmdlopts + 1] = res
cmdlopts[name] = res
local func
func = function(val)
local valType = assertType({"string", "table"}, val, "command-line option table / short name", 2)
if valType == "table" then
for k, v in pairs(val) do
assertType("string", k, "table key", 2)
res[k] = v
end
return res
else
res.ShortName = val
return func
end
end
return func
end
function GlobalData(tab)
if not vmake.GlobalDataContainer then
vmake.GlobalDataContainer = vmake.Classes.WithData()
end
vmake.GlobalDataContainer.Data = tab
-- Will work multiple times.
end
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- Utilitary Functions
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
function typeEx(val)
local t = type(val)
if t ~= "table" then
return t
else
local class = val.__class
if class then
return vmake.Classes[class] or t
-- This will not work for classes that are not actually declared.
else
return t
end
end
end
baseEnvironment.type = baseEnvironment.typeEx
-- Note the alias!
local function escapeForShell(s)
if #s < 1 then
return "\"\""
end
s = s:gsub('"', "\\\"")
if s:find("[^a-zA-Z0-9%+%-%*/=%.,_\"]") then
return '"' .. s .. '"'
end
return s
end
-- -- -- -- -- --
-- Error Handling --
-- -- -- -- -- --
function MSG(...)
if not vmake.Verbose then
return
end
local items = {...}
for i = 1, #items do
items[i] = tostring(items[i])
end
print(table.concat(items))
end
baseEnvironment.MSG = MSG
local function prettyString(val)
if type(val) == "string" then
return string.format("%q", val)
else
return tostring(val)
end
end
local function printTable(t, append, indent, done)
local myIndent = string.rep("\t", indent)
for key, value in pairs(t) do
append(myIndent)
append(prettyString(key))
if typeEx(value) == "table" and not done[value] then
done[value] = true
local ts = tostring(value)
if ts:sub(1, 9) == "table: 0x" then
append ": "
append(ts)
append "\n"
printTable(value, append, indent + 1, done)
else
append " = "
append(ts)
append "\n"
end
else
append " = "
append(prettyString(value))
append "\n"
end
end
end
local function printEndData(self, indent, out)
indent = indent or 0
local myIndent = string.rep("\t", indent)
local res = { myIndent, "ERROR:\t", self.Error, "\n" }
local function append(val, blergh, ...)
res[#res + 1] = val
if blergh then
append(blergh, ...)
end
end
myIndent = myIndent .. "\t"
for i = 1, #self.Stack do
local info, appendSource = self.Stack[i]
append(myIndent)
append(tostring(i))
append "\t"
if vmake.Verbose or vmake.Debug then
function appendSource()
append "\n"
append(myIndent)
append "\t location: "
if info.what ~= "C" then
append(info.short_src or info.source)
if info.currentline then
append ":"
append(tostring(info.currentline))
end
append "\n"
if info.what == "Lua" and info.linedefined and (info.linedefined ~= info.currentline or info.lastlinedefined ~= info.currentline) then
-- This hides the definition of inline functions that will contain the erroneous line of code anyway.
-- Also excludes C code and main chunks, which show placeholder values there.
append(myIndent)
append "\t definition at "
append(tostring(info.linedefined))
if info.lastlinedefined then
append "-"
append(tostring(info.lastlinedefined))
end
append "\n"
end
else
append "C\n"
end
end
else
function appendSource()
append "\t"
if info.what ~= "C" then
append " "
append(info.short_src or info.source)
if info.currentline then
append ":"
append(tostring(info.currentline))
end
if info.what == "Lua" and info.linedefined and (info.linedefined ~= info.currentline or info.lastlinedefined ~= info.currentline) then
-- This hides the definition of inline functions that will contain the erroneous line of code anyway.
-- Also excludes C code and main chunks, which show placeholder values there.
append "\t def. at "
append(tostring(info.linedefined))
if info.lastlinedefined then
append "-"
append(tostring(info.lastlinedefined))
end
end
append "\n"
else
append " [C]\n"
end
end
end
if info.istailcall then
append "tail calls..."
if info.short_src or info.source then
appendSource()
else
append "\n"
end
elseif info.name then
-- This is a named function!
append(info.namewhat)
append "\t"
append(info.name)
appendSource()
elseif info.what == "Lua" then
-- Unnamed Lua function = anonymous
append "anonymous function"
appendSource()
elseif info.what == "main" then
-- This is the main chunk of code that is executing.
append "main chunk"
appendSource()
elseif info.what == "C" then
-- This might be what invoked the main chunk.
append "unknown C code\n"
end
-- Now, upvalues, locals, parameters...
if info.what ~= "C" and (vmake.Verbose or vmake.Debug) then
-- Both main chunk and Lua functions can haz these.
append(myIndent)
append "\t "
if info.nparams == 1 then
append "1 parameter; "
else
append(tostring(info.nparams))
append " parameters; "
end
if #info._locals - info.nparams == 1 then
append "1 local; "
else
append(tostring(#info._locals - info.nparams))
append " locals; "
end
if info.nups == 1 then
append "1 upvalue\n"
else
append(tostring(info.nups))
append " upvalues\n"
end
local extraIndent = myIndent .. "\t\t"
local done = { [_G] = true, [vmake] = true, [self] = true }
for j = 1, #info._locals do
local key, value = info._locals[j].name, info._locals[j].value
append(extraIndent)
append(prettyString(key))
if typeEx(value) == "table" and not done[value] then
done[value] = true
local ts = tostring(value)
if ts:sub(1, 9) == "table: 0x" then
append ": "
append(ts)
append "\n"
printTable(value, append, indent + 4, done)
else
append " = "
append(ts)
append "\n"
end
else
append " = "
append(prettyString(value))
append "\n"
end
end
if info._upvalues then
for j = 1, #info._upvalues do
local key, value = info._upvalues[j].name, info._upvalues[j].value
append(extraIndent)
append(prettyString(key))
if typeEx(value) == "table" and not done[value] then
done[value] = true
local ts = tostring(value)
if ts:sub(1, 9) == "table: 0x" then
append ": "
append(ts)
append "\n"
printTable(value, append, indent + 4, done)
else
append " = "
append(ts)
append "\n"
end
else
append " = "
append(prettyString(value))
append "\n"
end
end
end
end
end
res = table.concat(res)
if out then
return out(res)
else
return res
end
end
local function queuefunc(fnc, functionlist, donefunctions)
if donefunctions[fnc] then return end
functionlist[#functionlist+1] = fnc
donefunctions[fnc] = true
end
function GatherEndState(err)
local functionlist, donefunctions = {}, {}
local stack, thesaurus = {}, {}
local i = 2
while true do
local info = debug.getinfo(i)
if not info then
break
end
stack[#stack+1] = info
info._stackpos = i
if info.func then
thesaurus[info.func] = info
queuefunc(info.func, functionlist, donefunctions)
info.func = tostring(info.func)
end
--if info.what == "Lua" then
info._locals = {}
local locals = info._locals
local j = 1
while true do
local n, v = debug.getlocal(i, j)
if not n then break end
locals[#locals+1] = {name=n,value=v}
if type(v) == "function" then
queuefunc(v, functionlist, donefunctions)
locals[#locals].value = tostring(locals[#locals].value)
end
j = j + 1
end
--end
i = i + 1
end
for i = 1, #functionlist do
local fnc = functionlist[i]
local info
if thesaurus[fnc] then
info = thesaurus[fnc]
else
info = debug.getinfo(fnc)
thesaurus[fnc] = info
end
local ups = {}
info._upvalues = ups
for j = 1, info.nups do
local n, v = debug.getupvalue(fnc, j)
ups[#ups+1] = {name=n,value=v}
if type(v) == "function" then
queuefunc(v, functionlist, donefunctions)
ups[#ups].value = tostring(ups[#ups].value)
end
end
end
local newthesaurus = {}
for k, v in pairs(thesaurus) do
newthesaurus[tostring(k)] = v
end
return { Stack = stack, Thesaurus = newthesaurus, Error = err, ShortTrace = debug.traceback(nil, 2), Print = printEndData }
end
do
-- A small workaround around old xpcall versions.
local foo = 1
xpcall(
function(arg)
if arg == "bar" then
foo = 2
else
foo = 0
end
end,
function(err)
io.stderr:write("This really shouldn't have happened:\n", err, "\n")
os.exit(-100)
end,
"bar")
assert(foo ~= 1, "'foo' should have changed!")
if foo == 0 then
MSG("xpcall doesn't seem to support passing arguments; working around it.")
function vcall(inner_function, ...)
local wrapped_args = {...}
local function wrapper_function()
return inner_function(unpack(wrapped_args))
end
local ret = {xpcall(wrapper_function, GatherEndState)}
if ret[1] then
-- Call succeeded.
table.remove(ret, 1)
return { Return = ret }
else
-- Call failed!
return ret[2]
end
end
else
function vcall(fnc, ...)
local ret = {xpcall(fnc, GatherEndState, ...)}
if ret[1] then
-- Call succeeded.
table.remove(ret, 1)
return { Return = ret }
else
-- Call failed!
return ret[2]
end
end
end
end
if setfenv then
local cache = {}
function withEnvironment(f, env)
if cache[f] and cache[f][env] then
return cache[f][env]
end
local bytecode = string.dump(f)
-- TODO: Get function info.
local new, err = loadstring(bytecode)
if not new then
error("vMake internal error: Failed to copy function " .. "<TODO>" .. " to change its environment: " .. err, 1)
end
setfenv(new, env)
local i, nameN = 1
repeat
nameN = debug.getupvalue(new, i)
if not nameN then
break
end
local j, nameO, temp = 1
repeat
nameO, temp = debug.getupvalue(f, j)
if nameO == nameN then
debug.setupvalue(new, i, temp)
break
end
j = j + 1
until not nameO
if not nameO then
error("vMake internal error: Failed to set upvalue \"" .. nameN .. "\" of function " .. "<TODO>", 1)
end
i = i + 1
until not nameN
if cache[f] then
cache[f][env] = new
else
cache[f] = { [env] = new }
end
cache[new] = { [env] = new }
-- Yup, cache this one as well.
return new
end
else
local cache = {}
function getfenv(f)
local i, name, val = 1
repeat
name, val = debug.getupvalue(f, i)
if name == "_ENV" then
return val
end
i = i + 1
until not name
return nil
end
function withEnvironment(f, env)
if cache[f] and (cache[f][env] or cache[f][true]) then
return cache[f][env] or cache[f][true]
end
if not getfenv(f) then
if cache[f] then
cache[f][true] = f
else
cache[f] = { [true] = f }
end
return f
end
-- So it has an environment, time to do the heavy lifting.
local bytecode = string.dump(f)
-- TODO: Get function info.
local new, err = load(bytecode, "temp", "b", env)
if not new then
error("vMake internal error: Failed to copy function " .. "<TODO>" .. " to change its environment: " .. err, 1)
end
local i, nameN, temp = 1
repeat
nameN, temp = debug.getupvalue(new, i)
if not nameN then
break
elseif nameN ~= "_ENV" then
local j, nameO = 1
repeat
nameO = debug.getupvalue(f, j)
if nameO == nameN then
debug.upvaluejoin(new, i, f, j)
break
end