Add support for Unions in react-native-codegen & Compat Checker (#54489)

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

Adding support for Unions in react-native-codegen & Compat Checker so that they can allow non-homogenous types and un-special casing `StringLiteralUnionTypeAnnotation`.

Changelog: [Internal]

**NOTE:** In case this needs to be reverted for any breakage to OTA Compat Checker v2, consider disabling it with D88289605 instead of reverting this change.

Reviewed By: RSNara

Differential Revision: D86501597

fbshipit-source-id: 6ea0d42c27f8f6b40fa607e7b671e599f25a94bc
This commit is contained in:
Arushi Kesarwani authored and meta-codesync[bot] committed 2025-12-04 17:25:47 -08:00
1 parent 1a28d9e238
commit 95cc1e7675
52 files changed
+3587 -1854

No files matched your search

+4 -13
View File
@@ -318,10 +318,8 @@ export interface StringLiteralTypeAnnotation {
readonly value: string;
}
export interface StringLiteralUnionTypeAnnotation {
readonly type: 'StringLiteralUnionTypeAnnotation';
readonly types: StringLiteralTypeAnnotation[];
}
export type StringLiteralUnionTypeAnnotation =
UnionTypeAnnotation<StringLiteralTypeAnnotation>;
export interface NativeModuleNumberTypeAnnotation {
readonly type: 'NumberTypeAnnotation';
@@ -383,11 +381,6 @@ export interface NativeModulePromiseTypeAnnotation {
readonly elementType: Nullable<NativeModuleBaseTypeAnnotation> | VoidTypeAnnotation;
}
export type UnionTypeAnnotationMemberType =
| 'NumberTypeAnnotation'
| 'ObjectTypeAnnotation'
| 'StringTypeAnnotation';
export type NativeModuleUnionTypeAnnotationMemberType =
| NativeModuleObjectTypeAnnotation
| StringLiteralTypeAnnotation
@@ -397,10 +390,8 @@ export type NativeModuleUnionTypeAnnotationMemberType =
| StringTypeAnnotation
| NumberTypeAnnotation;
export interface NativeModuleUnionTypeAnnotation {
readonly type: 'UnionTypeAnnotation';
readonly memberType: UnionTypeAnnotationMemberType;
}
export type NativeModuleUnionTypeAnnotation =
UnionTypeAnnotation<NativeModuleUnionTypeAnnotationMemberType>;
export interface NativeModuleMixedTypeAnnotation {
readonly type: 'MixedTypeAnnotation';
+5 -13
View File
@@ -61,10 +61,8 @@ export type BooleanLiteralTypeAnnotation = $ReadOnly<{
value: boolean,
}>;
export type StringLiteralUnionTypeAnnotation = $ReadOnly<{
type: 'StringLiteralUnionTypeAnnotation',
types: $ReadOnlyArray<StringLiteralTypeAnnotation>,
}>;
export type StringLiteralUnionTypeAnnotation =
UnionTypeAnnotation<StringLiteralTypeAnnotation>;
export type VoidTypeAnnotation = $ReadOnly<{
type: 'VoidTypeAnnotation',
@@ -372,11 +370,6 @@ export type NativeModulePromiseTypeAnnotation = $ReadOnly<{
elementType: VoidTypeAnnotation | Nullable<NativeModuleBaseTypeAnnotation>,
}>;
export type UnionTypeAnnotationMemberType =
| 'NumberTypeAnnotation'
| 'ObjectTypeAnnotation'
| 'StringTypeAnnotation';
export type NativeModuleUnionTypeAnnotationMemberType =
| NativeModuleObjectTypeAnnotation
| StringLiteralTypeAnnotation
@@ -386,10 +379,8 @@ export type NativeModuleUnionTypeAnnotationMemberType =
| StringTypeAnnotation
| NumberTypeAnnotation;
export type NativeModuleUnionTypeAnnotation = $ReadOnly<{
type: 'UnionTypeAnnotation',
memberType: UnionTypeAnnotationMemberType,
}>;
export type NativeModuleUnionTypeAnnotation =
UnionTypeAnnotation<NativeModuleUnionTypeAnnotationMemberType>;
export type NativeModuleMixedTypeAnnotation = $ReadOnly<{
type: 'MixedTypeAnnotation',
@@ -473,6 +464,7 @@ export type CompleteTypeAnnotation =
| UnsafeAnyTypeAnnotation
| ArrayTypeAnnotation<CompleteTypeAnnotation>
| ObjectTypeAnnotation<CompleteTypeAnnotation>
| NativeModuleUnionTypeAnnotationMemberType
// Components
| CommandTypeAnnotation
| CompleteReservedTypeAnnotation;
+58
View File
@@ -10,6 +10,8 @@
'use strict';
import type {NativeModuleUnionTypeAnnotation} from '../CodegenSchema';
function capitalize(string: string): string {
return string.charAt(0).toUpperCase() + string.slice(1);
}
@@ -44,10 +46,66 @@ function getEnumName(moduleName: string, origEnumName: string): string {
return `${moduleName}${uppercasedPropName}`;
}
type ValidUnionType = 'boolean' | 'number' | 'object' | 'string';
const NumberTypes = ['NumberTypeAnnotation', 'NumberLiteralTypeAnnotation'];
const StringTypes = ['StringTypeAnnotation', 'StringLiteralTypeAnnotation'];
const ObjectTypes = ['ObjectTypeAnnotation'];
const BooleanTypes = ['BooleanTypeAnnotation', 'BooleanLiteralTypeAnnotation'];
const ValidUnionTypes = [
...NumberTypes,
...ObjectTypes,
...StringTypes,
...BooleanTypes,
];
class HeterogeneousUnionError extends Error {
constructor() {
super(`Non-homogenous union member types`);
}
}
function parseValidUnionType(
annotation: NativeModuleUnionTypeAnnotation,
): ValidUnionType {
const isUnionOfType = (types: $ReadOnlyArray<string>): boolean => {
return annotation.types.every(memberTypeAnnotation =>
types.includes(memberTypeAnnotation.type),
);
};
if (isUnionOfType(BooleanTypes)) {
return 'boolean';
}
if (isUnionOfType(NumberTypes)) {
return 'number';
}
if (isUnionOfType(ObjectTypes)) {
return 'object';
}
if (isUnionOfType(StringTypes)) {
return 'string';
}
const invalidTypes = annotation.types.filter(member => {
return !ValidUnionTypes.includes(member.type);
});
// Check if union members are all supported but not homogeneous
// (e.g., mix of number and boolean)
if (invalidTypes.length === 0) {
throw new HeterogeneousUnionError();
} else {
throw new Error(
`Unsupported union member types: ${invalidTypes.join(', ')}"`,
);
}
}
module.exports = {
capitalize,
indent,
parseValidUnionType,
toPascalCase,
toSafeCppString,
getEnumName,
HeterogeneousUnionError,
};
@@ -15,7 +15,7 @@ import type {
PropTypeAnnotation,
} from '../../CodegenSchema';
const {getEnumName, toSafeCppString} = require('../Utils');
const {getEnumName, parseValidUnionType, toSafeCppString} = require('../Utils');
function toIntEnumValueName(propName: string, value: number): string {
return `${toSafeCppString(propName)}${value}`;
@@ -61,7 +61,40 @@ function getCppArrayTypeForAnnotation(
case 'Int32TypeAnnotation':
case 'MixedTypeAnnotation':
return `std::vector<${getCppTypeForAnnotation(typeElement.type)}>`;
case 'StringLiteralUnionTypeAnnotation':
case 'UnionTypeAnnotation':
const validUnionType = parseValidUnionType(typeElement);
switch (validUnionType) {
case 'boolean':
return `std::vector<${getCppTypeForAnnotation('BooleanTypeAnnotation')}>`;
case 'number':
// Have type-upgraded Number to Double in this case to match the Int32TypeAnnotation, FloatTypeAnnotation & DoubleTypeAnnotation
return `std::vector<${getCppTypeForAnnotation('DoubleTypeAnnotation')}>`;
case 'object':
if (!structParts) {
throw new Error(
`Trying to generate the event emitter for an Array of ${typeElement.type} without informations to generate the generic type`,
);
}
return `std::vector<${generateEventStructName(structParts)}>`;
case 'string':
if (
typeElement.types.every(
({type}) => type === 'StringLiteralTypeAnnotation',
)
) {
if (!structParts) {
throw new Error(
`Trying to generate the event emitter for an Array of ${typeElement.type} without informations to generate the generic type`,
);
}
return `std::vector<${generateEventStructName(structParts)}>`;
}
// Unions of strings and string literals are treated as just strings
return `std::vector<${getCppTypeForAnnotation('StringTypeAnnotation')}>`;
default:
(validUnionType: empty);
throw new Error(`Unsupported union member type`);
}
case 'ObjectTypeAnnotation':
if (!structParts) {
throw new Error(
@@ -19,6 +19,7 @@ import type {
} from '../../CodegenSchema';
const {indent} = require('../Utils');
const {parseValidUnionType} = require('../Utils');
const {IncludeTemplate, generateEventStructName} = require('./CppHelpers');
// File path -> contents
@@ -207,7 +208,11 @@ function handleArrayElementType(
loopLocalVariable,
val => `jsi::valueFromDynamic(runtime, ${val})`,
);
case 'StringLiteralUnionTypeAnnotation':
case 'UnionTypeAnnotation':
const validUnionType = parseValidUnionType(elementType);
if (validUnionType !== 'string') {
throw new Error('Invalid since it is a union of non strings');
}
return setValueAtIndex(
propertyName,
indexVariable,
@@ -320,7 +325,11 @@ function generateSetters(
usingEvent,
prop => `jsi::valueFromDynamic(runtime, ${prop})`,
);
case 'StringLiteralUnionTypeAnnotation':
case 'UnionTypeAnnotation':
const validUnionType = parseValidUnionType(typeAnnotation);
if (validUnionType !== 'string') {
throw new Error('Invalid since it is a union of non strings');
}
return generateSetter(
parentPropertyName,
eventProperty.name,
@@ -18,7 +18,7 @@ import type {
SchemaType,
} from '../../CodegenSchema';
const {indent, toSafeCppString} = require('../Utils');
const {indent, parseValidUnionType, toSafeCppString} = require('../Utils');
const {
generateEventStructName,
getCppArrayTypeForAnnotation,
@@ -118,17 +118,21 @@ function getNativeTypeFromAnnotation(
eventProperty: NamedShape<EventTypeAnnotation>,
nameParts: $ReadOnlyArray<string>,
): string {
const {type} = eventProperty.typeAnnotation;
switch (type) {
const {typeAnnotation} = eventProperty;
switch (typeAnnotation.type) {
case 'BooleanTypeAnnotation':
case 'StringTypeAnnotation':
case 'Int32TypeAnnotation':
case 'DoubleTypeAnnotation':
case 'FloatTypeAnnotation':
case 'MixedTypeAnnotation':
return getCppTypeForAnnotation(type);
case 'StringLiteralUnionTypeAnnotation':
return getCppTypeForAnnotation(typeAnnotation.type);
case 'UnionTypeAnnotation':
const validUnionType = parseValidUnionType(typeAnnotation);
if (validUnionType !== 'string') {
throw new Error('Invalid since it is a union of non strings');
}
return generateEventStructName([...nameParts, eventProperty.name]);
case 'ObjectTypeAnnotation':
return generateEventStructName([...nameParts, eventProperty.name]);
case 'ArrayTypeAnnotation':
@@ -143,8 +147,10 @@ function getNativeTypeFromAnnotation(
eventProperty.name,
]);
default:
(type: empty);
throw new Error(`Received invalid event property type ${type}`);
(typeAnnotation.type: empty);
throw new Error(
`Received invalid event property type ${typeAnnotation.type}`,
);
}
}
function generateEnum(
@@ -188,7 +194,11 @@ function handleGenerateStructForArray(
nameParts.concat([name]),
nullthrows(elementType.properties),
);
} else if (elementType.type === 'StringLiteralUnionTypeAnnotation') {
} else if (elementType.type === 'UnionTypeAnnotation') {
const validUnionType = parseValidUnionType(elementType);
if (validUnionType !== 'string') {
throw new Error('Invalid since it is a union of non strings');
}
generateEnum(
structs,
elementType.types.map(literal => literal.value),
@@ -251,7 +261,11 @@ function generateStruct(
nullthrows(typeAnnotation.properties),
);
return;
case 'StringLiteralUnionTypeAnnotation':
case 'UnionTypeAnnotation':
const validUnionType = parseValidUnionType(typeAnnotation);
if (validUnionType !== 'string') {
throw new Error('Invalid since it is a union of non strings');
}
generateEnum(
structs,
typeAnnotation.types.map(literal => literal.value),
@@ -1273,7 +1273,7 @@ const EVENT_PROPS: SchemaType = {
typeAnnotation: {
type: 'ArrayTypeAnnotation',
elementType: {
type: 'StringLiteralUnionTypeAnnotation',
type: 'UnionTypeAnnotation',
types: [
{
type: 'StringLiteralTypeAnnotation',
@@ -1383,7 +1383,7 @@ const EVENT_PROPS: SchemaType = {
name: 'orientation',
optional: false,
typeAnnotation: {
type: 'StringLiteralUnionTypeAnnotation',
type: 'UnionTypeAnnotation',
types: [
{
type: 'StringLiteralTypeAnnotation',
@@ -29,7 +29,12 @@ import type {AliasResolver} from './Utils';
const {unwrapNullable} = require('../../parsers/parsers-commons');
const {wrapOptional} = require('../TypeUtils/Cxx');
const {getEnumName, toPascalCase, toSafeCppString} = require('../Utils');
const {
getEnumName,
parseValidUnionType,
toPascalCase,
toSafeCppString,
} = require('../Utils');
const {
createAliasResolver,
getModules,
@@ -92,8 +97,6 @@ function serializeArg(
return wrap(val => `${val}.asString(rt)`);
case 'StringLiteralTypeAnnotation':
return wrap(val => `${val}.asString(rt)`);
case 'StringLiteralUnionTypeAnnotation':
return wrap(val => `${val}.asString(rt)`);
case 'BooleanTypeAnnotation':
return wrap(val => `${val}.asBool()`);
case 'BooleanLiteralTypeAnnotation':
@@ -126,17 +129,19 @@ function serializeArg(
case 'GenericObjectTypeAnnotation':
return wrap(val => `${val}.asObject(rt)`);
case 'UnionTypeAnnotation':
switch (typeAnnotation.memberType) {
case 'NumberTypeAnnotation':
const validUnionType = parseValidUnionType(realTypeAnnotation);
switch (validUnionType) {
case 'boolean':
return wrap(val => `${val}.asBool()`);
case 'number':
return wrap(val => `${val}.asNumber()`);
case 'ObjectTypeAnnotation':
case 'object':
return wrap(val => `${val}.asObject(rt)`);
case 'StringTypeAnnotation':
case 'string':
return wrap(val => `${val}.asString(rt)`);
default:
throw new Error(
`Unsupported union member type for param "${arg.name}, found: ${realTypeAnnotation.memberType}"`,
);
(validUnionType: empty);
throw new Error(`Unsupported union member type`);
}
case 'ObjectTypeAnnotation':
return wrap(val => `${val}.asObject(rt)`);
@@ -253,8 +258,6 @@ function translatePrimitiveJSTypeToCpp(
return wrapOptional('jsi::String', isRequired);
case 'StringLiteralTypeAnnotation':
return wrapOptional('jsi::String', isRequired);
case 'StringLiteralUnionTypeAnnotation':
return wrapOptional('jsi::String', isRequired);
case 'NumberTypeAnnotation':
return wrapOptional('double', isRequired);
case 'NumberLiteralTypeAnnotation':
@@ -281,15 +284,19 @@ function translatePrimitiveJSTypeToCpp(
case 'GenericObjectTypeAnnotation':
return wrapOptional('jsi::Object', isRequired);
case 'UnionTypeAnnotation':
switch (typeAnnotation.memberType) {
case 'NumberTypeAnnotation':
const validUnionType = parseValidUnionType(realTypeAnnotation);
switch (validUnionType) {
case 'boolean':
return wrapOptional('bool', isRequired);
case 'number':
return wrapOptional('double', isRequired);
case 'ObjectTypeAnnotation':
case 'object':
return wrapOptional('jsi::Object', isRequired);
case 'StringTypeAnnotation':
case 'string':
return wrapOptional('jsi::String', isRequired);
default:
throw new Error(createErrorMessage(realTypeAnnotation.type));
(validUnionType: empty);
throw new Error(`Unsupported union member type`);
}
case 'ObjectTypeAnnotation':
return wrapOptional('jsi::Object', isRequired);
@@ -24,7 +24,7 @@ import type {AliasResolver} from './Utils';
const {unwrapNullable} = require('../../parsers/parsers-commons');
const {wrapOptional} = require('../TypeUtils/Java');
const {toPascalCase} = require('../Utils');
const {parseValidUnionType, toPascalCase} = require('../Utils');
const {createAliasResolver, getModules} = require('./Utils');
type FilesOutput = Map<string, string>;
@@ -127,14 +127,28 @@ function translateEventEmitterTypeToJavaType(
eventEmitter: NativeModuleEventEmitterShape,
imports: Set<string>,
): string {
const type = eventEmitter.typeAnnotation.typeAnnotation.type;
switch (type) {
const typeAnnotation = eventEmitter.typeAnnotation.typeAnnotation;
switch (typeAnnotation.type) {
case 'StringTypeAnnotation':
return 'String';
case 'StringLiteralTypeAnnotation':
return 'String';
case 'StringLiteralUnionTypeAnnotation':
return 'String';
case 'UnionTypeAnnotation':
const validUnionType = parseValidUnionType(typeAnnotation);
switch (validUnionType) {
case 'boolean':
return 'boolean';
case 'number':
return 'double';
case 'object':
imports.add('com.facebook.react.bridge.ReadableMap');
return 'ReadableMap';
case 'string':
return 'String';
default:
(validUnionType: empty);
throw new Error(`Unsupported union member type`);
}
case 'NumberTypeAnnotation':
case 'NumberLiteralTypeAnnotation':
case 'FloatTypeAnnotation':
@@ -161,7 +175,7 @@ function translateEventEmitterTypeToJavaType(
`Unsupported eventType for ${eventEmitter.name}. Found: ${eventEmitter.typeAnnotation.typeAnnotation.type}`,
);
default:
(type: empty);
(typeAnnotation.type: empty);
throw new Error(
`Unsupported eventType for ${eventEmitter.name}. Found: ${eventEmitter.typeAnnotation.typeAnnotation.type}`,
);
@@ -201,8 +215,6 @@ function translateFunctionParamToJavaType(
return wrapOptional('String', isRequired);
case 'StringLiteralTypeAnnotation':
return wrapOptional('String', isRequired);
case 'StringLiteralUnionTypeAnnotation':
return wrapOptional('String', isRequired);
case 'NumberTypeAnnotation':
return wrapOptional('double', isRequired);
case 'NumberLiteralTypeAnnotation':
@@ -227,18 +239,20 @@ function translateFunctionParamToJavaType(
throw new Error(createErrorMessage(realTypeAnnotation.type));
}
case 'UnionTypeAnnotation':
switch (typeAnnotation.memberType) {
case 'NumberTypeAnnotation':
const validUnionType = parseValidUnionType(realTypeAnnotation);
switch (validUnionType) {
case 'boolean':
return wrapOptional('boolean', isRequired);
case 'number':
return wrapOptional('double', isRequired);
case 'ObjectTypeAnnotation':
case 'object':
imports.add('com.facebook.react.bridge.ReadableMap');
return wrapOptional('ReadableMap', isRequired);
case 'StringTypeAnnotation':
case 'string':
return wrapOptional('String', isRequired);
default:
throw new Error(
`Unsupported union member returning value, found: ${realTypeAnnotation.memberType}"`,
);
(validUnionType: empty);
throw new Error(`Unsupported union member type`);
}
case 'ObjectTypeAnnotation':
imports.add('com.facebook.react.bridge.ReadableMap');
@@ -299,8 +313,6 @@ function translateFunctionReturnTypeToJavaType(
return wrapOptional('String', isRequired);
case 'StringLiteralTypeAnnotation':
return wrapOptional('String', isRequired);
case 'StringLiteralUnionTypeAnnotation':
return wrapOptional('String', isRequired);
case 'NumberTypeAnnotation':
return wrapOptional('double', isRequired);
case 'NumberLiteralTypeAnnotation':
@@ -325,18 +337,20 @@ function translateFunctionReturnTypeToJavaType(
throw new Error(createErrorMessage(realTypeAnnotation.type));
}
case 'UnionTypeAnnotation':
switch (realTypeAnnotation.memberType) {
case 'NumberTypeAnnotation':
const validUnionType = parseValidUnionType(realTypeAnnotation);
switch (validUnionType) {
case 'boolean':
return wrapOptional('boolean', isRequired);
case 'number':
return wrapOptional('double', isRequired);
case 'ObjectTypeAnnotation':
case 'object':
imports.add('com.facebook.react.bridge.WritableMap');
return wrapOptional('WritableMap', isRequired);
case 'StringTypeAnnotation':
return wrapOptional('ReadableMap', isRequired);
case 'string':
return wrapOptional('String', isRequired);
default:
throw new Error(
`Unsupported union member returning value, found: ${realTypeAnnotation.memberType}"`,
);
(validUnionType: empty);
throw new Error(`Unsupported union member type`);
}
case 'ObjectTypeAnnotation':
imports.add('com.facebook.react.bridge.WritableMap');
@@ -405,24 +419,24 @@ function getFalsyReturnStatementFromReturnType(
throw new Error(createErrorMessage(realTypeAnnotation.type));
}
case 'UnionTypeAnnotation':
switch (realTypeAnnotation.memberType) {
case 'NumberTypeAnnotation':
const validUnionType = parseValidUnionType(realTypeAnnotation);
switch (validUnionType) {
case 'boolean':
return nullable ? 'return null;' : 'return false;';
case 'number':
return nullable ? 'return null;' : 'return 0;';
case 'ObjectTypeAnnotation':
case 'object':
return 'return null;';
case 'StringTypeAnnotation':
case 'string':
return nullable ? 'return null;' : 'return "";';
default:
throw new Error(
`Unsupported union member returning value, found: ${realTypeAnnotation.memberType}"`,
);
(validUnionType: empty);
throw new Error(`Unsupported union member type`);
}
case 'StringTypeAnnotation':
return nullable ? 'return null;' : 'return "";';
case 'StringLiteralTypeAnnotation':
return nullable ? 'return null;' : 'return "";';
case 'StringLiteralUnionTypeAnnotation':
return nullable ? 'return null;' : 'return "";';
case 'ObjectTypeAnnotation':
return 'return null;';
case 'GenericObjectTypeAnnotation':
@@ -23,6 +23,7 @@ import type {
import type {AliasResolver} from './Utils';
const {unwrapNullable} = require('../../parsers/parsers-commons');
const {parseValidUnionType} = require('../Utils');
const {createAliasResolver, getModules} = require('./Utils');
type FilesOutput = Map<string, string>;
@@ -167,8 +168,6 @@ function translateReturnTypeToKind(
return 'StringKind';
case 'StringLiteralTypeAnnotation':
return 'StringKind';
case 'StringLiteralUnionTypeAnnotation':
return 'StringKind';
case 'BooleanTypeAnnotation':
return 'BooleanKind';
case 'BooleanLiteralTypeAnnotation':
@@ -185,17 +184,19 @@ function translateReturnTypeToKind(
);
}
case 'UnionTypeAnnotation':
switch (typeAnnotation.memberType) {
case 'NumberTypeAnnotation':
const validUnionType = parseValidUnionType(realTypeAnnotation);
switch (validUnionType) {
case 'boolean':
return 'BooleanKind';
case 'number':
return 'NumberKind';
case 'ObjectTypeAnnotation':
case 'object':
return 'ObjectKind';
case 'StringTypeAnnotation':
case 'string':
return 'StringKind';
default:
throw new Error(
`Unsupported union member returning value, found: ${realTypeAnnotation.memberType}"`,
);
(validUnionType: empty);
throw new Error(`Unsupported union member type`);
}
case 'NumberTypeAnnotation':
return 'NumberKind';
@@ -254,8 +255,6 @@ function translateParamTypeToJniType(
return 'Ljava/lang/String;';
case 'StringLiteralTypeAnnotation':
return 'Ljava/lang/String;';
case 'StringLiteralUnionTypeAnnotation':
return 'Ljava/lang/String;';
case 'BooleanTypeAnnotation':
return !isRequired ? 'Ljava/lang/Boolean;' : 'Z';
case 'BooleanLiteralTypeAnnotation':
@@ -272,17 +271,19 @@ function translateParamTypeToJniType(
);
}
case 'UnionTypeAnnotation':
switch (typeAnnotation.memberType) {
case 'NumberTypeAnnotation':
const validUnionType = parseValidUnionType(realTypeAnnotation);
switch (validUnionType) {
case 'boolean':
return !isRequired ? 'Ljava/lang/Boolean;' : 'Z';
case 'number':
return !isRequired ? 'Ljava/lang/Double;' : 'D';
case 'ObjectTypeAnnotation':
case 'object':
return 'Lcom/facebook/react/bridge/ReadableMap;';
case 'StringTypeAnnotation':
case 'string':
return 'Ljava/lang/String;';
default:
throw new Error(
`Unsupported union prop value, found: ${realTypeAnnotation.memberType}"`,
);
(validUnionType: empty);
throw new Error(`Unsupported union member type`);
}
case 'NumberTypeAnnotation':
return !isRequired ? 'Ljava/lang/Double;' : 'D';
@@ -338,8 +339,6 @@ function translateReturnTypeToJniType(
return 'Ljava/lang/String;';
case 'StringLiteralTypeAnnotation':
return 'Ljava/lang/String;';
case 'StringLiteralUnionTypeAnnotation':
return 'Ljava/lang/String;';
case 'BooleanTypeAnnotation':
return nullable ? 'Ljava/lang/Boolean;' : 'Z';
case 'BooleanLiteralTypeAnnotation':
@@ -356,17 +355,19 @@ function translateReturnTypeToJniType(
);
}
case 'UnionTypeAnnotation':
switch (typeAnnotation.memberType) {
case 'NumberTypeAnnotation':
const validUnionType = parseValidUnionType(realTypeAnnotation);
switch (validUnionType) {
case 'boolean':
return nullable ? 'Ljava/lang/Boolean;' : 'Z';
case 'number':
return nullable ? 'Ljava/lang/Double;' : 'D';
case 'ObjectTypeAnnotation':
return 'Lcom/facebook/react/bridge/WritableMap;';
case 'StringTypeAnnotation':
case 'object':
return 'Lcom/facebook/react/bridge/ReadableMap;';
case 'string':
return 'Ljava/lang/String;';
default:
throw new Error(
`Unsupported union member type, found: ${realTypeAnnotation.memberType}"`,
);
(validUnionType: empty);
throw new Error(`Unsupported union member type`);
}
case 'NumberTypeAnnotation':
return nullable ? 'Ljava/lang/Double;' : 'D';
@@ -23,11 +23,11 @@ import type {
NativeModuleNumberTypeAnnotation,
NativeModuleObjectTypeAnnotation,
NativeModuleTypeAliasTypeAnnotation,
NativeModuleUnionTypeAnnotation,
Nullable,
NumberLiteralTypeAnnotation,
ReservedTypeAnnotation,
StringLiteralTypeAnnotation,
StringLiteralUnionTypeAnnotation,
StringTypeAnnotation,
} from '../../../CodegenSchema';
import type {AliasResolver} from '../Utils';
@@ -36,7 +36,11 @@ const {
unwrapNullable,
wrapNullable,
} = require('../../../parsers/parsers-commons');
const {capitalize} = require('../../Utils');
const {
HeterogeneousUnionError,
capitalize,
parseValidUnionType,
} = require('../../Utils');
type StructContext = 'CONSTANTS' | 'REGULAR';
@@ -63,7 +67,7 @@ export type StructProperty = $ReadOnly<{
export type StructTypeAnnotation =
| StringTypeAnnotation
| StringLiteralTypeAnnotation
| StringLiteralUnionTypeAnnotation
| NativeModuleUnionTypeAnnotation
| NativeModuleNumberTypeAnnotation
| NumberLiteralTypeAnnotation
| BooleanLiteralTypeAnnotation
@@ -129,27 +133,38 @@ class StructCollector {
case 'MixedTypeAnnotation':
throw new Error('Mixed types are unsupported in structs');
case 'UnionTypeAnnotation':
switch (typeAnnotation.memberType) {
case 'StringTypeAnnotation':
return wrapNullable(nullable, {
type: 'StringTypeAnnotation',
});
case 'NumberTypeAnnotation':
return wrapNullable(nullable, {
type: 'NumberTypeAnnotation',
});
case 'ObjectTypeAnnotation':
// This isn't smart enough to actually know how to generate the
// options on the native side. So we just treat it as an unknown object type
return wrapNullable(nullable, {
type: 'GenericObjectTypeAnnotation',
});
default:
(typeAnnotation.memberType: empty);
throw new Error(
'Union types are unsupported in structs' +
JSON.stringify(typeAnnotation),
);
try {
const validUnionType = parseValidUnionType(typeAnnotation);
switch (validUnionType) {
case 'boolean':
return wrapNullable(nullable, {
type: 'BooleanTypeAnnotation',
});
case 'number':
return wrapNullable(nullable, {
type: 'NumberTypeAnnotation',
});
case 'object':
// This isn't smart enough to actually know how to generate the
// options on the native side. So we just treat it as an unknown object type
return wrapNullable(nullable, {
type: 'GenericObjectTypeAnnotation',
});
case 'string':
return wrapNullable(nullable, {
type: 'StringTypeAnnotation',
});
default:
(validUnionType: empty);
throw new Error(`Unsupported union member types`);
}
} catch (ex) {
// TODO(T247151345): Implement proper heterogeneous union support.
if (ex instanceof HeterogeneousUnionError) {
return wrapNullable(nullable, typeAnnotation);
}
throw ex;
}
default: {
return wrapNullable(nullable, typeAnnotation);
@@ -96,8 +96,9 @@ function toObjCType(
return 'NSString *';
case 'StringLiteralTypeAnnotation':
return 'NSString *';
case 'StringLiteralUnionTypeAnnotation':
return 'NSString *';
case 'UnionTypeAnnotation':
// TODO(T247151345): Implement proper heterogeneous union support. This is unsafe.
return 'NSObject *';
case 'NumberTypeAnnotation':
return wrapCxxOptional('double', isRequired);
case 'NumberLiteralTypeAnnotation':
@@ -183,7 +184,7 @@ function toObjCValue(
return value;
case 'StringLiteralTypeAnnotation':
return value;
case 'StringLiteralUnionTypeAnnotation':
case 'UnionTypeAnnotation':
return value;
case 'NumberTypeAnnotation':
return wrapPrimitive('double');
@@ -87,8 +87,9 @@ function toObjCType(
return 'NSString *';
case 'StringLiteralTypeAnnotation':
return 'NSString *';
case 'StringLiteralUnionTypeAnnotation':
return 'NSString *';
case 'UnionTypeAnnotation':
// TODO(T247151345): Implement proper heterogeneous union support. This is unsafe.
return 'NSObject *';
case 'NumberTypeAnnotation':
return wrapCxxOptional('double', isRequired);
case 'NumberLiteralTypeAnnotation':
@@ -173,8 +174,10 @@ function toObjCValue(
return RCTBridgingTo('String');
case 'StringLiteralTypeAnnotation':
return RCTBridgingTo('String');
case 'StringLiteralUnionTypeAnnotation':
return RCTBridgingTo('String');
case 'UnionTypeAnnotation':
return !isRequired
? `!RCTNilIfNull(${value}) ? std::optional<NSObject *>{} : std::optional<NSObject *>(${value})`
: value;
case 'NumberTypeAnnotation':
return RCTBridgingTo('Double');
case 'NumberLiteralTypeAnnotation':
@@ -10,20 +10,33 @@
import type {NativeModuleEventEmitterShape} from '../../../CodegenSchema';
const {toPascalCase} = require('../../Utils');
const {parseValidUnionType, toPascalCase} = require('../../Utils');
function getEventEmitterTypeObjCType(
eventEmitter: NativeModuleEventEmitterShape,
): string {
const type = eventEmitter.typeAnnotation.typeAnnotation.type;
const typeAnnotation = eventEmitter.typeAnnotation.typeAnnotation;
switch (type) {
switch (typeAnnotation.type) {
case 'StringTypeAnnotation':
return 'NSString *_Nonnull';
case 'StringLiteralTypeAnnotation':
return 'NSString *_Nonnull';
case 'StringLiteralUnionTypeAnnotation':
return 'NSString *_Nonnull';
case 'UnionTypeAnnotation':
const validUnionType = parseValidUnionType(typeAnnotation);
switch (validUnionType) {
case 'boolean':
return 'BOOL';
case 'number':
return 'NSNumber *_Nonnull';
case 'object':
return 'NSDictionary *';
case 'string':
return 'NSString *_Nonnull';
default:
(validUnionType: empty);
throw new Error(`Unsupported union member type`);
}
case 'NumberTypeAnnotation':
case 'NumberLiteralTypeAnnotation':
return 'NSNumber *_Nonnull';
@@ -45,7 +58,7 @@ function getEventEmitterTypeObjCType(
`Unsupported eventType for ${eventEmitter.name}. Found: ${eventEmitter.typeAnnotation.typeAnnotation.type}`,
);
default:
(type: empty);
(typeAnnotation.type: empty);
throw new Error(
`Unsupported eventType for ${eventEmitter.name}. Found: ${eventEmitter.typeAnnotation.typeAnnotation.type}`,
);
@@ -25,7 +25,7 @@ const {
wrapNullable,
} = require('../../../parsers/parsers-commons');
const {wrapOptional} = require('../../TypeUtils/Objective-C');
const {capitalize} = require('../../Utils');
const {capitalize, parseValidUnionType} = require('../../Utils');
const {getNamespacedStructName} = require('./Utils');
const invariant = require('invariant');
@@ -259,8 +259,9 @@ function getParamObjCType(
return notStruct(wrapOptional('NSString *', !nullable));
case 'StringLiteralTypeAnnotation':
return notStruct(wrapOptional('NSString *', !nullable));
case 'StringLiteralUnionTypeAnnotation':
return notStruct(wrapOptional('NSString *', !nullable));
case 'UnionTypeAnnotation':
// TODO(T247151345): Implement proper heterogeneous union support. This is unsafe.
return notStruct(wrapOptional('NSObject *', !nullable));
case 'NumberTypeAnnotation':
return notStruct(isRequired ? 'double' : 'NSNumber *');
case 'NumberLiteralTypeAnnotation':
@@ -342,10 +343,6 @@ function getReturnObjCType(
// TODO: Can NSString * returns not be _Nullable?
// In the legacy codegen, we don't surround NSSTring * with _Nullable
return wrapOptional('NSString *', isRequired);
case 'StringLiteralUnionTypeAnnotation':
// TODO: Can NSString * returns not be _Nullable?
// In the legacy codegen, we don't surround NSSTring * with _Nullable
return wrapOptional('NSString *', isRequired);
case 'NumberTypeAnnotation':
return wrapOptional('NSNumber *', isRequired);
case 'NumberLiteralTypeAnnotation':
@@ -372,19 +369,21 @@ function getReturnObjCType(
);
}
case 'UnionTypeAnnotation':
switch (typeAnnotation.memberType) {
case 'NumberTypeAnnotation':
const validUnionType = parseValidUnionType(typeAnnotation);
switch (validUnionType) {
case 'boolean':
return wrapOptional('NSNumber *', isRequired);
case 'ObjectTypeAnnotation':
case 'number':
return wrapOptional('NSNumber *', isRequired);
case 'object':
return wrapOptional('NSDictionary *', isRequired);
case 'StringTypeAnnotation':
case 'string':
// TODO: Can NSString * returns not be _Nullable?
// In the legacy codegen, we don't surround NSSTring * with _Nullable
return wrapOptional('NSString *', isRequired);
default:
throw new Error(
`Unsupported union return type for ${methodName}, found: ${typeAnnotation.memberType}"`,
);
(validUnionType: empty);
throw new Error(`Unsupported union member type`);
}
case 'GenericObjectTypeAnnotation':
return wrapOptional('NSDictionary *', isRequired);
@@ -418,8 +417,6 @@ function getReturnJSType(
return 'StringKind';
case 'StringLiteralTypeAnnotation':
return 'StringKind';
case 'StringLiteralUnionTypeAnnotation':
return 'StringKind';
case 'NumberTypeAnnotation':
return 'NumberKind';
case 'NumberLiteralTypeAnnotation':
@@ -448,17 +445,19 @@ function getReturnJSType(
);
}
case 'UnionTypeAnnotation':
switch (typeAnnotation.memberType) {
case 'NumberTypeAnnotation':
const validUnionType = parseValidUnionType(typeAnnotation);
switch (validUnionType) {
case 'boolean':
return 'BooleanKind';
case 'number':
return 'NumberKind';
case 'ObjectTypeAnnotation':
case 'object':
return 'ObjectKind';
case 'StringTypeAnnotation':
case 'string':
return 'StringKind';
default:
throw new Error(
`Unsupported return type for ${methodName}. Found: ${typeAnnotation.type}`,
);
(validUnionType: empty);
throw new Error(`Unsupported union member types`);
}
default:
(typeAnnotation.type: 'MixedTypeAnnotation');
@@ -2353,7 +2353,11 @@ const CXX_ONLY_NATIVE_MODULES: SchemaType = {
optional: false,
typeAnnotation: {
type: 'UnionTypeAnnotation',
memberType: 'NumberTypeAnnotation',
types: [
{
type: 'NumberTypeAnnotation',
},
],
},
},
{
@@ -2361,14 +2365,18 @@ const CXX_ONLY_NATIVE_MODULES: SchemaType = {
optional: false,
typeAnnotation: {
type: 'UnionTypeAnnotation',
memberType: 'StringTypeAnnotation',
types: [
{
type: 'StringTypeAnnotation',
},
],
},
},
{
name: 'y-literal',
optional: false,
typeAnnotation: {
type: 'StringLiteralUnionTypeAnnotation',
type: 'UnionTypeAnnotation',
types: [
{
type: 'StringLiteralTypeAnnotation',
@@ -2386,7 +2394,11 @@ const CXX_ONLY_NATIVE_MODULES: SchemaType = {
optional: false,
typeAnnotation: {
type: 'UnionTypeAnnotation',
memberType: 'ObjectTypeAnnotation',
types: [
{
type: 'ObjectTypeAnnotation',
},
],
},
},
],
@@ -2656,7 +2668,20 @@ const UNION_MODULE: SchemaType = {
type: 'FunctionTypeAnnotation',
returnTypeAnnotation: {
type: 'UnionTypeAnnotation',
memberType: 'ObjectTypeAnnotation',
types: [
{
type: 'ObjectTypeAnnotation',
properties: [
{
name: 'low',
optional: false,
typeAnnotation: {
type: 'StringTypeAnnotation',
},
},
],
},
],
},
params: [
{
@@ -2664,7 +2689,15 @@ const UNION_MODULE: SchemaType = {
optional: false,
typeAnnotation: {
type: 'UnionTypeAnnotation',
memberType: 'NumberTypeAnnotation',
types: [
{
type: 'NumberTypeAnnotation',
},
{
type: 'NumberLiteralTypeAnnotation',
value: 1,
},
],
},
},
{
@@ -2672,7 +2705,15 @@ const UNION_MODULE: SchemaType = {
optional: false,
typeAnnotation: {
type: 'UnionTypeAnnotation',
memberType: 'NumberTypeAnnotation',
types: [
{
type: 'NumberTypeAnnotation',
},
{
type: 'NumberLiteralTypeAnnotation',
value: 2.88,
},
],
},
},
{
@@ -2680,7 +2721,20 @@ const UNION_MODULE: SchemaType = {
optional: false,
typeAnnotation: {
type: 'UnionTypeAnnotation',
memberType: 'ObjectTypeAnnotation',
types: [
{
type: 'ObjectTypeAnnotation',
properties: [
{
name: 'low',
optional: false,
typeAnnotation: {
type: 'StringTypeAnnotation',
},
},
],
},
],
},
},
{
@@ -2688,14 +2742,22 @@ const UNION_MODULE: SchemaType = {
optional: false,
typeAnnotation: {
type: 'UnionTypeAnnotation',
memberType: 'StringTypeAnnotation',
types: [
{
type: 'StringLiteralTypeAnnotation',
value: 'One',
},
{
type: 'StringTypeAnnotation',
},
],
},
},
{
name: 'chooseStringLiteral',
optional: false,
typeAnnotation: {
type: 'StringLiteralUnionTypeAnnotation',
type: 'UnionTypeAnnotation',
types: [
{
type: 'StringLiteralTypeAnnotation',
@@ -678,7 +678,7 @@ public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaMo
@ReactMethod(isBlockingSynchronousMethod = true)
@DoNotStrip
public abstract WritableMap getUnion(double chooseInt, double chooseFloat, ReadableMap chooseObject, String chooseString, String chooseStringLiteral);
public abstract ReadableMap getUnion(double chooseInt, double chooseFloat, ReadableMap chooseObject, String chooseString, String chooseStringLiteral);
}
",
}
@@ -571,7 +571,7 @@ namespace facebook::react {
static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getUnion(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) {
static jmethodID cachedMethodId = nullptr;
return static_cast<JavaTurboModule &>(turboModule).invokeJavaMethod(rt, ObjectKind, \\"getUnion\\", \\"(DDLcom/facebook/react/bridge/ReadableMap;Ljava/lang/String;Ljava/lang/String;)Lcom/facebook/react/bridge/WritableMap;\\", args, count, cachedMethodId);
return static_cast<JavaTurboModule &>(turboModule).invokeJavaMethod(rt, ObjectKind, \\"getUnion\\", \\"(DDLcom/facebook/react/bridge/ReadableMap;Ljava/lang/String;Ljava/lang/String;)Lcom/facebook/react/bridge/ReadableMap;\\", args, count, cachedMethodId);
}
NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams &params)
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -278,7 +278,7 @@ function throwIfArrayElementTypeAnnotationIsUnsupported(
PromiseTypeAnnotation: 'Promise',
// TODO: Added as a work-around for now until TupleTypeAnnotation are fully supported in both flow and TS
// Right now they are partially treated as UnionTypeAnnotation
UnionTypeAnnotation: 'UnionTypeAnnotation',
// UnionTypeAnnotation: 'UnionTypeAnnotation',
};
if (type in TypeMap) {
-22
View File
@@ -10,7 +10,6 @@
'use strict';
import type {UnionTypeAnnotationMemberType} from '../CodegenSchema';
import type {Parser} from './parser';
export type ParserType = 'Flow' | 'TypeScript';
@@ -337,26 +336,6 @@ class UnsupportedEnumDeclarationParserError extends ParserError {
}
}
/**
* Union parsing errors
*/
class UnsupportedUnionTypeAnnotationParserError extends ParserError {
constructor(
nativeModuleName: string,
arrayElementTypeAST: $FlowFixMe,
types: UnionTypeAnnotationMemberType[],
) {
super(
nativeModuleName,
arrayElementTypeAST,
`Union members must be of the same type, but multiple types were found ${types.join(
', ',
)}'.`,
);
}
}
/**
* Module parsing errors
*/
@@ -460,7 +439,6 @@ module.exports = {
UnsupportedFunctionParamTypeAnnotationParserError,
UnsupportedFunctionReturnTypeAnnotationParserError,
UnsupportedEnumDeclarationParserError,
UnsupportedUnionTypeAnnotationParserError,
UnsupportedModuleEventEmitterTypePropertyParserError,
UnsupportedModuleEventEmitterPropertyParserError,
UnsupportedModulePropertyParserError,
@@ -115,7 +115,7 @@ function extractArrayElementType(
};
case 'UnionTypeAnnotation':
return {
type: 'StringLiteralUnionTypeAnnotation',
type: 'UnionTypeAnnotation',
types: typeAnnotation.types.map(option => ({
type: 'StringLiteralTypeAnnotation',
value: parser.getLiteralValue(option),
@@ -401,7 +401,24 @@ exports[`RN Codegen Flow Parser can generate fixture CXX_ONLY_NATIVE_MODULE 1`]
'type': 'FunctionTypeAnnotation',
'returnTypeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'ObjectTypeAnnotation'
'types': [
{
'type': 'ObjectTypeAnnotation',
'properties': []
},
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'low',
'optional': false,
'typeAnnotation': {
'type': 'StringTypeAnnotation'
}
}
]
}
]
},
'params': [
{
@@ -409,7 +426,20 @@ exports[`RN Codegen Flow Parser can generate fixture CXX_ONLY_NATIVE_MODULE 1`]
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'NumberTypeAnnotation'
'types': [
{
'type': 'NumberLiteralTypeAnnotation',
'value': 1
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 2
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 3
}
]
}
},
{
@@ -417,7 +447,20 @@ exports[`RN Codegen Flow Parser can generate fixture CXX_ONLY_NATIVE_MODULE 1`]
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'NumberTypeAnnotation'
'types': [
{
'type': 'NumberLiteralTypeAnnotation',
'value': 1.44
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 2.88
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 5.76
}
]
}
},
{
@@ -425,14 +468,31 @@ exports[`RN Codegen Flow Parser can generate fixture CXX_ONLY_NATIVE_MODULE 1`]
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'ObjectTypeAnnotation'
'types': [
{
'type': 'ObjectTypeAnnotation',
'properties': []
},
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'low',
'optional': false,
'typeAnnotation': {
'type': 'StringTypeAnnotation'
}
}
]
}
]
}
},
{
'name': 'chooseString',
'optional': false,
'typeAnnotation': {
'type': 'StringLiteralUnionTypeAnnotation',
'type': 'UnionTypeAnnotation',
'types': [
{
'type': 'StringLiteralTypeAnnotation',
@@ -1111,7 +1171,18 @@ exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_ARRAY_WI
'returnTypeAnnotation': {
'type': 'ArrayTypeAnnotation',
'elementType': {
'type': 'AnyTypeAnnotation'
'type': 'UnionTypeAnnotation',
'types': [
{
'type': 'StringTypeAnnotation'
},
{
'type': 'NumberTypeAnnotation'
},
{
'type': 'BooleanTypeAnnotation'
}
]
}
},
'params': [
@@ -2686,7 +2757,24 @@ exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_UNION 1`
'type': 'FunctionTypeAnnotation',
'returnTypeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'ObjectTypeAnnotation'
'types': [
{
'type': 'ObjectTypeAnnotation',
'properties': []
},
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'low',
'optional': false,
'typeAnnotation': {
'type': 'StringTypeAnnotation'
}
}
]
}
]
},
'params': [
{
@@ -2694,7 +2782,20 @@ exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_UNION 1`
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'NumberTypeAnnotation'
'types': [
{
'type': 'NumberLiteralTypeAnnotation',
'value': 1
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 2
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 3
}
]
}
},
{
@@ -2702,7 +2803,20 @@ exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_UNION 1`
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'NumberTypeAnnotation'
'types': [
{
'type': 'NumberLiteralTypeAnnotation',
'value': 1.44
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 2.88
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 5.76
}
]
}
},
{
@@ -2710,14 +2824,31 @@ exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_UNION 1`
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'ObjectTypeAnnotation'
'types': [
{
'type': 'ObjectTypeAnnotation',
'properties': []
},
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'low',
'optional': false,
'typeAnnotation': {
'type': 'StringTypeAnnotation'
}
}
]
}
]
}
},
{
'name': 'chooseString',
'optional': false,
'typeAnnotation': {
'type': 'StringLiteralUnionTypeAnnotation',
'type': 'UnionTypeAnnotation',
'types': [
{
'type': 'StringLiteralTypeAnnotation',
@@ -2761,7 +2892,7 @@ exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_UNION_RE
'typeAnnotation': {
'type': 'FunctionTypeAnnotation',
'returnTypeAnnotation': {
'type': 'StringLiteralUnionTypeAnnotation',
'type': 'UnionTypeAnnotation',
'types': [
{
'type': 'StringLiteralTypeAnnotation',
@@ -2789,7 +2920,7 @@ exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_UNION_RE
'name': 'strings',
'optional': false,
'typeAnnotation': {
'type': 'StringLiteralUnionTypeAnnotation',
'type': 'UnionTypeAnnotation',
'types': [
{
'type': 'StringLiteralTypeAnnotation',
@@ -2812,7 +2943,16 @@ exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_UNION_RE
'type': 'FunctionTypeAnnotation',
'returnTypeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'NumberTypeAnnotation'
'types': [
{
'type': 'NumberLiteralTypeAnnotation',
'value': 1
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 2
}
]
},
'params': []
}
@@ -2831,7 +2971,16 @@ exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_UNION_RE
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'NumberTypeAnnotation'
'types': [
{
'type': 'NumberLiteralTypeAnnotation',
'value': 1
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 2
}
]
}
}
]
@@ -2844,7 +2993,34 @@ exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_UNION_RE
'type': 'FunctionTypeAnnotation',
'returnTypeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'ObjectTypeAnnotation'
'types': [
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'a',
'optional': false,
'typeAnnotation': {
'type': 'NumberLiteralTypeAnnotation',
'value': 1
}
}
]
},
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'b',
'optional': false,
'typeAnnotation': {
'type': 'NumberLiteralTypeAnnotation',
'value': 2
}
}
]
}
]
},
'params': []
}
@@ -2863,7 +3039,34 @@ exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_UNION_RE
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'ObjectTypeAnnotation'
'types': [
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'a',
'optional': false,
'typeAnnotation': {
'type': 'NumberLiteralTypeAnnotation',
'value': 1
}
}
]
},
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'b',
'optional': false,
'typeAnnotation': {
'type': 'NumberLiteralTypeAnnotation',
'value': 2
}
}
]
}
]
}
}
]
@@ -3032,7 +3235,32 @@ exports[`RN Codegen Flow Parser can generate fixture PROMISE_WITH_COMMONLY_USED_
'returnTypeAnnotation': {
'type': 'PromiseTypeAnnotation',
'elementType': {
'type': 'VoidTypeAnnotation'
'type': 'GenericObjectTypeAnnotation',
'dictionaryValueType': {
'type': 'UnionTypeAnnotation',
'types': [
{
'type': 'StringLiteralTypeAnnotation',
'value': 'authorized'
},
{
'type': 'StringLiteralTypeAnnotation',
'value': 'denied'
},
{
'type': 'StringLiteralTypeAnnotation',
'value': 'undetermined'
},
{
'type': 'BooleanLiteralTypeAnnotation',
'value': true
},
{
'type': 'BooleanLiteralTypeAnnotation',
'value': false
}
]
}
}
},
'params': []
@@ -3064,7 +3292,7 @@ exports[`RN Codegen Flow Parser can generate fixture PROMISE_WITH_COMMONLY_USED_
'returnTypeAnnotation': {
'type': 'PromiseTypeAnnotation',
'elementType': {
'type': 'StringLiteralUnionTypeAnnotation',
'type': 'UnionTypeAnnotation',
'types': [
{
'type': 'StringLiteralTypeAnnotation',
@@ -245,7 +245,18 @@ function translateTypeAnnotation(
);
}
case 'UnionTypeAnnotation': {
return emitUnion(nullable, hasteModuleName, typeAnnotation, parser);
return emitUnion(
nullable,
hasteModuleName,
typeAnnotation,
types,
aliasMap,
enumMap,
tryParse,
cxxOnly,
translateTypeAnnotation,
parser,
);
}
case 'NumberLiteralTypeAnnotation': {
return emitNumberLiteral(nullable, typeAnnotation.value);
+2 -8
View File
@@ -18,10 +18,10 @@ import type {
NativeModuleEnumMember,
NativeModuleEnumMemberType,
NativeModuleParamTypeAnnotation,
NativeModuleUnionTypeAnnotationMemberType,
Nullable,
PropTypeAnnotation,
SchemaType,
UnionTypeAnnotationMemberType,
} from '../../CodegenSchema';
import type {ParserType} from '../errors';
import type {
@@ -111,7 +111,7 @@ class FlowParser implements Parser {
remapUnionTypeAnnotationMemberNames(
membersTypes: $FlowFixMe[],
): UnionTypeAnnotationMemberType[] {
): NativeModuleUnionTypeAnnotationMemberType[] {
const remapLiteral = (item: $FlowFixMe) => {
return item.type
.replace('NumberLiteralTypeAnnotation', 'NumberTypeAnnotation')
@@ -121,12 +121,6 @@ class FlowParser implements Parser {
return [...new Set(membersTypes.map(remapLiteral))];
}
getStringLiteralUnionTypeAnnotationStringLiterals(
membersTypes: $FlowFixMe[],
): string[] {
return membersTypes.map((item: $FlowFixMe) => item.value);
}
parseFile(filename: string): SchemaType {
const contents = fs.readFileSync(filename, 'utf8');
+2 -10
View File
@@ -18,10 +18,10 @@ import type {
NativeModuleEnumMember,
NativeModuleEnumMemberType,
NativeModuleParamTypeAnnotation,
NativeModuleUnionTypeAnnotationMemberType,
Nullable,
PropTypeAnnotation,
SchemaType,
UnionTypeAnnotationMemberType,
} from '../CodegenSchema';
import type {ParserType} from './errors';
import type {
@@ -146,15 +146,7 @@ export interface Parser {
*/
remapUnionTypeAnnotationMemberNames(
types: $FlowFixMe,
): UnionTypeAnnotationMemberType[];
/**
* Given a union annotation members types, it returns an array of string literals.
* @parameter membersTypes: union annotation members types
* @returns: an array of string literals.
*/
getStringLiteralUnionTypeAnnotationStringLiterals(
types: $FlowFixMe,
): string[];
): NativeModuleUnionTypeAnnotationMemberType[];
/**
* Given the name of a file, it returns a Schema.
* @parameter filename: the name of the file.
+2 -8
View File
@@ -18,10 +18,10 @@ import type {
NativeModuleEnumMember,
NativeModuleEnumMemberType,
NativeModuleParamTypeAnnotation,
NativeModuleUnionTypeAnnotationMemberType,
Nullable,
PropTypeAnnotation,
SchemaType,
UnionTypeAnnotationMemberType,
} from '../CodegenSchema';
import type {ParserType} from './errors';
import type {
@@ -105,13 +105,7 @@ export class MockedParser implements Parser {
remapUnionTypeAnnotationMemberNames(
membersTypes: $FlowFixMe[],
): UnionTypeAnnotationMemberType[] {
return [];
}
getStringLiteralUnionTypeAnnotationStringLiterals(
membersTypes: $FlowFixMe[],
): string[] {
): NativeModuleUnionTypeAnnotationMemberType[] {
return [];
}
@@ -31,12 +31,12 @@ import type {
NativeModuleTypeAliasTypeAnnotation,
NativeModuleTypeAnnotation,
NativeModuleUnionTypeAnnotation,
NativeModuleUnionTypeAnnotationMemberType,
Nullable,
NumberLiteralTypeAnnotation,
ObjectTypeAnnotation,
ReservedTypeAnnotation,
StringLiteralTypeAnnotation,
StringLiteralUnionTypeAnnotation,
StringTypeAnnotation,
VoidTypeAnnotation,
} from '../CodegenSchema';
@@ -52,11 +52,7 @@ const {
throwIfPartialNotAnnotatingTypeParameter,
throwIfPartialWithMoreParameter,
} = require('./error-utils');
const {
ParserError,
UnsupportedTypeAnnotationParserError,
UnsupportedUnionTypeAnnotationParserError,
} = require('./errors');
const {ParserError, UnsupportedTypeAnnotationParserError} = require('./errors');
const {
assertGenericTypeAnnotationHasExactlyOneTypeParameter,
translateFunctionTypeAnnotation,
@@ -431,61 +427,53 @@ function emitUnion(
nullable: boolean,
hasteModuleName: string,
typeAnnotation: $FlowFixMe,
types: TypeDeclarationMap,
aliasMap: {...NativeModuleAliasMap},
enumMap: {...NativeModuleEnumMap},
tryParse: ParserErrorCapturer,
cxxOnly: boolean,
translateTypeAnnotation: $FlowFixMe,
parser: Parser,
): Nullable<
NativeModuleUnionTypeAnnotation | StringLiteralUnionTypeAnnotation,
> {
// Get all the literals by type
// Verify they are all the same
// If string, persist as StringLiteralUnionType
// If number, persist as NumberTypeAnnotation (TODO: Number literal)
): Nullable<NativeModuleUnionTypeAnnotation> {
const unparsedMemberTypes: $ReadOnlyArray<$FlowFixMe> =
(typeAnnotation.types: $ReadOnlyArray<$FlowFixMe>);
const unionTypes = parser.remapUnionTypeAnnotationMemberNames(
typeAnnotation.types,
const memberTypes = unparsedMemberTypes.map(
(memberType: $FlowFixMe): NativeModuleUnionTypeAnnotationMemberType => {
const memberTypeAnnotation = translateTypeAnnotation(
hasteModuleName,
memberType,
types,
aliasMap,
enumMap,
tryParse,
cxxOnly,
parser,
);
switch (memberTypeAnnotation.type) {
case 'StringTypeAnnotation':
case 'NumberTypeAnnotation':
case 'BooleanTypeAnnotation':
case 'NumberLiteralTypeAnnotation':
case 'StringLiteralTypeAnnotation':
case 'BooleanLiteralTypeAnnotation':
case 'ObjectTypeAnnotation':
case 'TypeAliasTypeAnnotation':
return memberTypeAnnotation;
default:
throw new UnsupportedTypeAnnotationParserError(
hasteModuleName,
memberType,
parser.language(),
);
}
},
);
// Only support unionTypes of the same kind
if (unionTypes.length > 1) {
throw new UnsupportedUnionTypeAnnotationParserError(
hasteModuleName,
typeAnnotation,
unionTypes,
);
}
if (unionTypes[0] === 'StringTypeAnnotation') {
// Reprocess as a string literal union
return emitStringLiteralUnion(
nullable,
hasteModuleName,
typeAnnotation,
parser,
);
}
return wrapNullable(nullable, {
type: 'UnionTypeAnnotation',
memberType: unionTypes[0],
});
}
function emitStringLiteralUnion(
nullable: boolean,
hasteModuleName: string,
typeAnnotation: $FlowFixMe,
parser: Parser,
): Nullable<StringLiteralUnionTypeAnnotation> {
const stringLiterals =
parser.getStringLiteralUnionTypeAnnotationStringLiterals(
typeAnnotation.types,
);
return wrapNullable(nullable, {
type: 'StringLiteralUnionTypeAnnotation',
types: stringLiterals.map(stringLiteral => ({
type: 'StringLiteralTypeAnnotation',
value: stringLiteral,
})),
types: memberTypes,
});
}
@@ -675,6 +663,7 @@ function emitCommonTypes(
VoidTypeAnnotation: emitVoid,
StringTypeAnnotation: emitString,
MixedTypeAnnotation: cxxOnly ? emitMixed : emitGenericObject,
UnsafeMixed: cxxOnly ? emitMixed : emitGenericObject,
};
const typeAnnotationName = parser.convertKeywordToTypeAnnotation(
@@ -763,7 +752,7 @@ function emitUnionProp(
name,
optional,
typeAnnotation: {
type: 'StringLiteralUnionTypeAnnotation',
type: 'UnionTypeAnnotation',
types: typeAnnotation.types.map(option => ({
type: 'StringLiteralTypeAnnotation',
value: parser.getLiteralValue(option),
@@ -127,7 +127,7 @@ function extractArrayElementType(
};
case 'TSUnionType':
return {
type: 'StringLiteralUnionTypeAnnotation',
type: 'UnionTypeAnnotation',
types: typeAnnotation.types.map(option => ({
type: 'StringLiteralTypeAnnotation',
value: parser.getLiteralValue(option),
@@ -388,7 +388,24 @@ exports[`RN Codegen TypeScript Parser can generate fixture CXX_ONLY_NATIVE_MODUL
'type': 'FunctionTypeAnnotation',
'returnTypeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'ObjectTypeAnnotation'
'types': [
{
'type': 'ObjectTypeAnnotation',
'properties': []
},
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'low',
'optional': false,
'typeAnnotation': {
'type': 'StringTypeAnnotation'
}
}
]
}
]
},
'params': [
{
@@ -396,7 +413,20 @@ exports[`RN Codegen TypeScript Parser can generate fixture CXX_ONLY_NATIVE_MODUL
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'NumberTypeAnnotation'
'types': [
{
'type': 'NumberLiteralTypeAnnotation',
'value': 1
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 2
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 3
}
]
}
},
{
@@ -404,7 +434,20 @@ exports[`RN Codegen TypeScript Parser can generate fixture CXX_ONLY_NATIVE_MODUL
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'NumberTypeAnnotation'
'types': [
{
'type': 'NumberLiteralTypeAnnotation',
'value': 1.44
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 2.88
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 5.76
}
]
}
},
{
@@ -412,14 +455,31 @@ exports[`RN Codegen TypeScript Parser can generate fixture CXX_ONLY_NATIVE_MODUL
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'ObjectTypeAnnotation'
'types': [
{
'type': 'ObjectTypeAnnotation',
'properties': []
},
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'low',
'optional': false,
'typeAnnotation': {
'type': 'StringTypeAnnotation'
}
}
]
}
]
}
},
{
'name': 'chooseString',
'optional': false,
'typeAnnotation': {
'type': 'StringLiteralUnionTypeAnnotation',
'type': 'UnionTypeAnnotation',
'types': [
{
'type': 'StringLiteralTypeAnnotation',
@@ -1098,7 +1158,18 @@ exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_AR
'returnTypeAnnotation': {
'type': 'ArrayTypeAnnotation',
'elementType': {
'type': 'AnyTypeAnnotation'
'type': 'UnionTypeAnnotation',
'types': [
{
'type': 'StringTypeAnnotation'
},
{
'type': 'NumberTypeAnnotation'
},
{
'type': 'BooleanTypeAnnotation'
}
]
}
},
'params': [
@@ -1184,7 +1255,18 @@ exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_AR
'returnTypeAnnotation': {
'type': 'ArrayTypeAnnotation',
'elementType': {
'type': 'AnyTypeAnnotation'
'type': 'UnionTypeAnnotation',
'types': [
{
'type': 'StringTypeAnnotation'
},
{
'type': 'NumberTypeAnnotation'
},
{
'type': 'BooleanTypeAnnotation'
}
]
}
},
'params': [
@@ -3058,7 +3140,24 @@ exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_UN
'type': 'FunctionTypeAnnotation',
'returnTypeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'ObjectTypeAnnotation'
'types': [
{
'type': 'ObjectTypeAnnotation',
'properties': []
},
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'low',
'optional': false,
'typeAnnotation': {
'type': 'StringTypeAnnotation'
}
}
]
}
]
},
'params': [
{
@@ -3066,7 +3165,20 @@ exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_UN
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'NumberTypeAnnotation'
'types': [
{
'type': 'NumberLiteralTypeAnnotation',
'value': 1
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 2
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 3
}
]
}
},
{
@@ -3074,7 +3186,20 @@ exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_UN
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'NumberTypeAnnotation'
'types': [
{
'type': 'NumberLiteralTypeAnnotation',
'value': 1.44
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 2.88
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 5.76
}
]
}
},
{
@@ -3082,14 +3207,31 @@ exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_UN
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'ObjectTypeAnnotation'
'types': [
{
'type': 'ObjectTypeAnnotation',
'properties': []
},
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'low',
'optional': false,
'typeAnnotation': {
'type': 'StringTypeAnnotation'
}
}
]
}
]
}
},
{
'name': 'chooseString',
'optional': false,
'typeAnnotation': {
'type': 'StringLiteralUnionTypeAnnotation',
'type': 'UnionTypeAnnotation',
'types': [
{
'type': 'StringLiteralTypeAnnotation',
@@ -3133,7 +3275,7 @@ exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_UN
'typeAnnotation': {
'type': 'FunctionTypeAnnotation',
'returnTypeAnnotation': {
'type': 'StringLiteralUnionTypeAnnotation',
'type': 'UnionTypeAnnotation',
'types': [
{
'type': 'StringLiteralTypeAnnotation',
@@ -3161,7 +3303,7 @@ exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_UN
'name': 'strings',
'optional': false,
'typeAnnotation': {
'type': 'StringLiteralUnionTypeAnnotation',
'type': 'UnionTypeAnnotation',
'types': [
{
'type': 'StringLiteralTypeAnnotation',
@@ -3184,7 +3326,16 @@ exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_UN
'type': 'FunctionTypeAnnotation',
'returnTypeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'NumberTypeAnnotation'
'types': [
{
'type': 'NumberLiteralTypeAnnotation',
'value': 1
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 2
}
]
},
'params': []
}
@@ -3203,7 +3354,16 @@ exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_UN
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'NumberTypeAnnotation'
'types': [
{
'type': 'NumberLiteralTypeAnnotation',
'value': 1
},
{
'type': 'NumberLiteralTypeAnnotation',
'value': 2
}
]
}
}
]
@@ -3216,7 +3376,34 @@ exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_UN
'type': 'FunctionTypeAnnotation',
'returnTypeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'ObjectTypeAnnotation'
'types': [
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'a',
'optional': false,
'typeAnnotation': {
'type': 'NumberLiteralTypeAnnotation',
'value': 1
}
}
]
},
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'b',
'optional': false,
'typeAnnotation': {
'type': 'NumberLiteralTypeAnnotation',
'value': 2
}
}
]
}
]
},
'params': []
}
@@ -3235,7 +3422,34 @@ exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_UN
'optional': false,
'typeAnnotation': {
'type': 'UnionTypeAnnotation',
'memberType': 'ObjectTypeAnnotation'
'types': [
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'a',
'optional': false,
'typeAnnotation': {
'type': 'NumberLiteralTypeAnnotation',
'value': 1
}
}
]
},
{
'type': 'ObjectTypeAnnotation',
'properties': [
{
'name': 'b',
'optional': false,
'typeAnnotation': {
'type': 'NumberLiteralTypeAnnotation',
'value': 2
}
}
]
}
]
}
}
]
@@ -399,7 +399,18 @@ function translateTypeAnnotation(
);
}
case 'TSUnionType': {
return emitUnion(nullable, hasteModuleName, typeAnnotation, parser);
return emitUnion(
nullable,
hasteModuleName,
typeAnnotation,
types,
aliasMap,
enumMap,
tryParse,
cxxOnly,
translateTypeAnnotation,
parser,
);
}
case 'TSLiteralType': {
const literal = typeAnnotation.literal;
@@ -18,10 +18,10 @@ import type {
NativeModuleEnumMember,
NativeModuleEnumMemberType,
NativeModuleParamTypeAnnotation,
NativeModuleUnionTypeAnnotationMemberType,
Nullable,
PropTypeAnnotation,
SchemaType,
UnionTypeAnnotationMemberType,
} from '../../CodegenSchema';
import type {ParserType} from '../errors';
import type {
@@ -109,7 +109,7 @@ class TypeScriptParser implements Parser {
remapUnionTypeAnnotationMemberNames(
membersTypes: Array<$FlowFixMe>,
): Array<UnionTypeAnnotationMemberType> {
): Array<NativeModuleUnionTypeAnnotationMemberType> {
const remapLiteral = (item: $FlowFixMe) => {
return item.literal
? item.literal.type
@@ -123,12 +123,6 @@ class TypeScriptParser implements Parser {
return [...new Set(membersTypes.map(remapLiteral))];
}
getStringLiteralUnionTypeAnnotationStringLiterals(
membersTypes: Array<$FlowFixMe>,
): Array<string> {
return membersTypes.map((item: $FlowFixMe) => item.literal.value);
}
parseFile(filename: string): SchemaType {
const contents = fs.readFileSync(filename, 'utf8');
@@ -109,6 +109,14 @@ export type MembersComparisonResult = {
fault?: TypeComparisonError,
}>,
};
export type UnionMembersComparisonResult = {
addedMembers?: Array<CompleteTypeAnnotation>,
missingMembers?: Array<CompleteTypeAnnotation>,
errorMembers?: Array<{
member: string,
fault?: TypeComparisonError,
}>,
};
export type NullableComparisonResult = {
/* Four possible cases of change:
void goes to T? :: typeRefined !optionsReduced
@@ -130,6 +138,7 @@ export type ComparisonResult =
| {status: 'nullableChange', nullableLog: NullableComparisonResult}
| {status: 'properties', propertyLog: PropertiesComparisonResult}
| {status: 'members', memberLog: MembersComparisonResult}
| {status: 'unionMembers', memberLog: UnionMembersComparisonResult}
| {status: 'functionChange', functionChangeLog: FunctionComparisonResult}
| {status: 'positionalTypeChange', changeLog: PositionalComparisonResult}
| {status: 'error', errorLog: TypeComparisonError};
@@ -151,6 +160,12 @@ export function isMemberLogEmpty(result: MembersComparisonResult): boolean {
return !(result.addedMembers || result.missingMembers || result.errorMembers);
}
export function isUnionMemberLogEmpty(
result: UnionMembersComparisonResult,
): boolean {
return !(result.addedMembers || result.missingMembers || result.errorMembers);
}
export function isFunctionLogEmpty(result: FunctionComparisonResult): boolean {
return !(result.returnType || result.parameterTypes);
}
@@ -20,6 +20,8 @@ import type {
} from './DiffResults';
import type {CompleteTypeAnnotation} from '@react-native/codegen/src/CodegenSchema';
import {parseValidUnionType} from '@react-native/codegen/src/generators/Utils';
function indentedLineStart(indent: number): string {
return '\n' + ' '.repeat(indent);
}
@@ -196,25 +198,66 @@ function formatTypeAnnotation(annotation: CompleteTypeAnnotation): string {
annotation.value.includes(' ')
? `'${annotation.value}'`
: annotation.value;
case 'StringLiteralUnionTypeAnnotation':
return (
'(' +
annotation.types
.map(stringLit => formatTypeAnnotation(stringLit))
.join(' | ') +
')'
);
case 'UnionTypeAnnotation':
const validUnionType = parseValidUnionType(annotation);
switch (validUnionType) {
case 'boolean':
if (
annotation.types.every(
({type}) => type === 'BooleanLiteralTypeAnnotation',
)
) {
return (
'(' +
// @lint-ignore-every FLOW_INCOMPATIBLE_TYPE_ARG
(annotation.types: $ReadOnlyArray<CompleteTypeAnnotation>)
.map(boolLit => formatTypeAnnotation(boolLit))
.join(' | ') +
')'
);
}
return `Union<boolean>`;
case 'number':
if (
annotation.types.every(
({type}) => type === 'NumberLiteralTypeAnnotation',
)
) {
return (
'(' +
// @lint-ignore-every FLOW_INCOMPATIBLE_TYPE_ARG
(annotation.types: $ReadOnlyArray<CompleteTypeAnnotation>)
.map(numLit => formatTypeAnnotation(numLit))
.join(' | ') +
')'
);
}
return `Union<number>`;
case 'object':
return `Union<Object>`;
case 'string':
if (
annotation.types.every(
({type}) => type === 'StringLiteralTypeAnnotation',
)
) {
return (
'(' +
// @lint-ignore-every FLOW_INCOMPATIBLE_TYPE_ARG
(annotation.types: $ReadOnlyArray<CompleteTypeAnnotation>)
.map(stringLit => formatTypeAnnotation(stringLit))
.join(' | ') +
')'
);
}
// Unions of strings and string literals are treated as just strings
return `Union<string>`;
default:
(validUnionType: empty);
throw new Error(`Unsupported union member type`);
}
case 'StringTypeAnnotation':
return 'string';
case 'UnionTypeAnnotation': {
const shortHandType =
annotation.memberType === 'StringTypeAnnotation'
? 'string'
: annotation.memberType === 'ObjectTypeAnnotation'
? 'Object'
: 'number';
return `Union<${shortHandType}>`;
}
case 'PromiseTypeAnnotation':
return 'Promise<' + formatTypeAnnotation(annotation.elementType) + '>';
case 'EventEmitterTypeAnnotation':
@@ -136,18 +136,12 @@ export function compareTypeAnnotationForSorting(
case 'StringLiteralTypeAnnotation':
invariant(typeB.type === 'StringLiteralTypeAnnotation', EQUALITY_MSG);
return typeA.value.localeCompare(typeB.value);
case 'StringLiteralUnionTypeAnnotation':
invariant(
typeB.type === 'StringLiteralUnionTypeAnnotation',
EQUALITY_MSG,
);
case 'UnionTypeAnnotation':
invariant(typeB.type === 'UnionTypeAnnotation', EQUALITY_MSG);
return compareAnnotationArraysForSorting(
[originalPositionA, typeA.types],
[originalPositionB, typeB.types],
);
case 'UnionTypeAnnotation':
invariant(typeB.type === 'UnionTypeAnnotation', EQUALITY_MSG);
return 0;
case 'VoidTypeAnnotation':
return 0;
case 'ReservedTypeAnnotation':
@@ -266,8 +260,6 @@ function typeAnnotationArbitraryOrder(annotation: CompleteTypeAnnotation) {
return 15;
case 'BooleanLiteralTypeAnnotation':
return 16;
case 'StringLiteralUnionTypeAnnotation':
return 17;
case 'StringTypeAnnotation':
return 18;
case 'StringLiteralTypeAnnotation':
+158 -11
View File
@@ -15,6 +15,7 @@ import type {
PositionalComparisonResult,
PropertiesComparisonResult,
TypeComparisonError,
UnionMembersComparisonResult,
} from './ComparisonResult';
import type {
BooleanLiteralTypeAnnotation,
@@ -44,6 +45,7 @@ import {
isFunctionLogEmpty,
isMemberLogEmpty,
isPropertyLogEmpty,
isUnionMemberLogEmpty,
makeError,
memberComparisonError,
propertyComparisonError,
@@ -244,12 +246,6 @@ export function compareTypeAnnotation(
EQUALITY_MSG,
);
return compareBooleanLiteralTypes(newerAnnotation, olderAnnotation);
case 'StringLiteralUnionTypeAnnotation':
invariant(
olderAnnotation.type === 'StringLiteralUnionTypeAnnotation',
EQUALITY_MSG,
);
return compareStringLiteralUnionTypes(newerAnnotation, olderAnnotation);
case 'StringLiteralTypeAnnotation':
invariant(
olderAnnotation.type === 'StringLiteralTypeAnnotation',
@@ -328,6 +324,32 @@ function updatePropertyError(
};
}
function updateUnionMemberError(
name: CompleteTypeAnnotation,
newType: CompleteTypeAnnotation,
oldType: CompleteTypeAnnotation,
result: UnionMembersComparisonResult,
) {
return (oldError: TypeComparisonError) => {
const comparisonError = typeAnnotationComparisonError(
'has conflicting changes',
newType,
oldType,
oldError,
);
const memberLabel = getTypeAnnotationLabel(name);
const newFault: {fault?: TypeComparisonError, member: string} = {
member: memberLabel,
fault: comparisonError,
};
if (result.errorMembers) {
result.errorMembers.push(newFault);
} else {
result.errorMembers = [newFault];
}
};
}
function updateEnumMemberError(
name: string,
newType: CompleteTypeAnnotation,
@@ -353,6 +375,22 @@ function updateEnumMemberError(
};
}
// Helper function to get a descriptive label for a CompleteTypeAnnotation
function getTypeAnnotationLabel(type: CompleteTypeAnnotation): string {
switch (type.type) {
case 'StringLiteralTypeAnnotation':
return `"${type.value}"`;
case 'NumberLiteralTypeAnnotation':
return String(type.value);
case 'BooleanLiteralTypeAnnotation':
return String(type.value);
case 'NullableTypeAnnotation':
return `?${getTypeAnnotationLabel(type.typeAnnotation)}`;
default:
return type.type;
}
}
function updateNestedProperties(
name: string,
propertyChange: ComparisonResult,
@@ -462,6 +500,7 @@ function comparePropertyArrays(
result,
);
case 'members':
case 'unionMembers':
case 'properties':
case 'functionChange':
case 'positionalTypeChange':
@@ -623,9 +662,9 @@ export function compareEnumDeclarationMemberArrays(
if (newer.length === 0 && older.length === 0) {
return {};
} else if (newer.length === 0) {
return {missingMembers: older};
return {missingMembers: [...older]};
} else if (older.length === 0) {
return {addedMembers: newer};
return {addedMembers: [...newer]};
}
const newerHead = newer.pop();
@@ -662,6 +701,7 @@ export function compareEnumDeclarationMemberArrays(
case 'functionChange':
case 'positionalTypeChange':
case 'members':
case 'unionMembers':
break;
default: // Flow exhaustiveness check
(comparedTypes: empty);
@@ -690,6 +730,80 @@ export function compareEnumDeclarationMemberArrays(
throw new Error('Internal error: should not reach here');
}
export function compareUnionMemberArrays(
newer: Array<CompleteTypeAnnotation>,
older: Array<CompleteTypeAnnotation>,
): UnionMembersComparisonResult {
if (newer.length === 0 && older.length === 0) {
return {};
} else if (newer.length === 0) {
return {missingMembers: [...older]};
} else if (older.length === 0) {
return {addedMembers: [...newer]};
}
const newerHead = newer.pop();
const olderHead = older.pop();
invariant(newerHead != null && olderHead != null, 'Array is empty');
const sortComparison = compareTypeAnnotationForSorting(
[0, newerHead],
[0, olderHead],
);
if (sortComparison === 0) {
const headComparison = compareTypeAnnotation(newerHead, olderHead);
const restComparison = compareUnionMemberArrays(newer, older);
switch (headComparison.status) {
case 'matching':
return restComparison;
case 'error':
updateUnionMemberError(
newerHead,
newerHead,
olderHead,
restComparison,
)(headComparison.errorLog);
return restComparison;
case 'skipped':
throw new Error(
"Internal error: returned 'skipped' for non-optional older type",
);
case 'properties':
restComparison.missingMembers = restComparison.missingMembers || [];
restComparison.missingMembers.push(olderHead);
restComparison.addedMembers = restComparison.addedMembers || [];
restComparison.addedMembers.push(newerHead);
return restComparison;
//TODO: Handle the nullable changes within Union
case 'nullableChange':
case 'functionChange':
case 'positionalTypeChange':
case 'members':
case 'unionMembers':
break;
default: // Flow exhaustiveness check
(headComparison: empty);
throw new Error('Unsupported status ' + headComparison.status);
}
} else if (sortComparison > 0) {
older.push(olderHead);
const restComparison = compareUnionMemberArrays(newer, older);
restComparison.addedMembers = restComparison.addedMembers || [];
restComparison.addedMembers.push(newerHead);
return restComparison;
} else if (sortComparison < 0) {
newer.push(newerHead);
const restComparison = compareUnionMemberArrays(newer, older);
restComparison.missingMembers = restComparison.missingMembers || [];
restComparison.missingMembers.push(olderHead);
return restComparison;
}
throw new Error('Internal error: should not reach here');
}
export function compareEnumDeclarationWithMembers(
newerDeclaration: NativeModuleEnumDeclarationWithMembers,
olderDeclaration: NativeModuleEnumDeclarationWithMembers,
@@ -819,17 +933,48 @@ export function compareUnionTypes(
newerType: NativeModuleUnionTypeAnnotation,
olderType: NativeModuleUnionTypeAnnotation,
): ComparisonResult {
if (newerType.memberType !== olderType.memberType) {
const sortedNewerTypes = sortTypeAnnotations(newerType.types);
const sortedOlderTypes = sortTypeAnnotations(olderType.types);
const result = compareUnionMemberArrays(
sortedNewerTypes.map(([_, type]) => type),
sortedOlderTypes.map(([_, type]) => type),
);
if (isUnionMemberLogEmpty(result)) {
return {status: 'matching'};
} else if (result.errorMembers) {
return makeError(
typeAnnotationComparisonError(
'Union member type does not match',
'Union types do not match',
newerType,
olderType,
memberComparisonError(
result.errorMembers.length > 1
? 'Union contained members with type mismatches'
: 'Union contained a member with a type mismatch',
result.errorMembers,
),
),
);
} else if (
(result.addedMembers &&
result.addedMembers.length > 0 &&
result.addedMembers.length === newerType.types.length) ||
(result.missingMembers &&
result.missingMembers.length > 0 &&
result.missingMembers.length === olderType.types.length)
) {
return makeError(
typeAnnotationComparisonError(
'Union types do not match.',
newerType,
olderType,
),
);
}
return {status: 'matching'};
return {status: 'unionMembers', memberLog: result};
}
export function comparePromiseTypes(
@@ -1011,6 +1156,7 @@ export function compareFunctionTypes(
if (
returnTypeResult.status === 'properties' ||
returnTypeResult.status === 'members' ||
returnTypeResult.status === 'unionMembers' ||
returnTypeResult.status === 'functionChange' ||
returnTypeResult.status === 'positionalTypeChange' ||
returnTypeResult.status === 'nullableChange'
@@ -1105,6 +1251,7 @@ function compareArrayOfTypes(
if (
result.status === 'properties' ||
result.status === 'members' ||
result.status === 'unionMembers' ||
result.status === 'functionChange' ||
result.status === 'positionalTypeChange' ||
result.status === 'nullableChange'
@@ -15,6 +15,7 @@ import type {
NullableComparisonResult,
PositionalComparisonResult,
PropertiesComparisonResult,
UnionMembersComparisonResult,
} from './ComparisonResult';
import type {
DiffSet,
@@ -51,6 +52,7 @@ type checkerType = (
positionalChange: ?PositionalComparisonResult,
nullableChange: ?NullableComparisonResult,
memberChange: ?MembersComparisonResult,
unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
) => Array<ErrorStore>;
@@ -79,7 +81,14 @@ function nestedPropertiesCheck(
'Internal error: nested property change ' + result.status,
);
case 'properties':
let finalResult = check(result.propertyLog, null, null, null, typeName);
let finalResult = check(
result.propertyLog,
null,
null,
null,
null,
typeName,
);
if (result.propertyLog.nestedPropertyChanges) {
finalResult = combine(
finalResult,
@@ -106,7 +115,9 @@ function nestedPropertiesCheck(
}
return finalResult;
case 'members':
return check(null, null, null, result.memberLog, typeName);
return check(null, null, null, result.memberLog, null, typeName);
case 'unionMembers':
return check(null, null, null, null, result.memberLog, typeName);
case 'functionChange':
let returnTypeResult: Array<ErrorStore> = [];
if (result.functionChangeLog.returnType) {
@@ -139,6 +150,7 @@ function nestedPropertiesCheck(
changeLog,
null,
null,
null,
typeName,
);
return combine(
@@ -156,6 +168,7 @@ function nestedPropertiesCheck(
null,
result.nullableLog,
null,
null,
typeName,
);
if (result.nullableLog.interiorLog) {
@@ -217,6 +230,7 @@ function checkForUnsafeRemovedProperties(
_postionalChange: ?PositionalComparisonResult,
_nullableChange: ?NullableComparisonResult,
_memberChange: ?MembersComparisonResult,
_unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (propertyChange && propertyChange.missingProperties) {
@@ -237,6 +251,7 @@ function checkForUnsafeAddedProperties(
_positionalChange: ?PositionalComparisonResult,
_nullableChange: ?NullableComparisonResult,
_memberChange: ?MembersComparisonResult,
_unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (propertyChange && propertyChange.addedProperties) {
@@ -257,6 +272,7 @@ function checkForUnSafeMadeStrictProperties(
_positionalChange: ?PositionalComparisonResult,
_nullableChange: ?NullableComparisonResult,
_memberChange: ?MembersComparisonResult,
_unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (
@@ -288,6 +304,7 @@ function checkForUnSafeMadeOptionalProperties(
_positionalChange: ?PositionalComparisonResult,
_nullableChange: ?NullableComparisonResult,
_memberChange: ?MembersComparisonResult,
_unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (
@@ -312,66 +329,6 @@ function checkForUnSafeMadeOptionalProperties(
return [];
}
export const removedUnionMessage =
'Union removed items, but native may still provide them';
function checkForUnsafeRemovedUnionItems(
_propertyChange: ?PropertiesComparisonResult,
positionalChange: ?PositionalComparisonResult,
_nullableChange: ?NullableComparisonResult,
_memberChange: ?MembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (
positionalChange &&
(positionalChange.typeKind === 'union' ||
positionalChange.typeKind === 'stringUnion') &&
positionalChange.removedElements &&
positionalChange.removedElements.length > 0
) {
return [
{
typeName,
errorCode: 'removedUnionCases',
errorInformation: positionalComparisonError(
removedUnionMessage,
positionalChange.removedElements,
),
},
];
}
return [];
}
export const addedUnionMessage =
'Union added items, but native will not expect/support them';
function checkForUnsafeAddedUnionItems(
_propertyChange: ?PropertiesComparisonResult,
positionalChange: ?PositionalComparisonResult,
_nullableChange: ?NullableComparisonResult,
_memberChange: ?MembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (
positionalChange &&
(positionalChange.typeKind === 'union' ||
positionalChange.typeKind === 'stringUnion') &&
positionalChange.addedElements &&
positionalChange.addedElements.length > 0
) {
return [
{
typeName,
errorCode: 'addedUnionCases',
errorInformation: positionalComparisonError(
addedUnionMessage,
positionalChange.addedElements,
),
},
];
}
return [];
}
export const removedEnumMessage =
'Enum removed items, but native may still provide them';
function checkForUnsafeRemovedEnumItems(
@@ -379,6 +336,7 @@ function checkForUnsafeRemovedEnumItems(
_positionalChange: ?PositionalComparisonResult,
_nullableChange: ?NullableComparisonResult,
memberChange: ?MembersComparisonResult,
_unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (memberChange?.missingMembers && memberChange?.missingMembers.length > 0) {
@@ -406,6 +364,7 @@ function checkForUnsafeAddedEnumItems(
_positionalChange: ?PositionalComparisonResult,
_nullableChange: ?NullableComparisonResult,
memberChange: ?MembersComparisonResult,
_unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (memberChange?.addedMembers && memberChange?.addedMembers.length > 0) {
@@ -426,6 +385,101 @@ function checkForUnsafeAddedEnumItems(
return [];
}
// Helper function to get a label for a member (either enum member or union type annotation)
function getMemberLabel(member: CompleteTypeAnnotation): string {
// Check if it's an enum member by checking if it has both 'name' and 'value' properties
// (NativeModuleEnumMember has { name: string, value: TypeAnnotation })
if (
typeof member === 'object' &&
member != null &&
'name' in member &&
'value' in member &&
typeof member.name === 'string'
) {
return member.name;
}
// Otherwise it's a CompleteTypeAnnotation (union member)
// Generate a descriptive label based on the type value
return getTypeAnnotationLabel(member);
}
// Helper function to get a descriptive label for a CompleteTypeAnnotation
function getTypeAnnotationLabel(type: CompleteTypeAnnotation): string {
if (type.type === 'StringLiteralTypeAnnotation') {
return `"${type.value}"`;
} else if (type.type === 'NumberLiteralTypeAnnotation') {
return String(type.value);
} else if (type.type === 'BooleanLiteralTypeAnnotation') {
return String(type.value);
} else if (type.type === 'NullableTypeAnnotation') {
return `?${getTypeAnnotationLabel(type.typeAnnotation)}`;
} else {
return type.type;
}
}
export const removedUnionMemberMessage =
'Union removed items, but native may still provide them';
function checkForUnsafeRemovedUnionItems(
_propertyChange: ?PropertiesComparisonResult,
_positionalChange: ?PositionalComparisonResult,
_nullableChange: ?NullableComparisonResult,
memberChange: ?MembersComparisonResult,
unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (
unionMemberChange?.missingMembers &&
unionMemberChange?.missingMembers.length > 0
) {
return [
{
typeName,
errorCode: 'removedUnionCases',
errorInformation: memberComparisonError(
removedUnionMemberMessage,
unionMemberChange.missingMembers.map(member => ({
member: getMemberLabel(member),
})),
),
},
];
}
return [];
}
export const addedUnionMemberMessage =
'Union added items, but native will not expect/support them';
function checkForUnsafeAddedUnionItems(
_propertyChange: ?PropertiesComparisonResult,
_positionalChange: ?PositionalComparisonResult,
_nullableChange: ?NullableComparisonResult,
memberChange: ?MembersComparisonResult,
unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (
unionMemberChange?.addedMembers &&
unionMemberChange?.addedMembers.length > 0
) {
return [
{
typeName,
errorCode: 'addedUnionCases',
errorInformation: memberComparisonError(
addedUnionMemberMessage,
unionMemberChange.addedMembers.map(member => ({
member: getMemberLabel(member),
})),
),
},
];
}
return [];
}
export const removedIntersectionMessage =
'Intersection removed items, but native may still require properties contained in them';
function checkForUnsafeRemovedIntersectionItems(
@@ -433,6 +487,7 @@ function checkForUnsafeRemovedIntersectionItems(
positionalChange: ?PositionalComparisonResult,
_nullableChange: ?NullableComparisonResult,
_memberChange: ?MembersComparisonResult,
_unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (
@@ -462,6 +517,7 @@ function checkForUnsafeAddedIntersectionItems(
positionalChange: ?PositionalComparisonResult,
_nullableChange: ?NullableComparisonResult,
_memberChange: ?MembersComparisonResult,
_unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (
@@ -493,6 +549,7 @@ function checkForUnsafeNullableToNativeChange(
_positionalChange: ?PositionalComparisonResult,
nullableChange: ?NullableComparisonResult,
_memberChange: ?MembersComparisonResult,
_unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (
@@ -527,6 +584,7 @@ function checkForUnsafeNullableFromNativeChange(
_positionalChange: ?PositionalComparisonResult,
nullableChange: ?NullableComparisonResult,
_memberChange: ?MembersComparisonResult,
_unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
): Array<ErrorStore> {
if (
@@ -558,6 +616,7 @@ function chainPropertiesChecks(checks: Array<checkerType>): checkerType {
positionalChange: ?PositionalComparisonResult,
nullableChange: ?NullableComparisonResult,
memberChange: ?MembersComparisonResult,
unionMemberChange: ?UnionMembersComparisonResult,
typeName: string,
) =>
checks.reduce(
@@ -568,6 +627,7 @@ function chainPropertiesChecks(checks: Array<checkerType>): checkerType {
positionalChange,
nullableChange,
memberChange,
unionMemberChange,
typeName,
),
),
@@ -694,10 +754,56 @@ export function assessComparisonResult(
null,
null,
memberChange,
null,
typeName,
);
const fromNativeErrorResult = checksForTypesFlowingFromNative(
null,
null,
null,
memberChange,
null,
typeName,
);
switch (oldDirection) {
case 'toNative':
toNativeErrorResult.forEach(error =>
incompatibleChanges.add(error),
);
break;
case 'fromNative':
fromNativeErrorResult.forEach(error =>
incompatibleChanges.add(error),
);
break;
case 'both':
toNativeErrorResult.forEach(error =>
incompatibleChanges.add(error),
);
fromNativeErrorResult.forEach(error =>
incompatibleChanges.add(error),
);
break;
}
}
break;
case 'unionMembers':
{
const memberChange = difference.memberLog;
const toNativeErrorResult = checksForTypesFlowingToNative(
null,
null,
null,
null,
memberChange,
typeName,
);
const fromNativeErrorResult = checksForTypesFlowingFromNative(
null,
null,
null,
null,
@@ -835,6 +941,7 @@ export function assessComparisonResult(
changeLog,
null,
null,
null,
typeName,
);
const toNativeResult = combine(
@@ -853,6 +960,7 @@ export function assessComparisonResult(
changeLog,
null,
null,
null,
typeName,
);
const fromNativeResult = combine(
@@ -893,6 +1001,7 @@ export function assessComparisonResult(
null,
difference.nullableLog,
null,
null,
typeName,
).forEach(error => incompatibleChanges.add(error));
break;
@@ -902,6 +1011,7 @@ export function assessComparisonResult(
null,
difference.nullableLog,
null,
null,
typeName,
).forEach(error => incompatibleChanges.add(error));
break;
@@ -118,6 +118,18 @@ export const incompatibleChanges = [
'native-module-with-union/NativeModule',
'native-module-with-union-confusing-string-literals/NativeModule',
],
[
'native-module-with-union-number/NativeModule',
'native-module-with-union-number-changes/NativeModule',
],
[
'native-module-with-union-boolean/NativeModule',
'native-module-with-union-boolean-changes/NativeModule',
],
[
'native-module-with-union-object/NativeModule',
'native-module-with-union-object-changes/NativeModule',
],
[
'native-component-with-command/NativeComponent',
'native-component-with-command-changed/NativeComponent',
@@ -242,15 +242,17 @@ describe('components', () => {
{},
{},
),
).toEqual(
expect.objectContaining({
status: 'positionalTypeChange',
changeLog: expect.objectContaining({
typeKind: 'stringUnion',
addedElements: expect.arrayContaining([expect.any(Array)]),
}),
}),
);
).toEqual({
status: 'unionMembers',
memberLog: {
addedMembers: [
{
type: 'StringLiteralTypeAnnotation',
value: 'baz',
},
],
},
});
});
it('array of an object to an extra key not compatible', () => {
@@ -815,7 +817,40 @@ describe('compareTypes unions', () => {
nativeModuleBeforeAfterTypesAliases,
nativeModuleBeforeAfterTypesAliases,
),
).toBeAnError();
).toEqual({
status: 'error',
errorLog: {
type: 'TypeAnnotationComparisonError',
message: 'Union types do not match.',
newerAnnotation: {
type: 'UnionTypeAnnotation',
types: [
{
type: 'StringLiteralTypeAnnotation',
value: 'str1',
},
{
type: 'StringLiteralTypeAnnotation',
value: 'str2',
},
],
},
olderAnnotation: {
type: 'UnionTypeAnnotation',
types: [
{
type: 'NumberLiteralTypeAnnotation',
value: 4,
},
{
type: 'NumberLiteralTypeAnnotation',
value: 5,
},
],
},
previousError: undefined,
},
});
});
it('fails on differing unions with same length and same alias name', () => {
expect(
@@ -825,7 +860,94 @@ describe('compareTypes unions', () => {
nativeModuleBeforeAfterTypesAliases,
nativeModuleBeforeAfterTypesAliases,
),
).toBeAnError();
).toEqual({
status: 'error',
errorLog: {
type: 'TypeAnnotationComparisonError',
message: 'Parameter at index 0 did not match',
newerAnnotation: {
type: 'FunctionTypeAnnotation',
params: [
{
name: 'a',
optional: false,
typeAnnotation: {
type: 'UnionTypeAnnotation',
types: [
{
type: 'StringLiteralTypeAnnotation',
value: 'str1',
},
{
type: 'StringLiteralTypeAnnotation',
value: 'str2',
},
],
},
},
],
returnTypeAnnotation: {
type: 'VoidTypeAnnotation',
},
},
olderAnnotation: {
type: 'FunctionTypeAnnotation',
params: [
{
name: 'a',
optional: false,
typeAnnotation: {
type: 'UnionTypeAnnotation',
types: [
{
type: 'NumberLiteralTypeAnnotation',
value: 4,
},
{
type: 'NumberLiteralTypeAnnotation',
value: 5,
},
],
},
},
],
returnTypeAnnotation: {
type: 'VoidTypeAnnotation',
},
},
previousError: {
type: 'TypeAnnotationComparisonError',
message: 'Union types do not match.',
newerAnnotation: {
type: 'UnionTypeAnnotation',
types: [
{
type: 'StringLiteralTypeAnnotation',
value: 'str1',
},
{
type: 'StringLiteralTypeAnnotation',
value: 'str2',
},
],
},
olderAnnotation: {
type: 'UnionTypeAnnotation',
types: [
{
type: 'NumberLiteralTypeAnnotation',
value: 4,
},
{
type: 'NumberLiteralTypeAnnotation',
value: 5,
},
],
},
previousError: undefined,
},
},
});
});
it('reports on unions with differing types: string -> object', () => {
expect(
@@ -835,7 +957,49 @@ describe('compareTypes unions', () => {
nativeModuleBeforeAfterTypesAliases,
nativeModuleBeforeAfterTypesAliases,
),
).toHaveErrorWithMessage('Union member type does not match');
).toEqual({
status: 'error',
errorLog: {
type: 'TypeAnnotationComparisonError',
message: 'Union types do not match.',
newerAnnotation: {
type: 'UnionTypeAnnotation',
types: [
{
type: 'NumberLiteralTypeAnnotation',
value: 4,
},
{
type: 'NumberLiteralTypeAnnotation',
value: 5,
},
],
},
olderAnnotation: {
type: 'UnionTypeAnnotation',
types: [
{
properties: [],
type: 'ObjectTypeAnnotation',
},
{
properties: [
{
name: 'key',
optional: false,
typeAnnotation: {
type: 'StringLiteralTypeAnnotation',
value: 'value',
},
},
],
type: 'ObjectTypeAnnotation',
},
],
},
previousError: undefined,
},
});
});
it('reports on unions with differing lengths same alias', () => {
expect(
@@ -847,14 +1011,33 @@ describe('compareTypes unions', () => {
).functionChangeLog.parameterTypes.nestedChanges[0][2],
).toEqual(
expect.objectContaining({
status: 'positionalTypeChange',
changeLog: expect.objectContaining({
typeKind: 'stringUnion',
removedElements: expect.arrayContaining([expect.any(Array)]),
status: 'unionMembers',
memberLog: expect.objectContaining({
missingMembers: expect.any(Array),
}),
}),
);
});
it('reports on unions with same lengths same alias String order changed', () => {
expect(
compareTypes(
nativeModuleBeforeAfterTypesMethodLookup('simpleUnion'),
nativeModuleBeforeAfterTypesMethodLookup('simpleUnionOrderChanged'),
nativeModuleBeforeAfterTypesAliases,
nativeModuleBeforeAfterTypesAliases,
).status,
).toBe('matching');
});
it('reports on unions with same lengths same alias Number order changed', () => {
expect(
compareTypes(
nativeModuleBeforeAfterTypesMethodLookup('simpleUnion2'),
nativeModuleBeforeAfterTypesMethodLookup('simpleUnion2OrderChanged'),
nativeModuleBeforeAfterTypesAliases,
nativeModuleBeforeAfterTypesAliases,
).status,
).toBe('matching');
});
});
describe('compareTypes on arrays', () => {
@@ -1015,15 +1198,17 @@ describe('compareTypes on string literal unions', () => {
nativeTypeDiffingTypesAliases,
nativeTypeDiffingTypesAliases,
),
).toEqual(
expect.objectContaining({
status: 'positionalTypeChange',
changeLog: expect.objectContaining({
typeKind: 'stringUnion',
removedElements: expect.arrayContaining([expect.any(Array)]),
}),
}),
);
).toEqual({
status: 'unionMembers',
memberLog: {
missingMembers: [
{
type: 'StringLiteralTypeAnnotation',
value: 'd',
},
],
},
});
});
it('fails on unions with differing elements', () => {
@@ -1034,16 +1219,23 @@ describe('compareTypes on string literal unions', () => {
nativeTypeDiffingTypesAliases,
nativeTypeDiffingTypesAliases,
),
).toEqual(
expect.objectContaining({
status: 'positionalTypeChange',
changeLog: expect.objectContaining({
typeKind: 'stringUnion',
addedElements: expect.arrayContaining([expect.any(Array)]),
removedElements: expect.arrayContaining([expect.any(Array)]),
}),
}),
);
).toEqual({
status: 'unionMembers',
memberLog: {
addedMembers: [
{
type: 'StringLiteralTypeAnnotation',
value: 'b',
},
],
missingMembers: [
{
type: 'StringLiteralTypeAnnotation',
value: 'x',
},
],
},
});
});
});
@@ -14,12 +14,10 @@ import {schemaDiffExporter} from '../DiffResults.js';
import {
addedEnumMessage,
addedPropertiesMessage,
addedUnionMessage,
buildSchemaDiff,
hasUpdatesTypes,
removedEnumMessage,
removedPropertiesMessage,
removedUnionMessage,
summarizeDiffSet,
tooOptionalPropertiesMessage,
typeNullableChangeMessage,
@@ -887,14 +885,43 @@ describe('buildSchemaDiff', () => {
).toEqual(
expect.objectContaining({
framework: 'ReactNative',
name: 'NativeModule',
status: expect.objectContaining({
incompatibleSpecs: expect.arrayContaining([
expect.objectContaining({
changeInformation: expect.objectContaining({
incompatibleChanges: expect.arrayContaining([
objectTypeChanges: expect.arrayContaining([
expect.objectContaining({
errorInformation: expect.objectContaining({
message: addedUnionMessage,
propertyChange: expect.objectContaining({
nestedPropertyChanges: expect.arrayContaining([
[
'exampleFunction',
expect.objectContaining({
status: 'functionChange',
functionChangeLog: expect.objectContaining({
parameterTypes: expect.objectContaining({
nestedChanges: expect.arrayContaining([
[
0,
0,
expect.objectContaining({
status: 'unionMembers',
memberLog: expect.objectContaining({
addedMembers: expect.arrayContaining([
expect.objectContaining({
type: 'StringLiteralTypeAnnotation',
value: 'd',
}),
]),
}),
}),
],
]),
}),
}),
}),
],
]),
}),
}),
]),
@@ -912,18 +939,47 @@ describe('buildSchemaDiff', () => {
),
).toEqual(
expect.objectContaining({
framework: 'ReactNative',
name: 'NativeModule',
status: expect.objectContaining({
incompatibleSpecs: expect.arrayContaining([
expect.objectContaining({
changeInformation: expect.objectContaining({
newTypes: expect.not.arrayContaining([expect.anything()]),
deprecatedTypes: expect.not.arrayContaining([
expect.anything(),
objectTypeChanges: expect.arrayContaining([
expect.objectContaining({
propertyChange: expect.objectContaining({
nestedPropertyChanges: expect.arrayContaining([
[
'exampleFunction',
expect.objectContaining({
status: 'functionChange',
functionChangeLog: expect.objectContaining({
parameterTypes: expect.objectContaining({
nestedChanges: expect.arrayContaining([
[
0,
0,
expect.objectContaining({
status: 'unionMembers',
memberLog: expect.objectContaining({
missingMembers: expect.arrayContaining([
expect.objectContaining({
type: 'StringLiteralTypeAnnotation',
value: 'd',
}),
]),
}),
}),
],
]),
}),
}),
}),
],
]),
}),
}),
]),
incompatibleChanges: expect.not.arrayContaining([
expect.anything(),
]),
objectTypeChanges: expect.any(Object),
}),
}),
]),
@@ -943,18 +999,52 @@ describe('buildSchemaDiff', () => {
),
).toEqual(
expect.objectContaining({
framework: 'ReactNative',
name: 'NativeModule',
status: expect.objectContaining({
incompatibleSpecs: expect.arrayContaining([
expect.objectContaining({
changeInformation: expect.objectContaining({
newTypes: expect.not.arrayContaining([expect.anything()]),
deprecatedTypes: expect.not.arrayContaining([
expect.anything(),
objectTypeChanges: expect.arrayContaining([
expect.objectContaining({
propertyChange: expect.objectContaining({
nestedPropertyChanges: expect.arrayContaining([
[
'getConstants',
expect.objectContaining({
status: 'functionChange',
functionChangeLog: expect.objectContaining({
returnType: expect.objectContaining({
status: 'properties',
propertyLog: expect.objectContaining({
nestedPropertyChanges: expect.arrayContaining(
[
[
'exampleConstant',
expect.objectContaining({
status: 'unionMembers',
memberLog: expect.objectContaining({
addedMembers:
expect.arrayContaining([
expect.objectContaining({
type: 'StringLiteralTypeAnnotation',
value: 'd',
}),
]),
}),
}),
],
],
),
}),
}),
}),
}),
],
]),
}),
}),
]),
incompatibleChanges: expect.not.arrayContaining([
expect.anything(),
]),
objectTypeChanges: expect.any(Object),
}),
}),
]),
@@ -975,14 +1065,48 @@ describe('buildSchemaDiff', () => {
).toEqual(
expect.objectContaining({
framework: 'ReactNative',
name: 'NativeModule',
status: expect.objectContaining({
incompatibleSpecs: expect.arrayContaining([
expect.objectContaining({
changeInformation: expect.objectContaining({
incompatibleChanges: expect.arrayContaining([
objectTypeChanges: expect.arrayContaining([
expect.objectContaining({
errorInformation: expect.objectContaining({
message: removedUnionMessage,
propertyChange: expect.objectContaining({
nestedPropertyChanges: expect.arrayContaining([
[
'getConstants',
expect.objectContaining({
status: 'functionChange',
functionChangeLog: expect.objectContaining({
returnType: expect.objectContaining({
status: 'properties',
propertyLog: expect.objectContaining({
nestedPropertyChanges: expect.arrayContaining(
[
[
'exampleConstant',
expect.objectContaining({
status: 'unionMembers',
memberLog: expect.objectContaining({
missingMembers:
expect.arrayContaining([
expect.objectContaining({
type: 'StringLiteralTypeAnnotation',
value: 'd',
}),
]),
}),
}),
],
],
),
}),
}),
}),
}),
],
]),
}),
}),
]),
@@ -1330,17 +1454,33 @@ describe('buildSchemaDiff', () => {
).toEqual(
expect.objectContaining({
framework: 'ReactNative',
name: 'NativeComponent',
status: expect.objectContaining({
incompatibleSpecs: expect.arrayContaining([
expect.objectContaining({
changeInformation: expect.objectContaining({
incompatibleChanges: expect.objectContaining({
'0': expect.objectContaining({
errorInformation: expect.objectContaining({
message: addedUnionMessage,
objectTypeChanges: expect.arrayContaining([
expect.objectContaining({
propertyChange: expect.objectContaining({
nestedPropertyChanges: expect.arrayContaining([
[
'size',
expect.objectContaining({
status: 'unionMembers',
memberLog: expect.objectContaining({
addedMembers: expect.arrayContaining([
expect.objectContaining({
type: 'StringLiteralTypeAnnotation',
value: 'huge',
}),
]),
}),
}),
],
]),
}),
}),
}),
]),
}),
}),
]),
@@ -1373,17 +1513,33 @@ describe('buildSchemaDiff', () => {
).toEqual(
expect.objectContaining({
framework: 'ReactNative',
name: 'NativeComponent',
status: expect.objectContaining({
incompatibleSpecs: expect.arrayContaining([
expect.objectContaining({
changeInformation: expect.objectContaining({
incompatibleChanges: expect.objectContaining({
'0': expect.objectContaining({
errorInformation: expect.objectContaining({
message: addedUnionMessage,
objectTypeChanges: expect.arrayContaining([
expect.objectContaining({
propertyChange: expect.objectContaining({
nestedPropertyChanges: expect.arrayContaining([
[
'sizes',
expect.objectContaining({
status: 'unionMembers',
memberLog: expect.objectContaining({
addedMembers: expect.arrayContaining([
expect.objectContaining({
type: 'StringLiteralTypeAnnotation',
value: 'huge',
}),
]),
}),
}),
],
]),
}),
}),
}),
]),
}),
}),
]),
@@ -29,8 +29,10 @@ type SimpleFunction3 = (foo: string) => string;
type SimpleFunction4 = (a: number) => string;
type SimpleUnion = 'str1' | 'str2';
type SimpleUnionOrderChanged = 'str2' | 'str1';
type SimpleUnionLonger = 'str1' | 'str2' | 'str3';
type SimpleUnion2 = 4 | 5;
type SimpleUnion2OrderChanged = 5 | 4;
type SimpleUnion3 = {} | {key: 'value'};
type SimpleUnion4 = BooleanType | StringType | SimpleObject;
@@ -60,7 +62,9 @@ export interface Spec extends TurboModule {
+simpleUnion: (a: SimpleUnion) => void;
+simpleUnionLonger: (a: SimpleUnionLonger) => void;
+simpleUnionOrderChanged: (a: SimpleUnionOrderChanged) => void;
+simpleUnion2: (a: SimpleUnion2) => void;
+simpleUnion2OrderChanged: (a: SimpleUnion2OrderChanged) => void;
+simpleUnion3: (a: SimpleUnion3) => void;
+simpleUnion4: (a: SimpleUnion4) => void;
@@ -25,8 +25,10 @@ type BooleanType = boolean;
type StringType = string;
type SimpleUnion = 'str1' | 'str2';
type SimpleUnionOrderChanged = 'str2' | 'str1';
type SimpleUnionLonger = 'str1' | 'str2' | 'str3';
type SimpleUnion2 = 4 | 5;
type SimpleUnion2OrderChanged = 5 | 4;
type SimpleUnion3 = {} | {key: 'value'};
type SimpleUnion4 = BooleanType | StringType | SimpleObject;
@@ -53,7 +55,9 @@ export interface Spec extends TurboModule {
+simpleUnion: (a: SimpleUnion) => void;
+simpleUnionLonger: (a: SimpleUnionLonger) => void;
+simpleUnionOrderChanged: (a: SimpleUnionOrderChanged) => void;
+simpleUnion2: (a: SimpleUnion2) => void;
+simpleUnion2OrderChanged: (a: SimpleUnion2OrderChanged) => void;
+simpleUnion3: (a: SimpleUnion3) => void;
+simpleUnion4: (a: SimpleUnion4) => void;
@@ -0,0 +1,27 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport';
import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry';
// Changed to incompatible type
type BooleanUnion = true | false;
export interface Spec extends TurboModule {
+exampleFunction: (a: BooleanUnion, b: number) => void;
+getConstants: () => {
+exampleConstant: number,
};
}
export default (TurboModuleRegistry.getEnforcing<Spec>(
'NativeModuleTest',
): Spec);
@@ -0,0 +1,26 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport';
import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry';
type BooleanUnion = true;
export interface Spec extends TurboModule {
+exampleFunction: (a: BooleanUnion, b: number) => void;
+getConstants: () => {
+exampleConstant: number,
};
}
export default (TurboModuleRegistry.getEnforcing<Spec>(
'NativeModuleTest',
): Spec);
@@ -0,0 +1,26 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport';
import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry';
type NumberUnion = 4 | 5 | 6;
export interface Spec extends TurboModule {
+exampleFunction: (a: NumberUnion, b: number) => void;
+getConstants: () => {
+exampleConstant: number,
};
}
export default (TurboModuleRegistry.getEnforcing<Spec>(
'NativeModuleTest',
): Spec);
@@ -0,0 +1,26 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport';
import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry';
type NumberUnion = 1 | 2 | 3;
export interface Spec extends TurboModule {
+exampleFunction: (a: NumberUnion, b: number) => void;
+getConstants: () => {
+exampleConstant: number,
};
}
export default (TurboModuleRegistry.getEnforcing<Spec>(
'NativeModuleTest',
): Spec);
@@ -0,0 +1,37 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport';
import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry';
type ObjectA = {|
kind: 'a',
value: number,
newField: string, // Added new required field
|};
type ObjectB = {|
kind: 'b',
name: string,
|};
type ObjectUnion = ObjectA | ObjectB;
export interface Spec extends TurboModule {
+exampleFunction: (a: ObjectUnion, b: number) => void;
+getConstants: () => {
+exampleConstant: number,
};
}
export default (TurboModuleRegistry.getEnforcing<Spec>(
'NativeModuleTest',
): Spec);
@@ -0,0 +1,36 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport';
import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry';
type ObjectA = {|
kind: 'a',
value: number,
|};
type ObjectB = {|
kind: 'b',
name: string,
|};
type ObjectUnion = ObjectA | ObjectB;
export interface Spec extends TurboModule {
+exampleFunction: (a: ObjectUnion, b: number) => void;
+getConstants: () => {
+exampleConstant: number,
};
}
export default (TurboModuleRegistry.getEnforcing<Spec>(
'NativeModuleTest',
): Spec);
@@ -196,7 +196,7 @@ Object {
Object {
"errorCode": "addedUnionCases",
"message": "NativeComponent.sizes: Union added items, but native will not expect/support them
-- position 2 huge",
-- Member \\"huge\\"",
},
],
},
@@ -237,7 +237,7 @@ Object {
Object {
"errorCode": "addedUnionCases",
"message": "NativeComponent.size: Union added items, but native will not expect/support them
-- position 1 huge",
-- Member \\"huge\\"",
},
],
},
@@ -266,9 +266,11 @@ Object {
-- simpleFunction4
-- simpleUnion
-- simpleUnion2
-- simpleUnion2OrderChanged
-- simpleUnion3
-- simpleUnion4
-- simpleUnionLonger
-- simpleUnionOrderChanged
-- stringType",
},
],
@@ -709,7 +711,33 @@ Object {
Object {
"errorCode": "addedUnionCases",
"message": "NativeModuleTest.exampleFunction parameter 0: Union added items, but native will not expect/support them
-- position 3 d",
-- Member \\"d\\"",
},
],
},
},
"status": "incompatible",
}
`;
exports[`codegen formattedSummarizeDiffSet reports a diff from native-module-with-union-boolean-changes/NativeModule to native-module-with-union-boolean/NativeModule 1`] = `
Object {
"incompatibilityReport": Object {
"NativeModule": Object {
"framework": "ReactNative",
"incompatibleSpecs": Array [
Object {
"errorCode": "incompatibleTypes",
"message": "NativeModuleTest: Object contained a property with a type mismatch
-- exampleFunction: has conflicting type changes
--new: (a: true, b: number)=>void
--old: (a: (true | false), b: number)=>void
Parameter at index 0 did not match
--new: (a: true, b: number)=>void
--old: (a: (true | false), b: number)=>void
Type annotations are not the same.
--new: true
--old: (true | false)",
},
],
},
@@ -727,8 +755,8 @@ Object {
Object {
"errorCode": "addedUnionCases",
"message": "NativeModuleTest.exampleFunction parameter 0: Union added items, but native will not expect/support them
-- position 1 b
-- position 2 c",
-- Member \\"b\\"
-- Member \\"c\\"",
},
],
},
@@ -746,7 +774,51 @@ Object {
Object {
"errorCode": "removedUnionCases",
"message": "NativeModuleTest.getConstants.exampleConstant: Union removed items, but native may still provide them
-- position 3 d",
-- Member \\"d\\"",
},
],
},
},
"status": "incompatible",
}
`;
exports[`codegen formattedSummarizeDiffSet reports a diff from native-module-with-union-number-changes/NativeModule to native-module-with-union-number/NativeModule 1`] = `
Object {
"incompatibilityReport": Object {
"NativeModule": Object {
"framework": "ReactNative",
"incompatibleSpecs": Array [
Object {
"errorCode": "incompatibleTypes",
"message": "NativeModuleTest: Object contained a property with a type mismatch
-- exampleFunction: has conflicting type changes
--new: (a: (1 | 2 | 3), b: number)=>void
--old: (a: (4 | 5 | 6), b: number)=>void
Parameter at index 0 did not match
--new: (a: (1 | 2 | 3), b: number)=>void
--old: (a: (4 | 5 | 6), b: number)=>void
Union types do not match.
--new: (1 | 2 | 3)
--old: (4 | 5 | 6)",
},
],
},
},
"status": "incompatible",
}
`;
exports[`codegen formattedSummarizeDiffSet reports a diff from native-module-with-union-object-changes/NativeModule to native-module-with-union-object/NativeModule 1`] = `
Object {
"incompatibilityReport": Object {
"NativeModule": Object {
"framework": "ReactNative",
"incompatibleSpecs": Array [
Object {
"errorCode": "addedUnionCases",
"message": "NativeModuleTest.exampleFunction parameter 0: Union added items, but native will not expect/support them
-- Member TypeAliasTypeAnnotation",
},
],
},
@@ -766,13 +838,13 @@ Object {
"message": "NativeModuleTest: Object contained a property with a type mismatch
-- exampleFunction: has conflicting type changes
--new: (a: (a | b | c), b: number)=>void
--old: (a: Union<number>, b: number)=>void
--old: (a: (1 | 2 | 3), b: number)=>void
Parameter at index 0 did not match
--new: (a: (a | b | c), b: number)=>void
--old: (a: Union<number>, b: number)=>void
Type annotations are not the same.
--old: (a: (1 | 2 | 3), b: number)=>void
Union types do not match.
--new: (a | b | c)
--old: Union<number>",
--old: (1 | 2 | 3)",
},
],
},
@@ -50,7 +50,7 @@ export default function convertPropToBasicTypes(
break;
case 'StringEnumTypeAnnotation':
resultingType = {
type: 'StringLiteralUnionTypeAnnotation',
type: 'UnionTypeAnnotation',
types: inputType.options.map(option => {
return {
type: 'StringLiteralTypeAnnotation',