MCPcopy
hub / github.com/prettier/prettier / needsParentheses

Function needsParentheses

src/language-js/parentheses/needs-parentheses.js:35–887  ·  view source on GitHub ↗

* @param {AstPath} path * @returns {boolean}

(path, options)

Source from the content-addressed store, hash-verified

33 * @returns {boolean}
34 */
35function needsParentheses(path, options) {
36 if (path.isRoot) {
37 return false;
38 }
39
40 const { node, key, parent } = path;
41
42 // to avoid unexpected `}}` in HTML interpolations
43 if (
44 options.__isInHtmlInterpolation &&
45 !options.bracketSpacing &&
46 endsWithRightBracket(node) &&
47 isFollowedByRightBracket(path)
48 ) {
49 return true;
50 }
51
52 // Only statements don't need parentheses.
53 if (isStatement(node)) {
54 return false;
55 }
56
57 if (node.type === "Identifier") {
58 return shouldAddParenthesesToIdentifier(path);
59 }
60
61 if (
62 node.type === "ObjectExpression" ||
63 node.type === "FunctionExpression" ||
64 node.type === "ClassExpression" ||
65 node.type === "DoExpression"
66 ) {
67 const expression = path.findAncestor(
68 (node) => node.type === "ExpressionStatement",
69 )?.expression;
70 if (
71 expression &&
72 startsWithNoLookaheadToken(
73 expression,
74 (leftmostNode) => leftmostNode === node,
75 )
76 ) {
77 return true;
78 }
79 }
80
81 if (node.type === "ObjectExpression") {
82 const arrowFunctionBody = path.findAncestor(
83 (node) => node.type === "ArrowFunctionExpression",
84 )?.body;
85 if (
86 arrowFunctionBody &&
87 arrowFunctionBody.type !== "SequenceExpression" && // these have parens added anyway
88 arrowFunctionBody.type !== "AssignmentExpression" &&
89 startsWithNoLookaheadToken(
90 arrowFunctionBody,
91 (leftmostNode) => leftmostNode === node,
92 )

Callers 12

parentNeedsParenthesesFunction · 0.85
printClassFunction · 0.85
printFunction · 0.85
printTernaryFunction · 0.85
printUnionTypeFunction · 0.85
printCallExpressionFunction · 0.85
printMatchOrPatternFunction · 0.85
recFunction · 0.85

Calls 15

parentNeedsParenthesesFunction · 0.90
isNullishCoalescingFunction · 0.90
hasCommentFunction · 0.90
getPrecedenceFunction · 0.90
shouldFlattenFunction · 0.90
isBitwiseOperatorFunction · 0.90
getFunctionParametersFunction · 0.90
isNumericLiteralFunction · 0.90
isObjectPropertyFunction · 0.90

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…