Rewrite Hub as interface #5047

This commit is contained in:
Yongxu Ren 2016-12-27 11:52:51 -05:00 committed by Nicolò Ribaudo
parent 3a399d1eb9
commit 0fd3da110d
12 changed files with 67 additions and 32 deletions

View File

@ -1,7 +1,7 @@
// @flow // @flow
import * as helpers from "@babel/helpers"; import * as helpers from "@babel/helpers";
import { NodePath, Hub, Scope } from "@babel/traverse"; import { NodePath, Scope, type HubInterface } from "@babel/traverse";
import { codeFrameColumns } from "@babel/code-frame"; import { codeFrameColumns } from "@babel/code-frame";
import traverse from "@babel/traverse"; import traverse from "@babel/traverse";
import * as t from "@babel/types"; import * as t from "@babel/types";
@ -27,10 +27,18 @@ export default class File {
ast: Object = {}; ast: Object = {};
scope: Scope; scope: Scope;
metadata: {} = {}; metadata: {} = {};
hub: Hub = new Hub(this);
code: string = ""; code: string = "";
inputMap: Object | null = null; inputMap: Object | null = null;
hub: HubInterface = {
// keep it for the usage in babel-core, ex: path.hub.file.opts.filename
file: this,
getCode: () => this.code,
getScope: () => this.scope,
addHelper: this.addHelper.bind(this),
buildError: this.buildCodeFrameError.bind(this),
};
constructor(options: {}, { code, ast, inputMap }: NormalizedFile) { constructor(options: {}, { code, ast, inputMap }: NormalizedFile) {
this.opts = options; this.opts = options;
this.code = code; this.code = code;

View File

@ -112,7 +112,7 @@ export function wrapInterop(
throw new Error(`Unknown interop: ${type}`); throw new Error(`Unknown interop: ${type}`);
} }
return t.callExpression(programPath.hub.file.addHelper(helper), [expr]); return t.callExpression(programPath.hub.addHelper(helper), [expr]);
} }
/** /**

View File

@ -59,10 +59,13 @@ export default declare(api => {
const fileNameIdentifier = path.scope.generateUidIdentifier( const fileNameIdentifier = path.scope.generateUidIdentifier(
FILE_NAME_VAR, FILE_NAME_VAR,
); );
path.hub.file.scope.push({ const scope = path.hub.getScope();
id: fileNameIdentifier, if (scope) {
init: t.stringLiteral(fileName), scope.push({
}); id: fileNameIdentifier,
init: t.stringLiteral(fileName),
});
}
state.fileNameIdentifier = fileNameIdentifier; state.fileNameIdentifier = fileNameIdentifier;
} }

View File

@ -143,7 +143,7 @@ export default declare((api, options) => {
} }
path.replaceWith( path.replaceWith(
t.callExpression(path.hub.file.addHelper("construct"), [ t.callExpression(path.hub.addHelper("construct"), [
node.callee, node.callee,
args, args,
]), ]),

View File

@ -1,5 +1,22 @@
export default class Hub { import type Scope from "./scope";
constructor(file) {
this.file = file; export interface HubInterface {
getCode(): ?string;
getScope(): ?Scope;
addHelper(name: string): Object;
buildError(node: Object, msg: string, Error: Class<Error>): Error;
}
export default class Hub implements HubInterface {
getCode() {}
getScope() {}
addHelper() {
throw new Error("Helpers are not supported by the default hub.");
}
buildError(node, msg, Error = TypeError): Error {
return new Error(msg);
} }
} }

View File

@ -7,6 +7,7 @@ import * as cache from "./cache";
export { default as NodePath } from "./path"; export { default as NodePath } from "./path";
export { default as Scope } from "./scope"; export { default as Scope } from "./scope";
export { default as Hub } from "./hub"; export { default as Hub } from "./hub";
export type { HubInterface } from "./hub";
export { visitors }; export { visitors };

View File

@ -133,7 +133,7 @@ export function arrowFunctionToExpression({
this.get("body").unshiftContainer( this.get("body").unshiftContainer(
"body", "body",
t.expressionStatement( t.expressionStatement(
t.callExpression(this.hub.file.addHelper("newArrowCheck"), [ t.callExpression(this.hub.addHelper("newArrowCheck"), [
t.thisExpression(), t.thisExpression(),
checkBinding checkBinding
? t.identifier(checkBinding.name) ? t.identifier(checkBinding.name)

View File

@ -1,4 +1,4 @@
import type Hub from "../hub"; import type { HubInterface } from "../hub";
import type TraversalContext from "../context"; import type TraversalContext from "../context";
import * as virtualTypes from "./lib/virtual-types"; import * as virtualTypes from "./lib/virtual-types";
import buildDebug from "debug"; import buildDebug from "debug";
@ -24,7 +24,7 @@ import * as NodePath_comments from "./comments";
const debug = buildDebug("babel"); const debug = buildDebug("babel");
export default class NodePath { export default class NodePath {
constructor(hub: Hub, parent: Object) { constructor(hub: HubInterface, parent: Object) {
this.parent = parent; this.parent = parent;
this.hub = hub; this.hub = hub;
this.contexts = []; this.contexts = [];
@ -49,7 +49,7 @@ export default class NodePath {
} }
parent: Object; parent: Object;
hub: Hub; hub: HubInterface;
contexts: Array<TraversalContext>; contexts: Array<TraversalContext>;
data: Object; data: Object;
shouldSkip: boolean; shouldSkip: boolean;
@ -121,7 +121,7 @@ export default class NodePath {
} }
buildCodeFrameError(msg: string, Error: typeof Error = SyntaxError): Error { buildCodeFrameError(msg: string, Error: typeof Error = SyntaxError): Error {
return this.hub.file.buildCodeFrameError(this.node, msg, Error); return this.hub.buildError(this.node, msg, Error);
} }
traverse(visitor: Object, state?: any) { traverse(visitor: Object, state?: any) {

View File

@ -196,10 +196,10 @@ export function referencesImport(moduleSource, importName) {
export function getSource() { export function getSource() {
const node = this.node; const node = this.node;
if (node.end) { if (node.end) {
return this.hub.file.code.slice(node.start, node.end); const code = this.hub.getCode();
} else { if (code) return code.slice(node.start, node.end);
return "";
} }
return "";
} }
export function willIMaybeExecuteBefore(target) { export function willIMaybeExecuteBefore(target) {

View File

@ -362,7 +362,7 @@ export default class Scope {
(local.kind === "param" && (kind === "let" || kind === "const")); (local.kind === "param" && (kind === "let" || kind === "const"));
if (duplicate) { if (duplicate) {
throw this.hub.file.buildCodeFrameError( throw this.hub.buildError(
id, id,
`Duplicate declaration "${name}"`, `Duplicate declaration "${name}"`,
TypeError, TypeError,
@ -404,9 +404,7 @@ export default class Scope {
console.log(sep); console.log(sep);
} }
toArray(node: Object, i?: number | boolean) { toArray(node: Object, i?: number) {
const file = this.hub.file;
if (t.isIdentifier(node)) { if (t.isIdentifier(node)) {
const binding = this.getBinding(node.name); const binding = this.getBinding(node.name);
if (binding && binding.constant && binding.path.isGenericType("Array")) { if (binding && binding.constant && binding.path.isGenericType("Array")) {
@ -444,12 +442,12 @@ export default class Scope {
// Used in array-rest to create an array from a subset of an iterable. // Used in array-rest to create an array from a subset of an iterable.
helperName = "slicedToArray"; helperName = "slicedToArray";
// TODO if (this.hub.file.isLoose("es6.forOf")) helperName += "-loose"; // TODO if (this.hub.isLoose("es6.forOf")) helperName += "-loose";
} else { } else {
// Used in array-rest to create an array // Used in array-rest to create an array
helperName = "toArray"; helperName = "toArray";
} }
return t.callExpression(file.addHelper(helperName), args); return t.callExpression(this.hub.addHelper(helperName), args);
} }
hasLabel(name: string) { hasLabel(name: string) {

View File

@ -13,13 +13,11 @@ function assertConversion(
const rootPath = NodePath.get({ const rootPath = NodePath.get({
hub: { hub: {
file: { addHelper(helperName) {
addHelper(helperName) { return t.memberExpression(
return t.memberExpression( t.identifier("babelHelpers"),
t.identifier("babelHelpers"), t.identifier(helperName),
t.identifier(helperName), );
);
},
}, },
}, },
parentPath: null, parentPath: null,

View File

@ -0,0 +1,10 @@
import assert from "assert";
import { Hub } from "../lib";
describe("hub", function() {
it("default buildError should return TypeError", function() {
const hub = new Hub();
const msg = "test_msg";
assert.deepEqual(hub.buildError(null, msg), new TypeError(msg));
});
});