Files
test-repo/src/printer.js
T

2733 lines
75 KiB
JavaScript
Raw Normal View History

2017-01-10 12:18:22 -05:00
"use strict";
2017-01-28 07:50:22 -08:00
var assert = require("assert");
2017-01-19 14:46:37 -05:00
var comments = require("./comments");
var FastPath = require("./fast-path");
var util = require("./util");
2017-01-10 21:48:49 -08:00
var isIdentifierName = require("esutils").keyword.isIdentifierNameES6;
var docBuilders = require("./doc-builders");
var concat = docBuilders.concat;
var join = docBuilders.join;
var line = docBuilders.line;
var hardline = docBuilders.hardline;
var softline = docBuilders.softline;
var literalline = docBuilders.literalline;
var group = docBuilders.group;
var indent = docBuilders.indent;
var conditionalGroup = docBuilders.conditionalGroup;
var ifBreak = docBuilders.ifBreak;
var breakParent = docBuilders.breakParent;
var docUtils = require("./doc-utils");
var willBreak = docUtils.willBreak;
var isLineNext = docUtils.isLineNext;
var getFirstString = docUtils.getFirstString;
var isEmpty = docUtils.isEmpty;
var types = require("ast-types");
var namedTypes = types.namedTypes;
var isString = types.builtInTypes.string;
var isObject = types.builtInTypes.object;
function maybeAddParens(path, lines) {
2017-01-28 07:50:22 -08:00
return path.needsParens() ? concat(["(", lines, ")"]) : lines;
}
function genericPrint(path, options, printPath) {
assert.ok(path instanceof FastPath);
2016-12-30 23:10:22 -05:00
var node = path.getValue();
var parts = [];
var needsParens = false;
var linesWithoutParens = genericPrintNoParens(path, options, printPath);
2016-12-31 14:38:58 -05:00
if (!node || isEmpty(linesWithoutParens)) {
return linesWithoutParens;
}
2016-12-30 23:10:22 -05:00
if (
2017-01-18 15:31:46 -08:00
node.decorators &&
node.decorators.length > 0 &&
// If the parent node is an export declaration, it will be
// responsible for printing node.decorators.
!util.getParentExportDeclaration(path)
) {
2017-01-25 13:30:09 -08:00
const separator = node.decorators.length === 1 &&
node.decorators[0].expression.type === "Identifier"
2017-01-28 07:50:22 -08:00
? " "
: hardline;
path.each(
function(decoratorPath) {
2017-01-25 13:30:09 -08:00
parts.push(printPath(decoratorPath), separator);
},
"decorators"
);
2017-01-09 12:09:04 -05:00
} else if (
2017-01-18 15:31:46 -08:00
util.isExportDeclaration(node) &&
node.declaration &&
2017-01-09 12:09:04 -05:00
node.declaration.decorators
) {
// Export declarations are responsible for printing any decorators
// that logically apply to node.declaration.
path.each(
function(decoratorPath) {
parts.push(printPath(decoratorPath), line);
},
"declaration",
"decorators"
);
} else {
// Nodes with decorators can't have parentheses, so we can avoid
// computing path.needsParens() except in this case.
needsParens = path.needsParens();
}
2016-12-30 23:10:22 -05:00
if (needsParens) {
parts.unshift("(");
}
2016-12-30 23:10:22 -05:00
parts.push(linesWithoutParens);
2016-12-30 23:10:22 -05:00
if (needsParens) {
parts.push(")");
}
2016-12-30 23:10:22 -05:00
return concat(parts);
}
function genericPrintNoParens(path, options, print) {
var n = path.getValue();
2016-12-31 14:38:58 -05:00
if (!n) {
2017-01-19 13:20:03 -08:00
return "";
}
2016-12-30 23:10:22 -05:00
if (typeof n === "string") {
2017-01-19 13:20:03 -08:00
return n;
}
2016-12-30 23:10:22 -05:00
// TODO: For some reason NumericLiteralTypeAnnotation is not
// printable so this throws, but I think that's a bug in ast-types.
// This assert isn't very useful though.
// namedTypes.Printable.assert(n);
var parts = [];
switch (n.type) {
2017-01-13 15:03:53 -05:00
case "File":
return path.call(print, "program");
case "Program":
// Babel 6
if (n.directives) {
path.each(
function(childPath) {
parts.push(print(childPath), ";", hardline);
2017-02-03 08:50:51 -08:00
if (
util.isNextLineEmpty(options.originalText, childPath.getValue())
) {
2017-01-25 13:26:09 -08:00
parts.push(hardline);
}
2017-01-13 15:03:53 -05:00
},
"directives"
);
}
parts.push(
path.call(
function(bodyPath) {
return printStatementSequence(bodyPath, options, print);
},
"body"
)
);
2016-12-30 23:10:22 -05:00
2017-01-27 13:09:15 -08:00
parts.push(
comments.printDanglingComments(path, options, /* noIdent */ true)
);
2017-01-13 15:03:53 -05:00
parts.push(hardline);
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
return concat(parts);
// Babel extension.
case "Noop":
case "EmptyStatement":
2017-01-19 13:20:03 -08:00
return "";
2017-01-13 15:03:53 -05:00
case "ExpressionStatement":
2017-01-28 07:50:22 -08:00
return concat([path.call(print, "expression"), ";"]); // Babel extension.
case "ParenthesizedExpression":
return concat(["(", path.call(print, "expression"), ")"]);
2017-01-13 15:03:53 -05:00
case "AssignmentExpression":
return group(
concat([
path.call(print, "left"),
" ",
n.operator,
" ",
path.call(print, "right")
])
);
case "BinaryExpression":
case "LogicalExpression": {
const parts = [];
printBinaryishExpressions(path, parts, print, options);
2017-02-03 08:50:51 -08:00
return group(
concat([
2017-01-18 15:31:46 -08:00
// Don't include the initial expression in the indentation
// level. The first item is guaranteed to be the first
// left-most expression.
parts.length > 0 ? parts[0] : "",
indent(options.tabWidth, concat(parts.slice(1)))
2017-02-03 08:50:51 -08:00
])
);
}
2017-01-13 15:03:53 -05:00
case "AssignmentPattern":
return concat([
2017-01-09 12:09:04 -05:00
path.call(print, "left"),
2017-01-13 15:03:53 -05:00
" = ",
2017-01-09 12:09:04 -05:00
path.call(print, "right")
2017-01-13 15:03:53 -05:00
]);
case "MemberExpression": {
2017-01-09 12:09:04 -05:00
return concat([
path.call(print, "object"),
2017-01-26 11:58:47 -08:00
printMemberLookup(path, options, print)
2017-01-09 12:09:04 -05:00
]);
}
2017-01-13 15:03:53 -05:00
case "MetaProperty":
return concat([
path.call(print, "meta"),
".",
path.call(print, "property")
]);
case "BindExpression":
if (n.object) {
parts.push(path.call(print, "object"));
2017-01-13 09:59:33 -08:00
}
2016-12-31 14:38:58 -05:00
2017-01-13 15:03:53 -05:00
parts.push("::", path.call(print, "callee"));
return concat(parts);
case "Path":
return join(".", n.body);
case "Identifier":
return concat([
n.name,
n.optional ? "?" : "",
path.call(print, "typeAnnotation")
]);
case "SpreadElement":
case "SpreadElementPattern":
// Babel 6 for ObjectPattern
case "RestProperty":
case "SpreadProperty":
case "SpreadPropertyPattern":
case "RestElement":
return concat([
"...",
path.call(print, "argument"),
path.call(print, "typeAnnotation")
]);
case "FunctionDeclaration":
case "FunctionExpression":
2017-01-18 15:31:46 -08:00
if (n.async) parts.push("async ");
2017-01-13 15:03:53 -05:00
parts.push("function");
2017-01-18 15:31:46 -08:00
if (n.generator) parts.push("*");
2017-01-13 15:03:53 -05:00
if (n.id) {
parts.push(" ", path.call(print, "id"));
2017-01-13 09:59:33 -08:00
}
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
parts.push(
path.call(print, "typeParameters"),
group(
2017-01-13 15:03:53 -05:00
concat([
printFunctionParams(path, print, options),
printReturnType(path, print)
])
),
" ",
path.call(print, "body")
);
return concat(parts);
case "ArrowFunctionExpression":
2017-01-18 15:31:46 -08:00
if (n.async) parts.push("async ");
2017-01-13 15:03:53 -05:00
if (n.typeParameters) {
parts.push(path.call(print, "typeParameters"));
}
if (
2017-01-18 15:31:46 -08:00
n.params.length === 1 &&
!n.rest &&
n.params[0].type === "Identifier" &&
!n.params[0].typeAnnotation &&
!n.params[0].leadingComments &&
!n.params[0].trailingComments &&
2017-01-13 15:03:53 -05:00
!n.predicate &&
!n.returnType
) {
parts.push(path.call(print, "params", 0));
} else {
2017-01-13 09:59:33 -08:00
parts.push(
group(
2017-01-13 15:03:53 -05:00
concat([
printFunctionParams(path, print, options),
printReturnType(path, print)
])
)
2017-01-13 09:59:33 -08:00
);
}
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
parts.push(" =>");
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
const body = path.call(print, "body");
2017-01-28 07:50:22 -08:00
const collapsed = concat([concat(parts), " ", body]);
2016-12-30 23:10:22 -05:00
2017-01-24 13:54:01 -05:00
// We want to always keep these types of nodes on the same line
// as the arrow.
if (
2017-01-18 15:31:46 -08:00
n.body.type === "ArrayExpression" ||
n.body.type === "ObjectExpression" ||
n.body.type === "JSXElement" ||
n.body.type === "BlockStatement"
) {
2017-01-13 15:03:53 -05:00
return group(collapsed);
}
2016-12-31 14:38:58 -05:00
2017-01-24 13:54:01 -05:00
// These nested groups are a little wonky, but because
// `conditionalGroup` suppresses break propagation, we want to
// re-propagate it. We still want to allow the printer to choose
// the more collapsed version, but still break parents if there
// are any hard breaks in the content.
return group(
conditionalGroup([
collapsed,
concat([
concat(parts),
2017-01-28 07:50:22 -08:00
indent(options.tabWidth, concat([line, body]))
2017-01-24 13:54:01 -05:00
])
]),
{ shouldBreak: willBreak(body) }
);
2017-01-13 15:03:53 -05:00
case "MethodDefinition":
if (n.static) {
parts.push("static ");
}
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
parts.push(printMethod(path, options, print));
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
return concat(parts);
case "YieldExpression":
parts.push("yield");
2017-01-18 15:31:46 -08:00
if (n.delegate) parts.push("*");
2017-01-13 15:03:53 -05:00
2017-01-18 15:31:46 -08:00
if (n.argument) parts.push(" ", path.call(print, "argument"));
2017-01-13 15:03:53 -05:00
return concat(parts);
case "AwaitExpression":
parts.push("await");
2017-01-18 15:31:46 -08:00
if (n.all) parts.push("*");
2017-01-13 15:03:53 -05:00
2017-01-18 15:31:46 -08:00
if (n.argument) parts.push(" ", path.call(print, "argument"));
2017-01-13 15:03:53 -05:00
return concat(parts);
case "ModuleDeclaration":
parts.push("module", path.call(print, "id"));
if (n.source) {
assert.ok(!n.body);
parts.push("from", path.call(print, "source"));
} else {
parts.push(path.call(print, "body"));
}
return join(" ", parts);
case "ImportSpecifier":
if (n.imported) {
parts.push(path.call(print, "imported"));
if (n.local && n.local.name !== n.imported.name) {
parts.push(" as ", path.call(print, "local"));
}
} else if (n.id) {
parts.push(path.call(print, "id"));
if (n.name) {
parts.push(" as ", path.call(print, "name"));
}
}
return concat(parts);
case "ExportSpecifier":
if (n.local) {
parts.push(path.call(print, "local"));
if (n.exported && n.exported.name !== n.local.name) {
parts.push(" as ", path.call(print, "exported"));
}
} else if (n.id) {
parts.push(path.call(print, "id"));
if (n.name) {
parts.push(" as ", path.call(print, "name"));
}
}
return concat(parts);
case "ExportBatchSpecifier":
2017-01-20 10:12:37 -08:00
return "*";
2017-01-13 15:03:53 -05:00
case "ImportNamespaceSpecifier":
parts.push("* as ");
if (n.local) {
parts.push(path.call(print, "local"));
} else if (n.id) {
parts.push(path.call(print, "id"));
}
return concat(parts);
case "ImportDefaultSpecifier":
if (n.local) {
return path.call(print, "local");
}
return path.call(print, "id");
case "ExportDeclaration":
case "ExportDefaultDeclaration":
case "ExportNamedDeclaration":
return printExportDeclaration(path, options, print);
case "ExportAllDeclaration":
parts.push("export *");
if (n.exported) {
parts.push(" as ", path.call(print, "exported"));
}
parts.push(" from ", path.call(print, "source"), ";");
return concat(parts);
case "ExportNamespaceSpecifier":
2017-01-28 07:50:22 -08:00
return concat(["* as ", path.call(print, "exported")]);
2017-01-13 15:03:53 -05:00
case "ExportDefaultSpecifier":
return path.call(print, "exported");
case "ImportDeclaration":
parts.push("import ");
2017-02-03 13:19:14 -08:00
const fromParts = [];
2017-01-13 15:03:53 -05:00
if (n.importKind && n.importKind !== "value") {
parts.push(n.importKind + " ");
}
2017-02-03 13:19:14 -08:00
var standalones = [];
var grouped = [];
2017-01-13 15:03:53 -05:00
if (n.specifiers && n.specifiers.length > 0) {
path.each(
function(specifierPath) {
var value = specifierPath.getValue();
if (
namedTypes.ImportDefaultSpecifier.check(value) ||
namedTypes.ImportNamespaceSpecifier.check(value)
) {
standalones.push(print(specifierPath));
} else {
grouped.push(print(specifierPath));
}
},
"specifiers"
);
if (standalones.length > 0) {
parts.push(join(", ", standalones));
2017-01-13 15:03:53 -05:00
}
if (standalones.length > 0 && grouped.length > 0) {
parts.push(", ");
}
if (grouped.length > 0) {
2017-01-09 12:09:04 -05:00
parts.push(
2017-01-24 13:54:01 -05:00
group(
2017-01-13 15:03:53 -05:00
concat([
"{",
indent(
options.tabWidth,
concat([
options.bracketSpacing ? line : softline,
2017-01-28 07:50:22 -08:00
join(concat([",", line]), grouped)
2017-01-13 15:03:53 -05:00
])
),
ifBreak(options.trailingComma ? "," : ""),
options.bracketSpacing ? line : softline,
"}"
])
2017-01-09 12:09:04 -05:00
)
);
2017-01-13 15:03:53 -05:00
}
2017-02-03 13:19:14 -08:00
fromParts.push(grouped.length === 0 ? line : " ", "from ");
2017-01-13 15:03:53 -05:00
}
2017-02-03 13:19:14 -08:00
fromParts.push(path.call(print, "source"), ";");
2017-01-13 15:03:53 -05:00
2017-02-03 13:19:14 -08:00
// If there's a very long import, break the following way:
//
// import veryLong
// from 'verylong'
//
// In case there are grouped elements, they will already break the way
// we want and this break would take precedence instead.
if (grouped.length === 0) {
return group(
concat([
concat(parts),
indent(options.tabWidth, concat(fromParts))
])
);
}
return concat([concat(parts), concat(fromParts)]);
2017-01-25 10:33:48 -05:00
case "Import": {
return "import";
}
case "BlockStatement": {
2017-01-13 15:03:53 -05:00
var naked = path.call(
function(bodyPath) {
return printStatementSequence(bodyPath, options, print);
},
2017-01-13 15:03:53 -05:00
"body"
);
2016-12-30 23:10:22 -05:00
const hasContent = getFirstString(naked);
const hasDirectives = n.directives && n.directives.length > 0;
var parent = path.getParentNode();
2017-01-28 07:50:22 -08:00
if (
!hasContent &&
!hasDirectives &&
!n.comments &&
(parent.type === "ArrowFunctionExpression" ||
parent.type === "FunctionExpression" ||
2017-01-28 07:50:22 -08:00
parent.type === "FunctionDeclaration")
) {
return "{}";
}
2017-01-13 15:03:53 -05:00
parts.push("{");
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
// Babel 6
if (hasDirectives) {
2017-01-13 15:03:53 -05:00
path.each(
function(childPath) {
parts.push(
indent(
options.tabWidth,
2017-01-28 07:50:22 -08:00
concat([hardline, print(childPath), ";"])
2017-01-13 15:03:53 -05:00
)
);
},
"directives"
);
}
2016-12-30 23:10:22 -05:00
if (hasContent) {
2017-01-28 07:50:22 -08:00
parts.push(indent(options.tabWidth, concat([hardline, naked])));
2017-01-19 14:46:37 -05:00
}
2016-12-30 23:10:22 -05:00
2017-01-27 13:09:15 -08:00
parts.push(comments.printDanglingComments(path, options));
2017-01-13 15:03:53 -05:00
parts.push(hardline, "}");
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
return concat(parts);
}
2017-01-13 15:03:53 -05:00
case "ReturnStatement":
parts.push("return");
if (n.argument) {
parts.push(" ", path.call(print, "argument"));
}
parts.push(";");
return concat(parts);
case "CallExpression": {
2017-01-09 12:09:04 -05:00
const parent = path.getParentNode();
// We detect calls on member lookups and possibly print them in a
// special chain format. See `printMemberChain` for more info.
if (n.callee.type === "MemberExpression") {
return printMemberChain(path, options, print);
}
2017-01-09 12:09:04 -05:00
return concat([
path.call(print, "callee"),
printArgumentsList(path, options, print)
]);
}
2017-01-13 15:03:53 -05:00
case "ObjectExpression":
case "ObjectPattern":
case "ObjectTypeAnnotation":
var allowBreak = false;
var isTypeAnnotation = n.type === "ObjectTypeAnnotation";
// Leave this here because we *might* want to make this
// configurable later -- flow accepts ";" for type separators
var separator = isTypeAnnotation ? "," : ",";
var fields = [];
var leftBrace = n.exact ? "{|" : "{";
var rightBrace = n.exact ? "|}" : "}";
2016-12-31 14:38:58 -05:00
2017-01-13 15:03:53 -05:00
if (isTypeAnnotation) {
fields.push("indexers", "callProperties");
2017-01-10 21:48:49 -08:00
}
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
fields.push("properties");
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
var i = 0;
var props = [];
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
fields.forEach(function(field) {
path.each(
function(childPath) {
props.push(group(print(childPath)));
},
field
);
});
const lastElem = util.getLast(n.properties);
const canHaveTrailingComma = !(lastElem &&
lastElem.type === "RestProperty");
2017-01-30 09:08:55 -08:00
const shouldBreak = util.hasNewlineInRange(
options.originalText,
util.locStart(n),
util.locEnd(n)
);
2017-01-13 15:03:53 -05:00
if (props.length === 0) {
return group(
concat([
"{",
comments.printDanglingComments(path, options),
softline,
"}"
])
);
2017-01-13 15:03:53 -05:00
} else {
2017-01-24 13:54:01 -05:00
return group(
2017-01-09 12:09:04 -05:00
concat([
2017-01-13 15:03:53 -05:00
leftBrace,
2017-01-09 12:09:04 -05:00
indent(
options.tabWidth,
concat([
options.bracketSpacing ? line : softline,
2017-01-28 07:50:22 -08:00
join(concat([separator, line]), props)
2017-01-09 12:09:04 -05:00
])
),
ifBreak(canHaveTrailingComma && options.trailingComma ? "," : ""),
options.bracketSpacing ? line : softline,
2017-01-13 15:03:53 -05:00
rightBrace,
path.call(print, "typeAnnotation")
2017-01-30 09:08:55 -08:00
]),
{ shouldBreak }
2017-01-13 15:03:53 -05:00
);
2017-01-05 12:10:14 -05:00
}
2017-01-13 15:03:53 -05:00
case "PropertyPattern":
2017-01-13 10:00:32 -08:00
return concat([
2017-01-13 15:03:53 -05:00
path.call(print, "key"),
": ",
path.call(print, "pattern")
2017-01-13 10:00:32 -08:00
]);
2017-01-13 15:03:53 -05:00
// Babel 6
2017-01-28 07:50:22 -08:00
case "ObjectProperty": // Non-standard AST node type.
case "Property":
2017-01-13 15:03:53 -05:00
if (n.method || n.kind === "get" || n.kind === "set") {
return printMethod(path, options, print);
}
2017-01-13 10:00:32 -08:00
2017-01-13 15:03:53 -05:00
if (n.shorthand) {
parts.push(path.call(print, "value"));
} else {
if (n.computed) {
parts.push("[", path.call(print, "key"), "]");
} else {
parts.push(printPropertyKey(path, options, print));
2017-01-13 15:03:53 -05:00
}
2017-01-24 20:20:24 +01:00
let printedValue = path.call(print, "value");
if (shouldPrintSameLine(n.value)) {
parts.push(concat([": ", printedValue]));
} else {
parts.push(
concat([
":",
ifBreak(" (", " "),
indent(options.tabWidth, concat([softline, printedValue])),
2017-01-25 13:24:16 -08:00
softline,
2017-01-24 20:20:24 +01:00
ifBreak(")")
])
);
}
2017-01-13 15:03:53 -05:00
}
2017-01-28 07:50:22 -08:00
return concat(parts); // Babel 6
case "ClassMethod":
2017-01-13 15:03:53 -05:00
if (n.static) {
parts.push("static ");
}
parts = parts.concat(printObjectMethod(path, options, print));
2017-01-28 07:50:22 -08:00
return concat(parts); // Babel 6
case "ObjectMethod":
2017-01-13 15:03:53 -05:00
return printObjectMethod(path, options, print);
case "Decorator":
2017-01-28 07:50:22 -08:00
return concat(["@", path.call(print, "expression")]);
2017-01-13 15:03:53 -05:00
case "ArrayExpression":
case "ArrayPattern":
2017-01-13 15:03:53 -05:00
if (n.elements.length === 0) {
2017-01-28 07:50:22 -08:00
parts.push(
concat(["[", comments.printDanglingComments(path, options), "]"])
);
2017-01-13 15:03:53 -05:00
} else {
const lastElem = util.getLast(n.elements);
2017-01-23 09:49:46 -08:00
const canHaveTrailingComma = !(lastElem &&
lastElem.type === "RestElement");
// JavaScript allows you to have empty elements in an array which
// changes its length based on the number of commas. The algorithm
// is that if the last argument is null, we need to force insert
// a comma to ensure JavaScript recognizes it.
// [,].length === 1
// [1,].length === 1
// [1,,].length === 2
//
// Note that util.getLast returns null if the array is empty, but
// we already check for an empty array just above so we are safe
2017-01-23 09:49:46 -08:00
const needsForcedTrailingComma = canHaveTrailingComma &&
lastElem === null;
2017-01-13 15:03:53 -05:00
parts.push(
2017-01-24 13:54:01 -05:00
group(
2017-01-13 15:03:53 -05:00
concat([
"[",
indent(
options.tabWidth,
concat([
softline,
2017-01-28 07:50:22 -08:00
join(concat([",", line]), path.map(print, "elements"))
2017-01-13 15:03:53 -05:00
])
),
needsForcedTrailingComma ? "," : "",
ifBreak(
canHaveTrailingComma &&
2017-01-23 09:49:46 -08:00
!needsForcedTrailingComma &&
options.trailingComma
? ","
: ""
),
softline,
2017-01-13 15:03:53 -05:00
"]"
])
)
);
}
2017-01-18 15:31:46 -08:00
if (n.typeAnnotation) parts.push(path.call(print, "typeAnnotation"));
2017-01-13 15:03:53 -05:00
return concat(parts);
case "SequenceExpression":
return join(", ", path.map(print, "expressions"));
case "ThisExpression":
2017-01-20 10:12:37 -08:00
return "this";
2017-01-13 15:03:53 -05:00
case "Super":
2017-01-28 07:50:22 -08:00
return "super"; // Babel 6 Literal split
case "NullLiteral":
return "null"; // Babel 6 Literal split
case "RegExpLiteral":
return n.extra.raw;
2017-01-13 15:03:53 -05:00
// Babel 6 Literal split
case "NumericLiteral":
2017-01-30 18:36:23 +01:00
return printNumber(n.extra.raw);
// Babel 6 Literal split
case "BooleanLiteral":
2017-01-13 15:03:53 -05:00
// Babel 6 Literal split
case "StringLiteral":
case "Literal":
2017-01-30 18:36:23 +01:00
if (typeof n.value === "number") return printNumber(n.raw);
2017-01-19 13:20:03 -08:00
if (typeof n.value !== "string") return "" + n.value;
2017-01-13 15:03:53 -05:00
2017-01-28 07:50:22 -08:00
return nodeStr(n, options); // Babel 6
case "Directive":
return path.call(print, "value"); // Babel 6
case "DirectiveLiteral":
2017-01-19 13:20:03 -08:00
return nodeStr(n, options);
2017-01-13 15:03:53 -05:00
case "ModuleSpecifier":
if (n.local) {
throw new Error("The ESTree ModuleSpecifier type should be abstract");
}
// The Esprima ModuleSpecifier type is just a string-valued
// Literal identifying the imported-from module.
2017-01-19 13:20:03 -08:00
return nodeStr(n, options);
2017-01-13 15:03:53 -05:00
case "UnaryExpression":
parts.push(n.operator);
2017-01-18 15:31:46 -08:00
if (/[a-z]$/.test(n.operator)) parts.push(" ");
2017-01-13 15:03:53 -05:00
parts.push(path.call(print, "argument"));
return concat(parts);
case "UpdateExpression":
parts.push(path.call(print, "argument"), n.operator);
2017-01-18 15:31:46 -08:00
if (n.prefix) parts.reverse();
2017-01-13 15:03:53 -05:00
return concat(parts);
case "ConditionalExpression":
return group(
2017-01-09 12:09:04 -05:00
concat([
2017-01-13 15:03:53 -05:00
path.call(print, "test"),
2017-01-09 12:09:04 -05:00
indent(
options.tabWidth,
concat([
line,
2017-01-13 15:03:53 -05:00
"? ",
2017-02-02 10:37:59 -08:00
indent(2, path.call(print, "consequent")),
2017-01-09 12:09:04 -05:00
line,
2017-01-13 15:03:53 -05:00
": ",
2017-02-02 10:37:59 -08:00
indent(2, path.call(print, "alternate"))
2017-01-09 12:09:04 -05:00
])
)
])
2017-01-13 15:03:53 -05:00
);
case "NewExpression":
parts.push("new ", path.call(print, "callee"));
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
var args = n.arguments;
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
if (args) {
parts.push(printArgumentsList(path, options, print));
2017-01-10 21:48:49 -08:00
}
2016-12-30 23:10:22 -05:00
return concat(parts);
2017-01-13 15:03:53 -05:00
case "VariableDeclaration":
var printed = path.map(
function(childPath) {
return print(childPath);
},
"declarations"
);
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
parts = [
n.kind,
" ",
2017-01-18 15:31:46 -08:00
printed[0],
2017-01-13 15:03:53 -05:00
indent(
options.tabWidth,
2017-01-28 07:50:22 -08:00
concat(printed.slice(1).map(p => concat([",", line, p])))
2017-01-13 15:03:53 -05:00
)
];
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
// We generally want to terminate all variable declarations with a
// semicolon, except when they in the () part of for loops.
2017-01-13 15:03:53 -05:00
var parentNode = path.getParentNode();
2016-12-30 23:10:22 -05:00
var isParentForLoop = namedTypes.ForStatement.check(parentNode) ||
2017-01-23 09:49:46 -08:00
namedTypes.ForInStatement.check(parentNode) ||
2017-01-28 07:50:22 -08:00
namedTypes.ForOfStatement &&
namedTypes.ForOfStatement.check(parentNode) ||
2017-01-23 09:49:46 -08:00
namedTypes.ForAwaitStatement &&
namedTypes.ForAwaitStatement.check(parentNode);
if (!(isParentForLoop && parentNode.body !== n)) {
2017-01-13 15:03:53 -05:00
parts.push(";");
}
2016-12-30 23:10:22 -05:00
2017-01-24 13:54:01 -05:00
return group(concat(parts));
2017-01-13 15:03:53 -05:00
case "VariableDeclarator":
return n.init
2017-01-28 07:50:22 -08:00
? concat([path.call(print, "id"), " = ", path.call(print, "init")])
2017-01-13 15:03:53 -05:00
: path.call(print, "id");
case "WithStatement":
return concat([
"with (",
path.call(print, "object"),
")",
adjustClause(path.call(print, "body"), options)
2017-01-13 15:03:53 -05:00
]);
case "IfStatement":
const con = adjustClause(path.call(print, "consequent"), options);
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
parts = [
"if (",
group(
concat([
indent(
options.tabWidth,
2017-01-28 07:50:22 -08:00
concat([softline, path.call(print, "test")])
2017-01-13 15:03:53 -05:00
),
softline
])
),
")",
con
];
2017-01-13 15:03:53 -05:00
if (n.alternate) {
const hasBraces = isCurlyBracket(con);
const isEmpty = isEmptyBlock(con);
if (hasBraces && !isEmpty) {
parts.push(" else");
} else {
// We use `conditionalGroup` to suppress break propagation.
// This allows us to provide a hardline without forcing the
// entire `if` clause to break up.
2017-01-28 07:50:22 -08:00
parts.push(conditionalGroup([concat([hardline, "else"])]));
2017-01-13 15:03:53 -05:00
}
parts.push(
adjustClause(
path.call(print, "alternate"),
options,
n.alternate.type === "IfStatement"
)
);
}
return group(concat(parts));
case "ForStatement": {
const body = adjustClause(path.call(print, "body"), options);
if (!n.init && !n.test && !n.update) {
2017-01-28 07:50:22 -08:00
return concat(["for (;;)", body]);
2017-01-13 15:03:53 -05:00
}
return concat([
"for (",
group(
concat([
indent(
options.tabWidth,
concat([
2017-01-13 15:03:53 -05:00
softline,
path.call(print, "init"),
";",
line,
path.call(print, "test"),
";",
line,
path.call(print, "update")
])
2017-01-13 15:03:53 -05:00
),
softline
])
),
")",
body
]);
}
case "WhileStatement":
return concat([
"while (",
group(
concat([
indent(
options.tabWidth,
2017-01-28 07:50:22 -08:00
concat([softline, path.call(print, "test")])
),
softline
])
),
2017-01-13 15:03:53 -05:00
")",
adjustClause(path.call(print, "body"), options)
]);
case "ForInStatement":
// Note: esprima can't actually parse "for each (".
return concat([
n.each ? "for each (" : "for (",
path.call(print, "left"),
" in ",
path.call(print, "right"),
")",
adjustClause(path.call(print, "body"), options)
]);
case "ForOfStatement":
return concat([
"for (",
path.call(print, "left"),
" of ",
path.call(print, "right"),
")",
adjustClause(path.call(print, "body"), options)
]);
case "ForAwaitStatement":
return concat([
"for await (",
path.call(print, "left"),
" of ",
path.call(print, "right"),
")",
adjustClause(path.call(print, "body"), options)
]);
case "DoWhileStatement":
var clause = adjustClause(path.call(print, "body"), options);
2017-01-28 07:50:22 -08:00
var doBody = concat(["do", clause]);
var parts = [doBody];
2017-01-13 15:03:53 -05:00
const hasBraces = isCurlyBracket(clause);
2017-01-18 15:31:46 -08:00
if (hasBraces) parts.push(" while");
2017-01-28 07:50:22 -08:00
else parts.push(concat([line, "while"]));
2017-01-13 15:03:53 -05:00
parts.push(" (", path.call(print, "test"), ");");
return concat(parts);
case "DoExpression":
var statements = path.call(
function(bodyPath) {
return printStatementSequence(bodyPath, options, print);
},
"body"
);
2017-01-28 07:50:22 -08:00
return concat(["do {\n", statements.indent(options.tabWidth), "\n}"]);
2017-01-13 15:03:53 -05:00
case "BreakStatement":
parts.push("break");
2017-01-18 15:31:46 -08:00
if (n.label) parts.push(" ", path.call(print, "label"));
2017-01-13 15:03:53 -05:00
parts.push(";");
return concat(parts);
case "ContinueStatement":
parts.push("continue");
2017-01-18 15:31:46 -08:00
if (n.label) parts.push(" ", path.call(print, "label"));
2017-01-13 15:03:53 -05:00
parts.push(";");
return concat(parts);
case "LabeledStatement":
2017-01-22 12:34:27 -08:00
if (n.body.type === "EmptyStatement") {
2017-01-28 07:50:22 -08:00
return concat([path.call(print, "label"), ":;"]);
2017-01-22 12:34:27 -08:00
}
2017-01-13 15:03:53 -05:00
return concat([
path.call(print, "label"),
":",
hardline,
path.call(print, "body")
]);
case "TryStatement":
parts.push("try ", path.call(print, "block"));
if (n.handler) {
parts.push(" ", path.call(print, "handler"));
} else if (n.handlers) {
path.each(
function(handlerPath) {
parts.push(" ", print(handlerPath));
},
"handlers"
);
}
if (n.finalizer) {
parts.push(" finally ", path.call(print, "finalizer"));
}
return concat(parts);
case "CatchClause":
parts.push("catch (", path.call(print, "param"));
if (n.guard)
// Note: esprima does not recognize conditional catch clauses.
parts.push(" if ", path.call(print, "guard"));
parts.push(") ", path.call(print, "body"));
return concat(parts);
case "ThrowStatement":
2017-01-28 07:50:22 -08:00
return concat(["throw ", path.call(print, "argument"), ";"]);
2017-01-13 15:03:53 -05:00
// Note: ignoring n.lexical because it has no printing consequences.
case "SwitchStatement":
return concat([
"switch (",
path.call(print, "discriminant"),
") {",
2017-01-23 09:49:46 -08:00
n.cases.length > 0
? indent(
2017-01-28 07:50:22 -08:00
options.tabWidth,
concat([hardline, join(hardline, path.map(print, "cases"))])
)
2017-01-23 09:49:46 -08:00
: "",
2017-01-13 15:03:53 -05:00
hardline,
"}"
]);
case "SwitchCase":
2017-01-18 15:31:46 -08:00
if (n.test) parts.push("case ", path.call(print, "test"), ":");
else parts.push("default:");
2017-01-13 15:03:53 -05:00
if (n.consequent.find(node => node.type !== "EmptyStatement")) {
2017-01-13 15:03:53 -05:00
const cons = path.call(
function(consequentPath) {
return printStatementSequence(consequentPath, options, print);
},
"consequent"
);
parts.push(
isCurlyBracket(cons)
2017-01-28 07:50:22 -08:00
? concat([" ", cons])
: indent(options.tabWidth, concat([hardline, cons]))
2017-01-13 15:03:53 -05:00
);
}
return concat(parts);
// JSX extensions below.
case "DebuggerStatement":
2017-01-20 10:12:37 -08:00
return "debugger;";
2017-01-13 15:03:53 -05:00
case "JSXAttribute":
parts.push(path.call(print, "name"));
if (n.value) {
let res;
if (
(n.value.type === "StringLiteral" || n.value.type === "Literal") &&
typeof n.value.value === "string"
) {
res = '"' + util.htmlEscapeInsideDoubleQuote(n.value.value) + '"';
} else {
res = path.call(print, "value");
}
parts.push("=", res);
}
return concat(parts);
case "JSXIdentifier":
2017-01-19 13:20:03 -08:00
return "" + n.name;
2017-01-13 15:03:53 -05:00
case "JSXNamespacedName":
return join(":", [
path.call(print, "namespace"),
path.call(print, "name")
]);
case "JSXMemberExpression":
return join(".", [
path.call(print, "object"),
path.call(print, "property")
]);
case "JSXSpreadAttribute":
2017-01-28 07:50:22 -08:00
return concat(["{...", path.call(print, "argument"), "}"]);
2017-01-26 11:51:08 -08:00
case "JSXExpressionContainer": {
const parent = path.getParentNode(0);
2017-01-26 11:51:08 -08:00
const shouldInline = n.expression.type === "ArrayExpression" ||
n.expression.type === "ObjectExpression" ||
n.expression.type === "ArrowFunctionExpression" ||
n.expression.type === "CallExpression" ||
n.expression.type === "FunctionExpression" ||
2017-01-28 07:50:22 -08:00
parent.type === "JSXElement" &&
(n.expression.type === "ConditionalExpression" ||
n.expression.type === "LogicalExpression");
2017-01-26 11:51:08 -08:00
if (shouldInline) {
2017-01-28 07:50:22 -08:00
return concat(["{", path.call(print, "expression"), "}"]);
}
return group(
2017-01-13 15:03:53 -05:00
concat([
"{",
indent(
options.tabWidth,
2017-01-28 07:50:22 -08:00
concat([softline, path.call(print, "expression")])
2017-01-13 15:03:53 -05:00
),
softline,
"}"
])
);
2017-01-26 11:51:08 -08:00
}
case "JSXElement": {
const elem = printJSXElement(path, options, print);
return maybeWrapJSXElementInParens(path, elem, options);
}
case "JSXOpeningElement": {
const n = path.getValue();
// don't break up opening elements with a single long text attribute
2017-01-28 07:50:22 -08:00
if (
n.attributes.length === 1 &&
n.attributes[0].value &&
n.attributes[0].value.type === "Literal" &&
typeof n.attributes[0].value.value === "string"
) {
2017-01-28 07:50:22 -08:00
return group(
concat([
"<",
path.call(print, "name"),
" ",
concat(path.map(print, "attributes")),
n.selfClosing ? " />" : ">"
])
);
}
2017-01-13 15:03:53 -05:00
return group(
concat([
"<",
path.call(print, "name"),
2017-01-24 13:54:01 -05:00
concat([
indent(
options.tabWidth,
concat(
2017-01-28 07:50:22 -08:00
path.map(attr => concat([line, print(attr)]), "attributes")
2017-01-24 13:54:01 -05:00
)
),
n.selfClosing ? line : softline
]),
2017-01-13 15:03:53 -05:00
n.selfClosing ? "/>" : ">"
])
);
}
2017-01-13 15:03:53 -05:00
case "JSXClosingElement":
2017-01-28 07:50:22 -08:00
return concat(["</", path.call(print, "name"), ">"]);
2017-01-13 15:03:53 -05:00
case "JSXText":
throw new Error("JSXTest should be handled by JSXElement");
case "JSXEmptyExpression":
2017-01-27 13:09:15 -08:00
return comments.printDanglingComments(path, options);
2017-01-13 15:03:53 -05:00
case "TypeAnnotatedIdentifier":
return concat([
path.call(print, "annotation"),
" ",
path.call(print, "identifier")
]);
case "ClassBody":
if (!n.comments && n.body.length === 0) {
return "{}";
2017-01-13 15:03:53 -05:00
}
2017-02-03 08:50:51 -08:00
return concat([
"{",
n.body.length > 0 ? indent(
2017-02-03 08:50:51 -08:00
options.tabWidth,
concat([
2017-01-13 15:03:53 -05:00
hardline,
path.call(
function(bodyPath) {
return printStatementSequence(bodyPath, options, print);
},
"body"
)
2017-02-03 08:50:51 -08:00
])
) : comments.printDanglingComments(path, options),
2017-02-03 08:50:51 -08:00
hardline,
"}"
]);
2017-01-13 15:03:53 -05:00
case "ClassPropertyDefinition":
parts.push("static ", path.call(print, "definition"));
2017-01-18 15:31:46 -08:00
if (!namedTypes.MethodDefinition.check(n.definition)) parts.push(";");
2017-01-13 15:03:53 -05:00
return concat(parts);
case "ClassProperty":
2017-01-18 15:31:46 -08:00
if (n.static) parts.push("static ");
2017-01-13 15:03:53 -05:00
var key;
if (n.computed) {
2017-01-28 07:50:22 -08:00
key = concat(["[", path.call(print, "key"), "]"]);
2017-01-13 15:03:53 -05:00
} else {
key = printPropertyKey(path, options, print);
2017-01-13 15:03:53 -05:00
if (n.variance === "plus") {
2017-01-28 07:50:22 -08:00
key = concat(["+", key]);
2017-01-13 15:03:53 -05:00
} else if (n.variance === "minus") {
2017-01-28 07:50:22 -08:00
key = concat(["-", key]);
2017-01-13 15:03:53 -05:00
}
}
parts.push(key);
2017-01-18 15:31:46 -08:00
if (n.typeAnnotation) parts.push(path.call(print, "typeAnnotation"));
2017-01-13 15:03:53 -05:00
2017-01-18 15:31:46 -08:00
if (n.value) parts.push(" = ", path.call(print, "value"));
2017-01-13 15:03:53 -05:00
parts.push(";");
return concat(parts);
case "ClassDeclaration":
case "ClassExpression":
return concat(printClass(path, options, print));
2017-01-13 15:03:53 -05:00
case "TemplateElement":
return join(literalline, n.value.raw.split("\n"));
2017-01-13 15:03:53 -05:00
case "TemplateLiteral":
var expressions = path.map(print, "expressions");
parts.push("`");
path.each(
function(childPath) {
var i = childPath.getName();
parts.push(print(childPath));
if (i < expressions.length) {
parts.push("${", expressions[i], "}");
}
},
"quasis"
2017-01-09 12:09:04 -05:00
);
2017-01-13 15:03:53 -05:00
parts.push("`");
return concat(parts);
// These types are unprintable because they serve as abstract
// supertypes for other (printable) types.
case "TaggedTemplateExpression":
2017-01-28 07:50:22 -08:00
return concat([path.call(print, "tag"), path.call(print, "quasi")]);
2017-01-13 15:03:53 -05:00
case "Node":
case "Printable":
case "SourceLocation":
case "Position":
case "Statement":
case "Function":
case "Pattern":
case "Expression":
case "Declaration":
case "Specifier":
case "NamedSpecifier":
// Supertype of Block and Line.
case "Comment":
// Flow
2017-01-28 07:50:22 -08:00
case "MemberTypeAnnotation": // Flow
case "Type":
2017-01-13 15:03:53 -05:00
throw new Error("unprintable type: " + JSON.stringify(n.type));
2017-01-13 15:03:53 -05:00
// Type Annotations for Facebook Flow, typically stripped out or
// transformed away before printing.
case "TypeAnnotation":
if (n.typeAnnotation) {
if (n.typeAnnotation.type !== "FunctionTypeAnnotation") {
parts.push(": ");
}
parts.push(path.call(print, "typeAnnotation"));
return concat(parts);
}
return "";
case "TupleTypeAnnotation":
2017-01-28 07:50:22 -08:00
return concat(["[", join(", ", path.map(print, "types")), "]"]);
2017-01-13 15:03:53 -05:00
case "ExistentialTypeParam":
case "ExistsTypeAnnotation":
2017-01-20 10:12:37 -08:00
return "*";
2017-01-13 15:03:53 -05:00
case "EmptyTypeAnnotation":
2017-01-20 10:12:37 -08:00
return "empty";
2017-01-13 15:03:53 -05:00
case "AnyTypeAnnotation":
2017-01-20 10:12:37 -08:00
return "any";
2017-01-13 15:03:53 -05:00
case "MixedTypeAnnotation":
2017-01-20 10:12:37 -08:00
return "mixed";
2017-01-13 15:03:53 -05:00
case "ArrayTypeAnnotation":
2017-01-28 07:50:22 -08:00
return concat([path.call(print, "elementType"), "[]"]);
2017-01-13 15:03:53 -05:00
case "BooleanTypeAnnotation":
2017-01-20 10:12:37 -08:00
return "boolean";
2017-01-13 15:03:53 -05:00
case "NumericLiteralTypeAnnotation":
case "BooleanLiteralTypeAnnotation":
return "" + n.value;
case "DeclareClass":
return printFlowDeclaration(path, printClass(path, options, print));
2017-01-13 15:03:53 -05:00
case "DeclareFunction":
return printFlowDeclaration(path, [
"function ",
path.call(print, "id"),
n.predicate ? " " : "",
path.call(print, "predicate"),
";"
]);
case "DeclareModule":
return printFlowDeclaration(path, [
"module ",
path.call(print, "id"),
" ",
path.call(print, "body")
]);
case "DeclareModuleExports":
return printFlowDeclaration(path, [
"module.exports",
path.call(print, "typeAnnotation"),
";"
]);
case "DeclareVariable":
2017-01-28 07:50:22 -08:00
return printFlowDeclaration(path, ["var ", path.call(print, "id"), ";"]);
2017-01-13 15:03:53 -05:00
case "DeclareExportAllDeclaration":
2017-01-28 07:50:22 -08:00
return concat(["declare export * from ", path.call(print, "source")]);
2017-01-13 15:03:53 -05:00
case "DeclareExportDeclaration":
2017-01-28 07:50:22 -08:00
return concat(["declare ", printExportDeclaration(path, options, print)]);
2017-01-13 15:03:53 -05:00
case "FunctionTypeAnnotation":
// FunctionTypeAnnotation is ambiguous:
// declare function foo(a: B): void; OR
// var A: (a: B) => void;
var parent = path.getParentNode(0);
var isArrowFunctionTypeAnnotation = !(!parent.variance &&
!parent.optional &&
namedTypes.ObjectTypeProperty.check(parent) ||
namedTypes.ObjectTypeCallProperty.check(parent) ||
namedTypes.DeclareFunction.check(path.getParentNode(2)));
2017-01-13 15:03:53 -05:00
var needsColon = isArrowFunctionTypeAnnotation &&
namedTypes.TypeAnnotation.check(parent);
if (isObjectTypePropertyAFunction(parent)) {
isArrowFunctionTypeAnnotation = true;
needsColon = true;
}
2017-01-13 15:03:53 -05:00
if (needsColon) {
parts.push(": ");
}
parts.push(path.call(print, "typeParameters"));
2017-01-24 13:54:01 -05:00
parts.push(group(printFunctionParams(path, print, options)));
2017-01-13 15:03:53 -05:00
// The returnType is not wrapped in a TypeAnnotation, so the colon
// needs to be added separately.
if (n.returnType || n.predicate) {
parts.push(
isArrowFunctionTypeAnnotation ? " => " : ": ",
path.call(print, "returnType"),
path.call(print, "predicate")
);
}
return concat(parts);
case "FunctionTypeParam":
return concat([
path.call(print, "name"),
n.optional ? "?" : "",
n.name ? ": " : "",
path.call(print, "typeAnnotation")
]);
case "GenericTypeAnnotation":
return concat([
path.call(print, "id"),
path.call(print, "typeParameters")
]);
case "DeclareInterface":
2017-01-13 20:15:30 -08:00
case "InterfaceDeclaration": {
const parent = path.getParentNode(1);
if (parent && parent.type === "DeclareModule") {
parts.push("declare ");
}
2017-01-13 15:03:53 -05:00
parts.push(
2017-01-19 13:20:03 -08:00
"interface ",
2017-01-13 15:03:53 -05:00
path.call(print, "id"),
path.call(print, "typeParameters"),
" "
);
if (n["extends"].length > 0) {
2017-01-18 15:31:46 -08:00
parts.push("extends ", join(", ", path.map(print, "extends")), " ");
2017-01-13 15:03:53 -05:00
}
2017-01-13 20:15:30 -08:00
parts.push(path.call(print, "body"));
2017-01-13 15:03:53 -05:00
return concat(parts);
2017-01-13 20:15:30 -08:00
}
2017-01-13 15:03:53 -05:00
case "ClassImplements":
case "InterfaceExtends":
return concat([
path.call(print, "id"),
path.call(print, "typeParameters")
]);
case "IntersectionTypeAnnotation":
case "UnionTypeAnnotation": {
const types = path.map(print, "types");
const op = n.type === "IntersectionTypeAnnotation" ? "&" : "|";
// single-line variation
// A | B | C
// multi-line variation
// | A
// | B
// | C
return group(
indent(
options.tabWidth,
concat([
ifBreak(concat([line, op, " "])),
join(concat([line, op, " "]), types)
])
)
);
2017-01-09 12:09:04 -05:00
}
2017-01-13 15:03:53 -05:00
case "NullableTypeAnnotation":
2017-01-28 07:50:22 -08:00
return concat(["?", path.call(print, "typeAnnotation")]);
2017-01-13 15:03:53 -05:00
case "NullLiteralTypeAnnotation":
2017-01-20 10:12:37 -08:00
return "null";
2017-01-13 15:03:53 -05:00
case "ThisTypeAnnotation":
2017-01-20 10:12:37 -08:00
return "this";
2017-01-13 15:03:53 -05:00
case "NumberTypeAnnotation":
2017-01-20 10:12:37 -08:00
return "number";
2017-01-13 15:03:53 -05:00
case "ObjectTypeCallProperty":
if (n.static) {
parts.push("static ");
}
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
parts.push(path.call(print, "value"));
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
return concat(parts);
case "ObjectTypeIndexer":
var variance = n.variance === "plus"
? "+"
: n.variance === "minus" ? "-" : "";
return concat([
variance,
"[",
path.call(print, "id"),
n.id ? ": " : "",
path.call(print, "key"),
"]: ",
path.call(print, "value")
]);
case "ObjectTypeProperty":
var variance = n.variance === "plus"
? "+"
: n.variance === "minus" ? "-" : "";
// TODO: This is a bad hack and we need a better way to know
// when to emit an arrow function or not.
2017-01-18 15:31:46 -08:00
var isFunction = !n.variance &&
!n.optional &&
2017-01-13 15:03:53 -05:00
n.value.type === "FunctionTypeAnnotation";
if (isObjectTypePropertyAFunction(n)) {
isFunction = true;
}
2017-01-13 15:03:53 -05:00
return concat([
n.static ? "static " : "",
variance,
path.call(print, "key"),
n.optional ? "?" : "",
isFunction ? "" : ": ",
path.call(print, "value")
]);
case "QualifiedTypeIdentifier":
return concat([
path.call(print, "qualification"),
".",
path.call(print, "id")
]);
case "StringLiteralTypeAnnotation":
2017-01-19 13:20:03 -08:00
return nodeStr(n, options);
2017-01-13 15:03:53 -05:00
case "NumberLiteralTypeAnnotation":
assert.strictEqual(typeof n.value, "number");
2016-12-30 23:10:22 -05:00
2017-01-19 13:20:03 -08:00
return "" + n.value;
2017-01-13 15:03:53 -05:00
case "StringTypeAnnotation":
2017-01-20 10:12:37 -08:00
return "string";
2017-01-13 15:03:53 -05:00
case "DeclareTypeAlias":
case "TypeAlias": {
const parent = path.getParentNode(1);
if (parent && parent.type === "DeclareModule") {
parts.push("declare ");
}
2016-12-30 23:10:22 -05:00
parts.push(
"type ",
path.call(print, "id"),
path.call(print, "typeParameters"),
" = ",
path.call(print, "right"),
";"
);
2016-12-30 23:10:22 -05:00
return concat(parts);
}
2017-01-13 15:03:53 -05:00
case "TypeCastExpression":
return concat([
"(",
path.call(print, "expression"),
path.call(print, "typeAnnotation"),
")"
]);
case "TypeParameterDeclaration":
case "TypeParameterInstantiation":
2017-01-28 07:50:22 -08:00
return concat(["<", join(", ", path.map(print, "params")), ">"]);
2017-01-13 15:03:53 -05:00
case "TypeParameter":
switch (n.variance) {
case "plus":
parts.push("+");
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
break;
case "minus":
parts.push("-");
2016-12-30 23:10:22 -05:00
2017-01-13 15:03:53 -05:00
break;
default:
}
parts.push(path.call(print, "name"));
if (n.bound) {
parts.push(path.call(print, "bound"));
}
if (n["default"]) {
parts.push("=", path.call(print, "default"));
}
return concat(parts);
case "TypeofTypeAnnotation":
2017-01-28 07:50:22 -08:00
return concat(["typeof ", path.call(print, "argument")]);
2017-01-13 15:03:53 -05:00
case "VoidTypeAnnotation":
return "void";
case "NullTypeAnnotation":
return "null";
case "InferredPredicate":
return "%checks";
// Unhandled types below. If encountered, nodes of these types should
// be either left alone or desugared into AST types that are fully
// supported by the pretty-printer.
case "DeclaredPredicate":
2017-01-28 07:50:22 -08:00
return concat(["%checks(", path.call(print, "value"), ")"]);
2017-01-13 15:03:53 -05:00
// TODO
case "ClassHeritage":
// TODO
case "ComprehensionBlock":
// TODO
case "ComprehensionExpression":
// TODO
case "Glob":
// TODO
case "GeneratorExpression":
// TODO
case "LetStatement":
// TODO
case "LetExpression":
// TODO
case "GraphExpression":
// TODO
// XML types that nobody cares about or needs to print.
case "GraphIndexExpression":
case "XMLDefaultDeclaration":
case "XMLAnyName":
case "XMLQualifiedIdentifier":
case "XMLFunctionQualifiedIdentifier":
case "XMLAttributeSelector":
case "XMLFilterExpression":
case "XML":
case "XMLElement":
case "XMLList":
case "XMLEscape":
case "XMLText":
case "XMLStartTag":
case "XMLEndTag":
case "XMLPointTag":
case "XMLName":
case "XMLAttribute":
case "XMLCdata":
case "XMLComment":
case "XMLProcessingInstruction":
default:
2017-01-13 15:03:53 -05:00
debugger;
throw new Error("unknown type: " + JSON.stringify(n.type));
}
return p;
}
function printStatementSequence(path, options, print) {
2016-12-30 23:10:22 -05:00
let printed = [];
2016-12-31 14:38:58 -05:00
2017-01-04 22:27:25 -05:00
path.map(function(stmtPath, i) {
var stmt = stmtPath.getValue();
2016-12-31 14:38:58 -05:00
2017-01-04 22:27:25 -05:00
// Just in case the AST has been modified to contain falsy
// "statements," it's safer simply to skip them.
if (!stmt) {
return;
}
2017-01-04 22:27:25 -05:00
// Skip printing EmptyStatement nodes to avoid leaving stray
// semicolons lying around.
if (stmt.type === "EmptyStatement") {
return;
}
const stmtPrinted = print(stmtPath);
const text = options.originalText;
2017-01-04 22:27:25 -05:00
const parts = [];
parts.push(stmtPrinted);
if (util.isNextLineEmpty(text, stmt) && !isLastStatement(stmtPath)) {
2017-01-04 22:27:25 -05:00
parts.push(hardline);
}
printed.push(concat(parts));
});
2016-12-30 23:10:22 -05:00
return join(hardline, printed);
}
function printPropertyKey(path, options, print) {
const node = path.getNode();
const key = node.key;
if (
(key.type === "StringLiteral" ||
key.type === "Literal" && typeof key.value === "string") &&
isIdentifierName(key.value) &&
!node.computed &&
// There's a bug in the flow parser where it throws if there are
// unquoted unicode literals as keys. Let's quote them for now.
(options.parser !== "flow" || key.value.match(/[a-zA-Z0-9$_]/))
) {
2017-01-11 09:31:34 -08:00
// 'a' -> a
return key.value;
2017-01-10 21:48:49 -08:00
}
return path.call(print, "key");
}
function printMethod(path, options, print) {
var node = path.getNode();
var kind = node.kind;
var parts = [];
2016-12-31 14:38:58 -05:00
if (node.type === "ObjectMethod" || node.type === "ClassMethod") {
node.value = node;
} else {
namedTypes.FunctionExpression.assert(node.value);
}
2016-12-30 23:10:22 -05:00
if (node.value.async) {
parts.push("async ");
}
2016-12-30 23:10:22 -05:00
if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
if (node.value.generator) {
parts.push("*");
}
} else {
assert.ok(kind === "get" || kind === "set");
2016-12-30 23:10:22 -05:00
parts.push(kind, " ");
}
2016-12-30 23:10:22 -05:00
var key = printPropertyKey(path, options, print);
2016-12-31 14:38:58 -05:00
if (node.computed) {
2017-01-28 07:50:22 -08:00
key = concat(["[", key, "]"]);
}
2016-12-30 23:10:22 -05:00
2017-02-03 08:50:51 -08:00
parts.push(
key,
path.call(print, "value", "typeParameters"),
group(
concat([
2017-01-13 15:03:53 -05:00
path.call(
function(valuePath) {
return printFunctionParams(valuePath, print, options);
},
"value"
),
path.call(p => printReturnType(p, print), "value")
2017-02-03 08:50:51 -08:00
])
),
" ",
path.call(print, "value", "body")
);
2016-12-30 23:10:22 -05:00
2017-01-09 13:47:02 -05:00
return concat(parts);
}
function printArgumentsList(path, options, print) {
var printed = path.map(print, "arguments");
var args;
2016-12-31 14:38:58 -05:00
if (printed.length === 0) {
return "()";
}
2016-12-30 23:10:22 -05:00
const lastArg = util.getLast(path.getValue().arguments);
// This is just an optimization; I think we could return the
// conditional group for all function calls, but it's more expensive
// so only do it for specific forms.
const groupLastArg = (!lastArg.comments || !lastArg.comments.length) &&
(lastArg.type === "ObjectExpression" ||
lastArg.type === "ArrayExpression" ||
lastArg.type === "FunctionExpression" ||
lastArg.type === "ArrowFunctionExpression" &&
(lastArg.body.type === "BlockStatement" ||
lastArg.body.type === "ArrowFunctionExpression" ||
lastArg.body.type === "ObjectExpression" ||
lastArg.body.type === "ArrayExpression" ||
lastArg.body.type === "CallExpression" ||
lastArg.body.type === "JSXElement") ||
lastArg.type === "NewExpression");
if (groupLastArg) {
const shouldBreak = printed.slice(0, -1).some(willBreak);
return concat([
printed.some(willBreak) ? breakParent : "",
conditionalGroup(
[
concat(["(", join(concat([", "]), printed), ")"]),
concat([
"(",
join(concat([",", line]), printed.slice(0, -1)),
printed.length > 1 ? ", " : "",
group(util.getLast(printed), { shouldBreak: true }),
")"
]),
group(
concat([
"(",
indent(
options.tabWidth,
concat([line, join(concat([",", line]), printed)])
),
options.trailingComma ? "," : "",
line,
")"
]),
{ shouldBreak: true }
)
],
{ shouldBreak }
)
]);
}
2017-01-24 13:54:01 -05:00
return group(
concat([
"(",
2017-01-09 12:09:04 -05:00
indent(
options.tabWidth,
2017-01-28 07:50:22 -08:00
concat([softline, join(concat([",", line]), printed)])
2017-01-09 12:09:04 -05:00
),
2017-01-05 12:19:30 -05:00
ifBreak(options.trailingComma ? "," : ""),
softline,
")"
2017-01-31 08:45:47 -08:00
]),
{ shouldBreak: printed.some(willBreak) }
);
}
function printFunctionParams(path, print, options) {
var fun = path.getValue();
// namedTypes.Function.assert(fun);
var printed = path.map(print, "params");
2016-12-31 14:38:58 -05:00
if (fun.defaults) {
path.each(
function(defExprPath) {
var i = defExprPath.getName();
var p = printed[i];
2016-12-31 14:38:58 -05:00
if (p && defExprPath.getValue()) {
2017-01-28 07:50:22 -08:00
printed[i] = concat([p, " = ", print(defExprPath)]);
}
},
"defaults"
);
}
2016-12-30 23:10:22 -05:00
if (fun.rest) {
2017-01-28 07:50:22 -08:00
printed.push(concat(["...", path.call(print, "rest")]));
}
2016-12-30 23:10:22 -05:00
if (printed.length === 0) {
return "()";
}
const lastParam = util.getLast(path.getValue().params);
2017-01-20 10:12:37 -08:00
const canHaveTrailingComma = !(lastParam &&
lastParam.type === "RestElement") &&
!fun.rest;
return concat([
"(",
2017-01-09 12:09:04 -05:00
indent(
options.tabWidth,
2017-01-28 07:50:22 -08:00
concat([softline, join(concat([",", line]), printed)])
2017-01-09 12:09:04 -05:00
),
ifBreak(canHaveTrailingComma && options.trailingComma ? "," : ""),
softline,
")"
]);
}
function printObjectMethod(path, options, print) {
var objMethod = path.getValue();
var parts = [];
2016-12-31 14:38:58 -05:00
2017-01-18 15:31:46 -08:00
if (objMethod.async) parts.push("async ");
2016-12-30 23:10:22 -05:00
2017-01-18 15:31:46 -08:00
if (objMethod.generator) parts.push("*");
2016-12-30 23:10:22 -05:00
if (
objMethod.method || objMethod.kind === "get" || objMethod.kind === "set"
) {
return printMethod(path, options, print);
}
2016-12-30 23:10:22 -05:00
var key = printPropertyKey(path, options, print);
2016-12-31 14:38:58 -05:00
if (objMethod.computed) {
parts.push("[", key, "]");
} else {
parts.push(key);
}
2016-12-30 23:10:22 -05:00
2017-01-11 15:14:46 -08:00
if (objMethod.typeParameters) {
parts.push(path.call(print, "typeParameters"));
}
parts.push(
2017-01-24 13:54:01 -05:00
group(
2017-01-13 15:03:53 -05:00
concat([
printFunctionParams(path, print, options),
printReturnType(path, print)
])
),
" ",
path.call(print, "body")
);
2016-12-30 23:10:22 -05:00
2017-01-09 13:47:02 -05:00
return concat(parts);
}
2016-12-30 13:32:43 -05:00
function printReturnType(path, print) {
const n = path.getValue();
2017-01-28 07:50:22 -08:00
const parts = [path.call(print, "returnType")];
2016-12-31 14:38:58 -05:00
if (n.predicate) {
2016-12-30 23:10:22 -05:00
// The return type will already add the colon, but otherwise we
// need to do it ourselves
2017-01-09 12:09:04 -05:00
parts.push(n.returnType ? " " : ": ", path.call(print, "predicate"));
2016-12-30 13:32:43 -05:00
}
2016-12-30 23:10:22 -05:00
2016-12-30 13:32:43 -05:00
return concat(parts);
}
function typeIsFunction(type) {
return type === "FunctionExpression" ||
type === "ArrowFunctionExpression" ||
type === "NewExpression";
}
function printExportDeclaration(path, options, print) {
var decl = path.getValue();
2017-01-28 07:50:22 -08:00
var parts = ["export "];
2016-12-31 14:38:58 -05:00
namedTypes.Declaration.assert(decl);
2016-12-30 23:10:22 -05:00
if (decl["default"] || decl.type === "ExportDefaultDeclaration") {
parts.push("default ");
}
2016-12-30 23:10:22 -05:00
if (decl.declaration) {
parts.push(path.call(print, "declaration"));
2017-01-11 20:43:27 +08:00
2017-01-13 15:03:53 -05:00
if (
decl.type === "ExportDefaultDeclaration" &&
(decl.declaration.type !== "ClassDeclaration" &&
decl.declaration.type !== "FunctionDeclaration")
2017-01-13 15:03:53 -05:00
) {
2017-01-11 20:43:27 +08:00
parts.push(";");
}
2017-01-16 10:58:23 -06:00
} else {
if (decl.specifiers && decl.specifiers.length > 0) {
if (
decl.specifiers.length === 1 &&
2017-01-18 15:31:46 -08:00
decl.specifiers[0].type === "ExportBatchSpecifier"
2017-01-16 10:58:23 -06:00
) {
parts.push("*");
2017-01-20 19:20:31 -08:00
} else if (
decl.specifiers.length === 1 &&
decl.specifiers[0].type === "ExportDefaultSpecifier" ||
decl.specifiers[0].type === "ExportNamespaceSpecifier"
) {
parts.push(path.map(print, "specifiers")[0]);
2017-01-16 10:58:23 -06:00
} else {
parts.push(
decl.exportKind === "type" ? "type " : "",
2017-01-24 13:54:01 -05:00
group(
2017-01-16 10:58:23 -06:00
concat([
"{",
indent(
options.tabWidth,
concat([
options.bracketSpacing ? line : softline,
2017-01-28 07:50:22 -08:00
join(concat([",", line]), path.map(print, "specifiers"))
2017-01-16 10:58:23 -06:00
])
),
ifBreak(options.trailingComma ? "," : ""),
options.bracketSpacing ? line : softline,
"}"
])
)
);
}
2017-01-09 12:09:04 -05:00
} else {
2017-01-16 10:58:23 -06:00
parts.push("{}");
}
2016-12-30 23:10:22 -05:00
2017-01-09 12:09:04 -05:00
if (decl.source) {
parts.push(" from ", path.call(print, "source"));
}
2017-01-11 20:43:27 +08:00
2017-01-13 15:03:53 -05:00
parts.push(";");
2017-01-09 12:09:04 -05:00
}
return concat(parts);
}
function printFlowDeclaration(path, parts) {
var parentExportDecl = util.getParentExportDeclaration(path);
2016-12-31 14:38:58 -05:00
if (parentExportDecl) {
assert.strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
} else {
// If the parent node has type DeclareExportDeclaration, then it
// will be responsible for printing the "declare" token. Otherwise
// it needs to be printed with this non-exported declaration node.
parts.unshift("declare ");
}
2016-12-30 23:10:22 -05:00
return concat(parts);
}
function printClass(path, options, print) {
const n = path.getValue();
2017-01-28 07:50:22 -08:00
const parts = ["class"];
2016-12-31 14:38:58 -05:00
if (n.id) {
parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
}
2016-12-30 23:10:22 -05:00
const partsGroup = [];
if (n.superClass) {
partsGroup.push(
line,
"extends ",
2017-01-09 12:09:04 -05:00
path.call(print, "superClass"),
path.call(print, "superTypeParameters")
);
} else if (n.extends && n.extends.length > 0) {
partsGroup.push(line, "extends ", join(", ", path.map(print, "extends")));
2017-01-09 12:09:04 -05:00
}
2016-12-30 23:10:22 -05:00
if (n["implements"] && n["implements"].length > 0) {
2017-01-28 07:50:22 -08:00
partsGroup.push(
line,
"implements ",
join(", ", path.map(print, "implements"))
);
}
if (partsGroup.length > 0) {
parts.push(group(indent(options.tabWidth, concat(partsGroup))));
}
2016-12-30 23:10:22 -05:00
parts.push(" ", path.call(print, "body"));
2016-12-30 23:10:22 -05:00
return parts;
}
2017-01-26 11:58:47 -08:00
function printMemberLookup(path, options, print) {
const property = path.call(print, "property");
const n = path.getValue();
2017-01-26 11:58:47 -08:00
return concat(
n.computed
2017-01-28 07:50:22 -08:00
? [
"[",
group(
concat([
indent(options.tabWidth, concat([softline, property])),
softline
])
),
"]"
]
: [".", property]
);
}
// We detect calls on member expressions specially to format a
// comman pattern better. The pattern we are looking for is this:
//
// arr
// .map(x => x + 1)
// .filter(x => x > 10)
// .some(x => x % 2)
//
// The way it is structured in the AST is via a nested sequence of
// MemberExpression and CallExpression. We need to traverse the AST
// and make groups out of it to print it in the desired way.
function printMemberChain(path, options, print) {
// The first phase is to linearize the AST by traversing it down.
//
// a().b()
// has the following AST structure:
// CallExpression(MemberExpression(CallExpression(Identifier)))
// and we transform it into
// [Identifier, CallExpression, MemberExpression, CallExpression]
const printedNodes = [];
function rec(path) {
const node = path.getValue();
if (node.type === "CallExpression") {
printedNodes.unshift({
node: node,
printed: printArgumentsList(path, options, print)
});
path.call(callee => rec(callee), "callee");
} else if (node.type === "MemberExpression") {
printedNodes.unshift({
node: node,
2017-02-03 08:50:51 -08:00
printed: comments.printComments(
path,
p => printMemberLookup(path, options, print),
options
)
});
path.call(object => rec(object), "object");
2017-01-09 12:09:04 -05:00
} else {
printedNodes.unshift({
node: node,
printed: path.call(print)
});
}
}
rec(path);
// Once we have a linear list of printed nodes, we want to create groups out
// of it.
//
// a().b.c().d().e
// will be grouped as
// [
// [Identifier, CallExpression],
// [MemberExpression, MemberExpression, CallExpression],
// [MemberExpression, CallExpression],
// [MemberExpression],
// ]
// so that we can print it as
// a()
// .b.c()
// .d()
// .e
// The first group is the first node followed by
// - as many CallExpression as possible
// < fn()()() >.something()
// - then, as many MemberExpression as possible but the last one
// < this.items >.something()
var groups = [];
var currentGroup = [printedNodes[0]];
var i = 1;
for (; i < printedNodes.length; ++i) {
if (printedNodes[i].node.type === "CallExpression") {
currentGroup.push(printedNodes[i]);
} else {
break;
}
}
for (; i + 1 < printedNodes.length; ++i) {
if (printedNodes[i].node.type === "MemberExpression" &&
printedNodes[i + 1].node.type === "MemberExpression") {
currentGroup.push(printedNodes[i]);
} else {
break;
}
}
groups.push(currentGroup);
currentGroup = [];
// Then, each following group is a sequence of MemberExpression followed by
// a sequence of CallExpression. To compute it, we keep adding things to the
// group until we has seen a CallExpression in the past and reach a
// MemberExpression
var hasSeenCallExpression = false;
for (; i < printedNodes.length; ++i) {
2017-02-03 08:50:51 -08:00
if (
hasSeenCallExpression && printedNodes[i].node.type === "MemberExpression"
) {
groups.push(currentGroup);
currentGroup = [];
hasSeenCallExpression = false;
}
if (printedNodes[i].node.type === "CallExpression") {
hasSeenCallExpression = true;
}
currentGroup.push(printedNodes[i]);
}
if (currentGroup.length > 0) {
groups.push(currentGroup);
}
// There are cases like Object.keys(), Observable.of(), _.values() where
// they are the subject of all the chained calls and therefore should
// be kept on the same line:
//
// Object.keys(items)
// .filter(x => x)
// .map(x => x)
//
// In order to detect those cases, we use an heuristic: if the first
// node is just an identifier with the name starting with a capital
// letter or just a sequence of _$. The rationale is that they are
// likely to be factories.
2017-02-03 08:50:51 -08:00
if (
groups[0].length === 1 &&
groups[0][0].node.type === "Identifier" &&
groups[0][0].node.name.match(/(^[A-Z])|^[_$]+$/) &&
2017-02-03 08:50:51 -08:00
groups.length >= 2
) {
// Push all the values of groups[0] at the beginning of groups[1]
[].unshift.apply(groups[1], groups[0]);
// Remove groups[0]
groups.splice(0, 1);
}
function printGroup(printedGroup) {
return concat(printedGroup.map(tuple => tuple.printed));
}
const printedGroups = groups.map(printGroup);
const oneLine = concat(printedGroups);
// If we only have a single `.`, we shouldn't do anything fancy and just
// render everything concatenated together.
if (groups.length <= 2) {
return group(oneLine);
}
const expanded = concat([
printGroup(groups[0]),
indent(
options.tabWidth,
2017-02-03 08:50:51 -08:00
group(concat([hardline, join(hardline, groups.slice(1).map(printGroup))]))
)
]);
// If any group but the last one has a hard line, we want to force expand
// it. If the last group is a function it's okay to inline if it fits.
if (printedGroups.slice(0, -1).some(willBreak)) {
return group(expanded);
}
return conditionalGroup([oneLine, expanded]);
}
function isEmptyJSXElement(node) {
if (node.children.length === 0) return true;
if (node.children.length > 1) return false;
// if there is one child but it's just a newline, treat as empty
const value = node.children[0].value;
if (!/\S/.test(value) && /\n/.test(value)) {
return true;
} else {
return false;
}
}
// JSX Children are strange, mostly for two reasons:
// 1. JSX reads newlines into string values, instead of skipping them like JS
// 2. up to one whitespace between elements within a line is significant,
// but not between lines.
//
// So for one thing, '\n' needs to be parsed out of string literals
// and turned into hardlines (with string boundaries otherwise using softline)
//
// For another, leading, trailing, and lone whitespace all need to
// turn themselves into the rather ugly `{' '}` when breaking.
function printJSXChildren(path, options, print) {
const n = path.getValue();
const children = [];
const jsxWhitespace = options.singleQuote
? ifBreak("{' '}", " ")
2017-01-18 15:31:46 -08:00
: ifBreak('{" "}', " ");
// using `map` instead of `each` because it provides `i`
2017-01-18 15:31:46 -08:00
path.map(
function(childPath, i) {
const child = childPath.getValue();
const isLiteral = namedTypes.Literal.check(child);
2017-01-18 15:31:46 -08:00
if (isLiteral && typeof child.value === "string") {
2017-01-19 08:30:35 -08:00
// There's a bug in the flow parser where it doesn't unescape the
// value field. To workaround this, we can use rawValue which is
// correctly escaped (since it parsed).
// We really want to use value and re-escape it ourself when possible
// though.
2017-02-01 15:29:42 -08:00
const partiallyEscapedValue = options.parser === "flow"
2017-01-20 10:12:37 -08:00
? child.raw
: util.htmlEscapeInsideAngleBracket(child.value);
2017-02-03 08:50:51 -08:00
const value = partiallyEscapedValue.replace(/\u00a0/g, "&nbsp;");
2017-01-19 08:30:35 -08:00
if (/\S/.test(value)) {
// treat each line of text as its own entity
value.split(/(\n\s*)/).forEach(line => {
const newlines = line.match(/\n/g);
if (newlines) {
children.push(hardline);
// allow one extra newline
if (newlines.length > 1) {
2017-01-28 07:50:22 -08:00
children.push(hardline);
}
return;
}
2017-01-18 15:31:46 -08:00
const beginSpace = /^\s+/.test(line);
if (beginSpace) {
children.push(jsxWhitespace);
}
const stripped = line.replace(/^\s+|\s+$/g, "");
if (stripped) {
children.push(stripped);
}
const endSpace = /\s+$/.test(line);
if (endSpace) {
children.push(jsxWhitespace);
}
2017-01-18 15:31:46 -08:00
children.push(softline);
});
2017-01-19 08:30:35 -08:00
} else if (/\n/.test(value)) {
children.push(hardline);
// allow one extra newline
if (value.match(/\n/g).length > 1) {
2017-01-28 07:50:22 -08:00
children.push(hardline);
}
2017-01-19 08:30:35 -08:00
} else if (/\s/.test(value)) {
2017-01-18 15:31:46 -08:00
// whitespace-only without newlines,
// eg; a single space separating two elements
children.push(jsxWhitespace);
children.push(softline);
}
2017-01-18 15:31:46 -08:00
} else {
children.push(print(childPath));
2017-01-18 15:31:46 -08:00
// add a line unless it's followed by a JSX newline
let next = n.children[i + 1];
if (!(next && /^\s*\n/.test(next.value))) {
children.push(softline);
}
}
2017-01-18 15:31:46 -08:00
},
"children"
);
return children;
}
// JSX expands children from the inside-out, instead of the outside-in.
// This is both to break children before attributes,
// and to ensure that when children break, their parents do as well.
//
// Any element that is written without any newlines and fits on a single line
// is left that way.
// Not only that, any user-written-line containing multiple JSX siblings
// should also be kept on one line if possible,
// so each user-written-line is wrapped in its own group.
//
// Elements that contain newlines or don't fit on a single line (recursively)
// are fully-split, using hardline and shouldBreak: true.
//
// To support that case properly, all leading and trailing spaces
// are stripped from the list of children, and replaced with a single hardline.
function printJSXElement(path, options, print) {
const n = path.getValue();
// Turn <div></div> into <div />
if (isEmptyJSXElement(n)) {
n.openingElement.selfClosing = true;
delete n.closingElement;
}
// If no children, just print the opening element
const openingLines = path.call(print, "openingElement");
if (n.openingElement.selfClosing) {
assert.ok(!n.closingElement);
return openingLines;
}
const children = printJSXChildren(path, options, print);
let forcedBreak = false;
// Trim trailing lines, recording if there was a hardline
let numTrailingHard = 0;
while (children.length && isLineNext(util.getLast(children))) {
if (willBreak(util.getLast(children))) {
++numTrailingHard;
forcedBreak = true;
}
children.pop();
}
// allow one extra newline
if (numTrailingHard > 1) {
children.push(hardline);
}
// Trim leading lines, recording if there was a hardline
let numLeadingHard = 0;
while (children.length && isLineNext(children[0])) {
if (willBreak(children[0])) {
++numLeadingHard;
forcedBreak = true;
}
children.shift();
}
// allow one extra newline
if (numLeadingHard > 1) {
children.unshift(hardline);
}
// Group by line, recording if there was a hardline.
let childrenGroupedByLine;
if (children.length === 1) {
if (!forcedBreak && willBreak(children[0])) {
forcedBreak = true;
}
// Don't wrap a single child in a group as there is no need, and a
// lone JSX whitespace doesn't work otherwise because the group
// will be printed in flat mode, and we need to print `{' '}` in
// break mode.
2017-01-28 07:50:22 -08:00
childrenGroupedByLine = [concat([hardline, children[0]])];
} else {
// Prefill leading newline, and initialize the first line's group
let groups = [[]];
children.forEach((child, i) => {
let prev = children[i - 1];
if (prev && willBreak(prev)) {
forcedBreak = true;
// On a new line, so create a new group and put this element
// in it.
2017-01-28 07:50:22 -08:00
groups.push([child]);
} else {
// Not on a newline, so add this element to the current group.
util.getLast(groups).push(child);
}
// Ensure we record hardline of last element.
if (!forcedBreak && i === children.length - 1) {
if (willBreak(child)) forcedBreak = true;
}
});
childrenGroupedByLine = [
hardline,
// Conditional groups suppress break propagation; we want output
// hard lines without breaking up the entire jsx element.
concat(groups.map(contents => conditionalGroup([concat(contents)])))
];
}
const closingLines = path.call(print, "closingElement");
2017-01-18 15:31:46 -08:00
const multiLineElem = group(
concat([
openingLines,
indent(
options.tabWidth,
group(concat(childrenGroupedByLine), { shouldBreak: true })
),
hardline,
closingLines
])
);
if (forcedBreak) {
return multiLineElem;
}
return conditionalGroup([
2017-01-28 07:50:22 -08:00
group(concat([openingLines, concat(children), closingLines])),
multiLineElem
]);
}
function maybeWrapJSXElementInParens(path, elem, options) {
const parent = path.getParentNode();
if (!parent) return elem;
const NO_WRAP_PARENTS = {
2017-01-18 15:31:46 -08:00
JSXElement: true,
ExpressionStatement: true,
CallExpression: true,
2017-01-26 11:51:08 -08:00
ConditionalExpression: true,
2017-01-28 07:50:22 -08:00
LogicalExpression: true
};
if (NO_WRAP_PARENTS[parent.type]) {
return elem;
}
2017-01-24 13:54:01 -05:00
return group(
2017-01-13 15:03:53 -05:00
concat([
ifBreak("("),
2017-01-28 07:50:22 -08:00
indent(options.tabWidth, concat([softline, elem])),
2017-01-13 15:03:53 -05:00
softline,
ifBreak(")")
])
);
}
function isBinaryish(node) {
return node.type === "BinaryExpression" || node.type === "LogicalExpression";
}
// For binary expressions to be consistent, we need to group
// subsequent operators with the same precedence level under a single
// group. Otherwise they will be nested such that some of them break
// onto new lines but not all. Operators with the same precedence
// level should either all break or not. Because we group them by
// precedence level and the AST is structured based on precedence
// level, things are naturally broken up correctly, i.e. `&&` is
// broken before `+`.
function printBinaryishExpressions(path, parts, print, options, isNested) {
let node = path.getValue();
// We treat BinaryExpression and LogicalExpression nodes the same.
2017-01-18 15:31:46 -08:00
if (isBinaryish(node)) {
// Put all operators with the same precedence level in the same
// group. The reason we only need to do this with the `left`
// expression is because given an expression like `1 + 2 - 3`, it
// is always parsed like `((1 + 2) - 3)`, meaning the `left` side
// is where the rest of the expression will exist. Binary
// expressions on the right side mean they have a difference
// precedence level and should be treated as a separate group, so
// print them normally.
2017-01-18 15:31:46 -08:00
if (
util.getPrecedence(node.left.operator) ===
util.getPrecedence(node.operator)
) {
// Flatten them out by recursively calling this function. The
// printed values will all be appended to `parts`.
2017-01-28 07:50:22 -08:00
path.call(
left =>
printBinaryishExpressions(
left,
parts,
print,
options,
/* isNested */ true
),
"left"
);
2017-01-18 15:31:46 -08:00
} else {
parts.push(path.call(print, "left"));
}
2017-01-18 15:31:46 -08:00
parts.push(" ", node.operator, line, path.call(print, "right"));
// The root comments are already printed, but we need to manually print
// the other ones since we don't call the normal print on BinaryExpression,
// only for the left and right parts
if (isNested && node.comments) {
2017-01-28 07:50:22 -08:00
parts.push(comments.printComments(path, p => "", options));
}
2017-01-18 15:31:46 -08:00
} else {
// Our stopping case. Simply print the node normally.
parts.push(path.call(print));
}
return parts;
}
2017-01-05 12:10:14 -05:00
function adjustClause(clause, options, forceSpace) {
if (clause === "") {
return ";";
}
2017-01-05 12:10:14 -05:00
if (isCurlyBracket(clause) || forceSpace) {
2017-01-28 07:50:22 -08:00
return concat([" ", clause]);
}
2016-12-30 23:10:22 -05:00
2017-01-28 07:50:22 -08:00
return indent(options.tabWidth, concat([line, clause]));
}
2017-01-05 12:10:14 -05:00
function isCurlyBracket(doc) {
const str = getFirstString(doc);
return str === "{" || str === "{}";
}
function isEmptyBlock(doc) {
const str = getFirstString(doc);
return str === "{}";
}
function lastNonSpaceCharacter(lines) {
var pos = lines.lastPos();
do {
var ch = lines.charAt(pos);
2016-12-31 14:38:58 -05:00
2017-01-18 15:31:46 -08:00
if (/\S/.test(ch)) return ch;
} while (lines.prevPos(pos));
}
function nodeStr(node, options) {
const str = node.value;
isString.assert(str);
2016-12-30 23:10:22 -05:00
2017-01-20 14:47:52 -08:00
// Workaround a bug in the Javascript version of the flow parser where
// astral unicode characters like \uD801\uDC28 are incorrectly parsed as
// a sequence of \uFFFD.
2017-02-03 08:50:51 -08:00
if (options.parser === "flow" && str.indexOf("\ufffd") !== -1) {
2017-01-20 14:47:52 -08:00
return node.raw;
}
const raw = node.extra ? node.extra.raw : node.raw;
// `rawContent` is the string exactly like it appeared in the input source
// code, with its enclosing quote.
const rawContent = raw.slice(1, -1);
const double = { quote: '"', regex: /"/g };
const single = { quote: "'", regex: /'/g };
const preferred = options.singleQuote ? single : double;
const alternate = preferred === single ? double : single;
let shouldUseAlternateQuote = false;
// If `rawContent` contains at least one of the quote preferred for enclosing
// the string, we might want to enclose with the alternate quote instead, to
// minimize the number of escaped quotes.
if (rawContent.includes(preferred.quote)) {
const numPreferredQuotes = (rawContent.match(preferred.regex) || []).length;
const numAlternateQuotes = (rawContent.match(alternate.regex) || []).length;
shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes;
}
const enclosingQuote = shouldUseAlternateQuote
? alternate.quote
: preferred.quote;
2017-01-20 14:47:52 -08:00
// It might sound unnecessary to use `makeString` even if `node.raw` already
// is enclosed with `enclosingQuote`, but it isn't. `node.raw` could contain
// unnecessary escapes (such as in `"\'"`). Always using `makeString` makes
// sure that we consistently output the minimum amount of escaped quotes.
return makeString(rawContent, enclosingQuote);
}
2017-01-20 14:47:52 -08:00
function makeString(rawContent, enclosingQuote) {
const otherQuote = enclosingQuote === '"' ? "'" : '"';
// Matches _any_ escape and unescaped quotes (both single and double).
const regex = /\\([\s\S])|(['"])/g;
// Escape and unescape single and double quotes as needed to be able to
// enclose `rawContent` with `enclosingQuote`.
const newContent = rawContent.replace(regex, (match, escaped, quote) => {
// If we matched an escape, and the escaped character is a quote of the
// other type than we intend to enclose the string with, there's no need for
// it to be escaped, so return it _without_ the backslash.
if (escaped === otherQuote) {
return escaped;
}
// If we matched an unescaped quote and it is of the _same_ type as we
// intend to enclose the string with, it must be escaped, so return it with
// a backslash.
if (quote === enclosingQuote) {
return "\\" + quote;
}
// Otherwise return the escape or unescaped quote as-is.
return match;
});
return enclosingQuote + newContent + enclosingQuote;
}
2017-01-30 18:36:23 +01:00
function printNumber(rawNumber) {
2017-02-03 08:50:51 -08:00
return rawNumber
.toLowerCase()
2017-01-30 18:36:23 +01:00
// Remove unnecessary plus and zeroes from scientific notation.
.replace(/^([\d.]+e)(?:\+|(-))?0*/, "$1$2")
// Make sure numbers always start with a digit.
.replace(/^\./, "0.")
// Remove trailing dot.
.replace(/\.(?=e|$)/, "");
}
function isFirstStatement(path) {
const parent = path.getParentNode();
const node = path.getValue();
const body = parent.body;
2017-01-18 15:31:46 -08:00
return body && body[0] === node;
}
function isLastStatement(path) {
const parent = path.getParentNode();
const node = path.getValue();
const body = parent.body;
return body && body[body.length - 1] === node;
}
// Hack to differentiate between the following two which have the same ast
// type T = { method: () => void };
// type T = { method(): void };
function isObjectTypePropertyAFunction(node) {
return node.type === "ObjectTypeProperty" &&
node.value.type === "FunctionTypeAnnotation" &&
!node.static &&
util.locStart(node.key) !== util.locStart(node.value);
}
2017-01-24 20:20:24 +01:00
function shouldPrintSameLine(node) {
const type = node.type;
return namedTypes.Literal.check(node) ||
type === "ArrayExpression" ||
type === "ArrayPattern" ||
type === "ArrowFunctionExpression" ||
type === "AssignmentPattern" ||
type === "CallExpression" ||
type === "FunctionExpression" ||
type === "Identifier" ||
2017-02-03 01:25:34 +01:00
type === "JSXElement" ||
2017-01-24 20:20:24 +01:00
type === "Literal" ||
type === "MemberExpression" ||
type === "NewExpression" ||
type === "ObjectExpression" ||
type === "ObjectPattern" ||
type === "StringLiteral" ||
type === "ThisExpression" ||
type === "TypeCastExpression" ||
type === "UnaryExpression";
2017-01-24 20:20:24 +01:00
}
function printAstToDoc(ast, options) {
function printGenerically(path) {
return comments.printComments(
path,
p => genericPrint(p, options, printGenerically),
options
);
}
const doc = printGenerically(FastPath.from(ast));
docUtils.propagateBreaks(doc);
return doc;
}
2017-01-20 10:12:37 -08:00
module.exports = { printAstToDoc };