Skip to content

Commit 92c061b

Browse files
committed
feat(es-classes): mirror the JS class hierarchy in Objective-C
`class B extends A extends UIView` registered B directly under UIView, as a sibling of A, and copied A's methods into it. JS saw `b instanceof A`, but Objective-C did not: [b isKindOfClass:A] was false, which breaks UIAppearance, class-keyed registration and KVO, and every inherited method was installed again at each level. The flattening existed because a native super call targeted the superclass of the receiver's runtime class. With a real hierarchy that is A's class, whose implementation of an overridden method calls back into A's JS method, so `super.foo()` from A on a B instance recursed. A JS super lookup only reaches a native method when no JS level above the caller defines it, so the correct target is the superclass of the rootmost JS-defined class in the chain (ClassBuilder::GetNativeSuperclass). Single-level classes, which is every legacy one, resolve to the same class as before. - EnsureExtendedClass registers a JS-defined parent first and subclasses it, exposing only the class's own prototype level. Statics are still read through the constructor, so an override of a method declared in an inherited ObjCExposedMethods/ObjCProtocols finds its signature. - An ES class may now extend a legacy .extend() class. The legacy `super` accessor resolves its prototype from the class that owns it rather than a fixed depth from the receiver, which pointed at the legacy implementation object itself once an ES subclass added a level. - .extend() of an already extended class is still refused.
1 parent 083aa71 commit 92c061b

4 files changed

Lines changed: 165 additions & 114 deletions

File tree

‎NativeScript/runtime/ClassBuilder.h‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
#define ClassBuilder_h
33

44
#include <string>
5-
#include <unordered_set>
65
#include <vector>
76

