-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathnimline.nim
752 lines (605 loc) · 26.8 KB
/
nimline.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
# Copyright (c) 2018-2020 Giovanni Petrantoni.
# For full license information see LICENSE.txt.
## Wrapper-less C/C++ interop for Nim
import macros, tables, strutils, os
{.experimental.}
var cppTypes {.compileTime.}: seq[NimNode]
macro isCppObject(T: typed): untyped =
for cppType in cppTypes:
if T.getTypeInst == cppType:
return bindSym"true"
return bindSym"false"
macro registerCppType*(T: typed): untyped =
## Makes a type satisfy the `CppObject` concept
T.expectKind(nnkSym)
cppTypes.add(T)
type
CppProxy* {.nodecl.} = object
## A C++ object whose type is not known to the Nim compiler. Proxies are typically results of C++ calls.
## They can be used in further C++ calls or cast to concrete types using `to`, but not stored in variables.
CppObject* = concept x
## A concept for types that support C++ method invokation. Users can mark types as `CppObject` using
## `registerCppType(MyType)`
x.isCppObject
when defined(js):
type WasmPtr* = distinct int
else:
# Linux gprof utility define
when defined(linux) and defined(gprof):
{.passC: "-pg".}
{.passL: "-pg".}
# Compiler utilities
macro cppdefines*(defines: varargs[string]): untyped =
## Add preprocessor defines to the C++ compilation in a platform-independent way.
result = nnkStmtList.newTree()
for adefine in defines:
var str: string
when defined(windows) and defined(vcc):
str = "/D" & $adefine
else:
str = "-D" & $adefine
result.add nnkPragma.newTree(nnkExprColonExpr.newTree(newIdentNode("passC"), newLit(str)))
macro cppincludes*(includes: varargs[string]): untyped =
## Add ab include path to the C++ compilation in a platform-independent way.
result = nnkStmtList.newTree()
for incl in includes:
var str: string
when defined windows:
let win_incl = ($incl).replace("/", "\\").quoteShell
when defined vcc:
str = "/I" & win_incl
else:
str = "-I" & win_incl
else:
str = "-I" & $incl
result.add nnkPragma.newTree(nnkExprColonExpr.newTree(newIdentNode("passC"), newLit(str)))
macro cppfiles*(files: varargs[string]): untyped =
## Add source files to the C++ compilation in a platform-independent way.
result = nnkStmtList.newTree()
for file in files:
var str: string
when defined windows:
let win_incl = ($file).replace("/", "\\") .quoteShell
str = win_incl
else:
str = $file
result.add nnkPragma.newTree(nnkExprColonExpr.newTree(newIdentNode("compile"), newLit(str)))
macro cpplibpaths*(paths: varargs[string]): untyped =
## Add search paths for static libraries to the C++ compilation in a platform-independent way.
result = nnkStmtList.newTree()
for path in paths:
var str: string
when defined windows:
let win_path = ($path).replace("/", "\\").quoteShell
when defined vcc:
str = "/LIBPATH:" & win_path
else:
str = "-L" & win_path
else:
str = "-L" & $path
result.add nnkPragma.newTree(nnkExprColonExpr.newTree(newIdentNode("passL"), newLit(str)))
macro cpplibs*(libs: varargs[string]): untyped =
## Add libraries defines to the C++ compilation in a platform-independent way.
result = nnkStmtList.newTree()
for lib in libs:
var str: string
when defined windows:
let win_incl = ($lib).replace("/", "\\").quoteShell
when defined vcc:
str = win_incl
else:
str = "-l" & win_incl
else:
str = "-l" & $lib
result.add nnkPragma.newTree(nnkExprColonExpr.newTree(newIdentNode("passL"), newLit(str)))
type CppGlobalType* = object
registerCppType(CppGlobalType)
var global* {.nodecl.}: CppGlobalType
const CppGlobalName = "global"
macro defineCppType*(name: untyped, importCppStr: string, headerStr: string = ""): untyped =
## Imports a C++ type and allows it to be used as `CppObject`
result = nnkStmtList.newTree()
result.add quote do:
type `name`* {.header: "", importcpp: "", inheritable.} = object
if $headerStr != "":
# replace empty string with proper values
result[0][0][0][1][0][1] = newStrLitNode($headerStr)
result[0][0][0][1][1][1] = newStrLitNode($importCppStr)
else:
# remove header pragma
result[0][0][0][1].del(0)
# replace empty string with proper values
result[0][0][0][1][0][1] = newStrLitNode($importCppStr)
var converterName = newIdentNode("to" & $name)
result.add quote do:
converter `converterName`*(co: CppProxy): `name` {.used, importcpp:"(#)".}
registerCppType(`name`)
proc cppinit*(T: typedesc[CppObject]): T {.importcpp:"'0(@)", varargs, constructor.}
## Constructs an object of a C++ type
proc cppctor*[T](x: ptr T): ptr T {.header:"new", importcpp: "(new (#) '*0(@))", varargs, nodecl, discardable.}
## Calls placement new, constructing an object in the location pointed to.
# magic placement new constructor for refs
proc cppctor*[T](x: ref T): ref T {.header:"new", importcpp: "(new (#) '*0(@))", varargs, nodecl, discardable.}
## Calls placement new, constructing an object in the location referenced.
when not defined(js):
{.emit:["""/*TYPESECTION*/
#ifdef __cplusplus
template<typename T>
static inline void callCppPtrDestructor(T* instance) { instance->~T(); }
template<typename T>
static inline void callCppPtrDestructor(T& instance) { instance.~T(); }
#endif
"""].}
## TODO: Unify?
# normal destructor for value types
proc internalCppdtor[T: CppObject](x: var T) {.importcpp:"callCppPtrDestructor(#)".}
# magic placement new compatible destructor for ptrs
proc internalCppdtor[T: CppObject](x: ptr T) {.importcpp:"callCppPtrDestructor(#)".}
# magic placement new compatible destructor for refs
proc internalCppdtor[T: CppObject](x: ref T) {.importcpp:"callCppPtrDestructor(#)".}
# normal destructor for value types
proc internalCppdtor[T: not CppObject](x: T) {.importcpp:"#.~'1()".}
## TODO: var T?
# magic placement new compatible destructor for ptrs
proc internalCppdtor[T: not CppObject](x: ptr T) = x[].internalCppdtor()
# magic placement new compatible destructor for refs
proc internalCppdtor[T: not CppObject](x: ref T) = x[].internalCppdtor()
proc cppdelptr*[T](x: ptr T) =
## TODO: Remove, or make more consistent helpers
x.internalCppdtor()
dealloc(x)
proc cppdtor*[T](x: ptr T) =
## Calls the destructor of a C++ type. Use together with `cppctor`
x.internalCppdtor()
proc cppmove*[T](x: T): T {.importcpp:"std::move(#)".}
## Calls `std::move` on the C++ object.
# TODO: Try to unify (varargs[typed] didn't seem to work yet)
proc cppnewref*(myRef: var ref) =
## Creates a new bject and constructs the underlying C++ object. The object will be destroyed when the `ref` is finalized.
new(myRef, proc(self: type(myRef)) = self.internalCppdtor())
myRef.cppctor()
proc cppnewref*(myRef: var ref, arg0: auto) =
## Creates a new bject and constructs the underlying C++ object. The object will be destroyed when the `ref` is finalized.
new(myRef, proc(self: type(myRef)) = self.internalCppdtor())
myRef.cppctor(arg0)
proc cppnewref*(myRef: var ref, arg0, arg1: auto) =
## Creates a new bject and constructs the underlying C++ object. The object will be destroyed when the `ref` is finalized.
new(myRef, proc(self: type(myRef)) = self.internalCppdtor())
myRef.cppctor(arg0, arg1)
template cppnewptr*[T](myPtr: ptr T): untyped =
## Allocates storage for and constructs a C++ object
myPtr = cast[ptr T](alloc0(sizeof(T)))
myPtr.cppctor()
template cppnewptr*[T](myPtr: ptr T, arg0: typed): untyped =
## Allocates storage for and constructs a C++ object
myPtr = cast[ptr T](alloc0(sizeof(T)))
myPtr.cppctor(arg0)
template cppnewptr*[T](myPtr: ptr T, arg0, arg1: typed): untyped =
## Allocates storage for and constructs a C++ object
myPtr = cast[ptr T](alloc0(sizeof(T)))
myPtr.cppctor(arg0, arg1)
template cppnewptr*[T](myPtr: ptr T, arg0, arg1, arg2: typed): untyped =
## Allocates storage for and constructs a C++ object
myPtr = cast[ptr T](alloc0(sizeof(T)))
myPtr.cppctor(arg0, arg1, arg2)
proc `+` *(x, y: CppProxy): CppProxy {.importcpp: "(# + #)".}
proc `-` *(x, y: CppProxy): CppProxy {.importcpp: "(# - #)".}
proc `*` *(x, y: CppProxy): CppProxy {.importcpp: "(# * #)".}
proc `/` *(x, y: CppProxy): CppProxy {.importcpp: "(# / #)".}
proc `%` *(x, y: CppProxy): CppProxy {.importcpp: "(# % #)".}
proc `+=` *(x, y: CppProxy): CppProxy {.importcpp: "(# += #)", discardable.}
proc `-=` *(x, y: CppProxy): CppProxy {.importcpp: "(# -= #)", discardable.}
proc `*=` *(x, y: CppProxy): CppProxy {.importcpp: "(# *= #)", discardable.}
proc `/=` *(x, y: CppProxy): CppProxy {.importcpp: "(# /= #)", discardable.}
proc `%=` *(x, y: CppProxy): CppProxy {.importcpp: "(# %= #)", discardable.}
proc `++` *(x: CppProxy): CppProxy {.importcpp: "(++#)", discardable}
proc `--` *(x: CppProxy): CppProxy {.importcpp: "(--#)", discardable}
proc `==` *(x, y: CppProxy): CppProxy {.importcpp: "(# == #)".}
proc `>` *(x, y: CppProxy): CppProxy {.importcpp: "(# > #)".}
proc `<` *(x, y: CppProxy): CppProxy {.importcpp: "(# < #)".}
proc `>=` *(x, y: CppProxy): CppProxy {.importcpp: "(# >= #)".}
proc `<=` *(x, y: CppProxy): CppProxy {.importcpp: "(# <= #)".}
proc `<<` *(x, y: CppProxy): CppProxy {.importcpp: "(# << #)".}
proc `>>` *(x, y: CppProxy): CppProxy {.importcpp: "(# >> #)".}
proc `xor`*(x, y: CppProxy): CppProxy {.importcpp: "(# ^ #)".}
proc `and`*(x, y: CppProxy): CppProxy {.importcpp: "(# & #)".}
proc `or` *(x, y: CppProxy): CppProxy {.importcpp: "(# | #)".}
proc `mod` *(x, y: CppProxy): CppProxy {.importcpp: "(# % #)".}
proc `shl` *(x, y: CppProxy): CppProxy {.importcpp: "(# << #)".}
proc `shr` *(x, y: CppProxy): CppProxy {.importcpp: "(# >> #)".}
proc `not`*(x: CppProxy): CppProxy {.importcpp: "(~#)".}
proc `-` *(x: CppProxy): CppProxy {.importcpp: "(-#)".}
proc `[]`*(obj: CppProxy, field: auto): CppProxy {.importcpp: "#[#]".}
proc `[]=`*[T](obj: CppProxy, field: auto, val: T) {.importcpp: "#[#] = #".}
proc `[]`*(obj: CppObject, field: auto): CppProxy {.importcpp: "#[#]".}
proc `[]=`*[T](obj: CppObject, field: auto, val: T) {.importcpp: "#[#] = #".}
when defined(js):
# Conversion to and from CppProxy
proc to*(x: CppProxy, T: typedesc): T {. importcpp: "(#)" .}
## Converts a CppProxy `x` to type `T`.
# Conversion to and from CppProxy
proc to*[T](x: CppProxy): T {. importcpp: "(#)" .}
## Converts a CppProxy `x` to type `T`.
else:
# Conversion to and from CppProxy
proc to*(x: CppProxy, T: typedesc[void]): T {. importcpp: "(#)" .}
## Converts a CppProxy `x` to type `T`.
# Conversion to and from CppProxy
proc to*(x: CppProxy, T: typedesc): T {. importcpp: "('0)(#)" .}
## Converts a CppProxy `x` to type `T`.
# Conversion to and from CppProxy
proc to*[T](x: CppProxy): T {. importcpp: "('0)(#)" .}
## Converts a CppProxy `x` to type `T`.
proc toCpp*[T](val: T): CppProxy {. importcpp: "(#)" .}
## Converts a value of any type to type CppProxy
template toCpp*(s: string): CppProxy = cstring(s).toCpp
# TODO: Remove used
converter toByte*(co: CppProxy): int8 {.used, importcpp: "(#)".}
converter toUByte*(co: CppProxy): uint8 {.used, importcpp: "(#)".}
converter toShort*(co: CppProxy): int16 {.used, importcpp: "(#)".}
converter toUShort*(co: CppProxy): uint16 {.used, importcpp: "(#)".}
converter toInt*(co: CppProxy): int {.used, importcpp: "(#)".}
converter toUInt*(co: CppProxy): uint {.used, importcpp: "(#)".}
converter toLong*(co: CppProxy): int64 {.used, importcpp: "(#)".}
converter toULong*(co: CppProxy): uint64 {.used, importcpp: "(#)".}
converter toFloat*(co: CppProxy): float {.used, importcpp: "(#)".}
converter toFloat32*(co: CppProxy): float32 {.used, importcpp: "(#)".}
converter toDouble*(co: CppProxy): float64 {.used, importcpp: "(#)".}
converter toCString*(co: CppProxy): cstring {.used, importcpp: "(#)".}
when defined(js):
converter toWasmPtr*(co: CppProxy): WasmPtr {.used, importcpp: "(#)".}
macro cppFromAst*(n: untyped): untyped =
result = n
if n.kind == nnkStmtList:
result = newProc(procType = nnkDo, body = result)
return quote: toCpp(`result`)
macro getMember*(obj: CppObject, field: untyped): CppProxy =
## Returns the value of a property of name `field` from a CppObject `obj`.
if obj.len == 0 and $obj == CppGlobalName:
let importString = "(" & $field & ")"
result = quote do:
proc helper(): CppProxy {.importcpp:`importString`, gensym.}
helper()
else:
let importString = "#." & $field
result = quote do:
proc helper(o: CppObject): CppProxy {.importcpp:`importString`, gensym.}
helper(`obj`)
template dynamicCppGet*(obj: CppObject, field: untyped): CppProxy {.deprecated.} =
obj.getMember(field)
template `.`*(obj: CppObject, field: untyped): CppProxy =
## Returns the value of a property of name `field` from a CppObject `obj`.
obj.getMember(field)
macro setMember*(obj: CppObject, field, value: untyped): untyped =
## Sets the value of a property of name `field` in a CppObject `obj` to `value`.
if obj.len == 0 and $obj == CppGlobalName:
let importString = $field & " = #"
result = quote do:
proc helper(v: auto) {.importcpp:`importString`, gensym.}
helper(`value`.toCpp)
else:
let importString = "#." & $field & " = #"
result = quote do:
proc helper(o: CppObject, v: auto) {.importcpp:`importString`, gensym.}
helper(`obj`, `value`.toCpp)
template dynamicCppSet*(obj: CppObject, field, value: untyped): untyped {.deprecated.} =
obj.setMember(field, value)
template `.=`*(obj: CppObject, field, value: untyped): untyped =
## Sets the value of a property of name `field` in a CppObject `obj` to `value`.
obj.setMember(field, value)
macro invokeFunction*(field: untyped, args: varargs[CppProxy, cppFromAst]): CppProxy =
## Calls a C function with `args` as arguments and returns a CppProxy.
## Return values have to be converted using `to(T)` or used in other C++ calls.
## Void returns have to be explicitly discarded with `to(void)`.
var importString: string
importString = $field & "(@)"
result = quote:
proc helper(): CppProxy {.importcpp:`importString`, gensym.}
helper()
for idx in 0 ..< args.len:
let paramName = ident("param" & $idx)
result[0][3].add newIdentDefs(paramName, ident("CppProxy"))
result[1].add args[idx].copyNimTree
template dynamicCCall*(field: untyped, args: varargs[CppProxy, cppFromAst]): CppProxy {.deprecated.} =
invokeFunction(field, args)
macro invoke*(obj: CppObject, field: untyped, args: varargs[CppProxy, cppFromAst]): CppProxy =
## Calls a mathod of a C++ object with `args` as arguments and returns a CppProxy.
## Return values have to be converted using `to(T)` or used in other C++ calls.
## Void returns have to be explicitly discarded with `to(void)`.
var importString: string
if obj.len == 0 and $obj == CppGlobalName:
importString = $field & "(@)"
result = quote:
proc helper(): CppProxy {.importcpp:`importString`, gensym.}
helper()
else:
when defined(js):
importString = "#." & "_" & $field & "(@)"
else:
importString = "#." & $field & "(@)"
result = quote:
proc helper(o: CppObject): CppProxy {.importcpp:`importString`, gensym.}
helper(`obj`)
for idx in 0 ..< args.len:
let paramName = ident("param" & $idx)
result[0][3].add newIdentDefs(paramName, ident("CppProxy"))
result[1].add args[idx].copyNimTree
template dynamicCppCall*(obj: CppObject, field: untyped, args: varargs[CppProxy, cppFromAst]): CppProxy {.deprecated.} =
invoke(obj, field, args)
template `.()`*(obj: CppObject, field: untyped, args: varargs[CppProxy, cppFromAst]): CppProxy =
## Calls a mathod of a C++ object with `args` as arguments and returns a CppProxy.
## Return values have to be converted using `to(T)` or used in other C++ calls.
## Void returns have to be explicitly discarded with `to(void)`.
invoke(obj, field, args)
# Iterator utils
type
CppIterator* [T] {.importcpp: "'0::iterator".} = object
proc itBegin [T] (cset: T): CppIterator[T] {.importcpp:"(#.begin())".}
proc itEnd [T] (cset: T): CppIterator[T] {.importcpp:"(#.end())".}
proc itPlusPlus [T] (csetIt: var CppIterator[T]): CppIterator[T] {.importcpp:"(++#)".}
proc itValue [T, R] (csetIt: var CppIterator[T]): R {.importcpp:"(*#)".}
proc itEqual [T] (csetIt: var CppIterator[T], csetIt2: var CppIterator[T]): bool {.importcpp:"(operator==(#, #))".}
iterator cppItems*[T, R](cset: var T): R =
var it = cset.itBegin()
var itend = cset.itEnd()
while not itEqual(it, itend):
yield itValue[T, R](it)
it = it.itPlusPlus
# String utils
defineCppType(StdString, "std::string", "string")
converter toStdString*(s: string): StdString {.inline, noinit.} = cppinit(StdString, s.cstring)
# Tuple utils
# TODO: Simplify
type
StdTuple2* [T1, T2] {.importcpp: "std::tuple", header: "tuple".} = object
StdTuple3* [T1, T2, T3] {.importcpp: "std::tuple", header: "tuple".} = object
StdTuple4* [T1, T2, T3, T4] {.importcpp: "std::tuple", header: "tuple".} = object
StdTuple5* [T1, T2, T3, T4, T5] {.importcpp: "std::tuple", header: "tuple".} = object
StdTuple* = StdTuple2 | StdTuple3 | StdTuple4 | StdTuple5
proc makeCppTuple*(arg1, arg2: auto): StdTuple2[type(arg1), type(arg2)] {.importcpp: "std::make_tuple(@)", header: "tuple".}
proc makeCppTuple*(arg1, arg2, arg3: auto): StdTuple3[type(arg1), type(arg2), type(arg3)] {.importcpp: "std::make_tuple(@)", header: "tuple".}
proc makeCppTuple*(arg1, arg2, arg3, arg4: auto): StdTuple4[type(arg1), type(arg2), type(arg3), type(arg4)] {.importcpp: "std::make_tuple(@)", header: "tuple".}
proc makeCppTuple*(arg1, arg2, arg3, arg4, arg5: auto): StdTuple5[type(arg1), type(arg2), type(arg3), type(arg4), type(arg5)] {.importcpp: "std::make_tuple(@)", header: "tuple".}
proc cppTupleGet*[T](index: int; obj: CppProxy): T {.importcpp: "std::get<#>(#)", header: "tuple".}
proc cppTupleSet*(index: int; obj: CppProxy, value: CppObject) {.importcpp: "std::get<#>(#) = #", header: "tuple".}
proc cppTupleSize*(obj: CppProxy): int {.importcpp: "std::tuple_size<decltype(#)>::value", header: "tuple".}
# proc len(T: typedesc[tuple|object]): static[int] =
# var f: T
# for _ in fields(f):
# inc result
proc toNimTuple*[T1, T2](t: StdTuple2[T1, T2]): (T1, T2) =
discard cppctor(addr(result[0]))
discard cppctor(addr(result[1]))
result = (cppTupleGet[T1](0, t.toCpp), cppTupleGet[T2](1, t.toCpp))
proc toNimTuple*[T1, T2, T3](t: StdTuple3[T1, T2, T3]): (T1, T2, T3) =
discard cppctor(addr(result[0]))
discard cppctor(addr(result[1]))
discard cppctor(addr(result[2]))
(cppTupleGet[T1](0, t.toCpp), cppTupleGet[T2](1, t.toCpp), cppTupleGet[T3](2, t.toCpp))
proc toNimTuple*[T1, T2, T3, T4](t: StdTuple4[T1, T2, T3, T4]): (T1, T2, T3, T4) =
discard cppctor(addr(result[0]))
discard cppctor(addr(result[1]))
discard cppctor(addr(result[2]))
discard cppctor(addr(result[3]))
(cppTupleGet[T1](0, t.toCpp), cppTupleGet[T2](1, t.toCpp), cppTupleGet[T3](2, t.toCpp), cppTupleGet[T4](3, t.toCpp))
proc toNimTuple*[T1, T2, T3, T4, T5](t: StdTuple5[T1, T2, T3, T4, T5]): (T1, T2, T3, T4, T5) =
discard cppctor(addr(result[0]))
discard cppctor(addr(result[1]))
discard cppctor(addr(result[2]))
discard cppctor(addr(result[3]))
discard cppctor(addr(result[4]))
(cppTupleGet[T1](0, t.toCpp), cppTupleGet[T2](1, t.toCpp), cppTupleGet[T3](2, t.toCpp), cppTupleGet[T4](3, t.toCpp), cppTupleGet[T5](4, t.toCpp))
# Array utils
type StdArray* [T; S: static[int]] {.importcpp: "std::array<'0, '1>", header: "array".} = object
proc `[]`*[T; S: static[int]](v: StdArray[T, S]; index: int): T {.inline.} = v.toCpp[index].to(T)
proc `[]=`*[T; S: static[int]](v: var StdArray[T, S]; index: int; value: T) {.inline.} = v.toCpp[index] = value
# Exception utils
type
StdException* {.importcpp: "std::exception", header: "<exception>".} = object
proc what*(s: StdException): cstring {.importcpp: "((char *)#.what())".}
# References utils
type
CppReference*[T] {.importcpp: "std::reference_wrapper", header: "<functional>".} = object
template cppref*[T](proxy: CppProxy): CppReference[T] = invokeFunction("std::ref", proxy).to(CppReference[T])
proc get*[T](reference: CppReference[T]): T {.importcpp: "#.get()".}
# proc nimPointerDeleter(p: pointer) {.exportc.} = dealloc(p)
# # Smart pointer utils
# {.emit: """/*TYPESECTION*/
# #include <functional>
# """.}
# type
# UniquePointer*[T] {.importcpp: "std::unique_ptr<'*0, std::function<void('*0*)>>", header: "<memory>".} = object
# proc internalMakeUnique[T](): UniquePointer[T] =
# var p: ptr T
# cppnewptr(p)
# proc stdmakeptr[T](vp: ptr T): UniquePointer[T] {.importcpp:"std::unique_ptr<'*0, std::function<void('*0*)>>(@, []('*0* ptr) { callCppPtrDestructor(ptr); nimPointerDeleter(ptr); })", varargs, constructor.}
# return stdmakeptr[T](p)
# proc makeUnique*[T](): UniquePointer[T] {.inline.} = internalMakeUnique[T]()
# proc getPtr*[T](up: var UniquePointer[T]): ptr T {.inline.} = up.toCpp.get().to(ptr T)
# type
# SharedPointer*[T] {.importcpp: "std::shared_ptr<'*0>", header: "<memory>".} = object
# proc internalMakeShared[T](): SharedPointer[T] =
# var p: ptr T
# cppnewptr(p)
# proc stdmakeptr[T](vp: ptr T): SharedPointer[T] {.importcpp:"std::shared_ptr<'*0>(@, []('*0* ptr) { callCppPtrDestructor(ptr); nimPointerDeleter(ptr); })", varargs, constructor.}
# return stdmakeptr[T](p)
# proc makeShared*[T](): SharedPointer[T] {.inline.} = internalMakeShared[T]()
# proc getPtr*[T](up: SharedPointer[T]): ptr T {.inline.} = up.toCpp.get().to(ptr T)
type
CppRef*[T: CppObject] = object
p: ptr T
proc new*[T: CppObject](_: type[T]): CppRef[T] =
var x: ptr T
cppnewptr x
result.p = x
proc new*[T: CppObject](_: type[T]; arg0: auto): CppRef[T] =
var x: ptr T
cppnewptr x, arg0
result.p = x
proc new*[T: CppObject](_: type[T]; arg0, arg1: auto): CppRef[T] =
var x: ptr T
cppnewptr x, arg0, arg1
result.p = x
proc new*[T: CppObject](_: type[T]; arg0, arg1, arg2: auto): CppRef[T] =
var x: ptr T
cppnewptr x, arg0, arg1, arg2
result.p = x
proc newref*[T: CppObject](_: type[T]): ref CppRef[T] =
new result
var x: ptr T
cppnewptr x
result.p = x
proc newref*[T: CppObject](_: type[T]; arg0: auto): ref CppRef[T] =
new result
var x: ptr T
cppnewptr x, arg0
result.p = x
proc newref*[T: CppObject](_: type[T]; arg0, arg1: auto): ref CppRef[T] =
new result
var x: ptr T
cppnewptr x, arg0, arg1
result.p = x
proc newref*[T: CppObject](_: type[T]; arg0, arg1, arg2: auto): ref CppRef[T] =
new result
var x: ptr T
cppnewptr x, arg0, arg1, arg2
result.p = x
proc `=destroy`*[T: CppObject](r: var CppRef[T]) =
cppdelptr r.p
template `.()`*[T: CppObject](obj: CppRef[T], field: untyped, args: varargs[CppProxy, cppFromAst]): CppProxy =
## Calls a mathod of a C++ object with `args` as arguments and returns a CppProxy.
## Return values have to be converted using `to(T)` or used in other C++ calls.
## Void returns have to be explicitly discarded with `to(void)`.
invoke(obj.p[], field, args)
template `.=`*[T: CppObject](obj: CppRef[T], field, value: untyped): untyped =
## Sets the value of a property of name `field` in a CppObject `obj` to `value`.
obj.p[].setMember(field, value)
macro emitc*(stmts: varargs[untyped]): untyped =
var bracktree = nnkBracket.newTree()
for s in stmts:
bracktree.add(s)
result = nnkStmtList.newTree(
nnkPragma.newTree(
nnkExprColonExpr.newTree(
newIdentNode("emit"),
bracktree
)
)
)
when defined wasm:
template EM_ASM*(jsCode: string): untyped =
{.emit: """/*INCLUDESECTION*/
#include <emscripten.h>
""".}
proc emAsmProc() =
{.emit: ["EM_ASM(", jsCode, ");"].}
emAsmProc()
# utility to automatically call NimMain when using C++17, just compile the library with -d:auto_nim_main
when defined auto_nim_main:
{.emit:"""
extern N_CDECL(void, NimMain)(void);
namespace nimline {
struct AutoNimMain {
AutoNimMain() {
NimMain();
}
};
struct AutoNimMainExecutor {
// requires c++17
static inline AutoNimMain doit{};
};
}
""".}
when isMainModule:
{.emit:"#include <stdio.h>".}
{.emit:"#include <string>".}
cppdefines("MYDEFINE", "MYDEFINE2=10")
cppincludes(".")
cppfiles("tests/MyClass.cpp")
cpplibpaths(".")
defineCppType(MyClass, "MyClass", "tests/MyClass.hpp")
defineCppType(MyClass2, "MyClass2", "tests/MyClass.hpp")
type
MyNimType = object # my nim types still needs to use cpp ctor/dtor cos includes a cpp type inside
x: MyClass
# expandMacros:
# dumpAstGen:
when true:
proc run() =
var x = cppinit(MyClass, 1)
var nx: MyNimType
var nxp: ptr MyNimType
cppnewptr nxp
var y = cast[ptr MyClass](alloc0(sizeof(MyClass)))
# var w: ref MyClass
# new(w, proc(self: ref MyClass) = self.internalCppdtor())
var z = y.cppctor(1)
# var q = w.cppctor(1)
# var j: ref MyClass
# cppnewref(j, 1)
# j.number = 22
# echo j.number.to(cint)
var k: ptr MyClass
cppnewptr(k, 2)
k.number = 55
echo k.number.to(cint)
k.cppdelptr
echo global.globalNumber.to(cint)
global.globalNumber = 102
echo global.globalNumber.to(cint)
global.printf("Hello World\n".cstring).to(void)
y.test3().to(void)
y.test4(7, 8).to(void)
echo z.number.to(cint)
y.number = 80
y.numbers[0] = 23
var n = (x.number + y.number + y.numbers[0]).to(cint)
var nInt: int = x.number + y.number + y.numbers[0]
echo nInt
echo n
echo x.test(1).to(cdouble)
echo x.test(x.test2(2)).to(cdouble)
echo x.test2(3).to(cint)
z.cppdtor()
x.internalCppdtor()
nx.internalCppdtor()
cppdelptr nxp
var x1 = cppinit(MyClass2, 1)
echo x1.test20(1).to(cint)
var c1 = x1.class1.to(MyClass)
c1.test3().to(void)
x1.class1.test3().to(void)
var myFloat: float32 = x1.myDouble
echo myFloat
var myStr = "Hello Mars"
x1.myCstring = myStr
echo x1.myCstring.to(cstring)
# TODO check macros -> callsite macro
x1.testVir3(11).to(void)
var cppTuple = makeCppTuple(x, y)
cppTupleSet(0, cppTuple.toCpp, x.toCpp)
var tx = cppTupleGet[MyClass](0, cppTuple.toCpp)
echo x.test(1).to(cdouble)
var nimTuple = cppTuple.toNimTuple()
var
myx = MyClass.new(10)
myxref = MyClass.newref()
myx.test3().to(void)
myx.number = 99
myxref.test3().to(void)
myxref.number = 100
# var
# uniqueInt = makeUnique[int]()
# uniqueIntPtr = uniqueInt.getPtr()
# uniqueIntPtr[] = 10
# assert uniqueIntPtr[] == 10
# var
# sharedInt = makeShared[int]()
# sharedIntPtr = sharedInt.getPtr()
# sharedIntPtr[] = 11
# assert sharedIntPtr[] == 11
# block:
# echo "Expect dtor"
# var sharedInt = makeShared[MyClass]()
# echo "Expect more dtors..."
run()