fixes #22662 Procs with constructor pragma doesn't initialize object's fields (#22665)

fixes #22662 Procs with constructor pragma doesn't initialize object's
fields

---------

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
(cherry picked from commit d45270bdf7)
This commit is contained in:
Juan M Gómez
2023-09-08 09:46:40 +01:00
committed by narimiran
parent 28cef86a09
commit 1bbbb2f46b
2 changed files with 30 additions and 2 deletions

View File

@@ -660,6 +660,13 @@ proc mangleRecFieldName(m: BModule; field: PSym): Rope =
result = rope(mangleField(m, field.name))
if result == "": internalError(m.config, field.info, "mangleRecFieldName")
proc hasCppCtor(m: BModule; typ: PType): bool =
result = false
if m.compileToCpp and typ != nil and typ.itemId in m.g.graph.memberProcsPerType:
for prc in m.g.graph.memberProcsPerType[typ.itemId]:
if sfConstructor in prc.flags:
return true
proc genRecordFieldsAux(m: BModule; n: PNode,
rectype: PType,
check: var IntSet; result: var Rope; unionPrefix = "") =
@@ -724,7 +731,7 @@ proc genRecordFieldsAux(m: BModule; n: PNode,
else:
# don't use fieldType here because we need the
# tyGenericInst for C++ template support
if fieldType.isOrHasImportedCppType():
if fieldType.isOrHasImportedCppType() or hasCppCtor(m, field.owner.typ):
result.addf("\t$1$3 $2{};$n", [getTypeDescAux(m, field.loc.t, check, dkField), sname, noAlias])
else:
result.addf("\t$1$3 $2;$n", [getTypeDescAux(m, field.loc.t, check, dkField), sname, noAlias])

View File

@@ -3,6 +3,10 @@ discard """
cmd: "nim cpp $file"
output: '''
1
0
123
0
123
'''
"""
@@ -52,4 +56,21 @@ proc makeCppClass(): NimClass {. constructor: "NimClass() : CppClass(0, 0) ".} =
this.x = 1
let nimClass = makeNimClass(1)
var nimClassDef {.used.}: NimClass #since we explictly defined the default constructor we can declare the obj
var nimClassDef {.used.}: NimClass #since we explictly defined the default constructor we can declare the obj
#bug: 22662
type
BugClass* = object
x: int # Not initialized
proc makeBugClass(): BugClass {.constructor.} =
discard
proc main =
for i in 0 .. 1:
var n = makeBugClass()
echo n.x
n.x = 123
echo n.x
main()