From 3c1ddc401923093251dc4fed0259cedb1cf8cc81 Mon Sep 17 00:00:00 2001 From: jjv360 Date: Mon, 27 Dec 2021 10:11:47 +0000 Subject: [PATCH] Bug with default constructors in proxied class --- classes.nimble | 2 +- src/classes.nim | 10 ++++++---- test.nim | 43 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 5 deletions(-) diff --git a/classes.nimble b/classes.nimble index cdf6482..24b7267 100644 --- a/classes.nimble +++ b/classes.nimble @@ -1,5 +1,5 @@ # Package -version = "0.2.6" +version = "0.2.7" author = "jjv360" description = "Adds class support to Nim." license = "MIT" diff --git a/src/classes.nim b/src/classes.nim index f975bea..7ad94c3 100644 --- a/src/classes.nim +++ b/src/classes.nim @@ -308,7 +308,10 @@ proc createClassStructure(head: NimNode, bodyNode: NimNode, result: NimNode, isS # Add default constructors for all constructors that don't exist in the subclass but do in the parent class - for methodNode in parentClassInfo.methodDefs: + for methodNode2 in parentClassInfo.methodDefs: + + # Allow methodNode to be captured + let methodNode = methodNode2 # Stop if not an init if $methodNode.name != "init": @@ -316,10 +319,9 @@ proc createClassStructure(head: NimNode, bodyNode: NimNode, result: NimNode, isS # Check if this method signature exists var didExist = false - for node in body: + traverseNodeStatements body, proc(idx: int, parent: NimNode, node: NimNode) = if node.kind == nnkMethodDef and $node.name == "init" and node.params.repr == methodNode.params.repr: didExist = true - break # Stop if exists if didExist: @@ -768,7 +770,7 @@ proc createClassStructure(head: NimNode, bodyNode: NimNode, result: NimNode, isS ) # if $className == "AsyncCls": - # echo result.repr + echo result.repr # Export new keyword which was imported from our lib # let newIdent = ident"new" diff --git a/test.nim b/test.nim index 030a879..4a87656 100644 --- a/test.nim +++ b/test.nim @@ -149,6 +149,26 @@ assert(ClassWith3Init.init(5, 5, 5, e=4.5, d=3.4).v1 == 15) +test "Constructor inheritance" + +class ClsInit1: + var v1 = 1 + method init() = this.v1 += 2 + +class ClsInit2 of ClsInit1: + method init() = + super.init() + this.v1 += 3 + +class ClsInit3 of ClsInit2: + method init() = + super.init() + this.v1 += 4 + +assert(ClsInit3.init().v1 == 10) + + + group "Destructors" test "Called on dealloc" warn "Not implemented yet" @@ -347,6 +367,29 @@ assert(MyProxiedClass.init().injectedVar == 3) assert(MyProxiedClass.init().injectedMethod() == 5) assert(MyProxiedClass.init().originalVar == 6) +class2 ProxyClass2 of MyProxiedClass: + var v3 = 3 + method m4(): int = 4 + +assert(ProxyClass2.init().v3 == 3) +assert(ProxyClass2.init().m4 == 4) + +class2 Cls2Init1: + var v1 = 1 + method init() = this.v1 += 2 + +class2 Cls2Init2 of Cls2Init1: + method init() = + super.init() + this.v1 += 3 + +class2 Cls2Init3 of Cls2Init2: + method init() = + super.init() + this.v1 += 4 + +assert(Cls2Init3.init().v1 == 10) + group "Mixins"