Run prettier on 0.13.0 (#497)

master
Christopher Chedeau 2017-01-28 07:50:22 -08:00 committed by GitHub
parent d548ef0790
commit c34013b1ee
12 changed files with 317 additions and 318 deletions

View File

@ -1,6 +1,7 @@
#!/usr/bin/env node
"use strict";
const fs = require("fs");
const getStdin = require("get-stdin");
const glob = require("glob");

View File

@ -1,4 +1,5 @@
"use strict";
const codeFrame = require("babel-code-frame");
const comments = require("./src/comments");
const version = require("./package.json").version;
@ -63,7 +64,7 @@ function formatWithShebang(text, opts) {
const shebang = text.slice(0, index + 1);
const programText = text.slice(index + 1);
const nextChar = text.charAt(index + 1);
const newLine = nextChar === "\n" ? "\n" : (nextChar === "\r" ? "\r\n" : "");
const newLine = nextChar === "\n" ? "\n" : nextChar === "\r" ? "\r\n" : "";
return shebang + newLine + format(programText, opts);
}

View File

@ -127,7 +127,6 @@ function decorateComment(node, comment, text) {
if (followingNode) {
comment.followingNode = followingNode;
}
}
function attach(comments, ast, text) {
@ -164,8 +163,7 @@ function attach(comments, ast, text) {
// TODO: If there are no nodes at all, we should still somehow
// print the comment.
}
} else if(util.hasNewline(text, locEnd(comment))) {
} else if (util.hasNewline(text, locEnd(comment))) {
// There is content before this comment on the same line, but
// none after it, so prefer a trailing comment. A trailing
// comment *always* attaches itself to the previous node, no
@ -174,8 +172,7 @@ function attach(comments, ast, text) {
if (lastNode) {
// Always a trailing comment
addTrailingComment(lastNode, comment);
}
else {
} else {
throw new Error("Preceding node not found");
}
} else {
@ -184,7 +181,7 @@ function attach(comments, ast, text) {
// node, use a tie-breaking algorithm to determine if it should
// be attached to the next or previous node. In the last case,
// simply attach the right node;
if(precedingNode && followingNode) {
if (precedingNode && followingNode) {
const tieCount = tiesToBreak.length;
if (tieCount > 0) {
var lastTie = tiesToBreak[tieCount - 1];
@ -193,9 +190,9 @@ function attach(comments, ast, text) {
}
}
tiesToBreak.push(comment);
} else if(precedingNode) {
} else if (precedingNode) {
addTrailingComment(precedingNode, comment);
} else if(followingNode) {
} else if (followingNode) {
addLeadingComment(followingNode, comment);
} else if (enclosingNode) {
addDanglingComment(enclosingNode, comment);
@ -284,7 +281,7 @@ function addTrailingComment(node, comment) {
function printComment(commentPath) {
const comment = commentPath.getValue();
switch(comment.type) {
switch (comment.type) {
case "CommentBlock":
case "Block":
return "/*" + comment.value + "*/";
@ -304,7 +301,7 @@ function printLeadingComment(commentPath, print, options) {
// Leading block comments should see if they need to stay on the
// same line or not.
if(isBlock) {
if (isBlock) {
return concat([
contents,
util.hasNewline(options.originalText, locEnd(comment)) ? hardline : " "
@ -319,12 +316,10 @@ function printTrailingComment(commentPath, print, options, parentNode) {
const contents = printComment(commentPath);
const isBlock = comment.type === "Block" || comment.type === "CommentBlock";
if(
util.hasNewline(
options.originalText,
locStart(comment),
{ backwards: true }
)
if (
util.hasNewline(options.originalText, locStart(comment), {
backwards: true
})
) {
// This allows comments at the end of nested structures:
// {
@ -337,19 +332,13 @@ function printTrailingComment(commentPath, print, options, parentNode) {
// trailing comment for `2`. We can simulate the above by checking
// if this a comment on its own line; normal trailing comments are
// always at the end of another expression.
return concat([
hardline,
contents
]);
return concat([hardline, contents]);
} else if (isBlock) {
// Trailing block comments never need a newline
return concat([" ", contents]);
}
return concat([
lineSuffix(" " + contents),
!isBlock ? breakParent : ""
])
return concat([lineSuffix(" " + contents), !isBlock ? breakParent : ""]);
}
function printDanglingComments(path, options, noIndent) {
@ -357,21 +346,24 @@ function printDanglingComments(path, options, noIndent) {
const parts = [];
const node = path.getValue();
if(!node || !node.comments) {
if (!node || !node.comments) {
return "";
}
path.each(commentPath => {
const comment = commentPath.getValue();
if(!comment.leading && !comment.trailing) {
if(util.hasNewline(text, locStart(comment), { backwards: true })) {
parts.push(hardline);
path.each(
commentPath => {
const comment = commentPath.getValue();
if (!comment.leading && !comment.trailing) {
if (util.hasNewline(text, locStart(comment), { backwards: true })) {
parts.push(hardline);
}
parts.push(printComment(commentPath));
}
parts.push(printComment(commentPath));
}
}, "comments");
},
"comments"
);
if(!noIndent) {
if (!noIndent) {
return indent(options.tabWidth, concat(parts));
}
return concat(parts);
@ -388,7 +380,7 @@ function printComments(path, print, options) {
}
var leadingParts = [];
var trailingParts = [ printed ];
var trailingParts = [printed];
path.each(
function(commentPath) {
@ -400,17 +392,14 @@ function printComments(path, print, options) {
leadingParts.push(printLeadingComment(commentPath, print, options));
const text = options.originalText;
if (util.hasNewline(text, util.skipNewline(text, util.locEnd(comment)))) {
if (
util.hasNewline(text, util.skipNewline(text, util.locEnd(comment)))
) {
leadingParts.push(hardline);
}
} else if (trailing) {
trailingParts.push(
printTrailingComment(
commentPath,
print,
options,
parent
)
printTrailingComment(commentPath, print, options, parent)
);
}
},
@ -420,8 +409,4 @@ function printComments(path, print, options) {
return concat(leadingParts.concat(trailingParts));
}
module.exports = {
attach,
printComments,
printDanglingComments
};
module.exports = { attach, printComments, printDanglingComments };

View File

@ -2,11 +2,11 @@
const deprecated = {
useFlowParser: config =>
` The ${"\"useFlowParser\""} option is deprecated. Use ${"\"parser\""} instead.
` The ${'"useFlowParser"'} option is deprecated. Use ${'"parser"'} instead.
Prettier now treats your configuration as:
{
${"\"parser\""}: ${config.useFlowParser ? "\"flow\"" : "\"babylon\""}
${'"parser"'}: ${config.useFlowParser ? '"flow"' : '"babylon"'}
}`
};

View File

@ -1,10 +1,15 @@
"use strict";
const utils = require("./doc-utils");
const willBreak = utils.willBreak;
function assertDoc(val) {
if (!(typeof val === "string" || val != null && typeof val.type === "string")) {
throw new Error("Value " + JSON.stringify(val) + " is not a valid document");
if (
!(typeof val === "string" || val != null && typeof val.type === "string")
) {
throw new Error(
"Value " + JSON.stringify(val) + " is not a valid document"
);
}
}
@ -58,19 +63,22 @@ function ifBreak(breakContents, flatContents) {
}
function lineSuffix(contents) {
if(typeof contents !== "string") {
if (typeof contents !== "string") {
throw new Error(
"lineSuffix only takes a string, but given: " + JSON.stringify(contents)
)
);
}
return { type: "line-suffix", contents };
}
const breakParent = { type: "break-parent" };
const breakParent = { type: "break-parent" };
const line = { type: "line" };
const softline = { type: "line", soft: true };
const hardline = concat([{ type: "line", hard: true }, breakParent ]);
const literalline = concat([{ type: "line", hard: true, literal: true }, breakParent ]);
const hardline = concat([{ type: "line", hard: true }, breakParent]);
const literalline = concat([
{ type: "line", hard: true, literal: true },
breakParent
]);
function join(sep, arr) {
var res = [];

View File

@ -1,4 +1,5 @@
"use strict";
function flattenDoc(doc) {
if (doc.type === "concat") {
var res = [];
@ -16,21 +17,24 @@ function flattenDoc(doc) {
}
return Object.assign({}, doc, { parts: res });
} else if (doc.type === "if-break") {
return Object.assign({}, doc, {
breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null,
flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null
breakContents: (
doc.breakContents != null ? flattenDoc(doc.breakContents) : null
),
flatContents: (
doc.flatContents != null ? flattenDoc(doc.flatContents) : null
)
});
} else if (doc.type === "group") {
return Object.assign({}, doc, {
contents: flattenDoc(doc.contents),
expandedStates: doc.expandedStates
? doc.expandedStates.map(flattenDoc)
: doc.expandedStates
expandedStates: (
doc.expandedStates
? doc.expandedStates.map(flattenDoc)
: doc.expandedStates
)
});
} else if (doc.contents) {
return Object.assign({}, doc, { contents: flattenDoc(doc.contents) });
} else {
@ -76,9 +80,11 @@ function printDoc(doc) {
}
if (doc.type === "group") {
if(doc.expandedStates) {
if (doc.expandedStates) {
return "conditionalGroup(" +
"[" + doc.expandedStates.map(printDoc).join(",") + "])";
"[" +
doc.expandedStates.map(printDoc).join(",") +
"])";
}
return (doc.break ? "wrappedGroup" : "group") +

View File

@ -1,10 +1,11 @@
"use strict";
const MODE_BREAK = 1;
const MODE_FLAT = 2;
function fits(next, restCommands, width) {
let restIdx = restCommands.length;
const cmds = [ next ];
const cmds = [next];
while (width >= 0) {
if (cmds.length === 0) {
if (restIdx === 0) {
@ -29,27 +30,27 @@ function fits(next, restCommands, width) {
switch (doc.type) {
case "concat":
for (var i = doc.parts.length - 1; i >= 0; i--) {
cmds.push([ ind, mode, doc.parts[i] ]);
cmds.push([ind, mode, doc.parts[i]]);
}
break;
case "indent":
cmds.push([ ind + doc.n, mode, doc.contents ]);
cmds.push([ind + doc.n, mode, doc.contents]);
break;
case "group":
cmds.push([ ind, doc.break ? MODE_BREAK : mode, doc.contents ]);
cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]);
break;
case "if-break":
if (mode === MODE_BREAK) {
if (doc.breakContents) {
cmds.push([ ind, mode, doc.breakContents ]);
cmds.push([ind, mode, doc.breakContents]);
}
}
if (mode === MODE_FLAT) {
if (doc.flatContents) {
cmds.push([ ind, mode, doc.flatContents ]);
cmds.push([ind, mode, doc.flatContents]);
}
}
@ -83,7 +84,7 @@ function printDocToString(doc, width, newLine) {
// cmds is basically a stack. We've turned a recursive call into a
// while loop which is much faster. The while loop below adds new
// cmds to the array instead of recursively calling `print`.
let cmds = [ [ 0, MODE_BREAK, doc ] ];
let cmds = [[0, MODE_BREAK, doc]];
let out = [];
let shouldRemeasure = false;
let lineSuffix = "";
@ -102,12 +103,12 @@ function printDocToString(doc, width, newLine) {
switch (doc.type) {
case "concat":
for (var i = doc.parts.length - 1; i >= 0; i--) {
cmds.push([ ind, mode, doc.parts[i] ]);
cmds.push([ind, mode, doc.parts[i]]);
}
break;
case "indent":
cmds.push([ ind + doc.n, mode, doc.contents ]);
cmds.push([ind + doc.n, mode, doc.contents]);
break;
case "group":
@ -127,7 +128,7 @@ function printDocToString(doc, width, newLine) {
case MODE_BREAK:
shouldRemeasure = false;
const next = [ ind, MODE_FLAT, doc.contents ];
const next = [ind, MODE_FLAT, doc.contents];
let rem = width - pos;
if (!doc.break && fits(next, cmds, rem)) {
@ -141,22 +142,23 @@ function printDocToString(doc, width, newLine) {
// group has these, we need to manually go through
// these states and find the first one that fits.
if (doc.expandedStates) {
const mostExpanded = doc.expandedStates[doc.expandedStates.length -
1];
const mostExpanded = doc.expandedStates[
doc.expandedStates.length - 1
];
if (doc.break) {
cmds.push([ ind, MODE_BREAK, mostExpanded ]);
cmds.push([ind, MODE_BREAK, mostExpanded]);
break;
} else {
for (var i = 1; i < doc.expandedStates.length + 1; i++) {
if (i >= doc.expandedStates.length) {
cmds.push([ ind, MODE_BREAK, mostExpanded ]);
cmds.push([ind, MODE_BREAK, mostExpanded]);
break;
} else {
const state = doc.expandedStates[i];
const cmd = [ ind, MODE_FLAT, state ];
const cmd = [ind, MODE_FLAT, state];
if (fits(cmd, cmds, rem)) {
cmds.push(cmd);
@ -167,7 +169,7 @@ function printDocToString(doc, width, newLine) {
}
}
} else {
cmds.push([ ind, MODE_BREAK, doc.contents ]);
cmds.push([ind, MODE_BREAK, doc.contents]);
}
}
@ -177,12 +179,12 @@ function printDocToString(doc, width, newLine) {
case "if-break":
if (mode === MODE_BREAK) {
if (doc.breakContents) {
cmds.push([ ind, mode, doc.breakContents ]);
cmds.push([ind, mode, doc.breakContents]);
}
}
if (mode === MODE_FLAT) {
if (doc.flatContents) {
cmds.push([ ind, mode, doc.flatContents ]);
cmds.push([ind, mode, doc.flatContents]);
}
}

View File

@ -45,47 +45,58 @@ function findInDoc(doc, fn, defaultValue) {
return result;
}
function isEmpty(n) {
return typeof n === "string" && n.length === 0;
}
function getFirstString(doc) {
return findInDoc(doc, doc => {
if (typeof doc === "string" && doc.trim().length !== 0) {
return doc;
}
}, null);
return findInDoc(
doc,
doc => {
if (typeof doc === "string" && doc.trim().length !== 0) {
return doc;
}
},
null
);
}
function isLineNext(doc) {
return findInDoc(doc, doc => {
if (typeof doc === "string") {
return false;
}
if (doc.type === "line") {
return true;
}
}, false);
return findInDoc(
doc,
doc => {
if (typeof doc === "string") {
return false;
}
if (doc.type === "line") {
return true;
}
},
false
);
}
function willBreak(doc) {
return findInDoc(doc, doc => {
if (doc.type === "group" && doc.break) {
return true;
}
if (doc.type === "line" && doc.hard) {
return true;
}
}, false);
return findInDoc(
doc,
doc => {
if (doc.type === "group" && doc.break) {
return true;
}
if (doc.type === "line" && doc.hard) {
return true;
}
},
false
);
}
function breakParentGroup(groupStack) {
if(groupStack.length > 0) {
if (groupStack.length > 0) {
const parentGroup = groupStack[groupStack.length - 1];
// Breaks are not propagated through conditional groups because
// the user is expected to manually handle what breaks.
if(!parentGroup.expandedStates) {
if (!parentGroup.expandedStates) {
parentGroup.break = true;
}
}

View File

@ -8,7 +8,7 @@ var isNumber = types.builtInTypes.number;
function FastPath(value) {
assert.ok(this instanceof FastPath);
this.stack = [ value ];
this.stack = [value];
}
var FPp = FastPath.prototype;
@ -24,8 +24,9 @@ FastPath.from = function(obj) {
// For backwards compatibility, unroll NodePath instances into
// lightweight FastPath [..., name, value] stacks.
var copy = Object.create(FastPath.prototype);
var stack = [ obj.value ];
for (var pp; pp = obj.parentPath; obj = pp) stack.push(obj.name, pp.value);
var stack = [obj.value];
for (var pp; pp = obj.parentPath; obj = pp)
stack.push(obj.name, pp.value);
copy.stack = stack.reverse();
return copy;
}
@ -83,7 +84,7 @@ FPp.getParentNode = function getParentNode(count) {
FPp.isLast = function isLast() {
var s = this.stack;
if(this.getParentNode()) {
if (this.getParentNode()) {
var idx = s[s.length - 2];
// The name of this node should be an index
assert.ok(typeof idx === "number");
@ -95,7 +96,7 @@ FPp.isLast = function isLast() {
return idx === arr.length - 1;
}
return false;
}
};
// Temporarily push properties named by string arguments given after the
// callback function onto this.stack, then call the callback with a
@ -292,10 +293,7 @@ FPp.needsParens = function(assumeExpressionContext) {
return true;
}
if (
node.operator === 'in' &&
parent.type === 'AssignmentExpression'
) {
if (node.operator === "in" && parent.type === "AssignmentExpression") {
return true;
}

View File

@ -1,4 +1,5 @@
"use strict";
function parseWithFlow(text) {
// Inline the require to avoid loading all the JS if we don't use it
const flowParser = require("flow-parser");

View File

@ -1,4 +1,5 @@
"use strict";
var assert = require("assert");
var comments = require("./comments");
var FastPath = require("./fast-path");
@ -29,7 +30,7 @@ var isString = types.builtInTypes.string;
var isObject = types.builtInTypes.object;
function maybeAddParens(path, lines) {
return path.needsParens() ? concat([ "(", lines, ")" ]) : lines;
return path.needsParens() ? concat(["(", lines, ")"]) : lines;
}
function genericPrint(path, options, printPath) {
@ -53,7 +54,8 @@ function genericPrint(path, options, printPath) {
) {
const separator = node.decorators.length === 1 &&
node.decorators[0].expression.type === "Identifier"
? " " : hardline;
? " "
: hardline;
path.each(
function(decoratorPath) {
parts.push(printPath(decoratorPath), separator);
@ -118,7 +120,12 @@ function genericPrintNoParens(path, options, print) {
path.each(
function(childPath) {
parts.push(print(childPath), ";", hardline);
if (util.hasNewline(options.originalText, util.locEnd(childPath.getValue()))) {
if (
util.hasNewline(
options.originalText,
util.locEnd(childPath.getValue())
)
) {
parts.push(hardline);
}
},
@ -135,7 +142,6 @@ function genericPrintNoParens(path, options, print) {
)
);
parts.push(
comments.printDanglingComments(path, options, /* noIdent */ true)
);
@ -147,10 +153,9 @@ function genericPrintNoParens(path, options, print) {
case "EmptyStatement":
return "";
case "ExpressionStatement":
return concat([ path.call(print, "expression"), ";" ]);
case // Babel extension.
"ParenthesizedExpression":
return concat([ "(", path.call(print, "expression"), ")" ]);
return concat([path.call(print, "expression"), ";"]); // Babel extension.
case "ParenthesizedExpression":
return concat(["(", path.call(print, "expression"), ")"]);
case "AssignmentExpression":
return group(
concat([
@ -166,15 +171,13 @@ function genericPrintNoParens(path, options, print) {
const parts = [];
printBinaryishExpressions(path, parts, print, options);
return group(
concat([
return group(concat([
// 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)))
])
);
]));
}
case "AssignmentPattern":
return concat([
@ -277,7 +280,7 @@ function genericPrintNoParens(path, options, print) {
parts.push(" =>");
const body = path.call(print, "body");
const collapsed = concat([ concat(parts), " ", body ]);
const collapsed = concat([concat(parts), " ", body]);
// We want to always keep these types of nodes on the same line
// as the arrow.
@ -300,7 +303,7 @@ function genericPrintNoParens(path, options, print) {
collapsed,
concat([
concat(parts),
indent(options.tabWidth, concat([ line, body ]))
indent(options.tabWidth, concat([line, body]))
])
]),
{ shouldBreak: willBreak(body) }
@ -406,7 +409,7 @@ function genericPrintNoParens(path, options, print) {
return concat(parts);
case "ExportNamespaceSpecifier":
return concat([ "* as ", path.call(print, "exported") ]);
return concat(["* as ", path.call(print, "exported")]);
case "ExportDefaultSpecifier":
return path.call(print, "exported");
case "ImportDeclaration":
@ -452,7 +455,7 @@ function genericPrintNoParens(path, options, print) {
options.tabWidth,
concat([
options.bracketSpacing ? line : softline,
join(concat([ ",", line ]), grouped)
join(concat([",", line]), grouped)
])
),
ifBreak(options.trailingComma ? "," : ""),
@ -485,10 +488,14 @@ function genericPrintNoParens(path, options, print) {
const hasDirectives = n.directives && n.directives.length > 0;
var parent = path.getParentNode();
if (!hasContent && !hasDirectives && !n.comments &&
if (
!hasContent &&
!hasDirectives &&
!n.comments &&
(parent.type === "ArrowFunctionExpression" ||
parent.type === "FunctionExpression" ||
parent.type === "FunctionDeclaration")) {
parent.type === "FunctionDeclaration")
) {
return "{}";
}
@ -501,7 +508,7 @@ function genericPrintNoParens(path, options, print) {
parts.push(
indent(
options.tabWidth,
concat([ hardline, print(childPath), ";" ])
concat([hardline, print(childPath), ";"])
)
);
},
@ -510,7 +517,7 @@ function genericPrintNoParens(path, options, print) {
}
if (hasContent) {
parts.push(indent(options.tabWidth, concat([ hardline, naked ])));
parts.push(indent(options.tabWidth, concat([hardline, naked])));
}
parts.push(comments.printDanglingComments(path, options));
@ -589,7 +596,7 @@ function genericPrintNoParens(path, options, print) {
options.tabWidth,
concat([
options.bracketSpacing ? line : softline,
join(concat([ separator, line ]), props)
join(concat([separator, line]), props)
])
),
ifBreak(options.trailingComma ? "," : ""),
@ -607,9 +614,8 @@ function genericPrintNoParens(path, options, print) {
path.call(print, "pattern")
]);
// Babel 6
case "ObjectProperty":
case // Non-standard AST node type.
"Property":
case "ObjectProperty": // Non-standard AST node type.
case "Property":
if (n.method || n.kind === "get" || n.kind === "set") {
return printMethod(path, options, print);
}
@ -643,29 +649,25 @@ function genericPrintNoParens(path, options, print) {
}
}
return concat(parts);
case // Babel 6
"ClassMethod":
return concat(parts); // Babel 6
case "ClassMethod":
if (n.static) {
parts.push("static ");
}
parts = parts.concat(printObjectMethod(path, options, print));
return concat(parts);
case // Babel 6
"ObjectMethod":
return concat(parts); // Babel 6
case "ObjectMethod":
return printObjectMethod(path, options, print);
case "Decorator":
return concat([ "@", path.call(print, "expression") ]);
return concat(["@", path.call(print, "expression")]);
case "ArrayExpression":
case "ArrayPattern":
if (n.elements.length === 0) {
parts.push(concat([
"[",
comments.printDanglingComments(path, options),
"]"
]));
parts.push(
concat(["[", comments.printDanglingComments(path, options), "]"])
);
} else {
const lastElem = util.getLast(n.elements);
const canHaveTrailingComma = !(lastElem &&
@ -692,7 +694,7 @@ function genericPrintNoParens(path, options, print) {
options.tabWidth,
concat([
softline,
join(concat([ ",", line ]), path.map(print, "elements"))
join(concat([",", line]), path.map(print, "elements"))
])
),
needsForcedTrailingComma ? "," : "",
@ -718,12 +720,10 @@ function genericPrintNoParens(path, options, print) {
case "ThisExpression":
return "this";
case "Super":
return "super";
case // Babel 6 Literal split
"NullLiteral":
return "null";
case // Babel 6 Literal split
"RegExpLiteral":
return "super"; // Babel 6 Literal split
case "NullLiteral":
return "null"; // Babel 6 Literal split
case "RegExpLiteral":
return n.extra.raw;
// Babel 6 Literal split
case "NumericLiteral":
@ -736,12 +736,10 @@ function genericPrintNoParens(path, options, print) {
if (typeof n.value === "number") return n.raw;
if (typeof n.value !== "string") return "" + n.value;
return nodeStr(n, options);
case // Babel 6
"Directive":
return path.call(print, "value");
case // Babel 6
"DirectiveLiteral":
return nodeStr(n, options); // Babel 6
case "Directive":
return path.call(print, "value"); // Babel 6
case "DirectiveLiteral":
return nodeStr(n, options);
case "ModuleSpecifier":
if (n.local) {
@ -806,7 +804,7 @@ function genericPrintNoParens(path, options, print) {
printed[0],
indent(
options.tabWidth,
concat(printed.slice(1).map(p => concat([ ",", line, p ])))
concat(printed.slice(1).map(p => concat([",", line, p])))
)
];
@ -816,8 +814,8 @@ function genericPrintNoParens(path, options, print) {
var isParentForLoop = namedTypes.ForStatement.check(parentNode) ||
namedTypes.ForInStatement.check(parentNode) ||
(namedTypes.ForOfStatement &&
namedTypes.ForOfStatement.check(parentNode)) ||
namedTypes.ForOfStatement &&
namedTypes.ForOfStatement.check(parentNode) ||
namedTypes.ForAwaitStatement &&
namedTypes.ForAwaitStatement.check(parentNode);
@ -828,7 +826,7 @@ function genericPrintNoParens(path, options, print) {
return group(concat(parts));
case "VariableDeclarator":
return n.init
? concat([ path.call(print, "id"), " = ", path.call(print, "init") ])
? concat([path.call(print, "id"), " = ", path.call(print, "init")])
: path.call(print, "id");
case "WithStatement":
return concat([
@ -846,7 +844,7 @@ function genericPrintNoParens(path, options, print) {
concat([
indent(
options.tabWidth,
concat([ softline, path.call(print, "test") ])
concat([softline, path.call(print, "test")])
),
softline
])
@ -865,7 +863,7 @@ function genericPrintNoParens(path, options, print) {
// We use `conditionalGroup` to suppress break propagation.
// This allows us to provide a hardline without forcing the
// entire `if` clause to break up.
parts.push(conditionalGroup([concat([ hardline, "else" ])]));
parts.push(conditionalGroup([concat([hardline, "else"])]));
}
parts.push(
@ -882,7 +880,7 @@ function genericPrintNoParens(path, options, print) {
const body = adjustClause(path.call(print, "body"), options);
if (!n.init && !n.test && !n.update) {
return concat([ "for (;;)", body ]);
return concat(["for (;;)", body]);
}
return concat([
@ -916,7 +914,7 @@ function genericPrintNoParens(path, options, print) {
concat([
indent(
options.tabWidth,
concat([ softline, path.call(print, "test") ])
concat([softline, path.call(print, "test")])
),
softline
])
@ -954,12 +952,12 @@ function genericPrintNoParens(path, options, print) {
]);
case "DoWhileStatement":
var clause = adjustClause(path.call(print, "body"), options);
var doBody = concat([ "do", clause ]);
var parts = [ doBody ];
var doBody = concat(["do", clause]);
var parts = [doBody];
const hasBraces = isCurlyBracket(clause);
if (hasBraces) parts.push(" while");
else parts.push(concat([ line, "while" ]));
else parts.push(concat([line, "while"]));
parts.push(" (", path.call(print, "test"), ");");
@ -971,7 +969,7 @@ function genericPrintNoParens(path, options, print) {
},
"body"
);
return concat([ "do {\n", statements.indent(options.tabWidth), "\n}" ]);
return concat(["do {\n", statements.indent(options.tabWidth), "\n}"]);
case "BreakStatement":
parts.push("break");
@ -990,7 +988,7 @@ function genericPrintNoParens(path, options, print) {
return concat(parts);
case "LabeledStatement":
if (n.body.type === "EmptyStatement") {
return concat([ path.call(print, "label"), ":;" ]);
return concat([path.call(print, "label"), ":;"]);
}
return concat([
@ -1029,7 +1027,7 @@ function genericPrintNoParens(path, options, print) {
return concat(parts);
case "ThrowStatement":
return concat([ "throw ", path.call(print, "argument"), ";" ]);
return concat(["throw ", path.call(print, "argument"), ";"]);
// Note: ignoring n.lexical because it has no printing consequences.
case "SwitchStatement":
return concat([
@ -1038,9 +1036,9 @@ function genericPrintNoParens(path, options, print) {
") {",
n.cases.length > 0
? indent(
options.tabWidth,
concat([ hardline, join(hardline, path.map(print, "cases")) ])
)
options.tabWidth,
concat([hardline, join(hardline, path.map(print, "cases"))])
)
: "",
hardline,
"}"
@ -1059,8 +1057,8 @@ function genericPrintNoParens(path, options, print) {
parts.push(
isCurlyBracket(cons)
? concat([ " ", cons ])
: indent(options.tabWidth, concat([ hardline, cons ]))
? concat([" ", cons])
: indent(options.tabWidth, concat([hardline, cons]))
);
}
@ -1098,7 +1096,7 @@ function genericPrintNoParens(path, options, print) {
path.call(print, "property")
]);
case "JSXSpreadAttribute":
return concat([ "{...", path.call(print, "argument"), "}" ]);
return concat(["{...", path.call(print, "argument"), "}"]);
case "JSXExpressionContainer": {
const parent = path.getParentNode(0);
@ -1107,13 +1105,12 @@ function genericPrintNoParens(path, options, print) {
n.expression.type === "ArrowFunctionExpression" ||
n.expression.type === "CallExpression" ||
n.expression.type === "FunctionExpression" ||
parent.type === "JSXElement" && (
n.expression.type === "ConditionalExpression" ||
n.expression.type === "LogicalExpression"
);
parent.type === "JSXElement" &&
(n.expression.type === "ConditionalExpression" ||
n.expression.type === "LogicalExpression");
if (shouldInline) {
return concat([ "{", path.call(print, "expression"), "}" ]);
return concat(["{", path.call(print, "expression"), "}"]);
}
return group(
@ -1121,7 +1118,7 @@ function genericPrintNoParens(path, options, print) {
"{",
indent(
options.tabWidth,
concat([ softline, path.call(print, "expression") ])
concat([softline, path.call(print, "expression")])
),
softline,
"}"
@ -1136,18 +1133,21 @@ function genericPrintNoParens(path, options, print) {
const n = path.getValue();
// don't break up opening elements with a single long text attribute
if (n.attributes.length === 1 &&
if (
n.attributes.length === 1 &&
n.attributes[0].value &&
n.attributes[0].value.type === "Literal" &&
typeof n.attributes[0].value.value === "string"
) {
return group(concat([
"<",
path.call(print, "name"),
" ",
concat(path.map(print, "attributes")),
n.selfClosing ? " />" : ">"
]));
return group(
concat([
"<",
path.call(print, "name"),
" ",
concat(path.map(print, "attributes")),
n.selfClosing ? " />" : ">"
])
);
}
return group(
@ -1158,7 +1158,7 @@ function genericPrintNoParens(path, options, print) {
indent(
options.tabWidth,
concat(
path.map(attr => concat([ line, print(attr) ]), "attributes")
path.map(attr => concat([line, print(attr)]), "attributes")
)
),
n.selfClosing ? line : softline
@ -1168,7 +1168,7 @@ function genericPrintNoParens(path, options, print) {
);
}
case "JSXClosingElement":
return concat([ "</", path.call(print, "name"), ">" ]);
return concat(["</", path.call(print, "name"), ">"]);
case "JSXText":
throw new Error("JSXTest should be handled by JSXElement");
case "JSXEmptyExpression":
@ -1184,11 +1184,7 @@ function genericPrintNoParens(path, options, print) {
return "{}";
}
return concat([
"{",
indent(
options.tabWidth,
concat([
return concat(["{", indent(options.tabWidth, concat([
hardline,
path.call(
function(bodyPath) {
@ -1196,11 +1192,7 @@ function genericPrintNoParens(path, options, print) {
},
"body"
)
])
),
hardline,
"}"
]);
])), hardline, "}"]);
case "ClassPropertyDefinition":
parts.push("static ", path.call(print, "definition"));
@ -1213,13 +1205,13 @@ function genericPrintNoParens(path, options, print) {
var key;
if (n.computed) {
key = concat([ "[", path.call(print, "key"), "]" ]);
key = concat(["[", path.call(print, "key"), "]"]);
} else {
key = printPropertyKey(path, options, print);
if (n.variance === "plus") {
key = concat([ "+", key ]);
key = concat(["+", key]);
} else if (n.variance === "minus") {
key = concat([ "-", key ]);
key = concat(["-", key]);
}
}
@ -1261,7 +1253,7 @@ function genericPrintNoParens(path, options, print) {
// These types are unprintable because they serve as abstract
// supertypes for other (printable) types.
case "TaggedTemplateExpression":
return concat([ path.call(print, "tag"), path.call(print, "quasi") ]);
return concat([path.call(print, "tag"), path.call(print, "quasi")]);
case "Node":
case "Printable":
case "SourceLocation":
@ -1276,9 +1268,8 @@ function genericPrintNoParens(path, options, print) {
// Supertype of Block and Line.
case "Comment":
// Flow
case "MemberTypeAnnotation":
case // Flow
"Type":
case "MemberTypeAnnotation": // Flow
case "Type":
throw new Error("unprintable type: " + JSON.stringify(n.type));
// Type Annotations for Facebook Flow, typically stripped out or
@ -1296,7 +1287,7 @@ function genericPrintNoParens(path, options, print) {
return "";
case "TupleTypeAnnotation":
return concat([ "[", join(", ", path.map(print, "types")), "]" ]);
return concat(["[", join(", ", path.map(print, "types")), "]"]);
case "ExistentialTypeParam":
case "ExistsTypeAnnotation":
return "*";
@ -1307,7 +1298,7 @@ function genericPrintNoParens(path, options, print) {
case "MixedTypeAnnotation":
return "mixed";
case "ArrayTypeAnnotation":
return concat([ path.call(print, "elementType"), "[]" ]);
return concat([path.call(print, "elementType"), "[]"]);
case "BooleanTypeAnnotation":
return "boolean";
case "NumericLiteralTypeAnnotation":
@ -1337,18 +1328,11 @@ function genericPrintNoParens(path, options, print) {
";"
]);
case "DeclareVariable":
return printFlowDeclaration(path, [
"var ",
path.call(print, "id"),
";"
]);
return printFlowDeclaration(path, ["var ", path.call(print, "id"), ";"]);
case "DeclareExportAllDeclaration":
return concat([ "declare export * from ", path.call(print, "source") ]);
return concat(["declare export * from ", path.call(print, "source")]);
case "DeclareExportDeclaration":
return concat([
"declare ",
printExportDeclaration(path, options, print)
]);
return concat(["declare ", printExportDeclaration(path, options, print)]);
case "FunctionTypeAnnotation":
// FunctionTypeAnnotation is ambiguous:
// declare function foo(a: B): void; OR
@ -1444,7 +1428,7 @@ function genericPrintNoParens(path, options, print) {
);
}
case "NullableTypeAnnotation":
return concat([ "?", path.call(print, "typeAnnotation") ]);
return concat(["?", path.call(print, "typeAnnotation")]);
case "NullLiteralTypeAnnotation":
return "null";
case "ThisTypeAnnotation":
@ -1530,7 +1514,7 @@ function genericPrintNoParens(path, options, print) {
]);
case "TypeParameterDeclaration":
case "TypeParameterInstantiation":
return concat([ "<", join(", ", path.map(print, "params")), ">" ]);
return concat(["<", join(", ", path.map(print, "params")), ">"]);
case "TypeParameter":
switch (n.variance) {
case "plus":
@ -1556,7 +1540,7 @@ function genericPrintNoParens(path, options, print) {
return concat(parts);
case "TypeofTypeAnnotation":
return concat([ "typeof ", path.call(print, "argument") ]);
return concat(["typeof ", path.call(print, "argument")]);
case "VoidTypeAnnotation":
return "void";
case "NullTypeAnnotation":
@ -1567,7 +1551,7 @@ function genericPrintNoParens(path, options, print) {
// be either left alone or desugared into AST types that are fully
// supported by the pretty-printer.
case "DeclaredPredicate":
return concat([ "%checks(", path.call(print, "value"), ")" ]);
return concat(["%checks(", path.call(print, "value"), ")"]);
// TODO
case "ClassHeritage":
// TODO
@ -1697,14 +1681,10 @@ function printMethod(path, options, print) {
var key = printPropertyKey(path, options, print);
if (node.computed) {
key = concat([ "[", key, "]" ]);
key = concat(["[", key, "]"]);
}
parts.push(
key,
path.call(print, "value", "typeParameters"),
group(
concat([
parts.push(key, path.call(print, "value", "typeParameters"), group(concat([
path.call(
function(valuePath) {
return printFunctionParams(valuePath, print, options);
@ -1712,11 +1692,7 @@ function printMethod(path, options, print) {
"value"
),
path.call(p => printReturnType(p, print), "value")
])
),
" ",
path.call(print, "value", "body")
);
])), " ", path.call(print, "value", "body"));
return concat(parts);
}
@ -1749,10 +1725,10 @@ function printArgumentsList(path, options, print) {
const shouldBreak = printed.slice(0, -1).some(willBreak);
return conditionalGroup(
[
concat([ "(", join(concat([ ", " ]), printed), ")" ]),
concat(["(", join(concat([", "]), printed), ")"]),
concat([
"(",
join(concat([ ",", line ]), printed.slice(0, -1)),
join(concat([",", line]), printed.slice(0, -1)),
printed.length > 1 ? ", " : "",
group(util.getLast(printed), { shouldBreak: true }),
")"
@ -1762,7 +1738,7 @@ function printArgumentsList(path, options, print) {
"(",
indent(
options.tabWidth,
concat([ line, join(concat([ ",", line ]), printed) ])
concat([line, join(concat([",", line]), printed)])
),
options.trailingComma ? "," : "",
line,
@ -1780,7 +1756,7 @@ function printArgumentsList(path, options, print) {
"(",
indent(
options.tabWidth,
concat([ softline, join(concat([ ",", line ]), printed) ])
concat([softline, join(concat([",", line]), printed)])
),
ifBreak(options.trailingComma ? "," : ""),
softline,
@ -1801,7 +1777,7 @@ function printFunctionParams(path, print, options) {
var p = printed[i];
if (p && defExprPath.getValue()) {
printed[i] = concat([ p, " = ", print(defExprPath) ]);
printed[i] = concat([p, " = ", print(defExprPath)]);
}
},
"defaults"
@ -1809,7 +1785,7 @@ function printFunctionParams(path, print, options) {
}
if (fun.rest) {
printed.push(concat([ "...", path.call(print, "rest") ]));
printed.push(concat(["...", path.call(print, "rest")]));
}
if (printed.length === 0) {
@ -1825,7 +1801,7 @@ function printFunctionParams(path, print, options) {
"(",
indent(
options.tabWidth,
concat([ softline, join(concat([ ",", line ]), printed) ])
concat([softline, join(concat([",", line]), printed)])
),
ifBreak(canHaveTrailingComma && options.trailingComma ? "," : ""),
softline,
@ -1875,7 +1851,7 @@ function printObjectMethod(path, options, print) {
function printReturnType(path, print) {
const n = path.getValue();
const parts = [ path.call(print, "returnType") ];
const parts = [path.call(print, "returnType")];
if (n.predicate) {
// The return type will already add the colon, but otherwise we
@ -1894,7 +1870,7 @@ function typeIsFunction(type) {
function printExportDeclaration(path, options, print) {
var decl = path.getValue();
var parts = [ "export " ];
var parts = ["export "];
namedTypes.Declaration.assert(decl);
@ -1935,7 +1911,7 @@ function printExportDeclaration(path, options, print) {
options.tabWidth,
concat([
options.bracketSpacing ? line : softline,
join(concat([ ",", line ]), path.map(print, "specifiers"))
join(concat([",", line]), path.map(print, "specifiers"))
])
),
ifBreak(options.trailingComma ? "," : ""),
@ -1976,7 +1952,7 @@ function printFlowDeclaration(path, parts) {
function printClass(path, options, print) {
const n = path.getValue();
const parts = [ "class" ];
const parts = ["class"];
if (n.id) {
parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
@ -1995,7 +1971,11 @@ function printClass(path, options, print) {
}
if (n["implements"] && n["implements"].length > 0) {
partsGroup.push(line, "implements ", join(", ", path.map(print, "implements")));
partsGroup.push(
line,
"implements ",
join(", ", path.map(print, "implements"))
);
}
if (partsGroup.length > 0) {
@ -2013,8 +1993,18 @@ function printMemberLookup(path, options, print) {
return concat(
n.computed
? [ "[", group(concat([indent(options.tabWidth, concat([ softline, property ])), softline])), "]" ]
: [ ".", property ]);
? [
"[",
group(
concat([
indent(options.tabWidth, concat([softline, property])),
softline
])
),
"]"
]
: [".", property]
);
}
// We detect calls on member expressions specially to format a
@ -2078,14 +2068,12 @@ function printMemberChain(node, options, print) {
}));
const fullyExpanded = concat([
leftmostPrinted,
concat(
nodesPrinted.map(node => {
concat(nodesPrinted.map(node => {
return indent(
options.tabWidth,
concat([ hardline, node.property, node.args ])
concat([hardline, node.property, node.args])
);
})
)
}))
]);
// If it's a chain, force it to be fully expanded and print a
@ -2100,14 +2088,9 @@ function printMemberChain(node, options, print) {
return fullyExpanded;
} else {
return conditionalGroup([
concat([
leftmostPrinted,
concat(
nodesPrinted.map(node => {
return concat([ node.property, node.args ]);
})
)
]),
concat([leftmostPrinted, concat(nodesPrinted.map(node => {
return concat([node.property, node.args]);
}))]),
fullyExpanded
]);
}
@ -2169,7 +2152,7 @@ function printJSXChildren(path, options, print) {
// allow one extra newline
if (newlines.length > 1) {
children.push(hardline)
children.push(hardline);
}
return;
}
@ -2196,7 +2179,7 @@ function printJSXChildren(path, options, print) {
// allow one extra newline
if (value.match(/\n/g).length > 1) {
children.push(hardline)
children.push(hardline);
}
} else if (/\s/.test(value)) {
// whitespace-only without newlines,
@ -2293,7 +2276,7 @@ function printJSXElement(path, options, print) {
// lone JSX whitespace doesn't work otherwise because the group
// will be printed in flat mode, and we need to print `{' '}` in
// break mode.
childrenGroupedByLine = [concat([ hardline, children[0] ])];
childrenGroupedByLine = [concat([hardline, children[0]])];
} else {
// Prefill leading newline, and initialize the first line's group
let groups = [[]];
@ -2304,7 +2287,7 @@ function printJSXElement(path, options, print) {
// On a new line, so create a new group and put this element
// in it.
groups.push([ child ]);
groups.push([child]);
} else {
// Not on a newline, so add this element to the current group.
util.getLast(groups).push(child);
@ -2343,7 +2326,7 @@ function printJSXElement(path, options, print) {
}
return conditionalGroup([
group(concat([ openingLines, concat(children), closingLines ])),
group(concat([openingLines, concat(children), closingLines])),
multiLineElem
]);
}
@ -2357,7 +2340,7 @@ function maybeWrapJSXElementInParens(path, elem, options) {
ExpressionStatement: true,
CallExpression: true,
ConditionalExpression: true,
LogicalExpression: true,
LogicalExpression: true
};
if (NO_WRAP_PARENTS[parent.type]) {
return elem;
@ -2366,7 +2349,7 @@ function maybeWrapJSXElementInParens(path, elem, options) {
return group(
concat([
ifBreak("("),
indent(options.tabWidth, concat([ softline, elem ])),
indent(options.tabWidth, concat([softline, elem])),
softline,
ifBreak(")")
])
@ -2404,7 +2387,17 @@ function printBinaryishExpressions(path, parts, print, options, isNested) {
) {
// Flatten them out by recursively calling this function. The
// printed values will all be appended to `parts`.
path.call(left => printBinaryishExpressions(left, parts, print, options, /* isNested */ true), "left");
path.call(
left =>
printBinaryishExpressions(
left,
parts,
print,
options,
/* isNested */ true
),
"left"
);
} else {
parts.push(path.call(print, "left"));
}
@ -2415,13 +2408,7 @@ function printBinaryishExpressions(path, parts, print, options, isNested) {
// the other ones since we don't call the normal print on BinaryExpression,
// only for the left and right parts
if (isNested && node.comments) {
parts.push(
comments.printComments(
path,
p => "",
options
)
);
parts.push(comments.printComments(path, p => "", options));
}
} else {
// Our stopping case. Simply print the node normally.
@ -2437,10 +2424,10 @@ function adjustClause(clause, options, forceSpace) {
}
if (isCurlyBracket(clause) || forceSpace) {
return concat([ " ", clause ]);
return concat([" ", clause]);
}
return indent(options.tabWidth, concat([ line, clause ]));
return indent(options.tabWidth, concat([line, clause]));
}
function isCurlyBracket(doc) {

View File

@ -1,4 +1,5 @@
"use strict";
var assert = require("assert");
var types = require("ast-types");
var n = types.namedTypes;
@ -55,7 +56,8 @@ function fixFaultyLocations(node, text) {
}
function isExportDeclaration(node) {
if (node) switch (node.type) {
if (node)
switch (node.type) {
case "ExportDeclaration":
case "ExportDefaultDeclaration":
case "ExportDefaultSpecifier":
@ -90,7 +92,7 @@ function skip(chars) {
// Allow `skip` functions to be threaded together without having
// to check for failures (did someone say monads?).
if(index === false) {
if (index === false) {
return false;
}
@ -98,19 +100,18 @@ function skip(chars) {
let cursor = index;
while (cursor >= 0 && cursor < length) {
const c = text.charAt(cursor);
if(chars instanceof RegExp) {
if(!chars.test(c)) {
if (chars instanceof RegExp) {
if (!chars.test(c)) {
return cursor;
}
}
else if (chars.indexOf(c) === -1) {
} else if (chars.indexOf(c) === -1) {
return cursor;
}
backwards ? cursor-- : cursor++;
}
if(cursor === -1 || cursor === length) {
if (cursor === -1 || cursor === length) {
// If we reached the beginning or end of the file, return the
// out-of-bounds cursor. It's up to the caller to handle this
// correctly. We don't want to indicate `false` though if it
@ -118,7 +119,7 @@ function skip(chars) {
return cursor;
}
return false;
}
};
}
const skipWhitespace = skip(/\s/);
@ -130,22 +131,20 @@ const skipToLineEnd = skip("; \t");
// want to skip one newline. It's simple to implement.
function skipNewline(text, index, opts) {
const backwards = opts && opts.backwards;
if(index === false) {
if (index === false) {
return false;
}
else if(backwards) {
if(text.charAt(index) === "\n") {
} else if (backwards) {
if (text.charAt(index) === "\n") {
return index - 1;
}
if(text.charAt(index - 1) === "\r" && text.charAt(index) === "\n") {
if (text.charAt(index - 1) === "\r" && text.charAt(index) === "\n") {
return index - 2;
}
}
else {
if(text.charAt(index) === "\n") {
} else {
if (text.charAt(index) === "\n") {
return index + 1;
}
if(text.charAt(index) === "\r" && text.charAt(index + 1) === "\n") {
if (text.charAt(index) === "\r" && text.charAt(index + 1) === "\n") {
return index + 2;
}
}
@ -218,16 +217,16 @@ function htmlEscapeInsideAngleBracket(str) {
var PRECEDENCE = {};
[
[ "||" ],
[ "&&" ],
[ "|" ],
[ "^" ],
[ "&" ],
[ "==", "===", "!=", "!==" ],
[ "<", ">", "<=", ">=", "in", "instanceof" ],
[ ">>", "<<", ">>>" ],
[ "+", "-" ],
[ "*", "/", "%", "**" ]
["||"],
["&&"],
["|"],
["^"],
["&"],
["==", "===", "!=", "!=="],
["<", ">", "<=", ">=", "in", "instanceof"],
[">>", "<<", ">>>"],
["+", "-"],
["*", "/", "%", "**"]
].forEach(function(tier, i) {
tier.forEach(function(op) {
PRECEDENCE[op] = i;