Files
react-native/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js
T
Héctor RamosandFacebook GitHub Bot 7e7706cb7d Codegen: Generate ObjC structs for type aliases
Summary:
**Motivation:**

Match the old codegen's behavior when generating structs for type alias derived objects.

**Problem description:**

Take, for example, the following spec:

```
export type MyTypeAlias = { /* ... */ }
export interface Spec extends TurboModule {
  // ...
  +myMethod: (paramName: MyTypeAlias) => void;
  // ...
}
```

The codegen needs to generate a struct to expose the properties of the type alias object. The codegen was producing the following output:

```
- (void)myMethod:(JS::MyModule::SpecMyMethodParamName &)paramName;
```

...which does not match the output from the original codegen:

```
- (void)myMethod:(JS::MyModule::MyTypeAlias &)paramName;
```

The original codegen generates a struct using the type alias name, while the new codegen was generating a struct that uses a combination of the property and parameter names.

Now that type alias names are exposed in the schema, the new codegen can match the original codegen's behavior.

**De-duplication of structs:**

Prior to these changes, type aliases were expanded into regular object types. This meant that any spec that used a type alias more than once would lead to redundant structs getting created. With these changes, we only generate the one struct per type alias, matching the old codegen.

**Expansion of type aliases:**

A new type was introduced in D22200700 (https://github.com/facebook/react-native/commit/e261f022fe6a7653b79330f878fed143725f5324), TypeAliasTypeAnnotation:

```
export type TypeAliasTypeAnnotation = $ReadOnly<{|
  type: 'TypeAliasTypeAnnotation',
  name: string,
|}>;
```

This type may now appear in several locations where a `{| type: 'ObjectTypeAnnotation', properties: [] |}` otherwise would have been used. A `getTypeAliasTypeAnnotation` function is introduced which, given an alias name and an array of aliases provided by the module, will produce the actual object type annotation for the given property parameter.

Changelog: [Internal]

Reviewed By: RSNara

Differential Revision: D22244323

fbshipit-source-id: 125fbf0d6d887bd05a99bf8b81b30bdda4f1682b
2020-07-01 23:39:44 -07:00

172 lines
5.3 KiB
JavaScript

/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
import type {SchemaType} from '../../CodegenSchema';
const {getTypeAliasTypeAnnotation} = require('./ObjCppUtils/Utils');
type FilesOutput = Map<string, string>;
const propertyHeaderTemplate =
'static jsi::Value __hostFunction_Native::_MODULE_NAME_::CxxSpecJSI_::_PROPERTY_NAME_::(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) {';
const propertyCastTemplate =
'static_cast<Native::_MODULE_NAME_::CxxSpecJSI *>(&turboModule)->::_PROPERTY_NAME_::(rt::_ARGS_::);';
const nonvoidPropertyTemplate = `
${propertyHeaderTemplate}
return ${propertyCastTemplate}
}`.trim();
const voidPropertyTemplate = `
${propertyHeaderTemplate}
${propertyCastTemplate}
return jsi::Value::undefined();
}`;
const proprertyDefTemplate =
' methodMap_["::_PROPERTY_NAME_::"] = MethodMetadata {::_ARGS_COUNT_::, __hostFunction_Native::_MODULE_NAME_::CxxSpecJSI_::_PROPERTY_NAME_::};';
const moduleTemplate = `
::_MODULE_PROPERTIES_::
Native::_MODULE_NAME_::CxxSpecJSI::Native::_MODULE_NAME_::CxxSpecJSI(std::shared_ptr<CallInvoker> jsInvoker)
: TurboModule("::_MODULE_NAME_::", jsInvoker) {
::_PROPERTIES_MAP_::
}`.trim();
const template = `
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <react/modules/::_LIBRARY_NAME_::/NativeModules.h>
namespace facebook {
namespace react {
::_MODULES_::
} // namespace react
} // namespace facebook
`;
function traverseArg(arg, index, aliases): string {
function wrap(suffix) {
return `args[${index}]${suffix}`;
}
const {typeAnnotation} = arg;
const realTypeAnnotation =
typeAnnotation.type === 'TypeAliasTypeAnnotation'
? getTypeAliasTypeAnnotation(typeAnnotation.name, aliases)
: typeAnnotation;
switch (realTypeAnnotation.type) {
case 'ReservedFunctionValueTypeAnnotation':
switch (realTypeAnnotation.name) {
case 'RootTag':
return wrap('.getNumber()');
default:
(realTypeAnnotation.name: empty);
throw new Error(
`Unknown prop type for "${arg.name}, found: ${realTypeAnnotation.name}"`,
);
}
case 'StringTypeAnnotation':
return wrap('.getString(rt)');
case 'BooleanTypeAnnotation':
return wrap('.getBool()');
case 'NumberTypeAnnotation':
case 'FloatTypeAnnotation':
case 'Int32TypeAnnotation':
return wrap('.getNumber()');
case 'ArrayTypeAnnotation':
return wrap('.getObject(rt).getArray(rt)');
case 'FunctionTypeAnnotation':
return `std::move(${wrap('.getObject(rt).getFunction(rt)')})`;
case 'GenericObjectTypeAnnotation':
case 'ObjectTypeAnnotation':
return wrap('.getObject(rt)');
case 'AnyTypeAnnotation':
throw new Error(`Any type is not allowed in params for "${arg.name}"`);
default:
// TODO (T65847278): Figure out why this does not work.
// (type: empty);
throw new Error(
`Unknown prop type for "${arg.name}, found: ${realTypeAnnotation.type}"`,
);
}
}
function traverseProperty(property, aliases): string {
const propertyTemplate =
property.typeAnnotation.returnTypeAnnotation.type === 'VoidTypeAnnotation'
? voidPropertyTemplate
: nonvoidPropertyTemplate;
const traversedArgs = property.typeAnnotation.params
.map((p, i) => traverseArg(p, i, aliases))
.join(', ');
return propertyTemplate
.replace(/::_PROPERTY_NAME_::/g, property.name)
.replace(/::_ARGS_::/g, traversedArgs === '' ? '' : ', ' + traversedArgs);
}
module.exports = {
generate(
libraryName: string,
schema: SchemaType,
moduleSpecName: string,
): FilesOutput {
const nativeModules = Object.keys(schema.modules)
.map(moduleName => {
const modules = schema.modules[moduleName].nativeModules;
if (modules == null) {
return null;
}
return modules;
})
.filter(Boolean)
.reduce((acc, modules) => Object.assign(acc, modules), {});
const modules = Object.keys(nativeModules)
.map(name => {
const {aliases, properties} = nativeModules[name];
const traversedProperties = properties
.map(property => traverseProperty(property, aliases))
.join('\n');
return moduleTemplate
.replace(/::_MODULE_PROPERTIES_::/g, traversedProperties)
.replace(
'::_PROPERTIES_MAP_::',
properties
.map(({name: propertyName, typeAnnotation: {params}}) =>
proprertyDefTemplate
.replace(/::_PROPERTY_NAME_::/g, propertyName)
.replace(/::_ARGS_COUNT_::/g, params.length.toString()),
)
.join('\n'),
)
.replace(/::_MODULE_NAME_::/g, name);
})
.join('\n');
const fileName = 'NativeModules.cpp';
const replacedTemplate = template
.replace(/::_MODULES_::/g, modules)
.replace(/::_LIBRARY_NAME_::/g, libraryName);
return new Map([[fileName, replacedTemplate]]);
},
};