From bd47d99ceb1046e2bef6a26f830a76ae8f06da43 Mon Sep 17 00:00:00 2001 From: s-hadinger <49731213+s-hadinger@users.noreply.github.com> Date: Wed, 12 Jun 2024 10:48:38 +0200 Subject: [PATCH] Berry `classof` extended to class methods (#21615) --- 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 da6372512..393947757 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 6ccb65c5a..f3851b5c6 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 e175fcdca..0bbc6be56 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)