-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathcreate-binary-operation-printer.ts
More file actions
63 lines (57 loc) · 1.8 KB
/
create-binary-operation-printer.ts
File metadata and controls
63 lines (57 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { NonterminalKind, TerminalKind } from '@nomicfoundation/slang/cst';
import { doc } from 'prettier';
import { isBinaryOperation } from '../slang-utils/is-binary-operation.js';
import type { AstPath, Doc, ParserOptions } from 'prettier';
import type {
AstNode,
BinaryOperation,
StrictAstNode
} from '../slang-nodes/types.d.ts';
import type { PrintFunction } from '../types.d.ts';
const { group, line } = doc.builders;
function rightOperandPrint(
node: BinaryOperation,
path: AstPath<BinaryOperation>,
print: PrintFunction
): Doc {
const rightOperand = [
` ${node.operator}`,
line,
path.call(print, 'rightOperand')
];
// If it's a single binary operation, avoid having a small right
// operand like - 1 on its own line
const leftOperand = node.leftOperand.variant;
const grandparentNode = path.getNode(2) as StrictAstNode;
const shouldGroup =
!(
leftOperand.kind !== TerminalKind.Identifier &&
isBinaryOperation(leftOperand)
) &&
(!isBinaryOperation(grandparentNode) ||
grandparentNode.kind === NonterminalKind.AssignmentExpression);
return shouldGroup ? group(rightOperand) : rightOperand;
}
export const createBinaryOperationPrinter =
(
groupRulesBuilder: (
path: AstPath<BinaryOperation>
) => (document: Doc) => Doc,
indentRulesBuilder: (
path: AstPath<BinaryOperation>,
options: ParserOptions<AstNode>
) => (document: Doc) => Doc
) =>
(
node: BinaryOperation,
path: AstPath<BinaryOperation>,
print: PrintFunction,
options: ParserOptions<AstNode>
): Doc => {
const groupRules = groupRulesBuilder(path);
const indentRules = indentRulesBuilder(path, options);
return groupRules([
path.call(print, 'leftOperand'),
indentRules(rightOperandPrint(node, path, print))
]);
};