Skip to content

Commit

Permalink
Simplify (transpiled) babel-types builder wrappers (#13843)
Browse files Browse the repository at this point in the history
  • Loading branch information
lightmare committed Oct 21, 2021
1 parent 362c623 commit 35ec439
Show file tree
Hide file tree
Showing 4 changed files with 272 additions and 271 deletions.
6 changes: 3 additions & 3 deletions packages/babel-types/scripts/generators/builders.js
Expand Up @@ -100,7 +100,7 @@ import type * as t from "../..";
formatedBuilderNameLocal === formatedBuilderName ? "export " : ""
}function ${formatedBuilderNameLocal}(${defArgs.join(
", "
)}): t.${type} { return builder("${type}", ...arguments); }\n`;
)}): t.${type} { return builder.apply("${type}", arguments); }\n`;
if (formatedBuilderNameLocal !== formatedBuilderName) {
output += `export { ${formatedBuilderNameLocal} as ${formatedBuilderName} };\n`;
}
Expand All @@ -119,9 +119,9 @@ import type * as t from "../..";
const newType = definitions.DEPRECATED_KEYS[type];
const formatedBuilderName = formatBuilderName(type);
output += `/** @deprecated */
function ${type}(...args: Array<any>): any {
function ${type}(${generateBuilderArgs(newType).join(", ")}): t.${type} {
console.trace("The node type ${type} has been renamed to ${newType}");
return builder("${type}", ...args);
return builder.apply("${type}", arguments);
}
export { ${type} as ${formatedBuilderName} };\n`;
// This is needed for backwards compatibility.
Expand Down
21 changes: 10 additions & 11 deletions packages/babel-types/src/builders/builder.ts
Expand Up @@ -2,12 +2,10 @@ import { NODE_FIELDS, BUILDER_KEYS } from "../definitions";
import validate from "../validators/validate";
import type * as t from "..";

export default function builder<T extends t.Node>(
type: T["type"],
...args: Array<any>
): T {
export default function builder<T extends t.Node>(this: T["type"]): T {
const type = this;
const keys = BUILDER_KEYS[type];
const countArgs = args.length;
const countArgs = arguments.length;
if (countArgs > keys.length) {
throw new Error(
`${type}: Too many arguments passed. Received ${countArgs} but can receive no more than ${keys.length}`,
Expand All @@ -16,21 +14,22 @@ export default function builder<T extends t.Node>(

const node = { type };

let i = 0;
keys.forEach(key => {
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
const field = NODE_FIELDS[type][key];

let arg;
if (i < countArgs) arg = args[i];
if (i < countArgs) arg = arguments[i];
if (arg === undefined) {
arg = Array.isArray(field.default) ? [] : field.default;
}

node[key] = arg;
i++;
});
}

for (const key of Object.keys(node)) {
// (assume all enumerable properties are own)
// eslint-disable-next-line guard-for-in
for (const key in node) {
validate(node as t.Node, key, node[key]);
}

Expand Down

0 comments on commit 35ec439

Please sign in to comment.