Skip to content

Commit 360f29b

Browse files
committed
feat(es-classes): run the constructor for every instance, through interop.initializer
Objects Objective-C creates itself (alloc/init, cell reuse, storyboards, NSCoding) reached JS as a bare object with the class prototype grafted on: the constructor never ran, so class fields were undefined and #private access threw. And super(...) matched positional arguments against initializer signatures by JS value shape, conflating the class's own data with the choice of native initializer. A class extending a native type now constructs through one contract: - super(...) takes nothing or a single options object. The class's own keys are plain data; [interop.initializer.args] names the initializer by its constructor tokens, matched as a set ({ frame } -> initWithFrame:), and is `init` when absent. - The first ES class above a native or legacy base gets a hook for every metadata initializer the base implements. When Objective-C sends one, the hook runs the JS constructor with { [interop.initializer.native]: { selector, args }, [interop.initializer.args]: <tokens of that call> }, and super(...) runs that initializer with the original arguments, exactly once. A constructor can force another initializer, like an ObjC -init calling [super initWithStyle:]; spread order decides default versus force. - `this` is bound to the object before the initializer runs, on both paths, so overrides the initializer calls see the instance. - An instance initialized through an initializer the metadata does not list is constructed the first time it reaches JS, with [interop.initializer.native].selector null and no initializer run. - A constructor failing inside an initializer Objective-C sent is reported through the uncaught-error path, and the initializer returns nil after releasing what the caller allocated. - An ES class defining a method that overrides an initializer is refused at registration: the constructor already runs for every initializer. - An NSException an initializer raises becomes a JS Error, as for any other native call (Interop::ThrowAsJSError, shared with CallFunctionInternal). Interop::GetResult now releases the surplus +1 when an owned result (alloc/new/copy, or an initializer sent to a receiver allocated for the call) is already wrapped. It returned the cached wrapper without balancing it, which every JS-side `X.alloc().init()` on an ES class now hits, since the hook binds the object before the initializer returns. An initializer sent to an already wrapped receiver still keeps its +1: that is the receiver's own reference passing through. The super(...) positional and bare-token forms throw with the spelling to use instead. The source-text debug warning about unreachable constructors is gone, along with the condition it warned about.
1 parent 92c061b commit 360f29b

12 files changed

Lines changed: 1160 additions & 265 deletions

File tree

‎NativeScript/runtime/ArgConverter.h‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,19 @@ class ArgConverter {
9595
const v8::FunctionCallbackInfo<v8::Value>& info,
9696
Class klass,
9797
const InterfaceMeta* interfaceMeta = nullptr);
98+
static std::vector<const MethodMeta*> GetInitializers(
99+
Caches* cache, Class klass, const InterfaceMeta* interfaceMeta);
100+
// An initializer's constructor tokens in selector order, e.g. { "int",
101+
// "andInt" } for initWithInt:andInt:, empty for init.
102+
static std::vector<std::string> ConstructorTokens(const MethodMeta* meta);
103+
// The initializer klass implements whose constructor tokens are exactly the
104+
// own keys of `tokens`, in any order; key order only breaks a tie between
105+
// initializers taking the same set. Fills args in selector order. Returns
106+
// nullptr when none matches, or throws listing the available token sets when
107+
// throwIfMissing.
108+
static const MethodMeta* FindInitializerByTokens(
109+
v8::Local<v8::Context> context, Class klass, v8::Local<v8::Object> tokens,
110+
std::vector<v8::Local<v8::Value>>& args, bool throwIfMissing);
98111

99112
private:
100113
static v8::Local<v8::Function> CreateEmptyInstanceFunction(
@@ -126,8 +139,6 @@ class ArgConverter {
126139
uint32_t index, v8::Local<v8::Value> value,
127140
const v8::PropertyCallbackInfo<v8::Boolean>& args);
128141
static bool IsErrorOutParameter(const TypeEncoding* typeEncoding);
129-
static std::vector<const MethodMeta*> GetInitializers(
130-
Caches* cache, Class klass, const InterfaceMeta* interfaceMeta);
131142
static void MethodCallbackInternal(ffi_cif* cif, void* retValue,
132143
void** argValues, void* userData);
133144
};

