-
Notifications
You must be signed in to change notification settings - Fork 0
/
euwren.nim
1409 lines (1291 loc) · 52.9 KB
/
euwren.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
import macros
import strutils
import tables
import euwren/private/wren
#--
# Definitions
#--
type
RawVM* = ptr WrenVM
MethodSign = tuple[module, class, name: string, isStatic: bool]
ClassSign = tuple[module, name: string]
WrenType* = enum
wtBool = "bool"
wtNumber = "number"
wtForeign = "foreign"
wtList = "list"
wtNull = "null"
wtString = "string"
wtUnknown = "<wren type>"
WrenRef* = ref object
vm: Wren
handle: ptr WrenHandle
WrenValueKind = enum
wvkBool
wvkNumber
wvkString
wvkWrenRef
WrenValue = object
case kind: WrenValueKind
of wvkBool: boolVal: bool
of wvkNumber: numVal: float
of wvkString: strVal: string
of wvkWrenRef: wrenRef: WrenRef
ModuleVar = tuple[module, variable: string]
Wren* = ref object
## A Wren virtual machine used for executing code.
handle: RawVM
procWrite: proc (str: string)
procResolveModule: proc (importer, name: string): string
procLoadModule: proc (path: string): string
methods: Table[MethodSign, WrenForeignMethodFn]
classes: Table[ClassSign, WrenForeignClassMethods]
typeNames: Table[uint16, string]
parentTypeIds: Table[uint16, set[uint16]]
compileErrors: seq[WrenError]
rtError: WrenError
WrenErrorKind* = enum
weCompile ## A compilation error (eg. syntax error).
weRuntime ## A runtime error (eg. ``Fiber.abort()``).
WrenError* = object of CatchableError
## A Wren error. This is raised when an error occurs *inside the VM.*
module*: string
line*: int
message*: string
case kind*: WrenErrorKind
of weCompile: discard
of weRuntime:
stackTrace*: seq[tuple[module: string, line: int, message: string]]
proc `$`*(vm: Wren): string =
## Return a string representation of the Wren instance. Keep in mind this
## doesn't really hold much useful information.
result = "- Wren instance\n" &
"VM: " & $cast[int](vm.handle) & '\n'
proc raw*(vm: Wren): RawVM =
## Returns the raw VM from the Wren instance.
vm.handle
proc raw*(wr: WrenRef): ptr WrenHandle =
## Returns the raw WrenHandle.
wr.handle
proc newWren*(): Wren =
## Creates a new VM.
new(result) do (vm: Wren):
wrenFreeVM(vm.handle)
var config: WrenConfiguration
wrenInitConfiguration(addr config)
# debugging
config.writeFn = proc (vm: RawVM, text: cstring) {.cdecl.} =
cast[Wren](wrenGetUserData(vm)).procWrite($text)
config.errorFn = proc (vm: RawVM, ty: WrenErrorType, module: cstring,
line: cint, msg: cstring) {.cdecl.} =
var wvm = cast[Wren](wrenGetUserData(vm))
case ty
of WREN_ERROR_COMPILE:
var err = WrenError(
kind: weCompile,
module: $module,
line: line.int,
message: $msg
)
wvm.compileErrors.add(err)
of WREN_ERROR_RUNTIME:
var err = WrenError(
kind: weRuntime,
message: $msg
)
wvm.rtError = err
of WREN_ERROR_STACK_TRACE:
wvm.rtError.stackTrace.add((module: $module,
line: line.int,
message: $msg))
else: doAssert(false) # unreachable
# modules
config.loadModuleFn = proc (vm: RawVM, name: cstring): cstring {.cdecl.} =
let
source = cast[Wren](wrenGetUserData(vm)).procLoadModule($name)
cssource = alloc0((source.len + 1) * sizeof(char))
if source.len > 0:
cssource.copyMem(source[0].unsafeAddr, source.len * sizeof(char))
result = cast[cstring](cssource)
config.resolveModuleFn = proc (vm: RawVM, importer,
name: cstring): cstring {.cdecl.} =
let
source =
cast[Wren](wrenGetUserData(vm)).procResolveModule($importer, $name)
cssource = alloc0((source.len + 1) * sizeof(char))
if source.len > 0:
cssource.copyMem(source[0].unsafeAddr, source.len * sizeof(char))
result = cast[cstring](cssource)
else:
result = nil
# FFI
config.bindForeignMethodFn = proc (vm: RawVM, module: cstring,
class: cstring, isStatic: bool,
name: cstring): WrenForeignMethodFn
{.cdecl.} =
var wvm = cast[Wren](wrenGetUserData(vm))
let sign = ($module, $class, $name, isStatic).MethodSign
if sign in wvm.methods:
result = wvm.methods[sign]
else:
result = nil
config.bindForeignClassFn = proc (vm: ptr WrenVM, module: cstring,
class: cstring): WrenForeignClassMethods
{.cdecl.} =
var wvm = cast[Wren](wrenGetUserData(vm))
let sign = ($module, $class).ClassSign
if sign in wvm.classes:
result = wvm.classes[sign]
else:
result = WrenForeignClassMethods()
# memory
config.reallocateFn = proc (mem: pointer, newSize: csize): pointer {.cdecl.} =
result = realloc(mem, newSize.Natural)
result.handle = wrenNewVM(addr config)
wrenSetUserData(result.handle, cast[pointer](result))
result.procWrite = proc (str: string) =
stdout.write(str)
result.procLoadModule = proc (path: string): string =
result = ""
result.procResolveModule = proc (importer, name: string): string =
result = name
result.rtError = WrenError(kind: weRuntime)
proc onWrite*(vm: Wren, callback: proc (str: string)) =
## Sets the write callback for the VM. This callback is called when the Wren
## VM wants to print something out to the console. The default callback simply
## writes to stdout.
vm.procWrite = callback
proc onLoadModule*(vm: Wren, callback: proc (path: string): string) =
## Sets the load module callback for the VM. The callback is called when
## the VM occurs an ``import`` statement, and doesn't have the given module
## loaded yet. The callback should then return the source code of the module
## at ``path``. If the callback returns an empty string, a module that aborts
## the fiber will be loaded (using ``import`` will throw an error). The
## default implementation returns an empty string, so override this if you
## want imports to work.
vm.procLoadModule = callback
proc onResolveModule*(vm: Wren,
callback: proc (importer, name: string): string) =
## Sets the resolve module callback for the VM. The callback is called when
## the VM occurs an ``import`` statement, to resolve what module should
## actually be loaded. This is usually used to implement relative imports.
## If the callback returns an empty string, the VM will raise an error saying
## that the requested module could not be found. The default implementation
## simply returns ``name`` without any side effects.
vm.procResolveModule = callback
proc newRef(vm: Wren, handle: ptr WrenHandle): WrenRef =
## Create a new, Nim GC-managed WrenRef out of a raw WrenHandle pointer.
assert vm != nil
assert handle != nil
new(result) do (wref: WrenRef):
wrenReleaseHandle(wref.vm.handle, wref.handle)
result.vm = vm
result.handle = handle
#--
# Low-level APIs
#--
# Ultimately, you shouldn't need to use these APIs. They're inherently unsafe,
# and don't provide any guarantees or assertions. In fact, they're only a thin
# wrapper over the underlying Wren embedding API. They're exported only to
# make the high-level API possible.
# Use with care.
proc ensureSlots*(vm: RawVM, amount: int) =
wrenEnsureSlots(vm, amount.cint)
proc slotCount*(vm: RawVM): int =
wrenGetSlotCount(vm)
macro genericParam(T: typed, index: int): untyped =
## Get the generic param at position ``index`` from T.
result = T.getTypeInst[1][index.intVal.int]
macro genericParam(T: typed): untyped =
## Get the actual type behind T.
result = T.getTypeInst[1]
proc genTypeCheck(vm, ty, slot: NimNode): NimNode
macro checkType(vm, ty: typed, slot: int): untyped =
result = genTypeCheck(vm, ty, slot)
proc getWrenName(typeSym: NimNode): string
macro wrenName(ty: typed): untyped =
result = newLit(getWrenName(ty))
proc getSlotType*(vm: RawVM, slot: int): WrenType =
result = wrenGetSlotType(vm, slot.cint).WrenType
proc getSlotForeignId*(vm: RawVM, slot: int): uint16 =
result = cast[ptr uint16](wrenGetSlotForeign(vm, slot.cint))[]
proc getSlotTypeString*(vm: RawVM, slot: int): string =
let ty = vm.getSlotType(slot)
if ty != wtForeign: result = $ty
else:
let wvm = cast[Wren](wrenGetUserData(vm))
result = wvm.typeNames[vm.getSlotForeignId(slot)]
proc getSlotForeign*[T](vm: RawVM, slot: int): ptr T =
let raw = cast[ptr UncheckedArray[uint16]](wrenGetSlotForeign(vm, slot.cint))
result = cast[ptr T](raw[1].unsafeAddr)
proc getSlot*[T](vm: RawVM, slot: int): T =
when T is bool:
result = wrenGetSlotBool(vm, slot.cint)
elif T is SomeNumber:
result = T(wrenGetSlotDouble(vm, slot.cint))
elif T is enum:
result = T(wrenGetSlotDouble(vm, slot.cint).int)
elif T is string:
var
len: cint
bytes = wrenGetSlotBytes(vm, slot.cint, addr len)
result = newString(len.Natural)
if len > 0:
copyMem(result[0].unsafeAddr, bytes, len.Natural)
elif T is array | seq:
when T is array:
const
P = 2
Min = ord(genericParam(T, 1).a)
Max = ord(genericParam(T, 1).b)
Len = Max - Min + 1
else:
const
P = 1
Min = 0
let listLen = wrenGetListCount(vm, slot.cint)
when T is seq:
result.setLen(listLen)
else:
if listLen != Len:
vm.abortFiber("got list of length " & $listLen & ", but the expected " &
"length is " & $Len)
return
let listHandle = wrenGetSlotHandle(vm, slot.cint)
for i in 0..<listLen:
wrenGetListElement(vm, slot.cint, i.cint, slot.cint)
if checkType(vm, genericParam(T, P), slot):
result[Min + i] = getSlot[genericParam(T, P)](vm, slot)
wrenSetSlotHandle(vm, slot.cint, listHandle)
else:
wrenReleaseHandle(vm, listHandle)
vm.abortFiber("got <" & vm.getSlotTypeString(slot) & "> in list, " &
"but expected <" & wrenName(genericParam(T, P)) & ">")
return
wrenReleaseHandle(vm, listHandle)
elif T is WrenRef:
result = cast[Wren](wrenGetUserData(vm))
.newRef(wrenGetSlotHandle(vm, slot.cint))
elif T is object | tuple | ref:
result = getSlotForeign[T](vm, slot)[]
else:
{.error: "unsupported type for slot retrieval: " & $T.}
proc newForeign*(vm: RawVM, slot: int, size: Natural, classSlot = 0): pointer =
result = wrenSetSlotNewForeign(vm, slot.cint, classSlot.cint, size.cuint)
proc getVariable*(vm: RawVM, slot: int, module, variable: string) =
wrenGetVariable(vm, module, variable, slot.cint)
var wrenNames {.compileTime.}: Table[uint16, ModuleVar] ## \
## Maps unique type IDs to their corresponding variables in bound modules.
proc getTypeId(typeSym: NimNode): uint16 {.compileTime.}
macro wrenVar(T: typed): untyped =
let id = getTypeId(T)
if id notin wrenNames:
error("type <" & T.repr & "> is unknown to the VM", T)
let v = wrenNames[id]
result = newTree(nnkPar, newLit(v.module), newLit(v.variable))
proc genForeignObjectInit(vm, objType, expr, slot: NimNode,
exprIsInit = false): NimNode
macro foreignObjectInit(vm, objType, expr: typed, slot: int,
exprIsInit = false): untyped =
result = genForeignObjectInit(vm, objType, expr, slot,
exprIsInit.boolVal)
proc setSlot*[T](vm: RawVM, slot: int, val: T) =
when T is bool:
wrenSetSlotBool(vm, slot.cint, val)
elif T is SomeNumber:
wrenSetSlotDouble(vm, slot.cint, val.cdouble)
elif T is enum:
wrenSetSlotDouble(vm, slot.cint, ord(val).cdouble)
elif T is string:
wrenSetSlotBytes(vm, slot.cint, val, val.len.cuint)
elif T is array | seq:
const P =
when T is array: 2
else: 1
wrenEnsureSlots(vm, cint(slot + 1))
wrenSetSlotNewList(vm, slot.cint)
for x in val:
setSlot[genericParam(T, P)](vm, slot + 1, x)
wrenInsertInList(vm, slot.cint, -1, cint(slot + 1))
elif T is WrenRef:
wrenSetSlotHandle(vm, slot.cint, val.handle)
elif T is object | tuple | ref:
let varInfo = wrenVar(genericParam(T))
vm.getVariable(slot, varInfo[0], varInfo[1])
foreignObjectInit(vm, genericParam(T), val, slot)
else:
{.error: "unsupported type for slot assignment: " & $T.}
proc abortFiber*(vm: RawVM, message: string) =
vm.setSlot[:string](0, message)
wrenAbortFiber(vm, 0)
proc checkParent*(vm: RawVM, base, compare: uint16): bool =
## Check if the ``compare`` type is one of ``base``'s parent types.
## Used internally for type checking with inheritance.
let wvm = cast[Wren](wrenGetUserData(vm))
result = base in wvm.parentTypeIds[compare]
proc addTypeInfo*(vm: Wren, id: uint16, name: string, parents: set[uint16]) =
## This is an implementation detail used internally by the wrapper.
## You should not use this in your code.
vm.typeNames[id] = name
vm.parentTypeIds[id] = parents
proc addProc*(vm: Wren, module, class, signature: string, isStatic: bool,
impl: WrenForeignMethodFn) =
vm.methods[(module, class, signature, isStatic)] = impl
proc addClass*(vm: Wren, module, name: string,
destroy: WrenFinalizerFn = nil) =
vm.classes[(module, name)] = WrenForeignClassMethods(
allocate: nil,
finalize: destroy
)
#--
# End user API - basics
#--
proc getError(vm: Wren, interpretResult: WrenInterpretResult): ref WrenError =
case interpretResult
of WREN_RESULT_SUCCESS: discard
of WREN_RESULT_COMPILE_ERROR:
var err = new(WrenError)
err.msg = "compile error"
for e in vm.compileErrors:
err.msg &= '\n' & e.module & '(' & $e.line & "): " & e.message
result = err
of WREN_RESULT_RUNTIME_ERROR:
var err = new(WrenError)
err.msg = vm.rtError.message & "\nwren stack trace:"
for t in vm.rtError.stackTrace:
err.msg &= "\n at " & t.module & '(' & $t.line & ')'
result = err
else: doAssert(false) # unreachable
proc checkRuntimeError(vm: Wren, interpretResult: WrenInterpretResult) =
if interpretResult != WREN_RESULT_SUCCESS:
raise vm.getError(interpretResult)
proc module*(vm: Wren, name, src: string) =
## Runs the provided source code inside of the specified module.
vm.checkRuntimeError(wrenInterpret(vm.handle, name, src))
proc run*(vm: Wren, src: string) =
## Runs the provided source code inside of a module named "main". This should
## be used for the entry point of your program. Use ``module`` if you want to
## modify the module name (used in error messages and imports).
vm.module("main", src)
proc `[]`*(vm: Wren, module, variable: string, T: typedesc = WrenRef): T =
## Retrieves a variable from the Wren VM. This works both for primitives and
## Wren objects (pass ``WrenRef`` to ``T`` to retrieve a Wren object).
## If the variable type does not match ``T``, an error will be thrown nagging
## the application user.
wrenEnsureSlots(vm.handle, 1)
wrenGetVariable(vm.handle, module, variable, 0)
if not checkType(vm.handle, genericParam(T), 0):
raise newException(WrenError,
"in wren module '" & module & "': variable '" &
variable & "' has type <" &
vm.handle.getSlotTypeString(0) & ">, but expected <" &
wrenName(genericParam(T)) & ">")
result = getSlot[T](vm.handle, 0)
proc `{}`*(vm: Wren, signature: string): WrenRef =
## Creates a 'call handle' to the method denoted by ``methodSignature``.
result = vm.newRef(wrenMakeCallHandle(vm.handle, signature))
proc toWrenValue*(val: bool): WrenValue =
WrenValue(kind: wvkBool, boolVal: val)
proc toWrenValue*(val: int): WrenValue =
WrenValue(kind: wvkNumber, numVal: val.float)
proc toWrenValue*(val: float): WrenValue =
WrenValue(kind: wvkNumber, numVal: val)
proc toWrenValue*(val: string): WrenValue =
WrenValue(kind: wvkString, strVal: val)
proc toWrenValue*(val: WrenRef): WrenValue =
WrenValue(kind: wvkWrenRef, wrenRef: val)
proc call*[T](theMethod: WrenRef,
receiver: WrenRef, args: varargs[WrenValue, toWrenValue]): T =
## Calls the given method with the given arguments. The first argument must
## always be present, and is the receiver of the method. The rest of the
## arguments is optional. The generic parameter decides on the return type of
## the method (which can be void).
##
## **Design note:** The ``receiver`` param only accepts ``WrenRef``, because
## it's pretty much never useful to call a method on a primitive type, since
## the native implementation is always faster.
let vm = theMethod.vm
wrenEnsureSlots(vm.handle, cint(1 + args.len))
vm.handle.setSlot[:WrenRef](0, receiver)
for i, arg in args:
case arg.kind
of wvkBool: vm.handle.setSlot[:bool](i + 1, arg.boolVal)
of wvkNumber: vm.handle.setSlot[:float](i + 1, arg.numVal)
of wvkString: vm.handle.setSlot[:string](i + 1, arg.strVal)
of wvkWrenRef: vm.handle.setSlot[:WrenRef](i + 1, arg.wrenRef)
vm.checkRuntimeError(wrenCall(vm.handle, theMethod.handle))
when T isnot void:
result = vm.handle.getSlot[:T](0)
#--
# End user API - foreign()
#--
# leaving this here for my own debugging convenience.
proc `$`(n: NimNode): string {.used.} = n.repr
proc getParamList(formalParams: NimNode): seq[NimNode] =
## Flattens an nnkFormalParams into a C-like list of argument types,
## eg. ``x, y: int`` becomes ``@[int, int]``.
for identDefs in formalParams[1..^1]:
let ty =
if identDefs[^2].kind != nnkEmpty: identDefs[^2]
else:
if identDefs[^1].kind != nnkIdent: identDefs[^1].getType
else: newEmptyNode()
for i in 0..<identDefs.len - 2:
result.add(ty)
proc getParamNames(formalParams: NimNode): seq[string] =
## Get the names of the parameters in the formalParams as a single list.
for identDefs in formalParams[1..^1]:
for name in identDefs[0..^3]:
result.add(name.strVal)
proc flattenType(typeSym: NimNode, typeKinds = {ntyTypeDesc}): NimNode =
result = typeSym
while result.typeKind in typeKinds:
let kind = result.typeKind
while result.typeKind == kind:
if result.typeKind == ntyTypeDesc and ntyTypeDesc in typeKinds:
if result.getTypeInst.kind != nnkBracketExpr: break
result = result.getTypeInst[1]
if result.typeKind == ntyRef and ntyRef in typeKinds:
if result.typeKind != ntyRef: break
result = result.getTypeImpl[0]
proc removeGeneric(typeExpr: NimNode): NimNode =
result = typeExpr
if result.kind == nnkBracketExpr:
result = result[0]
proc eqType(a, b: NimNode): bool =
## Compares two ``NimNodes`` to determine if they represent the same type.
## Better than ``sameType``, because it deals with ``typedesc``s properly.
## This ignores generic instantiations.
if a.kind == nnkEmpty or b.kind == nnkNilLit: return true
let
a = a.removeGeneric.flattenType
b = b.removeGeneric.flattenType
result = sameType(a, b)
proc getOverload(choices: NimNode, params: varargs[NimNode]): NimNode =
## Finds an appropriate proc overload based on the provided parameters.
for overload in choices:
block check:
let
impl = overload.getImpl
formalParams = impl[3]
argTypes = getParamList(formalParams)
# compare ``argTypes`` with ``params``
if params[0].len != argTypes.len: break check
for i, param in params[0]:
if not eqType(argTypes[i], param):
break check
return overload
error("couldn't find overload for given parameter types")
proc getParent(typeSym: NimNode): NimNode =
## Get the parent type for the given type symbol, or ``nil`` if the type has
## no parent type.
if typeSym.kind != nnkSym: return nil # generic types don't have parents
var impl = typeSym.getImpl[2]
if impl.kind == nnkTupleTy: return nil # tuples don't have parents
impl.expectKind({nnkRefTy, nnkObjectTy, nnkTupleTy})
while impl.kind == nnkRefTy:
impl = impl[0]
impl.expectKind(nnkObjectTy)
if impl[1].kind != nnkEmpty:
result = impl[1][0]
var
# compile-time data about types
typeIds {.compileTime.}: Table[string, uint16]
## Maps type hashes to unique integer IDs
typeNames {.compileTime.}: Table[uint16, string]
## Maps the unique IDs to actual names
parentTypeIds {.compileTime.}: Table[uint16, set[uint16]]
## Maps the unique IDs to their parents' IDs
proc isForeignType(typeSym: NimNode): bool =
## Check if the given type symbol denotes a foreign type (object, ref, tuple).
var theType = typeSym
# flatten generic type
if theType.kind == nnkBracketExpr:
theType = theType[0]
# XXX: this assumes that generic typedescs are proper foreign types
result = theType.flattenType.typeKind in {ntyObject, ntyRef, ntyTuple,
ntyGenericBody}
proc typeHash(typeSym: NimNode): string =
## Generate a type hash for a symbol. This is designed to work with generic
## instantiations.
var typeSym = typeSym.flattenType
if typeSym.kind != nnkBracketExpr:
# change any internal number alias types into their actual implementation;
# this prevents problems with types like float spontaneously becoming
# float64 in generic parameters
case typeSym.typeKind
of ntyInt:
# only support 32- and 64-bit
# it's unlikely that Wren works on architectures other than 32/64-bit
# anyways since it uses float64s for NaN tagging
if sizeof(pointer) == 4: typeSym = bindSym"int32"
elif sizeof(pointer) == 8: typeSym = bindSym"int64"
of ntyFloat:
# float is always float64
typeSym = bindSym"float64"
else: discard
result = typeSym.signatureHash
else:
result = typeSym[0].signatureHash & "["
for gparam in typeSym[1..^1]:
result.add(gparam.typeHash & ",")
result.add("]")
proc getTypeId(typeSym: NimNode): uint16 =
## Get a unique type ID for the given type symbol.
if not typeSym.isForeignType:
error("<" & typeSym.repr & "> (of kind " & $typeSym.typeKind &
") is not a supported foreign type", typeSym)
let hash = typeSym.typeHash
if hash notin typeIds:
let
id = typeIds.len.uint16
parent = typeSym.getParent
typeIds[hash] = id
typeNames[id] = typeSym.repr
if parent == nil:
parentTypeIds[id] = {}
else:
let parentId = getTypeId(parent)
parentTypeIds[id] = parentTypeIds[parentId] + {parentId}
result = typeIds[hash]
proc isRef(class: NimNode): bool =
## Checks if the given type symbol represents a ref type.
result = class.flattenType.typeKind == ntyRef
proc newCast(T, val: NimNode): NimNode =
## Create a new nnkCast node, which casts ``val`` to ``T``.
newTree(nnkCast, T, val)
type
Empty = object ## A dummy object to represent an nnkEmpty.
TypePair = array[2, NimNode]
proc getType(pair: TypePair): NimNode =
if pair[0] != bindSym"Empty": result = pair[0]
else: result = pair[1].getTypeInst
proc getSlotGetters(params: openarray[TypePair],
isStatic: bool): seq[NimNode] =
## Get a list of getSlot() calls which extract the given parameters from
## the VM.
for i, pair in params:
let
slot = newLit(i + ord(isStatic))
paramType = pair.getType
getter =
if paramType.typeKind in {ntyObject, ntyVar} or paramType.isRef:
if paramType.typeKind == ntyVar:
newCast(paramType,
newCall(newTree(nnkBracketExpr, ident"getSlotForeign",
paramType[0]),
ident"vm", slot))
else:
newTree(nnkBracketExpr,
newCall(newTree(nnkBracketExpr, ident"getSlotForeign",
paramType),
ident"vm", slot))
else:
newCall(newTree(nnkBracketExpr, ident"getSlot", paramType),
ident"vm", slot)
result.add(getter)
proc genTypeCheck(vm, ty, slot: NimNode): NimNode =
# type kind sets
const
Nums = {ntyInt..ntyUint64, ntyEnum}
Lists = {ntyArray, ntySequence}
Foreign = {ntyObject, ntyRef, ntyTuple, ntyGenericBody}
let ty = ty.flattenType
# generate the check
let
wrenType =
if ty.typeKind == ntyBool: wtBool
elif ty.typeKind in Nums: wtNumber
elif ty.typeKind == ntyString: wtString
elif ty == bindSym"WrenRef": wtUnknown
elif ty.kind == nnkBracketExpr:
let subTy = ty[0].flattenType
if subTy.typeKind in Lists: wtList
elif subTy.typeKind in Foreign: wtForeign
else:
error("unsupported generic type kind: " & $ty.typeKind & ' ' &
"for <" & ty.repr & ">", ty)
wtUnknown
elif ty.typeKind in Foreign: wtForeign
else:
error("unsupported type kind: " & $ty.typeKind &
" for <" & ty.repr & ">", ty)
wtUnknown
comparison = newTree(nnkInfix, ident"==",
newCall("getSlotType", vm, slot),
newLit(wrenType))
result = comparison
if wrenType == wtForeign:
let
typeId = getTypeId(ty)
typeIdLit = newLit(typeId)
slotId = newCall("getSlotForeignId", vm, slot)
idCheck = newTree(nnkInfix, ident"==", slotId, typeIdLit)
parentCheck = newCall(ident"checkParent", vm, typeIdLit, slotId)
result = newTree(nnkInfix, ident"and", result,
newPar(newTree(nnkInfix, ident"or", idCheck, parentCheck)))
proc genTypeChecks(vm: NimNode, isStatic: bool,
typePairs: varargs[TypePair]): NimNode =
## Generate a type check condition. This looks at all the params and assembles
## a big chain of conditions which check the type.
## This is a much better way of checking types compared to the 0.1.0
## ``checkTypes``, which simply looped through an array of ``WrenTypeData``
## structs and compared them. The current, macro-based version, has much lower
## runtime overhead, because it's just a simple chain of conditions.
# there isn't any work to be done if the proc doesn't accept params
if typePairs.len == 0 or typePairs.len == ord(not isStatic):
return newLit(true)
# place the actual types into a seq
var types: seq[NimNode]
for pair in typePairs:
types.add(pair.getType)
# if the first param is var, ignore that
if types[0].kind == nnkVarTy:
types[0] = types[0][0]
# generate a list of checks
var checks: seq[NimNode]
for i, ty in types[ord(not isStatic)..^1]:
let slot = i + 1
checks.add(genTypeCheck(vm, ty, newLit(slot)))
# fold the list of checks to an nnkInfix node
result = checks[^1]
for i in countdown(checks.len - 2, 0):
result = newTree(nnkInfix, ident"and", checks[i], result)
proc getWrenName(typeSym: NimNode): string =
## Get the Wren name for the corresponding type. This aliases number types
## to ``number``, ``WrenRef`` to ``object``, and any Wren-bound types to
## their names in the Wren VM.
let typeSym = typeSym.flattenType
if typeSym.typeKind in {ntyInt..ntyUint64}: result = "number"
elif typeSym == bindSym"WrenRef": result = "object"
elif typeSym.typeKind in {ntyObject, ntyRef} and
getTypeId(typeSym) in wrenNames:
let id = getTypeId(typeSym)
result = wrenNames[id].variable
else: result = typeSym.repr
proc genTypeError(theProc: NimNode, wrenName: string, arity: int,
overloads: varargs[NimNode]): NimNode =
## Generate a Nim-like type mismatch error.
result = newStmtList()
let
errVar = newVarStmt(ident"err",
newLit("type mismatch: got <"))
fiberAbort = newCall("abortFiber", ident"vm", ident"err")
result.add([errVar])
for i in 1..arity:
result.add(newCall("add", ident"err",
newCall("getSlotTypeString", ident"vm", newLit(i))))
if i != arity:
result.add(newCall("add", ident"err", newLit", "))
var expectedStr = ""
for overload in overloads:
let
impl = overload.getImpl
params = impl[3]
expectedStr.add("\n " & wrenName & '(')
for i, defs in params[1..^1]:
for j, def in defs[0..^3]:
expectedStr.add(def.repr)
if j < defs.len - 3:
expectedStr.add(", ")
expectedStr.add(": " & getWrenName(defs[^2]))
if i < params.len - 2:
expectedStr.add(", ")
expectedStr.add(')')
if params[0].kind != nnkEmpty:
expectedStr.add(": " & getWrenName(params[0]))
result.add(newCall("add", ident"err",
newLit(">\nbut expected one of:" & expectedStr)))
result.add(fiberAbort)
proc genForeignObjectInit(vm, objType, expr, slot: NimNode,
exprIsInit = false): NimNode =
## Generate a statement list with the initialization procedure for a new
## foreign object. ``expr`` is the expression that needs to be called to
## initialize the given ``objType``. ``slot`` is the VM slot where the new
## foreign object should be stored. It is also the slot where the foreign
## class must be stored. If ``exprIsInit`` is true, ``expr`` will be treated
## as an initializer instead of a constructor.
result = newStmtList()
# create the foreign object
let
size = newTree(nnkInfix, ident"+",
newCall("sizeof", ident"uint16"),
newCall("sizeof", objType))
dataSym = genSym(nskVar, "data")
newForeignCall = newCall("newForeign", vm, slot, size, slot)
u16array = newTree(nnkPtrTy,
newTree(nnkBracketExpr,
ident"UncheckedArray", ident"uint16"))
result.add(newVarStmt(dataSym, newCast(u16array, newForeignCall)))
# assign the type ID
let typeId = getTypeId(objType)
result.add(newTree(nnkAsgn,
newTree(nnkBracketExpr, dataSym, newLit(0)),
newLit(typeId)))
# assign the data
let
objSym = genSym(nskVar, "objectData")
ptrObjType = newTree(nnkPtrTy, objType)
objAddr = newTree(nnkAddr, newTree(nnkBracketExpr, dataSym, newLit(1)))
obj = newTree(nnkDerefExpr, objSym)
result.add(newVarStmt(objSym, newCast(ptrObjType, objAddr)))
if exprIsInit:
let
initSym = genSym(nskVar, "init")
initVar = newTree(nnkVarSection,
newTree(nnkIdentDefs, initSym, objType, newEmptyNode()))
result.add(initVar)
var initExpr = expr
initExpr[0] = initSym
result.add(newTree(nnkAsgn, obj, initExpr))
else:
result.add(newTree(nnkAsgn, obj, expr))
if objType.isRef:
result.add(newCall("GC_ref", obj))
proc genForeignErrorCheck(expr: NimNode): NimNode =
## Wraps ``expr`` in a try…except statement, which, in case of error, aborts
## the current fiber with the caught exception's error message.
## If in a debug build, the message will also contain the stack traceback.
result = newNimNode(nnkTryStmt)
result.add(newStmtList(expr))
var
branch = newNimNode(nnkExceptBranch)
branchStmts = newStmtList()
let
errSym = genSym(nskLet, "error")
msgSym = genSym(nskVar, "errorMessage")
branchStmts.add(newLetStmt(errSym, newCall("getCurrentException")))
branchStmts.add(newVarStmt(msgSym, newTree(nnkDotExpr, errSym, ident"msg")))
branchStmts.add(newCall("add", msgSym, newLit(" [")))
branchStmts.add(newCall("add", msgSym,
newTree(nnkDotExpr, errSym, ident"name")))
branchStmts.add(newCall("add", msgSym, newLit(']')))
when compileOption("stacktrace"):
branchStmts.add(newCall("add", msgSym, newLit("\nnim stack trace:\n")))
branchStmts.add(newCall("add", msgSym, newCall("getStackTrace", errSym)))
branchStmts.add(newCall("abortFiber", ident"vm", msgSym))
branch.add(branchStmts)
result.add(branch)
proc orEmpty(node: NimNode): NimNode =
result =
if node.kind == nnkEmpty: bindSym"Empty"
else: node
proc getGenericParams(theProc: NimNode,
params: openArray[TypePair]): Table[string, NimNode] =
let
procImpl = theProc.getImpl
procParams = getParamList(procImpl[3])
for i, param in procParams:
if param.repr notin result:
let userParam = params[i].getType
result[param.repr] = userParam
proc resolveGenericParams(expr: NimNode,
table: Table[string, NimNode]): NimNode =
if expr.flattenType.typeKind == ntyGenericParam:
result = table[expr.repr]
elif expr.typeKind == ntyGenericInvocation:
result = expr
if expr.repr in table:
result = table[expr.repr]
else:
for i, sub in result[1..^1]:
result[i + 1] = resolveGenericParams(sub, table)
else:
result = expr
proc genProcGlue(theProc: NimNode, wrenName: string,
isStatic, isGetter: bool,
params: openArray[TypePair]): NimNode =
## Generate a glue procedure with type checks and VM slot conversions.
# get some metadata about the proc
let
procImpl = theProc.getImpl
genericParamTable = getGenericParams(theProc, params)
procRetType = resolveGenericParams(procImpl[3][0], genericParamTable)
# create a new anonymous proc; this is our resulting glue proc
result = newProc(params = [newEmptyNode(),
newIdentDefs(ident"vm", ident"RawVM")])
result.addPragma(ident"cdecl")
var body = newStmtList()
# generate the call
let
call = newCall(theProc, getSlotGetters(params, isStatic))
callWithReturn =
# no return type
if procRetType.kind == nnkEmpty or eqIdent(procRetType, "void"): call
# some return type
else: newCall(newTree(nnkBracketExpr, ident"setSlot", procRetType),
ident"vm", newLit(0), call)
callWithTry = genForeignErrorCheck(callWithReturn)
# generate type check
let typeCheck = genTypeChecks(ident"vm", isStatic, params)
body.add(newIfStmt((cond: typeCheck, body: callWithTry))
.add(newTree(nnkElse, genTypeError(theProc, wrenName,
params.len, theProc))))
result.body = body
proc genSignature(theProc: NimNode, wrenName: string,
isStatic, isGetter: bool, namedParams = false): string =
## Generate a Wren signature for the given proc and its properties.
## If ``namedParams`` is true, a 'nice' signature will be generated with
## parameter names embedded into it.
var
param = ord(not isStatic)
paramNames = getParamNames(theProc.getImpl[3])
arity = paramNames.len
proc params(n: int): string =
## Generate a string of params like _,_,_,_
if namedParams:
for i in 1..n:
result.add(paramNames[param])
if i != n:
result.add(',')
inc(param)
else:
for i in 1..n:
result.add('_')
if i != n:
result.add(',')
var name = wrenName
name.removePrefix('`')
name.removeSuffix('`')
if not isGetter:
let arity = arity - ord(not isStatic)
if name == "[]":
result = '[' & arity.params & ']'
elif name == "[]=":
result = '[' & (arity - 1).params & "]=(" & params(1) & ")"
else:
result = name & '(' & arity.params & ')'
else:
result = name
macro genProcAux(vm: Wren, module: string, className: string,
theProc: typed, wrenName: static string,
isStatic, isGetter: static bool,
params: varargs[typed]): untyped =
## Second step of binding a proc, generates code which binds it to the
## provided Wren instance.
# unpack ``params`` into the correct type
var paramList: seq[array[2, NimNode]]
for i in countup(0, params.len - 1, 2):
paramList.add([params[i], params[i + 1]])
# call ``addProc``
let
classLit = className
nameLit = newLit(genSignature(theProc, wrenName, isStatic, isGetter))
result = newStmtList()
result.add(newCall("addProc", vm, module,
classLit, nameLit, newLit(isStatic),
genProcGlue(theProc, wrenName, isStatic, isGetter,
paramList)))
var wrenDecl = "foreign "
if isStatic:
wrenDecl.add("static ")
wrenDecl.add(genSignature(theProc, wrenName, isStatic, isGetter,
namedParams = true))
wrenDecl.add('\n')
result.add(newCall("add", ident"classMethods", newLit(wrenDecl)))
proc resolveOverload(procSym: NimNode, overloaded: bool,
params: varargs[NimNode]): NimNode =
## Resolve the overload of ``procSym``. If ``overloaded`` is true, overload
## parameters were provided during binding, and ``params`` are the desired
## overload's parameters.
result = procSym
if procSym == nil: return
if procSym.kind != nnkSym:
if not overloaded:
error("multiple overloads available; " &
"provide the correct overload's parameters", procSym)
result = getOverload(procSym, params)
macro addProcAux(vm: Wren, module: string, className: string,
procSym: typed, wrenName: string,
overloaded: static bool, isStatic, isGetter: bool,
params: varargs[typed]): untyped =
## First step of binding a proc, resolves the overload using the given params
## and defers the binding to ``genProcAux``. This is a workaround for
## Nim/#12942, to make the bound procedure's parameters ``typed``.
# as a workaround for Nim/#12831, unwrap the procSym if it's