Skip to content

Commit

Permalink
Add Hermes implementation for Object.create with prototype
Browse files Browse the repository at this point in the history
Summary:
Adds the implementation `createObjectWithPrototype` JSI method for
Hermes runtime.

Grafted from 1053185886992b918021c4d2578a0807f797dd00 (D66487948)
- Grafted path xplat/static_h to xplat/hermes

Reviewed By: tmikov

Differential Revision: D67412929

fbshipit-source-id: a283ffc775494f7df2bdcf9a91ada188b673c071
  • Loading branch information
tsaichien authored and facebook-github-bot committed Jan 9, 2025
1 parent 9f0b77f commit a942ef3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
14 changes: 14 additions & 0 deletions API/hermes/hermes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,7 @@ class HermesRuntimeImpl final : public HermesRuntime,
jsi::Object createObject() override;
jsi::Object createObject(std::shared_ptr<jsi::HostObject> ho) override;
std::shared_ptr<jsi::HostObject> getHostObject(const jsi::Object &) override;
jsi::Object createObjectWithPrototype(const jsi::Value &prototype) override;
jsi::HostFunctionType &getHostFunction(const jsi::Function &) override;
bool hasNativeState(const jsi::Object &) override;
std::shared_ptr<jsi::NativeState> getNativeState(
Expand Down Expand Up @@ -1874,6 +1875,19 @@ jsi::Object HermesRuntimeImpl::createObject(
return add<jsi::Object>(*objRes);
}

jsi::Object HermesRuntimeImpl::createObjectWithPrototype(
const jsi::Value &prototype) {
if (!prototype.isObject() && !prototype.isNull()) {
throw jsi::JSError(
*this, "Object prototype argument must be an Object or null");
}

auto object = vm::JSObject::create(
runtime_,
vm::Handle<vm::JSObject>::dyn_vmcast(vmHandleFromValue(prototype)));
return add<jsi::Object>(object.getHermesValue());
}

std::shared_ptr<jsi::HostObject> HermesRuntimeImpl::getHostObject(
const jsi::Object &obj) {
const vm::HostObjectProxy *proxy =
Expand Down
16 changes: 16 additions & 0 deletions unittests/API/APITest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1294,6 +1294,22 @@ TEST_P(HermesRuntimeTest, SetPrototypeOf) {
EXPECT_THROW(child.setPrototype(*rt, Value(1)), JSError);
}

TEST_P(HermesRuntimeTest, CreateObjectWithPrototype) {
Object prototypeObj(*rt);
prototypeObj.setProperty(*rt, "someProperty", 123);
Value prototype(*rt, prototypeObj);

Object child = Object::create(*rt, prototype);
EXPECT_EQ(child.getProperty(*rt, "someProperty").getNumber(), 123);

// Tests null value as prototype
child = Object::create(*rt, Value::null());
EXPECT_TRUE(child.getPrototype(*rt).isNull());

// Throw when prototype is neither an Object nor null
EXPECT_THROW(Object::create(*rt, Value(1)), JSError);
}

INSTANTIATE_TEST_CASE_P(
Runtimes,
HermesRuntimeTest,
Expand Down

0 comments on commit a942ef3

Please sign in to comment.