‎NativeScript/runtime/ArgConverter.mm‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
#include "ArgConverter.h"
22
#include <Foundation/Foundation.h>
33
#include <algorithm>
4+
#include <set>
45
#include <sstream>
6+
#include "ClassBuilder.h"
57
#include "DictionaryAdapter.h"
68
#include "ExternalMemory.h"
79
#include "Helpers.h"
@@ -115,6 +117,7 @@
115117
}
116118

117119
ObjCMethodCall methodCall(context, meta, target, klass, args, callSuper);
120+
methodCall.receiverAllocatedForCall_ = allocKlass != nil;
118121
return Interop::CallFunction(methodCall);
119122
}
120123

@@ -579,6 +582,11 @@
579582
Isolate* isolate = v8::Isolate::GetCurrent();
580583
tns::Assert(klass != nullptr, isolate);
581584
585+
if (ClassBuilder::IsESDerivedConstructor(isolate, info.NewTarget())) {
586+
ClassBuilder::ConstructESObject(context, info, klass);
587+
return;
588+
}
589+
582590
id result = nil;
583591
// A Caches::Instances entry owns exactly one reference to the object it maps
584592
// (ObjectManager::DisposeValue gives it back, and ClassBuilder's swizzled
@@ -904,6 +912,10 @@
904912
if (it != cache->Instances.end()) {
905913
receiver = it->second->Get(isolate).As<Object>();
906914
} else {
915+
Local<Value> adopted;
916+
if (ClassBuilder::TryAdoptNativeInstance(context, target, adopted)) {
917+
return adopted;
918+
}
907919
std::shared_ptr<Persistent<Value>> poValue = CreateEmptyObject(context, skipGCRegistration);
908920
receiver = poValue->Get(isolate).As<Object>();
909921
tns::SetValue(isolate, receiver, wrapper);
@@ -1285,4 +1297,131 @@
12851297
return initializers;
12861298
}
12871299
1300+
std::vector<std::string> ArgConverter::ConstructorTokens(const MethodMeta* meta) {
1301+
std::vector<std::string> tokens;
1302+
std::string token;
1303+
for (const char* c = meta->constructorTokens(); *c != '\0'; c++) {
1304+
if (*c == ':') {
1305+
tokens.push_back(token);
1306+
token.clear();
1307+
} else {
1308+
token += *c;
1309+
}
1310+
}
1311+
return tokens;
1312+
}
1313+
1314+
static std::string FormatTokens(const std::vector<std::string>& tokens) {
1315+
if (tokens.empty()) {
1316+
return "{}";
1317+
}
1318+
std::string result = "{ ";
1319+
for (size_t i = 0; i < tokens.size(); i++) {
1320+
result += (i > 0 ? ", " : "") + tokens[i];
1321+
}
1322+
return result + " }";
1323+
}
1324+
1325+
const MethodMeta* ArgConverter::FindInitializerByTokens(Local<Context> context, Class klass,
1326+
Local<Object> tokens,
1327+
std::vector<Local<Value>>& args,
1328+
bool throwIfMissing) {
1329+
Isolate* isolate = v8::Isolate::GetCurrent();
1330+
Local<v8::Array> names;
1331+
{
1332+
TryCatch tc(isolate);
1333+
if (!tokens->GetOwnPropertyNames(context).ToLocal(&names)) {
1334+
throw NativeScriptException(isolate, tc, "Cannot read initializer tokens");
1335+
}
1336+
}
1337+
std::vector<std::string> keys;
1338+
for (uint32_t i = 0; i < names->Length(); i++) {
1339+
Local<Value> name;
1340+
if (names->Get(context, i).ToLocal(&name)) {
1341+
keys.push_back(tns::ToString(isolate, name));
1342+
}
1343+
}
1344+
std::vector<std::string> sortedKeys = keys;
1345+
std::sort(sortedKeys.begin(), sortedKeys.end());
1346+
1347+
std::vector<const MethodMeta*> matches;
1348+
const MethodMeta* sameOrder = nullptr;
1349+
std::vector<std::string> available;
1350+
const Meta* meta = FindMeta(klass);
1351+
if (meta != nullptr && meta->type() == MetaType::Interface) {
1352+
auto cache = Caches::Get(isolate);
1353+
std::set<SEL> seen;
1354+
for (const InterfaceMeta* interfaceMeta = static_cast<const InterfaceMeta*>(meta);
1355+
interfaceMeta != nullptr; interfaceMeta = interfaceMeta->baseMeta()) {
1356+
for (const MethodMeta* candidate :
1357+
GetInitializers(cache.get(), objc_getClass(interfaceMeta->name()), interfaceMeta)) {
1358+
SEL selector = candidate->selector();
1359+
if (candidate->isVariadic() || !seen.insert(selector).second ||
1360+
![klass instancesRespondToSelector:selector]) {
1361+
continue;
1362+
}
1363+
std::vector<std::string> candidateTokens = ConstructorTokens(candidate);
1364+
available.push_back(FormatTokens(candidateTokens));
1365+
std::vector<std::string> sortedTokens = candidateTokens;
1366+
std::sort(sortedTokens.begin(), sortedTokens.end());
1367+
if (sortedTokens != sortedKeys) {
1368+
continue;
1369+
}
1370+
matches.push_back(candidate);
1371+
if (candidateTokens == keys && sameOrder == nullptr) {
1372+
sameOrder = candidate;
1373+
}
1374+
}
1375+
}
1376+
}
1377+
1378+
const MethodMeta* match = nullptr;
1379+
if (matches.size() == 1) {
1380+
match = matches[0];
1381+
} else if (matches.size() > 1 && sameOrder != nullptr) {
1382+
match = sameOrder;
1383+
}
1384+
1385+
if (match == nullptr) {
1386+
if (!throwIfMissing) {
1387+
return nullptr;
1388+
}
1389+
std::stringstream ss;
1390+
if (matches.size() > 1) {
1391+
ss << "More than one initializer of " << class_getName(klass) << " takes "
1392+
<< FormatTokens(keys) << ":";
1393+
for (const MethodMeta* candidate : matches) {
1394+
ss << " " << candidate->selectorAsString();
1395+
}
1396+
ss << ". List the keys in the order of the one to run.";
1397+
} else {
1398+
ss << "No initializer of " << class_getName(klass) << " takes " << FormatTokens(keys)
1399+
<< ". Available:";
1400+
for (size_t i = 0; i < available.size(); i++) {
1401+
ss << (i > 0 ? ", " : " ") << available[i];
1402+
}
1403+
}
1404+
throw NativeScriptException(ss.str());
1405+
}
1406+
1407+
args.clear();
1408+
// A parameterless initializer still has a token (initWithEmpty -> { empty }), so the values
1409+
// passed are bounded by the parameters, not the tokens.
1410+
size_t paramsCount = match->encodings()->count - 1 - (match->hasErrorOutParameter() ? 1 : 0);
1411+
std::vector<std::string> matchTokens = ConstructorTokens(match);
1412+
TryCatch tc(isolate);
1413+
for (size_t i = 0; i < matchTokens.size() && i < paramsCount; i++) {
1414+
Local<Value> value;
1415+
if (!tokens->Get(context, tns::ToV8String(isolate, matchTokens[i])).ToLocal(&value)) {
1416+
throw NativeScriptException(isolate, tc, "Cannot read initializer tokens");
1417+
}
1418+
args.push_back(value);
1419+
}
1420+
if (match->hasErrorOutParameter()) {
1421+
// The NSError** an error-out initializer takes: never exposed as a token.
1422+
args.push_back(v8::Null(isolate));
1423+
}
1424+
return match;
1425+
}
1426+
12881427
} // namespace tns

