Add implementation for arrow parens option

Based on https://github.com/prettier/prettier/pull/2676

* Thread `path` and `options` through helpers so we don't need to add `needsParens` onto the AST node anymore (mutation)
* Pull test call detection logic out into helper method so it can be re-used for arrow function parens
* Add arrow function parens option implementation (avoid/always)
* Don't break arrow function parens around (done) in test call
master
Stephen Scott 2017-11-26 16:27:03 -07:00 committed by Suchipi Izumi
parent 9a1e408a3f
commit e4eb8a4065
6 changed files with 343 additions and 77 deletions

View File

@ -214,14 +214,6 @@ function genericPrint(path, options, printPath, args) {
needsParens = path.needsParens(options);
}
if (node.type) {
// HACK: ASI prevention in no-semi mode relies on knowledge of whether
// or not a paren has been inserted (see `exprNeedsASIProtection()`).
// For now, we're just passing that information by mutating the AST here,
// but it would be nice to find a cleaner way to do this.
node.needsParens = needsParens;
}
const parts = [];
if (needsParens) {
parts.unshift("(");
@ -501,7 +493,7 @@ function genericPrintNoParens(path, options, print, args) {
parts.push("async ");
}
if (canPrintParamsWithoutParens(n)) {
if (shouldPrintParamsWithoutParens(path, options)) {
parts.push(path.call(print, "params", 0));
} else {
parts.push(
@ -855,7 +847,6 @@ function genericPrintNoParens(path, options, print, args) {
case "NewExpression":
case "CallExpression": {
const isNew = n.type === "NewExpression";
const unitTestRe = /^(f|x)?(it|describe|test)$/;
const optional = printOptionalToken(path);
if (
@ -869,22 +860,7 @@ function genericPrintNoParens(path, options, print, args) {
isTemplateOnItsOwnLine(n.arguments[0], options.originalText)) ||
// Keep test declarations on a single line
// e.g. `it('long name', () => {`
(!isNew &&
((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name)) ||
(n.callee.type === "MemberExpression" &&
n.callee.object.type === "Identifier" &&
n.callee.property.type === "Identifier" &&
unitTestRe.test(n.callee.object.name) &&
(n.callee.property.name === "only" ||
n.callee.property.name === "skip"))) &&
n.arguments.length === 2 &&
(n.arguments[0].type === "StringLiteral" ||
n.arguments[0].type === "TemplateLiteral" ||
(n.arguments[0].type === "Literal" &&
typeof n.arguments[0].value === "string")) &&
(n.arguments[1].type === "FunctionExpression" ||
n.arguments[1].type === "ArrowFunctionExpression") &&
n.arguments[1].params.length <= 1)
(!isNew && isTestCall(n))
) {
return concat([
isNew ? "new " : "",
@ -2873,11 +2849,9 @@ function printStatementSequence(path, options, print) {
!options.semi &&
!isClass &&
!isTheOnlyJSXElementInMarkdown(options, stmtPath) &&
stmtNeedsASIProtection(stmtPath)
stmtNeedsASIProtection(stmtPath, options)
) {
if (stmt.comments && stmt.comments.some(comment => comment.leading)) {
// Note: stmtNeedsASIProtection requires stmtPath to already be printed
// as it reads needsParens which is mutated on the instance
parts.push(print(stmtPath, { needsSemi: true }));
} else {
parts.push(";", stmtPrinted);
@ -3228,6 +3202,11 @@ function printFunctionParams(path, print, options, expandArg, printTypeParams) {
const parent = path.getParentNode();
// don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
if (parent.type === "CallExpression" && isTestCall(parent)) {
return concat([typeParams, "(", join(", ", printed), ")"]);
}
const flowTypeAnnotations = [
"AnyTypeAnnotation",
"NullLiteralTypeAnnotation",
@ -3282,6 +3261,19 @@ function printFunctionParams(path, print, options, expandArg, printTypeParams) {
]);
}
function shouldPrintParamsWithoutParens(path, options) {
if (options.arrowFunctionParentheses === "always") {
return false;
}
if (options.arrowFunctionParentheses === "avoid") {
const node = path.getValue();
return canPrintParamsWithoutParens(node);
}
return false;
}
function canPrintParamsWithoutParens(node) {
return (
node.params.length === 1 &&
@ -4683,15 +4675,43 @@ function getLeftSide(node) {
);
}
function exprNeedsASIProtection(node) {
// HACK: node.needsParens is added in `genericPrint()` for the sole purpose
// of being used here. It'd be preferable to find a cleaner way to do this.
function getLeftSidePathName(path, node) {
if (node.expressions) {
return ["expressions", 0];
}
if (node.left) {
return ["left"];
}
if (node.test) {
return ["test"];
}
if (node.callee) {
return ["callee"];
}
if (node.object) {
return ["object"];
}
if (node.tag) {
return ["tag"];
}
if (node.argument) {
return ["argument"];
}
if (node.expression) {
return ["expression"];
}
throw new Error("Unexpected node has no left side", node);
}
function exprNeedsASIProtection(path, options) {
const node = path.getValue();
const maybeASIProblem =
node.needsParens ||
path.needsParens(options) ||
node.type === "ParenthesizedExpression" ||
node.type === "TypeCastExpression" ||
(node.type === "ArrowFunctionExpression" &&
!canPrintParamsWithoutParens(node)) ||
!shouldPrintParamsWithoutParens(path, options)) ||
node.type === "ArrayExpression" ||
node.type === "ArrayPattern" ||
(node.type === "UnaryExpression" &&
@ -4713,17 +4733,25 @@ function exprNeedsASIProtection(node) {
return false;
}
return exprNeedsASIProtection(getLeftSide(node));
return path.call.apply(
path,
[childPath => exprNeedsASIProtection(childPath, options)].concat(
getLeftSidePathName(path, node)
)
);
}
function stmtNeedsASIProtection(path) {
function stmtNeedsASIProtection(path, options) {
const node = path.getNode();
if (node.type !== "ExpressionStatement") {
return false;
}
return exprNeedsASIProtection(node.expression);
return path.call(
childPath => exprNeedsASIProtection(childPath, options),
"expression"
);
}
function classPropMayCauseASIProblems(path) {
@ -4992,6 +5020,28 @@ function isObjectType(n) {
return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral";
}
// eg; `describe("some string", (done) => {})`
function isTestCall(n) {
const unitTestRe = /^(f|x)?(it|describe|test)$/;
return (
((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name)) ||
(n.callee.type === "MemberExpression" &&
n.callee.object.type === "Identifier" &&
n.callee.property.type === "Identifier" &&
unitTestRe.test(n.callee.object.name) &&
(n.callee.property.name === "only" ||
n.callee.property.name === "skip"))) &&
n.arguments.length === 2 &&
(n.arguments[0].type === "StringLiteral" ||
n.arguments[0].type === "TemplateLiteral" ||
(n.arguments[0].type === "Literal" &&
typeof n.arguments[0].value === "string")) &&
(n.arguments[1].type === "FunctionExpression" ||
n.arguments[1].type === "ArrowFunctionExpression") &&
n.arguments[1].params.length <= 1
);
}
function printAstToDoc(ast, options, addAlignmentSize) {
addAlignmentSize = addAlignmentSize || 0;

View File

@ -234,7 +234,7 @@ const composition = (ViewComponent, ContainerComponent) =>
static propTypes = {};
};
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const testResults = results.testResults.map(testResult =>
const testResults = results.testResults.map((testResult) =>
formatResult(testResult, formatter, reporter)
);
@ -265,16 +265,16 @@ expect(() =>
).not.toThrowError();
const a = Observable.fromPromise(axiosInstance.post("/carts/mine")).map(
response => response.data
(response) => response.data
);
const b = Observable.fromPromise(axiosInstance.get(url)).map(
response => response.data
(response) => response.data
);
func(
veryLoooooooooooooooooooooooongName,
veryLooooooooooooooooooooooooongName =>
(veryLooooooooooooooooooooooooongName) =>
veryLoooooooooooooooongName.something()
);

View File

@ -113,7 +113,7 @@ a = b => {
return c
};
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(a => {}).length;
((a) => {}).length;
typeof (() => {});
export default (() => {})();
(() => {})()\`\`;
@ -133,20 +133,20 @@ a = () => ({}[b] && a);
a = () => ({}\`\` && a);
a = () => ({} = 0);
a = () => ({}, a);
a => a instanceof {};
a => ({}().b && 0);
a => ({}().c = 0);
x => ({}()());
x => ({}()\`\`);
x => ({}().b);
a = b => c;
(a) => a instanceof {};
(a) => ({}().b && 0);
(a) => ({}().c = 0);
(x) => ({}()());
(x) => ({}()\`\`);
(x) => ({}().b);
a = (b) => c;
a = (b?) => c;
x => (y = z);
x => (y += z);
f(a => ({})) + 1;
(a => ({})) || 0;
a = b => c;
a = b => {
(x) => (y = z);
(x) => (y += z);
f((a) => ({})) + 1;
((a) => ({})) || 0;
a = (b) => c;
a = (b) => {
return c;
};
@ -421,7 +421,7 @@ fooooooooooooooooooooooooooooooooooooooooooooooooooo(action => next =>
dispatch(action),
);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Seq(typeDef.interface.groups).forEach(group =>
Seq(typeDef.interface.groups).forEach((group) =>
Seq(group.members).forEach((member, memberName) =>
markdownDoc(member.doc, {
typePath: typePath.concat(memberName.slice(1)),
@ -430,7 +430,7 @@ Seq(typeDef.interface.groups).forEach(group =>
)
);
const promiseFromCallback = fn =>
const promiseFromCallback = (fn) =>
new Promise((resolve, reject) =>
fn((err, result) => {
if (err) return reject(err);
@ -452,7 +452,7 @@ function render() {
return (
<View>
<Image
onProgress={e =>
onProgress={(e) =>
this.setState({
progress: Math.round(
100 * e.nativeEvent.loaded / e.nativeEvent.total
@ -468,7 +468,7 @@ function render() {
return (
<View>
<Image
onProgress={e =>
onProgress={(e) =>
this.setState({
progress: Math.round(
100 * e.nativeEvent.loaded / e.nativeEvent.total
@ -484,7 +484,7 @@ function render() {
return (
<View>
<Image
onProgress={e =>
onProgress={(e) =>
this.setState({
progress: Math.round(
100 * e.nativeEvent.loaded / e.nativeEvent.total
@ -506,7 +506,7 @@ jest.mock(
}
);
fooooooooooooooooooooooooooooooooooooooooooooooooooo(action => next =>
fooooooooooooooooooooooooooooooooooooooooooooooooooo((action) => (next) =>
dispatch(action)
);
@ -615,17 +615,17 @@ export const bem = block =>
* @param {String} block - the BEM Block you'd like to select.
* @returns {Function}
*/
export const bem = block =>
export const bem = (block) =>
/**
* @param {String} [element] - the BEM Element within that block; if undefined, selects the block itself.
* @returns {Function}
*/
element =>
(element) =>
/**
* @param {?String} [modifier] - the BEM Modifier for the Block or Element; if undefined, selects the Block or Element unmodified.
* @returns {String}
*/
modifier =>
(modifier) =>
[
".",
css(block),
@ -700,21 +700,21 @@ const middleware = options => (req, res, next) => {
// ...
};
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const fn = b => c => d => {
const fn = (b) => (c) => (d) => {
return 3;
};
const foo = (a, b) => c => d => {
const foo = (a, b) => (c) => (d) => {
return 3;
};
const bar = a => b => c => a + b + c;
const bar = (a) => (b) => (c) => a + b + c;
const mw = store => next => action => {
const mw = (store) => (next) => (action) => {
return next(action);
};
const middleware = options => (req, res, next) => {
const middleware = (options) => (req, res, next) => {
// ...
};
@ -829,26 +829,26 @@ foo(c, a => b)
foo(c, a => b, d)
foo(a => b, d)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
promise.then(result => result, err => err);
promise.then((result) => result, (err) => err);
promise.then(
result => {
(result) => {
f();
return result;
},
err => {
(err) => {
f();
return err;
}
);
foo(a => b);
foo(a => {
foo((a) => b);
foo((a) => {
return b;
});
foo(c, a => b);
foo(c, a => b, d);
foo(a => b, d);
foo(c, (a) => b);
foo(c, (a) => b, d);
foo((a) => b, d);
`;

View File

@ -34,6 +34,10 @@ test(\`does something really long and complicated so I have to write a very long
console.log("hello!");
});
test("does something really long and complicated so I have to write a very long name for the test", <T>(done) => {
console.log("hello!");
});
describe("does something really long and complicated so I have to write a very long name for the describe block", () => {
it("an example test", (done) => {
console.log("hello!");
@ -123,6 +127,12 @@ test(\`does something really long and complicated so I have to write a very long
console.log("hello!");
});
test("does something really long and complicated so I have to write a very long name for the test", <
T
>(done) => {
console.log("hello!");
});
describe("does something really long and complicated so I have to write a very long name for the describe block", () => {
it("an example test", done => {
console.log("hello!");
@ -190,3 +200,204 @@ it.only.only(
);
`;
exports[`test_declarations.js 2`] = `
// Shouldn't break
it("does something really long and complicated so I have to write a very long name for the test", () => {
console.log("hello!");
});
it("does something really long and complicated so I have to write a very long name for the test", function() {
console.log("hello!");
});
it(\`does something really long and complicated so I have to write a very long name for the test\`, function() {
console.log("hello!");
});
it(\`{foo + bar} does something really long and complicated so I have to write a very long name for the test\`, function() {
console.log("hello!");
});
it(\`handles
some
newlines
does something really long and complicated so I have to write a very long name for the test\`, () => {
console.log("hello!");
})
test("does something really long and complicated so I have to write a very long name for the test", (done) => {
console.log("hello!");
});
test(\`does something really long and complicated so I have to write a very long name for the test\`, (done) => {
console.log("hello!");
});
test("does something really long and complicated so I have to write a very long name for the test", <T>(done) => {
console.log("hello!");
});
describe("does something really long and complicated so I have to write a very long name for the describe block", () => {
it("an example test", (done) => {
console.log("hello!");
});
});
describe(\`does something really long and complicated so I have to write a very long name for the describe block\`, () => {
it(\`an example test\`, (done) => {
console.log("hello!");
});
});
xdescribe("does something really long and complicated so I have to write a very long name for the describe block", () => {});
fdescribe("does something really long and complicated so I have to write a very long name for the describe block", () => {});
describe.only(\`does something really long and complicated so I have to write a very long name for the test\`, () => {});
describe.skip(\`does something really long and complicated so I have to write a very long name for the test\`, () => {});
fit("does something really long and complicated so I have to write a very long name for the describe block", () => {});
xit("does something really long and complicated so I have to write a very long name for the describe block", () => {});
it.only("does something really long and complicated so I have to write a very long name for the test", () => {
console.log("hello!");
});
it.only(\`does something really long and complicated so I have to write a very long name for the test\`, () => {
console.log("hello!");
});
it.skip(\`does something really long and complicated so I have to write a very long name for the test\`, () => {});
test.only(\`does something really long and complicated so I have to write a very long name for the test\`, () => {});
test.skip(\`does something really long and complicated so I have to write a very long name for the test\`, () => {});
ftest("does something really long and complicated so I have to write a very long name for the describe block", () => {});
xtest("does something really long and complicated so I have to write a very long name for the describe block", () => {});
// Should break
it.only("does something really long and complicated so I have to write a very long name for the test", 10, () => {
console.log("hello!");
});
it.only.only("does something really long and complicated so I have to write a very long name for the test", () => {
console.log("hello!");
});
it.only.only("does something really long and complicated so I have to write a very long name for the test", (a, b, c) => {
console.log("hello!");
});
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Shouldn't break
it("does something really long and complicated so I have to write a very long name for the test", () => {
console.log("hello!");
});
it("does something really long and complicated so I have to write a very long name for the test", function() {
console.log("hello!");
});
it(\`does something really long and complicated so I have to write a very long name for the test\`, function() {
console.log("hello!");
});
it(\`{foo + bar} does something really long and complicated so I have to write a very long name for the test\`, function() {
console.log("hello!");
});
it(\`handles
some
newlines
does something really long and complicated so I have to write a very long name for the test\`, () => {
console.log("hello!");
});
test("does something really long and complicated so I have to write a very long name for the test", (done) => {
console.log("hello!");
});
test(\`does something really long and complicated so I have to write a very long name for the test\`, (done) => {
console.log("hello!");
});
test("does something really long and complicated so I have to write a very long name for the test", <
T
>(done) => {
console.log("hello!");
});
describe("does something really long and complicated so I have to write a very long name for the describe block", () => {
it("an example test", (done) => {
console.log("hello!");
});
});
describe(\`does something really long and complicated so I have to write a very long name for the describe block\`, () => {
it(\`an example test\`, (done) => {
console.log("hello!");
});
});
xdescribe("does something really long and complicated so I have to write a very long name for the describe block", () => {});
fdescribe("does something really long and complicated so I have to write a very long name for the describe block", () => {});
describe.only(\`does something really long and complicated so I have to write a very long name for the test\`, () => {});
describe.skip(\`does something really long and complicated so I have to write a very long name for the test\`, () => {});
fit("does something really long and complicated so I have to write a very long name for the describe block", () => {});
xit("does something really long and complicated so I have to write a very long name for the describe block", () => {});
it.only("does something really long and complicated so I have to write a very long name for the test", () => {
console.log("hello!");
});
it.only(\`does something really long and complicated so I have to write a very long name for the test\`, () => {
console.log("hello!");
});
it.skip(\`does something really long and complicated so I have to write a very long name for the test\`, () => {});
test.only(\`does something really long and complicated so I have to write a very long name for the test\`, () => {});
test.skip(\`does something really long and complicated so I have to write a very long name for the test\`, () => {});
ftest("does something really long and complicated so I have to write a very long name for the describe block", () => {});
xtest("does something really long and complicated so I have to write a very long name for the describe block", () => {});
// Should break
it.only(
"does something really long and complicated so I have to write a very long name for the test",
10,
() => {
console.log("hello!");
}
);
it.only.only(
"does something really long and complicated so I have to write a very long name for the test",
() => {
console.log("hello!");
}
);
it.only.only(
"does something really long and complicated so I have to write a very long name for the test",
(a, b, c) => {
console.log("hello!");
}
);
`;

View File

@ -1 +1,2 @@
run_spec(__dirname, null, ["typescript"]);
run_spec(__dirname, { arrowFunctionParentheses: "always" }, ["typescript"]);

View File

@ -31,6 +31,10 @@ test(`does something really long and complicated so I have to write a very long
console.log("hello!");
});
test("does something really long and complicated so I have to write a very long name for the test", <T>(done) => {
console.log("hello!");
});
describe("does something really long and complicated so I have to write a very long name for the describe block", () => {
it("an example test", (done) => {
console.log("hello!");