From 9d23aa2b64c933108a5073fc7d087e30ace4d65c Mon Sep 17 00:00:00 2001 From: Stephan Hadinger Date: Wed, 12 Jun 2024 10:12:26 +0200 Subject: [PATCH] Berry `classof` extended to class methods --- CHANGELOG.md | 1 + lib/libesp32/berry/src/be_api.c | 16 ++++++++++++++++ lib/libesp32/berry/tests/class.be | 17 ++++++++++++++++- 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da6372512cb0..393947757323 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to this project will be documented in this file. ## [14.1.0.2] ### Added +- Berry `classof` extended to class methods ### Breaking Changed diff --git a/lib/libesp32/berry/src/be_api.c b/lib/libesp32/berry/src/be_api.c index 6ccb65c5accb..f3851b5c67f5 100644 --- a/lib/libesp32/berry/src/be_api.c +++ b/lib/libesp32/berry/src/be_api.c @@ -544,6 +544,22 @@ BERRY_API bbool be_classof(bvm *vm, int index) binstance *ins = var_toobj(v); var_setclass(top, be_instance_class(ins)); return btrue; + } else if (var_isclosure(v)) { + bclosure *cl = var_toobj(v); + bproto *pr = cl->proto; + if (pr != NULL) { + bclass *cla; + if (pr->nproto > 0) { + cla = (bclass*) pr->ptab[pr->nproto]; + } else { + cla = (bclass*) pr->ptab; + } + if (cla && var_basetype(cla) == BE_CLASS) { + bvalue *top = be_incrtop(vm); + var_setclass(top, cla); + return btrue; + } + } } return bfalse; } diff --git a/lib/libesp32/berry/tests/class.be b/lib/libesp32/berry/tests/class.be index e175fcdca28a..0bbc6be5647d 100644 --- a/lib/libesp32/berry/tests/class.be +++ b/lib/libesp32/berry/tests/class.be @@ -57,4 +57,19 @@ c4 = Test_class() assert(type(c4.c) == 'class') c5 = c4.c() assert(type(c5) == 'instance') -assert(classname(c5) == 'map') \ No newline at end of file +assert(classname(c5) == 'map') + +#- classof now gets back the class of Berry methods -# +class A + def f() end + static def g() end +end +class B : A + def h() end +end +assert(classof(A.f) == A) +assert(classof(A.g) == A) +assert(classof(B.h) == B) +#- returns nil if native function of not in class -# +assert(classof(int) == nil) +assert(classof(def () end) == nil)