-
Notifications
You must be signed in to change notification settings - Fork 0
/
Neil.lua
3419 lines (3267 loc) · 136 KB
/
Neil.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
-- <License Block>
-- Neil.lua
-- Neil
-- version: 21.06.30
-- Copyright (C) 2020, 2021 Jeroen P. Broks
-- This software is provided 'as-is', without any express or implied
-- warranty. In no event will the authors be held liable for any damages
-- arising from the use of this software.
-- Permission is granted to anyone to use this software for any purpose,
-- including commercial applications, and to alter it and redistribute it
-- freely, subject to the following restrictions:
-- 1. The origin of this software must not be misrepresented; you must not
-- claim that you wrote the original software. If you use this software
-- in a product, an acknowledgment in the product documentation would be
-- appreciated but is not required.
-- 2. Altered source versions must be plainly marked as such, and must not be
-- misrepresented as being the original software.
-- 3. This notice may not be removed or altered from any source distribution.
-- </License Block>
-- Debug settings
local showtranslation = false -- When set to true, the translator will show the translation it generated... Only to be used when debugging Neil itself
local usedebug = false
local nodestructor = true -- When set destructors will be ignored. I found out that destructors have a bit of conflicts. I need to see how to do this better.
local destructorwarn = false -- When set to 'true' it warns for called destructors. For some reason they can sometimes crash the system due to the memory wipe sometimes taking place BEFORE the destructor has been called.
local destructorwarnings = 0
-- Need debug chat?
--local function dbgprint(...) print(...) end
local function dbgprint() end
-- Creation of library
local _Neil = {}
_Neil.Neil = "Neil"
_Neil.UseFileTable = { lua = function(s,chunk) return (loadstring or load)(s,chunk) end }
_Neil.UseDirTable = { }
_Neil.FileSystemCaseSensitive = false -- Must be set to true if directly reading from a Linux system or an other case senstive undeunderground
local TranslationCount = 0
-- For Global Defines
local GlobalDefines = { ["SYS_LUA"] = true,["__NEIL"]=true }
-- forwards
local DefineFunction
-- keywords and operators
local operators = {"++","--","!=" --[[Neil will replace != with ~=]],"~=","::=","+=","-=","==","<=",">=","//","||","&&" --[[ Maybe // is a bit odd to call an operator, but for Neil that's the easier way to work]], "/*", "*/",
"+", "-", "=", ">", "<", "!" --[[Neil will replace ! with 'not']] , "%","#","*","/","^",",","/","[","]","&","{","}"}
local keywords = { "void","int","byte","number","bool","boolean","delegate","function","plua", "userdata","string","table", -- types
"switch","case","default", "fallthrough", -- casing (fallthrough is reserved... it would require to translate with 'goto', but that would require Lua 5.2 or later)
"repeat","until","forever","loopwhile", -- basic looping
"do","end", -- Basic scope
"if","then","else","elseif", -- if
"while", -- while
"for", -- for
"ipairs","pairs","in",
"cfor", -- reserved. Idea for c-syntax for like this "for (i=1;i<=10;i++)". But not planned for short term
"global","public","private","final","abstract", "get", "set", "local", -- needed for declarations
"class","module","group","quickmeta","new","extends",
"mod", -- Neil will replace that with % -- Just a nice thing for BASIC and Pascal coders
"return", -- We need that one, don't we?
"true", "false", -- The two boolean values
"nil", "null", -- "null" will be replaced by "nil"
"init","defer","div","var","break","and","or","not",
"import","export","deftable","defmeta","link","infinity",
"constructor","destructor",
"try","catch","finally" -- "finally" is not yet supported, but I reserved the word as a keyword for later usage, as I hope to implement it in the future.
}
local declasupport = {"global","public","private","final","abstract", "get", "set", "local","static","const", "readonly" }
local types = {"void","int","string","bool","boolean","delegate","function","userdata","number","table","plua","var","byte"}
local quickmetaparameters = {
index = "self, key",
newindex = "self, key, value ",
call = "self, ...",
tostring = "self",
len = "self",
pairs = "self",
ipairs = "self",
gc = "self",
unm = "self, other",
add = "self, other",
sub = "self, other",
mul = "self, other",
div = "self, other",
idiv = "self, other",
pow = "self, other",
mod = "self, other",
concat = "self, other",
band = "self, other",
bor = "self, other",
bxor = "self, other",
bnot = "self, other",
shl = "self, other",
shr = "self, other",
lt = "self, other",
le = "self, other",
gt = "self, other",
ge = "self, other"
}
local UsedByNeil = {}
local NeilIsUsing = {} -- Has to prevent "circular" uses!
-- debug
local debugchat = true
local function Chat(...)
if debutchat then return end
for _,d in ipairs { ... } do print("DEBUG>",d) end
end
-- Constant/ReadOnly
local ReadOnlyWrite = {}
-- Check Type
local CTCase,ConvType
do local kk
function ConvType(v,wanttype,key,strict)
-- If "strict" is set to 'true' the value 'nil' won't be accepted for string and boollean variables
-- local kk = ""
if key then
kk = " for "..key
end
CTCase = CTCase or {
byte = function(v)
_Neil.Assert(type(v)=="number","Number required"..kk)
v = math.floor(v+.5)
if v<0 then
return 255-(math.abs(v)%256)
else
return v%256
end
end,
int = function(v)
_Neil.Assert(type(v)=="number","Number required"..kk.." (Got "..type(v)..")")
return math.floor(v+.5)
end,
['number'] = function(v)
_Neil.Assert(type(v)=="number","Number required"..kk.." (Got "..type(v)..")")
return v
end,
['bool'] = function(v)
_Neil.Assert(type(v)=="boolean","Boolean required"..kk)
return v
end,
['boolean'] = function(v)
if strict then _Neil.Assert( v~=nil , "Boolean required... and got 'nil'" ) end
return CTCase[wanttype].bool(v)
end,
['table'] = function(v)
_Neil.Assert(type(v)=="table" or v==nil,"Table required"..kk)
return v
end,
['userdata'] = function(v)
_Neil.Assert(type(v)=="userdata" or v==nil,"UserData required"..kk)
return v
end,
['delegate'] = function(v)
_Neil.Assert(type(v)=="function" or v==nil,"Delegate required"..kk)
return v
end,
['var'] = function(v) return v end,
['plua'] = function(v) return v end,
['QuickMeta_group'] = function(v) return v end,
['string'] = function(v)
if type(v)=="nil" then
_Neil.Assert(not strict,"Got nil, but expected a string"..kk)
return "nil"
elseif type(v)=="string" then
return v
elseif type(v)=="table" and v[".neilclass"] and v[".hasmember"]("ToString") then
return v.ToString()
else
return tostring(v)
end
end,
['void'] = function() return nil end,
var = function(v) return v end
}
-- TODO: Class-checktype
if not CTCase[wanttype] then
-- TODO: Class check
print("WARNING! type "..wanttype.." cannot yet be fully processed yet!")
return tostring(v)
end
return CTCase[wanttype](v)
end end
_Neil.ConvType = ConvType
-- Error
function _Neil.Error(a)
error(ConvType(a,"string").."\n"..debug.traceback () )
end
function _Neil.Assert(condition,err)
err = err or "Neil Assertion Failed"
if not condition then _Neil.Error(err) return false,err else return condition end
end
-- Globals
local substr = string.sub
local Globals
Globals = {
['LUALOADSTRING'] = {Type='delegate', Constant=true, Value=loadstring or load},
['LUADOSTRING'] = {Type='delegate', Constant=true, Value=function(str,chunk,...) return _Neil.Globals.LuaLoadString(str,chunk)(...) end},
['NEILLOADSTRING'] = {Type='delegate', Constant=true, Value=function(str,chunk) return _Neil.Load(str,chunk) end},
['NEILDOSTRING'] = {Type='delegate', Constant=true, Value=function(str,chunk,...) return _Neil.Load(str,chunk)(...) end},
['NEILUSE'] = {Type='delegate', Constant=true, Value=function(uf,chunk) return _Neil.Use(uf,chunk) end},
['NEILSOMETHING'] = {Type='delegate', Constant=true, Value=function(v) return v~=false and v~=nil end},
['SETMETATABLE'] = {Type='delegate', Constant=true, Value=setmetatable},
['TABLECONTAINS'] = {Type='delegate', Constant=true, Value=function(tab,want)
for i,v in ipairs(tab) do
if v==want then return i end
end
return nil
end},
['LUAVERSION'] = {Type='delegate', Constant=true, Value = function()
local ret,_ = _VERSION:gsub("Lua ","")
return tonumber(ret)
end},
['EXPAND'] = {Type='delegate', Value=function (t,p)
assert(type(t)=="table" or type(t)=="string","Table or string expected in Expand request (got "..type(t)..")\n"..debug.traceback())
p = tonumber(p) or 1
if p<#t then
if type(t)=="string" then
return t:sub(p,p),Globals.EXPAND.Value(t,p+1)
else
return t[p],Globals.EXPAND.Value(t,p+1)
end
end
if p==#t then
if type(t)=="string" then
return t:sub(p,p),Globals.EXPAND.Value(t,p+1)
else
return t[p]
end
end
return nil
end, Constant=true },
["REMOVEFROMARRAY"] = { Type="delegate", Constant=true, value=function(tab,index)
assert(type(tab)=="table","First argument of RemoveFromArray must be a table and not a "..type(tab))
index = math.floor(index or 1)
assert(type(index)=="number","Second argument of RemoveFromArray must be a number and not a "..type(index))
local l = #table
for i=index,l do
tab[i]=tab[i+1]
end
end},
['LUA'] = { Type='table', Value=_G, Constant=true },
["TRANSLATION_TARGET"] = {Type="string", Value="Lua", Constant=true},
["CHR"] = { Type='delegate', Value=string.char, Constant=true },
['ASSERT'] = {Type=='delegate', Value=_Neil.Assert, Constant=true },
['GLOBALDUMP'] = { Type='delegate', Constant=true, Value=function() local ret="" for k,v in pairs(Globals) do ret = ret .. k .. " = "..tostring(v.Value).."\n" end return ret end },
['GLOBALEXISTS'] = {Type='delegate', Constant=true, Value=function(n)
_Neil.Assert(type(n)=="string","Global exists expects a string. Not a "..type(n))
n = n:upper()
local g = Globals[n]
return g~=nil and g~=false
end},
['ROUND'] = {Type='delegate', Constant=true, Value=function(a) return math.floor(a+.5) end},
['SOUT'] = {Type='delegate', Constant=true,Value=function(...)
local ret = ""
for _,v in ipairs{...} do ret = ret .. Globals.TOSTRING.Value(v) end
return ret
end},
['COUT'] = {Type='delegate', Constant=true,Value=function(...) io.write(Globals.SOUT.Value(...)) end },
['PRINT'] = {Type='delegate', Constant=true, Value=function(...) print(...) end },
['SPRINTF'] = {Type='delegate', Constant=true, Value=string.format },
['PRINTF'] = {Type='delegate', Constant=true, Value=function(f,...) _Neil.Assert(type(f)=="string","Format value must be string")
-- _Neil.Globals.Cout(_Neil.Globals.SPrintF(f,...))
local s,e = pcall(_Neil.Globals.SPrintF,f,...)
if not s then
local err = e.."\nPrintF(\""..f.."\""
for i,k in ipairs{...} do err = err..", "..k end
err=err..")\n\n"..debug.traceback()
error(err)
else
Globals.COUT.Value(e)
end
end},
['CONVTYPE'] = {Type='delegate', Constent=true, Value=ConvType },
['TOSTRING'] = {Type='delegate', Constant=true,Value=function(v) return ConvType(v,"string") end },
["REPLACE"] = {Type='delegate', Constant=true,Value=string.gsub },
["RIPAIRS"] = {type="delegate", Constant=true, Value=function(tab)
assert(type(tab)=="table","RIPairs requires a table. Got "..type(tab))
local i = #tab + 1
return function ()
i = i - 1
if i<=0 then return nil,nil end
return i,tab[i]
end
end},
['TRIM'] = {Type='delegate', Constant=true,Value=function(str) return (_Neil.Globals.ToString(str):gsub("^%s*(.-)%s*$", "%1")) end },
['LEFT'] = {Type='delegate', Constant=true, Value=function(s, l)
if not _Neil.Assert(type(s)=="string","String exected as first argument for 'left'") then return end
l = l or 1
_Neil.Assert(type(l)=="number","Number expected for second argument in 'left'")
return substr(s,1,l)
end},
['RIGHT'] = {Type=delegate, Constant=true, Value=function(s,l)
local ln
local st
ln = l or 1
st = s or "nostring"
return substr(st,-ln,-1)
end},
['MID'] = {Type=delegate, Constant=true, Value=function(s,o,l)
local ln
local of
local st
ln=l or 1
of=o or 1
st=s or ""
return substr(st,of,(of+ln)-1)
end},
['EXTRACTEXT'] = {Type='delegate', Constant=true,Value=function(str,tolower)
local ret = ""
local l=0
local right = _Neil.Globals.Right
local left = _Neil.Globals.Left
repeat
l = l + 1
if l>=#str then return "" end
ret = right(str,l)
if left(ret,1)=="/" or left(ret,1)=="\\" then return "" end
until left(ret,1)=="."
if tolower then ret = ret:lower() end
return right(ret,#ret-1)
end},
["SPLIT"] = {Type='delegate', Constant=true, Value=function(inputstr,sep)
if sep == nil then
sep = "%s"
end
local t = {}
local i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end},
["PREFIXED"] = {Type='delegate', Constant=true, Value=function(str,prefix)
return _Neil.Globals.Left(str,#prefix)==prefix
end},
["SUFFIXED"] = {Type='delegate', Constant=true, Value=function(str,suffix)
return _Neil.Globals.Right(str,#suffix)==suffix
end},
["SPAIRS"] = {Type='delegate', Constant=true, Value=function(t, order)
-- collect the keys
local keys = {}
local t2 = {}
for k,v in pairs(t) do keys[#keys+1] = k t2[k]=v end
-- if order function given, sort by it by passing the table and keys a, b,
-- otherwise just sort the keys
if order then
function bo(a,b)
return order(t, a, b)
end
table.sort(keys, bo)
else
table.sort(keys)
end
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t2[keys[i]]
end
end
end},
["EACH"] = {Type='delegate', Constant=true, Value=function(tab)
assert(type(tab)=="table","EACH expects a table. Got "..type(tab))
if tab[".neilclass"] then return tab.__EACH() end
local i = 0
return function()
i = i + 1
if i>#tab then return nil end
return tab[i]
end
end},
["INV_EACH"] = {Type='delegate', Constant=true, Value=function(tab)
assert(type(tab)=="table","INV_EACH expects a table. Got "..type(tab))
if tab[".neilclass"] then return tab.__INVEACH() end
local i = #tab + 1
return function()
i = i - 1
if i<=0 then return nil end
return tab[i]
end
end},
["TYPE"] = {Type='delegate', Constant=true, Value=function(v)
-- stuff for classes and things, come later!
return type(v)
end},
["LGGTTT"] = {Type='delegate', Constant=true, Value=function(pref,performkill) -- Lua Grab Global Turn To Table
local ret = {}
local kill = {}
for k,v in pairs(_G) do
if _Neil.Globals.Prefixed(k,pref.."_") then
kill[#kill+1] = k
local s = _Neil.Globals.split(k,"_")
local prevlevel = ret
for i=2,#s do
local tg = s[i]:upper()
if i<#s then
prevlevel[tg] = prevlevel[tg] or {}
prevlevel = prevlevel[tg]
else
prevlevel[tg] = v
end
end
-- prevlevel = v
end
end
if performkill~=false then for _,k in ipairs(kill) do _G[k]=nil end end
return ret
end},
["TABLETYPECHAIN"] = {Type='delegate', Constant=true, Value=function(tab)
local ret=""
for i,v in ipairs(tab) do
if i>1 then ret=ret.."," end
ret = ret .. type(v)
end
if ret=="" then return "nothing" end
return ret
end},
["INVOKE"] = {Type='delegate', Constant=true, Value=function(func,...)
if func then return true,func(...) else return false end
end}
}
local function imodtoglob(name,asname)
local module = {}
for k,v in pairs(_G[name:lower()]) do module[k]=v end
Globals[(asname or name):upper()] = { Type='Lua Module', Constant=true, Value=setmetatable({},{
__newindex=function() error("Writing to internal module "..name.." prohibited") end,
__index=function(self,key)
local lkey=key:lower()
if module[lkey] then return module[lkey] end
if module[key] then return module[key] end
error("Module "..name.." does not appear to have an element named "..key)
end
})}
end
for k,m in pairs {"Math","IO","OS",MString = "String", MTable = "Table", "CoRoutine", "Debug", "Package" } do
if _G[m:lower()] then
if type(k)=="number" then imodtoglob(m) else imodtoglob(m,k) end
end
end
_Neil.Globals = setmetatable({},{
__index = function(s,k)
local uk = k:upper()
-- Chat(uk,tostring(Globals[uk]))
_Neil.Assert(Globals[uk],"Reading unknown global identifier \""..k.."\"!")
-- print(uk) for k,v in pairs(Globals[uk]) do print(k,v) end -- debug line --
-- print(s,k,uk,Globals[uk],Globals[uk].Value)
return Globals[uk].Value
end,
__newindex = function(s,k,v)
local uk = k:upper()
local want = Globals[uk]
if Globals[uk].Value==v then return end -- Prevent some "readonly" issues with += and -=! If the value (which can also be a pointer) reamins the same no complaints!
_Neil.Assert(want,"Defining unknown global identifier \""..k.."\"!")
if want.Constant and v == want.Value then return end -- This prevents some static conflicts
_Neil.Assert(not want.Constant,k.." is a constant and cannot be overwritten")
_Neil.Assert((not want.ReadOnly) or (ReadOnlyWrite.Globals),k.." is read-only and cannot be overwritten")
Globals[uk].Value = ConvType(v,Globals[uk].Type,k)
--print("Defined global ",uk," with ",v," became ",ConvType(v,Globals[uk].Type,k))
if want.UndefinedConstant then
want.Constant = true
want.UndefinedConstant = nil
end
if want.UndefinedReadOnly then
want.ReadOnly = true
want.UndefubedReadOnly = false
end
end,
__call=function(s,newk,oftype,rw,defaultvalue)
local uk = newk:upper()
_Neil.Assert(not Globals[uk],"Duplicate global identifier: "..newk)
local newdec = {}
if oftype=="string" then
defaultvalue = defaultvalue or ""
elseif oftype=="number" or oftype=="byte" or oftype=="int" then
defaultvalue = defaultvalue or 0
elseif oftype=="boolean" or oftype=="bool" then
oftype="bool"
if defaultvalue==nil then defaultvalue=false end
end
newdec.Value = ConvType(defaultvalue,oftype,"New global "..newk)
newdec.Type = oftype
newdec.ReadOnly = rw:lower()=="readonly"
newdec.Constant = rw:lower()=="const" or rw:lower()=="constant"
Globals[uk] = newdec
end
})
-- Locals
local function LocalToFunction(table,key,func)
local want
want = table[key:upper()]; assert(want,"INTERNAL ERROR!\nlocal table finding error >> '"..key.."'\n\n")
want.Value = func
want.ReturnType = want.Type
want.Type = 'delegate'
want.Constant = true
end
local function Local_Index(table,key)
local uk = key:upper()
if key==".converttofunction" then return function(name,func) return LocalToFunction(table,name,func) end end
_Neil.Assert(table[uk],"Reading unknown local identifier \""..key.."\"!")
return table[uk].Value
end
local function Local_NewIndex(table,key,value)
local uk = key:upper()
local want = table[uk]
if table[uk].Value==value then return end -- Prevent some "readonly" issues with += and -=! If the value (which can also be a pointer) reamins the same no complaints!
_Neil.Assert(want,"Defining unknown local identifier \""..key.."\"!")
_Neil.Assert(not want.Constant,key.." is a constant and cannot be overwritten")
_Neil.Assert((not want.ReadOnly) or (ReadOnlyWrite.Globals),key.." is read-only and cannot be overwritten")
table[uk].Value = ConvType(value,table[uk].Type,k)
if want.UndefinedConstant then
want.Constant = true
want.UndefinedConstant = nil
end
end
local function Local_Call(table,newk,oftype,rw,defaultvalue,strict)
local uk = newk:upper()
rw = rw or "readwrite"
_Neil.Assert(not table[uk],"Duplicate global identifier "..newk)
local newdec = {}
if oftype=="string" then
if strict then _Neil.Assert(defaultvalue,"String value expected for new local "..newk) end
defaultvalue = defaultvalue or ""
elseif oftype=="number" or oftype=="byte" or oftype=="int" then
if strict then _Neil.Assert(defaultvalue,"Numberic value expected for new local "..newk.." (received: "..tostring(defaultvalue)..")") end
defaultvalue = defaultvalue or 0
elseif oftype=="boolean" or oftype=="bool" then
oftype="bool"
if defaultvalue==nil then defaultvalue=false end
end
-- print(defaultvalue)
newdec.Value = ConvType(defaultvalue,oftype,"new "..oftype.." local "..newk)
newdec.Type = oftype
newdec.ReadOnly = rw:lower()=="readonly"
newdec.Constant = rw:lower()=="const" or rw:lower()=="constant"
table[uk] = newdec
end
function _Neil.CreateLocals()
local truetable = {}
return setmetatable({},{
__index = function(s,k) return Local_Index(truetable,k) end,
__newindex = function(s,k,v) return Local_NewIndex(truetable,k,v) end,
__call = function(s,...) return Local_Call(truetable,...) end
})
end
-- Regular Serialize
local function SafeString(avalue)
local value = avalue
for i=1, 255 do
if i<32 or i>126 or i==34 then value = value:gsub(string.char(i),("\\%03d"):format(i)) end
end
return value
end
local function Serialize(name,value,tabs)
tabs = tabs or 0
_Neil.Assert(type(name)=="string","Parameter #1 for Serialize must be a string and not a "..type(name))
local t = type(value)
local ret = "--[["..t.."]] "
for i=1,tabs do ret = ret .. "\t" end
if name~="" then ret = ret .. name .. " = " end
if t == "number" or t=="boolean" then
ret = ret .. tostring(value)
elseif t=="string" then
ret = ret .. "\""..SafeString(value).."\""
elseif t=="userdata" or t=="function" then
ret = ret .. "\"Type "..t.." cannot be serialized!\""
elseif t=="table" then
if t[".neilclass"] then
ret = ret .. "\"Class serializing not (yet) supported\""
else
ret = ret .. "{\n"
local comma
for k,v in pairs(value) do
-- if comma then ret = ret .. "," else comma = true end
if not (type(k)=="string" or type(k)=="number" or type(k)=="boolean") then return false,"Serialize error! Invalid table key!" end
key = k
if type(k)=="string" then
key = '"'..SafeString(k)..'"'
end
if comma then ret = ret .. ",\n" else comma = true end
ret = ret .. Serialize("["..key.."]",v,tabs+1)
end
-- for i=1,tabs do ret = ret .. "\t" end
ret = ret .. "}"
end
else
ret = ret .. '"Unknown type: '..type(v)..'"'
end
return ret
end
Globals.SERIALIZE = {Type='delegate', Value=Serialize, Constant=true}
Globals.SAFESTRING = {Type='delegate', Value=SafeString, Constant=true}
-- Scopes
local Scopes = { [0] = {ID="NOTHINGNESS"} }
local TrueLocals = { NOTHINGNESS = {} }
local Locals = { NOTHINGNESS=TrueLocals.NOTHINGNESS }
-- Incrementors
function _Neil.Inc(value) -- Using "++" will lead to translate to this function
if type(value)=="number" then
return value + 1
elseif type(value)=="table" and value[".neilclass"] then
local w,s = value[".hasmember"]("__Inc")
if not w then error("Class or object does not have __Inc") end
return value.__Inc()
else
error("Incrementor not usable on "..type(value))
end
end
function _Neil.Dec(value) -- Using "--" will lead to translate to this function
if type(value)=="number" then
return value - 1
elseif type(value)=="table" and value[".neilclass"] then
local w,s = value[".hasmember"]("__Dec")
if not w then error("Class or object does not have __Dec") end
return value.__Dec()
else
error("Decrementor not usable on "..type(value))
end
end
function _Neil.Add(value,modvalue) -- Using "+=" will translate to this function
if type(value)=="number" then
return value + modvalue
elseif type(value)=="string" then
return value .. Neil.Globals.ToString(modvalue)
elseif type(value)=="table" and value[".neilclass"] then
Neil.Assert(value[".hasmember"]("_Add"),"Class "..value[".neilclass"].." has no _Add() method")
return value._Add(modvalue)
elseif type(value)=="table" then
value[#value+1] = modvalue
return value
else
error("Adder not usable on "..type(value))
end
end
function _Neil.Subtract(value,modvalue) -- Using "-=" will translate to this function
if type(value)=="number" then
return value - modvalue
elseif type(value)=="string" then
return value:gsub(modvalue,"")
elseif type(value)=="table" and value[".neilclass"] then
Neil.Assert(value[".hasmember"]("_Subtract"),"Class "..value[".neilclass"].." has no _Subtract() method")
return value._Subtract(modvalue)
elseif type(value)=="table" then
local temp = {}
local array = true
-- temp stuff and see if this is an array
for k,v in pairs(value) do
array = array and (not(type(k)~="number" or (k<=#value and k<1 and k~=math.floor(k))))
temp[k]=v
end
-- Deletion
for k,_ in pairs(temp) do value[k]=nil end
if array then
local i = 1
for k,v in ipairs(temp) do
if v~=modvalue then
value[i]=v
i = i + 1
end
end
else
for k,v in pairs(temp) do
if v~=modvalue then
value[k]=v
end
end
end
return value
else
error("Subtractor not usable on "..type(value))
end
end
-- Classes Usage
local ClassIndex,ClassNewIndex
local function ClassDestructor(class,key)
end
local function ClassStaticConstructorCall(class,actclass)
-- print("start") for k,v in pairs(class) do print( "Class has "..type(v).." "..k ) end print("end")
if class.StaticConstructor and (not class.StaticConstructorRun) then
class.StaticConstructorRun=true
class.AllowReadOnly = true
class.StaticConstructor.Value(actclass.Value)
class.AllowReadOnly = false
end
end
local function ClassNew(class,actclass,...)
ClassStaticConstructorCall(class,actclass)
for k,v in pairs(class.AbstractGetProperties) do error("Abstract get-property ("..k..") found in class!") end
for k,v in pairs(class.AbstractSetProperties) do error("Abstract set-property ("..k..") found in class!") end
for k,v in pairs(class.AbstractMethods) do error("Abstract method ("..k..") found in class!") end
local obj,trueobject
trueobject = {}
for k,odata in pairs({class.Members, class.GetProperties, class.SetProperties, class.Methods }) do
-- trueobject[k] = {}
for k2,v2 in pairs(odata) do
trueobject[k2]={}
--print(k,odata,k2,v2)
for k3,v3 in pairs(v2) do
-- print("Copy: ",k,k2,k3,v3)
trueobject[k2][k3]=v3
end
end
end
trueobject.destructor = class.Destructor
trueobject.class=class
trueobject.actclass=actclass
local name=trueobject.Name
local clmeta = {
__index = function(s,k) return ClassIndex(trueobject,obj,k) end,
__newindex = function(s,k,v) return ClassNewIndex(trueobject,obj,k,v) end,
__call = function(s,...) if class.Methods.ONCALL then return class.Methods.ONCALL.Value(obj,...) else error("Class has no \"OnCall\" method") end end,
__len = function(s,...) if class.Methods.__LENGTH then return class.Methods.__LENGTH.Value(obj,...) else error("Class has no \"__Length\" method") end end,
__pairs = function(s) if class.Methods.__PAIRS then return class.Methods.__PAIRS.Value(obj)() else error("Class has no \"__Pairs\" method") end end,
__ipairs = function(s) if class.Methods.__IPAIRS then return class.Methods.__IPAIRS.Value(obj)() else error("Class has no \"__IPairs\" method") end end,
__gc = function(s,...) if trueobject.destructor then if destructorwarn then destructorwarnings=destructorwarnings+1 print("\007WARNING! Destructor call!",destructorwarnings,name) end trueobject.destructor.Value(s) end end
}
if nodestructor then
if trueobject.destructor then
clmeta.__gc = function(s)
if destructorwarn then
destructorwarnings=destructorwarnings+1
print("\007WARNING! Destructor call! Please note that destructors are now ignored!",destructorwarnings,name)
end
end
else
clmeta.__gc = nil
end
end
obj = setmetatable({},clmeta)
if trueobject.class.Constructor then
trueobject.AllowReadOnly = true
trueobject.class.Constructor.Value(obj,...)
trueobject.AllowReadOnly = false
end
return obj
end
local function ClassStaticIndex(class,actclass,k)
ClassStaticConstructorCall(class,actclass)
if type(k)=="number" then
return ClassStaticIndex(class,actclass,"__NumberIndex")(k)
end
if k==".neilclass" then
return true
elseif k==".hasmember" then
return function (m)
m = m:upper()
if class.Members[m] then return "Member","Regular" end
if class.StaticMembers[m] then return "Member","Static" end
if class.GetProperties[m] or class.SetProperties[m] then return "Property","Regular" end
if class.StaticGetProperties[m] or class.StaticSetProperties[m] then return "Property","Static" end
if class.AbstractGetProperties[m] or class.AbstractSetProperties[m] then return "Property","Abstract" end
if class.Methods[m] then return "Method","Regular" end
if class.StaticMethods[m] then return "Method","Static" end
if class.AbstractMethods[m] then return "Method","Abstract" end
return nil,nil
end
elseif k==".invoke" then
return function(m,...)
if class.StaticMethods[m] then
return true,class.StaticMethods[uk].TrueMethod(...)
end
return false
end
elseif Globals.PREFIXED.Value(k,".") then
error("Command field unknown: "..k)
else
local uk = k:upper(0)
if class.Members[uk] or class.GetProperties[uk] or class.Methods[uk] then error("Member "..k.." is not static\n\n"..debug.traceback()) end
if class.StaticMembers[uk] then return class.StaticMembers[uk].Value end
if class.StaticMethods[uk] then
-- for k,v in pairs(class.StaticMethods[uk]) do print(type(v),k) end
-- for k,v in pairs(actclass) do print("Class:",type(v),k) end
class.StaticMethods[uk].TrueMethod = class.StaticMethods[uk].TrueMethod or function(...) return class.StaticMethods[uk].Value(actclass.Value,...) end
return class.StaticMethods[uk].TrueMethod
end
if class.StaticGetProperties[uk] then
-- for k,v in pairs(actclass) do print("(Set)Class:",type(v),k) end
return class.StaticGetProperties[uk].Value(actclass.Value)
end
if class.StaticSetProperties[uk] then error("Property '"..k.."' is only configured for writing\n"..debug.traceback()) end -- Safe... The SET has already been acted upon if it exists, and this function was exited!
error("No static member named '"..k.."' present")
-- error("Temp Static index error: "..k.." code not yet fully up to date to deal with this request! That's WIP for ya!")
end
end
local function ClassStaticNewIndex(class,actclass,k,v)
ClassStaticConstructorCall(class,actclass)
if type(k)=="number" then
ClassStaticIndex(class,actclass,"__NumberNewIndex")(k,v)
return
end
if false then -- reserved section for system defintions inside the class
else
local uk = k:upper(0)
if class.Members[uk] or class.SetProperties[uk] or class.Methods[uk] then error("Member "..k.." is not static") end
if class.StaticMembers[uk] then
local m = class.StaticMembers[uk]
if m.Value~=v then -- Prevent some "readonly" issues with += and -=! If the value (which can also be a pointer) reamins the same no complaints!
if m.Constant then error("Cannot write to constant member: "..k) end
if m.ReadOnly and (not class.AllowReadOnly) then error("Cannot write to read-only member: "..k) end
m.Value = ConvType(v,m.Type,"Class member "..k)
end
return
end
if class.StaticMethods[uk] then error("Cannot overwrite static methods") end
if class.StaticSetProperties[uk] then
-- for k,v in pairs(actclass) do print("(Set)Class:",type(v),k) end
class.StaticSetProperties[uk].Value(actclass.Value,v) return
end
if class.StaticGetProperties[uk] then error("Property '"..k.."' is only configured for reading\n"..debug.traceback()) end -- Safe... The SET has already been acted upon if it exists, and this function was exited!
error("No static member named '"..k.."' present")
-- error("Temp Static newindex error: "..k.." code not yet fully up to date to deal with this request! That's WIP for ya!")
end
end
function ClassIndex(trueobject,self,k)
if type(k)=="number" then
return ClassIndex(trueobject,self,"__NumberIndex")(k)
end
if k:lower()==".neilclass" then
return true
elseif k:lower()==".neilclassobject" then
return true
elseif k:lower()==".hasmember" then
local check = function(key)
local fstatic = ClassStaticIndex(trueobject.class,trueobject.actclass,".hasmember")
return fstatic(key)
end
-- print(type(check).." returned!") -- DEBUG!!!
return check
elseif k:lower()==".invoke" then
return function(fun,...)
if trueobject.class.Methods[uk] then
return true,trueobject.class.Methods[uk].Value(self,...)
else
return false
end
end
elseif k:lower()==".fromclass" then
return trueobject.class
elseif Globals.PREFIXED.Value(k,".") then
error("No system property known for "..k)
end
local what,ctype = ClassStaticIndex(trueobject.class,trueobject.actclass,".hasmember")(k) -- trueobject.class[".hasmember"](key)
assert(what,"Object has no member named "..k)
if ctype=="Static" then
return trueobject.actclass.Value[k]
end
local uk = k:upper()
if trueobject.class.Members[uk] then return trueobject[uk].Value end
if trueobject.class.Methods[uk] then return function(...) return trueobject.class.Methods[uk].Value(self,...) end end
if trueobject.class.GetProperties[uk] then return trueobject.class.GetProperties[uk].Value(self) end
if trueobject.class.SetProperties[uk] then error("Property "..k.." appears to be write-only") end
error("No member named '"..k.."' present") -- Should never happen, but just in case!
end
function ClassNewIndex(trueobject,self,key,value)
if type(key)=="number" then
ClassIndex(trueobject,self,"__NumberNewIndex")(key,value)
return
end
local lk,uk = key:lower(),key:upper()
if false then -- reserved for system functionality later
elseif Globals.PREFIXED.Value(key,".") then
error("No system property known for "..key)
end
local what,ctype = trueobject.actclass.Value[".hasmember"](key)
assert(what,"Object has no member named "..key)
if ctype=="Static" then
trueobject.actclass.Value[key] = value
return
end
if trueobject.class.Members[uk] then
if trueobject[uk].Value~=value then -- Prevent some "readonly" issues with += and -=! If the value (which can also be a pointer) reamins the same no complaints!
if trueobject.class.Members[uk].Constant then error("Constants cannot be overwritten") end -- should be impossible, as constants are ALWAYS static, but when some clever whizkids break in, this measure is at least taken!
if trueobject.class.Members[uk].ReadOnly and (not trueobject.AllowReadOnly) then error("You cannot overwrite read-only values") end
-- for k,v in pairs(trueobject) do print("uk = "..uk,"key = "..k,type(v),value) end
trueobject[uk].Value = value
end
return
end
if trueobject.class.Methods[uk] then error("Methods cannot be overwritten") end
if trueobject.class.SetProperties[uk] then return trueobject.class.SetProperties[uk].Value(self,value) end
if trueobject.class.GetProperties[uk] then error("Property "..uk.." appears to be read-only") end
error("No member named '"..key.."' present") -- Should never happen, but just in case!
end
-- Classes Creation
local Class = {}
_Neil.Class = setmetatable({},{
__index=function(s,k)
if Class[k] then return Class[k] end
_Neil.Error(_Neil..".Class does not have a member named: "..k)
end,
__newindex=function()
error("READ-ONLY OVERWRITE ALERT!")
end
})
local GroupClasses = {}
function Class.Create(name,private,extend)
local ret = {}
ret.Name = name
ret.Class = { Members={}, Methods={}, GetProperties={},SetProperties={}, AbstractMethods={}, AbstractGetProperties={}, AbstractSetProperties={}, StaticMembers={}, StaticMethods={},StaticGetProperties={},StaticSetProperties={},Final={},Base={}, Extends=extend }
ret.Base = ret.Class.Base
ret.Final = ret.Class.Final
ret.Type = "class"
ret.Constant = true
ret.Value = setmetatable({},{
__call=function(s,...)
return ClassNew(ret.Class,ret,...)
end,
__index=function(s,k) return ClassStaticIndex(ret.Class,ret,k) end,
__newindex=function(s,k,v) return ClassStaticNewIndex(ret.Class,ret,k,v) end,
__len=function(s) return ClassStaticIndex(ret.Class,ret,"__LENGTH")() end
})
if private then
GroupClasses[name]=ret
else
if not _Neil.Assert(Globals[name:upper()]=="PLACEHOLDER","I cannot create a class named "..name) then return nil end
Globals[name:upper()] = ret
if extend then
extend = extend:upper()
if not Globals[extend] then
error("Request to extend a non-existent class! >> "..extend)
end
if Globals[extend].Type~="class" then
error("Tried to extend a non-class >> "..extend.." (that is a "..tostring(Globals[extend].Type)..")") -- tostring is to prevent unexplainable errors when 'nil' was given, which is by abusing Neil possible.
end
local base = Globals[extend]
for _,k in pairs { "Members", "Methods", "GetProperties", "SetProperties" } do
for iname,data in pairs(base.Class[k]) do
if data.final and k=="Members" then
ret.Class.Final[iname] = true
else
ret.Class.Base[iname]= ret.Class.Base[iname] or {tpe=k,dat=data}
if k=="GetProperties" or k=="SetProperties" then ret.Class.Base[iname].tpe="Properties" ret.Class.Base[iname][k]=false end
end
--print("Copying",k,iname,"from",extend,"into",name:upper(),type(data)) -- DEBUG ONLY!!!
ret.Class[k][iname]=data
end
for iname,data in pairs(base.Class["Abstract"..k] or {} ) do
ret.Base[iname]={tpe=k,dat=data,abstract=true}
ret.Class["Abstract"..k][iname]=true
end
for iname,data in pairs(base.Class["Static"..k]) do
ret.Class.Final[iname]=true
ret.Class["Static"..k][iname] = data
end
end
end
-- for k,v in pairs(Globals) do print(type(v),k) end -- debug
end
end