Skip to content

Commit

Permalink
Migrate Babel from Flow to TypeScript (except Babel parser) (babel#11578
Browse files Browse the repository at this point in the history
)

Co-authored-by: Nicolò Ribaudo <[email protected]>
  • Loading branch information
zxbodya and nicolo-ribaudo authored Nov 25, 2021
1 parent 473f145 commit 0058b7f
Show file tree
Hide file tree
Showing 162 changed files with 672 additions and 133 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ module.exports = {
],
excludedFiles: [
// @babel/register is the require() hook, so it will always be CJS-based
"packages/babel-register/**/*.js",
"packages/babel-register/**/*.{js,ts}",
],
rules: {
"no-restricted-globals": ["error", ...cjsGlobals],
Expand Down
2 changes: 1 addition & 1 deletion Gulpfile.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ function mapSrcToLib(srcPath) {
function mapToDts(packageName) {
return packageName.replace(
/(?<=\\|\/|^)(packages|eslint|codemods)(?=\\|\/)/,
"dts"
"dts/$1"
);
}

Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ function isOneLinerBlock(context, node) {
);
}

function report(context, node, missing) {
function report(context, node, missing?) {
const lastToken = context.getSourceCode().getLastToken(node);

let message,
Expand Down
10 changes: 5 additions & 5 deletions packages/babel-core/src/config/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import type { PluginObject } from "./validation/plugins";

export default class Plugin {
key: string | undefined | null;
manipulateOptions: ((options: unknown, parserOpts: unknown) => void) | void;
post: Function | void;
pre: Function | void;
manipulateOptions?: (options: unknown, parserOpts: unknown) => void;
post?: Function;
pre?: Function;
visitor: {};

parserOverride: Function | void;
generatorOverride: Function | void;
parserOverride?: Function;
generatorOverride?: Function;

options: {};

Expand Down
2 changes: 1 addition & 1 deletion packages/babel-generator/src/buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export default class Buffer {
* Get the final string output from the buffer, along with the sourcemap if one exists.
*/

get(): any {
get() {
this._flush();

const map = this._map;
Expand Down
4 changes: 2 additions & 2 deletions packages/babel-generator/src/generators/jsx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export function JSXElement(this: Printer, node: t.JSXElement) {
if (open.selfClosing) return;

this.indent();
for (const child of node.children as Array<any>) {
for (const child of node.children) {
this.print(child, node);
}
this.dedent();
Expand Down Expand Up @@ -109,7 +109,7 @@ export function JSXFragment(this: Printer, node: t.JSXFragment) {
this.print(node.openingFragment, node);

this.indent();
for (const child of node.children as Array<any>) {
for (const child of node.children) {
this.print(child, node);
}
this.dedent();
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-generator/src/generators/statements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ export function VariableDeclaration(
let hasInits = false;
// don't add whitespace to loop heads
if (!isFor(parent)) {
for (const declar of node.declarations as Array<any>) {
for (const declar of node.declarations) {
if (declar.init) {
// has an init so let's split it up over multiple lines
hasInits = true;
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-generator/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ export default function generate(
ast: t.Node,
opts?: GeneratorOptions,
code?: string | { [filename: string]: string },
): any {
) {
const gen = new Generator(ast, opts, code);
return gen.generate();
}
2 changes: 1 addition & 1 deletion packages/babel-generator/src/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ class Printer {
* `undefined` will be returned and not `foo` due to the terminator.
*/

startTerminatorless(isLabel: boolean = false): any {
startTerminatorless(isLabel: boolean = false) {
if (isLabel) {
this._noLineTerminator = true;
return null;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import explode from "@babel/helper-explode-assignable-expression";
import { assignmentExpression, sequenceExpression } from "@babel/types";
import type { Visitor } from "@babel/traverse";

export default function (opts: { build: Function, operator: string }): Object {
export default function (opts: { build: Function; operator: string }) {
const { build, operator } = opts;

return {
const visitor: Visitor = {
AssignmentExpression(path) {
const { node, scope } = path;
if (node.operator !== operator + "=") return;

const nodes = [];
// @ts-expect-error todo(flow->ts)
const exploded = explode(node.left, nodes, this, scope);
nodes.push(
assignmentExpression(
Expand All @@ -28,4 +30,5 @@ export default function (opts: { build: Function, operator: string }): Object {
}
},
};
return visitor;
}
3 changes: 3 additions & 0 deletions packages/babel-helper-builder-react-jsx/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
"@babel/helper-annotate-as-pure": "workspace:^",
"@babel/types": "workspace:^"
},
"devDependencies": {
"@babel/traverse": "workspace:^"
},
"engines": {
"node": ">=6.9.0"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,19 @@ import {
thisExpression,
} from "@babel/types";
import annotateAsPure from "@babel/helper-annotate-as-pure";
import type { Visitor } from "@babel/traverse";

type ElementState = {
tagExpr: Object, // tag node
tagName: ?string, // raw string tag name
args: Array<Object>, // array of call arguments
call?: Object, // optional call property that can be set to override the call expression returned
pure: boolean, // true if the element can be marked with a #__PURE__ annotation
tagExpr: any; // tag node,
tagName: string | undefined | null; // raw string tag name,
args: Array<any>; // array of call arguments,
call?: any; // optional call property that can be set to override the call expression returned,
pure: boolean; // true if the element can be marked with a #__PURE__ annotation
callee?: any;
};

export default function (opts) {
const visitor = {};
const visitor: Visitor = {};

visitor.JSXNamespacedName = function (path) {
if (opts.throwIfNamespace) {
Expand Down Expand Up @@ -81,6 +83,7 @@ You can set \`throwIfNamespace: false\` to bypass this warning.`,
if (node.name === "this" && isReferenced(node, parent)) {
return thisExpression();
} else if (isValidIdentifier(node.name, false)) {
// @ts-expect-error todo(flow->ts) avoid type unsafe mutations
node.type = "Identifier";
} else {
return stringLiteral(node.name);
Expand Down Expand Up @@ -152,6 +155,7 @@ You can set \`throwIfNamespace: false\` to bypass this warning.`,
if (isIdentifier(tagExpr)) {
tagName = tagExpr.name;
} else if (isLiteral(tagExpr)) {
// @ts-expect-error todo(flow->ts) NullLiteral
tagName = tagExpr.value;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
isLoose,
} from "./features";
import { assertFieldTransformed } from "./typescript";
import type { ParserOptions } from "@babel/parser";

export { FEATURES, enableFeature, injectInitialization };

Expand All @@ -38,7 +39,7 @@ interface Options {
feature: number;
loose?: boolean;
// same as PluginObject.manipulateOptions
manipulateOptions: (options: unknown, parserOpts: unknown) => void;
manipulateOptions: (options: unknown, parserOpts: ParserOptions) => void;
// TODO(flow->ts): change to babel api
api?: { assumption: (key?: string) => boolean | undefined };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
toKeyAlias,
} from "@babel/types";

function toKind(node: Object) {
function toKind(node: any) {
if (isClassMethod(node) || isObjectMethod(node)) {
if (node.kind === "get" || node.kind === "set") {
return node.kind;
Expand All @@ -30,18 +30,12 @@ function toKind(node: Object) {

const has = Function.prototype.call.bind(Object.prototype.hasOwnProperty);

export function push(
mutatorMap: Object,
node: Object,
kind: string,
file,
scope?,
): Object {
export function push(mutatorMap: any, node: any, kind: string, file, scope?) {
const alias = toKeyAlias(node);

//

let map = {};
let map = {} as any;
if (has(mutatorMap, alias)) map = mutatorMap[alias];
mutatorMap[alias] = map;

Expand Down Expand Up @@ -79,6 +73,7 @@ export function push(
} else if (isObjectMethod(node) || isClassMethod(node)) {
value = functionExpression(
null,
// @ts-expect-error todo(flow->ts) TSParameterProperty is not assignable to parameter of type 'Identifier | RestElement | Pattern'.
node.params,
node.body,
node.generator,
Expand Down Expand Up @@ -110,7 +105,7 @@ export function push(
return map;
}

export function hasComputed(mutatorMap: Object): boolean {
export function hasComputed(mutatorMap: any): boolean {
for (const key of Object.keys(mutatorMap)) {
if (mutatorMap[key]._computed) {
return true;
Expand All @@ -119,7 +114,7 @@ export function hasComputed(mutatorMap: Object): boolean {
return false;
}

export function toComputedObjectFromClass(obj: Object): Object {
export function toComputedObjectFromClass(obj: any) {
const objExpr = arrayExpression([]);

for (let i = 0; i < obj.properties.length; i++) {
Expand All @@ -134,7 +129,7 @@ export function toComputedObjectFromClass(obj: Object): Object {
return objExpr;
}

export function toClassObject(mutatorMap: Object): Object {
export function toClassObject(mutatorMap: any) {
const objExpr = objectExpression([]);

Object.keys(mutatorMap).forEach(function (mutatorMapKey) {
Expand All @@ -160,7 +155,7 @@ export function toClassObject(mutatorMap: Object): Object {
return objExpr;
}

export function toDefineObject(mutatorMap: Object): Object {
export function toDefineObject(mutatorMap: any) {
Object.keys(mutatorMap).forEach(function (key) {
const map = mutatorMap[key];
if (map.value) map.writable = booleanLiteral(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -482,8 +482,7 @@ function getLocalExportMetadata(
(initializeReexports || !child.node.source)
) {
if (child.node.declaration) {
// todo: flow->ts babel-types node field types
const declaration = child.get("declaration") as NodePath;
const declaration = child.get("declaration");
const ids = declaration.getOuterBindingIdentifierPaths();
Object.keys(ids).forEach(name => {
if (name === "__esModule") {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,19 @@
export function declare(builder) {
export function declare<
Args extends
| [any]
| [any, any?]
| [any, any?, any?]
| [any, any]
| [any, any, any?]
| [any, any, any],
Builder extends (...args: Args) => any,
>(
builder: Builder,
// todo(flow->ts) maybe add stricter type for returned function
// reason any is there to not expose exact implementation details in type
// example of issue with this packages/babel-preset-typescript/src/index.ts
): Builder extends (...args: infer A) => any ? (...args: A) => any : never {
// @ts-ignore
return (api, options, dirname) => {
let clonedApi;

Expand All @@ -10,6 +25,7 @@ export function declare(builder) {
clonedApi[name] = apiPolyfills[name](clonedApi);
}

// @ts-ignore
return builder(clonedApi ?? api, options || {}, dirname);
};
}
Expand Down Expand Up @@ -101,12 +117,9 @@ function throwVersionError(range, version) {
Error.stackTraceLimit = limit;
}

throw Object.assign(
err,
({
code: "BABEL_VERSION_UNSUPPORTED",
version,
range,
}: any),
);
throw Object.assign(err, {
code: "BABEL_VERSION_UNSUPPORTED",
version,
range,
} as any);
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,11 @@ const awaitVisitor = {
};

export default function (
path: NodePath,
helpers: { wrapAsync: Object, wrapAwait: Object },
path: NodePath<any>,
helpers: {
wrapAsync: any;
wrapAwait?: any;
},
noNewArrows?: boolean,
) {
path.traverse(awaitVisitor, {
Expand Down
Loading

0 comments on commit 0058b7f

Please sign in to comment.