-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathcreate-binary-operation-printer.ts
More file actions
61 lines (54 loc) · 1.93 KB
/
create-binary-operation-printer.ts
File metadata and controls
61 lines (54 loc) · 1.93 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
import { NonterminalKind } from '@nomicfoundation/slang/cst';
import { doc } from 'prettier';
import { isBinaryOperation } from '../slang-utils/is-binary-operation.js';
import { TerminalNode } from '../slang-nodes/TerminalNode.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(
{ operator, leftOperand }: BinaryOperation,
path: AstPath<BinaryOperation>,
print: PrintFunction,
options: ParserOptions<AstNode>
): Doc {
const rightOperand = path.call(print, 'rightOperand');
const rightOperandDoc =
options.experimentalOperatorPosition === 'end'
? [` ${operator}`, line, rightOperand]
: [line, `${operator} `, rightOperand];
// If there's only a single binary expression, we want to create a group in
// order to avoid having a small right part like -1 be on its own line.
const parent = path.parent as StrictAstNode;
const shouldGroup =
(leftOperand instanceof TerminalNode || !isBinaryOperation(leftOperand)) &&
(!isBinaryOperation(parent) ||
parent.kind === NonterminalKind.AssignmentExpression);
return shouldGroup ? group(rightOperandDoc) : rightOperandDoc;
}
export const createBinaryOperationPrinter =
(
groupRulesBuilder: (
path: AstPath<BinaryOperation>
) => (document: Doc) => Doc,
indentRulesBuilder: (
path: AstPath<BinaryOperation>
) => (document: Doc) => Doc
) =>
(
node: BinaryOperation,
path: AstPath<BinaryOperation>,
print: PrintFunction,
options: ParserOptions<AstNode>
): Doc => {
const groupRules = groupRulesBuilder(path);
const indentRules = indentRulesBuilder(path);
return groupRules([
path.call(print, 'leftOperand'),
indentRules(rightOperandPrint(node, path, print, options))
]);
};