Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ declare export default class HTMLCollection<out T>
readonly length: number;
item(index: number): T | null;
namedItem(name: string): T | null;
@@iterator(): IteratorObject<T>;
[Symbol.iterator](): IteratorObject<T>;
}

declare export function createHTMLCollection<T>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ declare export default class NodeList<T> implements Iterable<T>, ArrayLike<T> {
): void;
keys(): IteratorObject<number>;
values(): IteratorObject<T>;
@@iterator(): IteratorObject<T>;
[Symbol.iterator](): IteratorObject<T>;
}

declare export function createNodeList<T>(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/**
* 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 strict-local
* @format
*/

const translateSourceFile = require('../../../translateSourceFile');
const encodeComputedSymbolKeys = require('../encodeComputedSymbolKeys');
const {parse, print} = require('flow-transform');

const prettierOptions = {parser: 'babel'};

async function translate(code: string): Promise<string> {
const parsed = await parse(code);
const result = await encodeComputedSymbolKeys(parsed);
return print(result.ast, result.mutatedCode, prettierOptions);
}

describe('encodeComputedSymbolKeys', () => {
test('encodes computed [Symbol.*] members on declare class, interface, and object types', async () => {
const code = `
declare export default class Foo<out T> {
[Symbol.iterator](): IteratorObject<T>;
static get [Symbol.species](): typeof Foo;
readonly [Symbol.toStringTag]: string;
}
export interface Bar<T> {
[Symbol.asyncIterator](): AsyncIterator<T>;
readonly [Symbol.toStringTag]?: string;
}
export type Baz = {
[Symbol.dispose](): void,
};
`;
const result = await translate(code);
expect(result).toContain('$$SYMBOL_KEY__iterator$$(): IteratorObject<T>;');
expect(result).toContain(
'static get $$SYMBOL_KEY__species$$(): typeof Foo;',
);
expect(result).toContain('readonly $$SYMBOL_KEY__toStringTag$$: string;');
expect(result).toContain(
'$$SYMBOL_KEY__asyncIterator$$(): AsyncIterator<T>;',
);
expect(result).toContain('readonly $$SYMBOL_KEY__toStringTag$$?: string;');
expect(result).toContain('$$SYMBOL_KEY__dispose$$(): void,');
});

test('round-trips through translateSourceFile to TypeScript [Symbol.*] keys', async () => {
const code = `
declare export default class Collection<out T> implements Iterable<T> {
[index: number]: T;
readonly length: number;
[Symbol.iterator](): IteratorObject<T>;
static get [Symbol.species](): typeof Collection;
readonly [Symbol.toStringTag]: string;
}
`;
const {result} = await translateSourceFile(code, 'Collection.js.flow');
expect(result).toContain('[Symbol.iterator](): IteratorObject<T>;');
expect(result).toContain(
'static get [Symbol.species](): typeof Collection;',
);
expect(result).toContain('readonly [Symbol.toStringTag]: string;');
expect(result).not.toContain('$$SYMBOL_KEY__');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* 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 strict-local
* @format
*/

import type {TransformVisitor} from 'flow-transform';
import type {ParseResult} from 'flow-transform/dist/transform/parse';
import type {TransformASTResult} from 'flow-transform/dist/transform/transformAST';

const {t} = require('flow-transform');
const {transformAST} = require('flow-transform/dist/transform/transformAST');

const SYMBOL_KEY_PREFIX = '$$SYMBOL_KEY__';
const SYMBOL_KEY_SUFFIX = '$$';

const visitors: TransformVisitor = context => ({
ObjectTypeProperty(node): void {
if (
node.computed !== true ||
node.key.type !== 'MemberExpression' ||
node.key.computed !== false ||
node.key.object.type !== 'Identifier' ||
node.key.object.name !== 'Symbol' ||
node.key.property.type !== 'Identifier'
) {
return;
}

const encodedKey = t.Identifier({
name: `${SYMBOL_KEY_PREFIX}${node.key.property.name}${SYMBOL_KEY_SUFFIX}`,
});

context.modifyNodeInPlace(node, {
computed: undefined,
key: encodedKey,
});
},
});

/**
* Stopgap pre-transform for `flow-api-translator` versions that do not yet
* support computed `[Symbol.*]` keys on object/interface/class type members.
*
* Encodes `[Symbol.<name>]` as a placeholder identifier that passes through
* `flow-api-translator` untouched and is restored to `[Symbol.<name>]` by
* `transforms/typescript/decodeComputedSymbolKeys`.
*/
async function encodeComputedSymbolKeys(
source: ParseResult,
): Promise<TransformASTResult> {
return transformAST(source, visitors);
}

module.exports = encodeComputedSymbolKeys;
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* 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 strict-local
* @format
*/

const decodeComputedSymbolKeys = require('../decodeComputedSymbolKeys');
const babel = require('@babel/core');

async function translate(code: string): Promise<string> {
const result = await babel.transformAsync(code, {
plugins: ['@babel/plugin-syntax-typescript', decodeComputedSymbolKeys],
});

return result.code;
}

describe('decodeComputedSymbolKeys', () => {
test('restores placeholder identifiers to computed [Symbol.*] keys', async () => {
const code = `
declare class Foo<T> {
$$SYMBOL_KEY__iterator$$(): IteratorObject<T>;
static get $$SYMBOL_KEY__species$$(): typeof Foo;
readonly $$SYMBOL_KEY__toStringTag$$: string;
}
interface Bar<T> {
$$SYMBOL_KEY__asyncIterator$$(): AsyncIterator<T>;
readonly $$SYMBOL_KEY__toStringTag$$?: string | undefined;
}
type Baz = {
$$SYMBOL_KEY__dispose$$(): void;
regular(): void;
};
`;
const result = await translate(code);
expect(result).toContain('[Symbol.iterator](): IteratorObject<T>;');
expect(result).toContain('static get [Symbol.species](): typeof Foo;');
expect(result).toContain('readonly [Symbol.toStringTag]: string;');
expect(result).toContain('[Symbol.asyncIterator](): AsyncIterator<T>;');
expect(result).toContain(
'readonly [Symbol.toStringTag]?: string | undefined;',
);
expect(result).toContain('[Symbol.dispose](): void;');
expect(result).toContain('regular(): void;');
expect(result).not.toContain('$$SYMBOL_KEY__');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* 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 strict-local
* @format
*/

import type {PluginObj} from '@babel/core';
import type {
ClassMethod,
ClassProperty,
TSDeclareMethod,
TSMethodSignature,
TSPropertySignature,
} from '@babel/types';

import * as t from '@babel/types';

const SYMBOL_KEY_PATTERN = /^\$\$SYMBOL_KEY__([A-Za-z_$][A-Za-z0-9_$]*)\$\$$/;

function decodeSymbolKey(
node:
| TSDeclareMethod
| TSMethodSignature
| TSPropertySignature
| ClassMethod
| ClassProperty,
): void {
if (node.computed === true || !t.isIdentifier(node.key)) {
return;
}

const match = SYMBOL_KEY_PATTERN.exec(node.key.name);
if (match == null) {
return;
}

node.computed = true;
node.key = t.memberExpression(t.identifier('Symbol'), t.identifier(match[1]));
}

/**
* Stopgap post-transform paired with `transforms/flow/encodeComputedSymbolKeys`.
*
* Restores placeholder identifiers emitted for `[Symbol.<name>]` back into
* computed `Symbol.<name>` member expressions in the generated TypeScript AST.
*/
const visitor: PluginObj<unknown> = {
visitor: {
TSDeclareMethod(path) {
decodeSymbolKey(path.node);
},
TSMethodSignature(path) {
decodeSymbolKey(path.node);
},
TSPropertySignature(path) {
decodeSymbolKey(path.node);
},
ClassMethod(path) {
decodeSymbolKey(path.node);
},
ClassProperty(path) {
decodeSymbolKey(path.node);
},
},
};

module.exports = visitor;
2 changes: 2 additions & 0 deletions scripts/js-api/build-types/translateSourceFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@ const preTransforms: Array<PreTransformFn> = [
require('./transforms/flow/replaceNullablePropertiesWithUndefined'),
require('./transforms/flow/reattachDocComments'),
require('./transforms/flow/ensureNoUnprefixedProps'),
require('./transforms/flow/encodeComputedSymbolKeys'),
];
const postTransforms = (filePath: string): Array<PluginObj<unknown>> => [
require('./transforms/typescript/decodeComputedSymbolKeys'),
require('./transforms/typescript/convertTypeAliasesToInterfaces'),
require('./transforms/typescript/ensureUndefinedOnOptionalMembers'),
require('./transforms/typescript/replaceProtectedConstructors'),
Expand Down
Loading