mirror of
https://github.com/nim-lang/Nim.git
synced 2026-07-12 04:09:34 +00:00
fixes #25803 This pull request introduces a new approach for generating C++ constructor expressions in the Nim compiler's C++ backend, ensuring that type-prefixed construction is used when needed (such as in assignments), rather than just braced initializer lists. It also adds a new test case (with corresponding C++ header) to verify correct behavior when assigning to types with overloaded assignment operators and constructors. **C++ code generation improvements:** * Added `genCppConstructorExpr` in `ccgtypes.nim`, which generates a full type-prefixed constructor expression (e.g., `Foo(a, b)`) for C++ code generation, as opposed to just a braced initializer list. This is important for contexts like assignments where the type must be explicit. * Updated `resetLoc` in `cgen.nim` to use `genCppConstructorExpr` instead of `genCppInitializer` when initializing imported C++ types, ensuring correct code generation for assignments. **Testing:** * Added a new C++ header file, `tcpp_default_ctor_assignment.h`, defining a struct `AmbiguousAssign` with overloaded assignment operators and constructors to test ambiguous assignment scenarios. * Added a corresponding Nim test, `tcpp_default_ctor_assignment.nim`, which exercises construction and assignment for the imported C++ type, ensuring the new code generation logic works as intended.
This commit is contained in:
30
tests/cpp/tcpp_default_ctor_assignment.h
Normal file
30
tests/cpp/tcpp_default_ctor_assignment.h
Normal file
@@ -0,0 +1,30 @@
|
||||
#ifndef TCPP_DEFAULT_CTOR_ASSIGNMENT_H
|
||||
#define TCPP_DEFAULT_CTOR_ASSIGNMENT_H
|
||||
|
||||
struct AmbiguousAssign {
|
||||
int x;
|
||||
const char* y;
|
||||
|
||||
AmbiguousAssign(): x(0), y(nullptr) {}
|
||||
AmbiguousAssign(int x, const char* y): x(x), y(y) {}
|
||||
|
||||
AmbiguousAssign& operator=(int v) {
|
||||
x = v;
|
||||
y = nullptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AmbiguousAssign& operator=(const char* s) {
|
||||
x = 0;
|
||||
y = s;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AmbiguousAssign& operator=(const AmbiguousAssign& other) {
|
||||
x = other.x;
|
||||
y = other.y;
|
||||
return *this;
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
14
tests/cpp/tcpp_default_ctor_assignment.nim
Normal file
14
tests/cpp/tcpp_default_ctor_assignment.nim
Normal file
@@ -0,0 +1,14 @@
|
||||
discard """
|
||||
cmd: "nim cpp $file"
|
||||
"""
|
||||
|
||||
type
|
||||
AmbiguousAssign {.importcpp, header: "tcpp_default_ctor_assignment.h".} = object
|
||||
x: cint
|
||||
y: cstring
|
||||
|
||||
proc main =
|
||||
var xs = newSeq[AmbiguousAssign](3)
|
||||
doAssert xs.len == 3
|
||||
|
||||
main()
|
||||
Reference in New Issue
Block a user