-
Notifications
You must be signed in to change notification settings - Fork 12
/
nimLUA.nim
2337 lines (1963 loc) · 80.2 KB
/
nimLUA.nim
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
# nimLUA
# glue code generator to bind Nim and Lua together using Nim's powerful macro
#
# Copyright (c) 2015 Andri Lim
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in 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:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# 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
# AUTHORS 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 IN
# THE SOFTWARE.
#
#
#-------------------------------------
import macros, nimLUA/lua, strutils
export lua, macros
type
BindKind* = enum
isNothing
isClosure
isDestructor
bindDesc* = ref object
node*: NimNode #this is nnkSym or nnkClosedSymChoice node generated by bindSym,
# bindXXXImpl will then use getImpl to get the AST body of proc/const/enum/etc implementation
name*: string #newname that will be exported, taken from abc -> "newname", or oldname if no newname supplied
lhsKind*: NimNodeKind #op '->' lhs kind, it could be nnkIdent or nnkAccQuoted
rhsKind*: NimNodeKind #op '->' rhs kind, it could be nnkNone or nnkStrLit or nnkIdent
bindKind*: BindKind
genericParams*: seq[NimNode]
propDesc = tuple [
node: string,
name: string,
lhsKind: NimNodeKind,
getter: bool,
setter: bool
]
proxyDesc* = object
luaCtx* : string
libName* : NimNode
subject* : NimNode
bindList*: seq[bindDesc]
symList* : seq[NimNode]
propList*: seq[propDesc]
argDesc = object
mName, mType, mVal: NimNode
bindFlag = enum
nlbUseLib
nlbRegisterObject
nlbRegisterClosure
nlbRegisterGeneric
bindFlags = set[bindFlag]
ovProcElem = ref object
retType: NimNode
params: seq[argDesc]
ovProc = ref object
numArgs: int
procs: seq[ovProcElem]
ovList = seq[ovProc]
ovFlag = enum
ovfUseObject
ovfUseRet
ovfConstructor
ovFlags = set[ovFlag]
nlOptions* = enum
nloNone
nloDebug
nloAddMember
NLError* = object
source: string
currentLine: int
msg: string
NLErrorFunc* = proc(ctx: pointer, err: NLError) {.nimcall.}
let globalClosure {.compileTime.} = "_gCLV"
const
IDRegion = 0xEF
IDErrorContext = IDRegion - 1
IDErrorFunc = IDRegion - 2
NLMaxID* = 0xFFF
template luaError*(x: PState, m: string): untyped =
lua.error(x, m)
template newuserdata*(L: PState, sz: int): pointer =
newuserdata(L, sz.csize_t)
template pushlstring*(L: PState, s: cstring, len: int): cstring =
pushlstring(L, s, len.csize_t)
proc isStrictString*(L: PState, idx: int): bool {.inline.} =
luaType(L, idx.cint) == LUA_TSTRING.cint
#counter that will be used to generate unique intermediate macro name
#and avoid name collision
var
macroCount {.compileTime.} = 0
proxyCount {.compileTime.} = 0
regsCount {.compileTime.} = 0
nameList {.compileTime.} = newSeq[string]()
outValList {.compileTime.} : seq[string]
gContext {.compileTime.} = ""
gOptions {.compileTime.} = {nloAddMember}
objectMTList {.compileTime.} = newSeq[string]()
proc convOpt(a: NimNode): nlOptions {.compileTime.} =
case $a:
of "nloDebug": result = nloDebug
of "nloAddMember": result = nloAddMember
else: result = nloNone
macro nimLuaOptions*(opt: nlOptions, mode: bool): untyped =
if $mode == "true":
gOptions.incl convOpt(opt)
else:
gOptions.excl convOpt(opt)
result = newEmptyNode()
proc toString(c: LUA_TYPE): string =
const typeName = ["NIL", "BOOLEAN", "LIGHTUSERDATA", "NUMBER", "STRING",
"TABLE", "FUNCTION", "USERDATA", "THREAD", "NUMTAGS"]
if c in {LNIL..LNUMTAGS}:
return typeName[ord(c)]
elif c == LNONE:
return "NONE"
else:
return "INVALID"
proc nimDebug(L: PState, idx: cint, eType: string) =
var dbg: TDebug
if L.getStack(1, dbg.addr) != 0:
if L.getInfo("Sln", dbg.addr) != 0:
let gType = L.getType(idx).toString()
let err = NLError(source: $dbg.source, currentLine: dbg.currentLine,
msg: "expected `$1`, got `$2`" % [eType, $gType])
L.pushLightUserData(cast[pointer](IDErrorContext))
L.rawGet(LUA_REGISTRYINDEX) # get correct error context
let errCtx = L.toUserData(-1)
L.pushLightUserData(cast[pointer](IDErrorFunc))
L.rawGet(LUA_REGISTRYINDEX) # get correct error function
let errFunc = cast[NLErrorFunc](L.toUserData(-1))
L.pop(2)
errFunc(errCtx, err)
#inside macro, const bool become nnkIntLit, that's why we need to use
#this trick to test for bool type using 'when internalTestForBOOL(n)'
proc internalTestForBOOL*[T](a: T): bool {.compileTime.} =
when a is bool: result = true
else: result = false
proc parseCode(s: string): NimNode {.compileTime.} =
result = parseStmt(s)
if nloDebug in gOptions: echo s
#flatten formal param into seq
proc paramsToArgListBasic(params: NimNode, start = 1): seq[argDesc] {.compileTime.} =
var argList = newSeq[argDesc]()
for i in start..params.len-1:
let arg = params[i]
let mType = arg[arg.len - 2]
let mVal = arg[arg.len - 1]
for j in 0..arg.len-3:
argList.add(argDesc(mName: arg[j], mType: mType, mVal: mVal))
result = argList
proc paramsToArgList(params: NimNode, subs: seq[NimNode], templateParam: NimNode): seq[argDesc] {.compileTime.} =
var p = paramsToArgListBasic(params)
for i in 0..templateParam.len-1:
for j in 0..p.len-1:
if p[j].mType.kind == nnkVarTy:
if p[j].mType[0].kind == nnkBracketExpr:
if $p[j].mType[0][1] == $templateParam[i]:
if i < subs.len: p[j].mType[0][1] = subs[i]
else:
if $p[j].mType[0] == $templateParam[i]:
if i < subs.len: p[j].mType[0] = subs[i]
else:
if $p[j].mType == $templateParam[i]:
if i < subs.len: p[j].mType = subs[i]
result = p
proc replaceRet(ret: NimNode, subs: seq[NimNode], templateParam: NimNode): NimNode {.compileTime.} =
for i in 0..templateParam.len-1:
if ret.kind != nnkEmpty:
if $ret == $templateParam[i]:
if i < subs.len: return subs[i]
result = ret
proc newBindDesc*(node: NimNode, name: string, lhsKind, rhsKind: NimNodeKind,
kind = isNothing, genericParams: seq[NimNode] = @[]): bindDesc {.compileTime.} =
new(result)
result.node = node
result.name = name
result.lhsKind = lhsKind
result.rhsKind = rhsKind
result.bindKind = kind
result.genericParams = genericParams
proc collectGenericParam(p: bindDesc, n: NimNode) {.compileTime.} =
for i in 1..n.len-1:
p.genericParams.add n[i]
#split something like 'ident -> "newName"' into tuple
proc splitElem(n: NimNode, opts: bindFlags, proxyName: string): bindDesc {.compileTime.} =
let
op = n[0]
lhs = n[1]
rhs = n[2]
registerObject = nlbRegisterobject in opts
registerClosure = nlbRegisterClosure in opts
registerGeneric = nlbRegisterGeneric in opts
if $op != "->":
error("wrong operator, must be '->' and not '" & $op & "'")
if lhs.kind notin {nnkIdent, nnkAccQuoted, nnkCall, nnkBracket, nnkBracketExpr}:
error("param must be an identifier and not " & $lhs.kind)
if not registerObject and lhs.kind == nnkCall:
error("getter/setter not available in bind$1" % [proxyName])
if not registerClosure and lhs.kind == nnkBracket:
error("closure not available in bind$1" % [proxyName])
if not registerGeneric and lhs.kind == nnkBracketExpr:
error("generic not available in bind$1" % [proxyName])
if rhs.kind notin {nnkStrLit, nnkIdent}:
error("alias must be string literal and not " & $rhs.kind)
if lhs.kind == nnkAccQuoted:
result = newBindDesc(lhs[0], $rhs, lhs.kind, rhs.kind)
elif lhs.kind == nnkBracket:
if lhs[0].kind == nnkAccQuoted:
result = newBindDesc(lhs[0][0], $rhs, lhs[0].kind, rhs.kind, isClosure)
else:
result = newBindDesc(lhs[0], $rhs, lhs.kind, rhs.kind, isClosure)
elif lhs.kind == nnkBracketExpr:
if lhs[0].kind == nnkAccQuoted:
result = newBindDesc(lhs[0][0], $rhs, lhs[0].kind, rhs.kind)
else:
result = newBindDesc(lhs[0], $rhs, lhs.kind, rhs.kind)
collectGenericParam(result, lhs)
else:
result = newBindDesc(lhs, $rhs, lhs.kind, rhs.kind)
#helper proc to flatten nnkStmtList
proc unwindList(arg: NimNode, elemList: var seq[bindDesc], opts: bindFlags, proxyName: string) {.compileTime.} =
let
registerObject = nlbRegisterobject in opts
registerClosure = nlbRegisterClosure in opts
registerGeneric = nlbRegisterGeneric in opts
for i in 0..arg.len-1:
let n = arg[i]
case n.kind:
of nnkIdent:
let elem = newBindDesc(n, $n, n.kind, nnkNone)
elemList.add elem
of nnkAccQuoted:
let elem = newBindDesc(n[0], "`" & $n[0] & "`", n.kind, nnkNone)
elemList.add elem
of nnkInfix:
elemList.add splitElem(n, opts, proxyName)
of nnkCall:
if not registerObject:
error("getter/setter not available in bind$1" % [proxyName])
let elem = newBindDesc(n, $n[0], n.kind, nnkNone)
elemList.add elem
of nnkBracket:
if not registerClosure:
error("closure not available in bind$1" % [proxyName])
let elem = if n[0].kind == nnkAccQuoted:
newBindDesc(n[0][0], "`" & $n[0][0] & "`", n[0].kind, nnkNone, isClosure)
else:
newBindDesc(n[0], $n[0], n.kind, nnkNone, isClosure)
elemList.add elem
of nnkBracketExpr:
if not registerGeneric:
error("generic not available in bind$1" % [proxyName])
let elem = if n[0].kind == nnkAccQuoted:
newBindDesc(n[0][0], "`" & $n[0][0] & "`", n[0].kind, nnkNone)
else:
newBindDesc(n[0], $n[0], n.kind, nnkNone)
collectGenericParam(elem, n)
elemList.add elem
of nnkPrefix:
if $n[0] != "~": error("only `~` prefix supported", n[0])
let elem = newBindDesc(n[1], "__gc", n.kind, nnkNone, isDestructor)
elemList.add elem
else:
error("wrong param type: $1, $2 not allowed here" % [$n.kind, n.toStrLit().strVal], n)
proc checkDuplicate(list: seq[bindDesc]): string {.compileTime.} =
var checked = newSeq[bindDesc]()
for k in list:
if checked.contains(k):
return $k.node
else:
checked.add k
result = ""
#here is the factory of second level macro that will be expanded to utilize bindSym
proc genProxyMacro(arg: NimNode, opts: bindFlags, proxyName: string): NimNode {.compileTime.} =
let
useLib = nlbUseLib in opts
registerObject = nlbRegisterobject in opts
registerClosure = nlbRegisterClosure in opts
registerGeneric = nlbRegisterGeneric in opts
var
luaCtx = ""
libName = ""
libKind: NimNodeKind
objectName = ""
objectNewName = ""
elemList = newSeq[bindDesc]()
propList = newSeq[propDesc]()
for i in 0..arg.len-1:
let n = arg[i]
case n.kind
of nnkSym:
if i == 0: luaCtx = $n
else:
error("param " & $i & " must be an identifier, not symbol\n" & arg.treeRepr)
of nnkStrLit:
if i == 1 and useLib:
libName = n.strVal
libKind = n.kind
else:
let msg = "bind$1, param: $2" % [proxyName, n.toStrLit().strVal]
error("param " & $i & " must be an identifier, not string literal\n" & msg, n)
of nnkIdent:
if i == 1 and $n == "GLOBAL" and useLib:
libName = $n
libKind = n.kind
elif i == 1 and registerObject:
objectName = $n
objectNewName = $n
else:
let elem = newBindDesc(n, $n, n.kind, nnkNone)
elemList.add elem
of nnkAccQuoted:
let elem = newBindDesc(n[0], "`" & $n[0] & "`", n.kind, nnkNone)
elemList.add elem
of nnkInfix:
if registerObject and i == 1:
let k = splitElem(n, opts, proxyName)
objectName = $k.node
objectNewName = k.name
else:
elemList.add splitElem(n, opts, proxyName)
of nnkCall:
if not registerObject:
error("getter/setter not available in bind$1" % [proxyName])
let elem = newBindDesc(n, $n[0], n.kind, nnkNone)
elemList.add elem
of nnkBracket:
if not registerClosure:
error("closure not available in bind$1" % [proxyName])
let elem = if n[0].kind == nnkAccQuoted:
newBindDesc(n[0][0], "`" & $n[0][0] & "`", n[0].kind, nnkNone, isClosure)
else:
newBindDesc(n[0], $n[0], n.kind, nnkNone, isClosure)
elemList.add elem
of nnkBracketExpr:
if not registerGeneric:
error("generic not available in bind$1" % [proxyName])
let elem = if n[0].kind == nnkAccQuoted:
newBindDesc(n[0][0], "`" & $n[0][0] & "`", n[0].kind, nnkNone)
else:
newBindDesc(n[0], $n[0], n.kind, nnkNone)
collectGenericParam(elem, n)
elemList.add elem
of nnkStmtList:
unwindList(n, elemList, opts, proxyName)
of nnkPrefix:
if $n[0] != "~": error("only `~` prefix supported", n[0])
let elem = newBindDesc(n[1], "__gc", n.kind, nnkNone, isDestructor)
elemList.add elem
else:
error("wrong param type\n" & n.treeRepr, n)
if luaCtx == "":
error("need luaState as first param")
let dup = elemList.checkDuplicate()
if dup != "":
error("bind$1 detected duplicated entries: $2" % [proxyName, dup])
#generate intermediate macro to utilize bindSym that can only accept string literal
let macroName = "NLB$1$2" % [proxyName, $macroCount]
var nlb = "macro " & macroName & "(): untyped =\n"
nlb.add " var ctx: proxyDesc\n"
nlb.add " ctx.luaCtx = \"$1\"\n" % [luaCtx]
if registerObject:
nlb.add " ctx.subject = bindSym\"$1\"\n" % [objectName]
else:
nlb.add " ctx.subject = newEmptyNode()\n"
var numElem = 0
for k in elemList:
if k.node.kind in {nnkAccQuoted, nnkIdent}:
inc numElem
elif k.node.kind == nnkCall:
var v = if k.node[0].kind == nnkAccQuoted:
(node: $k.node[0][0], name: "`" & $k.node[0][0] & "`", lhsKind: k.node[0].kind, getter: false, setter: false)
else:
(node: $k.node[0], name: $k.node[0], lhsKind: k.node[0].kind, getter: false, setter: false)
if k.rhsKind in {nnkStrLit, nnkIdent}: v.name = k.name
for i in 1..k.node.len-1:
let n = k.node[i]
if n.kind != nnkIdent: error(v.node & ": getter/setter attribut must be identifier")
if $n == "get": v.getter = true
elif $n == "set": v.setter = true
else: error(v.node & ": getter/setter attribute must be 'get' and/or 'set'")
if v.getter == false and v.setter == false: error(v.node & ": getter/setter attribute must be present")
propList.add v
else:
error("unexpected node kind: " & $k.node.kind)
if numElem > 0:
nlb.add " ctx.bindList = @[\n"
var i = 0
for k in elemList:
let comma = if i < numElem: "," else: ""
if k.node.kind in {nnkAccQuoted, nnkIdent}:
var gp = ""
if k.genericParams.len > 0:
gp.add "@["
var ii = 0
for x in k.genericParams:
let cma = if ii < k.genericParams.len-1: "," else: ""
gp.add "bindSym\"$1\"$2" % [$x, cma]
inc ii
gp.add "]"
else:
gp.add "newSeq[NimNode]()"
nlb.add " newBindDesc(bindSym\"$1\", \"$2\", $3, $4, $5, $6)$7\n" %
[$k.node, k.name, $k.lhsKind, $k.rhsKind, $k.bindKind, gp, comma]
inc i
nlb.add " ]\n"
else:
nlb.add " ctx.bindList = @[]\n"
if propList.len > 0:
nlb.add " ctx.propList = @[\n"
var ii = 0
for k in propList:
let comma = if ii < propList.len-1: "," else: ""
nlb.add " (\"$1\", \"$2\", $3, $4, $5)$6\n" %
[k.node, k.name, $k.lhsKind, $k.getter, $k.setter, comma]
inc ii
nlb.add " ]\n"
else:
nlb.add " ctx.propList = @[]\n"
if libKind == nnkStrLit:
nlb.add " ctx.libName = newStrLitNode(\"$1\")\n" % [libName]
elif libKind == nnkIdent:
nlb.add " ctx.libName = newIdentNode(\"$1\")\n" % [libName]
elif registerObject:
nlb.add " ctx.libName = newIdentNode(\"$1\")\n" % [objectNewName]
else:
nlb.add " ctx.libName = newEmptyNode()\n"
nlb.add " result = proxyMixer(ctx, \"$1\")\n" % [proxyName]
nlb.add macroName & "()\n"
result = parseCode(nlb)
inc macroCount
#both normal ident and backticks quoted ident converted to string
proc getAccQuotedName(n: NimNode, kind: NimNodeKind): string {.compileTime.} =
let name = if n.kind == nnkClosedSymChoice: $n[0] else: $n
if kind == nnkAccQuoted: result = "`" & name & "`" else: result = name
proc getAccQuotedName(name: string, kind: NimNodeKind): string {.compileTime.} =
if kind == nnkAccQuoted: result = "`" & name & "`" else: result = name
proc ignoreGenerics(ids: var seq[string], id: string, generics: NimNode) {.compileTime.} =
var found = false
if generics.kind == nnkGenericParams:
for k in generics:
if $k == id:
found = true
break
if not found: ids.add id
proc collectSym(ids: var seq[string], arg: NimNode) {.compileTime.} =
if arg.kind == nnkProcDef:
let generics = arg[2]
let params = arg[3]
let retType = params[0]
let argList = paramsToArgListBasic(params)
if retType.kind == nnkIdent: ignoreGenerics(ids, $retType, generics)
for k in argList:
if k.mType.kind == nnkIdent: ignoreGenerics(ids, $k.mType, generics)
if k.mVal.kind == nnkIdent: ignoreGenerics(ids, $k.mVal, generics)
proc checkProp(subject: NimNode, prop: string): bool {.compileTime.} =
let parent = if subject.kind == nnkRefTy: subject[0][1] else: subject[1]
if parent.kind == nnkOfInherit:
let parentName = parent[0]
var t = getTypeImpl(parentName)
if t.kind == nnkRefTy: t = getTypeImpl(t[0])
if checkProp(t, prop): return true
let recList = if subject.kind == nnkRefTy: subject[0][2] else: subject[2]
if recList.kind == nnkEmpty: return false
for n in recList:
for i in 0..n.len-3:
let k = n[i]
if k.kind in {nnkIdent, nnkSym}:
if $k == prop: return true
elif k.kind == nnkPostfix:
if $k[1] == prop: return true
else:
error("unknown prop construct")
result = false
proc checkObject(subject: NimNode): bool {.compileTime.} =
if subject[2].kind == nnkDistinctTy:
return subject[2][0].kind == nnkSym and $subject[2][0] == "pointer"
result = subject[2].kind in {nnkObjectTy, nnkRefTy}
proc proxyMixer*(ctx: proxyDesc, proxyName: string): NimNode {.compileTime.} =
var ids = newSeq[string]()
for n in ctx.bindList:
if n.node.kind == nnkSym:
let im = getImpl(n.node)
collectSym(ids, im)
else:
for s in children(n.node):
let im = getImpl(s)
collectSym(ids, im)
let macroName = "NLB$1$2" % [proxyName, $macroCount]
var nlb = "macro " & macroName & "(): untyped =\n"
nlb.add " var ctx: proxyDesc\n"
nlb.add " ctx.luaCtx = \"$1\"\n" % [ctx.luaCtx]
if ctx.subject.kind == nnkSym:
let subject = getImpl(ctx.subject)
if not checkObject(subject):
error($ctx.subject & ": not an object")
nlb.add " ctx.subject = bindSym\"$1\"\n" % [$ctx.subject]
else:
nlb.add " ctx.subject = newEmptyNode()\n"
if ctx.bindList.len > 0:
nlb.add " ctx.bindList = @[\n"
var i = 0
for k in ctx.bindList:
var gp = ""
if k.genericParams.len > 0:
gp.add "@["
var ii = 0
for x in k.genericParams:
let cma = if ii < k.genericParams.len-1: "," else: ""
gp.add "bindSym\"$1\"$2" % [$x, cma]
inc ii
gp.add "]"
else:
gp.add "newSeq[NimNode]()"
let comma = if i < ctx.bindList.len-1: "," else: ""
nlb.add " newBindDesc(bindSym\"$1\", \"$2\", $3, $4, $5, $6)$7\n" %
[$k.node, k.name, $k.lhsKind, $k.rhsKind, $k.bindKind, gp, comma]
inc i
nlb.add " ]\n"
else:
nlb.add " ctx.bindList = @[]\n"
if ctx.propList.len > 0:
nlb.add " ctx.propList = @[\n"
var ii = 0
let subject = getImpl(ctx.subject)
for k in ctx.propList:
if not checkProp(subject[2], k.node):
error($ctx.subject & ": don't have properties " & k.name)
let comma = if ii < ctx.propList.len-1: "," else: ""
nlb.add " (\"$1\", \"$2\", $3, $4, $5)$6\n" %
[k.node, k.name, $k.lhsKind, $k.getter, $k.setter, comma]
inc ii
nlb.add " ]\n"
else:
nlb.add " ctx.propList = @[]\n"
if ids.len > 0:
nlb.add " ctx.symList = @[\n"
var i = 0
for k in ids:
let comma = if i < ids.len-1: "," else: ""
nlb.add " bindSym\"$1\"$2\n" % [k, comma]
inc i
nlb.add " ]\n"
else:
nlb.add " ctx.symList = @[]\n"
if ctx.libName.kind == nnkStrLit:
nlb.add " ctx.libName = newStrLitNode(\"$1\")\n" % [$ctx.libName]
elif ctx.libName.kind == nnkIdent:
nlb.add " ctx.libName = newIdentNode(\"$1\")\n" % [$ctx.libName]
else:
nlb.add " ctx.libName = newEmptyNode()\n"
nlb.add " result = bind$1Impl(ctx)\n" % [proxyName]
nlb.add macroName & "()\n"
result = parseCode(nlb)
inc macroCount
#proc params and return type
proc newProcElem(retType: NimNode, params: seq[argDesc]): ovProcElem {.compileTime.} =
result = new(ovProcElem)
result.retType = retType
result.params = params
#list of overloaded proc
proc newOvProc(retType: NimNode, params: seq[argDesc]): ovProc {.compileTime.} =
var ovp = new(ovProc)
ovp.numArgs = params.len
ovp.procs = newSeq[ovProcElem]()
ovp.procs.add newProcElem(retType, params)
result = ovp
#add overloaded proc into ovList
proc addOvProc(ovl: var ovList, retType: NimNode, params: seq[argDesc]) {.compileTime.} =
var found = false
for k in ovl:
if k.numArgs == params.len:
k.procs.add newProcElem(retType, params)
found = true
break
if not found:
ovl.add newOvProc(retType, params)
proc isRefType(s: NimNode): bool {.compileTime.} =
let n = getImpl(s)
if n.kind != nnkTypeDef: return false
if n[2].kind != nnkRefTy: return false
result = true
proc isObjectType(s: NimNode): bool {.compileTime.} =
let n = getImpl(s)
if n.kind != nnkTypeDef: return false
if n[2].kind != nnkObjectTy: return false
result = true
proc hasName(name: string): bool {.compileTime.} =
for n in nameList:
if n == name: return true
result = false
proc setName(name: string) {.compileTime.} =
nameList.add(name)
proc registerObject(subject: NimNode): string {.compileTime.} =
let name = $subject
let prefixedName = "nlobj" & name
for i in 0..nameList.high:
if nameList[i] == prefixedName:
return name & $i
let subjectID = $nameList.len
let subjectName = name & subjectID
nameList.add prefixedName
objectMTList.add "$1.nimNewMetatable(NL_$2)\n" % ["$1", subjectName]
var glue = "const\n"
glue.add " NL_$1 = $2+$3\n" % [subjectName, $IDRegion, subjectID]
glue.add " NL_$1name = \"$2\"\n" % [subjectName, name]
glue.add "type\n"
glue.add " NL_$1Proxy = object\n" % [subjectName]
glue.add " ud: $1\n" % [name]
gContext.add glue
result = subjectName
proc genMetaTableList(SL: string): string {.compileTime.} =
result = ""
for n in objectMTList:
result.add(n % [SL])
objectMTList.setLen 0
proc checkUD(s, n: string): string {.compileTime.} =
result = "cast[ptr NL_$1Proxy](L.nimCheckUData($2.cint, NL_$1, NL_$1name))\n" % [s, n]
proc newUD(s: string): string {.compileTime.} =
result = "cast[ptr NL_$1Proxy](L.newUserData(sizeof(NL_$1Proxy)))\n" % [s]
proc addMemberCap(SL, libName: string, argLen: int): string {.compileTime.} =
when nloAddMember in gOptions:
var glue = ""
glue.add "$1.getGlobal(\"$2\")\n" % [SL, libName]
glue.add "if not $1.isTable(-1):\n" % [SL]
glue.add " $1.pop(1)\n" % [SL]
glue.add " $1.createTable(0.cint, $2.cint)\n" % [SL, $(argLen)]
return glue
else:
result = "$1.createTable(0.cint, $2.cint)\n" % [SL, $(argLen)]
proc addClosureEnv(SL, procName: string, n: NimNode, bd: bindDesc, ovIdx: int = 0): string {.compileTime.} =
var glue = ""
var params = copy(n[3])
params.add newIdentDefs(newIdentNode("clEnv"), bindSym"pointer")
let clv = params.toStrLit.strVal
glue.add "type clsTyp$1$2 = proc$3 {.nimCall.}\n" % [$proxycount, $ovIdx, clv]
glue.add "$1.getGlobal(\"$2\")\n" % [SL, globalClosure]
glue.add "if not $1.isTable(-1):\n" % [SL]
glue.add " $1.pop(1)\n" % [SL]
glue.add " $1.createTable(0.cint, 2.cint)\n" % [SL]
glue.add "$1.pushLiteral(\"$2$3env$4\")\n" % [SL, procName, $proxycount, $ovIdx]
glue.add "$1.pushLightUserData(rawEnv($2))\n" % [Sl, procName]
glue.add "$1.setTable(-3)\n" % [SL]
glue.add "$1.pushLiteral(\"$2$3proc$4\")\n" % [SL, procName, $proxycount, $ovIdx]
glue.add "$1.pushLightUserData(rawProc($2))\n" % [Sl, procName]
glue.add "$1.setTable(-3)\n" % [SL]
glue.add "$1.setGlobal(\"$2\")\n" % [SL, globalClosure]
result = glue
proc getClosureEnv(SL, procName: string, ovIdx: int): string {.compileTime.} =
var glue = ""
glue.add " $1.getGlobal(\"$2\")\n" % [SL, globalClosure]
glue.add " let clsTab = $1.getTop()\n" % [SL]
glue.add " $1.pushLiteral(\"$2$3env$4\")\n" % [SL, procName, $proxycount, $ovIdx]
glue.add " $1.getTable(clsTab)\n" % [SL]
glue.add " let clsEnv$2 = $1.toUserData(-1)\n" % [SL, $ovIdx]
glue.add " $1.pushLiteral(\"$2$3proc$4\")\n" % [SL, procName, $proxycount, $ovIdx]
glue.add " $1.getTable(clsTab)\n" % [SL]
glue.add " let clsProc$2 = cast[clsTyp$1$2]($3.toUserData(-1))\n" % [$proxyCount, $ovIdx, SL]
glue.add " $1.pop(3)\n" % [SL]
result = glue
proc nimLuaPanic(L: PState): cint {.cdecl.} =
echo "panic"
echo L.toString(-1)
L.pop(1)
return 0
proc stdNimLuaErrFunc(ctx: pointer, err: NLError) =
echo "$1:$2 warning: $3" % [err.source, $err.currentLine, err.msg]
proc NLSetErrorHandler*(L: PState, errFunc: NLErrorFunc) =
L.pushLightUserData(cast[pointer](IDErrorFunc))
L.pushLightUserData(cast[pointer](errFunc))
L.rawSet(LUA_REGISTRYINDEX)
proc NLSetErrorContext*(L: PState, errCtx: pointer) =
L.pushLightUserData(cast[pointer](IDErrorContext))
L.pushLightUserData(errCtx)
L.rawSet(LUA_REGISTRYINDEX)
#call this before you use this library
proc newNimLua*(readOnlyEnum = false): PState =
var L = newState()
L.openLibs
discard L.atPanic(nimLuaPanic)
L.NLSetErrorHandler(stdNimLuaErrFunc)
L.NLSetErrorContext(nil)
const roEnum = """
function readonlytable(table)
return setmetatable({}, {
__index = table,
__newindex = function(table, key, value) error("Attempt to modify read-only table") end,
__metatable = false
});
end
"""
const rwEnum = """
function readonlytable(table)
return table
end
"""
const metaMethods = """
function __nlbIndex(myobject, key)
local mytable = getmetatable(myobject)
local x = rawget(mytable, "_get_" .. key)
if x ~= nil then
return x(myobject)
else
return mytable[key]
end
end
function __nlbNewIndex(myobject, key, value)
local mytable = getmetatable(myobject)
local x = rawget(mytable, "_set_" .. key)
if x ~= nil then
x(myobject, value)
else
mytable[key] = value
end
end
"""
const
nimVer = "Nim = { major = $1, minor = $2, patch = $3 }" %
[$NimMajor, $NimMinor, $NimPatch]
discard L.doString(if readOnlyEnum: roEnum else: rwEnum)
discard L.doString(metaMethods)
discard L.doString(nimVer)
result = L
proc propsEnd*(L: PState) =
L.getGlobal("__nlbIndex")
L.setField(-2, "__index")
L.getGlobal("__nlbNewIndex")
L.setField(-2, "__newindex")
# -------------------------------------------------------------------------
# --------------------------------- bindEnum ------------------------------
# -------------------------------------------------------------------------
proc bindEnumScoped(SL: string, s: NimNode, scopeName: string, kind: NimNodeKind): string {.compileTime.} =
let x = getImpl(s)
var err = false
if x.kind != nnkTypeDef: err = true
if x[0].kind notin {nnkSym, nnkPragmaExpr}: err = true
if x[2].kind != nnkEnumTy: err = true
if err: error("bindEnum: incorrect enum definition")
var pureEnum = false
var enumName = ""
if x[0].kind == nnkPragmaExpr:
pureEnum = $x[0][1][0] == "pure"
if pureEnum:
if x[0][0].kind != nnkSym: error("wrong enum definition")
enumName = if kind == nnkAccQuoted: "`" & $x[0][0] & "`" else: $x[0][0]
else:
enumName = if kind == nnkAccQuoted: "`" & $x[0] & "`" else: $x[0]
let numEnum = x[2].len - 1
var glue = ""
glue.add "$1.getGlobal(\"readonlytable\")\n" % [SL]
glue.add addMemberCap(SL, scopeName, numEnum)
for i in 1..numEnum:
let
n = x[2][i]
sym = if n.kind == nnkAccQuoted: "`" & $n[0] & "`" else: $n
glue.add "discard $1.pushLString(\"$2\", $3)\n" % [SL, sym, $sym.len]
if pureEnum: glue.add "$1.pushInteger(lua_Integer($2.$3))\n" % [SL, enumName, sym]
else: glue.add "$1.pushInteger(lua_Integer($2))\n" % [SL, sym]
glue.add "$1.setTable(-3)\n" % [SL]
glue.add "discard $1.pcall(1, 1, 0)\n" % [SL]
glue.add "$1.setGlobal(\"$2\")\n" % [SL, scopeName]
result = glue
proc bindEnumGlobal(SL: string, s: NimNode, kind: NimNodeKind): string {.compileTime.} =
let x = getImpl(s)
var err = false
if x.kind != nnkTypeDef: err = true
if x[0].kind notin {nnkSym, nnkPragmaExpr}: err = true
if x[2].kind != nnkEnumTy: err = true
if err: error("bindEnum: incorrect enum definition")
var pureEnum = false
var enumName = ""
if x[0].kind == nnkPragmaExpr:
pureEnum = $x[0][1][0] == "pure"
if pureEnum:
if x[0][0].kind != nnkSym: error("wrong enum definition")
enumName = if kind == nnkAccQuoted: "`" & $x[0][0] & "`" else: $x[0][0]
else:
enumName = if kind == nnkAccQuoted: "`" & $x[0] & "`" else: $x[0]
let numEnum = x[2].len - 1
var glue = ""
for i in 1..numEnum:
let
n = x[2][i]
sym = if n.kind == nnkAccQuoted: "`" & $n[0] & "`" else: $n
if pureEnum: glue.add "$1.pushInteger(lua_Integer($2.$3))\n" % [SL, enumName, sym]
else: glue.add "$1.pushInteger(lua_Integer($2))\n" % [SL, sym]
glue.add "$1.setGlobal(\"$2\")\n" % [SL, sym]
result = glue
#this proc need to be exported because intermediate macro call this proc from
#callsite module
proc bindEnumImpl*(ctx: proxyDesc): NimNode {.compileTime.} =
let
SL = ctx.luaCtx
arg = ctx.bindList
var glue = ""
for i in 0..arg.len-1:
let n = arg[i]
if n.name == "GLOBAL" and n.rhsKind == nnkIdent: glue.add bindEnumGlobal(SL, n.node, n.lhsKind)
else: glue.add bindEnumScoped(SL, n.node, n.name, n.lhsKind)
result = parseCode(glue)
macro bindEnum*(arg: varargs[untyped]): untyped =
result = genProxyMacro(arg, {}, "Enum")
# -------------------------------------------------------------------------
# ----------------------------- bindFunction ------------------------------
# -------------------------------------------------------------------------
# these are runtime type check helper for each type
# supported by Nim and Lua
proc nimCheckString*(L: PState, idx: cint): string =
if L.isStrictString(idx): result = L.toString(idx)
else:
L.nimDebug(idx.cint, "string")
result = ""
proc nimCheckBool*(L: PState, idx: cint): bool =
if L.isBoolean(idx): result = if L.toBoolean(idx) == 0: false else: true
else:
L.nimDebug(idx.cint, "bool")
result = false
proc nimCheckInteger*(L: PState, idx: cint): int =
if L.isInteger(idx) != 0: result = L.toInteger(idx).int
else:
L.nimDebug(idx.cint, "int")
result = 0
proc nimCheckNumber*(L: PState, idx: cint): float64 =
if L.isNumber(idx) != 0: result = L.toNumber(idx).float64
else:
L.nimDebug(idx.cint, "float")
result = 0.0
proc nimCheckCstring*(L: PState, idx: cint): cstring =
if L.isStrictString(idx): result = L.toLString(idx, nil)
else:
L.nimDebug(idx.cint, "cstring")
result = nil
proc nimCheckChar*(L: PState, idx: cint): char =
if L.isInteger(idx) != 0: result = L.toInteger(idx).char
else: result = chr(0)
proc nimNewMetaTable*(L: PState, key: int) =
L.pushLightUserData(cast[pointer](key))
L.rawGet(LUA_REGISTRYINDEX)
if not L.isNil(-1): # name already in use?
L.pop(1)
return
L.pop(1) # pop nil
L.pushLightUserData(cast[pointer](key))
L.newTable() # create metatable
L.rawSet(LUA_REGISTRYINDEX)
proc nimGetMetaTable*(L: PState, key: int) =
L.pushLightUserData(cast[pointer](key))
L.rawGet(LUA_REGISTRYINDEX)
proc nimCheckUData*(L: PState, idx, key: int, name: string): pointer =
let p = L.toUserData(idx.cint)
if p != nil: #value is a userdata?
if L.getMetaTable(idx.cint) != 0.cint: #does it have a metatable?
L.pushLightUserData(cast[pointer](key))
L.rawGet(LUA_REGISTRYINDEX) # get correct metatable
if L.rawEqual(-1, -2) != 0.cint: # does it have the correct mt?
L.pop(2) # remove both metatables
return p
# else error