From 2e4d344b43b040a4dce2c478ca13e49979e491fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20M=20G=C3=B3mez?= Date: Sun, 18 Aug 2024 12:21:17 +0100 Subject: [PATCH] Fixes #23962 `resetLoc`doenst produce any cgen code in `importcpp` types (#23964) --- compiler/cgen.nim | 5 ++++- tests/cpp/23962.h | 17 +++++++++++++++++ tests/cpp/t23962.nim | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 tests/cpp/23962.h create mode 100644 tests/cpp/t23962.nim diff --git a/compiler/cgen.nim b/compiler/cgen.nim index 95155bb203..7291602f4f 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -482,7 +482,10 @@ include ccgreset proc resetLoc(p: BProc, loc: var TLoc) = let containsGcRef = optSeqDestructors notin p.config.globalOptions and containsGarbageCollectedRef(loc.t) let typ = skipTypes(loc.t, abstractVarRange) - if isImportedCppType(typ): return + if isImportedCppType(typ): + var didGenTemp = false + linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(loc), genCppInitializer(p.module, p, typ, didGenTemp)]) + return if optSeqDestructors in p.config.globalOptions and typ.kind in {tyString, tySequence}: assert loc.snippet != "" diff --git a/tests/cpp/23962.h b/tests/cpp/23962.h new file mode 100644 index 0000000000..2d8147bfbd --- /dev/null +++ b/tests/cpp/23962.h @@ -0,0 +1,17 @@ +#include + +struct Foo { + + Foo(int inX): x(inX) { + std::cout << "Ctor Foo(" << x << ")\n"; + } + ~Foo() { + std::cout << "Destory Foo(" << x << ")\n"; + } + + void print() { + std::cout << "Foo.x = " << x << '\n'; + } + + int x; +}; \ No newline at end of file diff --git a/tests/cpp/t23962.nim b/tests/cpp/t23962.nim new file mode 100644 index 0000000000..c79d888df9 --- /dev/null +++ b/tests/cpp/t23962.nim @@ -0,0 +1,32 @@ +discard """ + cmd: "nim cpp $file" + output: ''' +Ctor Foo(-1) +Destory Foo(-1) +Ctor Foo(-1) +Destory Foo(-1) +Ctor Foo(-1) +Destory Foo(-1) +Foo.x = 1 +Foo.x = 2 +Foo.x = -1 +''' +""" + +type + Foo {.importcpp, header: "23962.h".} = object + x: cint + +proc print(f: Foo) {.importcpp.} + +#also tests the right constructor is used +proc makeFoo(x: int32 = -1): Foo {.importcpp:"Foo(#)", constructor.} + +proc test = + var xs = newSeq[Foo](3) + xs[0].x = 1 + xs[1].x = 2 + for x in xs: + x.print + +test() \ No newline at end of file