@jbrowse/jexl 5.0.0 → 5.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/print.ts ADDED
@@ -0,0 +1,205 @@
1
+ /*
2
+ * Jexl
3
+ * Copyright 2020 Tom Shawver
4
+ */
5
+
6
+ import type { AstNode, AstNodeUnion, BinaryExpression } from './types.ts'
7
+
8
+ type Node = AstNodeUnion
9
+
10
+ const PRECEDENCE: Record<string, number> = {
11
+ '=': 2,
12
+ '||': 10,
13
+ '??': 10,
14
+ '&&': 11,
15
+ '==': 20,
16
+ '!=': 20,
17
+ '~': 20,
18
+ '!~': 20,
19
+ '<': 20,
20
+ '<=': 20,
21
+ '>': 20,
22
+ '>=': 20,
23
+ in: 20,
24
+ '+': 30,
25
+ '-': 30,
26
+ '*': 40,
27
+ '/': 40,
28
+ '//': 40,
29
+ '%': 50,
30
+ '^': 50
31
+ }
32
+
33
+ const RIGHT_ASSOCIATIVE = new Set(['^'])
34
+ const LOGICAL = new Set(['||', '&&'])
35
+
36
+ // how tightly each form binds, mirroring the Parser's levels: `;`, then `=`
37
+ // and lambdas, then `?:`, then binary operators, then prefix operators
38
+ const SEQUENCE = 0
39
+ const ASSIGNMENT = 1
40
+ const CONDITIONAL = 2
41
+ const CUSTOM_BINARY = 3
42
+ const UNARY = 100
43
+
44
+ const letter = String.raw`a-zA-Zа-яА-Я_À-ÖØ-öø-ÿ$`
45
+ const IDENTIFIER = new RegExp(`^[${letter}][${letter}0-9]*$`)
46
+ const WORDS = new Set(['in', 'true', 'false', 'null'])
47
+
48
+ export function isName(text: string) {
49
+ return IDENTIFIER.test(text) && !WORDS.has(text)
50
+ }
51
+
52
+ export function key(name: string) {
53
+ return isName(name) ? `.${name}` : `[${quote(name)}]`
54
+ }
55
+
56
+ export function quote(text: string) {
57
+ return `'${text.replaceAll('\\', '\\\\').replaceAll("'", String.raw`\'`)}'`
58
+ }
59
+
60
+ function precedenceOf(node: Node) {
61
+ switch (node.type) {
62
+ case 'SequenceExpression': {
63
+ return SEQUENCE
64
+ }
65
+ case 'AssignmentExpression':
66
+ case 'Lambda': {
67
+ return ASSIGNMENT
68
+ }
69
+ case 'ConditionalExpression': {
70
+ // with no alternate, it ends only before `)`, `]`, `}`, `,`, `;` or the end
71
+ return node.alternate ? CONDITIONAL : SEQUENCE
72
+ }
73
+ case 'BinaryExpression': {
74
+ return PRECEDENCE[node.operator] ?? CUSTOM_BINARY
75
+ }
76
+ case 'UnaryExpression': {
77
+ return UNARY
78
+ }
79
+ default: {
80
+ return Infinity
81
+ }
82
+ }
83
+ }
84
+
85
+ function within(ast: AstNode, least: number) {
86
+ const text = print(ast)
87
+ return precedenceOf(ast as Node) < least ? `(${text})` : text
88
+ }
89
+
90
+ function binaryOperand(parent: BinaryExpression, ast: AstNode, left: boolean) {
91
+ const own = PRECEDENCE[parent.operator]
92
+ if (own === undefined) {
93
+ return within(ast, UNARY)
94
+ }
95
+ const child = ast as Node
96
+ const theirs = precedenceOf(child)
97
+ const chained =
98
+ child.type === 'BinaryExpression' &&
99
+ RIGHT_ASSOCIATIVE.has(parent.operator) &&
100
+ RIGHT_ASSOCIATIVE.has(child.operator)
101
+ const mixesNullish =
102
+ child.type === 'BinaryExpression' &&
103
+ ((parent.operator === '??' && LOGICAL.has(child.operator)) ||
104
+ (child.operator === '??' && LOGICAL.has(parent.operator)))
105
+ const text = print(ast)
106
+ return theirs < own || (theirs === own && left === chained) || mixesNullish
107
+ ? `(${text})`
108
+ : text
109
+ }
110
+
111
+ /**
112
+ * Renders a tree back to expression text, for messages and suggestions. The
113
+ * text parses back to the same tree.
114
+ */
115
+ export function print(ast: AstNode): string {
116
+ const node = ast as Node
117
+ switch (node.type) {
118
+ case 'Literal': {
119
+ const { value } = node
120
+ return typeof value === 'string'
121
+ ? quote(value)
122
+ : Object.is(value, -0)
123
+ ? '-0'
124
+ : String(value)
125
+ }
126
+ case 'Identifier': {
127
+ return node.from
128
+ ? within(node.from, Infinity) + key(node.value)
129
+ : node.value
130
+ }
131
+ case 'FilterExpression': {
132
+ return `${within(node.subject, Infinity)}[${within(node.expr, ASSIGNMENT)}]`
133
+ }
134
+ case 'BinaryExpression': {
135
+ return `${binaryOperand(node, node.left, true)} ${node.operator} ${binaryOperand(node, node.right!, false)}`
136
+ }
137
+ case 'UnaryExpression': {
138
+ const { operator } = node
139
+ const right = within(node.right!, UNARY)
140
+ // the Lexer folds a minus before a digit into the number
141
+ if (operator === '-' && /^\d/.test(right)) {
142
+ return `-(${right})`
143
+ }
144
+ return IDENTIFIER.test(operator)
145
+ ? `${operator} ${right}`
146
+ : operator + right
147
+ }
148
+ case 'ConditionalExpression': {
149
+ const test = within(node.test, CUSTOM_BINARY)
150
+ const consequent = node.consequent
151
+ ? ` ${within(node.consequent, ASSIGNMENT)} `
152
+ : ''
153
+ const alternate = node.alternate
154
+ ? ` ${within(node.alternate, ASSIGNMENT)}`
155
+ : ''
156
+ return `${test} ?${consequent}:${alternate}`
157
+ }
158
+ case 'FunctionCall': {
159
+ const args = node.args.map((arg) => within(arg, ASSIGNMENT))
160
+ return `${node.name}(${args.join(', ')})`
161
+ }
162
+ case 'ArrayLiteral': {
163
+ const items = node.value.map((item) => within(item, ASSIGNMENT))
164
+ return `[${items.join(', ')}]`
165
+ }
166
+ case 'ObjectLiteral': {
167
+ const entries = Object.entries(node.value).map(
168
+ ([name, value]) =>
169
+ `${isName(name) ? name : quote(name)}: ${within(value, ASSIGNMENT)}`
170
+ )
171
+ return `{${entries.join(', ')}}`
172
+ }
173
+ case 'TemplateLiteral': {
174
+ const parts = node.parts.map((part) =>
175
+ part.type === 'static'
176
+ ? part.value
177
+ .replaceAll('\\', '\\\\')
178
+ .replaceAll('`', '\\`')
179
+ .replaceAll('${', '\\${')
180
+ : `\${${print(part.value)}}`
181
+ )
182
+ return `\`${parts.join('')}\``
183
+ }
184
+ case 'SequenceExpression': {
185
+ const { expressions } = node
186
+ const text = expressions
187
+ .map((expr) => within(expr, ASSIGNMENT))
188
+ .join('; ')
189
+ return expressions.length === 1 ? `${text};` : text
190
+ }
191
+ case 'AssignmentExpression': {
192
+ return `${node.left.value} = ${within(node.right!, ASSIGNMENT)}`
193
+ }
194
+ case 'Lambda': {
195
+ const params =
196
+ node.params.length === 1
197
+ ? node.params[0]
198
+ : `(${node.params.join(', ')})`
199
+ return `${params} => ${within(node.body, ASSIGNMENT)}`
200
+ }
201
+ default: {
202
+ return '?'
203
+ }
204
+ }
205
+ }