diff --git a/ReactCommon/better/mutex.h b/ReactCommon/better/mutex.h index dc87ed8f114..e8451f818b7 100644 --- a/ReactCommon/better/mutex.h +++ b/ReactCommon/better/mutex.h @@ -8,8 +8,8 @@ #pragma once #include -#include #include +#include namespace facebook { namespace better { diff --git a/ReactCommon/config/ReactNativeConfig.h b/ReactCommon/config/ReactNativeConfig.h index de30d678635..328dc54a3bf 100644 --- a/ReactCommon/config/ReactNativeConfig.h +++ b/ReactCommon/config/ReactNativeConfig.h @@ -17,7 +17,7 @@ namespace react { * Provide a sub-class implementation to allow app specific customization. */ class ReactNativeConfig { -public: + public: ReactNativeConfig(); virtual ~ReactNativeConfig(); @@ -31,7 +31,7 @@ public: * Empty configuration that will always provide "falsy" values. */ class EmptyReactNativeConfig : public ReactNativeConfig { -public: + public: EmptyReactNativeConfig(); bool getBool(const std::string ¶m) const override; diff --git a/ReactCommon/cxxreact/CxxModule.h b/ReactCommon/cxxreact/CxxModule.h index 13bd8b5b3de..64b7db64259 100644 --- a/ReactCommon/cxxreact/CxxModule.h +++ b/ReactCommon/cxxreact/CxxModule.h @@ -21,7 +21,8 @@ namespace react { class Instance; -}} +} +} // namespace facebook namespace facebook { namespace xplat { @@ -57,7 +58,7 @@ class CxxModule { class AsyncTagType {}; class SyncTagType {}; -public: + public: typedef std::function()> Provider; typedef std::function)> Callback; @@ -81,81 +82,103 @@ public: // std::function/lambda ctors - Method(std::string aname, - std::function&& afunc) - : name(std::move(aname)) - , callbacks(0) - , isPromise(false) - , func(std::bind(std::move(afunc))) {} + Method(std::string aname, std::function &&afunc) + : name(std::move(aname)), + callbacks(0), + isPromise(false), + func(std::bind(std::move(afunc))) {} - Method(std::string aname, - std::function&& afunc) - : name(std::move(aname)) - , callbacks(0) - , isPromise(false) - , func(std::bind(std::move(afunc), std::placeholders::_1)) {} + Method(std::string aname, std::function &&afunc) + : name(std::move(aname)), + callbacks(0), + isPromise(false), + func(std::bind(std::move(afunc), std::placeholders::_1)) {} - Method(std::string aname, - std::function&& afunc) - : name(std::move(aname)) - , callbacks(1) - , isPromise(false) - , func(std::bind(std::move(afunc), std::placeholders::_1, std::placeholders::_2)) {} + Method( + std::string aname, + std::function &&afunc) + : name(std::move(aname)), + callbacks(1), + isPromise(false), + func(std::bind( + std::move(afunc), + std::placeholders::_1, + std::placeholders::_2)) {} - Method(std::string aname, - std::function&& afunc) - : name(std::move(aname)) - , callbacks(2) - , isPromise(true) - , func(std::move(afunc)) {} + Method( + std::string aname, + std::function &&afunc) + : name(std::move(aname)), + callbacks(2), + isPromise(true), + func(std::move(afunc)) {} - Method(std::string aname, - std::function&& afunc, - AsyncTagType) - : name(std::move(aname)) - , callbacks(2) - , isPromise(false) - , func(std::move(afunc)) {} + Method( + std::string aname, + std::function &&afunc, + AsyncTagType) + : name(std::move(aname)), + callbacks(2), + isPromise(false), + func(std::move(afunc)) {} // method pointer ctors template - Method(std::string aname, T* t, void (T::*method)()) - : name(std::move(aname)) - , callbacks(0) - , isPromise(false) - , func(std::bind(method, t)) {} + Method(std::string aname, T *t, void (T::*method)()) + : name(std::move(aname)), + callbacks(0), + isPromise(false), + func(std::bind(method, t)) {} template - Method(std::string aname, T* t, void (T::*method)(folly::dynamic)) - : name(std::move(aname)) - , callbacks(0) - , isPromise(false) - , func(std::bind(method, t, std::placeholders::_1)) {} + Method(std::string aname, T *t, void (T::*method)(folly::dynamic)) + : name(std::move(aname)), + callbacks(0), + isPromise(false), + func(std::bind(method, t, std::placeholders::_1)) {} template - Method(std::string aname, T* t, void (T::*method)(folly::dynamic, Callback)) - : name(std::move(aname)) - , callbacks(1) - , isPromise(false) - , func(std::bind(method, t, std::placeholders::_1, std::placeholders::_2)) {} + Method(std::string aname, T *t, void (T::*method)(folly::dynamic, Callback)) + : name(std::move(aname)), + callbacks(1), + isPromise(false), + func(std::bind( + method, + t, + std::placeholders::_1, + std::placeholders::_2)) {} template - Method(std::string aname, T* t, void (T::*method)(folly::dynamic, Callback, Callback)) - : name(std::move(aname)) - , callbacks(2) - , isPromise(true) - , func(std::bind(method, t, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)) {} + Method( + std::string aname, + T *t, + void (T::*method)(folly::dynamic, Callback, Callback)) + : name(std::move(aname)), + callbacks(2), + isPromise(true), + func(std::bind( + method, + t, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3)) {} template - Method(std::string aname, - T* t, - void (T::*method)(folly::dynamic, Callback, Callback), - AsyncTagType) - : name(std::move(aname)) - , callbacks(2) - , isPromise(false) - , func(std::bind(method, t, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)) {} + Method( + std::string aname, + T *t, + void (T::*method)(folly::dynamic, Callback, Callback), + AsyncTagType) + : name(std::move(aname)), + callbacks(2), + isPromise(false), + func(std::bind( + method, + t, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3)) {} // sync std::function/lambda ctors @@ -163,24 +186,25 @@ public: // I am not sure if this is a runtime/compiler bug, or a // limitation I do not understand. - Method(std::string aname, - std::function&& afunc, - SyncTagType) - : name(std::move(aname)) - , callbacks(0) - , isPromise(false) - , syncFunc([afunc=std::move(afunc)] (const folly::dynamic&) - { return afunc(); }) - {} + Method( + std::string aname, + std::function &&afunc, + SyncTagType) + : name(std::move(aname)), + callbacks(0), + isPromise(false), + syncFunc([afunc = std::move(afunc)](const folly::dynamic &) { + return afunc(); + }) {} - Method(std::string aname, - std::function&& afunc, - SyncTagType) - : name(std::move(aname)) - , callbacks(0) - , isPromise(false) - , syncFunc(std::move(afunc)) - {} + Method( + std::string aname, + std::function &&afunc, + SyncTagType) + : name(std::move(aname)), + callbacks(0), + isPromise(false), + syncFunc(std::move(afunc)) {} }; /** @@ -190,8 +214,8 @@ public: virtual ~CxxModule() {} /** - * @return the name of this module. This will be the name used to {@code require()} this module - * from javascript. + * @return the name of this module. This will be the name used to {@code + * require()} this module from javascript. */ virtual std::string getName() = 0; @@ -199,7 +223,9 @@ public: * Each entry in the map will be exported as a property to JS. The * key is the property name, and the value can be anything. */ - virtual auto getConstants() -> std::map { return {}; }; + virtual auto getConstants() -> std::map { + return {}; + }; /** * @return a list of methods this module exports to JS. @@ -223,8 +249,10 @@ public: return instance_; } -private: + private: std::weak_ptr instance_; }; -}}} +} // namespace module +} // namespace xplat +} // namespace facebook diff --git a/ReactCommon/cxxreact/CxxNativeModule.cpp b/ReactCommon/cxxreact/CxxNativeModule.cpp index 3b562ae1936..94ab82bfe0b 100644 --- a/ReactCommon/cxxreact/CxxNativeModule.cpp +++ b/ReactCommon/cxxreact/CxxNativeModule.cpp @@ -8,20 +8,21 @@ #include "CxxNativeModule.h" #include "Instance.h" -#include -#include #include +#include +#include #include "JsArgumentHelpers.h" -#include "SystraceSection.h" #include "MessageQueueThread.h" +#include "SystraceSection.h" using facebook::xplat::module::CxxModule; namespace facebook { namespace react { std::function makeCallback( - std::weak_ptr instance, const folly::dynamic& callbackId) { + std::weak_ptr instance, + const folly::dynamic &callbackId) { if (!callbackId.isNumber()) { throw std::invalid_argument("Expected callback(s) as final argument"); } @@ -45,12 +46,13 @@ namespace { CxxModule::Callback convertCallback( std::function callback) { return [callback = std::move(callback)](std::vector args) { - callback(folly::dynamic(std::make_move_iterator(args.begin()), - std::make_move_iterator(args.end()))); + callback(folly::dynamic( + std::make_move_iterator(args.begin()), + std::make_move_iterator(args.end()))); }; } -} +} // namespace std::string CxxNativeModule::getName() { return name_; @@ -60,7 +62,7 @@ std::vector CxxNativeModule::getMethods() { lazyInit(); std::vector descs; - for (auto& method : methods_) { + for (auto &method : methods_) { descs.emplace_back(method.name, method.getType()); } return descs; @@ -74,42 +76,54 @@ folly::dynamic CxxNativeModule::getConstants() { } folly::dynamic constants = folly::dynamic::object(); - for (auto& pair : module_->getConstants()) { + for (auto &pair : module_->getConstants()) { constants.insert(std::move(pair.first), std::move(pair.second)); } return constants; } -void CxxNativeModule::invoke(unsigned int reactMethodId, folly::dynamic&& params, int callId) { +void CxxNativeModule::invoke( + unsigned int reactMethodId, + folly::dynamic &¶ms, + int callId) { if (reactMethodId >= methods_.size()) { - throw std::invalid_argument(folly::to("methodId ", reactMethodId, - " out of range [0..", methods_.size(), "]")); + throw std::invalid_argument(folly::to( + "methodId ", + reactMethodId, + " out of range [0..", + methods_.size(), + "]")); } if (!params.isArray()) { - throw std::invalid_argument( - folly::to("method parameters should be array, but are ", params.typeName())); + throw std::invalid_argument(folly::to( + "method parameters should be array, but are ", params.typeName())); } CxxModule::Callback first; CxxModule::Callback second; - const auto& method = methods_[reactMethodId]; + const auto &method = methods_[reactMethodId]; if (!method.func) { - throw std::runtime_error(folly::to("Method ", method.name, - " is synchronous but invoked asynchronously")); + throw std::runtime_error(folly::to( + "Method ", method.name, " is synchronous but invoked asynchronously")); } if (params.size() < method.callbacks) { - throw std::invalid_argument(folly::to("Expected ", method.callbacks, - " callbacks, but only ", params.size(), " parameters provided")); + throw std::invalid_argument(folly::to( + "Expected ", + method.callbacks, + " callbacks, but only ", + params.size(), + " parameters provided")); } if (method.callbacks == 1) { first = convertCallback(makeCallback(instance_, params[params.size() - 1])); } else if (method.callbacks == 2) { first = convertCallback(makeCallback(instance_, params[params.size() - 2])); - second = convertCallback(makeCallback(instance_, params[params.size() - 1])); + second = + convertCallback(makeCallback(instance_, params[params.size() - 1])); } params.resize(params.size() - method.callbacks); @@ -133,44 +147,49 @@ void CxxNativeModule::invoke(unsigned int reactMethodId, folly::dynamic&& params // stack. I'm told that will be possible in the future. TODO // mhorowitz #7128529: convert C++ exceptions to Java - messageQueueThread_->runOnQueue([method, params=std::move(params), first, second, callId] () { - #ifdef WITH_FBSYSTRACE - if (callId != -1) { - fbsystrace_end_async_flow(TRACE_TAG_REACT_APPS, "native", callId); - } - #else - (void)(callId); - #endif - SystraceSection s(method.name.c_str()); - try { - method.func(std::move(params), first, second); - } catch (const facebook::xplat::JsArgumentException& ex) { - throw; - } catch (std::exception& e) { - LOG(ERROR) << "std::exception. Method call " << method.name.c_str() << " failed: " << e.what(); - std::terminate(); - } catch (std::string& error) { - LOG(ERROR) << "std::string. Method call " << method.name.c_str() << " failed: " << error.c_str(); - std::terminate(); - } catch (...) { - LOG(ERROR) << "Method call " << method.name.c_str() << " failed. unknown error"; - std::terminate(); - } - }); + messageQueueThread_->runOnQueue( + [method, params = std::move(params), first, second, callId]() { +#ifdef WITH_FBSYSTRACE + if (callId != -1) { + fbsystrace_end_async_flow(TRACE_TAG_REACT_APPS, "native", callId); + } +#else + (void)(callId); +#endif + SystraceSection s(method.name.c_str()); + try { + method.func(std::move(params), first, second); + } catch (const facebook::xplat::JsArgumentException &ex) { + throw; + } catch (std::exception &e) { + LOG(ERROR) << "std::exception. Method call " << method.name.c_str() + << " failed: " << e.what(); + std::terminate(); + } catch (std::string &error) { + LOG(ERROR) << "std::string. Method call " << method.name.c_str() + << " failed: " << error.c_str(); + std::terminate(); + } catch (...) { + LOG(ERROR) << "Method call " << method.name.c_str() + << " failed. unknown error"; + std::terminate(); + } + }); } -MethodCallResult CxxNativeModule::callSerializableNativeHook(unsigned int hookId, folly::dynamic&& args) { +MethodCallResult CxxNativeModule::callSerializableNativeHook( + unsigned int hookId, + folly::dynamic &&args) { if (hookId >= methods_.size()) { - throw std::invalid_argument( - folly::to("methodId ", hookId, " out of range [0..", methods_.size(), "]")); + throw std::invalid_argument(folly::to( + "methodId ", hookId, " out of range [0..", methods_.size(), "]")); } - const auto& method = methods_[hookId]; + const auto &method = methods_[hookId]; if (!method.syncFunc) { - throw std::runtime_error( - folly::to("Method ", method.name, - " is asynchronous but invoked synchronously")); + throw std::runtime_error(folly::to( + "Method ", method.name, " is asynchronous but invoked synchronously")); } return method.syncFunc(std::move(args)); @@ -190,5 +209,5 @@ void CxxNativeModule::lazyInit() { } } -} -} +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/CxxNativeModule.h b/ReactCommon/cxxreact/CxxNativeModule.h index a57ef094ef0..2c2230409d1 100644 --- a/ReactCommon/cxxreact/CxxNativeModule.h +++ b/ReactCommon/cxxreact/CxxNativeModule.h @@ -21,26 +21,31 @@ class Instance; class MessageQueueThread; std::function makeCallback( - std::weak_ptr instance, const folly::dynamic& callbackId); + std::weak_ptr instance, + const folly::dynamic &callbackId); class RN_EXPORT CxxNativeModule : public NativeModule { -public: - CxxNativeModule(std::weak_ptr instance, - std::string name, - xplat::module::CxxModule::Provider provider, - std::shared_ptr messageQueueThread) - : instance_(instance) - , name_(std::move(name)) - , provider_(provider) - , messageQueueThread_(messageQueueThread) {} + public: + CxxNativeModule( + std::weak_ptr instance, + std::string name, + xplat::module::CxxModule::Provider provider, + std::shared_ptr messageQueueThread) + : instance_(instance), + name_(std::move(name)), + provider_(provider), + messageQueueThread_(messageQueueThread) {} std::string getName() override; std::vector getMethods() override; folly::dynamic getConstants() override; - void invoke(unsigned int reactMethodId, folly::dynamic&& params, int callId) override; - MethodCallResult callSerializableNativeHook(unsigned int hookId, folly::dynamic&& args) override; + void invoke(unsigned int reactMethodId, folly::dynamic &¶ms, int callId) + override; + MethodCallResult callSerializableNativeHook( + unsigned int hookId, + folly::dynamic &&args) override; -private: + private: void lazyInit(); std::weak_ptr instance_; @@ -51,5 +56,5 @@ private: std::vector methods_; }; -} -} +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/Instance.h b/ReactCommon/cxxreact/Instance.h index f7b9a7f1969..ee2ebc44b73 100644 --- a/ReactCommon/cxxreact/Instance.h +++ b/ReactCommon/cxxreact/Instance.h @@ -37,54 +37,67 @@ struct InstanceCallback { }; class RN_EXPORT Instance { -public: + public: ~Instance(); - void initializeBridge(std::unique_ptr callback, - std::shared_ptr jsef, - std::shared_ptr jsQueue, - std::shared_ptr moduleRegistry); + void initializeBridge( + std::unique_ptr callback, + std::shared_ptr jsef, + std::shared_ptr jsQueue, + std::shared_ptr moduleRegistry); void setSourceURL(std::string sourceURL); - void loadScriptFromString(std::unique_ptr string, - std::string sourceURL, bool loadSynchronously); + void loadScriptFromString( + std::unique_ptr string, + std::string sourceURL, + bool loadSynchronously); static bool isIndexedRAMBundle(const char *sourcePath); - static bool isIndexedRAMBundle(std::unique_ptr* string); - void loadRAMBundleFromString(std::unique_ptr script, const std::string& sourceURL); - void loadRAMBundleFromFile(const std::string& sourcePath, - const std::string& sourceURL, - bool loadSynchronously); - void loadRAMBundle(std::unique_ptr bundleRegistry, - std::unique_ptr startupScript, - std::string startupScriptSourceURL, bool loadSynchronously); + static bool isIndexedRAMBundle(std::unique_ptr *string); + void loadRAMBundleFromString( + std::unique_ptr script, + const std::string &sourceURL); + void loadRAMBundleFromFile( + const std::string &sourcePath, + const std::string &sourceURL, + bool loadSynchronously); + void loadRAMBundle( + std::unique_ptr bundleRegistry, + std::unique_ptr startupScript, + std::string startupScriptSourceURL, + bool loadSynchronously); bool supportsProfiling(); - void setGlobalVariable(std::string propName, - std::unique_ptr jsonValue); + void setGlobalVariable( + std::string propName, + std::unique_ptr jsonValue); void *getJavaScriptContext(); bool isInspectable(); bool isBatchActive(); - void callJSFunction(std::string &&module, std::string &&method, - folly::dynamic &¶ms); + void callJSFunction( + std::string &&module, + std::string &&method, + folly::dynamic &¶ms); void callJSCallback(uint64_t callbackId, folly::dynamic &¶ms); // This method is experimental, and may be modified or removed. - void registerBundle(uint32_t bundleId, const std::string& bundlePath); + void registerBundle(uint32_t bundleId, const std::string &bundlePath); const ModuleRegistry &getModuleRegistry() const; ModuleRegistry &getModuleRegistry(); void handleMemoryPressure(int pressureLevel); - void invokeAsync(std::function&& func); + void invokeAsync(std::function &&func); -private: + private: void callNativeModules(folly::dynamic &&calls, bool isEndOfBatch); - void loadApplication(std::unique_ptr bundleRegistry, - std::unique_ptr startupScript, - std::string startupScriptSourceURL); - void loadApplicationSync(std::unique_ptr bundleRegistry, - std::unique_ptr startupScript, - std::string startupScriptSourceURL); + void loadApplication( + std::unique_ptr bundleRegistry, + std::unique_ptr startupScript, + std::string startupScriptSourceURL); + void loadApplicationSync( + std::unique_ptr bundleRegistry, + std::unique_ptr startupScript, + std::string startupScriptSourceURL); std::shared_ptr callback_; std::unique_ptr nativeToJsBridge_; diff --git a/ReactCommon/cxxreact/JSBundleType.cpp b/ReactCommon/cxxreact/JSBundleType.cpp index 44c602b789d..c676c738e0a 100644 --- a/ReactCommon/cxxreact/JSBundleType.cpp +++ b/ReactCommon/cxxreact/JSBundleType.cpp @@ -13,20 +13,20 @@ namespace facebook { namespace react { static uint32_t constexpr RAMBundleMagicNumber = 0xFB0BD1E5; -static uint32_t constexpr BCBundleMagicNumber = 0x6D657300; +static uint32_t constexpr BCBundleMagicNumber = 0x6D657300; -ScriptTag parseTypeFromHeader(const BundleHeader& header) { +ScriptTag parseTypeFromHeader(const BundleHeader &header) { switch (folly::Endian::little(header.magic)) { - case RAMBundleMagicNumber: - return ScriptTag::RAMBundle; - case BCBundleMagicNumber: - return ScriptTag::BCBundle; - default: - return ScriptTag::String; + case RAMBundleMagicNumber: + return ScriptTag::RAMBundle; + case BCBundleMagicNumber: + return ScriptTag::BCBundle; + default: + return ScriptTag::String; } } -const char *stringForScriptTag(const ScriptTag& tag) { +const char *stringForScriptTag(const ScriptTag &tag) { switch (tag) { case ScriptTag::String: return "String"; @@ -38,5 +38,5 @@ const char *stringForScriptTag(const ScriptTag& tag) { return ""; } -} // namespace react -} // namespace facebook +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/JSBundleType.h b/ReactCommon/cxxreact/JSBundleType.h index 4ecabb6525a..0a5bad0894c 100644 --- a/ReactCommon/cxxreact/JSBundleType.h +++ b/ReactCommon/cxxreact/JSBundleType.h @@ -7,9 +7,9 @@ #pragma once +#include #include #include -#include #ifndef RN_EXPORT #define RN_EXPORT __attribute__((visibility("default"))) @@ -55,7 +55,7 @@ FOLLY_PACK_POP * Takes the first 8 bytes of a bundle, and returns a tag describing the * bundle's format. */ -RN_EXPORT ScriptTag parseTypeFromHeader(const BundleHeader& header); +RN_EXPORT ScriptTag parseTypeFromHeader(const BundleHeader &header); /** * stringForScriptTag @@ -63,7 +63,7 @@ RN_EXPORT ScriptTag parseTypeFromHeader(const BundleHeader& header); * Convert an `ScriptTag` enum into a string, useful for emitting in errors * and diagnostic messages. */ -RN_EXPORT const char* stringForScriptTag(const ScriptTag& tag); +RN_EXPORT const char *stringForScriptTag(const ScriptTag &tag); -} // namespace react -} // namespace facebook +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/JSDeltaBundleClient.h b/ReactCommon/cxxreact/JSDeltaBundleClient.h index f03daffac86..9c9db775d5d 100644 --- a/ReactCommon/cxxreact/JSDeltaBundleClient.h +++ b/ReactCommon/cxxreact/JSDeltaBundleClient.h @@ -20,13 +20,13 @@ namespace facebook { namespace react { class JSDeltaBundleClient { -public: - void patch(const folly::dynamic& delta); + public: + void patch(const folly::dynamic &delta); JSModulesUnbundle::Module getModule(uint32_t moduleId) const; std::unique_ptr getStartupCode() const; void clear(); -private: + private: std::unordered_map modules_; std::string startupCode_; @@ -34,14 +34,16 @@ private: }; class JSDeltaBundleClientRAMBundle : public JSModulesUnbundle { -public: + public: JSDeltaBundleClientRAMBundle( - std::shared_ptr client) : client_(client) {} + std::shared_ptr client) + : client_(client) {} Module getModule(uint32_t moduleId) const override { return client_->getModule(moduleId); } -private: + + private: const std::shared_ptr client_; }; diff --git a/ReactCommon/cxxreact/JSExecutor.cpp b/ReactCommon/cxxreact/JSExecutor.cpp index 09ec0e7fd08..f303ef161b8 100644 --- a/ReactCommon/cxxreact/JSExecutor.cpp +++ b/ReactCommon/cxxreact/JSExecutor.cpp @@ -16,12 +16,12 @@ namespace react { std::string JSExecutor::getSyntheticBundlePath( uint32_t bundleId, - const std::string& bundlePath) { + const std::string &bundlePath) { if (bundleId == RAMBundleRegistry::MAIN_BUNDLE_ID) { return bundlePath; } return folly::to("seg-", bundleId, ".js"); } -} -} +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/JSExecutor.h b/ReactCommon/cxxreact/JSExecutor.h index fe1dc1b1175..ab54642d999 100644 --- a/ReactCommon/cxxreact/JSExecutor.h +++ b/ReactCommon/cxxreact/JSExecutor.h @@ -36,57 +36,75 @@ class ExecutorDelegate { virtual std::shared_ptr getModuleRegistry() = 0; virtual void callNativeModules( - JSExecutor& executor, folly::dynamic&& calls, bool isEndOfBatch) = 0; + JSExecutor &executor, + folly::dynamic &&calls, + bool isEndOfBatch) = 0; virtual MethodCallResult callSerializableNativeHook( - JSExecutor& executor, unsigned int moduleId, unsigned int methodId, folly::dynamic&& args) = 0; + JSExecutor &executor, + unsigned int moduleId, + unsigned int methodId, + folly::dynamic &&args) = 0; }; -using NativeExtensionsProvider = std::function; +using NativeExtensionsProvider = + std::function; class JSExecutorFactory { -public: + public: virtual std::unique_ptr createJSExecutor( - std::shared_ptr delegate, - std::shared_ptr jsQueue) = 0; + std::shared_ptr delegate, + std::shared_ptr jsQueue) = 0; virtual ~JSExecutorFactory() {} }; class RN_EXPORT JSExecutor { -public: + public: /** * Execute an application script bundle in the JS context. */ - virtual void loadApplicationScript(std::unique_ptr script, - std::string sourceURL) = 0; + virtual void loadApplicationScript( + std::unique_ptr script, + std::string sourceURL) = 0; /** * Add an application "RAM" bundle registry */ - virtual void setBundleRegistry(std::unique_ptr bundleRegistry) = 0; + virtual void setBundleRegistry( + std::unique_ptr bundleRegistry) = 0; /** * Register a file path for an additional "RAM" bundle */ - virtual void registerBundle(uint32_t bundleId, const std::string& bundlePath) = 0; + virtual void registerBundle( + uint32_t bundleId, + const std::string &bundlePath) = 0; /** * Executes BatchedBridge.callFunctionReturnFlushedQueue with the module ID, - * method ID and optional additional arguments in JS. The executor is responsible - * for using Bridge->callNativeModules to invoke any necessary native modules methods. + * method ID and optional additional arguments in JS. The executor is + * responsible for using Bridge->callNativeModules to invoke any necessary + * native modules methods. */ - virtual void callFunction(const std::string& moduleId, const std::string& methodId, const folly::dynamic& arguments) = 0; + virtual void callFunction( + const std::string &moduleId, + const std::string &methodId, + const folly::dynamic &arguments) = 0; /** * Executes BatchedBridge.invokeCallbackAndReturnFlushedQueue with the cbID, - * and optional additional arguments in JS and returns the next queue. The executor - * is responsible for using Bridge->callNativeModules to invoke any necessary - * native modules methods. + * and optional additional arguments in JS and returns the next queue. The + * executor is responsible for using Bridge->callNativeModules to invoke any + * necessary native modules methods. */ - virtual void invokeCallback(const double callbackId, const folly::dynamic& arguments) = 0; + virtual void invokeCallback( + const double callbackId, + const folly::dynamic &arguments) = 0; - virtual void setGlobalVariable(std::string propName, std::unique_ptr jsonValue) = 0; + virtual void setGlobalVariable( + std::string propName, + std::unique_ptr jsonValue) = 0; - virtual void* getJavaScriptContext() { + virtual void *getJavaScriptContext() { return nullptr; } @@ -114,7 +132,8 @@ public: static std::string getSyntheticBundlePath( uint32_t bundleId, - const std::string& bundlePath); + const std::string &bundlePath); }; -} } +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/JSIndexedRAMBundle.h b/ReactCommon/cxxreact/JSIndexedRAMBundle.h index 7696e2d98a8..3045eb6a284 100644 --- a/ReactCommon/cxxreact/JSIndexedRAMBundle.h +++ b/ReactCommon/cxxreact/JSIndexedRAMBundle.h @@ -21,8 +21,9 @@ namespace facebook { namespace react { class RN_EXPORT JSIndexedRAMBundle : public JSModulesUnbundle { -public: - static std::function(std::string)> buildFactory(); + public: + static std::function(std::string)> + buildFactory(); // Throws std::runtime_error on failure. JSIndexedRAMBundle(const char *sourceURL); @@ -33,22 +34,22 @@ public: // Throws std::runtime_error on failure. Module getModule(uint32_t moduleId) const override; -private: + private: struct ModuleData { uint32_t offset; uint32_t length; }; static_assert( - sizeof(ModuleData) == 8, - "ModuleData must not have any padding and use sizes matching input files"); + sizeof(ModuleData) == 8, + "ModuleData must not have any padding and use sizes matching input files"); struct ModuleTable { size_t numEntries; std::unique_ptr data; - ModuleTable() : numEntries(0) {}; - ModuleTable(size_t entries) : - numEntries(entries), - data(std::unique_ptr(new ModuleData[numEntries])) {}; + ModuleTable() : numEntries(0){}; + ModuleTable(size_t entries) + : numEntries(entries), + data(std::unique_ptr(new ModuleData[numEntries])){}; size_t byteLength() const { return numEntries * sizeof(ModuleData); } @@ -58,9 +59,9 @@ private: std::string getModuleCode(const uint32_t id) const; void readBundle(char *buffer, const std::streamsize bytes) const; void readBundle( - char *buffer, const - std::streamsize bytes, - const std::istream::pos_type position) const; + char *buffer, + const std::streamsize bytes, + const std::istream::pos_type position) const; mutable std::unique_ptr m_bundle; ModuleTable m_table; @@ -68,5 +69,5 @@ private: std::unique_ptr m_startupCode; }; -} // namespace react -} // namespace facebook +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/JSModulesUnbundle.h b/ReactCommon/cxxreact/JSModulesUnbundle.h index dee92e432b2..52103f7a58d 100644 --- a/ReactCommon/cxxreact/JSModulesUnbundle.h +++ b/ReactCommon/cxxreact/JSModulesUnbundle.h @@ -8,8 +8,8 @@ #pragma once #include -#include #include +#include #include @@ -24,12 +24,13 @@ class JSModulesUnbundle { * The class is non-copyable because copying instances might involve copying * several megabytes of memory. */ -public: + public: class ModuleNotFound : public std::out_of_range { - public: + public: using std::out_of_range::out_of_range; - ModuleNotFound(uint32_t moduleId) : std::out_of_range::out_of_range( - folly::to("Module not found: ", moduleId)) {} + ModuleNotFound(uint32_t moduleId) + : std::out_of_range::out_of_range( + folly::to("Module not found: ", moduleId)) {} }; struct Module { std::string name; @@ -39,9 +40,9 @@ public: virtual ~JSModulesUnbundle() {} virtual Module getModule(uint32_t moduleId) const = 0; -private: - JSModulesUnbundle(const JSModulesUnbundle&) = delete; + private: + JSModulesUnbundle(const JSModulesUnbundle &) = delete; }; -} -} +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/JsArgumentHelpers-inl.h b/ReactCommon/cxxreact/JsArgumentHelpers-inl.h index f38f329cfdc..f22ec920883 100644 --- a/ReactCommon/cxxreact/JsArgumentHelpers-inl.h +++ b/ReactCommon/cxxreact/JsArgumentHelpers-inl.h @@ -14,52 +14,67 @@ namespace xplat { namespace detail { template -R jsArg1(const folly::dynamic& arg, M asFoo, const T&... desc) { +R jsArg1(const folly::dynamic &arg, M asFoo, const T &... desc) { try { return (arg.*asFoo)(); - } catch (const folly::TypeError& ex) { - throw JsArgumentException( - folly::to( + } catch (const folly::TypeError &ex) { + throw JsArgumentException(folly::to( "Error converting javascript arg ", desc..., " to C++: ", ex.what())); - } catch (const std::range_error& ex) { - throw JsArgumentException( - folly::to( - "Could not convert argument ", desc..., " to required type: ", ex.what())); + } catch (const std::range_error &ex) { + throw JsArgumentException(folly::to( + "Could not convert argument ", + desc..., + " to required type: ", + ex.what())); } } -} +} // namespace detail template -R jsArg(const folly::dynamic& arg, R (folly::dynamic::*asFoo)() const, const T&... desc) { +R jsArg( + const folly::dynamic &arg, + R (folly::dynamic::*asFoo)() const, + const T &... desc) { return detail::jsArg1(arg, asFoo, desc...); } template -R jsArg(const folly::dynamic& arg, R (folly::dynamic::*asFoo)() const&, const T&... desc) { +R jsArg( + const folly::dynamic &arg, + R (folly::dynamic::*asFoo)() const &, + const T &... desc) { return detail::jsArg1(arg, asFoo, desc...); } template -typename detail::is_dynamic::type& jsArgAsDynamic(T&& args, size_t n) { +typename detail::is_dynamic::type &jsArgAsDynamic(T &&args, size_t n) { try { return args[n]; - } catch (const std::out_of_range& ex) { + } catch (const std::out_of_range &ex) { // Use 1-base counting for argument description. - throw JsArgumentException( - folly::to( - "JavaScript provided ", args.size(), - " arguments for C++ method which references at least ", n + 1, - " arguments: ", ex.what())); + throw JsArgumentException(folly::to( + "JavaScript provided ", + args.size(), + " arguments for C++ method which references at least ", + n + 1, + " arguments: ", + ex.what())); } } template -R jsArgN(const folly::dynamic& args, size_t n, R (folly::dynamic::*asFoo)() const) { +R jsArgN( + const folly::dynamic &args, + size_t n, + R (folly::dynamic::*asFoo)() const) { return jsArg(jsArgAsDynamic(args, n), asFoo, n); } template -R jsArgN(const folly::dynamic& args, size_t n, R (folly::dynamic::*asFoo)() const&) { +R jsArgN( + const folly::dynamic &args, + size_t n, + R (folly::dynamic::*asFoo)() const &) { return jsArg(jsArgAsDynamic(args, n), asFoo, n); } @@ -68,29 +83,37 @@ namespace detail { // This is a helper for jsArgAsArray and jsArgAsObject. template -typename detail::is_dynamic::type& jsArgAsType(T&& args, size_t n, const char* required, - bool (folly::dynamic::*isFoo)() const) { - T& ret = jsArgAsDynamic(args, n); +typename detail::is_dynamic::type &jsArgAsType( + T &&args, + size_t n, + const char *required, + bool (folly::dynamic::*isFoo)() const) { + T &ret = jsArgAsDynamic(args, n); if ((ret.*isFoo)()) { return ret; } // Use 1-base counting for argument description. - throw JsArgumentException( - folly::to( - "Argument ", n + 1, " of type ", ret.typeName(), " is not required type ", required)); + throw JsArgumentException(folly::to( + "Argument ", + n + 1, + " of type ", + ret.typeName(), + " is not required type ", + required)); } } // end namespace detail template -typename detail::is_dynamic::type& jsArgAsArray(T&& args, size_t n) { +typename detail::is_dynamic::type &jsArgAsArray(T &&args, size_t n) { return detail::jsArgAsType(args, n, "Array", &folly::dynamic::isArray); } template -typename detail::is_dynamic::type& jsArgAsObject(T&& args, size_t n) { +typename detail::is_dynamic::type &jsArgAsObject(T &&args, size_t n) { return detail::jsArgAsType(args, n, "Object", &folly::dynamic::isObject); } -}} +} // namespace xplat +} // namespace facebook diff --git a/ReactCommon/cxxreact/JsArgumentHelpers.h b/ReactCommon/cxxreact/JsArgumentHelpers.h index 29e1d0b5bf9..7e9f13934f6 100644 --- a/ReactCommon/cxxreact/JsArgumentHelpers.h +++ b/ReactCommon/cxxreact/JsArgumentHelpers.h @@ -25,8 +25,8 @@ namespace facebook { namespace xplat { class JsArgumentException : public std::logic_error { -public: - JsArgumentException(const std::string& msg) : std::logic_error(msg) {} + public: + JsArgumentException(const std::string &msg) : std::logic_error(msg) {} }; // This extracts a single argument by calling the given method pointer on it. @@ -36,9 +36,15 @@ public: // overload accepts ref-qualified member functions. template -R jsArg(const folly::dynamic& arg, R (folly::dynamic::*asFoo)() const, const T&... desc); +R jsArg( + const folly::dynamic &arg, + R (folly::dynamic::*asFoo)() const, + const T &... desc); template -R jsArg(const folly::dynamic& arg, R (folly::dynamic::*asFoo)() const&, const T&... desc); +R jsArg( + const folly::dynamic &arg, + R (folly::dynamic::*asFoo)() const &, + const T &... desc); // This is like jsArg, but a operates on a dynamic representing an array of // arguments. The argument n is used both to index the array and build the @@ -46,9 +52,15 @@ R jsArg(const folly::dynamic& arg, R (folly::dynamic::*asFoo)() const&, const T& // used by the type-specific methods following. template -R jsArgN(const folly::dynamic& args, size_t n, R (folly::dynamic::*asFoo)() const); +R jsArgN( + const folly::dynamic &args, + size_t n, + R (folly::dynamic::*asFoo)() const); template -R jsArgN(const folly::dynamic& args, size_t n, R (folly::dynamic::*asFoo)() const&); +R jsArgN( + const folly::dynamic &args, + size_t n, + R (folly::dynamic::*asFoo)() const &); namespace detail { @@ -58,7 +70,8 @@ namespace detail { // only for types compatible with folly::dynamic. template struct is_dynamic { - typedef typename std::enable_if::value, T>::type type; + typedef typename std:: + enable_if::value, T>::type type; }; } // end namespace detail @@ -68,44 +81,45 @@ struct is_dynamic { // Extract the n'th arg from the given dynamic, as a dynamic. Throws a // JsArgumentException if there is no n'th arg in the input. template -typename detail::is_dynamic::type& jsArgAsDynamic(T&& args, size_t n); +typename detail::is_dynamic::type &jsArgAsDynamic(T &&args, size_t n); // Extract the n'th arg from the given dynamic, as a dynamic Array. Throws a // JsArgumentException if there is no n'th arg in the input, or it is not an // Array. template -typename detail::is_dynamic::type& jsArgAsArray(T&& args, size_t n); +typename detail::is_dynamic::type &jsArgAsArray(T &&args, size_t n); // Extract the n'th arg from the given dynamic, as a dynamic Object. Throws a // JsArgumentException if there is no n'th arg in the input, or it is not an // Object. template -typename detail::is_dynamic::type& jsArgAsObject(T&& args, size_t n); +typename detail::is_dynamic::type &jsArgAsObject(T &&args, size_t n); // Extract the n'th arg from the given dynamic, as a bool. Throws a // JsArgumentException if this fails for some reason. -inline bool jsArgAsBool(const folly::dynamic& args, size_t n) { +inline bool jsArgAsBool(const folly::dynamic &args, size_t n) { return jsArgN(args, n, &folly::dynamic::asBool); } // Extract the n'th arg from the given dynamic, as an integer. Throws a // JsArgumentException if this fails for some reason. -inline int64_t jsArgAsInt(const folly::dynamic& args, size_t n) { +inline int64_t jsArgAsInt(const folly::dynamic &args, size_t n) { return jsArgN(args, n, &folly::dynamic::asInt); } // Extract the n'th arg from the given dynamic, as a double. Throws a // JsArgumentException if this fails for some reason. -inline double jsArgAsDouble(const folly::dynamic& args, size_t n) { +inline double jsArgAsDouble(const folly::dynamic &args, size_t n) { return jsArgN(args, n, &folly::dynamic::asDouble); } // Extract the n'th arg from the given dynamic, as a string. Throws a // JsArgumentException if this fails for some reason. -inline std::string jsArgAsString(const folly::dynamic& args, size_t n) { +inline std::string jsArgAsString(const folly::dynamic &args, size_t n) { return jsArgN(args, n, &folly::dynamic::asString); } -}} +} // namespace xplat +} // namespace facebook #include diff --git a/ReactCommon/cxxreact/MessageQueueThread.h b/ReactCommon/cxxreact/MessageQueueThread.h index 9dfd1e39a28..9026a0ba870 100644 --- a/ReactCommon/cxxreact/MessageQueueThread.h +++ b/ReactCommon/cxxreact/MessageQueueThread.h @@ -17,12 +17,13 @@ namespace react { class MessageQueueThread { public: virtual ~MessageQueueThread() {} - virtual void runOnQueue(std::function&&) = 0; + virtual void runOnQueue(std::function &&) = 0; // runOnQueueSync and quitSynchronous are dangerous. They should only be // used for initialization and cleanup. - virtual void runOnQueueSync(std::function&&) = 0; + virtual void runOnQueueSync(std::function &&) = 0; // Once quitSynchronous() returns, no further work should run on the queue. virtual void quitSynchronous() = 0; }; -}} +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/MethodCall.cpp b/ReactCommon/cxxreact/MethodCall.cpp index 91e8b238325..f5f541265a5 100644 --- a/ReactCommon/cxxreact/MethodCall.cpp +++ b/ReactCommon/cxxreact/MethodCall.cpp @@ -20,40 +20,45 @@ namespace react { static const char *errorPrefix = "Malformed calls from JS: "; -std::vector parseMethodCalls(folly::dynamic&& jsonData) { +std::vector parseMethodCalls(folly::dynamic &&jsonData) { if (jsonData.isNull()) { return {}; } if (!jsonData.isArray()) { - throw std::invalid_argument( - folly::to(errorPrefix, "input isn't array but ", jsonData.typeName())); + throw std::invalid_argument(folly::to( + errorPrefix, "input isn't array but ", jsonData.typeName())); } if (jsonData.size() < REQUEST_PARAMSS + 1) { throw std::invalid_argument( - folly::to(errorPrefix, "size == ", jsonData.size())); + folly::to(errorPrefix, "size == ", jsonData.size())); } - auto& moduleIds = jsonData[REQUEST_MODULE_IDS]; - auto& methodIds = jsonData[REQUEST_METHOD_IDS]; - auto& params = jsonData[REQUEST_PARAMSS]; - int callId = -1; + auto &moduleIds = jsonData[REQUEST_MODULE_IDS]; + auto &methodIds = jsonData[REQUEST_METHOD_IDS]; + auto ¶ms = jsonData[REQUEST_PARAMSS]; + int callId = -1; if (!moduleIds.isArray() || !methodIds.isArray() || !params.isArray()) { - throw std::invalid_argument( - folly::to(errorPrefix, "not all fields are arrays.\n\n", folly::toJson(jsonData))); + throw std::invalid_argument(folly::to( + errorPrefix, + "not all fields are arrays.\n\n", + folly::toJson(jsonData))); } - if (moduleIds.size() != methodIds.size() || moduleIds.size() != params.size()) { - throw std::invalid_argument( - folly::to(errorPrefix, "field sizes are different.\n\n", folly::toJson(jsonData))); + if (moduleIds.size() != methodIds.size() || + moduleIds.size() != params.size()) { + throw std::invalid_argument(folly::to( + errorPrefix, + "field sizes are different.\n\n", + folly::toJson(jsonData))); } if (jsonData.size() > REQUEST_CALLID) { if (!jsonData[REQUEST_CALLID].isNumber()) { - throw std::invalid_argument( - folly::to(errorPrefix, "invalid callId", jsonData[REQUEST_CALLID].typeName())); + throw std::invalid_argument(folly::to( + errorPrefix, "invalid callId", jsonData[REQUEST_CALLID].typeName())); } callId = (int)jsonData[REQUEST_CALLID].asInt(); } @@ -61,15 +66,17 @@ std::vector parseMethodCalls(folly::dynamic&& jsonData) { std::vector methodCalls; for (size_t i = 0; i < moduleIds.size(); i++) { if (!params[i].isArray()) { - throw std::invalid_argument( - folly::to(errorPrefix, "method arguments isn't array but ", params[i].typeName())); + throw std::invalid_argument(folly::to( + errorPrefix, + "method arguments isn't array but ", + params[i].typeName())); } methodCalls.emplace_back( - moduleIds[i].asInt(), - methodIds[i].asInt(), - std::move(params[i]), - callId); + moduleIds[i].asInt(), + methodIds[i].asInt(), + std::move(params[i]), + callId); // only increment callid if contains valid callid as callid is optional callId += (callId != -1) ? 1 : 0; @@ -78,4 +85,5 @@ std::vector parseMethodCalls(folly::dynamic&& jsonData) { return methodCalls; } -}} +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/MethodCall.h b/ReactCommon/cxxreact/MethodCall.h index e1452313b7a..665cd70f831 100644 --- a/ReactCommon/cxxreact/MethodCall.h +++ b/ReactCommon/cxxreact/MethodCall.h @@ -22,14 +22,15 @@ struct MethodCall { folly::dynamic arguments; int callId; - MethodCall(int mod, int meth, folly::dynamic&& args, int cid) - : moduleId(mod) - , methodId(meth) - , arguments(std::move(args)) - , callId(cid) {} + MethodCall(int mod, int meth, folly::dynamic &&args, int cid) + : moduleId(mod), + methodId(meth), + arguments(std::move(args)), + callId(cid) {} }; /// \throws std::invalid_argument -std::vector parseMethodCalls(folly::dynamic&& calls); +std::vector parseMethodCalls(folly::dynamic &&calls); -} } +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/ModuleRegistry.cpp b/ReactCommon/cxxreact/ModuleRegistry.cpp index 3c26dd3df21..b59dac82f44 100644 --- a/ReactCommon/cxxreact/ModuleRegistry.cpp +++ b/ReactCommon/cxxreact/ModuleRegistry.cpp @@ -30,19 +30,22 @@ std::string normalizeName(std::string name) { return name; } -} +} // namespace -ModuleRegistry::ModuleRegistry(std::vector> modules, ModuleNotFoundCallback callback) +ModuleRegistry::ModuleRegistry( + std::vector> modules, + ModuleNotFoundCallback callback) : modules_{std::move(modules)}, moduleNotFoundCallback_{callback} {} void ModuleRegistry::updateModuleNamesFromIndex(size_t index) { - for (; index < modules_.size(); index++ ) { + for (; index < modules_.size(); index++) { std::string name = normalizeName(modules_[index]->getName()); modulesByName_[name] = index; } } -void ModuleRegistry::registerModules(std::vector> modules) { +void ModuleRegistry::registerModules( + std::vector> modules) { SystraceSection s_("ModuleRegistry::registerModules"); if (modules_.empty() && unknownModules_.empty()) { modules_ = std::move(modules); @@ -53,12 +56,15 @@ void ModuleRegistry::registerModules(std::vector> modules_.reserve(modulesSize + addModulesSize); std::move(modules.begin(), modules.end(), std::back_inserter(modules_)); if (!unknownModules_.empty()) { - for (size_t index = modulesSize; index < modulesSize + addModulesSize; index++) { + for (size_t index = modulesSize; index < modulesSize + addModulesSize; + index++) { std::string name = normalizeName(modules_[index]->getName()); auto it = unknownModules_.find(name); if (it != unknownModules_.end()) { - throw std::runtime_error( - folly::to("module ", name, " was required without being registered and is now being registered.")); + throw std::runtime_error(folly::to( + "module ", + name, + " was required without being registered and is now being registered.")); } else if (addToNames) { modulesByName_[name] = index; } @@ -80,7 +86,8 @@ std::vector ModuleRegistry::moduleNames() { return names; } -folly::Optional ModuleRegistry::getConfig(const std::string& name) { +folly::Optional ModuleRegistry::getConfig( + const std::string &name) { SystraceSection s("ModuleRegistry::getConfig", "module", name); // Initialize modulesByName_ @@ -94,8 +101,7 @@ folly::Optional ModuleRegistry::getConfig(const std::string& name) if (unknownModules_.find(name) != unknownModules_.end()) { return folly::none; } - if (!moduleNotFoundCallback_ || - !moduleNotFoundCallback_(name) || + if (!moduleNotFoundCallback_ || !moduleNotFoundCallback_(name) || (it = modulesByName_.find(name)) == modulesByName_.end()) { unknownModules_.insert(name); return folly::none; @@ -106,7 +112,8 @@ folly::Optional ModuleRegistry::getConfig(const std::string& name) CHECK(index < modules_.size()); NativeModule *module = modules_[index].get(); - // string name, object constants, array methodNames (methodId is index), [array promiseMethodIds], [array syncMethodIds] + // string name, object constants, array methodNames (methodId is index), + // [array promiseMethodIds], [array syncMethodIds] folly::dynamic config = folly::dynamic::array(name); { @@ -122,7 +129,7 @@ folly::Optional ModuleRegistry::getConfig(const std::string& name) folly::dynamic promiseMethodIds = folly::dynamic::array; folly::dynamic syncMethodIds = folly::dynamic::array; - for (auto& descriptor : methods) { + for (auto &descriptor : methods) { // TODO: #10487027 compare tags instead of doing string comparison? methodNames.push_back(std::move(descriptor.name)); if (descriptor.type == "promise") { @@ -151,20 +158,29 @@ folly::Optional ModuleRegistry::getConfig(const std::string& name) } } -void ModuleRegistry::callNativeMethod(unsigned int moduleId, unsigned int methodId, folly::dynamic&& params, int callId) { +void ModuleRegistry::callNativeMethod( + unsigned int moduleId, + unsigned int methodId, + folly::dynamic &¶ms, + int callId) { if (moduleId >= modules_.size()) { - throw std::runtime_error( - folly::to("moduleId ", moduleId, " out of range [0..", modules_.size(), ")")); + throw std::runtime_error(folly::to( + "moduleId ", moduleId, " out of range [0..", modules_.size(), ")")); } modules_[moduleId]->invoke(methodId, std::move(params), callId); } -MethodCallResult ModuleRegistry::callSerializableNativeHook(unsigned int moduleId, unsigned int methodId, folly::dynamic&& params) { +MethodCallResult ModuleRegistry::callSerializableNativeHook( + unsigned int moduleId, + unsigned int methodId, + folly::dynamic &¶ms) { if (moduleId >= modules_.size()) { - throw std::runtime_error( - folly::to("moduleId ", moduleId, "out of range [0..", modules_.size(), ")")); + throw std::runtime_error(folly::to( + "moduleId ", moduleId, "out of range [0..", modules_.size(), ")")); } - return modules_[moduleId]->callSerializableNativeHook(methodId, std::move(params)); + return modules_[moduleId]->callSerializableNativeHook( + methodId, std::move(params)); } -}} +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/ModuleRegistry.h b/ReactCommon/cxxreact/ModuleRegistry.h index 9cae045065e..b24f5390e30 100644 --- a/ReactCommon/cxxreact/ModuleRegistry.h +++ b/ReactCommon/cxxreact/ModuleRegistry.h @@ -32,43 +32,56 @@ struct ModuleConfig { class RN_EXPORT ModuleRegistry { public: // not implemented: - // onBatchComplete: see https://our.intern.facebook.com/intern/tasks/?t=5279396 - // getModule: only used by views - // getAllModules: only used for cleanup; use RAII instead - // notifyCatalystInstanceInitialized: this is really only used by view-related code - // notifyCatalystInstanceDestroy: use RAII instead + // onBatchComplete: see + // https://our.intern.facebook.com/intern/tasks/?t=5279396 getModule: only + // used by views getAllModules: only used for cleanup; use RAII instead + // notifyCatalystInstanceInitialized: this is really only used by view-related + // code notifyCatalystInstanceDestroy: use RAII instead using ModuleNotFoundCallback = std::function; - ModuleRegistry(std::vector> modules, ModuleNotFoundCallback callback = nullptr); + ModuleRegistry( + std::vector> modules, + ModuleNotFoundCallback callback = nullptr); void registerModules(std::vector> modules); std::vector moduleNames(); - folly::Optional getConfig(const std::string& name); + folly::Optional getConfig(const std::string &name); - void callNativeMethod(unsigned int moduleId, unsigned int methodId, folly::dynamic&& params, int callId); - MethodCallResult callSerializableNativeHook(unsigned int moduleId, unsigned int methodId, folly::dynamic&& args); + void callNativeMethod( + unsigned int moduleId, + unsigned int methodId, + folly::dynamic &¶ms, + int callId); + MethodCallResult callSerializableNativeHook( + unsigned int moduleId, + unsigned int methodId, + folly::dynamic &&args); private: // This is always populated std::vector> modules_; - // This is used to extend the population of modulesByName_ if registerModules is called after moduleNames + // This is used to extend the population of modulesByName_ if registerModules + // is called after moduleNames void updateModuleNamesFromIndex(size_t size); - // This is only populated if moduleNames() is called. Values are indices into modules_. + // This is only populated if moduleNames() is called. Values are indices into + // modules_. std::unordered_map modulesByName_; - // This is populated with modules that are requested via getConfig but are unknown. - // An error will be thrown if they are subsequently added to the registry. + // This is populated with modules that are requested via getConfig but are + // unknown. An error will be thrown if they are subsequently added to the + // registry. std::unordered_set unknownModules_; // Function will be called if a module was requested but was not found. - // If the function returns true, ModuleRegistry will try to find the module again (assuming it's registered) - // If the functon returns false, ModuleRegistry will not try to find the module and return nullptr instead. + // If the function returns true, ModuleRegistry will try to find the module + // again (assuming it's registered) If the functon returns false, + // ModuleRegistry will not try to find the module and return nullptr instead. ModuleNotFoundCallback moduleNotFoundCallback_; }; -} -} +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/NativeModule.h b/ReactCommon/cxxreact/NativeModule.h index 1c286d70dc3..6e7287cf469 100644 --- a/ReactCommon/cxxreact/NativeModule.h +++ b/ReactCommon/cxxreact/NativeModule.h @@ -22,11 +22,10 @@ struct MethodDescriptor { std::string type; MethodDescriptor(std::string n, std::string t) - : name(std::move(n)) - , type(std::move(t)) {} + : name(std::move(n)), type(std::move(t)) {} }; - using MethodCallResult = folly::Optional; +using MethodCallResult = folly::Optional; class NativeModule { public: @@ -34,9 +33,12 @@ class NativeModule { virtual std::string getName() = 0; virtual std::vector getMethods() = 0; virtual folly::dynamic getConstants() = 0; - virtual void invoke(unsigned int reactMethodId, folly::dynamic&& params, int callId) = 0; - virtual MethodCallResult callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic&& args) = 0; + virtual void + invoke(unsigned int reactMethodId, folly::dynamic &¶ms, int callId) = 0; + virtual MethodCallResult callSerializableNativeHook( + unsigned int reactMethodId, + folly::dynamic &&args) = 0; }; -} -} +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/NativeToJsBridge.h b/ReactCommon/cxxreact/NativeToJsBridge.h index aa0c569b214..e94bb21f06e 100644 --- a/ReactCommon/cxxreact/NativeToJsBridge.h +++ b/ReactCommon/cxxreact/NativeToJsBridge.h @@ -35,14 +35,14 @@ class RAMBundleRegistry; // work to run on the jsQueue passed to the ctor, and return // immediately. class NativeToJsBridge { -public: + public: friend class JsToNativeBridge; /** * This must be called on the main JS thread. */ NativeToJsBridge( - JSExecutorFactory* jsExecutorFactory, + JSExecutorFactory *jsExecutorFactory, std::shared_ptr registry, std::shared_ptr jsQueue, std::shared_ptr callback); @@ -52,12 +52,15 @@ public: * Executes a function with the module ID and method ID and any additional * arguments in JS. */ - void callFunction(std::string&& module, std::string&& method, folly::dynamic&& args); + void callFunction( + std::string &&module, + std::string &&method, + folly::dynamic &&args); /** * Invokes a callback with the cbID, and optional additional arguments in JS. */ - void invokeCallback(double callbackId, folly::dynamic&& args); + void invokeCallback(double callbackId, folly::dynamic &&args); /** * Starts the JS application. If bundleRegistry is non-null, then it is @@ -65,17 +68,19 @@ public: * Otherwise, the script is assumed to include all the modules. */ void loadApplication( - std::unique_ptr bundleRegistry, - std::unique_ptr startupCode, - std::string sourceURL); + std::unique_ptr bundleRegistry, + std::unique_ptr startupCode, + std::string sourceURL); void loadApplicationSync( - std::unique_ptr bundleRegistry, - std::unique_ptr startupCode, - std::string sourceURL); + std::unique_ptr bundleRegistry, + std::unique_ptr startupCode, + std::string sourceURL); - void registerBundle(uint32_t bundleId, const std::string& bundlePath); - void setGlobalVariable(std::string propName, std::unique_ptr jsonValue); - void* getJavaScriptContext(); + void registerBundle(uint32_t bundleId, const std::string &bundlePath); + void setGlobalVariable( + std::string propName, + std::unique_ptr jsonValue); + void *getJavaScriptContext(); bool isInspectable(); bool isBatchActive(); @@ -86,9 +91,9 @@ public: */ void destroy(); - void runOnExecutorQueue(std::function task); + void runOnExecutorQueue(std::function task); -private: + private: // This is used to avoid a race condition where a proxyCallback gets queued // after ~NativeToJsBridge(), on the same thread. In that case, the callback // will try to run the task on m_callback which will have been destroyed @@ -108,9 +113,10 @@ private: // likely fail as well, so this flag can help prevent them. bool m_applicationScriptHasFailure = false; - #ifdef WITH_FBSYSTRACE +#ifdef WITH_FBSYSTRACE std::atomic_uint_least32_t m_systraceCookie = ATOMIC_VAR_INIT(0); - #endif +#endif }; -} } +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/RAMBundleRegistry.h b/ReactCommon/cxxreact/RAMBundleRegistry.h index e507172f67e..9dcb210c990 100644 --- a/ReactCommon/cxxreact/RAMBundleRegistry.h +++ b/ReactCommon/cxxreact/RAMBundleRegistry.h @@ -23,7 +23,7 @@ namespace facebook { namespace react { class RN_EXPORT RAMBundleRegistry { -public: + public: constexpr static uint32_t MAIN_BUNDLE_ID = 0; static std::unique_ptr singleBundleRegistry( @@ -34,22 +34,23 @@ public: explicit RAMBundleRegistry( std::unique_ptr mainBundle, - std::function< - std::unique_ptr(std::string)> factory = nullptr); + std::function(std::string)> factory = + nullptr); - RAMBundleRegistry(RAMBundleRegistry&&) = default; - RAMBundleRegistry& operator=(RAMBundleRegistry&&) = default; + RAMBundleRegistry(RAMBundleRegistry &&) = default; + RAMBundleRegistry &operator=(RAMBundleRegistry &&) = default; void registerBundle(uint32_t bundleId, std::string bundlePath); JSModulesUnbundle::Module getModule(uint32_t bundleId, uint32_t moduleId); - virtual ~RAMBundleRegistry() {}; -private: - JSModulesUnbundle* getBundle(uint32_t bundleId) const; + virtual ~RAMBundleRegistry(){}; + + private: + JSModulesUnbundle *getBundle(uint32_t bundleId) const; std::function(std::string)> m_factory; std::unordered_map m_bundlePaths; std::unordered_map> m_bundles; }; -} // namespace react -} // namespace facebook +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/ReactMarker.cpp b/ReactCommon/cxxreact/ReactMarker.cpp index 45b8aebf2fc..52da94e7d08 100644 --- a/ReactCommon/cxxreact/ReactMarker.cpp +++ b/ReactCommon/cxxreact/ReactMarker.cpp @@ -26,6 +26,6 @@ void logMarker(const ReactMarkerId markerId) { logTaggedMarker(markerId, nullptr); } -} -} -} +} // namespace ReactMarker +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/ReactMarker.h b/ReactCommon/cxxreact/ReactMarker.h index 047a3a3975c..cc55b9ac776 100644 --- a/ReactCommon/cxxreact/ReactMarker.h +++ b/ReactCommon/cxxreact/ReactMarker.h @@ -30,9 +30,10 @@ enum ReactMarkerId { }; #ifdef __APPLE__ -using LogTaggedMarker = std::function; +using LogTaggedMarker = + std::function; #else -typedef void(*LogTaggedMarker)(const ReactMarkerId, const char* tag); +typedef void (*LogTaggedMarker)(const ReactMarkerId, const char *tag); #endif #ifndef RN_EXPORT @@ -43,6 +44,6 @@ extern RN_EXPORT LogTaggedMarker logTaggedMarker; extern RN_EXPORT void logMarker(const ReactMarkerId markerId); -} -} -} +} // namespace ReactMarker +} // namespace react +} // namespace facebook diff --git a/ReactCommon/cxxreact/RecoverableError.h b/ReactCommon/cxxreact/RecoverableError.h index 3c77ccef124..362fea22224 100644 --- a/ReactCommon/cxxreact/RecoverableError.h +++ b/ReactCommon/cxxreact/RecoverableError.h @@ -20,12 +20,12 @@ namespace react { * An exception that it is expected we should be able to recover from. */ struct RecoverableError : public std::exception { - explicit RecoverableError(const std::string &what_) - : m_what { "facebook::react::Recoverable: " + what_ } - {} + : m_what{"facebook::react::Recoverable: " + what_} {} - virtual const char* what() const noexcept override { return m_what.c_str(); } + virtual const char *what() const noexcept override { + return m_what.c_str(); + } /** * runRethrowingAsRecoverable @@ -37,12 +37,12 @@ struct RecoverableError : public std::exception { inline static void runRethrowingAsRecoverable(std::function act) { try { act(); - } catch(const E &err) { + } catch (const E &err) { throw RecoverableError(err.what()); } } -private: + private: std::string m_what; }; diff --git a/ReactCommon/cxxreact/SampleCxxModule.h b/ReactCommon/cxxreact/SampleCxxModule.h index 0e2c2b46605..e669989645f 100644 --- a/ReactCommon/cxxreact/SampleCxxModule.h +++ b/ReactCommon/cxxreact/SampleCxxModule.h @@ -12,29 +12,31 @@ #include -namespace facebook { namespace xplat { namespace samples { +namespace facebook { +namespace xplat { +namespace samples { // In a less contrived example, Sample would be part of a traditional // C++ library. class Sample { -public: + public: std::string hello(); double add(double a, double b); - std::string concat(const std::string& a, const std::string& b); - std::string repeat(int count, const std::string& str); + std::string concat(const std::string &a, const std::string &b); + std::string repeat(int count, const std::string &str); void save(std::map dict); std::map load(); void call_later(int msec, std::function f); void except(); double twice(double n); -private: + private: std::map state_; }; class SampleCxxModule : public module::CxxModule { -public: + public: SampleCxxModule(std::unique_ptr sample); std::string getName(); @@ -43,13 +45,15 @@ public: virtual auto getMethods() -> std::vector; -private: + private: void save(folly::dynamic args); void load(folly::dynamic args, Callback cb); std::unique_ptr sample_; }; -}}} +} // namespace samples +} // namespace xplat +} // namespace facebook extern "C" facebook::xplat::module::CxxModule *SampleCxxModule(); diff --git a/ReactCommon/cxxreact/SharedProxyCxxModule.h b/ReactCommon/cxxreact/SharedProxyCxxModule.h index 5d986afb8a8..97d67ddf0db 100644 --- a/ReactCommon/cxxreact/SharedProxyCxxModule.h +++ b/ReactCommon/cxxreact/SharedProxyCxxModule.h @@ -9,15 +9,17 @@ #include -namespace facebook { namespace xplat { namespace module { +namespace facebook { +namespace xplat { +namespace module { // Allows a Cxx-module to be shared or reused across multiple React instances -// Caveat: the setInstance call is not forwarded, so usages of getInstance inside your -// module (e.g. dispatching events) will always be nullptr. +// Caveat: the setInstance call is not forwarded, so usages of getInstance +// inside your module (e.g. dispatching events) will always be nullptr. class SharedProxyCxxModule : public CxxModule { -public: + public: explicit SharedProxyCxxModule(std::shared_ptr shared) - : shared_(shared) {} + : shared_(shared) {} std::string getName() override { return shared_->getName(); @@ -31,10 +33,10 @@ public: return shared_->getMethods(); } -private: + private: std::shared_ptr shared_; }; -} -} -} +} // namespace module +} // namespace xplat +} // namespace facebook diff --git a/ReactCommon/cxxreact/tests/RecoverableErrorTest.cpp b/ReactCommon/cxxreact/tests/RecoverableErrorTest.cpp index 87322054b0c..cba8d16f70e 100644 --- a/ReactCommon/cxxreact/tests/RecoverableErrorTest.cpp +++ b/ReactCommon/cxxreact/tests/RecoverableErrorTest.cpp @@ -16,9 +16,8 @@ using namespace facebook::react; TEST(RecoverableError, RunRethrowingAsRecoverableRecoverTest) { try { - RecoverableError::runRethrowingAsRecoverable([]() { - throw std::runtime_error("catch me"); - }); + RecoverableError::runRethrowingAsRecoverable( + []() { throw std::runtime_error("catch me"); }); FAIL() << "Unthrown exception"; } catch (const RecoverableError &err) { ASSERT_STREQ(err.what(), "facebook::react::Recoverable: catch me"); @@ -29,9 +28,8 @@ TEST(RecoverableError, RunRethrowingAsRecoverableRecoverTest) { TEST(RecoverableError, RunRethrowingAsRecoverableFallthroughTest) { try { - RecoverableError::runRethrowingAsRecoverable([]() { - throw std::logic_error("catch me"); - }); + RecoverableError::runRethrowingAsRecoverable( + []() { throw std::logic_error("catch me"); }); FAIL() << "Unthrown exception"; } catch (const RecoverableError &err) { FAIL() << "Recovered exception that should have fallen through"; diff --git a/ReactCommon/cxxreact/tests/jsarg_helpers.cpp b/ReactCommon/cxxreact/tests/jsarg_helpers.cpp index 2b3ca978287..c49a65b47d7 100644 --- a/ReactCommon/cxxreact/tests/jsarg_helpers.cpp +++ b/ReactCommon/cxxreact/tests/jsarg_helpers.cpp @@ -16,14 +16,15 @@ using namespace std; using namespace folly; using namespace facebook::xplat; -#define EXPECT_JSAE(statement, exstr) do { \ - try { \ - statement; \ +#define EXPECT_JSAE(statement, exstr) \ + do { \ + try { \ + statement; \ FAIL() << "Expected JsArgumentException(" << (exstr) << ") not thrown"; \ - } catch (const JsArgumentException& ex) { \ - EXPECT_EQ(ex.what(), std::string(exstr)); \ - } \ - } while(0) // let any other exception escape, gtest will deal. + } catch (const JsArgumentException &ex) { \ + EXPECT_EQ(ex.what(), std::string(exstr)); \ + } \ + } while (0) // let any other exception escape, gtest will deal. TEST(JsArgumentHelpersTest, args) { const bool aBool = true; @@ -34,7 +35,8 @@ TEST(JsArgumentHelpersTest, args) { const dynamic anObject = dynamic::object("k1", "v1")("k2", "v2"); const string aNumericString = to(anInt); - folly::dynamic args = dynamic::array(aBool, anInt, aDouble, aString, anArray, anObject, aNumericString); + folly::dynamic args = dynamic::array( + aBool, anInt, aDouble, aString, anArray, anObject, aNumericString); EXPECT_EQ(jsArgAsBool(args, 0), aBool); EXPECT_EQ(jsArgAsInt(args, 1), anInt); @@ -44,8 +46,8 @@ TEST(JsArgumentHelpersTest, args) { EXPECT_EQ(jsArgAsObject(args, 5), anObject); // const args - const folly::dynamic& cargs = args; - const folly::dynamic& a4 = jsArgAsArray(cargs, 4); + const folly::dynamic &cargs = args; + const folly::dynamic &a4 = jsArgAsArray(cargs, 4); EXPECT_EQ(a4, anArray); EXPECT_EQ(jsArgAsObject(cargs, 5), anObject); @@ -73,33 +75,40 @@ TEST(JsArgumentHelpersTest, args) { // Test exception messages. // out_of_range - EXPECT_JSAE(jsArgAsBool(args, 7), - "JavaScript provided 7 arguments for C++ method which references at least " - "8 arguments: out of range in dynamic array"); + EXPECT_JSAE( + jsArgAsBool(args, 7), + "JavaScript provided 7 arguments for C++ method which references at least " + "8 arguments: out of range in dynamic array"); // Conv range_error (invalid value conversion) const std::string exhead = "Could not convert argument 3 to required type: "; const std::string extail = ": Invalid leading character: \"word\""; try { jsArgAsInt(args, 3); - FAIL() << "Expected JsArgumentException(" << exhead << "..." << extail << ") not thrown"; - } catch (const JsArgumentException& ex) { + FAIL() << "Expected JsArgumentException(" << exhead << "..." << extail + << ") not thrown"; + } catch (const JsArgumentException &ex) { const std::string exwhat = ex.what(); EXPECT_GT(exwhat.size(), exhead.size()); EXPECT_GT(exwhat.size(), extail.size()); EXPECT_TRUE(std::equal(exhead.cbegin(), exhead.cend(), exwhat.cbegin())) - << "JsArgumentException('" << exwhat << "') does not begin with '" << exhead << "'"; + << "JsArgumentException('" << exwhat << "') does not begin with '" + << exhead << "'"; EXPECT_TRUE(std::equal(extail.crbegin(), extail.crend(), exwhat.crbegin())) - << "JsArgumentException('" << exwhat << "') does not end with '" << extail << "'"; + << "JsArgumentException('" << exwhat << "') does not end with '" + << extail << "'"; } // inconvertible types - EXPECT_JSAE(jsArgAsArray(args, 2), - "Argument 3 of type double is not required type Array"); - EXPECT_JSAE(jsArgAsInt(args, 4), - "Error converting javascript arg 4 to C++: " - "TypeError: expected dynamic type `int/double/bool/string', but had type `array'"); + EXPECT_JSAE( + jsArgAsArray(args, 2), + "Argument 3 of type double is not required type Array"); + EXPECT_JSAE( + jsArgAsInt(args, 4), + "Error converting javascript arg 4 to C++: " + "TypeError: expected dynamic type `int/double/bool/string', but had type `array'"); // type predicate failure - EXPECT_JSAE(jsArgAsObject(args, 4), - "Argument 5 of type array is not required type Object"); + EXPECT_JSAE( + jsArgAsObject(args, 4), + "Argument 5 of type array is not required type Object"); } diff --git a/ReactCommon/cxxreact/tests/jsbigstring.cpp b/ReactCommon/cxxreact/tests/jsbigstring.cpp index 928fa44949d..de5aaad38ab 100644 --- a/ReactCommon/cxxreact/tests/jsbigstring.cpp +++ b/ReactCommon/cxxreact/tests/jsbigstring.cpp @@ -5,26 +5,25 @@ * LICENSE file in the root directory of this source tree. */ -#include #include +#include +#include #include #include -#include using namespace facebook; using namespace facebook::react; namespace { -int tempFileFromString(std::string contents) -{ +int tempFileFromString(std::string contents) { const char *tmpDir = getenv("TMPDIR"); if (tmpDir == nullptr) tmpDir = "/tmp"; - std::string tmp {tmpDir}; + std::string tmp{tmpDir}; tmp += "/temp.XXXXXX"; - std::vector tmpBuf {tmp.begin(), tmp.end()}; + std::vector tmpBuf{tmp.begin(), tmp.end()}; tmpBuf.push_back('\0'); const int fd = mkstemp(tmpBuf.data()); @@ -32,30 +31,30 @@ int tempFileFromString(std::string contents) return fd; } -}; +}; // namespace TEST(JSBigFileString, MapWholeFileTest) { - std::string data {"Hello, world"}; + std::string data{"Hello, world"}; const auto size = data.length() + 1; // Initialise Big String int fd = tempFileFromString("Hello, world"); - JSBigFileString bigStr {fd, size}; + JSBigFileString bigStr{fd, size}; // Test ASSERT_STREQ(data.c_str(), bigStr.c_str()); } TEST(JSBigFileString, MapPartTest) { - std::string data {"Hello, world"}; + std::string data{"Hello, world"}; // Sub-string to actually map - std::string needle {"or"}; + std::string needle{"or"}; off_t offset = data.find(needle); // Initialise Big String int fd = tempFileFromString(data); - JSBigFileString bigStr {fd, needle.size(), offset}; + JSBigFileString bigStr{fd, needle.size(), offset}; // Test EXPECT_EQ(needle.length(), bigStr.size()); @@ -66,8 +65,7 @@ TEST(JSBigFileString, MapPartTest) { TEST(JSBigFileString, RemapTest) { static const uint8_t kRemapMagic[] = { - 0xc6, 0x1f, 0xbc, 0x03, 0xc1, 0x03, 0x19, 0x1f, 0xa1, 0xd0, 0xeb, 0x73 - }; + 0xc6, 0x1f, 0xbc, 0x03, 0xc1, 0x03, 0x19, 0x1f, 0xa1, 0xd0, 0xeb, 0x73}; std::string data(std::begin(kRemapMagic), std::end(kRemapMagic)); auto app = [&data](uint16_t v) { data.append(reinterpret_cast(&v), sizeof(v)); @@ -75,14 +73,14 @@ TEST(JSBigFileString, RemapTest) { size_t pageSizeLog2 = 16; app(pageSizeLog2); size_t pageSize = 1 << pageSizeLog2; - app(1); // header pages - app(2); // num mappings + app(1); // header pages + app(2); // num mappings // file page 0 -> memory page 1 - app(1); // memory page - app(1); // num pages + app(1); // memory page + app(1); // num pages // file page 1 -> memory page 0 - app(0); // memory page - app(1); // num pages + app(0); // memory page + app(1); // num pages while (data.size() < pageSize) { app(0); } @@ -94,7 +92,7 @@ TEST(JSBigFileString, RemapTest) { } int fd = tempFileFromString(data); - JSBigFileString bigStr {fd, data.size()}; + JSBigFileString bigStr{fd, data.size()}; EXPECT_EQ(pageSize * 2, bigStr.size()); auto remapped = bigStr.c_str(); diff --git a/ReactCommon/cxxreact/tests/methodcall.cpp b/ReactCommon/cxxreact/tests/methodcall.cpp index 772005409e7..3035548d417 100644 --- a/ReactCommon/cxxreact/tests/methodcall.cpp +++ b/ReactCommon/cxxreact/tests/methodcall.cpp @@ -32,39 +32,37 @@ TEST(parseMethodCalls, InvalidReturnFormat) { auto input = dynamic::object("foo", 1); parseMethodCalls(std::move(input)); ADD_FAILURE(); - } catch (const std::invalid_argument&) { + } catch (const std::invalid_argument &) { // ignored } try { auto input = dynamic::array(dynamic::object("foo", 1)); parseMethodCalls(std::move(input)); ADD_FAILURE(); - } catch (const std::invalid_argument&) { + } catch (const std::invalid_argument &) { // ignored } try { auto input = dynamic::array(1, 4, dynamic::object("foo", 2)); parseMethodCalls(std::move(input)); ADD_FAILURE(); - } catch (const std::invalid_argument&) { + } catch (const std::invalid_argument &) { // ignored } try { - auto input = dynamic::array(dynamic::array(1), - dynamic::array(4), - dynamic::object("foo", 2)); + auto input = dynamic::array( + dynamic::array(1), dynamic::array(4), dynamic::object("foo", 2)); parseMethodCalls(std::move(input)); ADD_FAILURE(); - } catch (const std::invalid_argument&) { + } catch (const std::invalid_argument &) { // ignored } try { - auto input = dynamic::array(dynamic::array(1), - dynamic::array(4), - dynamic::array()); + auto input = + dynamic::array(dynamic::array(1), dynamic::array(4), dynamic::array()); parseMethodCalls(std::move(input)); ADD_FAILURE(); - } catch (const std::invalid_argument&) { + } catch (const std::invalid_argument &) { // ignored } } @@ -109,13 +107,14 @@ TEST(parseMethodCalls, NullReturn) { } TEST(parseMethodCalls, MapReturn) { - auto jsText = "[[0],[0],[[{\"foo\": \"hello\", \"bar\": 4.0, \"baz\": true}]]]"; + auto jsText = + "[[0],[0],[[{\"foo\": \"hello\", \"bar\": 4.0, \"baz\": true}]]]"; auto returnedCalls = parseMethodCalls(folly::parseJson(jsText)); EXPECT_EQ(1, returnedCalls.size()); auto returnedCall = returnedCalls[0]; EXPECT_EQ(1, returnedCall.arguments.size()); EXPECT_EQ(folly::dynamic::OBJECT, returnedCall.arguments[0].type()); - auto& returnedMap = returnedCall.arguments[0]; + auto &returnedMap = returnedCall.arguments[0]; auto foo = returnedMap.at("foo"); EXPECT_EQ(folly::dynamic("hello"), foo); auto bar = returnedMap.at("bar"); @@ -131,7 +130,7 @@ TEST(parseMethodCalls, ArrayReturn) { auto returnedCall = returnedCalls[0]; EXPECT_EQ(1, returnedCall.arguments.size()); EXPECT_EQ(folly::dynamic::ARRAY, returnedCall.arguments[0].type()); - auto& returnedArray = returnedCall.arguments[0]; + auto &returnedArray = returnedCall.arguments[0]; EXPECT_EQ(3, returnedArray.size()); EXPECT_EQ(folly::dynamic("foo"), returnedArray[0]); EXPECT_EQ(folly::dynamic(42.0), returnedArray[1]); diff --git a/ReactCommon/fabric/attributedstring/AttributedString.h b/ReactCommon/fabric/attributedstring/AttributedString.h index 8b74d9abca0..99b35d19c34 100644 --- a/ReactCommon/fabric/attributedstring/AttributedString.h +++ b/ReactCommon/fabric/attributedstring/AttributedString.h @@ -109,10 +109,7 @@ struct hash { size_t operator()( const facebook::react::AttributedString::Fragment &fragment) const { return folly::hash::hash_combine( - 0, - fragment.string, - fragment.textAttributes, - fragment.parentShadowView); + 0, fragment.string, fragment.textAttributes, fragment.parentShadowView); } }; diff --git a/ReactCommon/fabric/components/legacyviewmanagerinterop/LegacyViewManagerInteropState.mm b/ReactCommon/fabric/components/legacyviewmanagerinterop/LegacyViewManagerInteropState.mm index 36893532435..4ded11fa599 100644 --- a/ReactCommon/fabric/components/legacyviewmanagerinterop/LegacyViewManagerInteropState.mm +++ b/ReactCommon/fabric/components/legacyviewmanagerinterop/LegacyViewManagerInteropState.mm @@ -8,5 +8,6 @@ #include "LegacyViewManagerInteropState.h" namespace facebook { -namespace react {} // namespace react +namespace react { +} // namespace react } // namespace facebook diff --git a/ReactCommon/fabric/components/view/Touch.h b/ReactCommon/fabric/components/view/Touch.h index 82bbc1b4947..866850deb3d 100644 --- a/ReactCommon/fabric/components/view/Touch.h +++ b/ReactCommon/fabric/components/view/Touch.h @@ -7,9 +7,9 @@ #pragma once -#include #include #include +#include namespace facebook { namespace react { diff --git a/ReactCommon/fabric/components/view/TouchEvent.cpp b/ReactCommon/fabric/components/view/TouchEvent.cpp index 9ecad86005b..203a1bad0b0 100644 --- a/ReactCommon/fabric/components/view/TouchEvent.cpp +++ b/ReactCommon/fabric/components/view/TouchEvent.cpp @@ -19,10 +19,10 @@ std::string getDebugName(TouchEvent const &touchEvent) { std::vector getDebugProps( TouchEvent const &touchEvent, DebugStringConvertibleOptions options) { - return { {"touches", getDebugDescription(touchEvent.touches, options)}, - {"changedTouches", getDebugDescription(touchEvent.changedTouches, options)}, + {"changedTouches", + getDebugDescription(touchEvent.changedTouches, options)}, {"targetTouches", getDebugDescription(touchEvent.targetTouches, options)}, }; } diff --git a/ReactCommon/fabric/components/view/TouchEventEmitter.h b/ReactCommon/fabric/components/view/TouchEventEmitter.h index 46b7273a4b1..f43d5a3037f 100644 --- a/ReactCommon/fabric/components/view/TouchEventEmitter.h +++ b/ReactCommon/fabric/components/view/TouchEventEmitter.h @@ -7,11 +7,11 @@ #pragma once +#include #include #include #include #include -#include namespace facebook { namespace react { diff --git a/ReactCommon/fabric/graphics/Transform.cpp b/ReactCommon/fabric/graphics/Transform.cpp index aa7ba92b165..a9b51ea5ca5 100644 --- a/ReactCommon/fabric/graphics/Transform.cpp +++ b/ReactCommon/fabric/graphics/Transform.cpp @@ -165,9 +165,12 @@ Point operator*(Point const &point, Transform const &transform) { } auto result = Point{}; - result.x = transform.at(3, 0) + point.x * transform.at(0, 0) + point.y * transform.at(1, 0); - result.y = transform.at(3, 1) + point.x * transform.at(0, 1) + point.y * transform.at(1, 1); - auto w = transform.at(3, 3) + point.x * transform.at(0, 3) + point.y * transform.at(1, 3); + result.x = transform.at(3, 0) + point.x * transform.at(0, 0) + + point.y * transform.at(1, 0); + result.y = transform.at(3, 1) + point.x * transform.at(0, 1) + + point.y * transform.at(1, 1); + auto w = transform.at(3, 3) + point.x * transform.at(0, 3) + + point.y * transform.at(1, 3); if (w != 1 && w != 0) { result.x /= w; diff --git a/ReactCommon/fabric/imagemanager/platform/ios/RCTImagePrimitivesConversions.h b/ReactCommon/fabric/imagemanager/platform/ios/RCTImagePrimitivesConversions.h index db8739a5822..db9d498dfe6 100644 --- a/ReactCommon/fabric/imagemanager/platform/ios/RCTImagePrimitivesConversions.h +++ b/ReactCommon/fabric/imagemanager/platform/ios/RCTImagePrimitivesConversions.h @@ -12,8 +12,8 @@ using namespace facebook::react; -inline static RCTResizeMode RCTResizeModeFromImageResizeMode( - ImageResizeMode imageResizeMode) { +inline static RCTResizeMode RCTResizeModeFromImageResizeMode(ImageResizeMode imageResizeMode) +{ switch (imageResizeMode) { case ImageResizeMode::Cover: return RCTResizeModeCover; @@ -28,7 +28,8 @@ inline static RCTResizeMode RCTResizeModeFromImageResizeMode( } } -inline std::string toString(const ImageResizeMode &value) { +inline std::string toString(const ImageResizeMode &value) +{ switch (value) { case ImageResizeMode::Cover: return "cover"; @@ -43,17 +44,15 @@ inline std::string toString(const ImageResizeMode &value) { } } -inline static NSURL *NSURLFromImageSource(const ImageSource &imageSource) { +inline static NSURL *NSURLFromImageSource(const ImageSource &imageSource) +{ // `NSURL` has a history of crashing with bad input, so let's be safe. @try { - NSString *urlString = [NSString stringWithCString:imageSource.uri.c_str() - encoding:NSASCIIStringEncoding]; + NSString *urlString = [NSString stringWithCString:imageSource.uri.c_str() encoding:NSASCIIStringEncoding]; if (!imageSource.bundle.empty()) { - NSString *bundle = [NSString stringWithCString:imageSource.bundle.c_str() - encoding:NSASCIIStringEncoding]; - urlString = - [NSString stringWithFormat:@"%@.bundle/%@", bundle, urlString]; + NSString *bundle = [NSString stringWithCString:imageSource.bundle.c_str() encoding:NSASCIIStringEncoding]; + urlString = [NSString stringWithFormat:@"%@.bundle/%@", bundle, urlString]; } NSURL *url = [[NSURL alloc] initWithString:urlString]; @@ -65,8 +64,7 @@ inline static NSURL *NSURLFromImageSource(const ImageSource &imageSource) { if ([urlString rangeOfString:@":"].location != NSNotFound) { // The URL has a scheme. - urlString = [urlString - stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; url = [NSURL URLWithString:urlString]; return url; } @@ -80,8 +78,7 @@ inline static NSURL *NSURLFromImageSource(const ImageSource &imageSource) { } else { if (![urlString isAbsolutePath]) { // Assume it's a resource path. - urlString = [[[NSBundle mainBundle] resourcePath] - stringByAppendingPathComponent:urlString]; + urlString = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:urlString]; } } @@ -93,8 +90,8 @@ inline static NSURL *NSURLFromImageSource(const ImageSource &imageSource) { } } -inline static NSURLRequest *NSURLRequestFromImageSource( - const ImageSource &imageSource) { +inline static NSURLRequest *NSURLRequestFromImageSource(const ImageSource &imageSource) +{ NSURL *url = NSURLFromImageSource(imageSource); if (!url) { diff --git a/ReactCommon/fabric/mounting/ShadowTreeRegistry.cpp b/ReactCommon/fabric/mounting/ShadowTreeRegistry.cpp index 694de536080..f2792af365b 100644 --- a/ReactCommon/fabric/mounting/ShadowTreeRegistry.cpp +++ b/ReactCommon/fabric/mounting/ShadowTreeRegistry.cpp @@ -11,7 +11,9 @@ namespace facebook { namespace react { ShadowTreeRegistry::~ShadowTreeRegistry() { - assert(registry_.size() == 0 && "Deallocation of non-empty `ShadowTreeRegistry`."); + assert( + registry_.size() == 0 && + "Deallocation of non-empty `ShadowTreeRegistry`."); } void ShadowTreeRegistry::add(std::unique_ptr &&shadowTree) const { diff --git a/ReactCommon/fabric/textlayoutmanager/platform/ios/NSTextStorage+FontScaling.m b/ReactCommon/fabric/textlayoutmanager/platform/ios/NSTextStorage+FontScaling.m index 71c86e49d6d..3a39ca20f62 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/ios/NSTextStorage+FontScaling.m +++ b/ReactCommon/fabric/textlayoutmanager/platform/ios/NSTextStorage+FontScaling.m @@ -17,7 +17,8 @@ typedef NS_OPTIONS(NSInteger, RCTTextSizeComparisonOptions) { - (void)scaleFontSizeToFitSize:(CGSize)size minimumFontSize:(CGFloat)minimumFontSize - maximumFontSize:(CGFloat)maximumFontSize { + maximumFontSize:(CGFloat)maximumFontSize +{ CGFloat bottomRatio = 1.0 / 128.0; CGFloat topRatio = 128.0; CGFloat ratio = 1.0; @@ -27,15 +28,11 @@ typedef NS_OPTIONS(NSInteger, RCTTextSizeComparisonOptions) { CGFloat lastRatioWhichFits = 0.02; while (true) { - [self scaleFontSizeWithRatio:ratio - minimumFontSize:minimumFontSize - maximumFontSize:maximumFontSize]; + [self scaleFontSizeWithRatio:ratio minimumFontSize:minimumFontSize maximumFontSize:maximumFontSize]; - RCTTextSizeComparisonOptions comparsion = [self compareToSize:size - thresholdRatio:0.01]; + RCTTextSizeComparisonOptions comparsion = [self compareToSize:size thresholdRatio:0.01]; - if ((comparsion & RCTTextSizeComparisonWithinRange) && - (comparsion & RCTTextSizeComparisonSmaller)) { + if ((comparsion & RCTTextSizeComparisonWithinRange) && (comparsion & RCTTextSizeComparisonSmaller)) { return; } else if (comparsion & RCTTextSizeComparisonSmaller) { bottomRatio = ratio; @@ -47,25 +44,20 @@ typedef NS_OPTIONS(NSInteger, RCTTextSizeComparisonOptions) { ratio = (topRatio + bottomRatio) / 2.0; CGFloat kRatioThreshold = 0.005; - if (ABS(topRatio - bottomRatio) < kRatioThreshold || - ABS(topRatio - ratio) < kRatioThreshold || + if (ABS(topRatio - bottomRatio) < kRatioThreshold || ABS(topRatio - ratio) < kRatioThreshold || ABS(bottomRatio - ratio) < kRatioThreshold) { - [self replaceCharactersInRange:(NSRange){0, self.length} - withAttributedString:originalAttributedString]; + [self replaceCharactersInRange:(NSRange){0, self.length} withAttributedString:originalAttributedString]; - [self scaleFontSizeWithRatio:lastRatioWhichFits - minimumFontSize:minimumFontSize - maximumFontSize:maximumFontSize]; + [self scaleFontSizeWithRatio:lastRatioWhichFits minimumFontSize:minimumFontSize maximumFontSize:maximumFontSize]; return; } - [self replaceCharactersInRange:(NSRange){0, self.length} - withAttributedString:originalAttributedString]; + [self replaceCharactersInRange:(NSRange){0, self.length} withAttributedString:originalAttributedString]; } } -- (RCTTextSizeComparisonOptions)compareToSize:(CGSize)size - thresholdRatio:(CGFloat)thresholdRatio { +- (RCTTextSizeComparisonOptions)compareToSize:(CGSize)size thresholdRatio:(CGFloat)thresholdRatio +{ NSLayoutManager *layoutManager = self.layoutManagers.firstObject; NSTextContainer *textContainer = layoutManager.textContainers.firstObject; @@ -73,19 +65,16 @@ typedef NS_OPTIONS(NSInteger, RCTTextSizeComparisonOptions) { // Does it fit the text container? NSRange glyphRange = [layoutManager glyphRangeForTextContainer:textContainer]; - NSRange truncatedGlyphRange = [layoutManager - truncatedGlyphRangeInLineFragmentForGlyphAtIndex:glyphRange.length - 1]; + NSRange truncatedGlyphRange = [layoutManager truncatedGlyphRangeInLineFragmentForGlyphAtIndex:glyphRange.length - 1]; if (truncatedGlyphRange.location != NSNotFound) { return RCTTextSizeComparisonLarger; } - CGSize measuredSize = - [layoutManager usedRectForTextContainer:textContainer].size; + CGSize measuredSize = [layoutManager usedRectForTextContainer:textContainer].size; // Does it fit the size? - BOOL fitsSize = - size.width >= measuredSize.width && size.height >= measuredSize.height; + BOOL fitsSize = size.width >= measuredSize.width && size.height >= measuredSize.height; CGSize thresholdSize = (CGSize){ size.width * thresholdRatio, @@ -94,8 +83,7 @@ typedef NS_OPTIONS(NSInteger, RCTTextSizeComparisonOptions) { RCTTextSizeComparisonOptions result = 0; - result |= - (fitsSize) ? RCTTextSizeComparisonSmaller : RCTTextSizeComparisonLarger; + result |= (fitsSize) ? RCTTextSizeComparisonSmaller : RCTTextSizeComparisonLarger; if (ABS(measuredSize.width - size.width) < thresholdSize.width) { result = result | RCTTextSizeComparisonWithinRange; @@ -106,28 +94,22 @@ typedef NS_OPTIONS(NSInteger, RCTTextSizeComparisonOptions) { - (void)scaleFontSizeWithRatio:(CGFloat)ratio minimumFontSize:(CGFloat)minimumFontSize - maximumFontSize:(CGFloat)maximumFontSize { + maximumFontSize:(CGFloat)maximumFontSize +{ [self beginEditing]; - [self - enumerateAttribute:NSFontAttributeName - inRange:(NSRange){0, self.length} - options: - NSAttributedStringEnumerationLongestEffectiveRangeNotRequired - usingBlock:^( - UIFont *_Nullable font, NSRange range, BOOL *_Nonnull stop) { - if (!font) { - return; - } + [self enumerateAttribute:NSFontAttributeName + inRange:(NSRange){0, self.length} + options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired + usingBlock:^(UIFont *_Nullable font, NSRange range, BOOL *_Nonnull stop) { + if (!font) { + return; + } - CGFloat fontSize = - MAX(MIN(font.pointSize * ratio, maximumFontSize), - minimumFontSize); + CGFloat fontSize = MAX(MIN(font.pointSize * ratio, maximumFontSize), minimumFontSize); - [self addAttribute:NSFontAttributeName - value:[font fontWithSize:fontSize] - range:range]; - }]; + [self addAttribute:NSFontAttributeName value:[font fontWithSize:fontSize] range:range]; + }]; [self endEditing]; } diff --git a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.h b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.h index 0091b23b6a7..a88eb2902a2 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.h +++ b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.h @@ -28,15 +28,12 @@ NS_ASSUME_NONNULL_BEGIN layoutConstraints:(facebook::react::LayoutConstraints)layoutConstraints; - (void)drawAttributedString:(facebook::react::AttributedString)attributedString - paragraphAttributes: - (facebook::react::ParagraphAttributes)paragraphAttributes + paragraphAttributes:(facebook::react::ParagraphAttributes)paragraphAttributes frame:(CGRect)frame; - (facebook::react::SharedEventEmitter) - getEventEmitterWithAttributeString: - (facebook::react::AttributedString)attributedString - paragraphAttributes: - (facebook::react::ParagraphAttributes)paragraphAttributes + getEventEmitterWithAttributeString:(facebook::react::AttributedString)attributedString + paragraphAttributes:(facebook::react::ParagraphAttributes)paragraphAttributes frame:(CGRect)frame atPoint:(CGPoint)point; diff --git a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.mm b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.mm index 2c3a3e93411..875ee084090 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.mm +++ b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.mm @@ -69,7 +69,8 @@ static NSLineBreakMode RCTNSLineBreakModeFromEllipsizeMode(EllipsizeMode ellipsi - (void)drawAttributedString:(AttributedString)attributedString paragraphAttributes:(ParagraphAttributes)paragraphAttributes - frame:(CGRect)frame { + frame:(CGRect)frame +{ NSTextStorage *textStorage = [self _textStorageAndLayoutManagerWithAttributesString:[self _nsAttributedStringFromAttributedString:attributedString] paragraphAttributes:paragraphAttributes @@ -82,12 +83,10 @@ static NSLineBreakMode RCTNSLineBreakModeFromEllipsizeMode(EllipsizeMode ellipsi [layoutManager drawGlyphsForGlyphRange:glyphRange atPoint:frame.origin]; } -- (NSTextStorage *) - _textStorageAndLayoutManagerWithAttributesString: - (NSAttributedString *)attributedString - paragraphAttributes: - (ParagraphAttributes)paragraphAttributes - size:(CGSize)size { +- (NSTextStorage *)_textStorageAndLayoutManagerWithAttributesString:(NSAttributedString *)attributedString + paragraphAttributes:(ParagraphAttributes)paragraphAttributes + size:(CGSize)size +{ NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:size]; textContainer.lineFragmentPadding = 0.0; // Note, the default value is 5. @@ -100,31 +99,24 @@ static NSLineBreakMode RCTNSLineBreakModeFromEllipsizeMode(EllipsizeMode ellipsi layoutManager.usesFontLeading = NO; [layoutManager addTextContainer:textContainer]; - NSTextStorage *textStorage = - [[NSTextStorage alloc] initWithAttributedString:attributedString]; + NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedString]; [textStorage addLayoutManager:layoutManager]; if (paragraphAttributes.adjustsFontSizeToFit) { - CGFloat minimumFontSize = !isnan(paragraphAttributes.minimumFontSize) - ? paragraphAttributes.minimumFontSize - : 4.0; - CGFloat maximumFontSize = !isnan(paragraphAttributes.maximumFontSize) - ? paragraphAttributes.maximumFontSize - : 96.0; - [textStorage scaleFontSizeToFitSize:size - minimumFontSize:minimumFontSize - maximumFontSize:maximumFontSize]; + CGFloat minimumFontSize = !isnan(paragraphAttributes.minimumFontSize) ? paragraphAttributes.minimumFontSize : 4.0; + CGFloat maximumFontSize = !isnan(paragraphAttributes.maximumFontSize) ? paragraphAttributes.maximumFontSize : 96.0; + [textStorage scaleFontSizeToFitSize:size minimumFontSize:minimumFontSize maximumFontSize:maximumFontSize]; } return textStorage; } -- (SharedEventEmitter) - getEventEmitterWithAttributeString:(AttributedString)attributedString - paragraphAttributes:(ParagraphAttributes)paragraphAttributes - frame:(CGRect)frame - atPoint:(CGPoint)point { +- (SharedEventEmitter)getEventEmitterWithAttributeString:(AttributedString)attributedString + paragraphAttributes:(ParagraphAttributes)paragraphAttributes + frame:(CGRect)frame + atPoint:(CGPoint)point +{ NSTextStorage *textStorage = [self _textStorageAndLayoutManagerWithAttributesString:[self _nsAttributedStringFromAttributedString:attributedString] paragraphAttributes:paragraphAttributes @@ -133,20 +125,18 @@ static NSLineBreakMode RCTNSLineBreakModeFromEllipsizeMode(EllipsizeMode ellipsi NSTextContainer *textContainer = layoutManager.textContainers.firstObject; CGFloat fraction; - NSUInteger characterIndex = - [layoutManager characterIndexForPoint:point - inTextContainer:textContainer - fractionOfDistanceBetweenInsertionPoints:&fraction]; + NSUInteger characterIndex = [layoutManager characterIndexForPoint:point + inTextContainer:textContainer + fractionOfDistanceBetweenInsertionPoints:&fraction]; // If the point is not before (fraction == 0.0) the first character and not // after (fraction == 1.0) the last character, then the attribute is valid. if (textStorage.length > 0 && (fraction > 0 || characterIndex > 0) && (fraction < 1 || characterIndex < textStorage.length - 1)) { RCTWeakEventEmitterWrapper *eventEmitterWrapper = - (RCTWeakEventEmitterWrapper *)[textStorage - attribute:RCTAttributedStringEventEmitterKey - atIndex:characterIndex - effectiveRange:NULL]; + (RCTWeakEventEmitterWrapper *)[textStorage attribute:RCTAttributedStringEventEmitterKey + atIndex:characterIndex + effectiveRange:NULL]; return eventEmitterWrapper.eventEmitter; } diff --git a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextPrimitivesConversions.h b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextPrimitivesConversions.h index a4eafd6ce40..1b69bbf2c7e 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextPrimitivesConversions.h +++ b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextPrimitivesConversions.h @@ -12,8 +12,8 @@ using namespace facebook::react; -inline static NSTextAlignment RCTNSTextAlignmentFromTextAlignment( - TextAlignment textAlignment) { +inline static NSTextAlignment RCTNSTextAlignmentFromTextAlignment(TextAlignment textAlignment) +{ switch (textAlignment) { case TextAlignment::Natural: return NSTextAlignmentNatural; @@ -28,8 +28,8 @@ inline static NSTextAlignment RCTNSTextAlignmentFromTextAlignment( } } -inline static NSWritingDirection RCTNSWritingDirectionFromWritingDirection( - WritingDirection writingDirection) { +inline static NSWritingDirection RCTNSWritingDirectionFromWritingDirection(WritingDirection writingDirection) +{ switch (writingDirection) { case WritingDirection::Natural: return NSWritingDirectionNatural; @@ -40,7 +40,8 @@ inline static NSWritingDirection RCTNSWritingDirectionFromWritingDirection( } } -inline static RCTFontStyle RCTFontStyleFromFontStyle(FontStyle fontStyle) { +inline static RCTFontStyle RCTFontStyleFromFontStyle(FontStyle fontStyle) +{ switch (fontStyle) { case FontStyle::Normal: return RCTFontStyleNormal; @@ -51,14 +52,15 @@ inline static RCTFontStyle RCTFontStyleFromFontStyle(FontStyle fontStyle) { } } -inline static RCTFontVariant RCTFontVariantFromFontVariant( - FontVariant fontVariant) { +inline static RCTFontVariant RCTFontVariantFromFontVariant(FontVariant fontVariant) +{ return (RCTFontVariant)fontVariant; } inline static NSUnderlineStyle RCTNSUnderlineStyleFromStyleAndPattern( TextDecorationLineStyle textDecorationLineStyle, - TextDecorationLinePattern textDecorationLinePattern) { + TextDecorationLinePattern textDecorationLinePattern) +{ NSUnderlineStyle style = NSUnderlineStyleNone; switch (textDecorationLineStyle) { @@ -94,6 +96,7 @@ inline static NSUnderlineStyle RCTNSUnderlineStyleFromStyleAndPattern( return style; } -inline static UIColor *RCTUIColorFromSharedColor(const SharedColor &color) { +inline static UIColor *RCTUIColorFromSharedColor(const SharedColor &color) +{ return color ? [UIColor colorWithCGColor:color.get()] : nil; } diff --git a/ReactCommon/jsi/JSCRuntime.cpp b/ReactCommon/jsi/JSCRuntime.cpp index f96cab8d73f..0a09afb7dae 100644 --- a/ReactCommon/jsi/JSCRuntime.cpp +++ b/ReactCommon/jsi/JSCRuntime.cpp @@ -1368,8 +1368,8 @@ jsi::Value JSCRuntime::createValue(JSValueRef value) const { JSObjectRef objRef = JSValueToObject(ctx_, value, nullptr); return jsi::Value(createObject(objRef)); } -// TODO: Uncomment this when all supported JSC versions have this symbol -// case kJSTypeSymbol: + // TODO: Uncomment this when all supported JSC versions have this symbol + // case kJSTypeSymbol: default: { if (smellsLikeES6Symbol(ctx_, value)) { return jsi::Value(createSymbol(value)); diff --git a/ReactCommon/jsiexecutor/jsireact/JSINativeModules.cpp b/ReactCommon/jsiexecutor/jsireact/JSINativeModules.cpp index a4d3ae2b8aa..425152cdac6 100644 --- a/ReactCommon/jsiexecutor/jsireact/JSINativeModules.cpp +++ b/ReactCommon/jsiexecutor/jsireact/JSINativeModules.cpp @@ -24,7 +24,7 @@ JSINativeModules::JSINativeModules( std::shared_ptr moduleRegistry) : m_moduleRegistry(std::move(moduleRegistry)) {} -Value JSINativeModules::getModule(Runtime& rt, const PropNameID& name) { +Value JSINativeModules::getModule(Runtime &rt, const PropNameID &name) { if (!m_moduleRegistry) { return nullptr; } @@ -54,8 +54,8 @@ void JSINativeModules::reset() { } folly::Optional JSINativeModules::createModule( - Runtime& rt, - const std::string& name) { + Runtime &rt, + const std::string &name) { bool hasLogger(ReactMarker::logTaggedMarker); if (hasLogger) { ReactMarker::logTaggedMarker( diff --git a/ReactCommon/jsiexecutor/jsireact/JSINativeModules.h b/ReactCommon/jsiexecutor/jsireact/JSINativeModules.h index 7d45a13362c..a1dff88ec9f 100644 --- a/ReactCommon/jsiexecutor/jsireact/JSINativeModules.h +++ b/ReactCommon/jsiexecutor/jsireact/JSINativeModules.h @@ -23,7 +23,7 @@ namespace react { class JSINativeModules { public: explicit JSINativeModules(std::shared_ptr moduleRegistry); - jsi::Value getModule(jsi::Runtime& rt, const jsi::PropNameID& name); + jsi::Value getModule(jsi::Runtime &rt, const jsi::PropNameID &name); void reset(); private: @@ -32,8 +32,8 @@ class JSINativeModules { std::unordered_map m_objects; folly::Optional createModule( - jsi::Runtime& rt, - const std::string& name); + jsi::Runtime &rt, + const std::string &name); }; } // namespace react diff --git a/ReactCommon/jsinspector/InspectorInterfaces.cpp b/ReactCommon/jsinspector/InspectorInterfaces.cpp index 7923d2b10f6..ed918c97db6 100644 --- a/ReactCommon/jsinspector/InspectorInterfaces.cpp +++ b/ReactCommon/jsinspector/InspectorInterfaces.cpp @@ -8,8 +8,8 @@ #include "InspectorInterfaces.h" #include -#include #include +#include namespace facebook { namespace react { @@ -26,7 +26,10 @@ namespace { class InspectorImpl : public IInspector { public: - int addPage(const std::string& title, const std::string& vm, ConnectFunc connectFunc) override; + int addPage( + const std::string &title, + const std::string &vm, + ConnectFunc connectFunc) override; void removePage(int pageId) override; std::vector getPages() const override; @@ -41,7 +44,10 @@ class InspectorImpl : public IInspector { std::unordered_map connectFuncs_; }; -int InspectorImpl::addPage(const std::string& title, const std::string& vm, ConnectFunc connectFunc) { +int InspectorImpl::addPage( + const std::string &title, + const std::string &vm, + ConnectFunc connectFunc) { std::lock_guard lock(mutex_); int pageId = nextPageId_++; @@ -62,8 +68,9 @@ std::vector InspectorImpl::getPages() const { std::lock_guard lock(mutex_); std::vector inspectorPages; - for (auto& it : titles_) { - inspectorPages.push_back(InspectorPage{it.first, std::get<0>(it.second), std::get<1>(it.second)}); + for (auto &it : titles_) { + inspectorPages.push_back(InspectorPage{ + it.first, std::get<0>(it.second), std::get<1>(it.second)}); } return inspectorPages; @@ -88,7 +95,7 @@ std::unique_ptr InspectorImpl::connect( } // namespace -IInspector& getInspectorInstance() { +IInspector &getInspectorInstance() { static InspectorImpl instance; return instance; } diff --git a/ReactCommon/jsinspector/InspectorInterfaces.h b/ReactCommon/jsinspector/InspectorInterfaces.h index bb3f0894c81..32178e7b9a0 100644 --- a/ReactCommon/jsinspector/InspectorInterfaces.h +++ b/ReactCommon/jsinspector/InspectorInterfaces.h @@ -51,7 +51,10 @@ class IInspector : public IDestructible { virtual ~IInspector() = 0; /// addPage is called by the VM to add a page to the list of debuggable pages. - virtual int addPage(const std::string& title, const std::string& vm, ConnectFunc connectFunc) = 0; + virtual int addPage( + const std::string &title, + const std::string &vm, + ConnectFunc connectFunc) = 0; /// removePage is called by the VM to remove a page from the list of /// debuggable pages. @@ -69,7 +72,7 @@ class IInspector : public IDestructible { /// getInspectorInstance retrieves the singleton inspector that tracks all /// debuggable pages in this process. -extern IInspector& getInspectorInstance(); +extern IInspector &getInspectorInstance(); /// makeTestInspectorInstance creates an independent inspector instance that /// should only be used in tests. diff --git a/ReactCommon/microprofiler/MicroProfiler.cpp b/ReactCommon/microprofiler/MicroProfiler.cpp index 82f2981a2b5..15fd0164603 100644 --- a/ReactCommon/microprofiler/MicroProfiler.cpp +++ b/ReactCommon/microprofiler/MicroProfiler.cpp @@ -5,19 +5,19 @@ * LICENSE file in the root directory of this source tree. */ +#include #include #include #include #include #include -#include #include #include "MicroProfiler.h" -// iOS doesn't support 'thread_local'. If we reimplement this to use pthread_setspecific -// we can get rid of this +// iOS doesn't support 'thread_local'. If we reimplement this to use +// pthread_setspecific we can get rid of this #if defined(__APPLE__) #define MICRO_PROFILER_STUB_IMPLEMENTATION 1 #elif !defined(MICRO_PROFILER_STUB_IMPLEMENTATION) @@ -32,18 +32,22 @@ struct TraceData { TraceData(); ~TraceData(); - void addTime(MicroProfilerName name, uint_fast64_t time, uint_fast32_t internalClockCalls); + void addTime( + MicroProfilerName name, + uint_fast64_t time, + uint_fast32_t internalClockCalls); std::thread::id threadId_; uint_fast64_t startTime_; std::atomic_uint_fast64_t times_[MicroProfilerName::__LENGTH__] = {}; std::atomic_uint_fast32_t calls_[MicroProfilerName::__LENGTH__] = {}; - std::atomic_uint_fast32_t childProfileSections_[MicroProfilerName::__LENGTH__] = {}; + std::atomic_uint_fast32_t + childProfileSections_[MicroProfilerName::__LENGTH__] = {}; }; struct ProfilingImpl { std::mutex mutex_; - std::vector allTraceData_; + std::vector allTraceData_; bool isProfiling_ = false; uint_fast64_t startTime_; uint_fast64_t endTime_; @@ -78,10 +82,10 @@ static std::string formatTimeNs(uint_fast64_t timeNs) { return out.str(); } -MicroProfilerSection::MicroProfilerSection(MicroProfilerName name) : - isProfiling_(profiling.isProfiling_), - name_(name), - startNumProfileSections_(profileSections) { +MicroProfilerSection::MicroProfilerSection(MicroProfilerName name) + : isProfiling_(profiling.isProfiling_), + name_(name), + startNumProfileSections_(profileSections) { if (!isProfiling_) { return; } @@ -94,22 +98,27 @@ MicroProfilerSection::~MicroProfilerSection() { } auto endTime = nowNs(); auto endNumProfileSections = profileSections; - myTraceData.addTime(name_, endTime - startTime_, endNumProfileSections - startNumProfileSections_ - 1); + myTraceData.addTime( + name_, + endTime - startTime_, + endNumProfileSections - startNumProfileSections_ - 1); } -TraceData::TraceData() : - threadId_(std::this_thread::get_id()) { +TraceData::TraceData() : threadId_(std::this_thread::get_id()) { std::lock_guard lock(profiling.mutex_); profiling.allTraceData_.push_back(this); } TraceData::~TraceData() { std::lock_guard lock(profiling.mutex_); - auto& infos = profiling.allTraceData_; + auto &infos = profiling.allTraceData_; infos.erase(std::remove(infos.begin(), infos.end(), this), infos.end()); } -void TraceData::addTime(MicroProfilerName name, uint_fast64_t time, uint_fast32_t childprofileSections) { +void TraceData::addTime( + MicroProfilerName name, + uint_fast64_t time, + uint_fast32_t childprofileSections) { times_[name] += time; calls_[name]++; childProfileSections_[name] += childprofileSections; @@ -117,24 +126,36 @@ void TraceData::addTime(MicroProfilerName name, uint_fast64_t time, uint_fast32_ static void printReport() { LOG(ERROR) << "======= MICRO PROFILER REPORT ======="; - LOG(ERROR) << "- Total Time: " << formatTimeNs(diffNs(profiling.startTime_, profiling.endTime_)); + LOG(ERROR) << "- Total Time: " + << formatTimeNs(diffNs(profiling.startTime_, profiling.endTime_)); LOG(ERROR) << "- Clock Overhead: " << formatTimeNs(profiling.clockOverhead_); - LOG(ERROR) << "- Profiler Section Overhead: " << formatTimeNs(profiling.profileSectionOverhead_); + LOG(ERROR) << "- Profiler Section Overhead: " + << formatTimeNs(profiling.profileSectionOverhead_); for (auto info : profiling.allTraceData_) { LOG(ERROR) << "--- Thread ID 0x" << std::hex << info->threadId_ << " ---"; for (int i = 0; i < MicroProfilerName::__LENGTH__; i++) { if (info->times_[i] > 0) { auto totalTime = info->times_[i].load(); auto calls = info->calls_[i].load(); - auto clockOverhead = profiling.clockOverhead_ * calls + profiling.profileSectionOverhead_ * info->childProfileSections_[i].load(); + auto clockOverhead = profiling.clockOverhead_ * calls + + profiling.profileSectionOverhead_ * + info->childProfileSections_[i].load(); if (totalTime < clockOverhead) { - LOG(ERROR) << "- " << MicroProfiler::profilingNameToString(static_cast(i)) << ": " - << "ERROR: Total time was " << totalTime << "ns but clock overhead was calculated to be " << clockOverhead << "ns!"; + LOG(ERROR) << "- " + << MicroProfiler::profilingNameToString( + static_cast(i)) + << ": " + << "ERROR: Total time was " << totalTime + << "ns but clock overhead was calculated to be " + << clockOverhead << "ns!"; } else { auto correctedTime = totalTime - clockOverhead; auto timePerCall = correctedTime / calls; - LOG(ERROR) << "- " << MicroProfiler::profilingNameToString(static_cast(i)) << ": " - << formatTimeNs(correctedTime) << " (" << calls << " calls, " << formatTimeNs(timePerCall) << "/call)"; + LOG(ERROR) << "- " + << MicroProfiler::profilingNameToString( + static_cast(i)) + << ": " << formatTimeNs(correctedTime) << " (" << calls + << " calls, " << formatTimeNs(timePerCall) << "/call)"; } } } @@ -142,7 +163,8 @@ static void printReport() { } static void clearProfiling() { - CHECK(!profiling.isProfiling_) << "Trying to clear profiling but profiling was already started!"; + CHECK(!profiling.isProfiling_) + << "Trying to clear profiling but profiling was already started!"; for (auto info : profiling.allTraceData_) { for (unsigned int i = 0; i < MicroProfilerName::__LENGTH__; i++) { info->times_[i] = 0; @@ -175,7 +197,8 @@ static uint_fast64_t calculateProfileSectionOverhead() { } void MicroProfiler::startProfiling() { - CHECK(!profiling.isProfiling_) << "Trying to start profiling but profiling was already started!"; + CHECK(!profiling.isProfiling_) + << "Trying to start profiling but profiling was already started!"; profiling.clockOverhead_ = calculateClockOverhead(); profiling.profileSectionOverhead_ = calculateProfileSectionOverhead(); @@ -188,7 +211,8 @@ void MicroProfiler::startProfiling() { } void MicroProfiler::stopProfiling() { - CHECK(profiling.isProfiling_) << "Trying to stop profiling but profiling hasn't been started!"; + CHECK(profiling.isProfiling_) + << "Trying to stop profiling but profiling hasn't been started!"; profiling.isProfiling_ = false; profiling.endTime_ = nowNs(); @@ -208,23 +232,21 @@ void MicroProfiler::runInternalBenchmark() { MicroProfiler::startProfiling(); for (int i = 0; i < 1000000; i++) { MICRO_PROFILER_SECTION_NAMED(outer, __INTERNAL_BENCHMARK_OUTER); - { - MICRO_PROFILER_SECTION_NAMED(inner, __INTERNAL_BENCHMARK_INNER); - } + { MICRO_PROFILER_SECTION_NAMED(inner, __INTERNAL_BENCHMARK_INNER); } } MicroProfiler::stopProfiling(); } #else void MicroProfiler::startProfiling() { - CHECK(false) << "This platform has a stub implementation of the micro profiler and cannot collect traces"; -} -void MicroProfiler::stopProfiling() { + CHECK(false) + << "This platform has a stub implementation of the micro profiler and cannot collect traces"; } +void MicroProfiler::stopProfiling() {} bool MicroProfiler::isProfiling() { return false; } -void MicroProfiler::runInternalBenchmark() { -} +void MicroProfiler::runInternalBenchmark() {} #endif -} } +} // namespace react +} // namespace facebook diff --git a/ReactCommon/microprofiler/MicroProfiler.h b/ReactCommon/microprofiler/MicroProfiler.h index 70adecf251b..3c6861173a7 100644 --- a/ReactCommon/microprofiler/MicroProfiler.h +++ b/ReactCommon/microprofiler/MicroProfiler.h @@ -14,7 +14,8 @@ #ifdef WITH_MICRO_PROFILER #define MICRO_PROFILER_SECTION(name) MicroProfilerSection __b(name) -#define MICRO_PROFILER_SECTION_NAMED(var_name, name) MicroProfilerSection var_name(name) +#define MICRO_PROFILER_SECTION_NAMED(var_name, name) \ + MicroProfilerSection var_name(name) #else #define MICRO_PROFILER_SECTION(name) #define MICRO_PROFILER_SECTION_NAMED(var_name, name) @@ -30,27 +31,29 @@ enum MicroProfilerName { }; /** - * MicroProfiler is a performance profiler for measuring the cumulative impact of - * a large number of small-ish calls. This is normally a problem for standard profilers - * like Systrace because the overhead of the profiler itself skews the timings you - * are able to collect. This is especially a problem when doing nested calls to - * profiled functions, as the parent calls will contain the overhead of their profiling - * plus the overhead of all their childrens' profiling. + * MicroProfiler is a performance profiler for measuring the cumulative impact + * of a large number of small-ish calls. This is normally a problem for standard + * profilers like Systrace because the overhead of the profiler itself skews the + * timings you are able to collect. This is especially a problem when doing + * nested calls to profiled functions, as the parent calls will contain the + * overhead of their profiling plus the overhead of all their childrens' + * profiling. * - * MicroProfiler attempts to be low overhead by 1) aggregating timings in memory and - * 2) trying to remove estimated profiling overhead from the returned timings. + * MicroProfiler attempts to be low overhead by 1) aggregating timings in memory + * and 2) trying to remove estimated profiling overhead from the returned + * timings. * * To remove estimated overhead, at the beginning of each trace we calculate the - * average cost of profiling a no-op code section, as well as invoking the average - * cost of invoking the system clock. The former is subtracted out for each child - * profiler section that is invoked within a parent profiler section. The latter is - * subtracted from each section, child or not. + * average cost of profiling a no-op code section, as well as invoking the + * average cost of invoking the system clock. The former is subtracted out for + * each child profiler section that is invoked within a parent profiler section. + * The latter is subtracted from each section, child or not. * - * After MicroProfiler::stopProfiling() is called, a table of tracing data is emitted - * to glog (which shows up in logcat on Android). + * After MicroProfiler::stopProfiling() is called, a table of tracing data is + * emitted to glog (which shows up in logcat on Android). */ struct MicroProfiler { - static const char* profilingNameToString(MicroProfilerName name) { + static const char *profilingNameToString(MicroProfilerName name) { switch (name) { case __INTERNAL_BENCHMARK_INNER: return "__INTERNAL_BENCHMARK_INNER"; @@ -59,7 +62,8 @@ struct MicroProfiler { case __LENGTH__: throw std::runtime_error("__LENGTH__ has no name"); default: - throw std::runtime_error("Trying to convert unknown MicroProfilerName to string"); + throw std::runtime_error( + "Trying to convert unknown MicroProfilerName to string"); } } @@ -70,15 +74,16 @@ struct MicroProfiler { }; class MicroProfilerSection { -public: + public: MicroProfilerSection(MicroProfilerName name); ~MicroProfilerSection(); -private: + private: bool isProfiling_; MicroProfilerName name_; uint_fast64_t startTime_; uint_fast32_t startNumProfileSections_; }; -} } +} // namespace react +} // namespace facebook diff --git a/ReactCommon/utils/ManagedObjectWrapper.h b/ReactCommon/utils/ManagedObjectWrapper.h index 3b671408aad..0f44838c39f 100644 --- a/ReactCommon/utils/ManagedObjectWrapper.h +++ b/ReactCommon/utils/ManagedObjectWrapper.h @@ -35,11 +35,13 @@ namespace react { * represented as multiple bumps of C++ counter, so we can have multiple * counters for the same object that form some kind of counters tree. */ -inline std::shared_ptr wrapManagedObject(id object) { +inline std::shared_ptr wrapManagedObject(id object) +{ return std::shared_ptr((__bridge_retained void *)object, CFRelease); } -inline id unwrapManagedObject(std::shared_ptr const &object) { +inline id unwrapManagedObject(std::shared_ptr const &object) +{ return (__bridge id)object.get(); } diff --git a/ReactCommon/utils/SimpleThreadSafeCache.h b/ReactCommon/utils/SimpleThreadSafeCache.h index 8492709462e..b500535bb7f 100644 --- a/ReactCommon/utils/SimpleThreadSafeCache.h +++ b/ReactCommon/utils/SimpleThreadSafeCache.h @@ -18,9 +18,9 @@ namespace react { /* * Simple thread-safe LRU cache. */ -template +template class SimpleThreadSafeCache { -public: + public: SimpleThreadSafeCache() : map_{maxSize} {} /* @@ -29,7 +29,8 @@ public: * generator function, stores it inside a cache and returns it. * Can be called from any thread. */ - ValueT get(const KeyT &key, std::function generator) const { + ValueT get(const KeyT &key, std::function generator) + const { std::lock_guard lock(mutex_); auto iterator = map_.find(key); if (iterator == map_.end()) { @@ -65,7 +66,7 @@ public: map_.set(std::move(key), std::move(value)); } -private: + private: mutable folly::EvictingCacheMap map_; mutable std::mutex mutex_; }; diff --git a/ReactCommon/utils/TimeUtils.h b/ReactCommon/utils/TimeUtils.h index 91e6e5ae151..b87fc564e75 100644 --- a/ReactCommon/utils/TimeUtils.h +++ b/ReactCommon/utils/TimeUtils.h @@ -62,10 +62,13 @@ inline static int64_t monotonicTimeInMilliseconds() { #else - It's Unix *without* MONOTONIC_CLOCK support or Microsoft Windows. - If you run this on Microsoft Windows, could you please implement the - function using some Windows-specific APIs, and submit a PR? - https://stackoverflow.com/questions/5404277/porting-clock-gettime-to-windows + It's Unix *without* MONOTONIC_CLOCK support or Microsoft Windows. If you + run this on Microsoft Windows, + could you please implement the function using some Windows - + specific APIs, + and submit a PR + ? https + : // stackoverflow.com/questions/5404277/porting-clock-gettime-to-windows #endif }