‎NativeScript/runtime/Caches.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,10 @@ class Caches {
155155
robin_hood::unordered_map<std::string,
156156
std::unique_ptr<v8::Persistent<v8::Function>>>
157157
ProtocolCtorFuncs;
158+
// Classes registered from plain ES `class X extends Native {}` constructors.
159+
// Membership is the cheap test that keeps every object's first wrap from
160+
// looking up a constructor by name.
161+
robin_hood::unordered_set<Class> ESClasses;
158162
robin_hood::unordered_map<BinaryTypeEncodingType,
159163
std::unique_ptr<v8::Persistent<v8::Object>>>
160164
PrimitiveInteropTypes;

‎NativeScript/runtime/ClassBuilder.h‎

Lines changed: 34 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -51,12 +51,9 @@ class ClassBuilder {
5151
// 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
5353
// chain. Idempotent: subsequent calls return the cached class from the ctor's
54-
// ObjCClassWrapper. Pass nativeAllocates when the caller is handing the class
55-
// to Objective-C (or allocating through it), which is what makes the JS
56-
// constructor unreachable and gates the debug diagnostic.
54+
// ObjCClassWrapper.
5755
static Class EnsureExtendedClass(v8::Local<v8::Context> context,
58-
v8::Local<v8::Function> ctorFunc,
59-
bool nativeAllocates = false);
56+
v8::Local<v8::Function> ctorFunc);
6057

6158
// Resolves the Objective-C class that should be instantiated for a construct
6259
// call, honoring `new.target` so that plain ES subclasses of native classes
@@ -65,12 +62,36 @@ class ClassBuilder {
6562
v8::Local<v8::Value> newTarget,
6663
Class fallback);
6764

68-
// Throws unless a super(...) call from a plain ES subclass uses a form that
69-
// names exactly one initializer. Call after ResolveConstructedClass, which
70-
// is what marks new.target as ES-derived.
71-
static void ValidateEsClassSuperArgs(
72-
v8::Local<v8::Context> context,
73-
const v8::FunctionCallbackInfo<v8::Value>& info);
65+
// True when a construct call's new.target is a plain ES class registered by
66+
// EnsureExtendedClass, whose super(...) follows the interop.initializer
67+
// contract rather than the legacy constructor-argument matching.
68+
static bool IsESDerivedConstructor(v8::Isolate* isolate,
69+
v8::Local<v8::Value> newTarget);
70+
71+
// The native end of super(...) for an ES class. Binds info.This() to the
72+
// object being initialized before the initializer runs, so overrides the
73+
// initializer calls see the instance under construction:
74+
// - inside an initializer hook (Objective-C started the construction), the
75+
// object already exists and the initializer the caller sent runs unless
76+
// the constructor names another in [interop.initializer.args];
77+
// - when adopting an object first seen after an initializer that has no
78+
// hook, the object is bound as is and no initializer runs;
79+
// - otherwise (`new X(...)`), klass is allocated and initialized with the
80+
// initializer [interop.initializer.args] names, or `init`.
81+
static void ConstructESObject(v8::Local<v8::Context> context,
82+
const v8::FunctionCallbackInfo<v8::Value>& info,
83+
Class klass);
84+
85+
// Runs the ES constructor for an instance of an ES class that reaches JS
86+
// without having been constructed, i.e. one initialized through an
87+
// initializer the metadata does not list and so has no hook. Returns false
88+
// when target is not such an instance.
89+
static bool TryAdoptNativeInstance(v8::Local<v8::Context> context, id target,
90+
v8::Local<v8::Value>& result);
91+
92+
// Defines interop.initializer.{args,native}.
93+
static void RegisterInitializerSymbols(v8::Local<v8::Context> context,
94+
v8::Local<v8::Object> interop);
7495

7596
// The class a JS `super.method()` reaching a native method must dispatch
7697
// to: the superclass of the rootmost JS-defined class in klass's chain. A JS
@@ -89,9 +110,8 @@ class ClassBuilder {
89110
const v8::FunctionCallbackInfo<v8::Value>& info);
90111

91112
static void SwizzleRetainRelease(v8::Isolate* isolate, Class extendedClass);
92-
static void WarnIfConstructorIsUnreachable(
93-
v8::Local<v8::Context> context,
94-
const std::vector<v8::Local<v8::Function>>& chainCtors, Class extendedClass);
113+
static void InstallInitializerHooks(v8::Isolate* isolate,
114+
Class extendedClass);
95115
static void ExposeDynamicMethods(v8::Local<v8::Context> context,
96116
Class extendedClass,
97117
v8::Local<v8::Value> exposedMethods,

0 commit comments

Comments
 (0)