Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46788
Changelog: [internal]
This fixes the reported keys for C++ TurboModules:
```
import MyNativeCppModule from 'MyNativeCppModule';
Object.keys(MyNativeCppModule); // [] - expected
Object.keys(Object.getPrototypeOf(MyNativeCppModule)); // [] - NOT expected
```
Before, we were trying to read the properties from the method map in the public `TurboModule`, but in this implementation all the logic is actually in its delegate (also a `TurboModule` instance, yeah, confusing).
This fixes the issue by forwarding the call to the delegate that has the right information.
Reviewed By: javache
Differential Revision: D63761381
fbshipit-source-id: 90bd216efa0f60352c5ca341d210d83239c80dba
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46751
rubennorte noticed that some turbo module methods were not getting cached on the jsRepresentation as expected. This is caused by the react-native-codegen wrappers we generate overriding the `get` method and bypassing this caching layer. Instead they should be overriding `create` to lazily allocate new properties. To prevent this from re-occuring, I've made `get` final so no other overrides can happen.
## Changelog:
[General][Fixed] Properties for C++ TurboModules using codegen were not correctly cached
[General][Breaking] TurboModule::get is now a final method, override `create` to customize property lookup
Reviewed By: rubennorte
Differential Revision: D63665966
fbshipit-source-id: c614901c2f0d698147ec9ba36a4b592ed3d37652
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/44809
Adding react-native-codegen parser support for a new `EventEmitter` property type on C++ Turbo Modules.
It is possible to later expand this feature to other languages (Java, ObjC).
## Characteristics
An `EventEmitter` must:
- be non null:
`EventEmitter<string>` works, `?EventEmitter<string>` does NOT
- have a non null eventType:
`EventEmitter<number>` works, `EventEmitter<?number>` does NOT
- have at most 1 eventType, `void` is possible as well:
`EventEmitter<>` or `EventEmitter<MyObject>` work - `EventEmitter<number, string>` do NOT
- have a concrete eventType, `{}` is not allowed
`EventEmitter<{}>` does NOT work
- be used in `Cxx` Turbo Modules only at this time
## Example
For these 4 eventEmitters in on an RN JS TM spec
```
+onPress: EventEmitter<void>;
+onClick: EventEmitter<string>;
+onChange: EventEmitter<ObjectStruct>;
+onSubmit: EventEmitter<ObjectStruct[]>;
```
We now generate this code:
1.) in the spec based header `{MyModuleName}CxxSpec` in the constructor:
```
... // existing code
eventEmitterMap_["onPress"] = std::make_shared<AsyncEventEmitter<>>();
eventEmitterMap_["onClick"] = std::make_shared<AsyncEventEmitter<OnClickType>>();
eventEmitterMap_["onChange"] = std::make_shared<AsyncEventEmitter<OnChangeType>>();
eventEmitterMap_["onSubmit"] = std::make_shared<AsyncEventEmitter<OnSubmitType>>();
```
2.) as `protected` functions
```
void emitOnPress() {
std::static_pointer_cast<AsyncEventEmitter<>>(delegate_.eventEmitterMap_["onPress"])->emit();
}
void emitOnClick(const OnClickType& value) {
std::static_pointer_cast<AsyncEventEmitter<OnClickType>>(delegate_.eventEmitterMap_["onClick"])->emit(value);
}
void emitOnChange(const OnChangeType& value) {
std::static_pointer_cast<AsyncEventEmitter<OnChangeType>>(delegate_.eventEmitterMap_["onChange"])->emit(value);
}
void emitOnSubmit(const OnSubmitType& value) {
std::static_pointer_cast<AsyncEventEmitter<OnSubmitType>>(delegate_.eventEmitterMap_["onSubmit"])->emit(value);
}
```
## Changelog:
[General] [Added] - Add EventEmitter code-gen support for C++ Turbo Modules
Reviewed By: javache
Differential Revision: D57407871
fbshipit-source-id: 2345cc6dacf0cb0d45f8a374ad9d4cbf8082f9d6
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/44630
Changelog:
[General][Breaking] Use hasteModuleName for C++ Turbo Module structs
This changes the names of C++ Turbo Modules structs to use the `hasteModuleName`.
Example: `NativeMyAbcModule.js` with this spec:
```
export type ValueStruct = {
x: number,
y: string,
z: ObjectStruct,
};
export interface Spec extends TurboModule {
+getValueStruct: () => ValueStruct
}
export default (TurboModuleRegistry.get<Spec>('MyAbcModuleCxx'): ?Spec);
```
Before now we generated a base C++ struct with the name:
```
MyAbcModuleCxxValueStruct
^^^
```
Now the generate name is:
```
NativeMyAbcModuleValueStruct
^^^^^^
```
## Changes:
- No `Cxx` injected anymore
- Ensure base struct is `Native` prefixed (all RN JS TM specs start with it)
## Why?
- The `Cxx` extension is a temporary hint to react-native-codegen to enable extra capabilities and might disappear eventually
- The C++ base struct name should be 'stable'
- The name of the exported TM JS spec `TurboModuleRegistry.get<Spec>(...)` is abritrary, the hasteName is not
- The name of the RN JS TM spec must start with `Native` which better guarantees a consistent naming scheme for these generated base class
- The C++ Turbo Module base class has now the same prefix as the generated structs - `NativeMyAbcModule` for the example above
Reviewed By: cipolleschi
Differential Revision: D57599257
fbshipit-source-id: 4fafe6c7e920737fa766bd7e8e68e521f608e775
Summary:
The motiviation of this change is to produce sorted / stable native module schemas which members are alphabetically sorted. The benefit is mainly for verifying test fixtures as now new test cases will be inserted at predicatable spots.
Changelog: [Internal]
Reviewed By: rshest
Differential Revision: D56741776
fbshipit-source-id: 842af73cac3b4859d2074e6a5206015924e87201
Summary:
Changelog: [General][BREAKING] Don't support 'float' enums in Turbo Modules
- The current implementation of 'float enums' in C++ does not work as invalid results are returned.
- At potential fix could still cause rounding errors when crossing language bounaries, e.g. `4.6` can become `4.5599999942..`
- C++ enum classes don't support float: https://eel.is/c++draft/dcl.enum#2.sentence-4
> The type-specifier-seq of an enum-base shall name an integral type; any cv-qualification is ignored.
Hence removing the feature of `float enums` for now
Reviewed By: NickGerleman
Differential Revision: D52120405
fbshipit-source-id: 3685ad0629e16ff9db424ba67e07d09df6027553
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/44005
When using frameworks on iOS, there is a possibility that modules import the Spec.h file twice and this might end up in a Redefinition of some symbols and duplication of symbols which ends up in build errors, as reported here: https://github.com/facebook/react-native/issues/42670.
This change adds some [`#include guards`](https://en.wikipedia.org/wiki/Include_guard) in codegen to avoid the redefinition of those symbols if the header is imported/included multiple times.
Note: I also experimented with `#pragma once`, but it looks like Apple is not happy with that directive. [It seems](https://forums.developer.apple.com/forums/thread/739964) that it started working flakely from Xcode 15.
## Changelog:
[General][Fixed] - Make sure that we can't include Codegen symbols multiple times
Reviewed By: cortinico
Differential Revision: D55925605
fbshipit-source-id: 15ca076aace2ffbd03ab8fa8a68a3d8ce0d1ea65
Summary:
Changelog: [General][Breaking] Native modules using the codegen now throw an error when called with `null` for optional but not nullable arguments.
## Context
Right now, if you have a native module using the codegen with a method like this:
```
someMethod(value?: number): void;
```
And you call it like this:
```
NativeModule.someMethod(null);
```
The app doesn't throw an error, but it should because this method shouldn't accept `null` according to its type definition.
## Changes
This modifies the codegen to only check for `undefined` in those cases, otherwise trying to cast the value to the expected type and failing if it's `null`.
NOTE: this is technically a breaking change, but if people are using Flow or TypeScript in their projects they're very unlikely to hit this case, because they would've complained if you tried to pass `null` in these cases.
Reviewed By: cipolleschi
Differential Revision: D54206289
fbshipit-source-id: 58f2f2f3009d203b96189d3c66d1ae98a9e4fb36
Summary:
Changelog: [General][Fixed] Fixed crash when passing fewer arguments than expected in native modules using codegen
## Context
Right now, if you have a native module using the codegen with a method like this:
```
someMethod(value: number): void;
```
And you call it like this:
```
NativeModule.someMethod();
```
The app crashes.
This happens because the codegen tries to cast the value to the expected type without checking if the argument is within the bounds of the arguments array.
## Changes
This fixes that issue with a change in the codegen to guard against this in the generated code (see changes in the snapshot tests).
Reviewed By: RSNara
Differential Revision: D54206287
fbshipit-source-id: 575af462725515928f8634fccc7a9cb51ca0ce4f
Summary:
Changelog: [General][Fixed] Fixed crash when passing non-numeric values where RootTag is expected to methods in native modules using codegen
## Context
Right now, if you have a native module using the codegen with a method like this:
```
someMethod(value: RootTag): void;
```
And you call it like this:
```
NativeModule.someMethod('');
```
The app crashes.
This happens because we cast the JS value to a C++ value using the method that asserts (`toNumber`) instead of the one that throws a JS error (`asNumber`).
## Changes
This fixes the crash by using `asNumber` instead of `toNumber`.
Reviewed By: RSNara
Differential Revision: D54206288
fbshipit-source-id: 9398112667e0f26edaf4f8f3b32e79fa8aafde62
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/42122
This diff introduces the `TypeUtils` directory where we can put platform-specific, context-independent type transformations.
Changelog: [Internal]
Reviewed By: cipolleschi
Differential Revision: D52291837
fbshipit-source-id: 561b9c494aab5bfee3b3c668d3346bbd320e5266
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41923
Changelog: [Internal][BREAKING] Use C++ enum classes in C++ Turbo Modules
Problem:
Using **C styles** `enums` can easily cause compiliation errors if symbol names collide. This code does not compile:
```
enum CustomEnumInt { A = 23, B = 42 };
static int A = 22;
```
This **C++ code**, using `enum classes` compiles:
```
enum class CustomEnumInt : int32_t { A = 23, B = 42 };
static int A = 22;
```
Reviewed By: rshest
Differential Revision: D52098598
fbshipit-source-id: c919bd2e41970c83a032fec91b0537cd6fae8397
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41771
Changelog: [Internal]
Since we are already enforcing C++20 (and 17), we can set the namespace declaration to the C++17 style
Reviewed By: NickGerleman
Differential Revision: D51789991
fbshipit-source-id: 165d7d4e652d60ab200e2355e084010a02f470a4
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41645
Right now, when defining concrete structs and Bridging headers for Cxx TMs we need to define their member types twice:
```
using ConstantsStruct =
NativeCxxModuleExampleCxxBaseConstantsStruct<bool, int32_t, std::string>;
template <>
struct Bridging<ConstantsStruct>
: NativeCxxModuleExampleCxxBaseConstantsStructBridging<
bool,
int32_t,
std::string> {};
```
Now we only need to define those once
```
using ConstantsStruct =
NativeCxxModuleExampleCxxConstantsStruct<bool, int32_t, std::string>;
template <>
struct Bridging<ConstantsStruct>
: NativeCxxModuleExampleCxxConstantsStructBridging<ConstantsStruct> {};
```
This change keeps the existing base types untouched - but they will be removed in the next RN version.
Changelog: [Internal]
Reviewed By: rshest
Differential Revision: D51571453
fbshipit-source-id: 2783bd48bf786ffa80d322d06456b5d6f2d7ba8a
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/39212
## Changelog:
[Internal] -
Some of the generated C++ code was badly formatted - even though it's normally not supposed to be read by humans, sometimes it's still useful/needed, so it helps when it's more readable.
Reviewed By: christophpurrer
Differential Revision: D48827010
fbshipit-source-id: 3481af68ee6158902007c431e72e631d852c8b3c
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/38295
Move constant to class instance so customers can use strongly typed name, feedback from D46159001
Changelog:
[Internal] [Changed] - Add module name constant to codegen'd class for downstream use
Reviewed By: christophpurrer
Differential Revision: D47095993
fbshipit-source-id: 741d0d837bf912d6b32e5f12c5df871563d46686
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37832
This parameter is currently unused and is causing Android builds to fail
as they compile with `-Wall`
This is a follow-up to https://github.com/facebook/react-native/pull/37454/ as that PR updated only the `fromJs` and not the `toJs` method as well.
Changelog:
[Internal] [Changed] - Remove CallInvoker parameter from toJs method in Codegen
Reviewed By: rshest
Differential Revision: D46647110
fbshipit-source-id: 1f3e22aca7a3df11ac02b5c4b89c9311b8b1798c
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36030
Generate enum types in c++ turbo modules.
For enums in the ts schema file such as:
```
export enum NumEnum {
ONE = 1,
TWO = 2,
}
```
This would export enums and the relevant Bridging to js and from js code to the spec H files such as:
```
#pragma mark - SampleTurboModuleCxxNumEnum
enum SampleTurboModuleCxxNumEnum { ONE, TWO };
template <>
struct Bridging<SampleTurboModuleCxxNumEnum> {
static SampleTurboModuleCxxNumEnum fromJs(jsi::Runtime &rt, int32_t value) {
if (value == 1) {
return SampleTurboModuleCxxNumEnum::ONE;
} else if (value == 2) {
return SampleTurboModuleCxxNumEnum::TWO;
} else {
throw jsi::JSError(rt, "No appropriate enum member found for value");
}
}
static jsi::Value toJs(jsi::Runtime &rt, SampleTurboModuleCxxNumEnum value) {
if (value == SampleTurboModuleCxxNumEnum::ONE) {
return bridging::toJs(rt, 1);
} else if (value == SampleTurboModuleCxxNumEnum::TWO) {
return bridging::toJs(rt, 2);
} else {
throw jsi::JSError(rt, "No appropriate enum member found for enum value");
}
}
};
```
That code would allow us to use these enums in the cxx files like this:
```
NativeCxxModuleExampleCxxEnumInt getNumEnum(
jsi::Runtime &rt,
NativeCxxModuleExampleCxxEnumInt arg);
```
Changelog: [General] [Added] Generate enum types that would be allowed to be used as well as string/number in c++ turbo modules generators
Reviewed By: christophpurrer
Differential Revision: D42884147
fbshipit-source-id: d34d1fc7ba268b570821dc108444196f69a431b2
Summary:
* Added an e2e test fixture with all the supported enum variations
* Added H and C file TM generators to the TM e2e tests
Changelog: [Internal] Added an e2e test fixture for Enums and .H+.C TM e2e snapshot tests
Reviewed By: cipolleschi
Differential Revision: D42917330
fbshipit-source-id: 8e4adb86b6eb4e2b29a9e6d0cd6e4fd5b002ad1a
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/35961
Pull Request resolved: https://github.com/facebook/react-native/pull/35960
This fixes#35864
This feature allows using `$Partial<Obj>` in flow and `Partial<Obj>` in TypeScript based on the spec mentioned here: https://flow.org/en/docs/types/utilities/#toc-partial.
We currently only allow passing an Obj to Partial so
```
export type SomeObj = {
a: string,
b?: boolean,
};
export type PartialSomeObj = Partial<SomeObj>;
```
should work.
and also-
```
export type PartialSomeObj = Partial<{
a: string,
b?: boolean,
}>;
```
But not
```
export type PartialSomeObj = Partial<Partial<{
a: string,
b?: boolean,
}>>;
```
This can be improved in the future by a recursive unwrapping of the value inside the `Partial` annotation.
Changelog:
[General] [Added] - Allow the use of "Partial<T>" in Turbo Module specs.
Reviewed By: christophpurrer, cipolleschi
Differential Revision: D42640880
fbshipit-source-id: 03a3fccc38ccfc7a5440fe11893beb68e77753f3
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/32840Closes#31516
I've cherry-picked the original PR that had merge conficts + updated all
the headers as the one for the TurboModule generators were not handled.
Original Commit Message from acoates
The codegen generates a Facebook copyright notice at the top of the generated files.
While this might make sense on the core files, this codegen will be run on external components too.
The notice also refers to a LICENSE file in the root of this project, which might not be there if this is run on another project.
I did a quick look at some of the codegen that we ship within windows dev tools, and it looks like we normally just have comments
saying the file was codegen'd and so the file shouldn't be manually edited.
Open to suggestions on what the comment header should say.
Changelog:
[General] [Changed] - Do not include Facebook license on users codegen'd code
Reviewed By: ShikaSD
Differential Revision: D33455176
fbshipit-source-id: b247e72efb242e79d99b388c80e4126633e5234d
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/31543
Changelog:
[iOS][Added] - Description
When compiling iOS apps with flag `-Wnullability-completeness` (like Lightspeed app and soon Instagram), Objective-C headers are required to either have full *explicit* nullability annotations on all members of its public API, or none at all; partially annotated headers will fail to build that module.
RN native modules are currently generated with *partial* annotations. This works today because most apps are not compiled with `-Wnullability-completeness` turned on. But when we flip the switch for Instagram, the app doesn't build due to importing these RN partially annotated modules.
JavsScript Flow types are implied nonnull, and the current RN codegen translates Flow's [maybe/optional](https://flow.org/en/docs/types/maybe/) type to Obj-C `_Nullable` annotation, and everything else without an explicit Obj-C annotation. However this creates a mismatch with the Obj-C type system, where the implied default is *unannotated*, which is handled differently from nonnull when built with the nullability compiler flags.
There is a simple Obj-C macro that automatically adds *explicit nonnull* annotations to all members in a header: `NS_ASSUME_NONNULL_BEGIN` / `NS_ASSUME_NONNULL_END`. If we add this to *all* RN-generated headers, however, we run into issues:
1) We may erroneously assume any previously-unannotated header was meant to be nonnull and cause future bugs
2) Another compiler flag (`-Wnullable-to-nonnull-conversion`) statically analyzes Obj-C implementation code to prevent us from ever passing null to one of these headers. Much existing Obj-C code will break here, and it's ambiguous if these are true or false positives because of the first point.
Instead, in this diff we add a new BUCK flag `ios_assume_nonnull` to let module authors opt into automatic nonnull for unannotated members so that Obj-C headers are generated correctly in alignment with Flow's type system. We can migrate all libraries individually as needed and eventually make this the RN native codegen default.
Reviewed By: RSNara
Differential Revision: D28396446
fbshipit-source-id: ad3a3a97ab19183df4ef504b1c3140596c8f69ca
Summary:
## Problem
Suppose we have this NativeModule spec, that uses Object literals that contain a property called "id":
```
export interface Spec extends TurboModule {
// Exported methods.
+getConstants: () => {|
id: string,
|};
+getObject: (arg: {id: Object}) => Object;
}
```
For both object literals, we'll generate C++ structs, backed by NSDictionaries. The method in each struct will be named "id_" to avoid a name clash with ObjC's `id` identifier. However, calling that id_ method should still access the "id" property in the corresponding NSDictionary.
## Expected Output
```
inline id<NSObject> JS::NativeSampleTurboModule::SpecGetObjectArg::id_() const
{
id const p = _v[@"id"];
return p;
}
inline JS::NativeSampleTurboModule::Constants::Builder::Builder(const Input i) : _factory(^{
NSMutableDictionary *d = [NSMutableDictionary new];
auto id_ = i.id_.get();
d[@"id"] = id_;
return d;
}) {}
```
## Actual Output
```
inline id<NSObject> JS::NativeSampleTurboModule::SpecGetObjectArg::id_() const
{
id const p = _v[@"id_"]; // <-- HERE!
return p;
}
inline JS::NativeSampleTurboModule::Constants::Builder::Builder(const Input i) : _factory(^{
NSMutableDictionary *d = [NSMutableDictionary new];
auto id_ = i.id_.get();
d[@"id_"] = id_; // <-- HERE!
return d;
}) {}
```
NOTE: This code was generated by running `jf get --version 119805822 && buck build //xplat/js:FBReactNativeSpec_Sample-flow-types-ios --show-output`
This diff fixes this mistake.
Changelog: [Internal]
Reviewed By: fkgozali
Differential Revision: D25907493
fbshipit-source-id: cb37cbf49db4f871b3f4046f7397a7b1b7df0357
Summary:
Changelog: [internal]
Codegen was generating code with return value number instead of boolean.
Reviewed By: RSNara
Differential Revision: D25863062
fbshipit-source-id: 780f88dd2d83e303b03d1ed9cc837ac6733f1702
Summary:
NOTE: Flow and Jest won't pass on this diff. Sandcastle, should, however, be green on D24236405 (i.e: the tip of this stack).
## Changes
1. NativeModule generators now use the new RN Codegen NativeModule schema.
2. Tangential: We're no longer removing the `Native` prefix from the NativeModule filename, assuming that that's the module name (problem: wrong), and prefixing again with Native (problem: redundant), when we're generating code. Instead, like the internal codegen, we simply pass the filename to the Codegen output. Our linters enforce that all NativeModule specs are contained with files that start off with `Native`.
3. `GenerateModuleCpp` was fixed to use the actual module name as opposed to the spec name. I added a comment inline.
Changelog: [Internal]
(Note: this ignores all push blocking failures!)
Reviewed By: PeteTheHeat
Differential Revision: D24236405
fbshipit-source-id: ccd6b5674d252c350be0ec8a86e7ca5f2f614778
Summary:
Remove extraneous newlines before and after structs, before copyright headers, and other locations.
Changelog: [Internal]
Reviewed By: fkgozali
Differential Revision: D24117137
fbshipit-source-id: 194996019b4cadef9239a78334f31c0bc89e3901
Summary:
Adjust generated ObjC++ code to resolve a few build time and run time errors:
* Suppress CONSTANTS struct implementations
* Use type alias name as struct name when serializing arguments that involve a type alias
* Use actual number of arguments for a method when generating method map.
With these changes in place, RNTester can be built and run using the code that is generated by the new codegen.
Changelog: [Internal]
Reviewed By: hramos
Differential Revision: D23926500
fbshipit-source-id: 88fcbb795fd71dc8155eb26348db943975e13e84
Summary:
* Removed extraneous closing brace.
* Fixed static method signature, replacing double colon with an underscore (`static facebook::jsi::Value __hostFunction_Native${moduleName}SpecJSI::${methodName}()` -> `static facebook::jsi::Value __hostFunction_Native${moduleName}SpecJSI_${methodName}()`).
* Wrap `getConstants` selector name with `selector()`.
* Pass through `getConstants` and `constantsToExport` to allow de-duping of `getConstants` method in generator output.
Note that the FBReactNativeSpec that is output by the generator still has some issues that need to be addressed before it can be used.
Changelog: [Internal]
Reviewed By: fkgozali
Differential Revision: D23910505
fbshipit-source-id: 37d884885b8878f38d40637377c2a74a728c3a13
Summary:
NativeModule specs exist under `react-native-github/packages/react-native-codegen/src/__tests__/modules/fixtures`. `GenerateModuleObjCpp-test.js` runs the RN Codegen on those NativeModule specs, and saves the output inside a snapshot. For convenience, the folowing command runs the legacy codegen on the fixtures:
```
buck build fbsource//xplat/js/react-native-github/packages/react-native-codegen/src/__tests__/modules:RNCodegenModuleFixtures-flow-types-ios --show-output
```
Changelog: [Internal]
Reviewed By: hramos
Differential Revision: D23637708
fbshipit-source-id: 3319f319515eca42b4499682313fea6e0bdc2a06