Commit Graph

46 Commits

Author SHA1 Message Date
Rubén Norte 4b82922ac5 Fix reported properties for native modules (#46788)
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
2024-10-02 12:25:06 -07:00
Pieter De Baets 5b5e150eaf Fix Cxx TurboModule methods not being cached (#46751)
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
2024-10-02 05:10:33 -07:00
Christoph Purrer ad3df84668 Add EventEmitter Code-gen support for Java and ObjC Turbo Modules (#45119)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/45119

## Changelog:

[iOS][Added] - Add EventEmitter Code-gen support for Java and ObjC Turbo Modules

Reviewed By: RSNara

Differential Revision: D58929417

fbshipit-source-id: 5208ba5ecb5882d47c3827c2aa8e3a54a3d7f2b6
2024-07-01 14:42:46 -07:00
Christoph Purrer ed5f558a6c Code-generate an optional base class to use for every NativeModule (#45113)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/45113

## Changelog:

[iOS][Added] - Code-generate an optional base class to use for every NativeModule

Extend RN Code-gen to generate a NativeModule base class for each ObjC Turbo Modules.

Its usage is not mandatory now, but would become for future features to add

A practial first step would be to migrate

https://github.com/facebook/react-native/blob/main/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.h#L157-L160

from the `protocol` to the default `interface` and then provide a default implementation for it

Reviewed By: RSNara

Differential Revision: D58907395

fbshipit-source-id: a6b0ef97a5c7f5bb0c53a4cb6fd83d2e55306953
2024-06-28 13:29:15 -07:00
Christoph Purrer fd618819c7 Add EventEmitter code-gen support for C++ Turbo Modules (#44809)
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
2024-06-11 19:19:22 -07:00
zhongwuzw 1a1795a537 Fixes enum codegen value cases (#44654)
Summary:
Fixes https://github.com/facebook/react-native/issues/44632

## Changelog:

[GENERAL] [FIXED] - [codegen] Fixes enum codegen value cases

Pull Request resolved: https://github.com/facebook/react-native/pull/44654

Test Plan: https://github.com/facebook/react-native/issues/44632

Reviewed By: cipolleschi, dmytrorykun

Differential Revision: D58135645

Pulled By: cortinico

fbshipit-source-id: 5c0634ef1d1d7375d2ecfcf7f916d67fd39b7300
2024-06-07 07:53:59 -07:00
Christoph Purrer 07261d0408 Use hasteModuleName for C++ Turbo Module structs (#44630)
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
2024-05-23 03:28:52 -07:00
Christoph Purrer eb1b42fa8b Sort spec members
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
2024-05-02 20:31:50 -07:00
Christoph Purrer 536edf3726 Don't support float enums
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
2024-04-30 21:52:09 -07:00
Riccardo Cipolleschi 46b6453eb6 Fix the Redefinition of 'NativeXXXSpecJSI' error with Frameworks (#44005)
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
2024-04-11 11:39:43 -07:00
Christoph Purrer 04bf8cfb23 Clean up old Cxx TM member generation (#43710)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/43710

As we had already cut a branch for RN 0.74
https://github.com/facebook/react-native/releases/tag/v0.74.0-rc.1

We can delete this code already

Changelog: [Internal]

Reviewed By: shwanton

Differential Revision: D55511382

fbshipit-source-id: 3ef15af338b5ad31b02e0a1eed7ac873566d9562
2024-03-29 14:39:24 -07:00
Rubén Norte 67b9628af5 Modify native module codegen to throw JS errors when passing null values for non-nullable arguments
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
2024-02-29 13:12:49 -08:00
Rubén Norte 179b684e76 Modify native module codegen to throw JS errors instead of crashing when not passing required parameters
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
2024-02-27 09:29:53 -08:00
Rubén Norte abbc6eb022 Modify codegen to throw JS errors instead of crashing when passing non-number arguments where RootTags are expected
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
2024-02-27 09:29:53 -08:00
Dmitry Rykun 82f8cf1836 Introduce TypeUtils (#42122)
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
2024-01-03 08:58:30 -08:00
Christoph Purrer 8183afeb81 Use enum classes in C++ Turbo Modules (#41923)
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
2023-12-14 06:54:49 -08:00
Christoph Purrer b101dd0e34 Use C++17 namespace (#41771)
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
2023-12-04 19:07:51 -08:00
Christoph Purrer ef9c164f5f Simplify C++ TM struct generation (#41645)
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
2023-11-27 03:43:28 -08:00
Christoph Purrer c2ac0cc72a react-native-codegen: Cxx TMs > Fixed Undefined Behavior exception when running ASAN builds (#41401)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41401

Changelog: [Internal]

When build Cxx Turbo Modules with Clang's ASAN build mode the apps are crashing at runtime due to, e.g.:
```
runtime error: downcast of address 0x00010dafd618 which does not point to an object of type 'facebook::react::NativePerformance'
0x00010dafd618: note: object is of type 'facebook::react::NativePerformanceCxxSpec<facebook::react::NativePerformance>'
 00 00 00 00  f0 08 49 06 01 00 00 00  4e 61 74 69 76 65 50 65  72 66 6f 72 6d 61 6e 63  65 43 78 78
              ^~~~~~~~~~~~~~~~~~~~~~~
              vptr for 'facebook::react::NativePerformanceCxxSpec<facebook::react::NativePerformance>'
UndefinedBehaviorSanitizer: undefined-behavior FBReactNativeSpecJSI.h:6122:17
```

Where the corresponding generated code looks like

```
NativePerformanceCxxSpec(std::shared_ptr<CallInvoker> jsInvoker)
    : TurboModule(std::string{NativePerformanceCxxSpec::kModuleName}, jsInvoker),
      delegate_(static_cast<T*>(this), jsInvoker) {}
```

This change fixes that problem

AddressSanitizer: stack-use-after-scope shared_ptr.h:634 in std::__1::shared_ptr<facebook::react::InstanceHandle const>::shared_ptr[abi:v160006](std::__1::shared_ptr<facebook::react::InstanceHandle const> const&)
Shadow bytes around the buggy address:
  0x00016cea4a80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00016cea4b00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00016cea4b80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00016cea4c00: 00 00 00 00 00 00 00 00 f1 f1 f1 f1 f8 f8 f8 f8
  0x00016cea4c80: f8 f8 f2 f2 f2 f2 f8 f8 f2 f2 00 00 f2 f2 f8 f8
=>0x00016cea4d00: f2 f2 f8 f8 f2 f2 00 00 f2 f2[f8]f8 f2 f2 00 00
  0x00016cea4d80: f2 f2 f8 f8 f2 f2 f8 f8 f2 f2 f8 f8 f8 f2 f2 f2
  0x00016cea4e00: f2 f2 f8 f8 f2 f2 f8 f8 f8 f8 f8 f8 f8 f8 f8 f8
  0x00016cea4e80: f8 f8 f8 f8 f8 f8 f8 f8 f8 f2 f2 f2 f2 f2 f2 f2
  0x00016cea4f00: f2 f2 f8 f8 f3 f3 f3 f3 00 00 00 00 00 00 00 00
  0x00016cea4f80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==41992==ABORTING

```

Reviewed By: rshest

Differential Revision: D51183328

fbshipit-source-id: 5aff5b5eecb9d78f9b7438fbdda2c01625c9a4d9
2023-11-09 22:14:57 -08:00
Moti Zilberman d6e0bc714a Enable lint/sort-imports everywhere (#41334)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41334

TSIA.

Changelog: [Internal]

Reviewed By: robhogan

Differential Revision: D51025812

fbshipit-source-id: e10d437be775a6b80946483aa96460f34927f870
2023-11-06 12:59:38 -08:00
Sunbreak af7bf9371c Fix typo of JSI module Cpp codegen (#39604)
Summary:
Fix code generatetion comment from `GenerateModuleH.js` to `GenerateModuleCpp.js`

## Changelog:

[GENERAL] [FIXED] - Fix typo of JSI module Cpp codegen

Pull Request resolved: https://github.com/facebook/react-native/pull/39604

Test Plan: None

Reviewed By: christophpurrer

Differential Revision: D49558245

Pulled By: cortinico

fbshipit-source-id: 28b6a6f4da0f5f973717f785fe21db86179f1996
2023-09-25 12:30:34 -07:00
Ruslan Shestopalyuk 0c292f3934 Fix bad formatting of generated C++ code (#39212)
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
2023-08-30 10:40:47 -07:00
Roy Berger f396067cca Add module name constant to class for downstream use (#38295)
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
2023-07-11 13:03:17 -07:00
Nicola Corti 3a246ed024 Remove CallInvoker parameter from toJs method in Codegen (#37832)
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
2023-06-12 12:46:00 -07:00
Christoph Purrer f7dcc65a3f Remove unused jsInvoker from Cxx TM enums (#37454)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37454

Raised here: https://github.com/reactwg/react-native-releases/discussions/54#discussioncomment-5914928

Changelog: [Internal]

Reviewed By: rshest

Differential Revision: D45918922

fbshipit-source-id: 931d2017c37e7327ba472c36e3ac0b29b74d093d
2023-05-17 08:33:36 -07:00
Pieter De Baets 0a8164d993 Fix off-by-one error in cxx codegen (#36574)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36574

We would previously generate the following codegen for optional args

```
return static_cast<NativeAudioModuleCxxSpecJSI *>(&turboModule)->playAudio(
    rt,
    args[0].asString(rt),
    args[1].isNull() || args[1].isUndefined() ? std::nullopt : std::make_optional(args[1].asString(rt)),
    args[2].isNull() || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asString(rt)),
    args[3].asNumber(),
    count < 4 || args[4].isNull() || args[4].isUndefined() ? std::nullopt : std::make_optional(args[4].asObject(rt)),
    count < 5 || args[5].isNull() || args[5].isUndefined() ? std::nullopt : std::make_optional(args[5].asObject(rt)),
    count < 6 || args[6].isNull() || args[6].isUndefined() ? std::nullopt : std::make_optional(args[6].asBool())
);
```

However, the counts checked are off-by-one, causing us to incorrectly process args.

Changelog: [General][Fixed] Issue with TurboModule C++ codegen with optional args

Differential Revision: D44299193

fbshipit-source-id: f00b9f5e09c2f524f9393137346c256d8b6b2979
2023-03-22 16:57:40 -07:00
Ruslan Shestopalyuk 96fb708d3e Make enums to work as part of data structures for C++ TurboModules codegen (#36155)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36155

[Changelog][Internal]

The PR  https://github.com/facebook/react-native/pull/36030 (diff D42884147 (https://github.com/facebook/react-native/commit/ceb1d0dea694739f357d86296b94f5834e5ee7f7)) added support for enum types in JS to C++ bridging in C++ TurboModules.

This only worked for enums as argument types for exposed methods, but not for the cases when enums are members of complex data structures that are also exposed through a codegen.

This diff fixes this problem, so that codegen now correctly works both with enum types as method arguments, but also as data structure members.

Some part of the change is the same as D42008724 (https://github.com/facebook/react-native/commit/963e45afd1c69771d1d26df8282774c948f762e3), but there are also some changes related to the types, that were required.

Reviewed By: christophpurrer

Differential Revision: D43292254

fbshipit-source-id: b2d6cf4a2d4d233b8cc403ecd02b5be16d5d91a7
2023-02-15 06:03:12 -08:00
Vitali Zaidman ceb1d0dea6 Generate enum types that would be allowed to be used as well as string/number in c++ turbo modules generators (#36030)
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
2023-02-13 15:09:44 -08:00
Vitali Zaidman 209d019055 Added an e2e test fixture for Enums and .H+.C TM e2e snapshot tests
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
2023-02-03 03:03:41 -08:00
Vitali Zaidman 97e707d897 simple support to the Partial<T> annotation (#35961)
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
2023-01-26 12:30:38 -08:00
MaeIg 3f2691cf84 Extract the parseFile function in the typescript and flow parsers (#35318)
Summary:
This PR aims to extract  the parseFile function in the typescript and flow parsers.  This is to solve the problem described [here](https://github.com/facebook/react-native/pull/35158#issuecomment-1298330753) and help with the work done in https://github.com/facebook/react-native/issues/34872.

## Changelog

<!-- Help reviewers and the release process by writing your own changelog entry. For an example, see:
https://reactnative.dev/contributing/changelogs-in-pull-requests
-->
[Internal] [Changed] - Extract the parseFile function in the typescript and flow parsers

Pull Request resolved: https://github.com/facebook/react-native/pull/35318

Test Plan:
yarn flow:
<img width="496" alt="image" src="https://user-images.githubusercontent.com/40902940/206518024-83084c3d-ab0d-4a04-810a-d40270add4b0.png">

yarn lint:
<img width="495" alt="image" src="https://user-images.githubusercontent.com/40902940/206518076-9e07eafe-db61-4c6e-8aaa-f92f190cf4f3.png">

yarn test:
<img width="389" alt="image" src="https://user-images.githubusercontent.com/40902940/206518118-5633b28c-b79b-4421-80f7-de1e03fb8ff2.png">

Reviewed By: cortinico

Differential Revision: D41248581

Pulled By: cipolleschi

fbshipit-source-id: f5b878a28a7de612fcdd1528f064b44f668503af
2022-12-13 09:00:46 -08:00
Gabriel Donadel Dall'Agnol 376ffac759 chore: Export codegen parseFile function (#35000)
Summary:
This PR export the content of the `parseFile` into a parseFile function accepting a callback to buildSchema properly in `parsers/utils.js` as requested on https://github.com/facebook/react-native/issues/34872.

## Changelog

[Internal] [Changed] - Export ` parseFile` in to a `parseFile` function in `parsers/utils.js`

Pull Request resolved: https://github.com/facebook/react-native/pull/35000

Test Plan:
Run `yarn jest react-native-codegen` and ensure CI is green

![image](https://user-images.githubusercontent.com/11707729/196051689-1b61838c-477c-4be5-8df0-9f5969fcf90d.png)

Reviewed By: cortinico

Differential Revision: D40424857

Pulled By: cipolleschi

fbshipit-source-id: a700033d674b8be8e1af942dedf73155ea3ca025
2022-10-19 01:38:28 -07:00
Rujin Cao b2ac528156 @emails -> @oncall (remaining ones)
Differential Revision: D39536169

fbshipit-source-id: 6c8d6787328eefecd23f3498b14a6d9ff750a670
2022-09-15 15:54:10 -07:00
Erich Graham 45e2941367 Remove folly import in GenerateModuleObjCpp
Summary:
Changelog:

[iOS][Changed]
Replaced folly::Optional with std::optional from C++17 in Objc module generator.

Reviewed By: philIip

Differential Revision: D32367103

fbshipit-source-id: f0d254c4add7d6d2e0bdbceb09a852b4a01ea8c7
2022-03-22 17:10:18 -07:00
Nicola Corti 450967938a Do not include Facebook license on users codegen'd code (#32840)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/32840

Closes #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
2022-01-19 08:07:35 -08:00
Andres Suarez 8bd3edec88 Update copyright headers from Facebook to Meta
Reviewed By: aaronabramov

Differential Revision: D33367752

fbshipit-source-id: 4ce94d184485e5ee0a62cf67ad2d3ba16e285c8f
2021-12-30 15:11:21 -08:00
Erich Graham fa4045e4dd Add ios_assume_nonnull flag to react native codegen library (#31543)
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
2021-05-20 10:07:37 -07:00
Ramanpreet Nara fc0b3faf96 Fix ObjC structs with id properties
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
2021-01-13 19:19:30 -08:00
Samuel Susla 0c5d59cffa Fix codegen boolean return value
Summary:
Changelog: [internal]

Codegen was generating code with return value number instead of boolean.

Reviewed By: RSNara

Differential Revision: D25863062

fbshipit-source-id: 780f88dd2d83e303b03d1ed9cc837ac6733f1702
2021-01-10 09:54:25 -08:00
Ramanpreet Nara 9215980471 Remove moduleSpecName
Summary:
All our codegen JavaScript now simply uses libraryName instead of moduleSpecName. In our buck infra, we assign native_module_spec_name to libraryName.

Changelog: [Internal]

Reviewed By: fkgozali

Differential Revision: D25842696

fbshipit-source-id: efd3af402585f9ad4ff3b593179147eea91cc331
2021-01-07 19:39:56 -08:00
Ramanpreet Nara bc0c5c98bb Move react-native-codegen/e2e/__tests__/modules/BUCK
Reviewed By: PeteTheHeat

Differential Revision: D25675408

fbshipit-source-id: 97f8070611f7f7707af9bd7dd9c9a59e8ad96125
2020-12-22 09:06:31 -08:00
Ramanpreet Nara c4f23354fd Update Module Generators to follow new NativeModuleSchema
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
2020-10-15 22:53:56 -07:00
Héctor Ramos 4eb8bd5084 trivial: Remove whitespace in generated output
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
2020-10-06 01:44:20 -07:00
Ramanpreet Nara 6d6e04619f Fix ObjC++ structs and method mapping
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
2020-09-29 14:39:41 -07:00
Ramanpreet Nara 97d3e85c29 Fix ObjC++ module generator output
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
2020-09-29 14:39:41 -07:00
Ramanpreet Nara 1ac1255d63 E2E snapshot test ObjC++ generator
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
2020-09-29 14:39:40 -07:00