|
| 1 | +import { doc } from 'prettier'; |
| 2 | +import { assignment } from '../assignment.js'; |
| 3 | +import { comparison } from '../comparison.js'; |
| 4 | + |
| 5 | +const { group, indent, line } = doc.builders; |
| 6 | + |
| 7 | +const shouldGroupOrIndent = (node, matchers) => |
| 8 | + matchers.some((matcher) => matcher.match(node.operator)); |
| 9 | + |
| 10 | +export const createGroupIfNecessaryBuilder = |
| 11 | + (matchers) => (path) => (document) => { |
| 12 | + const parentNode = path.getParentNode(); |
| 13 | + if ( |
| 14 | + parentNode.type === 'BinaryOperation' && |
| 15 | + !comparison.match(parentNode.operator) |
| 16 | + ) { |
| 17 | + return shouldGroupOrIndent(parentNode, matchers) |
| 18 | + ? group(document) |
| 19 | + : document; |
| 20 | + } |
| 21 | + return group(document); |
| 22 | + }; |
| 23 | + |
| 24 | +export const createIndentIfNecessaryBuilder = |
| 25 | + (matchers) => (path) => (document) => { |
| 26 | + let node = path.getNode(); |
| 27 | + for (let i = 0; ; i += 1) { |
| 28 | + const parentNode = path.getParentNode(i); |
| 29 | + if (parentNode.type === 'ReturnStatement') return document; |
| 30 | + if ( |
| 31 | + parentNode.type !== 'BinaryOperation' || |
| 32 | + comparison.match(parentNode.operator) || |
| 33 | + shouldGroupOrIndent(parentNode, matchers) |
| 34 | + ) { |
| 35 | + return indent(document); |
| 36 | + } |
| 37 | + if (node === parentNode.right) return document; |
| 38 | + node = parentNode; |
| 39 | + } |
| 40 | + }; |
| 41 | + |
| 42 | +export const createBinaryOperationPrinter = |
| 43 | + (groupIfNecessaryBuilder, indentIfNecessaryBuilder) => |
| 44 | + (node, path, print) => { |
| 45 | + const groupIfNecessary = groupIfNecessaryBuilder(path); |
| 46 | + const indentIfNecessary = indentIfNecessaryBuilder(path); |
| 47 | + |
| 48 | + const right = [' ', node.operator, line, path.call(print, 'right')]; |
| 49 | + // If it's a single binary operation, avoid having a small right |
| 50 | + // operand like - 1 on its own line |
| 51 | + const parent = path.getParentNode(); |
| 52 | + const shouldGroup = |
| 53 | + node.left.type !== 'BinaryOperation' && |
| 54 | + (parent.type !== 'BinaryOperation' || assignment.match(parent.operator)); |
| 55 | + return groupIfNecessary([ |
| 56 | + path.call(print, 'left'), |
| 57 | + indentIfNecessary(shouldGroup ? group(right) : right) |
| 58 | + ]); |
| 59 | + }; |
| 60 | + |
| 61 | +export const defaultBinaryOperationPrinter = createBinaryOperationPrinter( |
| 62 | + createGroupIfNecessaryBuilder([]), |
| 63 | + createIndentIfNecessaryBuilder([]) |
| 64 | +); |
0 commit comments