diff --git a/packages/babel-code-frame/src/index.js b/packages/babel-code-frame/src/index.js index fc4eb9e376..a42a5f3229 100644 --- a/packages/babel-code-frame/src/index.js +++ b/packages/babel-code-frame/src/index.js @@ -1,3 +1,4 @@ +/* @flow */ /* eslint indent: 0 */ /* eslint max-len: 0 */ @@ -61,7 +62,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 +78,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; diff --git a/packages/babel-core/src/helpers/merge.js b/packages/babel-core/src/helpers/merge.js index 0ee0c9e7c9..962f255926 100644 --- a/packages/babel-core/src/helpers/merge.js +++ b/packages/babel-core/src/helpers/merge.js @@ -1,8 +1,8 @@ - +/* @flow */ 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) { diff --git a/packages/babel-core/src/helpers/normalize-ast.js b/packages/babel-core/src/helpers/normalize-ast.js index 607883d923..cd8881a9fd 100644 --- a/packages/babel-core/src/helpers/normalize-ast.js +++ b/packages/babel-core/src/helpers/normalize-ast.js @@ -1,3 +1,4 @@ +/* @flow */ import * as t from "babel-types"; @@ -7,7 +8,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, + tokens?: Array, +) { if (ast) { if (ast.type === "Program") { return t.file(ast, comments || [], tokens || []); diff --git a/packages/babel-core/src/transformation/file/index.js b/packages/babel-core/src/transformation/file/index.js index 1e3c0f3132..9b1d4647a5 100644 --- a/packages/babel-core/src/transformation/file/index.js +++ b/packages/babel-core/src/transformation/file/index.js @@ -4,10 +4,10 @@ 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 +39,7 @@ let errorVisitor = { }; export default class File extends Store { - constructor(opts = {}, pipeline) { + constructor(opts: Object = {}, pipeline: Pipeline) { super(); this.pipeline = pipeline; @@ -100,9 +100,30 @@ export default class File extends Store { this.hub = new Hub(this); } + static helpers: Array; + + pluginVisitors: Array; + pluginPasses: Array; + pipeline: Pipeline; + parserOpts: BabelParserOptions; + log: Logger; + opts: Object; + dynamicImportTypes: Object; + dynamicImportIds: Object; + dynamicImports: Array; + 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)) { if (t.isModuleDeclaration(node)) { has = true; break; @@ -157,7 +178,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 +198,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 +242,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 +275,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 +314,11 @@ export default class File extends Store { return uid; } - addTemplateObject(helperName, strings, raw) { + addTemplateObject( + helperName: string, + strings: Array, + 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 +342,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 +364,7 @@ export default class File extends Store { return err; } - mergeSourceMap(map) { + mergeSourceMap(map: Object) { let inputMap = this.opts.inputSourceMap; if (inputMap) { @@ -383,7 +408,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 +434,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 +448,7 @@ export default class File extends Store { return this.generate(); } - wrap(code, callback) { + wrap(code: string, callback: Function): BabelFileResult { code = code + ""; try { @@ -462,7 +487,7 @@ export default class File extends Store { } } - addCode(code) { + addCode(code: string) { code = (code || "") + ""; code = this.parseInputSourceMap(code); this.code = code; @@ -479,7 +504,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) { for (let pass of pluginPasses) { let plugin = pass.plugin; let fn = plugin[key]; @@ -487,7 +512,7 @@ export default class File extends Store { } } - parseInputSourceMap(code) { + parseInputSourceMap(code: string): string { let opts = this.opts; if (opts.inputSourceMap !== false) { @@ -509,7 +534,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 +559,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"); diff --git a/packages/babel-core/src/transformation/file/options/index.js b/packages/babel-core/src/transformation/file/options/index.js index 4683c1ef52..521f8193e9 100644 --- a/packages/babel-core/src/transformation/file/options/index.js +++ b/packages/babel-core/src/transformation/file/options/index.js @@ -1,10 +1,11 @@ +/* @flow */ 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; diff --git a/packages/babel-core/src/transformation/file/options/parsers.js b/packages/babel-core/src/transformation/file/options/parsers.js index 3f33915b8f..840c6e5f6c 100644 --- a/packages/babel-core/src/transformation/file/options/parsers.js +++ b/packages/babel-core/src/transformation/file/options/parsers.js @@ -1,18 +1,18 @@ - +/* @flow */ 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 { return util.list(val); } diff --git a/packages/babel-core/src/transformation/internal-plugins/block-hoist.js b/packages/babel-core/src/transformation/internal-plugins/block-hoist.js index 5af3311fc0..a0b5fab150 100644 --- a/packages/babel-core/src/transformation/internal-plugins/block-hoist.js +++ b/packages/babel-core/src/transformation/internal-plugins/block-hoist.js @@ -1,3 +1,4 @@ +/* @flow */ import Plugin from "../plugin"; import sortBy from "lodash/collection/sortBy"; diff --git a/packages/babel-core/src/transformation/pipeline.js b/packages/babel-core/src/transformation/pipeline.js index 7844635b39..cbaf7fc32b 100644 --- a/packages/babel-core/src/transformation/pipeline.js +++ b/packages/babel-core/src/transformation/pipeline.js @@ -1,15 +1,19 @@ +/* @flow */ +/* global BabelFileResult */ +/* global 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 +22,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 +31,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 +40,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); diff --git a/packages/babel-core/src/transformation/plugin.js b/packages/babel-core/src/transformation/plugin.js index 4cd325b15a..641ed06b40 100644 --- a/packages/babel-core/src/transformation/plugin.js +++ b/packages/babel-core/src/transformation/plugin.js @@ -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 = [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."); diff --git a/packages/babel-core/src/util.js b/packages/babel-core/src/util.js index d87e845a92..8c1c1b1d80 100644 --- a/packages/babel-core/src/util.js +++ b/packages/babel-core/src/util.js @@ -1,3 +1,4 @@ +/* @flow */ import escapeRegExp from "lodash/string/escapeRegExp"; import startsWith from "lodash/string/startsWith"; @@ -15,7 +16,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): boolean { let exts = altExts || canCompile.EXTENSIONS; let ext = path.extname(filename); return contains(exts, ext); @@ -31,7 +32,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 { if (!val) { return []; } else if (Array.isArray(val)) { @@ -47,7 +48,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 +80,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 { if (!val) return []; if (isBoolean(val)) return arrayify([val], mapFn); if (isString(val)) return arrayify(list(val), mapFn); @@ -96,7 +97,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 +113,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 = [], + only?: Array, +): boolean { filename = slash(filename); if (only) { @@ -134,7 +139,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 { diff --git a/packages/babel-generator/src/buffer.js b/packages/babel-generator/src/buffer.js index 3cfcf10102..af8f91ac01 100644 --- a/packages/babel-generator/src/buffer.js +++ b/packages/babel-generator/src/buffer.js @@ -1,4 +1,6 @@ +/* @flow */ +import type Position from "./position"; import repeating from "repeating"; import trimRight from "trim-right"; @@ -7,7 +9,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 +23,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 +48,7 @@ export default class Buffer { * Get the current trimmed buffer. */ - get() { + get(): string { return trimRight(this.buf); } @@ -46,7 +56,7 @@ export default class Buffer { * Get the current indent. */ - getIndent() { + getIndent(): string { if (this.format.compact || this.format.concise) { return ""; } else { @@ -58,7 +68,7 @@ export default class Buffer { * Get the current indent size. */ - indentSize() { + indentSize(): number { return this.getIndent().length; } @@ -110,7 +120,7 @@ export default class Buffer { * Add a keyword to the buffer. */ - keyword(name) { + keyword(name: string) { this.push(name); this.space(); } @@ -119,7 +129,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 +141,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 +169,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 +179,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 +192,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 +236,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 +255,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 +288,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 +300,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)) { diff --git a/packages/babel-generator/src/generators/base.js b/packages/babel-generator/src/generators/base.js index 11d878646c..9868dfe7f5 100644 --- a/packages/babel-generator/src/generators/base.js +++ b/packages/babel-generator/src/generators/base.js @@ -1,9 +1,10 @@ +/* @flow */ -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 +13,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 +32,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)); } diff --git a/packages/babel-generator/src/generators/classes.js b/packages/babel-generator/src/generators/classes.js index bf1155fa05..c1bb4cf0f3 100644 --- a/packages/babel-generator/src/generators/classes.js +++ b/packages/babel-generator/src/generators/classes.js @@ -1,5 +1,6 @@ +/* @flow */ -export function ClassDeclaration(node) { +export function ClassDeclaration(node: Object) { this.printJoin(node.decorators, node, { separator: "" }); this.push("class"); @@ -27,7 +28,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 +44,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 +59,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) { diff --git a/packages/babel-generator/src/generators/expressions.js b/packages/babel-generator/src/generators/expressions.js index 13c3d02c16..1f302a4342 100644 --- a/packages/babel-generator/src/generators/expressions.js +++ b/packages/babel-generator/src/generators/expressions.js @@ -1,3 +1,4 @@ +/* @flow */ /* eslint max-len: 0 */ import isInteger from "is-integer"; @@ -9,7 +10,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 +27,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 +49,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 +61,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 +74,7 @@ export function NewExpression(node, parent) { this.push(")"); } -export function SequenceExpression(node) { +export function SequenceExpression(node: Object) { this.printList(node.expressions, node); } @@ -85,13 +86,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 +117,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 +142,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 +155,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 +196,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 +207,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 +240,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); diff --git a/packages/babel-generator/src/generators/flow.js b/packages/babel-generator/src/generators/flow.js index b29e51526b..07562c17b1 100644 --- a/packages/babel-generator/src/generators/flow.js +++ b/packages/babel-generator/src/generators/flow.js @@ -1,3 +1,4 @@ +/* @flow */ /* eslint max-len: 0 */ import * as t from "babel-types"; @@ -6,7 +7,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 +17,7 @@ export function BooleanTypeAnnotation() { this.push("bool"); } -export function BooleanLiteralTypeAnnotation(node) { +export function BooleanLiteralTypeAnnotation(node: Object) { this.push(node.value ? "true" : "false"); } @@ -24,36 +25,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 +65,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 +93,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 +101,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 +123,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 +136,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 +147,7 @@ export function NumberTypeAnnotation() { this.push("number"); } -export function StringLiteralTypeAnnotation(node) { +export function StringLiteralTypeAnnotation(node: Object) { this.push(this._stringLiteral(node.value)); } @@ -158,18 +159,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 +181,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 +201,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 +225,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 +243,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 +254,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); diff --git a/packages/babel-generator/src/generators/jsx.js b/packages/babel-generator/src/generators/jsx.js index 849f3339f6..310a26209f 100644 --- a/packages/babel-generator/src/generators/jsx.js +++ b/packages/babel-generator/src/generators/jsx.js @@ -1,6 +1,6 @@ +/* @flow */ - -export function JSXAttribute(node) { +export function JSXAttribute(node: Object) { this.print(node.name, node); if (node.value) { this.push("="); @@ -8,45 +8,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)) { this.print(child, node); } this.dedent(); @@ -54,7 +54,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 +64,7 @@ export function JSXOpeningElement(node) { this.push(node.selfClosing ? " />" : ">"); } -export function JSXClosingElement(node) { +export function JSXClosingElement(node: Object) { this.push(""); diff --git a/packages/babel-generator/src/generators/methods.js b/packages/babel-generator/src/generators/methods.js index 4c4bec94d7..b72760055e 100644 --- a/packages/babel-generator/src/generators/methods.js +++ b/packages/babel-generator/src/generators/methods.js @@ -1,8 +1,8 @@ - +/* @flow */ 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 +18,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 +47,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 +66,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])) { diff --git a/packages/babel-generator/src/generators/modules.js b/packages/babel-generator/src/generators/modules.js index bba6106697..87aace643f 100644 --- a/packages/babel-generator/src/generators/modules.js +++ b/packages/babel-generator/src/generators/modules.js @@ -1,7 +1,8 @@ +/* @flow */ 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 +10,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 +26,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 +52,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 +98,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 +135,7 @@ export function ImportDeclaration(node) { this.semicolon(); } -export function ImportNamespaceSpecifier(node) { +export function ImportNamespaceSpecifier(node: Object) { this.push("* as "); this.print(node.local, node); } diff --git a/packages/babel-generator/src/generators/statements.js b/packages/babel-generator/src/generators/statements.js index 9ffaa964f0..1d46a7d1b1 100644 --- a/packages/babel-generator/src/generators/statements.js +++ b/packages/babel-generator/src/generators/statements.js @@ -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)) { 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) { diff --git a/packages/babel-generator/src/generators/template-literals.js b/packages/babel-generator/src/generators/template-literals.js index fab66c941b..6b815a0a57 100644 --- a/packages/babel-generator/src/generators/template-literals.js +++ b/packages/babel-generator/src/generators/template-literals.js @@ -1,14 +1,15 @@ +/* @flow */ -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; diff --git a/packages/babel-generator/src/generators/types.js b/packages/babel-generator/src/generators/types.js index 067f26be29..5c40209172 100644 --- a/packages/babel-generator/src/generators/types.js +++ b/packages/babel-generator/src/generators/types.js @@ -1,13 +1,14 @@ +/* @flow */ /* eslint max-len: 0 */ /* eslint quotes: 0 */ 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 +19,7 @@ export { RestElement as RestProperty, }; -export function ObjectExpression(node) { +export function ObjectExpression(node: Object) { let props = node.properties; this.push("{"); @@ -35,12 +36,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 +71,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 +99,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 +111,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 diff --git a/packages/babel-generator/src/node/parentheses.js b/packages/babel-generator/src/node/parentheses.js index 0f78d5276a..0c2bba3c5a 100644 --- a/packages/babel-generator/src/node/parentheses.js +++ b/packages/babel-generator/src/node/parentheses.js @@ -1,3 +1,4 @@ +/* @flow */ import * as t from "babel-types"; @@ -28,13 +29,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 +44,7 @@ export function UpdateExpression(node, parent) { return false; } -export function ObjectExpression(node, parent, printStack) { +export function ObjectExpression(node: Object, parent: Object, printStack: Array): boolean { if (t.isExpressionStatement(parent)) { // ({ foo: "bar" }); return true; @@ -52,7 +53,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 +86,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 +102,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 +144,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 +154,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 +168,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 +180,7 @@ export function UnaryLike(node, parent) { return false; } -export function FunctionExpression(node, parent, printStack) { +export function FunctionExpression(node: Object, parent: Object, printStack: Array): boolean { // (function () {}); if (t.isExpressionStatement(parent)) { return true; @@ -193,7 +194,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 +211,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 +227,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 +237,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, considerArrow: bool = false): boolean { let i = printStack.length - 1; let node = printStack[i]; i--; diff --git a/packages/babel-generator/src/node/whitespace.js b/packages/babel-generator/src/node/whitespace.js index 19cba52455..2126c9110b 100644 --- a/packages/babel-generator/src/node/whitespace.js +++ b/packages/babel-generator/src/node/whitespace.js @@ -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 { return map(node.declarations, "init"); }, @@ -189,7 +194,7 @@ exports.list = { * Return VariableDeclaration elements. */ - ArrayExpression(node) { + ArrayExpression(node: Object): Array { return node.elements; }, @@ -197,7 +202,7 @@ exports.list = { * Return VariableDeclaration properties. */ - ObjectExpression(node) { + ObjectExpression(node: Object): Array { return node.properties; } }; diff --git a/packages/babel-generator/src/position.js b/packages/babel-generator/src/position.js index 31454e8bdc..c653792ba7 100644 --- a/packages/babel-generator/src/position.js +++ b/packages/babel-generator/src/position.js @@ -1,9 +1,12 @@ +/* @flow */ /** * Track current position in code generation. */ export default class Position { + column: number; + line: number; constructor() { this.line = 1; @@ -14,7 +17,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 +32,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--; diff --git a/packages/babel-helper-builder-binary-assignment-operator-visitor/src/index.js b/packages/babel-helper-builder-binary-assignment-operator-visitor/src/index.js index 2363df4abc..5f4a2aec4d 100644 --- a/packages/babel-helper-builder-binary-assignment-operator-visitor/src/index.js +++ b/packages/babel-helper-builder-binary-assignment-operator-visitor/src/index.js @@ -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) { diff --git a/packages/babel-helper-builder-conditional-assignment-operator-visitor/src/index.js b/packages/babel-helper-builder-conditional-assignment-operator-visitor/src/index.js index fcdbc5d8f8..bf8f9d48b9 100644 --- a/packages/babel-helper-builder-conditional-assignment-operator-visitor/src/index.js +++ b/packages/babel-helper-builder-conditional-assignment-operator-visitor/src/index.js @@ -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); }; diff --git a/packages/babel-helper-regex/src/index.js b/packages/babel-helper-regex/src/index.js index 7ef828019f..6077c3a2b5 100644 --- a/packages/babel-helper-regex/src/index.js +++ b/packages/babel-helper-regex/src/index.js @@ -1,13 +1,13 @@ - +/* @flow */ 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); diff --git a/packages/babel-helper-remap-async-to-generator/src/index.js b/packages/babel-helper-remap-async-to-generator/src/index.js index 14e7be43b0..78625ac6bc 100644 --- a/packages/babel-helper-remap-async-to-generator/src/index.js +++ b/packages/babel-helper-remap-async-to-generator/src/index.js @@ -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; diff --git a/packages/babel-messages/src/index.js b/packages/babel-messages/src/index.js index 5790540033..4f33f6a250 100644 --- a/packages/babel-messages/src/index.js +++ b/packages/babel-messages/src/index.js @@ -1,3 +1,4 @@ +/* @flow */ /* eslint max-len: 0 */ import * as util from "util"; @@ -47,7 +48,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): string { let msg = MESSAGES[key]; if (!msg) throw new ReferenceError(`Unknown message ${JSON.stringify(key)}`); @@ -64,7 +65,7 @@ export function get(key, ...args) { * Stingify arguments to be used inside messages. */ -export function parseArgs(args) { +export function parseArgs(args: Array): Array { return args.map(function (val) { if (val != null && val.inspect) { return val.inspect(); diff --git a/packages/babel-register/src/node.js b/packages/babel-register/src/node.js index c1863843d5..da9a08e87c 100644 --- a/packages/babel-register/src/node.js +++ b/packages/babel-register/src/node.js @@ -1,3 +1,4 @@ +/* @flow */ import deepClone from "lodash/lang/cloneDeep"; import sourceMapSupport from "source-map-support"; @@ -128,7 +129,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); diff --git a/packages/babel-types/src/converters.js b/packages/babel-types/src/converters.js index fdeb3e9526..bcbc7efbe3 100644 --- a/packages/babel-types/src/converters.js +++ b/packages/babel-types/src/converters.js @@ -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, 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"); diff --git a/packages/babel-types/src/definitions/es2015.js b/packages/babel-types/src/definitions/es2015.js index 87512202d4..60916e5e77 100644 --- a/packages/babel-types/src/definitions/es2015.js +++ b/packages/babel-types/src/definitions/es2015.js @@ -1,3 +1,4 @@ +/* @flow */ /* eslint max-len: 0 */ import defineType, { diff --git a/packages/babel-types/src/definitions/experimental.js b/packages/babel-types/src/definitions/experimental.js index 0c132d4ec9..eb85a19fc1 100644 --- a/packages/babel-types/src/definitions/experimental.js +++ b/packages/babel-types/src/definitions/experimental.js @@ -1,3 +1,4 @@ +/* @flow */ import defineType, { assertNodeType } from "./index"; diff --git a/packages/babel-types/src/definitions/flow.js b/packages/babel-types/src/definitions/flow.js index 5f77b63b55..1e87ac165f 100644 --- a/packages/babel-types/src/definitions/flow.js +++ b/packages/babel-types/src/definitions/flow.js @@ -1,3 +1,4 @@ +/* @flow */ import defineType from "./index"; diff --git a/packages/babel-types/src/definitions/index.js b/packages/babel-types/src/definitions/index.js index 5311163635..ef1c8ae6bd 100644 --- a/packages/babel-types/src/definitions/index.js +++ b/packages/babel-types/src/definitions/index.js @@ -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): 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): 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 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; + aliases?: Array; + builder?: Array; + 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)) { opts.fields[key] = opts.fields[key] || {}; } diff --git a/packages/babel-types/src/definitions/jsx.js b/packages/babel-types/src/definitions/jsx.js index e7e9690fe8..9e724179dd 100644 --- a/packages/babel-types/src/definitions/jsx.js +++ b/packages/babel-types/src/definitions/jsx.js @@ -1,3 +1,4 @@ +/* @flow */ import defineType, { assertNodeType, assertValueType, chain, assertEach } from "./index"; diff --git a/packages/babel-types/src/definitions/misc.js b/packages/babel-types/src/definitions/misc.js index 01c6773c06..23e010da14 100644 --- a/packages/babel-types/src/definitions/misc.js +++ b/packages/babel-types/src/definitions/misc.js @@ -1,3 +1,4 @@ +/* @flow */ import defineType, { assertNodeType } from "./index"; diff --git a/packages/babel-types/src/flow.js b/packages/babel-types/src/flow.js index c5a27d7811..531471f2d8 100644 --- a/packages/babel-types/src/flow.js +++ b/packages/babel-types/src/flow.js @@ -1,3 +1,4 @@ +/* @flow */ import * as t from "./index"; @@ -6,7 +7,7 @@ import * as t from "./index"; * returns a `UnionTypeAnnotation` node containg them. */ -export function createUnionTypeAnnotation(types) { +export function createUnionTypeAnnotation(types: Array) { let flattened = removeTypeDuplicates(types); if (flattened.length === 1) { @@ -20,7 +21,7 @@ export function createUnionTypeAnnotation(types) { * Dedupe type annotations. */ -export function removeTypeDuplicates(nodes) { +export function removeTypeDuplicates(nodes: Array): Array { let generics = {}; let bases = {}; @@ -100,7 +101,7 @@ export function removeTypeDuplicates(nodes) { * Create a type anotation based on typeof expression. */ -export function createTypeAnnotationBasedOnTypeof(type) { +export function createTypeAnnotationBasedOnTypeof(type: string) { if (type === "string") { return t.stringTypeAnnotation(); } else if (type === "number") { diff --git a/packages/babel-types/src/index.js b/packages/babel-types/src/index.js index 03cac174eb..c0abb139f0 100644 --- a/packages/babel-types/src/index.js +++ b/packages/babel-types/src/index.js @@ -1,3 +1,4 @@ +/* @flow */ import toFastProperties from "to-fast-properties"; import compact from "lodash/array/compact"; @@ -12,7 +13,7 @@ let t = exports; * Pass `skipAliasCheck` to force it to directly compare `node.type` with `type`. */ -function registerType(type) { +function registerType(type: string) { let is = t[`is${type}`] = function (node, opts) { return t.is(type, node, opts); }; @@ -77,7 +78,7 @@ export const TYPES = Object.keys(t.VISITOR_KEYS) * Optionally, pass `skipAliasCheck` to directly compare `node.type` with `type`. */ -export function is(type, node, opts) { +export function is(type: string, node: Object, opts?: Object): boolean { if (!node) return false; let matches = isType(node.type, type); @@ -94,7 +95,7 @@ export function is(type, node, opts) { * Test if a `nodeType` is a `targetType` or if `targetType` is an alias of `nodeType`. */ -export function isType(nodeType, targetType) { +export function isType(nodeType: string, targetType: string): boolean { if (nodeType === targetType) return true; let aliases: ?Array = t.FLIPPED_ALIAS_KEYS[targetType]; @@ -127,7 +128,7 @@ each(t.BUILDER_KEYS, function (keys, type) { let i = 0; - for (let key of keys) { + for (let key of (keys: Array)) { let field = t.NODE_FIELDS[type][key]; let arg = arguments[i++]; @@ -170,7 +171,7 @@ for (let type in t.DEPRECATED_KEYS) { * Description */ -export function validate(node, key, val) { +export function validate(node?: Object, key: string, val: any) { if (!node) return; let fields = t.NODE_FIELDS[node.type]; @@ -187,10 +188,10 @@ export function validate(node, key, val) { * Test if an object is shallowly equal. */ -export function shallowEqual(actual, expected) { +export function shallowEqual(actual: Object, expected: Object): boolean { let keys = Object.keys(expected); - for (let key of keys) { + for (let key of (keys: Array)) { if (actual[key] !== expected[key]) { return false; } @@ -203,7 +204,7 @@ export function shallowEqual(actual, expected) { * Append a node to a member expression. */ -export function appendToMemberExpression(member, append, computed) { +export function appendToMemberExpression(member: Object, append: Object, computed?: boolean): Object { member.object = t.memberExpression(member.object, member.property, member.computed); member.property = append; member.computed = !!computed; @@ -214,7 +215,7 @@ export function appendToMemberExpression(member, append, computed) { * Prepend a node to a member expression. */ -export function prependToMemberExpression(member, prepend) { +export function prependToMemberExpression(member: Object, prepend: Object): Object { member.object = t.memberExpression(prepend, member.object); return member; } @@ -224,7 +225,7 @@ export function prependToMemberExpression(member, prepend) { * Casting it to a block if it is not. */ -export function ensureBlock(node, key = "body") { +export function ensureBlock(node: Object, key: string = "body"): Object { return node[key] = t.toBlock(node[key], node); } @@ -232,7 +233,7 @@ export function ensureBlock(node, key = "body") { * Create a shallow clone of a `node` excluding `_private` properties. */ -export function clone(node) { +export function clone(node: Object): Object { let newNode = {}; for (let key in node) { if (key[0] === "_") continue; @@ -245,7 +246,7 @@ export function clone(node) { * Create a shallow clone of a `node` excluding `_private` and location properties. */ -export function cloneWithoutLoc(node) { +export function cloneWithoutLoc(node: Object): Object { let newNode = clone(node); delete newNode.loc; return newNode; @@ -256,7 +257,7 @@ export function cloneWithoutLoc(node) { * exluding `_private` properties. */ -export function cloneDeep(node) { +export function cloneDeep(node: Object): Object { let newNode = {}; for (let key in node) { @@ -286,7 +287,7 @@ export function cloneDeep(node) { * parsed nodes of `React.createClass` and `React["createClass"]`. */ -export function buildMatchMemberExpression(match, allowPartial) { +export function buildMatchMemberExpression(match:string, allowPartial?: boolean): Function { let parts = match.split("."); return function (member) { @@ -337,7 +338,7 @@ export function buildMatchMemberExpression(match, allowPartial) { * Remove comment properties from a node. */ -export function removeComments(node) { +export function removeComments(node: Object): Object { for (let key of t.COMMENT_KEYS) { delete node[key]; } @@ -348,22 +349,22 @@ export function removeComments(node) { * Inherit all unique comments from `parent` node to `child` node. */ -export function inheritsComments(child, parent) { +export function inheritsComments(child: Object, parent: Object): Object { inheritTrailingComments(child, parent); inheritLeadingComments(child, parent); inheritInnerComments(child, parent); return child; } -export function inheritTrailingComments(child, parent) { +export function inheritTrailingComments(child: Object, parent: Object) { _inheritComments("trailingComments", child, parent); } -export function inheritLeadingComments(child, parent) { +export function inheritLeadingComments(child: Object, parent: Object) { _inheritComments("leadingComments", child, parent); } -export function inheritInnerComments(child, parent) { +export function inheritInnerComments(child: Object, parent: Object) { _inheritComments("innerComments", child, parent); } @@ -377,11 +378,11 @@ function _inheritComments(key, child, parent) { * Inherit all contextual properties from `parent` node to `child` node. */ -export function inherits(child, parent) { +export function inherits(child: Object, parent: Object): Object { if (!child || !parent) return child; // optionally inherit specific properties if not null - for (let key of t.INHERIT_KEYS.optional) { + for (let key of (t.INHERIT_KEYS.optional: Array)) { if (child[key] == null) { child[key] = parent[key]; } @@ -393,7 +394,7 @@ export function inherits(child, parent) { } // force inherit select properties - for (let key of t.INHERIT_KEYS.force) { + for (let key of (t.INHERIT_KEYS.force: Array)) { child[key] = parent[key]; } @@ -406,7 +407,7 @@ export function inherits(child, parent) { * TODO */ -export function assertNode(node) { +export function assertNode(node?) { if (!isNode(node)) { // $FlowFixMe throw new TypeError("Not a valid node " + (node && node.type)); @@ -417,7 +418,7 @@ export function assertNode(node) { * TODO */ -export function isNode(node) { +export function isNode(node?): boolean { return !!(node && VISITOR_KEYS[node.type]); } diff --git a/packages/babel-types/src/react.js b/packages/babel-types/src/react.js index 978a4b6353..8ec3f457b1 100644 --- a/packages/babel-types/src/react.js +++ b/packages/babel-types/src/react.js @@ -1,14 +1,17 @@ - +/* @flow */ import * as t from "./index"; export let isReactComponent = t.buildMatchMemberExpression("React.Component"); -export function isCompatTag(tagName) { +export function isCompatTag(tagName?: string): boolean { return !!tagName && /^[a-z]|\-/.test(tagName); } -function cleanJSXElementLiteralChild(child, args) { +function cleanJSXElementLiteralChild( + child: { value: string }, + args: Array, +) { let lines = child.value.split(/\r\n|\n|\r/); let lastNonEmptyLine = 0; @@ -53,7 +56,7 @@ function cleanJSXElementLiteralChild(child, args) { if (str) args.push(t.stringLiteral(str)); } -export function buildChildren(node) { +export function buildChildren(node: Object): Array { let elems = []; for (let i = 0; i < node.children.length; i++) { diff --git a/packages/babel-types/src/retrievers.js b/packages/babel-types/src/retrievers.js index 5014e59109..36eac28625 100644 --- a/packages/babel-types/src/retrievers.js +++ b/packages/babel-types/src/retrievers.js @@ -1,3 +1,4 @@ +/* @flow */ import * as t from "./index"; @@ -5,7 +6,11 @@ import * as t from "./index"; * Return a list of binding identifiers associated with the input `node`. */ -export function getBindingIdentifiers(node, duplicates, outerOnly) { +export function getBindingIdentifiers( + node: Object, + duplicates?: boolean, + outerOnly?: boolean +): Object { let search = [].concat(node); let ids = Object.create(null); @@ -102,6 +107,9 @@ getBindingIdentifiers.keys = { VariableDeclarator: ["id"] }; -export function getOuterBindingIdentifiers(node, duplicates) { +export function getOuterBindingIdentifiers( + node: Object, + duplicates?: boolean, +): Object { return getBindingIdentifiers(node, duplicates, true); } diff --git a/packages/babel-types/src/validators.js b/packages/babel-types/src/validators.js index 9b9c03c20b..4e57b2d656 100644 --- a/packages/babel-types/src/validators.js +++ b/packages/babel-types/src/validators.js @@ -1,3 +1,4 @@ +/* @flow */ /* eslint indent: 0 */ import { getBindingIdentifiers } from "./retrievers"; @@ -9,7 +10,7 @@ import { BLOCK_SCOPED_SYMBOL } from "./constants"; * Check if the input `node` is a binding identifier. */ -export function isBinding(node, parent) { +export function isBinding(node: Object, parent: Object): boolean { let keys = getBindingIdentifiers.keys[parent.type]; if (keys) { for (let i = 0; i < keys.length; i++) { @@ -30,7 +31,7 @@ export function isBinding(node, parent) { * Check if the input `node` is a reference to a bound variable. */ -export function isReferenced(node, parent) { +export function isReferenced(node: Object, parent: Object): boolean { switch (parent.type) { // yes: object::NODE // yes: NODE::callee @@ -73,7 +74,7 @@ export function isReferenced(node, parent) { case "ArrowFunctionExpression": case "FunctionDeclaration": case "FunctionExpression": - for (let param of parent.params) { + for (let param of (parent.params: Array)) { if (param === node) return false; } @@ -161,7 +162,7 @@ export function isReferenced(node, parent) { * and isn't a reserved word. */ -export function isValidIdentifier(name) { +export function isValidIdentifier(name: string): boolean { if (typeof name !== "string" || esutils.keyword.isReservedWordES6(name, true)) { return false; } else { @@ -173,7 +174,7 @@ export function isValidIdentifier(name) { * Check if the input `node` is a `let` variable declaration. */ -export function isLet(node) { +export function isLet(node: Object): boolean { return t.isVariableDeclaration(node) && (node.kind !== "var" || node[BLOCK_SCOPED_SYMBOL]); } @@ -181,7 +182,7 @@ export function isLet(node) { * Check if the input `node` is block scoped. */ -export function isBlockScoped(node) { +export function isBlockScoped(node: Object): boolean { return t.isFunctionDeclaration(node) || t.isClassDeclaration(node) || t.isLet(node); } @@ -189,7 +190,7 @@ export function isBlockScoped(node) { * Check if the input `node` is a variable declaration. */ -export function isVar(node) { +export function isVar(node: Object): boolean { return t.isVariableDeclaration(node, { kind: "var" }) && !node[BLOCK_SCOPED_SYMBOL]; } @@ -206,7 +207,7 @@ export function isSpecifierDefault(specifier: Object): boolean { * Check if the input `node` is a scope. */ -export function isScope(node, parent) { +export function isScope(node: Object, parent: Object): boolean { if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) { return false; } @@ -218,7 +219,7 @@ export function isScope(node, parent) { * Check if the input `node` is definitely immutable. */ -export function isImmutable(node) { +export function isImmutable(node: Object): boolean { if (t.isType(node.type, "Immutable")) return true; if (t.isIdentifier(node)) { diff --git a/packages/babylon/src/options.js b/packages/babylon/src/options.js index 3439e0ccd9..1456be6360 100755 --- a/packages/babylon/src/options.js +++ b/packages/babylon/src/options.js @@ -1,8 +1,15 @@ +/* @flow */ // A second optional argument can be given to further configure // the parser process. These options are recognized: - -export const defaultOptions = { +export const defaultOptions: { + sourceType: string, + allowReturnOutsideFunction: boolean, + allowImportExportEverywhere: boolean, + allowSuperOutsideMethod: boolean, + plugins: Array, + strictMode: any +} = { // Source type ("script" or "module") for different semantics sourceType: "script", // When enabled, a return at the top level is not considered an @@ -21,7 +28,7 @@ export const defaultOptions = { // Interpret and default an options object -export function getOptions(opts) { +export function getOptions(opts?: Object): Object { let options = {}; for (let key in defaultOptions) { options[key] = opts && key in opts ? opts[key] : defaultOptions[key]; diff --git a/packages/babylon/src/parser/comments.js b/packages/babylon/src/parser/comments.js index f1a266b58a..9fabbed737 100644 --- a/packages/babylon/src/parser/comments.js +++ b/packages/babylon/src/parser/comments.js @@ -1,3 +1,4 @@ +/* @flow */ /* eslint max-len: 0 */ /** @@ -118,7 +119,7 @@ pp.processComment = function (node) { // result in an empty array, and if so, the array must be // deleted. node.leadingComments = this.state.leadingComments.slice(0, i); - if (node.leadingComments.length === 0) { + if ((node.leadingComments: Array).length === 0) { node.leadingComments = null; } diff --git a/packages/babylon/src/parser/index.js b/packages/babylon/src/parser/index.js index 7be5ec3bae..bc034e0549 100644 --- a/packages/babylon/src/parser/index.js +++ b/packages/babylon/src/parser/index.js @@ -1,3 +1,4 @@ +/* @flow */ import { reservedWords } from "../util/identifier"; import { getOptions } from "../options"; @@ -6,7 +7,7 @@ import Tokenizer from "../tokenizer"; export const plugins = {}; export default class Parser extends Tokenizer { - constructor(options, input) { + constructor(options: Object, input: string) { options = getOptions(options); super(options, input); @@ -22,15 +23,15 @@ export default class Parser extends Tokenizer { } } - hasPlugin(name) { + hasPlugin(name: string): boolean { return !!(this.plugins["*"] || this.plugins[name]); } - extend(name, f) { + extend(name: string, f: Function) { this[name] = f(this[name]); } - loadPlugins(plugins) { + loadPlugins(plugins: Array): Object { let pluginMap = {}; if (plugins.indexOf("flow") >= 0) { @@ -51,7 +52,13 @@ export default class Parser extends Tokenizer { return pluginMap; } - parse() { + parse(): { + type: "File", + program: { + type: "Program", + body: Array + } + } { let file = this.startNode(); let program = this.startNode(); this.nextToken(); diff --git a/packages/babylon/src/parser/util.js b/packages/babylon/src/parser/util.js index 240f6c672e..03ca0b2e57 100644 --- a/packages/babylon/src/parser/util.js +++ b/packages/babylon/src/parser/util.js @@ -1,3 +1,4 @@ +/* @flow */ import { types as tt } from "../tokenizer/types"; import Parser from "./index"; diff --git a/packages/babylon/src/tokenizer/context.js b/packages/babylon/src/tokenizer/context.js index 3e158b915e..bd35e67860 100644 --- a/packages/babylon/src/tokenizer/context.js +++ b/packages/babylon/src/tokenizer/context.js @@ -1,3 +1,4 @@ +/* @flow */ // The algorithm used to determine whether a regexp can appear at a // given point in the program is loosely based on sweet.js' approach. @@ -7,16 +8,27 @@ import { types as tt } from "./types"; import { lineBreak } from "../util/whitespace"; export class TokContext { - constructor(token, isExpr, preserveSpace, override) { + constructor( + token: string, + isExpr?: boolean, + preserveSpace?: boolean, + override?: Function, + ) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; } + token: string; + isExpr: boolean; + preserveSpace: boolean; + override: ?Function; } -export const types = { +export const types: { + [key: string]: TokContext; +} = { b_stat: new TokContext("{", false), b_expr: new TokContext("{", true), b_tmpl: new TokContext("${", true), diff --git a/packages/babylon/src/tokenizer/index.js b/packages/babylon/src/tokenizer/index.js index f16d6de1f9..a029fee07b 100644 --- a/packages/babylon/src/tokenizer/index.js +++ b/packages/babylon/src/tokenizer/index.js @@ -1,6 +1,7 @@ /* eslint max-len: 0 */ /* eslint indent: 0 */ +import type { TokenType } from "./types"; import { isIdentifierStart, isIdentifierChar, isKeyword } from "../util/identifier"; import { types as tt, keywords as keywordTypes } from "./types"; import { types as ct } from "./context"; @@ -21,6 +22,11 @@ export class Token { this.loc = new SourceLocation(state.startLoc, state.endLoc); } + type: TokenType; + value: any; + start: number; + end: number; + loc: SourceLocation; } // ## Tokenizer diff --git a/packages/babylon/src/util/whitespace.js b/packages/babylon/src/util/whitespace.js index 4463c8e549..50b90c8ca7 100644 --- a/packages/babylon/src/util/whitespace.js +++ b/packages/babylon/src/util/whitespace.js @@ -1,3 +1,4 @@ +/* @flow */ // Matches a whole line break (where CRLF is considered a single // line break). Used to count lines. @@ -5,7 +6,7 @@ export const lineBreak = /\r\n?|\n|\u2028|\u2029/; export const lineBreakG = new RegExp(lineBreak.source, "g"); -export function isNewLine(code) { +export function isNewLine(code: number): boolean { return code === 10 || code === 13 || code === 0x2028 || code === 0x2029; }