Skip to content

Commit

Permalink
New bridging API for JSI <-> C++
Browse files Browse the repository at this point in the history
Summary:
This adds  `bridging::toJs` and `bridging::fromJs` functions that will safely cast to and from JSI values and C++ types. This is extensible by specializing `Bridging<T>` with `toJs` and/or `fromJs` static methods. There are specializations for most common C++ and JSI types along with tests for those.

C++ functions and lambdas will effortlessly bridge into JS, and bridging JS functions back into C++ require you to choose `SyncCallback<R(Args...)>` or `AsyncCallback<Args...>` types. The sync version allows for having a return value and is strictly not movable to prevent accidentally moving onto another thread. The async version will move its args onto the JS thread and safely call the callback there, but hence always has a `void` return value.

For promises, you can construct a `AsyncPromise<T>` that has `resolve` and `reject` methods that can be called from any thread, and will bridge into JS as a regular `Promise`.

Changelog:
[General][Added] - New bridging API for JSI <-> C++

Reviewed By: christophpurrer

Differential Revision: D34607143

fbshipit-source-id: d832ac24cf84b4c1672a7b544d82e324d5fca3ef
  • Loading branch information
appden authored and facebook-github-bot committed Mar 11, 2022
1 parent 6a9497d commit 30cb78e
Show file tree
Hide file tree
Showing 18 changed files with 1,469 additions and 1 deletion.
108 changes: 108 additions & 0 deletions ReactCommon/react/bridging/Array.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#pragma once

#include <react/bridging/Base.h>

#include <array>
#include <deque>
#include <initializer_list>
#include <list>
#include <tuple>
#include <utility>
#include <vector>

namespace facebook::react {

namespace array_detail {

template <typename T, size_t N>
struct BridgingStatic {
static jsi::Array toJs(
jsi::Runtime &rt,
const T &array,
const std::shared_ptr<CallInvoker> &jsInvoker) {
return toJs(rt, array, jsInvoker, std::make_index_sequence<N>{});
}

private:
template <size_t... Index>
static jsi::Array toJs(
facebook::jsi::Runtime &rt,
const T &array,
const std::shared_ptr<CallInvoker> &jsInvoker,
std::index_sequence<Index...>) {
return jsi::Array::createWithElements(
rt, bridging::toJs(rt, std::get<Index>(array), jsInvoker)...);
}
};

template <typename T>
struct BridgingDynamic {
static jsi::Array toJs(
jsi::Runtime &rt,
const T &list,
const std::shared_ptr<CallInvoker> &jsInvoker) {
jsi::Array result(rt, list.size());
size_t index = 0;

for (const auto &item : list) {
result.setValueAtIndex(rt, index++, bridging::toJs(rt, item, jsInvoker));
}

return result;
}
};

} // namespace array_detail

template <typename T, size_t N>
struct Bridging<std::array<T, N>>
: array_detail::BridgingStatic<std::array<T, N>, N> {};

template <typename T1, typename T2>
struct Bridging<std::pair<T1, T2>>
: array_detail::BridgingStatic<std::pair<T1, T2>, 2> {};

template <typename... Types>
struct Bridging<std::tuple<Types...>>
: array_detail::BridgingStatic<std::tuple<Types...>, sizeof...(Types)> {};

template <typename T>
struct Bridging<std::deque<T>> : array_detail::BridgingDynamic<std::deque<T>> {
};

template <typename T>
struct Bridging<std::initializer_list<T>>
: array_detail::BridgingDynamic<std::initializer_list<T>> {};

template <typename T>
struct Bridging<std::list<T>> : array_detail::BridgingDynamic<std::list<T>> {};

template <typename T>
struct Bridging<std::vector<T>>
: array_detail::BridgingDynamic<std::vector<T>> {
static std::vector<T> fromJs(
facebook::jsi::Runtime &rt,
const jsi::Array &array,
const std::shared_ptr<CallInvoker> &jsInvoker) {
size_t length = array.length(rt);

std::vector<T> vector;
vector.reserve(length);

for (size_t i = 0; i < length; i++) {
vector.push_back(
bridging::fromJs<T>(rt, array.getValueAtIndex(rt, i), jsInvoker));
}

return vector;
}
};

} // namespace facebook::react
36 changes: 35 additions & 1 deletion ReactCommon/react/bridging/BUCK
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "APPLE", "CXX", "react_native_xplat_shared_library_target", "react_native_xplat_target", "rn_xplat_cxx_library")
load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "APPLE", "CXX", "IOS", "MACOSX", "fb_xplat_cxx_test", "react_native_xplat_shared_library_target", "react_native_xplat_target", "rn_xplat_cxx_library")