87
#include "Common.h"
@@ -48,10 +47,10 @@ class ClassBuilder {
4847
static void RegisterNativeClassFunction(v8::Local<v8::Context> context);
4948

5049
// Lazily registers an Objective-C subclass for a plain ES
51-
// `class X extends NativeBase {}` constructor function. Returns the
50+
// `class X extends Base {}` constructor function, registering a JS-defined
51+
// Base first so the Objective-C hierarchy mirrors the JS one. Returns the
5252
// registered class, or nil when ctorFunc is not part of a native inheritance
53-
// chain; throws when the chain goes through a legacy `.extend()`-created
54-
// class. Idempotent: subsequent calls return the cached class from the ctor's
53+
// chain. Idempotent: subsequent calls return the cached class from the ctor's
5554
// ObjCClassWrapper. Pass nativeAllocates when the caller is handing the class
5655
// to Objective-C (or allocating through it), which is what makes the JS
5756
// constructor unreachable and gates the debug diagnostic.
@@ -73,6 +72,13 @@ class ClassBuilder {
7372
v8::Local<v8::Context> context,
7473
const v8::FunctionCallbackInfo<v8::Value>& info);
7574

75+
// The class a JS `super.method()` reaching a native method must dispatch
76+
// to: the superclass of the rootmost JS-defined class in klass's chain. A JS
77+
// super lookup only lands on a native method when no JS level above the
78+
// caller defines it, so every JS-defined class in between must be skipped —
79+
// their implementations call back into JS and would recurse.
80+
static Class GetNativeSuperclass(Class klass);
81+
7682
private:
7783
static std::atomic<unsigned long long> classNameCounter_;
7884

@@ -86,12 +92,11 @@ class ClassBuilder {
8692
static void WarnIfConstructorIsUnreachable(
8793
v8::Local<v8::Context> context,
8894
const std::vector<v8::Local<v8::Function>>& chainCtors, Class extendedClass);
89-
static void ExposeDynamicMethods(
90-
v8::Local<v8::Context> context, Class extendedClass,
91-
v8::Local<v8::Value> exposedMethods,
92-
v8::Local<v8::Value> exposedProtocols,
93-
v8::Local<v8::Object> implementationObject,
94-
std::unordered_set<std::string>* visitedNames = nullptr);
95+
static void ExposeDynamicMethods(v8::Local<v8::Context> context,
96+
Class extendedClass,
97+
v8::Local<v8::Value> exposedMethods,
98+
v8::Local<v8::Value> exposedProtocols,
99+
v8::Local<v8::Object> implementationObject);
95100
static void ExposeDynamicMembers(v8::Local<v8::Context> context,
96101
Class extendedClass,
97102
v8::Local<v8::Object> implementationObject,

‎NativeScript/runtime/ClassBuilder.mm‎

Lines changed: 59 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -554,55 +554,15 @@ bool DeclaresConstructorOrFields(const std::string& src) {
554554
return nil;
555555
}
556556

557-
// Walk the constructor prototype chain (mirrors the `class X extends Y` chain) and collect
558-
// every plain (unregistered) ES constructor level until we reach a constructor holding an
559-
// ObjCClassWrapper. ES-registered ancestors are flattened into this registration; legacy
560-
// `.extend()`-created ancestors are not supported (mirrors the historic restriction) and
561-
// make this function bail out so callers preserve their old behavior.
562-
std::vector<Local<v8::Function>> chainCtors;
563-
Local<v8::Function> current = ctorFunc;
564-
Class baseClass = nil;
565-
while (true) {
566-
chainCtors.push_back(current);
567-
568-
Local<Value> parentValue = current->GetPrototype();
569-
if (parentValue.IsEmpty() || !parentValue->IsObject() || !parentValue->IsFunction()) {
570-
return nil;
571-
}
572-
573-
Local<v8::Function> parent = parentValue.As<v8::Function>();
574-
BaseDataWrapper* parentWrapper = tns::GetValue(isolate, parent);
575-
if (parentWrapper == nullptr) {
576-
current = parent;
577-
continue;
578-
}
579-
580-
if (parentWrapper->Type() != WrapperType::ObjCClass) {
581-
return nil;
582-
}
583-
584-
ObjCClassWrapper* parentClassWrapper = static_cast<ObjCClassWrapper*>(parentWrapper);
585-
if (!parentClassWrapper->ExtendedClass()) {
586-
baseClass = parentClassWrapper->Klass();
587-
break;
588-
}
589-
590-
if (parentClassWrapper->ESDerivedClass()) {
591-
// Flatten: the parent's registered class sits directly under the pure native base, so
592-
// keep walking (collecting the parent's prototype for scanning) until we reach it.
593-
current = parent;
594-
continue;
595-
}
596-
597-
// Legacy `.extend()`-created base. Falling back to the parent's class would
598-
// register nothing and silently dispatch this class's overrides to the
599-
// parent's implementations, so refuse instead.
600-
throw NativeScriptException(
601-
std::string("Cannot extend \"") + class_getName(parentClassWrapper->Klass()) +
602-
"\" with an ES class: it was created by the legacy .extend() API. Convert the base class "
603-
"to an ES class, or declare this one with .extend() as well.");
557+
Local<Value> parentValue = ctorFunc->GetPrototype();
558+
if (parentValue.IsEmpty() || !parentValue->IsFunction()) {
559+
return nil;
604560
}
605561

562+
// The parent is native, legacy `.extend()`-created, already registered, or an
563+
// ES class that is registered here first so it can be this class's superclass.
564+
Class baseClass =
565+
ClassBuilder::EnsureExtendedClass(context, parentValue.As<v8::Function>(), nativeAllocates);
606566
if (baseClass == nil) {
607567
return nil;
608568
}
@@ -637,30 +597,27 @@ throw NativeScriptException(
637597
class_addProtocol(extendedClass, @protocol(TNSDerivedClass));
638598
class_addProtocol(object_getClass(extendedClass), @protocol(TNSDerivedClass));
639599

640-
// Expose members level by level, most-derived first, so JS shadowing semantics carry over to
641-
// the installed Objective-C implementations. Statics like ObjCProtocols/ObjCExposedMethods are
642-
// read through the constructor (inheriting through the static chain like class statics do).
643-
std::unordered_set<std::string> visitedNames;
644-
for (Local<v8::Function> levelCtor : chainCtors) {
645-
Local<Value> prototypeValue;
646-
bool success =
647-
levelCtor->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&prototypeValue);
648-
tns::Assert(success && !prototypeValue.IsEmpty() && prototypeValue->IsObject(), isolate);
649-
Local<Object> implementationObject = prototypeValue.As<Object>();
600+
// Statics like ObjCProtocols/ObjCExposedMethods are read through the constructor, so they
601+
// inherit through the static chain like class statics do: a subclass overriding a method
602+
// declared there still finds its signature.
603+
Local<Value> prototypeValue;
604+
bool success =
605+
ctorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&prototypeValue);
606+
tns::Assert(success && !prototypeValue.IsEmpty() && prototypeValue->IsObject(), isolate);
607+
Local<Object> implementationObject = prototypeValue.As<Object>();
650608

651-
Local<Value> exposedMethods;
652-
success = levelCtor->Get(context, tns::ToV8String(isolate, "ObjCExposedMethods"))
653-
.ToLocal(&exposedMethods);
654-
tns::Assert(success, isolate);
609+
Local<Value> exposedMethods;
610+
success = ctorFunc->Get(context, tns::ToV8String(isolate, "ObjCExposedMethods"))
611+
.ToLocal(&exposedMethods);
612+
tns::Assert(success, isolate);
655613

656-
Local<Value> exposedProtocols;
657-
success = levelCtor->Get(context, tns::ToV8String(isolate, "ObjCProtocols"))
658-
.ToLocal(&exposedProtocols);
659-
tns::Assert(success, isolate);
614+
Local<Value> exposedProtocols;
615+
success =
616+
ctorFunc->Get(context, tns::ToV8String(isolate, "ObjCProtocols")).ToLocal(&exposedProtocols);
617+
tns::Assert(success, isolate);
660618

661-
ClassBuilder::ExposeDynamicMethods(context, extendedClass, exposedMethods, exposedProtocols,
662-
implementationObject, &visitedNames);
663-
}
619+
ClassBuilder::ExposeDynamicMethods(context, extendedClass, exposedMethods, exposedProtocols,
620+
implementationObject);
664621

665622
tns::SetValue(isolate, ctorFunc, new ObjCClassWrapper(extendedClass, true, true));
666623

@@ -670,17 +627,13 @@ throw NativeScriptException(
670627
extendedPersistent->SetWrapperClassId(Constants::ClassTypes::DataWrapper);
671628
cache->CtorFuncs.emplace(extendedClassName, std::move(extendedPersistent));
672629

673-
Local<Value> ctorPrototypeValue;
674-
bool success =
675-
ctorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&ctorPrototypeValue);
676-
tns::Assert(success && !ctorPrototypeValue.IsEmpty() && ctorPrototypeValue->IsObject(), isolate);
677-
cache->ClassPrototypes.emplace(extendedClassName, std::make_unique<Persistent<Object>>(
678-
isolate, ctorPrototypeValue.As<Object>()));
630+
cache->ClassPrototypes.emplace(
631+
extendedClassName, std::make_unique<Persistent<Object>>(isolate, implementationObject));
679632

680633
ClassBuilder::SwizzleRetainRelease(isolate, extendedClass);
681634

682635
if (nativeAllocates && RuntimeConfig.IsDebug) {
683-
WarnIfConstructorIsUnreachable(context, chainCtors, extendedClass);
636+
WarnIfConstructorIsUnreachable(context, {ctorFunc}, extendedClass);
684637
}
685638

686639
return extendedClass;
@@ -963,9 +916,16 @@ throw NativeScriptException(
963916

964917
void ClassBuilder::ExposeDynamicMethods(Local<Context> context, Class extendedClass,
965918
Local<Value> exposedMethods, Local<Value> exposedProtocols,
966-
Local<Object> implementationObject,
967-
std::unordered_set<std::string>* visitedNames) {
919+
Local<Object> implementationObject) {
968920
Isolate* isolate = v8::Isolate::GetCurrent();
921+
// A subclass of a JS-defined class inherits its parent's implementations through the
922+
// Objective-C hierarchy; installing what it only inherits in JS would duplicate them.
923+
bool inheritsJsClass =
924+
class_conformsToProtocol(class_getSuperclass(extendedClass), @protocol(TNSDerivedClass));
925+
auto isOwnMember = [&](Local<v8::Name> key) {
926+
bool own = false;
927+
return !inheritsJsClass || (implementationObject->HasOwnProperty(context, key).To(&own) && own);
928+
};
969929
std::vector<const ProtocolMeta*> protocols;
970930
if (!exposedProtocols.IsEmpty() && exposedProtocols->IsArray()) {
971931
Local<v8::Array> protocolsArray = exposedProtocols.As<v8::Array>();
@@ -999,10 +959,7 @@ throw NativeScriptException(
999959
bool success = methodNames->Get(context, i).ToLocal(&methodName);
1000960
tns::Assert(success, isolate);
1001961

1002-
// When flattening a multi-level ES class chain, skip names already exposed by a more
1003-
// derived level (JS shadowing semantics)
1004-
if (visitedNames != nullptr &&
1005-
!visitedNames->insert("exposed:" + tns::ToString(isolate, methodName)).second) {
962+
if (!methodName->IsName() || !isOwnMember(methodName.As<v8::Name>())) {
1006963
continue;
1007964
}
1008965

@@ -1094,7 +1051,7 @@ throw NativeScriptException(
10941051
tns::Assert(success, isolate);
10951052

10961053
if (!symbolIterator.IsEmpty() && symbolIterator->IsFunction() &&
1097-
!class_conformsToProtocol(extendedClass, @protocol(NSFastEnumeration))) {
1054+
isOwnMember(Symbol::GetIterator(isolate))) {
10981055
Local<v8::Function> symbolIteratorFunc = symbolIterator.As<v8::Function>();
10991056

11001057
class_addProtocol(extendedClass, @protocol(NSFastEnumeration));
@@ -1139,12 +1096,6 @@ throw NativeScriptException(
11391096
continue;
11401097
}
11411098

1142-
// When flattening a multi-level ES class chain, skip names already handled by a more derived
1143-
// level (JS shadowing semantics)
1144-
if (visitedNames != nullptr && !visitedNames->insert(methodName).second) {
1145-
continue;
1146-
}
1147-
11481099
Local<Value> propertyDescriptor;
11491100
tns::Assert(implementationObject->GetOwnPropertyDescriptor(context, key.As<v8::Name>())
11501101
.ToLocal(&propertyDescriptor),
@@ -1403,19 +1354,35 @@ throw NativeScriptException(
14031354
Local<Context> context = isolate->GetCurrentContext();
14041355
Local<Object> thiz = info.This();
14051356

1357+
// Resolved from the class that owns this accessor, not from the receiver: an ES subclass of a
1358+
// legacy class puts more prototypes between the instance and the implementation object.
1359+
CacheItem* item = static_cast<CacheItem*>(
1360+
info.Data().As<External>()->Value(v8::kExternalPointerTypeTagDefault));
1361+
auto cache = Caches::Get(isolate);
1362+
auto it = cache->ClassPrototypes.find(std::string_view(class_getName(item->data_)));
1363+
tns::Assert(it != cache->ClassPrototypes.end(), isolate);
1364+
Local<Object> implementationObject = it->second->Get(isolate)->GetPrototype().As<Object>();
1365+
14061366
std::shared_ptr<Persistent<Value>> poValue = ArgConverter::CreateEmptyObject(context);
14071367
Local<Object> superValue = poValue->Get(isolate).As<Object>();
14081368

1409-
superValue
1410-
->SetPrototype(context,
1411-
thiz->GetPrototype().As<Object>()->GetPrototype().As<Object>()->GetPrototype())
1412-
.ToChecked();
1369+
superValue->SetPrototype(context, implementationObject->GetPrototype()).ToChecked();
14131370
superValue->SetInternalField(0, thiz->GetInternalField(0));
14141371
superValue->SetInternalField(1, tns::ToV8String(isolate, "super"));
14151372

14161373
info.GetReturnValue().Set(superValue);
14171374
}
14181375

1376+
Class ClassBuilder::GetNativeSuperclass(Class klass) {
1377+
Class rootmostDerived = nil;
1378+
for (Class c = klass; c != nil; c = class_getSuperclass(c)) {
1379+
if (class_conformsToProtocol(c, @protocol(TNSDerivedClass))) {
1380+
rootmostDerived = c;
1381+
}
1382+
}
1383+
return class_getSuperclass(rootmostDerived != nil ? rootmostDerived : klass);
1384+
}
1385+
14191386
IMP ClassBuilder::FindNotOverridenMethod(Class klass, SEL method) {
14201387
while (class_conformsToProtocol(klass, @protocol(TNSDerivedClass))) {
14211388
klass = class_getSuperclass(klass);

‎NativeScript/runtime/Interop.mm‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1828,7 +1828,7 @@ throw NativeScriptException(
18281828
18291829
if (methodCall.callSuper_) {
18301830
sup.receiver = methodCall.target_;
1831-
sup.super_class = class_getSuperclass(object_getClass(methodCall.target_));
1831+
sup.super_class = ClassBuilder::GetNativeSuperclass(object_getClass(methodCall.target_));
18321832
Interop::SetValue(call.ArgumentBuffer(0), &sup);
18331833
} else {
18341834
Interop::SetValue(call.ArgumentBuffer(0), methodCall.target_);

0 commit comments

Comments
 (0)