Revert "Remove Flow annotations and pragmas"

This reverts commit 4252244d06b225ab26a02d52c04f9940a3e4d6a2.
This commit is contained in:
Amjad Masad 2016-03-03 15:03:55 -08:00
parent 3667527d04
commit 12ee11a0a4
49 changed files with 444 additions and 287 deletions

View File

@ -1,3 +1,4 @@
/* @flow */
/* eslint indent: 0 */ /* eslint indent: 0 */
/* eslint max-len: 0 */ /* eslint max-len: 0 */
@ -61,7 +62,7 @@ function getTokenType(match) {
* Highlight `text`. * Highlight `text`.
*/ */
function highlight(text) { function highlight(text: string) {
return text.replace(jsTokens, function (...args) { return text.replace(jsTokens, function (...args) {
let type = getTokenType(args); let type = getTokenType(args);
let colorize = defs[type]; 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. * 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); colNumber = Math.max(colNumber, 0);
let highlighted = opts.highlightCode && chalk.supportsColor; let highlighted = opts.highlightCode && chalk.supportsColor;

View File

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

View File

@ -1,3 +1,4 @@
/* @flow */
import * as t from "babel-types"; import * as t from "babel-types";
@ -7,7 +8,11 @@ import * as t from "babel-types";
* - Wrap `Program` node with a `File` node. * - 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) {
if (ast.type === "Program") { if (ast.type === "Program") {
return t.file(ast, comments || [], tokens || []); return t.file(ast, comments || [], tokens || []);

View File

@ -4,10 +4,10 @@ import getHelper from "babel-helpers";
import * as metadataVisitor from "./metadata"; import * as metadataVisitor from "./metadata";
import convertSourceMap from "convert-source-map"; import convertSourceMap from "convert-source-map";
import OptionManager from "./options/option-manager"; import OptionManager from "./options/option-manager";
import type Pipeline from "../pipeline";
import PluginPass from "../plugin-pass"; import PluginPass from "../plugin-pass";
import shebangRegex from "shebang-regex"; import shebangRegex from "shebang-regex";
import { NodePath, Hub } from "babel-traverse"; import { NodePath, Hub, Scope } from "babel-traverse";
import sourceMap from "source-map"; import sourceMap from "source-map";
import generate from "babel-generator"; import generate from "babel-generator";
import codeFrame from "babel-code-frame"; import codeFrame from "babel-code-frame";
@ -39,7 +39,7 @@ let errorVisitor = {
}; };
export default class File extends Store { export default class File extends Store {
constructor(opts = {}, pipeline) { constructor(opts: Object = {}, pipeline: Pipeline) {
super(); super();
this.pipeline = pipeline; this.pipeline = pipeline;
@ -100,9 +100,30 @@ export default class File extends Store {
this.hub = new Hub(this); 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() { getMetadata() {
let has = false; 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)) { if (t.isModuleDeclaration(node)) {
has = true; has = true;
break; break;
@ -157,7 +178,7 @@ export default class File extends Store {
return; return;
} }
let plugins = opts.plugins.concat(INTERNAL_PLUGINS); let plugins: Array<[PluginPass, Object]> = opts.plugins.concat(INTERNAL_PLUGINS);
let currentPluginVisitors = []; let currentPluginVisitors = [];
let currentPluginPasses = []; let currentPluginPasses = [];
@ -177,7 +198,7 @@ export default class File extends Store {
this.pluginPasses.push(currentPluginPasses); this.pluginPasses.push(currentPluginPasses);
} }
getModuleName() { getModuleName(): ?string {
let opts = this.opts; let opts = this.opts;
if (!opts.moduleIds) { if (!opts.moduleIds) {
return null; return null;
@ -221,13 +242,13 @@ export default class File extends Store {
} }
} }
resolveModuleSource(source) { resolveModuleSource(source: string): string {
let resolveModuleSource = this.opts.resolveModuleSource; let resolveModuleSource = this.opts.resolveModuleSource;
if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename); if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
return source; return source;
} }
addImport(source, imported, name = imported) { addImport(source: string, imported: string, name?: string = imported): Object {
let alias = `${source}:${imported}`; let alias = `${source}:${imported}`;
let id = this.dynamicImportIds[alias]; let id = this.dynamicImportIds[alias];
@ -254,7 +275,7 @@ export default class File extends Store {
return id; return id;
} }
addHelper(name) { addHelper(name: string): Object {
let declar = this.declarations[name]; let declar = this.declarations[name];
if (declar) return declar; if (declar) return declar;
@ -293,7 +314,11 @@ export default class File extends Store {
return uid; 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 // Generate a unique name based on the string literals so we dedupe
// identical strings used in the program. // identical strings used in the program.
let stringIds = raw.elements.map(function(string) { let stringIds = raw.elements.map(function(string) {
@ -317,7 +342,7 @@ export default class File extends Store {
return uid; 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 loc = node && (node.loc || node._loc);
let err = new Error(msg); let err = new Error(msg);
@ -339,7 +364,7 @@ export default class File extends Store {
return err; return err;
} }
mergeSourceMap(map) { mergeSourceMap(map: Object) {
let inputMap = this.opts.inputSourceMap; let inputMap = this.opts.inputSourceMap;
if (inputMap) { if (inputMap) {
@ -383,7 +408,7 @@ export default class File extends Store {
} }
} }
parse(code) { parse(code: string) {
this.log.debug("Parse start"); this.log.debug("Parse start");
let ast = parse(code, this.parserOpts); let ast = parse(code, this.parserOpts);
this.log.debug("Parse stop"); this.log.debug("Parse stop");
@ -409,7 +434,7 @@ export default class File extends Store {
this.log.debug("End set AST"); this.log.debug("End set AST");
} }
transform() { transform(): BabelFileResult {
// In the "pass per preset" mode, we have grouped passes. // In the "pass per preset" mode, we have grouped passes.
// Otherwise, there is only one plain pluginPasses array. // Otherwise, there is only one plain pluginPasses array.
this.pluginPasses.forEach((pluginPasses, index) => { this.pluginPasses.forEach((pluginPasses, index) => {
@ -423,7 +448,7 @@ export default class File extends Store {
return this.generate(); return this.generate();
} }
wrap(code, callback) { wrap(code: string, callback: Function): BabelFileResult {
code = code + ""; code = code + "";
try { try {
@ -462,7 +487,7 @@ export default class File extends Store {
} }
} }
addCode(code) { addCode(code: string) {
code = (code || "") + ""; code = (code || "") + "";
code = this.parseInputSourceMap(code); code = this.parseInputSourceMap(code);
this.code = code; this.code = code;
@ -479,7 +504,7 @@ export default class File extends Store {
return util.shouldIgnore(opts.filename, opts.ignore, opts.only); return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
} }
call(key, pluginPasses) { call(key: "pre" | "post", pluginPasses: Array<PluginPass>) {
for (let pass of pluginPasses) { for (let pass of pluginPasses) {
let plugin = pass.plugin; let plugin = pass.plugin;
let fn = plugin[key]; let fn = plugin[key];
@ -487,7 +512,7 @@ export default class File extends Store {
} }
} }
parseInputSourceMap(code) { parseInputSourceMap(code: string): string {
let opts = this.opts; let opts = this.opts;
if (opts.inputSourceMap !== false) { 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 = { let result = {
metadata: null, metadata: null,
options: this.opts, options: this.opts,
@ -534,11 +559,11 @@ export default class File extends Store {
return result; return result;
} }
generate() { generate(): BabelFileResult {
let opts = this.opts; let opts = this.opts;
let ast = this.ast; let ast = this.ast;
let result = { ast }; let result: BabelFileResult = { ast };
if (!opts.code) return this.makeResult(result); if (!opts.code) return this.makeResult(result);
this.log.debug("Generation start"); this.log.debug("Generation start");

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,6 @@
/* @flow */
export function ClassDeclaration(node) { export function ClassDeclaration(node: Object) {
this.printJoin(node.decorators, node, { separator: "" }); this.printJoin(node.decorators, node, { separator: "" });
this.push("class"); this.push("class");
@ -27,7 +28,7 @@ export function ClassDeclaration(node) {
export { ClassDeclaration as ClassExpression }; export { ClassDeclaration as ClassExpression };
export function ClassBody(node) { export function ClassBody(node: Object) {
this.push("{"); this.push("{");
this.printInnerComments(node); this.printInnerComments(node);
if (node.body.length === 0) { 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: "" }); this.printJoin(node.decorators, node, { separator: "" });
if (node.static) this.push("static "); if (node.static) this.push("static ");
@ -58,7 +59,7 @@ export function ClassProperty(node) {
this.semicolon(); this.semicolon();
} }
export function ClassMethod(node) { export function ClassMethod(node: Object) {
this.printJoin(node.decorators, node, { separator: "" }); this.printJoin(node.decorators, node, { separator: "" });
if (node.static) { if (node.static) {

View File

@ -1,3 +1,4 @@
/* @flow */
/* eslint max-len: 0 */ /* eslint max-len: 0 */
import isInteger from "is-integer"; import isInteger from "is-integer";
@ -9,7 +10,7 @@ const SCIENTIFIC_NOTATION = /e/i;
const ZERO_DECIMAL_INTEGER = /\.0+$/; const ZERO_DECIMAL_INTEGER = /\.0+$/;
const NON_DECIMAL_LITERAL = /^0[box]/; const NON_DECIMAL_LITERAL = /^0[box]/;
export function UnaryExpression(node) { export function UnaryExpression(node: Object) {
let needsSpace = /[a-z]$/.test(node.operator); let needsSpace = /[a-z]$/.test(node.operator);
let arg = node.argument; let arg = node.argument;
@ -26,19 +27,19 @@ export function UnaryExpression(node) {
this.print(node.argument, node); this.print(node.argument, node);
} }
export function DoExpression(node) { export function DoExpression(node: Object) {
this.push("do"); this.push("do");
this.space(); this.space();
this.print(node.body, node); this.print(node.body, node);
} }
export function ParenthesizedExpression(node) { export function ParenthesizedExpression(node: Object) {
this.push("("); this.push("(");
this.print(node.expression, node); this.print(node.expression, node);
this.push(")"); this.push(")");
} }
export function UpdateExpression(node) { export function UpdateExpression(node: Object) {
if (node.prefix) { if (node.prefix) {
this.push(node.operator); this.push(node.operator);
this.print(node.argument, node); 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.print(node.test, node);
this.space(); this.space();
this.push("?"); this.push("?");
@ -60,7 +61,7 @@ export function ConditionalExpression(node) {
this.print(node.alternate, node); this.print(node.alternate, node);
} }
export function NewExpression(node, parent) { export function NewExpression(node: Object, parent: Object) {
this.push("new "); this.push("new ");
this.print(node.callee, node); this.print(node.callee, node);
if (node.arguments.length === 0 && this.format.minified && if (node.arguments.length === 0 && this.format.minified &&
@ -73,7 +74,7 @@ export function NewExpression(node, parent) {
this.push(")"); this.push(")");
} }
export function SequenceExpression(node) { export function SequenceExpression(node: Object) {
this.printList(node.expressions, node); this.printList(node.expressions, node);
} }
@ -85,13 +86,13 @@ export function Super() {
this.push("super"); this.push("super");
} }
export function Decorator(node) { export function Decorator(node: Object) {
this.push("@"); this.push("@");
this.print(node.expression, node); this.print(node.expression, node);
this.newline(); this.newline();
} }
export function CallExpression(node) { export function CallExpression(node: Object) {
this.print(node.callee, node); this.print(node.callee, node);
if (node.loc) this.printAuxAfterComment(); if (node.loc) this.printAuxAfterComment();
@ -116,8 +117,8 @@ export function CallExpression(node) {
this.push(")"); this.push(")");
} }
function buildYieldAwait(keyword) { function buildYieldAwait(keyword: string) {
return function (node) { return function (node: Object) {
this.push(keyword); this.push(keyword);
if (node.delegate) { if (node.delegate) {
@ -141,12 +142,12 @@ export function EmptyStatement() {
this.semicolon(); this.semicolon();
} }
export function ExpressionStatement(node) { export function ExpressionStatement(node: Object) {
this.print(node.expression, node); this.print(node.expression, node);
this.semicolon(); this.semicolon();
} }
export function AssignmentPattern(node) { export function AssignmentPattern(node: Object) {
this.print(node.left, node); this.print(node.left, node);
this.space(); this.space();
this.push("="); this.push("=");
@ -154,7 +155,7 @@ export function AssignmentPattern(node) {
this.print(node.right, 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 // Somewhere inside a for statement `init` node but doesn't usually
// needs a paren except for `in` expressions: `for (a in b ? a : b;;)` // needs a paren except for `in` expressions: `for (a in b ? a : b;;)`
let parens = this._inForStatementInitCounter && node.operator === "in" && 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.print(node.object, node);
this.push("::"); this.push("::");
this.print(node.callee, node); this.print(node.callee, node);
@ -206,7 +207,7 @@ export {
AssignmentExpression as LogicalExpression AssignmentExpression as LogicalExpression
}; };
export function MemberExpression(node) { export function MemberExpression(node: Object) {
this.print(node.object, node); this.print(node.object, node);
if (!node.computed && t.isMemberExpression(node.property)) { 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.print(node.meta, node);
this.push("."); this.push(".");
this.print(node.property, node); this.print(node.property, node);

View File

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

View File

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

View File

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

View File

@ -1,7 +1,8 @@
/* @flow */
import * as t from "babel-types"; import * as t from "babel-types";
export function ImportSpecifier(node) { export function ImportSpecifier(node: Object) {
this.print(node.imported, node); this.print(node.imported, node);
if (node.local && node.local.name !== node.imported.name) { if (node.local && node.local.name !== node.imported.name) {
this.push(" as "); 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); this.print(node.local, node);
} }
export function ExportDefaultSpecifier(node) { export function ExportDefaultSpecifier(node: Object) {
this.print(node.exported, node); this.print(node.exported, node);
} }
export function ExportSpecifier(node) { export function ExportSpecifier(node: Object) {
this.print(node.local, node); this.print(node.local, node);
if (node.exported && node.local.name !== node.exported.name) { if (node.exported && node.local.name !== node.exported.name) {
this.push(" as "); this.push(" as ");
@ -25,12 +26,12 @@ export function ExportSpecifier(node) {
} }
} }
export function ExportNamespaceSpecifier(node) { export function ExportNamespaceSpecifier(node: Object) {
this.push("* as "); this.push("* as ");
this.print(node.exported, node); this.print(node.exported, node);
} }
export function ExportAllDeclaration(node) { export function ExportAllDeclaration(node: Object) {
this.push("export *"); this.push("export *");
if (node.exported) { if (node.exported) {
this.push(" as "); this.push(" as ");
@ -51,7 +52,7 @@ export function ExportDefaultDeclaration() {
ExportDeclaration.apply(this, arguments); ExportDeclaration.apply(this, arguments);
} }
function ExportDeclaration(node) { function ExportDeclaration(node: Object) {
if (node.declaration) { if (node.declaration) {
let declar = node.declaration; let declar = node.declaration;
this.print(declar, node); this.print(declar, node);
@ -97,7 +98,7 @@ function ExportDeclaration(node) {
this.ensureSemicolon(); this.ensureSemicolon();
} }
export function ImportDeclaration(node) { export function ImportDeclaration(node: Object) {
this.push("import "); this.push("import ");
if (node.importKind === "type" || node.importKind === "typeof") { if (node.importKind === "type" || node.importKind === "typeof") {
@ -134,7 +135,7 @@ export function ImportDeclaration(node) {
this.semicolon(); this.semicolon();
} }
export function ImportNamespaceSpecifier(node) { export function ImportNamespaceSpecifier(node: Object) {
this.push("* as "); this.push("* as ");
this.print(node.local, node); 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(["!"]); 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.keyword("with");
this.push("("); this.push("(");
this.print(node.object, node); this.print(node.object, node);
@ -11,7 +11,7 @@ export function WithStatement(node) {
this.printBlock(node); this.printBlock(node);
} }
export function IfStatement(node) { export function IfStatement(node: Object) {
this.keyword("if"); this.keyword("if");
this.push("("); this.push("(");
this.print(node.test, node); this.print(node.test, node);
@ -46,7 +46,7 @@ function getLastStatement(statement) {
return getLastStatement(statement.body); return getLastStatement(statement.body);
} }
export function ForStatement(node) { export function ForStatement(node: Object) {
this.keyword("for"); this.keyword("for");
this.push("("); this.push("(");
@ -70,7 +70,7 @@ export function ForStatement(node) {
this.printBlock(node); this.printBlock(node);
} }
export function WhileStatement(node) { export function WhileStatement(node: Object) {
this.keyword("while"); this.keyword("while");
this.push("("); this.push("(");
this.print(node.test, node); this.print(node.test, node);
@ -79,7 +79,7 @@ export function WhileStatement(node) {
} }
let buildForXStatement = function (op) { let buildForXStatement = function (op) {
return function (node) { return function (node: Object) {
this.keyword("for"); this.keyword("for");
this.push("("); this.push("(");
this.print(node.left, node); this.print(node.left, node);
@ -93,7 +93,7 @@ let buildForXStatement = function (op) {
export let ForInStatement = buildForXStatement("in"); export let ForInStatement = buildForXStatement("in");
export let ForOfStatement = buildForXStatement("of"); export let ForOfStatement = buildForXStatement("of");
export function DoWhileStatement(node) { export function DoWhileStatement(node: Object) {
this.push("do "); this.push("do ");
this.print(node.body, node); this.print(node.body, node);
this.space(); this.space();
@ -104,7 +104,7 @@ export function DoWhileStatement(node) {
} }
function buildLabelStatement(prefix, key = "label") { function buildLabelStatement(prefix, key = "label") {
return function (node) { return function (node: Object) {
this.push(prefix); this.push(prefix);
let label = node[key]; let label = node[key];
@ -130,13 +130,13 @@ export let ReturnStatement = buildLabelStatement("return", "argument");
export let BreakStatement = buildLabelStatement("break"); export let BreakStatement = buildLabelStatement("break");
export let ThrowStatement = buildLabelStatement("throw", "argument"); export let ThrowStatement = buildLabelStatement("throw", "argument");
export function LabeledStatement(node) { export function LabeledStatement(node: Object) {
this.print(node.label, node); this.print(node.label, node);
this.push(": "); this.push(": ");
this.print(node.body, node); this.print(node.body, node);
} }
export function TryStatement(node) { export function TryStatement(node: Object) {
this.keyword("try"); this.keyword("try");
this.print(node.block, node); this.print(node.block, node);
this.space(); this.space();
@ -157,7 +157,7 @@ export function TryStatement(node) {
} }
} }
export function CatchClause(node) { export function CatchClause(node: Object) {
this.keyword("catch"); this.keyword("catch");
this.push("("); this.push("(");
this.print(node.param, node); this.print(node.param, node);
@ -166,7 +166,7 @@ export function CatchClause(node) {
this.print(node.body, node); this.print(node.body, node);
} }
export function SwitchStatement(node) { export function SwitchStatement(node: Object) {
this.keyword("switch"); this.keyword("switch");
this.push("("); this.push("(");
this.print(node.discriminant, node); this.print(node.discriminant, node);
@ -184,7 +184,7 @@ export function SwitchStatement(node) {
this.push("}"); this.push("}");
} }
export function SwitchCase(node) { export function SwitchCase(node: Object) {
if (node.test) { if (node.test) {
this.push("case "); this.push("case ");
this.print(node.test, node); this.print(node.test, node);
@ -203,13 +203,13 @@ export function DebuggerStatement() {
this.push("debugger;"); this.push("debugger;");
} }
export function VariableDeclaration(node, parent) { export function VariableDeclaration(node: Object, parent: Object) {
this.push(node.kind + " "); this.push(node.kind + " ");
let hasInits = false; let hasInits = false;
// don't add whitespace to loop heads // don't add whitespace to loop heads
if (!t.isFor(parent)) { if (!t.isFor(parent)) {
for (let declar of node.declarations) { for (let declar of (node.declarations: Array<Object>)) {
if (declar.init) { if (declar.init) {
// has an init so let's split it up over multiple lines // has an init so let's split it up over multiple lines
hasInits = true; hasInits = true;
@ -246,7 +246,7 @@ export function VariableDeclaration(node, parent) {
this.semicolon(); this.semicolon();
} }
export function VariableDeclarator(node) { export function VariableDeclarator(node: Object) {
this.print(node.id, node); this.print(node.id, node);
this.print(node.id.typeAnnotation, node); this.print(node.id.typeAnnotation, node);
if (node.init) { if (node.init) {

View File

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

View File

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

View File

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

View File

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

View File

@ -1,9 +1,12 @@
/* @flow */
/** /**
* Track current position in code generation. * Track current position in code generation.
*/ */
export default class Position { export default class Position {
column: number;
line: number;
constructor() { constructor() {
this.line = 1; 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 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++) { for (let i = 0; i < str.length; i++) {
if (str[i] === "\n") { if (str[i] === "\n") {
this.line++; this.line++;
@ -29,7 +32,7 @@ export default class Position {
* Unshift a string from the current position, mantaining the current line and column. * 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++) { for (let i = 0; i < str.length; i++) {
if (str[i] === "\n") { if (str[i] === "\n") {
this.line--; this.line--;

View File

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

View File

@ -1,7 +1,13 @@
import explode from "babel-helper-explode-assignable-expression"; import explode from "babel-helper-explode-assignable-expression";
import * as t from "babel-types"; 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) { let buildAssignment = function (left, right) {
return t.assignmentExpression("=", left, right); return t.assignmentExpression("=", left, right);
}; };

View File

@ -1,13 +1,13 @@
/* @flow */
import pull from "lodash/array/pull"; import pull from "lodash/array/pull";
import * as t from "babel-types"; 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; 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(""); let flags = node.flags.split("");
if (node.flags.indexOf(flag) < 0) return; if (node.flags.indexOf(flag) < 0) return;
pull(flags, flag); pull(flags, flag);

View File

@ -1,4 +1,6 @@
/* @noflow */
import type { NodePath } from "babel-traverse";
import nameFunction from "babel-helper-function-name"; import nameFunction from "babel-helper-function-name";
import template from "babel-template"; import template from "babel-template";
import * as t from "babel-types"; 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 node = path.node;
let body = node.body; 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 node = path.node;
let wrapper = buildWrapper; 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; let node = path.node;
if (node.generator) return; if (node.generator) return;

View File

@ -1,3 +1,4 @@
/* @flow */
/* eslint max-len: 0 */ /* eslint max-len: 0 */
import * as util from "util"; import * as util from "util";
@ -47,7 +48,7 @@ export const MESSAGES = {
* Get a message with $0 placeholders replaced by arguments. * 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]; let msg = MESSAGES[key];
if (!msg) throw new ReferenceError(`Unknown message ${JSON.stringify(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. * Stingify arguments to be used inside messages.
*/ */
export function parseArgs(args) { export function parseArgs(args: Array<any>): Array<string> {
return args.map(function (val) { return args.map(function (val) {
if (val != null && val.inspect) { if (val != null && val.inspect) {
return val.inspect(); return val.inspect();

View File

@ -1,3 +1,4 @@
/* @flow */
import deepClone from "lodash/lang/cloneDeep"; import deepClone from "lodash/lang/cloneDeep";
import sourceMapSupport from "source-map-support"; import sourceMapSupport from "source-map-support";
@ -128,7 +129,7 @@ function hookExtensions(_exts) {
hookExtensions(util.canCompile.EXTENSIONS); 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.only != null) only = util.arrayify(opts.only, util.regexify);
if (opts.ignore != null) ignore = util.arrayify(opts.ignore, util.regexify); if (opts.ignore != null) ignore = util.arrayify(opts.ignore, util.regexify);

View File

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

View File

@ -1,3 +1,4 @@
/* @flow */
/* eslint max-len: 0 */ /* eslint max-len: 0 */
import defineType, { import defineType, {

View File

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

View File

@ -1,3 +1,4 @@
/* @flow */
import defineType from "./index"; import defineType from "./index";

View File

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

View File

@ -1,3 +1,4 @@
/* @flow */
import defineType, { assertNodeType, assertValueType, chain, assertEach } from "./index"; import defineType, { assertNodeType, assertValueType, chain, assertEach } from "./index";

View File

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

View File

@ -1,3 +1,4 @@
/* @flow */
import * as t from "./index"; import * as t from "./index";
@ -6,7 +7,7 @@ import * as t from "./index";
* returns a `UnionTypeAnnotation` node containg them. * returns a `UnionTypeAnnotation` node containg them.
*/ */
export function createUnionTypeAnnotation(types) { export function createUnionTypeAnnotation(types: Array<Object>) {
let flattened = removeTypeDuplicates(types); let flattened = removeTypeDuplicates(types);
if (flattened.length === 1) { if (flattened.length === 1) {
@ -20,7 +21,7 @@ export function createUnionTypeAnnotation(types) {
* Dedupe type annotations. * Dedupe type annotations.
*/ */
export function removeTypeDuplicates(nodes) { export function removeTypeDuplicates(nodes: Array<Object>): Array<Object> {
let generics = {}; let generics = {};
let bases = {}; let bases = {};
@ -100,7 +101,7 @@ export function removeTypeDuplicates(nodes) {
* Create a type anotation based on typeof expression. * Create a type anotation based on typeof expression.
*/ */
export function createTypeAnnotationBasedOnTypeof(type) { export function createTypeAnnotationBasedOnTypeof(type: string) {
if (type === "string") { if (type === "string") {
return t.stringTypeAnnotation(); return t.stringTypeAnnotation();
} else if (type === "number") { } else if (type === "number") {

View File

@ -1,3 +1,4 @@
/* @flow */
import toFastProperties from "to-fast-properties"; import toFastProperties from "to-fast-properties";
import compact from "lodash/array/compact"; 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`. * 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) { let is = t[`is${type}`] = function (node, opts) {
return t.is(type, 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`. * 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; if (!node) return false;
let matches = isType(node.type, type); 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`. * 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; if (nodeType === targetType) return true;
let aliases: ?Array<string> = t.FLIPPED_ALIAS_KEYS[targetType]; let aliases: ?Array<string> = t.FLIPPED_ALIAS_KEYS[targetType];
@ -127,7 +128,7 @@ each(t.BUILDER_KEYS, function (keys, type) {
let i = 0; let i = 0;
for (let key of keys) { for (let key of (keys: Array<string>)) {
let field = t.NODE_FIELDS[type][key]; let field = t.NODE_FIELDS[type][key];
let arg = arguments[i++]; let arg = arguments[i++];
@ -170,7 +171,7 @@ for (let type in t.DEPRECATED_KEYS) {
* Description * Description
*/ */
export function validate(node, key, val) { export function validate(node?: Object, key: string, val: any) {
if (!node) return; if (!node) return;
let fields = t.NODE_FIELDS[node.type]; let fields = t.NODE_FIELDS[node.type];
@ -187,10 +188,10 @@ export function validate(node, key, val) {
* Test if an object is shallowly equal. * 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); let keys = Object.keys(expected);
for (let key of keys) { for (let key of (keys: Array<string>)) {
if (actual[key] !== expected[key]) { if (actual[key] !== expected[key]) {
return false; return false;
} }
@ -203,7 +204,7 @@ export function shallowEqual(actual, expected) {
* Append a node to a member expression. * 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.object = t.memberExpression(member.object, member.property, member.computed);
member.property = append; member.property = append;
member.computed = !!computed; member.computed = !!computed;
@ -214,7 +215,7 @@ export function appendToMemberExpression(member, append, computed) {
* Prepend a node to a member expression. * 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); member.object = t.memberExpression(prepend, member.object);
return member; return member;
} }
@ -224,7 +225,7 @@ export function prependToMemberExpression(member, prepend) {
* Casting it to a block if it is not. * 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); 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. * Create a shallow clone of a `node` excluding `_private` properties.
*/ */
export function clone(node) { export function clone(node: Object): Object {
let newNode = {}; let newNode = {};
for (let key in node) { for (let key in node) {
if (key[0] === "_") continue; if (key[0] === "_") continue;
@ -245,7 +246,7 @@ export function clone(node) {
* Create a shallow clone of a `node` excluding `_private` and location properties. * 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); let newNode = clone(node);
delete newNode.loc; delete newNode.loc;
return newNode; return newNode;
@ -256,7 +257,7 @@ export function cloneWithoutLoc(node) {
* exluding `_private` properties. * exluding `_private` properties.
*/ */
export function cloneDeep(node) { export function cloneDeep(node: Object): Object {
let newNode = {}; let newNode = {};
for (let key in node) { for (let key in node) {
@ -286,7 +287,7 @@ export function cloneDeep(node) {
* parsed nodes of `React.createClass` and `React["createClass"]`. * 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("."); let parts = match.split(".");
return function (member) { return function (member) {
@ -337,7 +338,7 @@ export function buildMatchMemberExpression(match, allowPartial) {
* Remove comment properties from a node. * Remove comment properties from a node.
*/ */
export function removeComments(node) { export function removeComments(node: Object): Object {
for (let key of t.COMMENT_KEYS) { for (let key of t.COMMENT_KEYS) {
delete node[key]; delete node[key];
} }
@ -348,22 +349,22 @@ export function removeComments(node) {
* Inherit all unique comments from `parent` node to `child` 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); inheritTrailingComments(child, parent);
inheritLeadingComments(child, parent); inheritLeadingComments(child, parent);
inheritInnerComments(child, parent); inheritInnerComments(child, parent);
return child; return child;
} }
export function inheritTrailingComments(child, parent) { export function inheritTrailingComments(child: Object, parent: Object) {
_inheritComments("trailingComments", child, parent); _inheritComments("trailingComments", child, parent);
} }
export function inheritLeadingComments(child, parent) { export function inheritLeadingComments(child: Object, parent: Object) {
_inheritComments("leadingComments", child, parent); _inheritComments("leadingComments", child, parent);
} }
export function inheritInnerComments(child, parent) { export function inheritInnerComments(child: Object, parent: Object) {
_inheritComments("innerComments", child, parent); _inheritComments("innerComments", child, parent);
} }
@ -377,11 +378,11 @@ function _inheritComments(key, child, parent) {
* Inherit all contextual properties from `parent` node to `child` node. * 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; if (!child || !parent) return child;
// optionally inherit specific properties if not null // optionally inherit specific properties if not null
for (let key of t.INHERIT_KEYS.optional) { for (let key of (t.INHERIT_KEYS.optional: Array<string>)) {
if (child[key] == null) { if (child[key] == null) {
child[key] = parent[key]; child[key] = parent[key];
} }
@ -393,7 +394,7 @@ export function inherits(child, parent) {
} }
// force inherit select properties // force inherit select properties
for (let key of t.INHERIT_KEYS.force) { for (let key of (t.INHERIT_KEYS.force: Array<string>)) {
child[key] = parent[key]; child[key] = parent[key];
} }
@ -406,7 +407,7 @@ export function inherits(child, parent) {
* TODO * TODO
*/ */
export function assertNode(node) { export function assertNode(node?) {
if (!isNode(node)) { if (!isNode(node)) {
// $FlowFixMe // $FlowFixMe
throw new TypeError("Not a valid node " + (node && node.type)); throw new TypeError("Not a valid node " + (node && node.type));
@ -417,7 +418,7 @@ export function assertNode(node) {
* TODO * TODO
*/ */
export function isNode(node) { export function isNode(node?): boolean {
return !!(node && VISITOR_KEYS[node.type]); return !!(node && VISITOR_KEYS[node.type]);
} }

View File

@ -1,14 +1,17 @@
/* @flow */
import * as t from "./index"; import * as t from "./index";
export let isReactComponent = t.buildMatchMemberExpression("React.Component"); export let isReactComponent = t.buildMatchMemberExpression("React.Component");
export function isCompatTag(tagName) { export function isCompatTag(tagName?: string): boolean {
return !!tagName && /^[a-z]|\-/.test(tagName); return !!tagName && /^[a-z]|\-/.test(tagName);
} }
function cleanJSXElementLiteralChild(child, args) { function cleanJSXElementLiteralChild(
child: { value: string },
args: Array<Object>,
) {
let lines = child.value.split(/\r\n|\n|\r/); let lines = child.value.split(/\r\n|\n|\r/);
let lastNonEmptyLine = 0; let lastNonEmptyLine = 0;
@ -53,7 +56,7 @@ function cleanJSXElementLiteralChild(child, args) {
if (str) args.push(t.stringLiteral(str)); if (str) args.push(t.stringLiteral(str));
} }
export function buildChildren(node) { export function buildChildren(node: Object): Array<Object> {
let elems = []; let elems = [];
for (let i = 0; i < node.children.length; i++) { for (let i = 0; i < node.children.length; i++) {

View File

@ -1,3 +1,4 @@
/* @flow */
import * as t from "./index"; 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`. * 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 search = [].concat(node);
let ids = Object.create(null); let ids = Object.create(null);
@ -102,6 +107,9 @@ getBindingIdentifiers.keys = {
VariableDeclarator: ["id"] VariableDeclarator: ["id"]
}; };
export function getOuterBindingIdentifiers(node, duplicates) { export function getOuterBindingIdentifiers(
node: Object,
duplicates?: boolean,
): Object {
return getBindingIdentifiers(node, duplicates, true); return getBindingIdentifiers(node, duplicates, true);
} }

View File

@ -1,3 +1,4 @@
/* @flow */
/* eslint indent: 0 */ /* eslint indent: 0 */
import { getBindingIdentifiers } from "./retrievers"; import { getBindingIdentifiers } from "./retrievers";
@ -9,7 +10,7 @@ import { BLOCK_SCOPED_SYMBOL } from "./constants";
* Check if the input `node` is a binding identifier. * 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]; let keys = getBindingIdentifiers.keys[parent.type];
if (keys) { if (keys) {
for (let i = 0; i < keys.length; i++) { 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. * 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) { switch (parent.type) {
// yes: object::NODE // yes: object::NODE
// yes: NODE::callee // yes: NODE::callee
@ -73,7 +74,7 @@ export function isReferenced(node, parent) {
case "ArrowFunctionExpression": case "ArrowFunctionExpression":
case "FunctionDeclaration": case "FunctionDeclaration":
case "FunctionExpression": case "FunctionExpression":
for (let param of parent.params) { for (let param of (parent.params: Array<any>)) {
if (param === node) return false; if (param === node) return false;
} }
@ -161,7 +162,7 @@ export function isReferenced(node, parent) {
* and isn't a reserved word. * 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)) { if (typeof name !== "string" || esutils.keyword.isReservedWordES6(name, true)) {
return false; return false;
} else { } else {
@ -173,7 +174,7 @@ export function isValidIdentifier(name) {
* Check if the input `node` is a `let` variable declaration. * 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]); 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. * 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); 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. * 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]; 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. * 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 })) { if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) {
return false; return false;
} }
@ -218,7 +219,7 @@ export function isScope(node, parent) {
* Check if the input `node` is definitely immutable. * 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.isType(node.type, "Immutable")) return true;
if (t.isIdentifier(node)) { if (t.isIdentifier(node)) {

View File

@ -1,8 +1,15 @@
/* @flow */
// A second optional argument can be given to further configure // A second optional argument can be given to further configure
// the parser process. These options are recognized: // the parser process. These options are recognized:
export const defaultOptions: {
export const defaultOptions = { sourceType: string,
allowReturnOutsideFunction: boolean,
allowImportExportEverywhere: boolean,
allowSuperOutsideMethod: boolean,
plugins: Array<string>,
strictMode: any
} = {
// Source type ("script" or "module") for different semantics // Source type ("script" or "module") for different semantics
sourceType: "script", sourceType: "script",
// When enabled, a return at the top level is not considered an // 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 // Interpret and default an options object
export function getOptions(opts) { export function getOptions(opts?: Object): Object {
let options = {}; let options = {};
for (let key in defaultOptions) { for (let key in defaultOptions) {
options[key] = opts && key in opts ? opts[key] : defaultOptions[key]; options[key] = opts && key in opts ? opts[key] : defaultOptions[key];

View File

@ -1,3 +1,4 @@
/* @flow */
/* eslint max-len: 0 */ /* eslint max-len: 0 */
/** /**
@ -118,7 +119,7 @@ pp.processComment = function (node) {
// result in an empty array, and if so, the array must be // result in an empty array, and if so, the array must be
// deleted. // deleted.
node.leadingComments = this.state.leadingComments.slice(0, i); node.leadingComments = this.state.leadingComments.slice(0, i);
if (node.leadingComments.length === 0) { if ((node.leadingComments: Array<any>).length === 0) {
node.leadingComments = null; node.leadingComments = null;
} }

View File

@ -1,3 +1,4 @@
/* @flow */
import { reservedWords } from "../util/identifier"; import { reservedWords } from "../util/identifier";
import { getOptions } from "../options"; import { getOptions } from "../options";
@ -6,7 +7,7 @@ import Tokenizer from "../tokenizer";
export const plugins = {}; export const plugins = {};
export default class Parser extends Tokenizer { export default class Parser extends Tokenizer {
constructor(options, input) { constructor(options: Object, input: string) {
options = getOptions(options); options = getOptions(options);
super(options, input); 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]); return !!(this.plugins["*"] || this.plugins[name]);
} }
extend(name, f) { extend(name: string, f: Function) {
this[name] = f(this[name]); this[name] = f(this[name]);
} }
loadPlugins(plugins) { loadPlugins(plugins: Array<string>): Object {
let pluginMap = {}; let pluginMap = {};
if (plugins.indexOf("flow") >= 0) { if (plugins.indexOf("flow") >= 0) {
@ -51,7 +52,13 @@ export default class Parser extends Tokenizer {
return pluginMap; return pluginMap;
} }
parse() { parse(): {
type: "File",
program: {
type: "Program",
body: Array<Object>
}
} {
let file = this.startNode(); let file = this.startNode();
let program = this.startNode(); let program = this.startNode();
this.nextToken(); this.nextToken();

View File

@ -1,3 +1,4 @@
/* @flow */
import { types as tt } from "../tokenizer/types"; import { types as tt } from "../tokenizer/types";
import Parser from "./index"; import Parser from "./index";

View File

@ -1,3 +1,4 @@
/* @flow */
// The algorithm used to determine whether a regexp can appear at a // The algorithm used to determine whether a regexp can appear at a
// given point in the program is loosely based on sweet.js' approach. // 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"; import { lineBreak } from "../util/whitespace";
export class TokContext { export class TokContext {
constructor(token, isExpr, preserveSpace, override) { constructor(
token: string,
isExpr?: boolean,
preserveSpace?: boolean,
override?: Function,
) {
this.token = token; this.token = token;
this.isExpr = !!isExpr; this.isExpr = !!isExpr;
this.preserveSpace = !!preserveSpace; this.preserveSpace = !!preserveSpace;
this.override = override; 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_stat: new TokContext("{", false),
b_expr: new TokContext("{", true), b_expr: new TokContext("{", true),
b_tmpl: new TokContext("${", true), b_tmpl: new TokContext("${", true),

View File

@ -1,6 +1,7 @@
/* eslint max-len: 0 */ /* eslint max-len: 0 */
/* eslint indent: 0 */ /* eslint indent: 0 */
import type { TokenType } from "./types";
import { isIdentifierStart, isIdentifierChar, isKeyword } from "../util/identifier"; import { isIdentifierStart, isIdentifierChar, isKeyword } from "../util/identifier";
import { types as tt, keywords as keywordTypes } from "./types"; import { types as tt, keywords as keywordTypes } from "./types";
import { types as ct } from "./context"; import { types as ct } from "./context";
@ -21,6 +22,11 @@ export class Token {
this.loc = new SourceLocation(state.startLoc, state.endLoc); this.loc = new SourceLocation(state.startLoc, state.endLoc);
} }
type: TokenType;
value: any;
start: number;
end: number;
loc: SourceLocation;
} }
// ## Tokenizer // ## Tokenizer

View File

@ -1,3 +1,4 @@
/* @flow */
// Matches a whole line break (where CRLF is considered a single // Matches a whole line break (where CRLF is considered a single
// line break). Used to count lines. // line break). Used to count lines.
@ -5,7 +6,7 @@
export const lineBreak = /\r\n?|\n|\u2028|\u2029/; export const lineBreak = /\r\n?|\n|\u2028|\u2029/;
export const lineBreakG = new RegExp(lineBreak.source, "g"); 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; return code === 10 || code === 13 || code === 0x2028 || code === 0x2029;
} }