rn_xplat_cxx_library(
name = "bridging",
srcs = glob(["*.cpp"]),
header_namespace = "react/bridging",
exported_headers = glob(["*.h"]),
compiler_flags_enable_exceptions = True,
compiler_flags_enable_rtti = True,
labels = ["supermodule:xplat/default/public.react_native.infra"],
platforms = (ANDROID, APPLE, CXX),
tests = [":tests"],
visibility = ["PUBLIC"],
deps = [
"//xplat/folly:headers_only",
Expand All @@ -17,3 +20,34 @@ rn_xplat_cxx_library(
react_native_xplat_shared_library_target("jsi:jsi"),
],
)

rn_xplat_cxx_library(
name = "testlib",
header_namespace = "react/bridging",
exported_headers = glob(["tests/*.h"]),
platforms = (ANDROID, APPLE, CXX),
visibility = ["PUBLIC"],
exported_deps = [
"//xplat/third-party/gmock:gtest",
],
)

fb_xplat_cxx_test(
name = "tests",
srcs = glob(["tests/*.cpp"]),
headers = glob(["tests/*.h"]),
apple_sdks = (IOS, MACOSX),
compiler_flags = [
"-fexceptions",
"-frtti",
"-std=c++17",
"-Wall",
],
contacts = ["oncall+react_native@xmail.facebook.com"],
platforms = (ANDROID, APPLE, CXX),
deps = [
":bridging",
"//xplat/hermes/API:HermesAPI",
"//xplat/third-party/gmock:gtest",
],
)
124 changes: 124 additions & 0 deletions ReactCommon/react/bridging/Base.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#pragma once

#include <react/bridging/Convert.h>

#include <ReactCommon/CallInvoker.h>
#include <folly/Function.h>
#include <jsi/jsi.h>

#include <cstdint>
#include <memory>
#include <type_traits>

namespace facebook::react {

template <typename T, typename = void>
struct Bridging;

template <>
struct Bridging<void> {
// Highly generic code may result in "casting" to void.
static void fromJs(jsi::Runtime &, const jsi::Value &) {}
};

namespace bridging {
namespace detail {

template <typename F>
struct function_wrapper;

template <typename C, typename R, typename... Args>
struct function_wrapper<R (C::*)(Args...)> {
using type = folly::Function<R(Args...)>;
};

template <typename C, typename R, typename... Args>
struct function_wrapper<R (C::*)(Args...) const> {
using type = folly::Function<R(Args...)>;
};

template <typename T, typename = void>
struct bridging_wrapper {
using type = remove_cvref_t<T>;
};

// Convert lambda types to move-only function types since we can't specialize
// Bridging templates for arbitrary lambdas.
template <typename T>
struct bridging_wrapper<
T,
std::void_t<decltype(&remove_cvref_t<T>::operator())>>
: function_wrapper<decltype(&remove_cvref_t<T>::operator())> {};

} // namespace detail

template <typename T>
using bridging_t = typename detail::bridging_wrapper<T>::type;

template <typename R, typename T, std::enable_if_t<is_jsi_v<T>, int> = 0>
auto fromJs(jsi::Runtime &rt, T &&value, const std::shared_ptr<CallInvoker> &)
-> decltype(static_cast<R>(convert(rt, std::forward<T>(value)))) {
return convert(rt, std::forward<T>(value));
}

template <typename R, typename T>
auto fromJs(jsi::Runtime &rt, T &&value, const std::shared_ptr<CallInvoker> &)
-> decltype(Bridging<remove_cvref_t<R>>::fromJs(
rt,
convert(rt, std::forward<T>(value)))) {
return Bridging<remove_cvref_t<R>>::fromJs(
rt, convert(rt, std::forward<T>(value)));
}

template <typename R, typename T>
auto fromJs(
jsi::Runtime &rt,
T &&value,
const std::shared_ptr<CallInvoker> &jsInvoker)
-> decltype(Bridging<remove_cvref_t<R>>::fromJs(
rt,
convert(rt, std::forward<T>(value)),
jsInvoker)) {
return Bridging<remove_cvref_t<R>>::fromJs(
rt, convert(rt, std::forward<T>(value)), jsInvoker);
}

template <typename T, std::enable_if_t<is_jsi_v<T>, int> = 0>
auto toJs(
jsi::Runtime &rt,
T &&value,
const std::shared_ptr<CallInvoker> & = nullptr)
-> decltype(convert(rt, std::forward<T>(value))) {
return convert(rt, std::forward<T>(value));
}

template <typename T>
auto toJs(
jsi::Runtime &rt,
T &&value,
const std::shared_ptr<CallInvoker> & = nullptr)
-> decltype(Bridging<bridging_t<T>>::toJs(rt, std::forward<T>(value))) {
return Bridging<bridging_t<T>>::toJs(rt, std::forward<T>(value));
}

template <typename T>
auto toJs(
jsi::Runtime &rt,
T &&value,
const std::shared_ptr<CallInvoker> &jsInvoker)
-> decltype(Bridging<bridging_t<T>>::toJs(
rt,
std::forward<T>(value),
jsInvoker)) {
return Bridging<bridging_t<T>>::toJs(rt, std::forward<T>(value), jsInvoker);
}

} // namespace bridging
} // namespace facebook::react
25 changes: 25 additions & 0 deletions ReactCommon/react/bridging/Bool.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#pragma once

#include <react/bridging/Base.h>

namespace facebook::react {

template <>
struct Bridging<bool> {
static bool fromJs(jsi::Runtime &rt, const jsi::Value &value) {
return value.asBool();
}

static jsi::Value toJs(jsi::Runtime &, bool value) {
return value;
}
};

} // namespace facebook::react
18 changes: 18 additions & 0 deletions ReactCommon/react/bridging/Bridging.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#pragma once

#include <react/bridging/Array.h>
#include <react/bridging/Bool.h>
#include <react/bridging/Error.h>
#include <react/bridging/Function.h>
#include <react/bridging/Number.h>
#include <react/bridging/Object.h>
#include <react/bridging/Promise.h>
#include <react/bridging/String.h>
#include <react/bridging/Value.h>
4 changes: 4 additions & 0 deletions ReactCommon/react/bridging/CallbackWrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ class CallbackWrapper : public LongLivedObject {
return *(jsInvoker_);
}

std::shared_ptr<CallInvoker> jsInvokerPtr() {
return jsInvoker_;
}

void allowRelease() override {
if (auto longLivedObjectCollection = longLivedObjectCollection_.lock()) {
if (longLivedObjectCollection != nullptr) {
Expand Down
Loading

0 comments on commit 30cb78e

Please sign in to comment.