Merge pull request #3398 from babel/revert-rm-flow

Revert "Remove flow"
This commit is contained in:
Amjad Masad 2016-03-03 16:07:24 -08:00
commit 92ed05640c
120 changed files with 945 additions and 594 deletions

View File

@ -36,7 +36,7 @@ while (nodeModulesDirectories.length) {
let loc = nodeModulesDirectories.shift();
if (!fs.existsSync(loc)) continue;
let packagesNames = fs.readdirSync(loc);
let packagesNames: Array<string> = fs.readdirSync(loc);
for (let packageName of packagesNames) {
if (packageName[0] === ".") continue;

View File

@ -61,7 +61,7 @@ function getTokenType(match) {
* Highlight `text`.
*/
function highlight(text) {
function highlight(text: string) {
return text.replace(jsTokens, function (...args) {
let type = getTokenType(args);
let colorize = defs[type];
@ -77,7 +77,12 @@ function highlight(text) {
* Create a code frame, adding line numbers, code highlighting, and pointing to a given position.
*/
export default function (rawLines, lineNumber, colNumber, opts = {}) {
export default function (
rawLines: string,
lineNumber: number,
colNumber: number,
opts: Object = {},
): string {
colNumber = Math.max(colNumber, 0);
let highlighted = opts.highlightCode && chalk.supportsColor;

View File

@ -4,11 +4,11 @@
import { transform } from "./node";
export * from "./node";
export function run(code, opts = {}) {
export function run(code: string, opts: Object = {}): any {
return new Function(transform(code, opts).code)();
}
export function load(url, callback, opts = {}, hold) {
export function load(url: string, callback: Function, opts: Object = {}, hold?: boolean) {
opts.filename = opts.filename || url;
let xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest();
@ -32,7 +32,7 @@ export function load(url, callback, opts = {}, hold) {
}
function runScripts() {
let scripts = [];
let scripts: Array<Array<any> | Object> = [];
let types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"];
let index = 0;
@ -53,7 +53,7 @@ function runScripts() {
* Load, transform, and execute all scripts.
*/
function run(script, i) {
function run(script: Object, i: number) {
let opts = {};
if (script.src) {

View File

@ -42,7 +42,7 @@ export let transformFromAst = pipeline.transformFromAst.bind(pipeline);
//
export function transformFile(filename, opts, callback) {
export function transformFile(filename: string, opts?: Object, callback: Function) {
if (isFunction(opts)) {
callback = opts;
opts = {};
@ -69,7 +69,7 @@ export function transformFile(filename, opts, callback) {
});
}
export function transformFileSync(filename, opts = {}) {
export function transformFileSync(filename: string, opts?: Object = {}): string {
opts.filename = filename;
return transform(fs.readFileSync(filename, "utf8"), opts);
}

View File

@ -1,8 +1,6 @@
import merge from "lodash/object/merge";
export default function (dest, src) {
export default function (dest?: Object, src?: Object): ?Object {
if (!dest || !src) return;
return merge(dest, src, function (a, b) {

View File

@ -1,4 +1,3 @@
import * as t from "babel-types";
/**
@ -7,7 +6,11 @@ import * as t from "babel-types";
* - Wrap `Program` node with a `File` node.
*/
export default function (ast, comments, tokens) {
export default function (
ast: Object,
comments?: Array<Object>,
tokens?: Array<Object>,
) {
if (ast) {
if (ast.type === "Program") {
return t.file(ast, comments || [], tokens || []);

View File

@ -3,7 +3,7 @@ import path from "path";
let relativeModules = {};
export default function (loc, relative = process.cwd()) {
export default function (loc: string, relative: string = process.cwd()): ?string {
// we're in the browser, probably
if (typeof Module === "object") return null;

View File

@ -4,11 +4,13 @@ export default class Store extends Map {
this.dynamicData = {};
}
dynamicData: Object;
setDynamic(key, fn) {
this.dynamicData[key] = fn;
}
get(key) {
get(key: string): any {
if (this.has(key)) {
return super.get(key);
} else {

View File

@ -82,7 +82,10 @@ function buildHelpers(body, namespace, whitelist) {
));
});
}
export default function (whitelist, outputType = "global") {
export default function (
whitelist?: Array<string>,
outputType: "global" | "umd" | "var" = "global",
) {
let namespace = t.identifier("babelHelpers");
let builder = function (body) {

View File

@ -1,13 +1,14 @@
/* global BabelFileResult, BabelParserOptions, BabelFileMetadata */
/* eslint max-len: 0 */
import getHelper from "babel-helpers";
import * as metadataVisitor from "./metadata";
import convertSourceMap from "convert-source-map";
import OptionManager from "./options/option-manager";
import type Pipeline from "../pipeline";
import PluginPass from "../plugin-pass";
import shebangRegex from "shebang-regex";
import { NodePath, Hub } from "babel-traverse";
import { NodePath, Hub, Scope } from "babel-traverse";
import sourceMap from "source-map";
import generate from "babel-generator";
import codeFrame from "babel-code-frame";
@ -39,7 +40,7 @@ let errorVisitor = {
};
export default class File extends Store {
constructor(opts = {}, pipeline) {
constructor(opts: Object = {}, pipeline: Pipeline) {
super();
this.pipeline = pipeline;
@ -100,9 +101,30 @@ export default class File extends Store {
this.hub = new Hub(this);
}
static helpers: Array<string>;
pluginVisitors: Array<Object>;
pluginPasses: Array<PluginPass>;
pipeline: Pipeline;
parserOpts: BabelParserOptions;
log: Logger;
opts: Object;
dynamicImportTypes: Object;
dynamicImportIds: Object;
dynamicImports: Array<Object>;
declarations: Object;
usedHelpers: Object;
path: NodePath;
ast: Object;
scope: Scope;
metadata: BabelFileMetadata;
hub: Hub;
code: string;
shebang: string;
getMetadata() {
let has = false;
for (let node of this.ast.program.body) {
for (let node of (this.ast.program.body: Array<Object>)) {
if (t.isModuleDeclaration(node)) {
has = true;
break;
@ -157,7 +179,7 @@ export default class File extends Store {
return;
}
let plugins = opts.plugins.concat(INTERNAL_PLUGINS);
let plugins: Array<[PluginPass, Object]> = opts.plugins.concat(INTERNAL_PLUGINS);
let currentPluginVisitors = [];
let currentPluginPasses = [];
@ -177,7 +199,7 @@ export default class File extends Store {
this.pluginPasses.push(currentPluginPasses);
}
getModuleName() {
getModuleName(): ?string {
let opts = this.opts;
if (!opts.moduleIds) {
return null;
@ -221,13 +243,13 @@ export default class File extends Store {
}
}
resolveModuleSource(source) {
resolveModuleSource(source: string): string {
let resolveModuleSource = this.opts.resolveModuleSource;
if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
return source;
}
addImport(source, imported, name = imported) {
addImport(source: string, imported: string, name?: string = imported): Object {
let alias = `${source}:${imported}`;
let id = this.dynamicImportIds[alias];
@ -254,7 +276,7 @@ export default class File extends Store {
return id;
}
addHelper(name) {
addHelper(name: string): Object {
let declar = this.declarations[name];
if (declar) return declar;
@ -293,7 +315,11 @@ export default class File extends Store {
return uid;
}
addTemplateObject(helperName, strings, raw) {
addTemplateObject(
helperName: string,
strings: Array<Object>,
raw: Object,
): Object {
// Generate a unique name based on the string literals so we dedupe
// identical strings used in the program.
let stringIds = raw.elements.map(function(string) {
@ -317,7 +343,7 @@ export default class File extends Store {
return uid;
}
buildCodeFrameError(node, msg, Error = SyntaxError) {
buildCodeFrameError(node: Object, msg: string, Error: typeof Error = SyntaxError): Error {
let loc = node && (node.loc || node._loc);
let err = new Error(msg);
@ -339,7 +365,7 @@ export default class File extends Store {
return err;
}
mergeSourceMap(map) {
mergeSourceMap(map: Object) {
let inputMap = this.opts.inputSourceMap;
if (inputMap) {
@ -383,7 +409,7 @@ export default class File extends Store {
}
}
parse(code) {
parse(code: string) {
this.log.debug("Parse start");
let ast = parse(code, this.parserOpts);
this.log.debug("Parse stop");
@ -409,7 +435,7 @@ export default class File extends Store {
this.log.debug("End set AST");
}
transform() {
transform(): BabelFileResult {
// In the "pass per preset" mode, we have grouped passes.
// Otherwise, there is only one plain pluginPasses array.
this.pluginPasses.forEach((pluginPasses, index) => {
@ -423,7 +449,7 @@ export default class File extends Store {
return this.generate();
}
wrap(code, callback) {
wrap(code: string, callback: Function): BabelFileResult {
code = code + "";
try {
@ -462,7 +488,7 @@ export default class File extends Store {
}
}
addCode(code) {
addCode(code: string) {
code = (code || "") + "";
code = this.parseInputSourceMap(code);
this.code = code;
@ -479,7 +505,7 @@ export default class File extends Store {
return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
}
call(key, pluginPasses) {
call(key: "pre" | "post", pluginPasses: Array<PluginPass>) {
for (let pass of pluginPasses) {
let plugin = pass.plugin;
let fn = plugin[key];
@ -487,7 +513,7 @@ export default class File extends Store {
}
}
parseInputSourceMap(code) {
parseInputSourceMap(code: string): string {
let opts = this.opts;
if (opts.inputSourceMap !== false) {
@ -509,7 +535,7 @@ export default class File extends Store {
}
}
makeResult({ code, map, ast, ignored }) {
makeResult({ code, map, ast, ignored }: BabelFileResult): BabelFileResult {
let result = {
metadata: null,
options: this.opts,
@ -534,11 +560,11 @@ export default class File extends Store {
return result;
}
generate() {
generate(): BabelFileResult {
let opts = this.opts;
let ast = this.ast;
let result = { ast };
let result: BabelFileResult = { ast };
if (!opts.code) return this.makeResult(result);
this.log.debug("Generation start");

View File

@ -1,3 +1,4 @@
import type File from "./index";
import buildDebug from "debug/node";
let verboseDebug = buildDebug("babel:verbose");
@ -6,26 +7,29 @@ let generalDebug = buildDebug("babel");
let seenDeprecatedMessages = [];
export default class Logger {
constructor(file, filename) {
constructor(file: File, filename: string) {
this.filename = filename;
this.file = file;
}
_buildMessage(msg) {
filename: string;
file: File;
_buildMessage(msg: string): string {
let parts = `[BABEL] ${this.filename}`;
if (msg) parts += `: ${msg}`;
return parts;
}
warn(msg) {
warn(msg: string) {
console.warn(this._buildMessage(msg));
}
error(msg, Constructor = Error) {
error(msg: string, Constructor: typeof Error = Error): Error {
throw new Constructor(this._buildMessage(msg));
}
deprecate(msg) {
deprecate(msg: string) {
if (this.file.opts && this.file.opts.suppressDeprecationMessages) return;
msg = this._buildMessage(msg);
@ -39,15 +43,15 @@ export default class Logger {
console.error(msg);
}
verbose(msg) {
verbose(msg: string) {
if (verboseDebug.enabled) verboseDebug(this._buildMessage(msg));
}
debug(msg) {
debug(msg: string) {
if (generalDebug.enabled) generalDebug(this._buildMessage(msg));
}
deopt(node, msg) {
deopt(node: Object, msg: string) {
this.debug(msg);
}
}

View File

@ -21,7 +21,7 @@ export let ImportDeclaration = {
specifiers
});
for (let specifier of path.get("specifiers")) {
for (let specifier of (path.get("specifiers"): Array<Object>)) {
let local = specifier.node.local.name;
if (specifier.isImportDefaultSpecifier()) {
@ -77,7 +77,7 @@ export function ExportDeclaration(path, file) {
}
if (path.isExportNamedDeclaration() && node.specifiers) {
for (let specifier of node.specifiers) {
for (let specifier of (node.specifiers: Array<Object>)) {
let exported = specifier.exported.name;
exports.exported.push(exported);

View File

@ -1,10 +1,9 @@
import * as parsers from "./parsers";
import config from "./config";
export { config };
export function normaliseOptions(options = {}) {
export function normaliseOptions(options: Object = {}): Object {
for (let key in options) {
let val = options[key];
if (val == null) continue;

View File

@ -1,6 +1,7 @@
/* eslint max-len: 0 */
import * as context from "../../../api/node";
import type Logger from "../logger";
import Plugin from "../../plugin";
import * as messages from "babel-messages";
import { normaliseOptions } from "./index";
@ -32,19 +33,49 @@ function exists(filename) {
}
}
type PluginObject = {
pre?: Function;
post?: Function;
manipulateOptions?: Function;
visitor: ?{
[key: string]: Function | {
enter?: Function | Array<Function>;
exit?: Function | Array<Function>;
}
};
};
type MergeOptions = {
options?: Object,
extending?: Object,
alias: string,
loc?: string,
dirname?: string
};
export default class OptionManager {
constructor(log) {
constructor(log?: Logger) {
this.resolvedConfigs = [];
this.options = OptionManager.createBareOptions();
this.log = log;
}
resolvedConfigs: Array<string>;
options: Object;
log: ?Logger;
static memoisedPlugins: Array<{
container: Function;
plugin: Plugin;
}>;
static memoisePluginContainer(fn, loc, i, alias) {
for (let cache of OptionManager.memoisedPlugins) {
for (let cache of (OptionManager.memoisedPlugins: Array<Object>)) {
if (cache.container === fn) return cache.plugin;
}
let obj;
let obj: ?PluginObject;
if (typeof fn === "function") {
obj = fn(context);
@ -125,7 +156,7 @@ export default class OptionManager {
});
}
addConfig(loc, key, json = json5) {
addConfig(loc: string, key?: string, json = json5): boolean {
if (this.resolvedConfigs.indexOf(loc) >= 0) {
return false;
}
@ -167,7 +198,7 @@ export default class OptionManager {
alias,
loc,
dirname
}) {
}: MergeOptions) {
alias = alias || "foreign";
if (!rawOpts) return;
@ -272,7 +303,7 @@ export default class OptionManager {
* Merges all presets into the main options in case we are not in the
* "pass per preset" mode. Otherwise, options are calculated per preset.
*/
mergePresets(presets, dirname) {
mergePresets(presets: Array<string | Object>, dirname: string) {
this.resolvePresets(presets, dirname, (presetOpts, presetLoc) => {
this.mergeOptions({
options: presetOpts,
@ -287,7 +318,7 @@ export default class OptionManager {
* Resolves presets options which can be either direct object data,
* or a module name to require.
*/
resolvePresets(presets, dirname, onResolve) {
resolvePresets(presets: Array<string | Object>, dirname: string, onResolve?) {
return presets.map((val) => {
if (typeof val === "string") {
let presetLoc = resolve(`babel-preset-${val}`, dirname) || resolve(val, dirname);
@ -376,7 +407,7 @@ export default class OptionManager {
}
}
init(opts = {}) {
init(opts: Object = {}): Object {
let filename = opts.filename;
// resolve all .babelrc files

View File

@ -1,18 +1,16 @@
import slash from "slash";
import * as util from "../../../util";
export let filename = slash;
export function boolean(val) {
export function boolean(val: any): boolean {
return !!val;
}
export function booleanString(val) {
export function booleanString(val: any): boolean | any {
return util.booleanify(val);
}
export function list(val) {
export function list(val: any): Array<string> {
return util.list(val);
}

View File

@ -1,4 +1,3 @@
import Plugin from "../plugin";
import sortBy from "lodash/collection/sortBy";

View File

@ -1,15 +1,16 @@
/* global BabelFileResult, BabelFileMetadata */
import normalizeAst from "../helpers/normalize-ast";
import Plugin from "./plugin";
import File from "./file";
export default class Pipeline {
lint(code, opts = {}) {
lint(code: string, opts?: Object = {}): BabelFileResult {
opts.code = false;
opts.mode = "lint";
return this.transform(code, opts);
}
pretransform(code, opts) {
pretransform(code: string, opts?: Object): BabelFileResult {
let file = new File(opts, this);
return file.wrap(code, function () {
file.addCode(code);
@ -18,7 +19,7 @@ export default class Pipeline {
});
}
transform(code, opts) {
transform(code: string, opts?: Object): BabelFileResult {
let file = new File(opts, this);
return file.wrap(code, function () {
file.addCode(code);
@ -27,7 +28,7 @@ export default class Pipeline {
});
}
analyse(code, opts = {}, visitor) {
analyse(code: string, opts: Object = {}, visitor?: Object): ?BabelFileMetadata {
opts.code = false;
if (visitor) {
opts.plugins = opts.plugins || [];
@ -36,7 +37,7 @@ export default class Pipeline {
return this.transform(code, opts).metadata;
}
transformFromAst(ast, code, opts) {
transformFromAst(ast: Object, code: string, opts: Object): BabelFileResult {
ast = normalizeAst(ast);
let file = new File(opts, this);

View File

@ -1,14 +1,20 @@
import type Plugin from "./plugin";
import Store from "../store";
import traverse from "babel-traverse";
import File from "./file";
export default class PluginPass extends Store {
constructor(file, plugin, options = {}) {
constructor(file: File, plugin: Plugin, options: Object = {}) {
super();
this.plugin = plugin;
this.file = file;
this.opts = options;
}
plugin: Plugin;
file: File;
opts: Object;
transform() {
let file = this.file;
file.log.debug(`Start transformer ${this.key}`);

View File

@ -10,7 +10,7 @@ import clone from "lodash/lang/clone";
const GLOBAL_VISITOR_PROPS = ["enter", "exit"];
export default class Plugin extends Store {
constructor(plugin, key) {
constructor(plugin: Object, key?: string) {
super();
this.initialized = false;
@ -23,6 +23,13 @@ export default class Plugin extends Store {
this.visitor = this.normaliseVisitor(clone(this.take("visitor")) || {});
}
initialized: boolean;
raw: Object;
manipulateOptions: ?Function;
post: ?Function;
pre: ?Function;
visitor: Object;
take(key) {
let val = this.raw[key];
delete this.raw[key];
@ -33,7 +40,7 @@ export default class Plugin extends Store {
if (!target[key]) return this[key];
if (!this[key]) return target[key];
let fns = [target[key], this[key]];
let fns: Array<?Function> = [target[key], this[key]];
return function (...args) {
let val;
@ -47,7 +54,7 @@ export default class Plugin extends Store {
};
}
maybeInherit(loc) {
maybeInherit(loc: string) {
let inherits = this.take("inherits");
if (!inherits) return;
@ -64,7 +71,7 @@ export default class Plugin extends Store {
* position on disk and how it was specified.
*/
init(loc, i) {
init(loc: string, i: number) {
if (this.initialized) return;
this.initialized = true;
@ -75,7 +82,7 @@ export default class Plugin extends Store {
}
}
normaliseVisitor(visitor) {
normaliseVisitor(visitor: Object): Object {
for (let key of GLOBAL_VISITOR_PROPS) {
if (visitor[key]) {
throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. Please target individual nodes.");

View File

@ -1,4 +1,3 @@
import escapeRegExp from "lodash/string/escapeRegExp";
import startsWith from "lodash/string/startsWith";
import isBoolean from "lodash/lang/isBoolean";
@ -15,7 +14,7 @@ export { inherits, inspect } from "util";
* Test if a filename ends with a compilable extension.
*/
export function canCompile(filename, altExts) {
export function canCompile(filename: string, altExts?: Array<string>): boolean {
let exts = altExts || canCompile.EXTENSIONS;
let ext = path.extname(filename);
return contains(exts, ext);
@ -31,7 +30,7 @@ canCompile.EXTENSIONS = [".js", ".jsx", ".es6", ".es"];
* Create an array from any value, splitting strings by ",".
*/
export function list(val) {
export function list(val?: string): Array<string> {
if (!val) {
return [];
} else if (Array.isArray(val)) {
@ -47,7 +46,7 @@ export function list(val) {
* Create a RegExp from a string, array, or regexp.
*/
export function regexify(val) {
export function regexify(val: any): RegExp {
if (!val) {
return new RegExp(/.^/);
}
@ -79,7 +78,7 @@ export function regexify(val) {
* Create an array from a boolean, string, or array, mapped by and optional function.
*/
export function arrayify(val, mapFn) {
export function arrayify(val: any, mapFn?: Function): Array<any> {
if (!val) return [];
if (isBoolean(val)) return arrayify([val], mapFn);
if (isString(val)) return arrayify(list(val), mapFn);
@ -96,7 +95,7 @@ export function arrayify(val, mapFn) {
* Makes boolean-like strings into booleans.
*/
export function booleanify(val) {
export function booleanify(val: any): boolean | any {
if (val === "true" || val == 1) {
return true;
}
@ -112,7 +111,11 @@ export function booleanify(val) {
* Tests if a filename should be ignored based on "ignore" and "only" options.
*/
export function shouldIgnore(filename, ignore = [], only) {
export function shouldIgnore(
filename: string,
ignore: Array<RegExp | Function> = [],
only?: Array<RegExp | Function>,
): boolean {
filename = slash(filename);
if (only) {
@ -134,7 +137,7 @@ export function shouldIgnore(filename, ignore = [], only) {
* Otherwise returns result of matching pattern Regex with filename.
*/
function _shouldIgnore(pattern, filename) {
function _shouldIgnore(pattern: Function | RegExp, filename: string) {
if (typeof pattern === "function") {
return pattern(filename);
} else {

View File

@ -1,4 +1,4 @@
import type Position from "./position";
import repeating from "repeating";
import trimRight from "trim-right";
@ -7,7 +7,7 @@ import trimRight from "trim-right";
*/
export default class Buffer {
constructor(position, format) {
constructor(position: Position, format: Object) {
this.printedCommentStarts = {};
this.parenPushNewlineState = null;
this.position = position;
@ -21,11 +21,19 @@ export default class Buffer {
this.last = "";
}
printedCommentStarts: Object;
parenPushNewlineState: ?Object;
position: Position;
_indent: number;
format: Object;
buf: string;
last: string;
/**
* Description
*/
catchUp(node) {
catchUp(node: Object) {
// catch up to this nodes newline if we're behind
if (node.loc && this.format.retainLines && this.buf) {
while (this.position.line < node.loc.start.line) {
@ -38,7 +46,7 @@ export default class Buffer {
* Get the current trimmed buffer.
*/
get() {
get(): string {
return trimRight(this.buf);
}
@ -46,7 +54,7 @@ export default class Buffer {
* Get the current indent.
*/
getIndent() {
getIndent(): string {
if (this.format.compact || this.format.concise) {
return "";
} else {
@ -58,7 +66,7 @@ export default class Buffer {
* Get the current indent size.
*/
indentSize() {
indentSize(): number {
return this.getIndent().length;
}
@ -110,7 +118,7 @@ export default class Buffer {
* Add a keyword to the buffer.
*/
keyword(name) {
keyword(name: string) {
this.push(name);
this.space();
}
@ -119,7 +127,7 @@ export default class Buffer {
* Add a space to the buffer unless it is compact (override with force).
*/
space(force) {
space(force?: boolean) {
if (!force && this.format.compact) return;
if (force || this.buf && !this.isLast(" ") && !this.isLast("\n")) {
@ -131,12 +139,12 @@ export default class Buffer {
* Remove the last character.
*/
removeLast(cha) {
removeLast(cha: string) {
if (this.format.compact) return;
return this._removeLast(cha);
}
_removeLast(cha) {
_removeLast(cha: string) {
if (!this._isLast(cha)) return;
this.buf = this.buf.slice(0, -1);
this.last = this.buf[this.buf.length - 1];
@ -159,7 +167,7 @@ export default class Buffer {
* `undefined` will be returned and not `foo` due to the terminator.
*/
startTerminatorless() {
startTerminatorless(): Object {
return this.parenPushNewlineState = {
printed: false
};
@ -169,7 +177,7 @@ export default class Buffer {
* Print an ending parentheses if a starting one has been printed.
*/
endTerminatorless(state) {
endTerminatorless(state: Object) {
if (state.printed) {
this.dedent();
this.newline();
@ -182,7 +190,7 @@ export default class Buffer {
* Strips multiple newlines if removeLast is true.
*/
newline(i, removeLast) {
newline(i?: boolean | number, removeLast?: boolean) {
if (this.format.retainLines || this.format.compact) return;
if (this.format.concise) {
@ -226,7 +234,7 @@ export default class Buffer {
* Push a string to the buffer, maintaining indentation and newlines.
*/
push(str, noIndent) {
push(str: string, noIndent?: boolean) {
if (!this.format.compact && this._indent && !noIndent && str !== "\n") {
// we have an indent level and we aren't pushing a newline
let indent = this.getIndent();
@ -245,7 +253,7 @@ export default class Buffer {
* Push a string to the buffer.
*/
_push(str) {
_push(str: string): void {
// see startTerminatorless() instance method
let parenPushNewlineState = this.parenPushNewlineState;
if (parenPushNewlineState) {
@ -278,7 +286,7 @@ export default class Buffer {
* Test if the buffer ends with a string.
*/
endsWith(str) {
endsWith(str: string): boolean {
if (str.length === 1) {
return this.last === str;
} else {
@ -290,12 +298,12 @@ export default class Buffer {
* Test if a character is last in the buffer.
*/
isLast(cha) {
isLast(cha: string): boolean {
if (this.format.compact) return false;
return this._isLast(cha);
}
_isLast(cha) {
_isLast(cha: string): boolean {
let last = this.last;
if (Array.isArray(cha)) {

View File

@ -1,9 +1,8 @@
export function File(node) {
export function File(node: Object) {
this.print(node.program, node);
}
export function Program(node) {
export function Program(node: Object) {
this.printInnerComments(node, false);
this.printSequence(node.directives, node);
@ -12,7 +11,7 @@ export function Program(node) {
this.printSequence(node.body, node);
}
export function BlockStatement(node) {
export function BlockStatement(node: Object) {
this.push("{");
this.printInnerComments(node);
if (node.body.length) {
@ -31,11 +30,11 @@ export function BlockStatement(node) {
export function Noop() {}
export function Directive(node) {
export function Directive(node: Object) {
this.print(node.value, node);
this.semicolon();
}
export function DirectiveLiteral(node) {
export function DirectiveLiteral(node: Object) {
this.push(this._stringLiteral(node.value));
}

View File

@ -1,5 +1,4 @@
export function ClassDeclaration(node) {
export function ClassDeclaration(node: Object) {
this.printJoin(node.decorators, node, { separator: "" });
this.push("class");
@ -27,7 +26,7 @@ export function ClassDeclaration(node) {
export { ClassDeclaration as ClassExpression };
export function ClassBody(node) {
export function ClassBody(node: Object) {
this.push("{");
this.printInnerComments(node);
if (node.body.length === 0) {
@ -43,7 +42,7 @@ export function ClassBody(node) {
}
}
export function ClassProperty(node) {
export function ClassProperty(node: Object) {
this.printJoin(node.decorators, node, { separator: "" });
if (node.static) this.push("static ");
@ -58,7 +57,7 @@ export function ClassProperty(node) {
this.semicolon();
}
export function ClassMethod(node) {
export function ClassMethod(node: Object) {
this.printJoin(node.decorators, node, { separator: "" });
if (node.static) {

View File

@ -9,7 +9,7 @@ const SCIENTIFIC_NOTATION = /e/i;
const ZERO_DECIMAL_INTEGER = /\.0+$/;
const NON_DECIMAL_LITERAL = /^0[box]/;
export function UnaryExpression(node) {
export function UnaryExpression(node: Object) {
let needsSpace = /[a-z]$/.test(node.operator);
let arg = node.argument;
@ -26,19 +26,19 @@ export function UnaryExpression(node) {
this.print(node.argument, node);
}
export function DoExpression(node) {
export function DoExpression(node: Object) {
this.push("do");
this.space();
this.print(node.body, node);
}
export function ParenthesizedExpression(node) {
export function ParenthesizedExpression(node: Object) {
this.push("(");
this.print(node.expression, node);
this.push(")");
}
export function UpdateExpression(node) {
export function UpdateExpression(node: Object) {
if (node.prefix) {
this.push(node.operator);
this.print(node.argument, node);
@ -48,7 +48,7 @@ export function UpdateExpression(node) {
}
}
export function ConditionalExpression(node) {
export function ConditionalExpression(node: Object) {
this.print(node.test, node);
this.space();
this.push("?");
@ -60,7 +60,7 @@ export function ConditionalExpression(node) {
this.print(node.alternate, node);
}
export function NewExpression(node, parent) {
export function NewExpression(node: Object, parent: Object) {
this.push("new ");
this.print(node.callee, node);
if (node.arguments.length === 0 && this.format.minified &&
@ -73,7 +73,7 @@ export function NewExpression(node, parent) {
this.push(")");
}
export function SequenceExpression(node) {
export function SequenceExpression(node: Object) {
this.printList(node.expressions, node);
}
@ -85,13 +85,13 @@ export function Super() {
this.push("super");
}
export function Decorator(node) {
export function Decorator(node: Object) {
this.push("@");
this.print(node.expression, node);
this.newline();
}
export function CallExpression(node) {
export function CallExpression(node: Object) {
this.print(node.callee, node);
if (node.loc) this.printAuxAfterComment();
@ -116,8 +116,8 @@ export function CallExpression(node) {
this.push(")");
}
function buildYieldAwait(keyword) {
return function (node) {
function buildYieldAwait(keyword: string) {
return function (node: Object) {
this.push(keyword);
if (node.delegate) {
@ -141,12 +141,12 @@ export function EmptyStatement() {
this.semicolon();
}
export function ExpressionStatement(node) {
export function ExpressionStatement(node: Object) {
this.print(node.expression, node);
this.semicolon();
}
export function AssignmentPattern(node) {
export function AssignmentPattern(node: Object) {
this.print(node.left, node);
this.space();
this.push("=");
@ -154,7 +154,7 @@ export function AssignmentPattern(node) {
this.print(node.right, node);
}
export function AssignmentExpression(node, parent) {
export function AssignmentExpression(node: Object, parent: Object) {
// Somewhere inside a for statement `init` node but doesn't usually
// needs a paren except for `in` expressions: `for (a in b ? a : b;;)`
let parens = this._inForStatementInitCounter && node.operator === "in" &&
@ -195,7 +195,7 @@ export function AssignmentExpression(node, parent) {
}
}
export function BindExpression(node) {
export function BindExpression(node: Object) {
this.print(node.object, node);
this.push("::");
this.print(node.callee, node);
@ -206,7 +206,7 @@ export {
AssignmentExpression as LogicalExpression
};
export function MemberExpression(node) {
export function MemberExpression(node: Object) {
this.print(node.object, node);
if (!node.computed && t.isMemberExpression(node.property)) {
@ -239,7 +239,7 @@ export function MemberExpression(node) {
}
}
export function MetaProperty(node) {
export function MetaProperty(node: Object) {
this.print(node.meta, node);
this.push(".");
this.print(node.property, node);

View File

@ -6,7 +6,7 @@ export function AnyTypeAnnotation() {
this.push("any");
}
export function ArrayTypeAnnotation(node) {
export function ArrayTypeAnnotation(node: Object) {
this.print(node.elementType, node);
this.push("[");
this.push("]");
@ -16,7 +16,7 @@ export function BooleanTypeAnnotation() {
this.push("bool");
}
export function BooleanLiteralTypeAnnotation(node) {
export function BooleanLiteralTypeAnnotation(node: Object) {
this.push(node.value ? "true" : "false");
}
@ -24,36 +24,36 @@ export function NullLiteralTypeAnnotation() {
this.push("null");
}
export function DeclareClass(node) {
export function DeclareClass(node: Object) {
this.push("declare class ");
this._interfaceish(node);
}
export function DeclareFunction(node) {
export function DeclareFunction(node: Object) {
this.push("declare function ");
this.print(node.id, node);
this.print(node.id.typeAnnotation.typeAnnotation, node);
this.semicolon();
}
export function DeclareInterface(node) {
export function DeclareInterface(node: Object) {
this.push("declare ");
this.InterfaceDeclaration(node);
}
export function DeclareModule(node) {
export function DeclareModule(node: Object) {
this.push("declare module ");
this.print(node.id, node);
this.space();
this.print(node.body, node);
}
export function DeclareTypeAlias(node) {
export function DeclareTypeAlias(node: Object) {
this.push("declare ");
this.TypeAlias(node);
}
export function DeclareVariable(node) {
export function DeclareVariable(node: Object) {
this.push("declare var ");
this.print(node.id, node);
this.print(node.id.typeAnnotation, node);
@ -64,7 +64,7 @@ export function ExistentialTypeParam() {
this.push("*");
}
export function FunctionTypeAnnotation(node, parent) {
export function FunctionTypeAnnotation(node: Object, parent: Object) {
this.print(node.typeParameters, node);
this.push("(");
this.printList(node.params, node);
@ -92,7 +92,7 @@ export function FunctionTypeAnnotation(node, parent) {
this.print(node.returnType, node);
}
export function FunctionTypeParam(node) {
export function FunctionTypeParam(node: Object) {
this.print(node.name, node);
if (node.optional) this.push("?");
this.push(":");
@ -100,14 +100,14 @@ export function FunctionTypeParam(node) {
this.print(node.typeAnnotation, node);
}
export function InterfaceExtends(node) {
export function InterfaceExtends(node: Object) {
this.print(node.id, node);
this.print(node.typeParameters, node);
}
export { InterfaceExtends as ClassImplements, InterfaceExtends as GenericTypeAnnotation };
export function _interfaceish(node) {
export function _interfaceish(node: Object) {
this.print(node.id, node);
this.print(node.typeParameters, node);
if (node.extends.length) {
@ -122,12 +122,12 @@ export function _interfaceish(node) {
this.print(node.body, node);
}
export function InterfaceDeclaration(node) {
export function InterfaceDeclaration(node: Object) {
this.push("interface ");
this._interfaceish(node);
}
export function IntersectionTypeAnnotation(node) {
export function IntersectionTypeAnnotation(node: Object) {
this.printJoin(node.types, node, { separator: " & " });
}
@ -135,7 +135,7 @@ export function MixedTypeAnnotation() {
this.push("mixed");
}
export function NullableTypeAnnotation(node) {
export function NullableTypeAnnotation(node: Object) {
this.push("?");
this.print(node.typeAnnotation, node);
}
@ -146,7 +146,7 @@ export function NumberTypeAnnotation() {
this.push("number");
}
export function StringLiteralTypeAnnotation(node) {
export function StringLiteralTypeAnnotation(node: Object) {
this.push(this._stringLiteral(node.value));
}
@ -158,18 +158,18 @@ export function ThisTypeAnnotation() {
this.push("this");
}
export function TupleTypeAnnotation(node) {
export function TupleTypeAnnotation(node: Object) {
this.push("[");
this.printJoin(node.types, node, { separator: ", " });
this.push("]");
}
export function TypeofTypeAnnotation(node) {
export function TypeofTypeAnnotation(node: Object) {
this.push("typeof ");
this.print(node.argument, node);
}
export function TypeAlias(node) {
export function TypeAlias(node: Object) {
this.push("type ");
this.print(node.id, node);
this.print(node.typeParameters, node);
@ -180,18 +180,18 @@ export function TypeAlias(node) {
this.semicolon();
}
export function TypeAnnotation(node) {
export function TypeAnnotation(node: Object) {
this.push(":");
this.space();
if (node.optional) this.push("?");
this.print(node.typeAnnotation, node);
}
export function TypeParameterInstantiation(node) {
export function TypeParameterInstantiation(node: Object) {
this.push("<");
this.printJoin(node.params, node, {
separator: ", ",
iterator: (node) => {
iterator: (node: Object) => {
this.print(node.typeAnnotation, node);
}
});
@ -200,7 +200,7 @@ export function TypeParameterInstantiation(node) {
export { TypeParameterInstantiation as TypeParameterDeclaration };
export function ObjectTypeAnnotation(node) {
export function ObjectTypeAnnotation(node: Object) {
this.push("{");
let props = node.properties.concat(node.callProperties, node.indexers);
@ -224,12 +224,12 @@ export function ObjectTypeAnnotation(node) {
this.push("}");
}
export function ObjectTypeCallProperty(node) {
export function ObjectTypeCallProperty(node: Object) {
if (node.static) this.push("static ");
this.print(node.value, node);
}
export function ObjectTypeIndexer(node) {
export function ObjectTypeIndexer(node: Object) {
if (node.static) this.push("static ");
this.push("[");
this.print(node.id, node);
@ -242,7 +242,7 @@ export function ObjectTypeIndexer(node) {
this.print(node.value, node);
}
export function ObjectTypeProperty(node) {
export function ObjectTypeProperty(node: Object) {
if (node.static) this.push("static ");
this.print(node.key, node);
if (node.optional) this.push("?");
@ -253,17 +253,17 @@ export function ObjectTypeProperty(node) {
this.print(node.value, node);
}
export function QualifiedTypeIdentifier(node) {
export function QualifiedTypeIdentifier(node: Object) {
this.print(node.qualification, node);
this.push(".");
this.print(node.id, node);
}
export function UnionTypeAnnotation(node) {
export function UnionTypeAnnotation(node: Object) {
this.printJoin(node.types, node, { separator: " | " });
}
export function TypeCastExpression(node) {
export function TypeCastExpression(node: Object) {
this.push("(");
this.print(node.expression, node);
this.print(node.typeAnnotation, node);

View File

@ -1,6 +1,4 @@
export function JSXAttribute(node) {
export function JSXAttribute(node: Object) {
this.print(node.name, node);
if (node.value) {
this.push("=");
@ -8,45 +6,45 @@ export function JSXAttribute(node) {
}
}
export function JSXIdentifier(node) {
export function JSXIdentifier(node: Object) {
this.push(node.name);
}
export function JSXNamespacedName(node) {
export function JSXNamespacedName(node: Object) {
this.print(node.namespace, node);
this.push(":");
this.print(node.name, node);
}
export function JSXMemberExpression(node) {
export function JSXMemberExpression(node: Object) {
this.print(node.object, node);
this.push(".");
this.print(node.property, node);
}
export function JSXSpreadAttribute(node) {
export function JSXSpreadAttribute(node: Object) {
this.push("{...");
this.print(node.argument, node);
this.push("}");
}
export function JSXExpressionContainer(node) {
export function JSXExpressionContainer(node: Object) {
this.push("{");
this.print(node.expression, node);
this.push("}");
}
export function JSXText(node) {
export function JSXText(node: Object) {
this.push(node.value, true);
}
export function JSXElement(node) {
export function JSXElement(node: Object) {
let open = node.openingElement;
this.print(open, node);
if (open.selfClosing) return;
this.indent();
for (let child of node.children) {
for (let child of (node.children: Array<Object>)) {
this.print(child, node);
}
this.dedent();
@ -54,7 +52,7 @@ export function JSXElement(node) {
this.print(node.closingElement, node);
}
export function JSXOpeningElement(node) {
export function JSXOpeningElement(node: Object) {
this.push("<");
this.print(node.name, node);
if (node.attributes.length > 0) {
@ -64,7 +62,7 @@ export function JSXOpeningElement(node) {
this.push(node.selfClosing ? " />" : ">");
}
export function JSXClosingElement(node) {
export function JSXClosingElement(node: Object) {
this.push("</");
this.print(node.name, node);
this.push(">");

View File

@ -1,8 +1,6 @@
import * as t from "babel-types";
export function _params(node) {
export function _params(node: Object) {
this.print(node.typeParameters, node);
this.push("(");
this.printList(node.params, node, {
@ -18,9 +16,9 @@ export function _params(node) {
}
}
export function _method(node) {
export function _method(node: Object) {
let kind = node.kind;
let key = node.key;
let key = node.key;
if (kind === "method" || kind === "init") {
if (node.generator) {
@ -47,7 +45,7 @@ export function _method(node) {
this.print(node.body, node);
}
export function FunctionExpression(node) {
export function FunctionExpression(node: Object) {
if (node.async) this.push("async ");
this.push("function");
if (node.generator) this.push("*");
@ -66,7 +64,7 @@ export function FunctionExpression(node) {
export { FunctionExpression as FunctionDeclaration };
export function ArrowFunctionExpression(node) {
export function ArrowFunctionExpression(node: Object) {
if (node.async) this.push("async ");
if (node.params.length === 1 && t.isIdentifier(node.params[0])) {

View File

@ -1,7 +1,6 @@
import * as t from "babel-types";
export function ImportSpecifier(node) {
export function ImportSpecifier(node: Object) {
this.print(node.imported, node);
if (node.local && node.local.name !== node.imported.name) {
this.push(" as ");
@ -9,15 +8,15 @@ export function ImportSpecifier(node) {
}
}
export function ImportDefaultSpecifier(node) {
export function ImportDefaultSpecifier(node: Object) {
this.print(node.local, node);
}
export function ExportDefaultSpecifier(node) {
export function ExportDefaultSpecifier(node: Object) {
this.print(node.exported, node);
}
export function ExportSpecifier(node) {
export function ExportSpecifier(node: Object) {
this.print(node.local, node);
if (node.exported && node.local.name !== node.exported.name) {
this.push(" as ");
@ -25,12 +24,12 @@ export function ExportSpecifier(node) {
}
}
export function ExportNamespaceSpecifier(node) {
export function ExportNamespaceSpecifier(node: Object) {
this.push("* as ");
this.print(node.exported, node);
}
export function ExportAllDeclaration(node) {
export function ExportAllDeclaration(node: Object) {
this.push("export *");
if (node.exported) {
this.push(" as ");
@ -51,7 +50,7 @@ export function ExportDefaultDeclaration() {
ExportDeclaration.apply(this, arguments);
}
function ExportDeclaration(node) {
function ExportDeclaration(node: Object) {
if (node.declaration) {
let declar = node.declaration;
this.print(declar, node);
@ -97,7 +96,7 @@ function ExportDeclaration(node) {
this.ensureSemicolon();
}
export function ImportDeclaration(node) {
export function ImportDeclaration(node: Object) {
this.push("import ");
if (node.importKind === "type" || node.importKind === "typeof") {
@ -134,7 +133,7 @@ export function ImportDeclaration(node) {
this.semicolon();
}
export function ImportNamespaceSpecifier(node) {
export function ImportNamespaceSpecifier(node: Object) {
this.push("* as ");
this.print(node.local, node);
}

View File

@ -3,7 +3,7 @@ import * as t from "babel-types";
const NON_ALPHABETIC_UNARY_OPERATORS = t.UPDATE_OPERATORS.concat(t.NUMBER_UNARY_OPERATORS).concat(["!"]);
export function WithStatement(node) {
export function WithStatement(node: Object) {
this.keyword("with");
this.push("(");
this.print(node.object, node);
@ -11,7 +11,7 @@ export function WithStatement(node) {
this.printBlock(node);
}
export function IfStatement(node) {
export function IfStatement(node: Object) {
this.keyword("if");
this.push("(");
this.print(node.test, node);
@ -46,7 +46,7 @@ function getLastStatement(statement) {
return getLastStatement(statement.body);
}
export function ForStatement(node) {
export function ForStatement(node: Object) {
this.keyword("for");
this.push("(");
@ -70,7 +70,7 @@ export function ForStatement(node) {
this.printBlock(node);
}
export function WhileStatement(node) {
export function WhileStatement(node: Object) {
this.keyword("while");
this.push("(");
this.print(node.test, node);
@ -79,7 +79,7 @@ export function WhileStatement(node) {
}
let buildForXStatement = function (op) {
return function (node) {
return function (node: Object) {
this.keyword("for");
this.push("(");
this.print(node.left, node);
@ -93,7 +93,7 @@ let buildForXStatement = function (op) {
export let ForInStatement = buildForXStatement("in");
export let ForOfStatement = buildForXStatement("of");
export function DoWhileStatement(node) {
export function DoWhileStatement(node: Object) {
this.push("do ");
this.print(node.body, node);
this.space();
@ -104,7 +104,7 @@ export function DoWhileStatement(node) {
}
function buildLabelStatement(prefix, key = "label") {
return function (node) {
return function (node: Object) {
this.push(prefix);
let label = node[key];
@ -130,13 +130,13 @@ export let ReturnStatement = buildLabelStatement("return", "argument");
export let BreakStatement = buildLabelStatement("break");
export let ThrowStatement = buildLabelStatement("throw", "argument");
export function LabeledStatement(node) {
export function LabeledStatement(node: Object) {
this.print(node.label, node);
this.push(": ");
this.print(node.body, node);
}
export function TryStatement(node) {
export function TryStatement(node: Object) {
this.keyword("try");
this.print(node.block, node);
this.space();
@ -157,7 +157,7 @@ export function TryStatement(node) {
}
}
export function CatchClause(node) {
export function CatchClause(node: Object) {
this.keyword("catch");
this.push("(");
this.print(node.param, node);
@ -166,7 +166,7 @@ export function CatchClause(node) {
this.print(node.body, node);
}
export function SwitchStatement(node) {
export function SwitchStatement(node: Object) {
this.keyword("switch");
this.push("(");
this.print(node.discriminant, node);
@ -184,7 +184,7 @@ export function SwitchStatement(node) {
this.push("}");
}
export function SwitchCase(node) {
export function SwitchCase(node: Object) {
if (node.test) {
this.push("case ");
this.print(node.test, node);
@ -203,13 +203,13 @@ export function DebuggerStatement() {
this.push("debugger;");
}
export function VariableDeclaration(node, parent) {
export function VariableDeclaration(node: Object, parent: Object) {
this.push(node.kind + " ");
let hasInits = false;
// don't add whitespace to loop heads
if (!t.isFor(parent)) {
for (let declar of node.declarations) {
for (let declar of (node.declarations: Array<Object>)) {
if (declar.init) {
// has an init so let's split it up over multiple lines
hasInits = true;
@ -246,7 +246,7 @@ export function VariableDeclaration(node, parent) {
this.semicolon();
}
export function VariableDeclarator(node) {
export function VariableDeclarator(node: Object) {
this.print(node.id, node);
this.print(node.id.typeAnnotation, node);
if (node.init) {

View File

@ -1,14 +1,13 @@
export function TaggedTemplateExpression(node) {
export function TaggedTemplateExpression(node: Object) {
this.print(node.tag, node);
this.print(node.quasi, node);
}
export function TemplateElement(node) {
export function TemplateElement(node: Object) {
this._push(node.value.raw);
}
export function TemplateLiteral(node) {
export function TemplateLiteral(node: Object) {
this.push("`");
let quasis = node.quasis;

View File

@ -3,11 +3,11 @@
import * as t from "babel-types";
export function Identifier(node) {
export function Identifier(node: Object) {
this.push(node.name);
}
export function RestElement(node) {
export function RestElement(node: Object) {
this.push("...");
this.print(node.argument, node);
}
@ -18,7 +18,7 @@ export {
RestElement as RestProperty,
};
export function ObjectExpression(node) {
export function ObjectExpression(node: Object) {
let props = node.properties;
this.push("{");
@ -35,12 +35,12 @@ export function ObjectExpression(node) {
export { ObjectExpression as ObjectPattern };
export function ObjectMethod(node) {
export function ObjectMethod(node: Object) {
this.printJoin(node.decorators, node, { separator: "" });
this._method(node);
}
export function ObjectProperty(node) {
export function ObjectProperty(node: Object) {
this.printJoin(node.decorators, node, { separator: "" });
if (node.computed) {
@ -70,7 +70,7 @@ export function ObjectProperty(node) {
this.print(node.value, node);
}
export function ArrayExpression(node) {
export function ArrayExpression(node: Object) {
let elems = node.elements;
let len = elems.length;
@ -98,11 +98,11 @@ export function ArrayExpression(node) {
export { ArrayExpression as ArrayPattern };
export function RegExpLiteral(node) {
export function RegExpLiteral(node: Object) {
this.push(`/${node.pattern}/${node.flags}`);
}
export function BooleanLiteral(node) {
export function BooleanLiteral(node: Object) {
this.push(node.value ? "true" : "false");
}
@ -110,15 +110,15 @@ export function NullLiteral() {
this.push("null");
}
export function NumericLiteral(node) {
export function NumericLiteral(node: Object) {
this.push(node.value + "");
}
export function StringLiteral(node, parent) {
export function StringLiteral(node: Object, parent: Object) {
this.push(this._stringLiteral(node.value, parent));
}
export function _stringLiteral(val, parent) {
export function _stringLiteral(val: string, parent: Object): string {
val = JSON.stringify(val);
// escape illegal js but valid json unicode characters

View File

@ -34,6 +34,33 @@ export class CodeGenerator extends Printer {
this.map = new SourceMap(position, opts, code);
}
format: {
shouldPrintComment: (comment: string) => boolean;
retainLines: boolean;
comments: boolean;
auxiliaryCommentBefore: string;
auxiliaryCommentAfter: string;
compact: boolean | "auto";
minified: boolean;
quotes: "single" | "double";
concise: boolean;
indent: {
adjustMultilineComment: boolean;
style: string;
base: number;
}
};
auxiliaryCommentBefore: string;
auxiliaryCommentAfter: string;
whitespace: Whitespace;
position: Position;
map: SourceMap;
comments: Array<Object>;
tokens: Array<Object>;
opts: Object;
ast: Object;
/**
* Normalize generator options, setting defaults.
*
@ -134,7 +161,7 @@ export class CodeGenerator extends Printer {
}
}
export default function (ast, opts, code) {
export default function (ast: Object, opts: Object, code: string): Object {
let gen = new CodeGenerator(ast, opts, code);
return gen.generate();
}

View File

@ -1,4 +1,3 @@
import * as t from "babel-types";
const PRECEDENCE = {
@ -28,13 +27,13 @@ const PRECEDENCE = {
"**": 10
};
export function NullableTypeAnnotation(node, parent) {
export function NullableTypeAnnotation(node: Object, parent: Object): boolean {
return t.isArrayTypeAnnotation(parent);
}
export { NullableTypeAnnotation as FunctionTypeAnnotation };
export function UpdateExpression(node, parent) {
export function UpdateExpression(node: Object, parent: Object): boolean {
if (t.isMemberExpression(parent) && parent.object === node) {
// (foo++).test()
return true;
@ -43,7 +42,7 @@ export function UpdateExpression(node, parent) {
return false;
}
export function ObjectExpression(node, parent, printStack) {
export function ObjectExpression(node: Object, parent: Object, printStack: Array<Object>): boolean {
if (t.isExpressionStatement(parent)) {
// ({ foo: "bar" });
return true;
@ -52,7 +51,7 @@ export function ObjectExpression(node, parent, printStack) {
return isFirstInStatement(printStack, true);
}
export function Binary(node, parent) {
export function Binary(node: Object, parent: Object): boolean {
if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node) {
return true;
}
@ -85,7 +84,7 @@ export function Binary(node, parent) {
return false;
}
export function BinaryExpression(node, parent) {
export function BinaryExpression(node: Object, parent: Object): boolean {
if (node.operator === "in") {
// let i = (1 in []);
if (t.isVariableDeclarator(parent)) {
@ -101,7 +100,7 @@ export function BinaryExpression(node, parent) {
return false;
}
export function SequenceExpression(node, parent) {
export function SequenceExpression(node: Object, parent: Object): boolean {
if (t.isForStatement(parent)) {
// Although parentheses wouldn"t hurt around sequence
// expressions in the head of for loops, traditional style
@ -143,7 +142,7 @@ export function SequenceExpression(node, parent) {
return true;
}
export function YieldExpression(node, parent) {
export function YieldExpression(node: Object, parent: Object): boolean {
return t.isBinary(parent) ||
t.isUnaryLike(parent) ||
t.isCallExpression(parent) ||
@ -153,7 +152,7 @@ export function YieldExpression(node, parent) {
export { YieldExpression as AwaitExpression };
export function ClassExpression(node, parent) {
export function ClassExpression(node: Object, parent: Object): boolean {
// (class {});
if (t.isExpressionStatement(parent)) {
return true;
@ -167,7 +166,7 @@ export function ClassExpression(node, parent) {
return false;
}
export function UnaryLike(node, parent) {
export function UnaryLike(node: Object, parent: Object): boolean {
if (t.isMemberExpression(parent, { object: node })) {
return true;
}
@ -179,7 +178,7 @@ export function UnaryLike(node, parent) {
return false;
}
export function FunctionExpression(node, parent, printStack) {
export function FunctionExpression(node: Object, parent: Object, printStack: Array<Object>): boolean {
// (function () {});
if (t.isExpressionStatement(parent)) {
return true;
@ -193,7 +192,7 @@ export function FunctionExpression(node, parent, printStack) {
return isFirstInStatement(printStack);
}
export function ArrowFunctionExpression(node, parent) {
export function ArrowFunctionExpression(node: Object, parent: Object): boolean {
// export default (function () {});
if (t.isExportDeclaration(parent)) {
return true;
@ -210,7 +209,7 @@ export function ArrowFunctionExpression(node, parent) {
return UnaryLike(node, parent);
}
export function ConditionalExpression(node, parent) {
export function ConditionalExpression(node: Object, parent: Object): boolean {
if (t.isUnaryLike(parent)) {
return true;
}
@ -226,7 +225,7 @@ export function ConditionalExpression(node, parent) {
return UnaryLike(node, parent);
}
export function AssignmentExpression(node) {
export function AssignmentExpression(node: Object): boolean {
if (t.isObjectPattern(node.left)) {
return true;
} else {
@ -236,7 +235,7 @@ export function AssignmentExpression(node) {
// Walk up the print stack to deterimine if our node can come first
// in statement.
function isFirstInStatement(printStack, considerArrow = false) {
function isFirstInStatement(printStack: Array<Object>, considerArrow: bool = false): boolean {
let i = printStack.length - 1;
let node = printStack[i];
i--;

View File

@ -3,6 +3,11 @@ import each from "lodash/collection/each";
import map from "lodash/collection/map";
import * as t from "babel-types";
type WhitespaceObject = {
before?: boolean,
after?: boolean
};
/**
* Crawl a node to test if it contains a CallExpression, a Function, or a Helper.
*
@ -63,7 +68,7 @@ exports.nodes = {
* Test if AssignmentExpression needs whitespace.
*/
AssignmentExpression(node) {
AssignmentExpression(node: Object): ?WhitespaceObject {
let state = crawl(node.right);
if ((state.hasCall && state.hasHelper) || state.hasFunction) {
return {
@ -77,7 +82,7 @@ exports.nodes = {
* Test if SwitchCase needs whitespace.
*/
SwitchCase(node, parent) {
SwitchCase(node: Object, parent: Object): ?WhitespaceObject {
return {
before: node.consequent.length || parent.cases[0] === node
};
@ -87,7 +92,7 @@ exports.nodes = {
* Test if LogicalExpression needs whitespace.
*/
LogicalExpression(node) {
LogicalExpression(node: Object): ?WhitespaceObject {
if (t.isFunction(node.left) || t.isFunction(node.right)) {
return {
after: true
@ -99,7 +104,7 @@ exports.nodes = {
* Test if Literal needs whitespace.
*/
Literal(node) {
Literal(node: Object): ?WhitespaceObject {
if (node.value === "use strict") {
return {
after: true
@ -111,7 +116,7 @@ exports.nodes = {
* Test if CallExpression needs whitespace.
*/
CallExpression(node) {
CallExpression(node: Object): ?WhitespaceObject {
if (t.isFunction(node.callee) || isHelper(node)) {
return {
before: true,
@ -124,7 +129,7 @@ exports.nodes = {
* Test if VariableDeclaration needs whitespace.
*/
VariableDeclaration(node) {
VariableDeclaration(node: Object): ?WhitespaceObject {
for (let i = 0; i < node.declarations.length; i++) {
let declar = node.declarations[i];
@ -147,7 +152,7 @@ exports.nodes = {
* Test if IfStatement needs whitespace.
*/
IfStatement(node) {
IfStatement(node: Object): ?WhitespaceObject {
if (t.isBlockStatement(node.consequent)) {
return {
before: true,
@ -163,7 +168,7 @@ exports.nodes = {
exports.nodes.ObjectProperty =
exports.nodes.ObjectMethod =
exports.nodes.SpreadProperty = function (node, parent) {
exports.nodes.SpreadProperty = function (node: Object, parent): ?WhitespaceObject {
if (parent.properties[0] === node) {
return {
before: true
@ -181,7 +186,7 @@ exports.list = {
* Return VariableDeclaration declarations init properties.
*/
VariableDeclaration(node) {
VariableDeclaration(node: Object): Array<Object> {
return map(node.declarations, "init");
},
@ -189,7 +194,7 @@ exports.list = {
* Return VariableDeclaration elements.
*/
ArrayExpression(node) {
ArrayExpression(node: Object): Array<Object> {
return node.elements;
},
@ -197,7 +202,7 @@ exports.list = {
* Return VariableDeclaration properties.
*/
ObjectExpression(node) {
ObjectExpression(node: Object): Array<Object> {
return node.properties;
}
};

View File

@ -1,9 +1,10 @@
/**
* Track current position in code generation.
*/
export default class Position {
column: number;
line: number;
constructor() {
this.line = 1;
@ -14,7 +15,7 @@ export default class Position {
* Push a string to the current position, mantaining the current line and column.
*/
push(str) {
push(str: string): void {
for (let i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line++;
@ -29,7 +30,7 @@ export default class Position {
* Unshift a string from the current position, mantaining the current line and column.
*/
unshift(str) {
unshift(str: string): void {
for (let i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line--;

View File

@ -120,7 +120,7 @@ export default class Printer extends Buffer {
printMethod.call(this, node, parent);
}
printJoin(nodes, parent, opts = {}) {
printJoin(nodes: ?Array, parent: Object, opts = {}) {
if (!nodes || !nodes.length) return;
let len = nodes.length;
@ -310,7 +310,7 @@ export default class Printer extends Buffer {
this.newline(this.whitespace.getNewlinesAfter(comment));
}
printComments(comments) {
printComments(comments?: Array<Object>) {
if (!comments || !comments.length) return;
for (let comment of comments) {

View File

@ -82,10 +82,10 @@ export default class Whitespace {
* Find a token between start and end.
*/
_findToken(test, start, end) {
_findToken(test: Function, start: number, end: number): number {
if (start >= end) return -1;
const middle = (start + end) >>> 1;
const match = test(this.tokens[middle]);
const match: number = test(this.tokens[middle]);
if (match < 0) {
return this._findToken(test, middle + 1, end);
} else if (match > 0) {

View File

@ -1,6 +1,7 @@
import type { NodePath } from "babel-traverse";
import * as t from "babel-types";
export default function bindifyDecorators(decorators) {
export default function bindifyDecorators(decorators: Array<NodePath>): Array<NodePath> {
for (let decoratorPath of decorators) {
let decorator = decoratorPath.node;
let expression = decorator.expression;

View File

@ -1,7 +1,10 @@
import explode from "babel-helper-explode-assignable-expression";
import * as t from "babel-types";
export default function (opts) {
export default function (opts: {
build: Function;
operator: string;
}): Object {
let visitor = {};
function isAssignment(node) {

View File

@ -1,7 +1,13 @@
import explode from "babel-helper-explode-assignable-expression";
import * as t from "babel-types";
export default function (exports, opts) {
export default function (
exports: Object,
opts: {
build: Function;
is: Function;
},
) {
let buildAssignment = function (left, right) {
return t.assignmentExpression("=", left, right);
};

View File

@ -1,6 +1,14 @@
import esutils from "esutils";
import * as t from "babel-types";
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
pre?: Function; // function called with (state: ElementState) before building attribs
post?: Function; // function called with (state: ElementState) after building attribs
};
export default function (opts) {
let visitor = {};
@ -81,7 +89,7 @@ export default function (opts) {
tagName = tagExpr.value;
}
let state = {
let state: ElementState = {
tagExpr: tagExpr,
tagName: tagName,
args: args

View File

@ -1,4 +1,5 @@
import hoistVariables from "babel-helper-hoist-variables";
import type { NodePath } from "babel-traverse";
import * as t from "babel-types";
let visitor = {
@ -17,7 +18,7 @@ let visitor = {
}
};
export default function (path, scope = path.scope) {
export default function (path: NodePath, scope = path.scope) {
let { node } = path;
let container = t.functionExpression(null, [], node.body, node.generator, node.async);

View File

@ -5,7 +5,7 @@ import each from "lodash/collection/each";
import has from "lodash/object/has";
import * as t from "babel-types";
function toKind(node) {
function toKind(node: Object) {
if (t.isClassMethod(node) || t.isObjectMethod(node)) {
if (node.kind === "get" || node.kind === "set") {
return node.kind;
@ -15,7 +15,7 @@ function toKind(node) {
return "value";
}
export function push(mutatorMap, node, kind, file, scope) {
export function push(mutatorMap: Object, node: Object, kind: string, file, scope?): Object {
let alias = t.toKeyAlias(node);
//
@ -75,7 +75,7 @@ export function push(mutatorMap, node, kind, file, scope) {
return map;
}
export function hasComputed(mutatorMap) {
export function hasComputed(mutatorMap: Object): boolean {
for (let key in mutatorMap) {
if (mutatorMap[key]._computed) {
return true;
@ -84,7 +84,7 @@ export function hasComputed(mutatorMap) {
return false;
}
export function toComputedObjectFromClass(obj) {
export function toComputedObjectFromClass(obj: Object): Object {
let objExpr = t.arrayExpression([]);
for (let i = 0; i < obj.properties.length; i++) {
@ -97,7 +97,7 @@ export function toComputedObjectFromClass(obj) {
return objExpr;
}
export function toClassObject(mutatorMap) {
export function toClassObject(mutatorMap: Object): Object {
let objExpr = t.objectExpression([]);
each(mutatorMap, function (map) {
@ -124,7 +124,7 @@ export function toClassObject(mutatorMap) {
return objExpr;
}
export function toDefineObject(mutatorMap) {
export function toDefineObject(mutatorMap: Object): Object {
each(mutatorMap, function (map) {
if (map.value) map.writable = t.booleanLiteral(true);
map.configurable = t.booleanLiteral(true);

View File

@ -1,3 +1,4 @@
import type { Scope } from "babel-traverse";
import * as t from "babel-types";
function getObjRef(node, nodes, file, scope) {
@ -45,7 +46,16 @@ function getPropRef(node, nodes, file, scope) {
return temp;
}
export default function (node, nodes, file, scope, allowedSingleIdent) {
export default function (
node: Object,
nodes: Array<Object>,
file,
scope: Scope,
allowedSingleIdent?: boolean,
): {
uid: Object;
ref: Object;
} {
let obj;
if (t.isIdentifier(node) && allowedSingleIdent) {
obj = node;

View File

@ -1,4 +1,5 @@
import bindifyDecorators from "babel-helper-bindify-decorators";
import type { NodePath } from "babel-traverse";
import * as t from "babel-types";
export default function (classPath) {
@ -14,7 +15,7 @@ export default function (classPath) {
path.replaceWith(uid);
}
function memoiseDecorators(paths) {
function memoiseDecorators(paths: Array<NodePath>) {
if (!Array.isArray(paths) || !paths.length) return;
// ensure correct evaluation order of decorators
@ -31,7 +32,7 @@ export default function (classPath) {
maybeMemoise(classPath.get("superClass"));
memoiseDecorators(classPath.get("decorators"), true);
let methods = classPath.get("body.body");
let methods: Array<NodePath> = classPath.get("body.body");
for (let methodPath of methods) {
if (methodPath.is("computed")) {
maybeMemoise(methodPath.get("key"));

View File

@ -10,13 +10,35 @@ function humanize(val, noext) {
return val.replace(/-/g, " ");
}
type TestFile = {
loc: string;
code: string;
filename: string;
};
type Test = {
title: string;
disabled: boolean;
options: Object;
exec: TestFile;
actual: TestFile;
expected: TestFile;
};
type Suite = {
options: Object;
tests: Array<Test>;
title: string;
filename: string;
};
function assertDirectory(loc) {
if (!fs.statSync(loc).isDirectory()) {
throw new Error(`Expected ${loc} to be a directory.`);
}
}
function shouldIgnore(name, blacklist) {
function shouldIgnore(name, blacklist?: Array<string>) {
if (blacklist && blacklist.indexOf(name) >= 0) {
return true;
}
@ -27,7 +49,7 @@ function shouldIgnore(name, blacklist) {
return name[0] === "." || ext === ".md" || base === "LICENSE" || base === "options";
}
export default function get(entryLoc) {
export default function get(entryLoc): Array<Suite> {
let suites = [];
let rootOpts = {};
@ -125,7 +147,7 @@ export default function get(entryLoc) {
return suites;
}
export function multiple(entryLoc, ignore) {
export function multiple(entryLoc, ignore?: Array<string>) {
let categories = {};
for (let name of fs.readdirSync(entryLoc)) {

View File

@ -1,7 +1,7 @@
import * as t from "babel-types";
export default function (node) {
let params = node.params;
export default function (node): number {
let params: Array<Object> = node.params;
for (let i = 0; i < params.length; i++) {
let param = params[i];
if (t.isAssignmentPattern(param) || t.isRestElement(param)) {

View File

@ -14,7 +14,7 @@ let visitor = {
let nodes = [];
let declarations = path.get("declarations");
let declarations: Array<Object> = path.get("declarations");
let firstId;
for (let declar of declarations) {
@ -40,6 +40,6 @@ let visitor = {
}
};
export default function (path, emit, kind = "var") {
export default function (path, emit: Function, kind: "var" | "let" = "var") {
path.traverse(visitor, { kind, emit });
}

View File

@ -1,13 +1,11 @@
import pull from "lodash/array/pull";
import * as t from "babel-types";
export function is(node, flag) {
export function is(node: Object, flag: string): boolean {
return t.isRegExpLiteral(node) && node.flags.indexOf(flag) >= 0;
}
export function pullFlag(node, flag) {
export function pullFlag(node: Object, flag: string) {
let flags = node.flags.split("");
if (node.flags.indexOf(flag) < 0) return;
pull(flags, flag);

View File

@ -1,4 +1,6 @@
/* @noflow */
import type { NodePath } from "babel-traverse";
import nameFunction from "babel-helper-function-name";
import template from "babel-template";
import * as t from "babel-types";
@ -33,7 +35,7 @@ let awaitVisitor = {
}
};
function classOrObjectMethod(path, callId) {
function classOrObjectMethod(path: NodePath, callId: Object) {
let node = path.node;
let body = node.body;
@ -49,7 +51,7 @@ function classOrObjectMethod(path, callId) {
];
}
function plainFunction(path, callId) {
function plainFunction(path: NodePath, callId: Object) {
let node = path.node;
let wrapper = buildWrapper;
@ -116,7 +118,7 @@ function plainFunction(path, callId) {
}
}
export default function (path, callId) {
export default function (path: NodePath, callId: Object) {
let node = path.node;
if (node.generator) return;

View File

@ -1,5 +1,6 @@
/* eslint max-len: 0 */
import type { NodePath, Scope } from "babel-traverse";
import optimiseCall from "babel-helper-optimise-call-expression";
import * as messages from "babel-messages";
import * as t from "babel-types";
@ -72,7 +73,7 @@ let visitor = {
};
export default class ReplaceSupers {
constructor(opts, inClass = false) {
constructor(opts: Object, inClass?: boolean = false) {
this.forceSuperMemoisation = opts.forceSuperMemoisation;
this.methodPath = opts.methodPath;
this.methodNode = opts.methodNode;
@ -90,6 +91,27 @@ export default class ReplaceSupers {
this.thises = [];
}
forceSuperMemoisation: boolean;
methodPath: NodePath;
methodNode: Object;
superRef: Object;
isStatic: boolean;
hasSuper: boolean;
inClass: boolean;
isLoose: boolean;
scope: Scope;
file;
opts: {
forceSuperMemoisation: boolean;
getObjetRef: Function;
methodPath: NodePath;
methodNode: Object;
superRef: Object;
isStatic: boolean;
isLoose: boolean;
file: any;
};
getObjectRef() {
return this.opts.objectRef || this.opts.getObjectRef();
}
@ -103,7 +125,7 @@ export default class ReplaceSupers {
*
*/
setSuperProperty(property, value, isComputed) {
setSuperProperty(property: Object, value: Object, isComputed: boolean): Object {
return t.callExpression(
this.file.addHelper("set"),
[
@ -129,7 +151,7 @@ export default class ReplaceSupers {
*
*/
getSuperProperty(property, isComputed) {
getSuperProperty(property: Object, isComputed: boolean): Object {
return t.callExpression(
this.file.addHelper("get"),
[
@ -149,7 +171,7 @@ export default class ReplaceSupers {
this.methodPath.traverse(visitor, this);
}
getLooseSuperProperty(id, parent) {
getLooseSuperProperty(id: Object, parent: Object) {
let methodNode = this.methodNode;
let superRef = this.superRef || t.identifier("Function");
@ -165,7 +187,7 @@ export default class ReplaceSupers {
}
}
looseHandle(path) {
looseHandle(path: NodePath) {
let node = path.node;
if (path.isSuper()) {
return this.getLooseSuperProperty(node, path.parent);
@ -199,7 +221,7 @@ export default class ReplaceSupers {
}
}
specHandle(path) {
specHandle(path: NodePath) {
let property;
let computed;
let args;

View File

@ -111,7 +111,13 @@ function runExec(opts, execCode) {
return fn.apply(null, Object.values(sandbox));
}
export default function (fixturesLoc, name, suiteOpts = {}, taskOpts = {}, dynamicOpts) {
export default function (
fixturesLoc: string,
name: string,
suiteOpts = {},
taskOpts = {},
dynamicOpts?: Function,
) {
let suites = getFixtures(fixturesLoc);
for (let testSuite of suites) {

View File

@ -47,7 +47,7 @@ export const MESSAGES = {
* Get a message with $0 placeholders replaced by arguments.
*/
export function get(key, ...args) {
export function get(key: string, ...args: Array<any>): string {
let msg = MESSAGES[key];
if (!msg) throw new ReferenceError(`Unknown message ${JSON.stringify(key)}`);
@ -64,7 +64,7 @@ export function get(key, ...args) {
* Stingify arguments to be used inside messages.
*/
export function parseArgs(args) {
export function parseArgs(args: Array<any>): Array<string> {
return args.map(function (val) {
if (val != null && val.inspect) {
return val.inspect();

View File

@ -6,11 +6,11 @@ export default function ({ messages }) {
let binding = scope.bindings[name];
if (binding.kind !== "const" && binding.kind !== "module") continue;
for (let violation of binding.constantViolations) {
for (let violation of (binding.constantViolations: Array)) {
throw violation.buildCodeFrameError(messages.get("readOnly", name));
}
}
}
},
}
};
}

View File

@ -17,8 +17,8 @@ let buildWrapper = template(`
export default function ({ types: t }) {
let ALREADY_VISITED = Symbol();
function findConstructorCall(path) {
let methods = path.get("body.body");
function findConstructorCall(path): ?Object {
let methods: Array<Object> = path.get("body.body");
for (let method of methods) {
if (method.node.kind === "constructorCall") {

View File

@ -54,13 +54,13 @@ export default function ({ types: t }) {
if (path.isClass()) {
if (path.node.decorators) return true;
for (let method of path.node.body.body) {
for (let method of (path.node.body.body: Array<Object>)) {
if (method.decorators) {
return true;
}
}
} else if (path.isObjectExpression()) {
for (let prop of path.node.properties) {
for (let prop of (path.node.properties: Array<Object>)) {
if (prop.decorators) {
return true;
}

View File

@ -1,6 +1,6 @@
export default function ({ types: t }) {
function statementList(key, path) {
let paths = path.get(key);
let paths: Array = path.get(key);
for (let path of paths) {
let func = path.node;

View File

@ -1,5 +1,8 @@
/* eslint max-len: 0 */
import type NodePath from "babel-traverse";
import type Scope from "babel-traverse";
import type File from "../../../file";
import traverse from "babel-traverse";
import { visitor as tdzVisitor } from "./tdz";
import * as t from "babel-types";
@ -288,7 +291,7 @@ let loopVisitor = {
};
class BlockScoping {
constructor(loopPath, blockPath, parent, scope, file) {
constructor(loopPath?: NodePath, blockPath: NodePath, parent: Object, scope: Scope, file: File) {
this.parent = parent;
this.scope = scope;
this.file = file;
@ -472,7 +475,7 @@ class BlockScoping {
* Push the closure to the body.
*/
buildClosure(ret, call) {
buildClosure(ret: { type: "Identifier" }, call: { type: "CallExpression" }) {
let has = this.has;
if (has.hasReturn || has.hasBreakContinue) {
this.buildHas(ret, call);
@ -570,7 +573,7 @@ class BlockScoping {
* later on.
*/
checkLoop() {
checkLoop(): Object {
let state = {
hasBreakContinue: false,
ignoreLabeless: false,
@ -602,7 +605,7 @@ class BlockScoping {
* their declarations hoisted to before the closure wrapper.
*/
pushDeclar(node) {
pushDeclar(node: { type: "VariableDeclaration" }): Array<Object> {
let declars = [];
let names = t.getBindingIdentifiers(node);
for (let name in names) {
@ -624,7 +627,7 @@ class BlockScoping {
return replace;
}
buildHas(ret, call) {
buildHas(ret: { type: "Identifier" }, call: { type: "CallExpression" }) {
let body = this.body;
body.push(t.variableDeclaration("var", [

View File

@ -1,5 +1,6 @@
/* eslint max-len: 0 */
import type { NodePath } from "babel-traverse";
import { visitors } from "babel-traverse";
import ReplaceSupers from "babel-helper-replace-supers";
import optimiseCall from "babel-helper-optimise-call-expression";
@ -60,7 +61,7 @@ let findThisesVisitor = visitors.merge([noMethodVisitor, {
}]);
export default class ClassTransformer {
constructor(path, file) {
constructor(path: NodePath, file) {
this.parent = path.parent;
this.scope = path.scope;
this.node = path.node;
@ -148,7 +149,7 @@ export default class ClassTransformer {
return func;
}
pushToMap(node, enumerable, kind = "value", scope) {
pushToMap(node, enumerable, kind = "value", scope?) {
let mutatorMap;
if (node.static) {
this.hasStaticDescriptors = true;
@ -175,7 +176,7 @@ export default class ClassTransformer {
constructorMeMaybe() {
let hasConstructor = false;
let paths = this.path.get("body.body");
for (let path of paths) {
for (let path of (paths: Array)) {
hasConstructor = path.equals("kind", "constructor");
if (hasConstructor) break;
}
@ -216,7 +217,7 @@ export default class ClassTransformer {
}
pushBody() {
let classBodyPaths = this.path.get("body.body");
let classBodyPaths: Array<Object> = this.path.get("body.body");
for (let path of classBodyPaths) {
let node = path.node;
@ -450,7 +451,7 @@ export default class ClassTransformer {
* Push a method to its respective mutatorMap.
*/
pushMethod(node, path) {
pushMethod(node: { type: "ClassMethod" }, path?: NodePath) {
let scope = path ? path.scope : this.scope;
if (node.kind === "method") {
@ -468,7 +469,7 @@ export default class ClassTransformer {
* Replace the constructor body of our class.
*/
pushConstructor(replaceSupers, method, path) {
pushConstructor(replaceSupers, method: { type: "ClassMethod" }, path: NodePath) {
this.bareSupers = replaceSupers.bareSupers;
this.superReturns = replaceSupers.returns;

View File

@ -89,7 +89,7 @@ export default function ({ types: t, template }) {
exit(path, state) {
let { node, parent, scope } = path;
let hasComputed = false;
for (let prop of node.properties) {
for (let prop of (node.properties: Array<Object>)) {
hasComputed = prop.computed === true;
if (hasComputed) break;
}

View File

@ -7,7 +7,7 @@ export default function ({ types: t }) {
*/
function variableDeclarationHasPattern(node) {
for (let declar of node.declarations) {
for (let declar of (node.declarations: Array)) {
if (t.isPattern(declar.id)) {
return true;
}
@ -20,7 +20,7 @@ export default function ({ types: t }) {
*/
function hasRest(pattern) {
for (let elem of pattern.elements) {
for (let elem of (pattern.elements: Array)) {
if (t.isRestElement(elem)) {
return true;
}
@ -210,7 +210,7 @@ export default function ({ types: t }) {
if (pattern.elements.length > arr.elements.length) return;
if (pattern.elements.length < arr.elements.length && !hasRest(pattern)) return false;
for (let elem of pattern.elements) {
for (let elem of (pattern.elements: Array)) {
// deopt on holes
if (!elem) return false;
@ -218,7 +218,7 @@ export default function ({ types: t }) {
if (t.isMemberExpression(elem)) return false;
}
for (let elem of arr.elements) {
for (let elem of (arr.elements: Array)) {
// deopt on spread elements
if (t.isSpreadElement(elem)) return false;
}

View File

@ -159,7 +159,7 @@ export default function () {
let hasExports = false;
let hasImports = false;
let body = path.get("body");
let body: Array<Object> = path.get("body");
let imports = Object.create(null);
let exports = Object.create(null);

View File

@ -92,7 +92,7 @@ export default function ({ types: t }) {
);
}
let body = path.get("body");
let body: Array<Object> = path.get("body");
let canHoist = true;
for (let path of body) {

View File

@ -30,7 +30,7 @@ export default function ({ types: t }) {
let objectRef;
let getObjectRef = () => objectRef = objectRef || path.scope.generateUidIdentifier("obj");
let propPaths = path.get("properties");
let propPaths: Array = path.get("properties");
for (let propPath of propPaths) {
if (propPath.isObjectProperty()) propPath = propPath.get("value");
Property(propPath, propPath.node, path.scope, getObjectRef, file);

View File

@ -22,7 +22,7 @@ let buildCutOff = template(`
`);
function hasDefaults(node) {
for (let param of node.params) {
for (let param of (node.params: Array<Object>)) {
if (!t.isIdentifier(param)) return true;
}
return false;

View File

@ -2,7 +2,7 @@ import * as t from "babel-types";
export let visitor = {
Function(path) {
let params = path.get("params");
let params: Array = path.get("params");
// If there's a rest param, no need to loop through it. Also, we need to
// hoist one more level to get `declar` at the right spot.

View File

@ -1,3 +1,4 @@
import type { NodePath } from "babel-traverse";
import { visitors } from "babel-traverse";
import * as destructuring from "./destructuring";
@ -9,7 +10,7 @@ export default function () {
visitor: visitors.merge([{
ArrowFunctionExpression(path) {
// default/rest visitors require access to `arguments`
let params = path.get("params");
let params: Array<NodePath> = path.get("params");
for (let param of params) {
if (param.isRestElement() || param.isAssignmentPattern()) {
path.arrowFunctionToShadowed();

View File

@ -198,7 +198,7 @@ export let visitor = {
// There are only "shorthand" references
if (!state.deopted && !state.references.length) {
for (let {path, cause} of state.candidates) {
for (let {path, cause} of (state.candidates: Array)) {
switch (cause) {
case "indexGetter":
optimiseIndexGetter(path, argsId, state.offset);

View File

@ -16,7 +16,7 @@ export default function ({ types: t }) {
return false;
}
function build(props, scope, state) {
function build(props: Array, scope, state) {
let nodes = [];
let _props = [];

View File

@ -17,7 +17,7 @@ export default function ({ types: t }) {
let strings = [];
let raw = [];
for (let elem of quasi.quasis) {
for (let elem of (quasi.quasis: Array)) {
strings.push(t.stringLiteral(elem.value.cooked));
raw.push(t.stringLiteral(elem.value.raw));
}
@ -37,11 +37,11 @@ export default function ({ types: t }) {
},
TemplateLiteral(path, state) {
let nodes = [];
let nodes: Array<Object> = [];
let expressions = path.get("expressions");
for (let elem of path.node.quasis) {
for (let elem of (path.node.quasis: Array)) {
nodes.push(t.stringLiteral(elem.value.cooked));
let expr = expressions.shift();

View File

@ -6,7 +6,7 @@ export default function ({ types: t }) {
ObjectExpression(path, file) {
let { node } = path;
let hasAny = false;
for (let prop of node.properties) {
for (let prop of (node.properties: Array)) {
if (prop.kind === "get" || prop.kind === "set") {
hasAny = true;
break;

View File

@ -6,7 +6,7 @@ export default function ({ types: t }) {
visitor: {
Program(path, { file: { ast: { comments } } }) {
for (let comment of comments) {
for (let comment of (comments: Array<Object>)) {
if (comment.value.indexOf(FLOW_DIRECTIVE) >= 0) {
// remove flow directive
comment.value = comment.value.replace(FLOW_DIRECTIVE, "");

View File

@ -1,6 +1,6 @@
export default function ({ types: t }) {
function hasSpread(node) {
for (let prop of node.properties) {
for (let prop of (node.properties: Array<Object>)) {
if (t.isSpreadProperty(prop)) {
return true;
}
@ -24,7 +24,7 @@ export default function ({ types: t }) {
props = [];
}
for (let prop of path.node.properties) {
for (let prop of (path.node.properties: Array)) {
if (t.isSpreadProperty(prop)) {
push();
args.push(prop.argument);

View File

@ -45,7 +45,7 @@ export default function ({ types: t }) {
let proto;
let { node } = path;
for (let prop of node.properties) {
for (let prop of (node.properties: Array)) {
if (isProtoKey(prop)) {
proto = prop.value;
pull(node.properties, prop);

View File

@ -42,7 +42,7 @@ export default function ({ types: t }) {
}
// props
for (let attr of open.attributes) {
for (let attr of (open.attributes: Array<Object>)) {
if (isJSXAttributeOfName(attr, "key")) {
key = getAttributeValue(attr);
} else {

View File

@ -23,7 +23,7 @@ export default function ({ types: t }) {
let { file } = state;
let id = state.opts.pragma || "React.createElement";
for (let comment of file.ast.comments) {
for (let comment of (file.ast.comments: Array<Object>)) {
let matches = JSX_ANNOTATION_REGEX.exec(comment.value);
if (matches) {
id = matches[1];

View File

@ -8,7 +8,7 @@ export default function () {
let { node } = path;
for (let directive of node.directives) {
for (let directive of (node.directives: Array<Object>)) {
if (directive.value.value === "use strict") return;
}

View File

@ -1,4 +1,3 @@
import deepClone from "lodash/lang/cloneDeep";
import sourceMapSupport from "source-map-support";
import * as registerCache from "./cache";
@ -128,7 +127,7 @@ function hookExtensions(_exts) {
hookExtensions(util.canCompile.EXTENSIONS);
export default function (opts = {}) {
export default function (opts?: Object = {}) {
if (opts.only != null) only = util.arrayify(opts.only, util.regexify);
if (opts.ignore != null) ignore = util.arrayify(opts.ignore, util.regexify);

View File

@ -10,7 +10,7 @@ import * as t from "babel-types";
let FROM_TEMPLATE = "_fromTemplate"; //Symbol(); // todo: probably wont get copied over
let TEMPLATE_SKIP = Symbol();
export default function (code, opts) {
export default function (code: string, opts?: Object): Function {
// since we lazy parse the template, we get the current stack so we have the
// original stack to append if it errors when parsing
let stack;
@ -52,7 +52,7 @@ export default function (code, opts) {
};
}
function useTemplate(ast, nodes) {
function useTemplate(ast, nodes?: Array<Object>) {
ast = cloneDeep(ast);
let { program } = ast;

View File

@ -11,12 +11,18 @@ export default class TraversalContext {
this.opts = opts;
}
parentPath: NodePath;
scope;
state;
opts;
queue: ?Array<NodePath> = null;
/**
* This method does a simple check to determine whether or not we really need to attempt
* visit a node. This will prevent us from constructing a NodePath.
*/
shouldVisit(node) {
shouldVisit(node): boolean {
let opts = this.opts;
if (opts.enter || opts.exit) return true;
@ -24,7 +30,7 @@ export default class TraversalContext {
if (opts[node.type]) return true;
// check if we're going to traverse into this node
let keys = t.VISITOR_KEYS[node.type];
let keys: ?Array<string> = t.VISITOR_KEYS[node.type];
if (!keys || !keys.length) return false;
// we need to traverse into this node so ensure that it has children to traverse into!
@ -35,7 +41,7 @@ export default class TraversalContext {
return false;
}
create(node, obj, key, listKey) {
create(node, obj, key, listKey): NodePath {
return NodePath.get({
parentPath: this.parentPath,
parent: node,
@ -45,7 +51,7 @@ export default class TraversalContext {
});
}
maybeQueue(path, notPriority) {
maybeQueue(path, notPriority?: boolean) {
if (this.trap) {
throw new Error("Infinite cycle detected");
}
@ -76,7 +82,7 @@ export default class TraversalContext {
return this.visitQueue(queue);
}
visitSingle(node, key) {
visitSingle(node, key): boolean {
if (this.shouldVisit(node[key])) {
return this.visitQueue([
this.create(node, node, key)
@ -86,7 +92,7 @@ export default class TraversalContext {
}
}
visitQueue(queue) {
visitQueue(queue: Array<NodePath>) {
// set queue
this.queue = queue;
this.priorityQueue = [];

View File

@ -11,7 +11,13 @@ export { default as Scope } from "./scope";
export { default as Hub } from "./hub";
export { visitors };
export default function traverse(parent, opts, scope, state, parentPath) {
export default function traverse(
parent: Object | Array<Object>,
opts?: Object,
scope?: Object,
state: Object,
parentPath: Object,
) {
if (!parent) return;
if (!opts) opts = {};
@ -55,8 +61,8 @@ traverse.cheap = function (node, enter) {
}
};
traverse.node = function (node, opts, scope, state, parentPath, skipKeys) {
let keys = t.VISITOR_KEYS[node.type];
traverse.node = function (node: Object, opts: Object, scope: Object, state: Object, parentPath: Object, skipKeys?) {
let keys: Array = t.VISITOR_KEYS[node.type];
if (!keys) return;
let context = new TraversalContext(scope, opts, state, parentPath);
@ -66,7 +72,7 @@ traverse.node = function (node, opts, scope, state, parentPath, skipKeys) {
}
};
const CLEAR_KEYS = t.COMMENT_KEYS.concat([
const CLEAR_KEYS: Array = t.COMMENT_KEYS.concat([
"tokens", "comments",
"start", "end", "loc",
"raw", "rawValue"
@ -81,7 +87,7 @@ traverse.clearNode = function (node) {
if (key[0] === "_" && node[key] != null) node[key] = undefined;
}
let syms = Object.getOwnPropertySymbols(node);
let syms: Array<Symbol> = Object.getOwnPropertySymbols(node);
for (let sym of syms) {
node[sym] = null;
}
@ -99,7 +105,7 @@ function hasBlacklistedType(path, state) {
}
}
traverse.hasType = function (tree, scope, type, blacklistTypes) {
traverse.hasType = function (tree: Object, scope: Object, type: Object, blacklistTypes: Array<string>): boolean {
// the node we're searching in is blacklisted
if (includes(blacklistTypes, tree.type)) return false;

View File

@ -1,6 +1,7 @@
// This file contains that retrieve or validate anything related to the current paths ancestry.
import * as t from "babel-types";
import NodePath from "./index";
/**
* Call the provided `callback` with the `NodePath`s of all the parents.
@ -56,12 +57,12 @@ export function getStatementParent() {
* position and visiting key.
*/
export function getEarliestCommonAncestorFrom(paths) {
export function getEarliestCommonAncestorFrom(paths: Array<NodePath>): NodePath {
return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) {
let earliest;
let keys = t.VISITOR_KEYS[deepest.type];
for (let ancestry of ancestries) {
for (let ancestry of (ancestries: Array)) {
let path = ancestry[i + 1];
// first path
@ -98,7 +99,7 @@ export function getEarliestCommonAncestorFrom(paths) {
* TODO: Possible optimisation target.
*/
export function getDeepestCommonAncestorFrom(paths, filter) {
export function getDeepestCommonAncestorFrom(paths: Array<NodePath>, filter?: Function): NodePath {
if (!paths.length) {
return this;
}
@ -136,7 +137,7 @@ export function getDeepestCommonAncestorFrom(paths, filter) {
depthLoop: for (let i = 0; i < minDepth; i++) {
let shouldMatch = first[i];
for (let ancestry of ancestries) {
for (let ancestry of (ancestries: Array)) {
if (ancestry[i] !== shouldMatch) {
// we've hit a snag
break depthLoop;
@ -177,7 +178,7 @@ export function getAncestry() {
export function inType() {
let path = this;
while (path) {
for (let type of arguments) {
for (let type of (arguments: Array)) {
if (path.node.type === type) return true;
}
path = path.parentPath;
@ -190,7 +191,7 @@ export function inType() {
* Check if we're inside a shadowed function.
*/
export function inShadow(key) {
export function inShadow(key?) {
let path = this;
do {
if (path.isFunction()) {

View File

@ -22,7 +22,7 @@ export function shareCommentsWithSiblings() {
next.addComments("leading", trailing);
}
export function addComment(type, content, line) {
export function addComment(type, content, line?) {
this.addComments(type, [{
type: line ? "CommentLine" : "CommentBlock",
value: content
@ -33,7 +33,7 @@ export function addComment(type, content, line) {
* Give node `comments` of the specified `type`.
*/
export function addComments(type, comments) {
export function addComments(type: string, comments: Array) {
if (!comments) return;
let node = this.node;

View File

@ -2,7 +2,7 @@
import traverse from "../index";
export function call(key) {
export function call(key): boolean {
let opts = this.opts;
this.debug(() => key);
@ -18,7 +18,7 @@ export function call(key) {
return false;
}
export function _call(fns) {
export function _call(fns?: Array<Function>): boolean {
if (!fns) return false;
for (let fn of fns) {
@ -39,12 +39,12 @@ export function _call(fns) {
return false;
}
export function isBlacklisted() {
export function isBlacklisted(): boolean {
let blacklist = this.opts.blacklist;
return blacklist && blacklist.indexOf(this.node.type) > -1;
}
export function visit() {
export function visit(): boolean {
if (!this.node) {
return false;
}

View File

@ -2,7 +2,7 @@
import * as t from "babel-types";
export function toComputedKey() {
export function toComputedKey(): Object {
let node = this.node;
let key;

View File

@ -1,6 +1,8 @@
/* eslint indent: 0 */
/* eslint max-len: 0 */
import type NodePath from "./index";
// This file contains Babels metainterpreter that can evaluate static code.
/* eslint eqeqeq: 0 */
@ -26,7 +28,7 @@ const INVALID_METHODS = ["random"];
*
*/
export function evaluateTruthy() {
export function evaluateTruthy(): boolean {
let res = this.evaluate();
if (res.confident) return !!res.value;
}
@ -46,9 +48,9 @@ export function evaluateTruthy() {
*
*/
export function evaluate() {
export function evaluate(): { confident: boolean; value: any } {
let confident = true;
let deoptPath;
let deoptPath: ?NodePath;
function deopt(path) {
if (!confident) return;
@ -88,7 +90,7 @@ export function evaluate() {
let i = 0;
let exprs = path.get("expressions");
for (let elem of node.quasis) {
for (let elem of (node.quasis: Array<Object>)) {
// not confident, evaluated an expression we don't like
if (!confident) break;
@ -178,7 +180,7 @@ export function evaluate() {
if (path.isArrayExpression()) {
let arr = [];
let elems = path.get("elements");
let elems: Array<NodePath> = path.get("elements");
for (let elem of elems) {
elem = elem.evaluate();

View File

@ -1,9 +1,10 @@
// This file contains methods responsible for dealing with/retrieving children or siblings.
import type TraversalContext from "../index";
import NodePath from "./index";
import * as t from "babel-types";
export function getStatementParent() {
export function getStatementParent(): ?NodePath {
let path = this;
do {
@ -29,7 +30,7 @@ export function getOpposite() {
}
}
export function getCompletionRecords() {
export function getCompletionRecords(): Array {
let paths = [];
let add = function (path) {
@ -66,7 +67,7 @@ export function getSibling(key) {
});
}
export function get(key, context) {
export function get(key: string, context?: boolean | TraversalContext): NodePath {
if (context === true) context = this.context;
let parts = key.split(".");
if (parts.length === 1) { // "foo"
@ -76,7 +77,7 @@ export function get(key, context) {
}
}
export function _getKey(key, context) {
export function _getKey(key, context?) {
let node = this.node;
let container = node[key];
@ -103,7 +104,7 @@ export function _getKey(key, context) {
export function _getPattern(parts, context) {
let path = this;
for (let part of parts) {
for (let part of (parts: Array)) {
if (part === ".") {
path = path.parentPath;
} else {
@ -117,10 +118,10 @@ export function _getPattern(parts, context) {
return path;
}
export function getBindingIdentifiers(duplicates) {
export function getBindingIdentifiers(duplicates?) {
return t.getBindingIdentifiers(this.node, duplicates);
}
export function getOuterBindingIdentifiers(duplicates) {
export function getOuterBindingIdentifiers(duplicates?) {
return t.getOuterBindingIdentifiers(this.node, duplicates);
}

View File

@ -1,5 +1,7 @@
/* eslint max-len: 0 */
import type Hub from "../hub";
import type TraversalContext from "../context";
import * as virtualTypes from "./lib/virtual-types";
import buildDebug from "debug";
import { PATH_CACHE_KEY } from "./constants";
@ -12,7 +14,7 @@ import * as t from "babel-types";
let debug = buildDebug("babel");
export default class NodePath {
constructor(hub, parent) {
constructor(hub: Hub, parent: Object) {
this.parent = parent;
this.hub = hub;
this.contexts = [];
@ -36,7 +38,29 @@ export default class NodePath {
this.typeAnnotation = null;
}
static get({ hub, parentPath, parent, container, listKey, key }) {
parent: Object;
hub: Hub;
contexts: Array<TraversalContext>;
data: Object;
shouldSkip: boolean;
shouldStop: boolean;
removed: boolean;
state: any;
opts: ?Object;
skipKeys: ?Object;
parentPath: ?NodePath;
context: TraversalContext;
container: ?Object | Array<Object>;
listKey: ?string;
inList: boolean;
parentKey: ?string;
key: ?string;
node: ?Object;
scope: Scope;
type: ?string;
typeAnnotation: ?Object;
static get({ hub, parentPath, parent, container, listKey, key }): NodePath {
if (!hub && parentPath) {
hub = parentPath.hub;
}
@ -78,7 +102,7 @@ export default class NodePath {
return path;
}
getScope(scope) {
getScope(scope: Scope) {
let ourScope = scope;
// we're entering a new scope so let's construct it!
@ -89,25 +113,25 @@ export default class NodePath {
return ourScope;
}
setData(key, val) {
setData(key: string, val: any): any {
return this.data[key] = val;
}
getData(key, def) {
getData(key: string, def?: any): any {
let val = this.data[key];
if (!val && def) val = this.data[key] = def;
return val;
}
buildCodeFrameError(msg, Error = SyntaxError) {
buildCodeFrameError(msg: string, Error: typeof Error = SyntaxError): Error {
return this.hub.file.buildCodeFrameError(this.node, msg, Error);
}
traverse(visitor, state) {
traverse(visitor: Object, state?: any) {
traverse(this.node, visitor, this.scope, state, this);
}
mark(type, message) {
mark(type: string, message: string) {
this.hub.file.metadata.marked.push({
type,
message,
@ -115,12 +139,12 @@ export default class NodePath {
});
}
set(key, node) {
set(key: string, node: Object) {
t.validate(this.node, key, node);
this.node[key] = node;
}
getPathLocation() {
getPathLocation(): string {
let parts = [];
let path = this;
do {
@ -131,7 +155,7 @@ export default class NodePath {
return parts.join(".");
}
debug(buildMessage) {
debug(buildMessage: Function) {
if (!debug.enabled) return;
debug(`${this.getPathLocation()} ${this.type}: ${buildMessage()}`);
}
@ -149,7 +173,7 @@ assign(NodePath.prototype, require("./modification"));
assign(NodePath.prototype, require("./family"));
assign(NodePath.prototype, require("./comments"));
for (let type of t.TYPES) {
for (let type of (t.TYPES: Array<string>)) {
let typeKey = `is${type}`;
NodePath.prototype[typeKey] = function (opts) {
return t[typeKey](this.node, opts);

View File

@ -1,3 +1,4 @@
import type NodePath from "./index";
import * as inferers from "./inferers";
import * as t from "babel-types";
@ -5,7 +6,7 @@ import * as t from "babel-types";
* Infer the type of the current `NodePath`.
*/
export function getTypeAnnotation() {
export function getTypeAnnotation(): Object {
if (this.typeAnnotation) return this.typeAnnotation;
let type = this._getTypeAnnotation() || t.anyTypeAnnotation();
@ -17,7 +18,7 @@ export function getTypeAnnotation() {
* todo: split up this method
*/
export function _getTypeAnnotation() {
export function _getTypeAnnotation(): ?Object {
let node = this.node;
if (!node) {
@ -57,11 +58,11 @@ export function _getTypeAnnotation() {
}
}
export function isBaseType(baseName, soft) {
export function isBaseType(baseName: string, soft?: boolean): boolean {
return _isBaseType(baseName, this.getTypeAnnotation(), soft);
}
function _isBaseType(baseName, type, soft) {
function _isBaseType(baseName: string, type?, soft?): boolean {
if (baseName === "string") {
return t.isStringTypeAnnotation(type);
} else if (baseName === "number") {
@ -83,12 +84,12 @@ function _isBaseType(baseName, type, soft) {
}
}
export function couldBeBaseType(name) {
export function couldBeBaseType(name: string): boolean {
let type = this.getTypeAnnotation();
if (t.isAnyTypeAnnotation(type)) return true;
if (t.isUnionTypeAnnotation(type)) {
for (let type2 of type.types) {
for (let type2 of (type.types: Array<Object>)) {
if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) {
return true;
}
@ -99,7 +100,7 @@ export function couldBeBaseType(name) {
}
}
export function baseTypeStrictlyMatches(right) {
export function baseTypeStrictlyMatches(right: NodePath) {
let left = this.getTypeAnnotation();
right = right.getTypeAnnotation();
@ -108,7 +109,7 @@ export function baseTypeStrictlyMatches(right) {
}
}
export function isGenericType(genericName) {
export function isGenericType(genericName: string): boolean {
let type = this.getTypeAnnotation();
return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName });
}

View File

@ -1,6 +1,7 @@
import type NodePath from "../index";
import * as t from "babel-types";
export default function (node) {
export default function (node: Object) {
if (!this.isReferenced()) return;
// check if a binding exists of this value and if so then return a union type of all
@ -75,7 +76,7 @@ function getTypeAnnotationBindingConstantViolations(path, name) {
constantViolations = constantViolations.concat(functionConstantViolations);
// push on inferred types of violated paths
for (let violation of constantViolations) {
for (let violation of (constantViolations: Array<NodePath>)) {
types.push(violation.getTypeAnnotation());
}
}

View File

@ -1,5 +1,6 @@
// This file contains methods responsible for introspecting the current path for certain values.
import type NodePath from "./index";
import includes from "lodash/collection/includes";
import * as t from "babel-types";
@ -10,7 +11,7 @@ import * as t from "babel-types";
* parsed nodes of `React.createClass` and `React["createClass"]`.
*/
export function matchesPattern(pattern, allowPartial) {
export function matchesPattern(pattern: string, allowPartial?: boolean): boolean {
// not a member expression
if (!this.isMemberExpression()) return false;
@ -66,7 +67,7 @@ export function matchesPattern(pattern, allowPartial) {
* if the array has any items, otherwise we just check if it's falsy.
*/
export function has(key) {
export function has(key): boolean {
let val = this.node && this.node[key];
if (val && Array.isArray(val)) {
return !!val.length;
@ -93,7 +94,7 @@ export let is = has;
* Opposite of `has`.
*/
export function isnt(key) {
export function isnt(key): boolean {
return !this.has(key);
}
@ -101,7 +102,7 @@ export function isnt(key) {
* Check whether the path node `key` strict equals `value`.
*/
export function equals(key, value) {
export function equals(key, value): boolean {
return this.node[key] === value;
}
@ -110,7 +111,7 @@ export function equals(key, value) {
* been removed yet we still internally know the type and need it to calculate node replacement.
*/
export function isNodeType(type) {
export function isNodeType(type: string): boolean {
return t.isType(this.type, type);
}
@ -154,7 +155,7 @@ export function canSwapBetweenExpressionAndStatement(replacement) {
* Check whether the current path references a completion record
*/
export function isCompletionRecord(allowInsideFunction) {
export function isCompletionRecord(allowInsideFunction?) {
let path = this;
let first = true;
@ -319,7 +320,7 @@ export function _guessExecutionStatusRelativeToDifferentFunctions(targetFuncPare
// no references!
if (!binding.references) return "before";
let referencePaths = binding.referencePaths;
let referencePaths: Array<NodePath> = binding.referencePaths;
// verify that all of the references are calls
for (let path of referencePaths) {
@ -357,7 +358,7 @@ export function resolve(dangerous, resolved) {
return this._resolve(dangerous, resolved) || this;
}
export function _resolve(dangerous, resolved) {
export function _resolve(dangerous?, resolved?): ?NodePath {
// detect infinite recursion
// todo: possibly have a max length on this just to be safe
if (resolved && resolved.indexOf(this) >= 0) return;
@ -403,7 +404,7 @@ export function _resolve(dangerous, resolved) {
if (target.isObjectExpression()) {
let props = target.get("properties");
for (let prop of props) {
for (let prop of (props: Array)) {
if (!prop.isProperty()) continue;
let key = prop.get("key");

View File

@ -18,7 +18,7 @@ export function remove() {
}
export function _callRemovalHooks() {
for (let fn of hooks) {
for (let fn of (hooks: Array<Function>)) {
if (fn(this, this.parentPath)) return true;
}
}

View File

@ -22,7 +22,7 @@ let hoistVariablesVisitor = {
let exprs = [];
for (let declar of path.node.declarations) {
for (let declar of (path.node.declarations: Array<Object>)) {
if (declar.init) {
exprs.push(t.expressionStatement(
t.assignmentExpression("=", declar.id, declar.init)
@ -42,7 +42,7 @@ let hoistVariablesVisitor = {
* - Remove the current node.
*/
export function replaceWithMultiple(nodes) {
export function replaceWithMultiple(nodes: Array<Object>) {
this.resync();
nodes = this._verifyNodeList(nodes);
@ -178,7 +178,7 @@ export function _replaceWith(node) {
* extremely important to retain original semantics.
*/
export function replaceExpressionWithStatements(nodes) {
export function replaceExpressionWithStatements(nodes: Array<Object>) {
this.resync();
let toSequenceExpression = t.toSequenceExpression(nodes, this.scope);
@ -206,7 +206,7 @@ export function replaceExpressionWithStatements(nodes) {
this.traverse(hoistVariablesVisitor);
// add implicit returns to all ending expression statements
let completionRecords = this.get("callee").getCompletionRecords();
let completionRecords: Array<NodePath> = this.get("callee").getCompletionRecords();
for (let path of completionRecords) {
if (!path.isExpressionStatement()) continue;
@ -229,7 +229,7 @@ export function replaceExpressionWithStatements(nodes) {
}
}
export function replaceInline(nodes) {
export function replaceInline(nodes: Object | Array<Object>) {
this.resync();
if (Array.isArray(nodes)) {

View File

@ -1,3 +1,4 @@
import type NodePath from "../path";
/**
* This class is responsible for a binding inside of a scope.
@ -35,12 +36,24 @@ export default class Binding {
}
}
constantViolations: Array<NodePath>;
constant: boolean;
referencePaths: Array<NodePath>;
referenced: boolean;
references: number;
hasDeoptedValue: boolean;
hasValue: boolean;
value: any;
deoptValue() {
this.clearValue();
this.hasDeoptedValue = true;
}
setValue(value) {
setValue(value: any) {
if (this.hasDeoptedValue) return;
this.hasValue = true;
this.value = value;
@ -56,7 +69,7 @@ export default class Binding {
* Register a constant violation with the provided `path`.
*/
reassign(path) {
reassign(path: Object) {
this.constant = false;
this.constantViolations.push(path);
}
@ -65,7 +78,7 @@ export default class Binding {
* Increment the amount of references to this binding.
*/
reference(path) {
reference(path: NodePath) {
this.referenced = true;
this.references++;
this.referencePaths.push(path);

View File

@ -3,6 +3,7 @@
import includes from "lodash/collection/includes";
import repeating from "repeating";
import Renamer from "./lib/renamer";
import type NodePath from "../path";
import traverse from "../index";
import defaults from "lodash/object/defaults";
import * as messages from "babel-messages";
@ -48,7 +49,7 @@ function matchesParent(scope, parentScope) {
}
function getCacheMultiple(node, parentScope, self, singleCache) {
let scopes = node[CACHE_MULTIPLE_KEY] = node[CACHE_MULTIPLE_KEY] || [];
let scopes: Array<Scope> = node[CACHE_MULTIPLE_KEY] = node[CACHE_MULTIPLE_KEY] || [];
if (singleCache) {
// we have a scope assocation miss so push it onto our scopes
@ -68,7 +69,7 @@ function getCacheMultiple(node, parentScope, self, singleCache) {
let collectorVisitor = {
For(path) {
for (let key of t.FOR_INIT_KEYS) {
for (let key of (t.FOR_INIT_KEYS: Array)) {
let declar = path.get(key);
if (declar.isVar()) path.scope.getFunctionParent().registerBinding("var", declar);
}
@ -106,7 +107,7 @@ let collectorVisitor = {
let binding = scope.getBinding(id.name);
if (binding) binding.reference();
} else if (t.isVariableDeclaration(declar)) {
for (let decl of declar.declarations) {
for (let decl of (declar.declarations: Array<Object>)) {
let ids = t.getBindingIdentifiers(decl);
for (let name in ids) {
let binding = scope.getBinding(name);
@ -152,7 +153,7 @@ let collectorVisitor = {
Block(path) {
let paths = path.get("body");
for (let bodyPath of paths) {
for (let bodyPath of (paths: Array)) {
if (bodyPath.isFunctionDeclaration()) {
path.scope.getBlockParent().registerDeclaration(bodyPath);
}
@ -169,7 +170,7 @@ export default class Scope {
* within.
*/
constructor(path, parentScope) {
constructor(path: NodePath, parentScope?: Scope) {
if (parentScope && parentScope.block === path.node) {
return parentScope;
}
@ -207,7 +208,7 @@ export default class Scope {
* Traverse node with current scope and path.
*/
traverse(node, opts, state) {
traverse(node: Object, opts: Object, state?) {
traverse(node, opts, this, state, this.path);
}
@ -215,7 +216,7 @@ export default class Scope {
* Generate a unique identifier and add it to the current scope.
*/
generateDeclaredUidIdentifier(name = "temp") {
generateDeclaredUidIdentifier(name: string = "temp") {
let id = this.generateUidIdentifier(name);
this.push({ id });
return id;
@ -225,7 +226,7 @@ export default class Scope {
* Generate a unique identifier.
*/
generateUidIdentifier(name = "temp") {
generateUidIdentifier(name: string = "temp") {
return t.identifier(this.generateUid(name));
}
@ -233,7 +234,7 @@ export default class Scope {
* Generate a unique `_id1` binding.
*/
generateUid(name = "temp") {
generateUid(name: string = "temp") {
name = t.toIdentifier(name).replace(/^_+/, "").replace(/[0-9]+$/g, "");
let uid;
@ -264,7 +265,7 @@ export default class Scope {
* Generate a unique identifier based on a node.
*/
generateUidIdentifierBasedOnNode(parent, defaultName) {
generateUidIdentifierBasedOnNode(parent: Object, defaultName?: String): Object {
let node = parent;
if (t.isAssignmentExpression(parent)) {
@ -282,7 +283,7 @@ export default class Scope {
if (node.source) {
add(node.source);
} else if (node.specifiers && node.specifiers.length) {
for (let specifier of node.specifiers) {
for (let specifier of (node.specifiers: Array)) {
add(specifier);
}
} else if (node.declaration) {
@ -300,7 +301,7 @@ export default class Scope {
} else if (t.isCallExpression(node)) {
add(node.callee);
} else if (t.isObjectExpression(node) || t.isObjectPattern(node)) {
for (let prop of node.properties) {
for (let prop of (node.properties: Array)) {
add(prop.key || prop.argument);
}
}
@ -324,7 +325,7 @@ export default class Scope {
* - Bound identifiers
*/
isStatic(node) {
isStatic(node: Object): boolean {
if (t.isThisExpression(node) || t.isSuper(node)) {
return true;
}
@ -345,7 +346,7 @@ export default class Scope {
* Possibly generate a memoised identifier if it is not static and has consequences.
*/
maybeGenerateMemoised(node, dontPush) {
maybeGenerateMemoised(node: Object, dontPush?: boolean): ?Object {
if (this.isStatic(node)) {
return null;
} else {
@ -355,7 +356,7 @@ export default class Scope {
}
}
checkBlockScopedCollisions(local, kind, name, id) {
checkBlockScopedCollisions(local, kind: string, name: string, id: Object) {
// ignore parameters
if (kind === "param") return;
@ -375,7 +376,7 @@ export default class Scope {
}
}
rename(oldName, newName, block) {
rename(oldName: string, newName: string, block?) {
let binding = this.getBinding(oldName);
if (binding) {
newName = newName || this.generateUidIdentifier(oldName).name;
@ -409,7 +410,7 @@ export default class Scope {
console.log(sep);
}
toArray(node, i) {
toArray(node: Object, i?: number) {
let file = this.hub.file;
if (t.isIdentifier(node)) {
@ -449,21 +450,21 @@ export default class Scope {
return t.callExpression(file.addHelper(helperName), args);
}
registerDeclaration(path) {
registerDeclaration(path: NodePath) {
if (path.isLabeledStatement()) {
this.registerBinding("label", path);
} else if (path.isFunctionDeclaration()) {
this.registerBinding("hoisted", path.get("id"), path);
} else if (path.isVariableDeclaration()) {
let declarations = path.get("declarations");
for (let declar of declarations) {
for (let declar of (declarations: Array)) {
this.registerBinding(path.node.kind, declar);
}
} else if (path.isClassDeclaration()) {
this.registerBinding("let", path);
} else if (path.isImportDeclaration()) {
let specifiers = path.get("specifiers");
for (let specifier of specifiers) {
for (let specifier of (specifiers: Array)) {
this.registerBinding("module", specifier);
}
} else if (path.isExportDeclaration()) {
@ -484,7 +485,7 @@ export default class Scope {
}
}
registerConstantViolation(path) {
registerConstantViolation(path: NodePath) {
let ids = path.getBindingIdentifiers();
for (let name in ids) {
let binding = this.getBinding(name);
@ -492,11 +493,11 @@ export default class Scope {
}
}
registerBinding(kind, path, bindingPath = path) {
registerBinding(kind: string, path: NodePath, bindingPath = path) {
if (!kind) throw new ReferenceError("no `kind`");
if (path.isVariableDeclaration()) {
let declarators = path.get("declarations");
let declarators: Array<NodePath> = path.get("declarations");
for (let declar of declarators) {
this.registerBinding(kind, declar);
}
@ -507,7 +508,7 @@ export default class Scope {
let ids = path.getBindingIdentifiers(true);
for (let name in ids) {
for (let id of ids[name]) {
for (let id of (ids[name]: Array<Object>)) {
let local = this.getOwnBinding(name);
if (local) {
// same identifier so continue safely as we're likely trying to register it
@ -530,11 +531,11 @@ export default class Scope {
}
}
addGlobal(node) {
addGlobal(node: Object) {
this.globals[node.name] = node;
}
hasUid(name) {
hasUid(name): boolean {
let scope = this;
do {
@ -544,7 +545,7 @@ export default class Scope {
return false;
}
hasGlobal(name) {
hasGlobal(name: string): boolean {
let scope = this;
do {
@ -554,7 +555,7 @@ export default class Scope {
return false;
}
hasReference(name) {
hasReference(name: string): boolean {
let scope = this;
do {
@ -564,7 +565,7 @@ export default class Scope {
return false;
}
isPure(node, constantsOnly) {
isPure(node, constantsOnly?: boolean) {
if (t.isIdentifier(node)) {
let binding = this.getBinding(node.name);
if (!binding) return false;
@ -581,12 +582,12 @@ export default class Scope {
} else if (t.isBinary(node)) {
return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly);
} else if (t.isArrayExpression(node)) {
for (let elem of node.elements) {
for (let elem of (node.elements: Array<Object>)) {
if (!this.isPure(elem, constantsOnly)) return false;
}
return true;
} else if (t.isObjectExpression(node)) {
for (let prop of node.properties) {
for (let prop of (node.properties: Array<Object>)) {
if (!this.isPure(prop, constantsOnly)) return false;
}
return true;
@ -655,7 +656,7 @@ export default class Scope {
// ForStatement - left, init
if (path.isLoop()) {
for (let key of t.FOR_INIT_KEYS) {
for (let key of (t.FOR_INIT_KEYS: Array<string>)) {
let node = path.get(key);
if (node.isBlockScoped()) this.registerBinding(node.node.kind, node);
}
@ -680,7 +681,7 @@ export default class Scope {
// Function - params, rest
if (path.isFunction()) {
let params = path.get("params");
let params: Array<NodePath> = path.get("params");
for (let param of params) {
this.registerBinding("param", param);
}
@ -739,7 +740,13 @@ export default class Scope {
}
}
push(opts) {
push(opts: {
id: Object;
init: ?Object;
unique: ?boolean;
_blockHoist: ?number;
kind: "var" | "let";
}) {
let path = this.path;
if (!path.isBlockStatement() && !path.isProgram()) {
@ -824,7 +831,7 @@ export default class Scope {
* Walks the scope tree and gathers **all** bindings.
*/
getAllBindings() {
getAllBindings(): Object {
let ids = Object.create(null);
let scope = this;
@ -840,10 +847,10 @@ export default class Scope {
* Walks the scope tree and gathers all declarations of `kind`.
*/
getAllBindingsOfKind() {
getAllBindingsOfKind(): Object {
let ids = Object.create(null);
for (let kind of arguments) {
for (let kind of (arguments: Array)) {
let scope = this;
do {
for (let name in scope.bindings) {
@ -857,11 +864,11 @@ export default class Scope {
return ids;
}
bindingIdentifierEquals(name, node) {
bindingIdentifierEquals(name: string, node: Object): boolean {
return this.getBindingIdentifier(name) === node;
}
getBinding(name) {
getBinding(name: string) {
let scope = this;
do {
@ -870,25 +877,25 @@ export default class Scope {
} while (scope = scope.parent);
}
getOwnBinding(name) {
getOwnBinding(name: string) {
return this.bindings[name];
}
getBindingIdentifier(name) {
getBindingIdentifier(name: string) {
let info = this.getBinding(name);
return info && info.identifier;
}
getOwnBindingIdentifier(name) {
getOwnBindingIdentifier(name: string) {
let binding = this.bindings[name];
return binding && binding.identifier;
}
hasOwnBinding(name) {
hasOwnBinding(name: string) {
return !!this.getOwnBinding(name);
}
hasBinding(name, noGlobals) {
hasBinding(name: string, noGlobals?) {
if (!name) return false;
if (this.hasOwnBinding(name)) return true;
if (this.parentHasBinding(name, noGlobals)) return true;
@ -898,7 +905,7 @@ export default class Scope {
return false;
}
parentHasBinding(name, noGlobals) {
parentHasBinding(name: string, noGlobals?) {
return this.parent && this.parent.hasBinding(name, noGlobals);
}
@ -915,11 +922,11 @@ export default class Scope {
}
}
removeOwnBinding(name) {
removeOwnBinding(name: string) {
delete this.bindings[name];
}
removeBinding(name) {
removeBinding(name: string) {
// clear literal binding
let info = this.getBinding(name);
if (info) {

View File

@ -27,7 +27,7 @@ export function explode(visitor) {
for (let nodeType in visitor) {
if (shouldIgnoreKey(nodeType)) continue;
let parts = nodeType.split("|");
let parts: Array<string> = nodeType.split("|");
if (parts.length === 1) continue;
let fns = visitor[nodeType];
@ -52,7 +52,7 @@ export function explode(visitor) {
ensureCallbackArrays(visitor);
// add type wrappers
for (let nodeType of Object.keys(visitor)) {
for (let nodeType of (Object.keys(visitor): Array)) {
if (shouldIgnoreKey(nodeType)) continue;
let wrapper = virtualTypes[nodeType];
@ -68,7 +68,7 @@ export function explode(visitor) {
delete visitor[nodeType];
if (wrapper.types) {
for (let type of wrapper.types) {
for (let type of (wrapper.types: Array<string>)) {
// merge the visitor if necessary or just put it back in
if (visitor[type]) {
mergePair(visitor[type], fns);
@ -87,7 +87,7 @@ export function explode(visitor) {
let fns = visitor[nodeType];
let aliases = t.FLIPPED_ALIAS_KEYS[nodeType];
let aliases: ?Array<string> = t.FLIPPED_ALIAS_KEYS[nodeType];
let deprecratedKey = t.DEPRECATED_KEYS[nodeType];
if (deprecratedKey) {
@ -162,7 +162,7 @@ function validateVisitorMethods(path, val) {
}
}
export function merge(visitors, states = []) {
export function merge(visitors: Array, states: Array = []) {
let rootVisitor = {};
for (let i = 0; i < visitors.length; i++) {

View File

@ -3,9 +3,10 @@ import isNumber from "lodash/lang/isNumber";
import isRegExp from "lodash/lang/isRegExp";
import isString from "lodash/lang/isString";
import traverse from "babel-traverse";
import type { Scope } from "babel-traverse";
import * as t from "./index";
export function toComputedKey(node, key = node.key || node.property) {
export function toComputedKey(node: Object, key: Object = node.key || node.property): Object {
if (!node.computed) {
if (t.isIdentifier(key)) key = t.stringLiteral(key.name);
}
@ -21,7 +22,7 @@ export function toComputedKey(node, key = node.key || node.property) {
* Expression statements are just resolved to their expression.
*/
export function toSequenceExpression(nodes, scope) {
export function toSequenceExpression(nodes: Array<Object>, scope: Scope): ?Object {
if (!nodes || !nodes.length) return;
let declars = [];
@ -40,7 +41,7 @@ export function toSequenceExpression(nodes, scope) {
let ensureLastUndefined = false;
let exprs = [];
for (let node of nodes) {
for (let node of (nodes: Array)) {
if (t.isExpression(node)) {
exprs.push(node);
} else if (t.isExpressionStatement(node)) {
@ -48,7 +49,7 @@ export function toSequenceExpression(nodes, scope) {
} else if (t.isVariableDeclaration(node)) {
if (node.kind !== "var") return bailed = true; // bailed
for (let declar of node.declarations) {
for (let declar of (node.declarations: Array)) {
let bindings = t.getBindingIdentifiers(declar);
for (let key in bindings) {
declars.push({
@ -98,7 +99,7 @@ export function toSequenceExpression(nodes, scope) {
}
}
export function toKeyAlias(node, key = node.key) {
export function toKeyAlias(node: Object, key: Object = node.key): string {
let alias;
if (node.kind === "method") {
@ -132,7 +133,7 @@ toKeyAlias.increment = function () {
}
};
export function toIdentifier(name) {
export function toIdentifier(name: string): string {
name = name + "";
// replace all non-valid identifiers with dashes
@ -153,7 +154,7 @@ export function toIdentifier(name) {
return name || "_";
}
export function toBindingIdentifierName(name) {
export function toBindingIdentifierName(name: string): string {
name = toIdentifier(name);
if (name === "eval" || name === "arguments") name = "_" + name;
return name;
@ -164,7 +165,7 @@ export function toBindingIdentifierName(name) {
* @returns {Object|Boolean}
*/
export function toStatement(node, ignore) {
export function toStatement(node: Object, ignore?: boolean) {
if (t.isStatement(node)) {
return node;
}
@ -199,7 +200,7 @@ export function toStatement(node, ignore) {
return node;
}
export function toExpression(node) {
export function toExpression(node: Object): Object {
if (t.isExpressionStatement(node)) {
node = node.expression;
}
@ -217,7 +218,7 @@ export function toExpression(node) {
}
}
export function toBlock(node, parent) {
export function toBlock(node: Object, parent: Object): Object {
if (t.isBlockStatement(node)) {
return node;
}
@ -241,7 +242,7 @@ export function toBlock(node, parent) {
return t.blockStatement(node);
}
export function valueToNode(value) {
export function valueToNode(value: any): Object {
// undefined
if (value === undefined) {
return t.identifier("undefined");

View File

@ -1,4 +1,3 @@
import defineType, { assertNodeType } from "./index";
defineType("AwaitExpression", {

View File

@ -1,4 +1,3 @@
import defineType from "./index";
defineType("AnyTypeAnnotation", {

View File

@ -18,7 +18,7 @@ function getType(val) {
}
}
export function assertEach(callback) {
export function assertEach(callback: Function): Function {
function validator(node, key, val) {
if (!Array.isArray(val)) return;
@ -30,7 +30,7 @@ export function assertEach(callback) {
return validator;
}
export function assertOneOf(...vals) {
export function assertOneOf(...vals): Function {
function validate(node, key, val) {
if (vals.indexOf(val) < 0) {
throw new TypeError(
@ -44,7 +44,7 @@ export function assertOneOf(...vals) {
return validate;
}
export function assertNodeType(...types) {
export function assertNodeType(...types: Array<string>): Function {
function validate(node, key, val) {
let valid = false;
@ -68,7 +68,7 @@ export function assertNodeType(...types) {
return validate;
}
export function assertNodeOrValueType(...types) {
export function assertNodeOrValueType(...types: Array<string>): Function {
function validate(node, key, val) {
let valid = false;
@ -92,7 +92,7 @@ export function assertNodeOrValueType(...types) {
return validate;
}
export function assertValueType(type) {
export function assertValueType(type: string): Function {
function validate(node, key, val) {
let valid = getType(val) === type;
@ -106,7 +106,7 @@ export function assertValueType(type) {
return validate;
}
export function chain(...fns) {
export function chain(...fns: Array<Function>): Function {
function validate(...args) {
for (let fn of fns) {
fn(...args);
@ -116,7 +116,16 @@ export function chain(...fns) {
return validate;
}
export default function defineType(type, opts = {}) {
export default function defineType(
type: string,
opts: {
fields?: Object;
visitor?: Array<string>;
aliases?: Array<string>;
builder?: Array<string>;
inherits?: string;
} = {},
) {
let inherits = (opts.inherits && store[opts.inherits]) || {};
opts.fields = opts.fields || inherits.fields || {};
@ -129,7 +138,7 @@ export default function defineType(type, opts = {}) {
}
// ensure all field keys are represented in `fields`
for (let key of opts.visitor.concat(opts.builder)) {
for (let key of (opts.visitor.concat(opts.builder): Array<string>)) {
opts.fields[key] = opts.fields[key] || {};
}

Some files were not shown because too many files have changed in this diff Show More