-
Notifications
You must be signed in to change notification settings - Fork 11
/
compiler.js
329 lines (288 loc) · 10 KB
/
compiler.js
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// @ts-check
'use strict'
import {
isSync,
Sync,
Compiled
} from './constants.js'
// asyncIterators is required for the compiler to operate as intended.
import asyncIterators from './async_iterators.js'
import { coerceArray } from './utilities/coerceArray.js'
import { countArguments } from './utilities/countArguments.js'
/**
* Provides a simple way to compile logic into a function that can be run.
* @param {string[]} strings
* @param {...any} items
* @returns {{ [Compiled]: string }}
*/
function compileTemplate (strings, ...items) {
let res = ''
const buildState = this
for (let i = 0; i < strings.length; i++) {
res += strings[i]
if (i < items.length) {
if (typeof items[i] === 'function') {
this.methods.push(items[i])
if (!isSync(items[i])) buildState.asyncDetected = true
res += (isSync(items[i]) ? '' : ' await ') + 'methods[' + (buildState.methods.length - 1) + ']'
} else if (items[i] && typeof items[i][Compiled] !== 'undefined') res += items[i][Compiled]
else res += buildString(items[i], buildState)
}
}
return { [Compiled]: res }
}
/**
* @typedef BuildState
* Used to keep track of the compilation.
* @property {*} [engine]
* @property {Object} [notTraversed]
* @property {Object} [methods]
* @property {Object} [state]
* @property {Array} [processing]
* @property {*} [async]
* @property {Array} [above]
* @property {Boolean} [asyncDetected]
* @property {*} [values]
* @property {Boolean} [avoidInlineAsync]
* @property {string} [extraArguments]
* @property {(strings: string[], ...items: any[]) => { compiled: string }} [compile] A function that can be used to compile a template.
*/
/**
* Checks if the value passed in is a primitive JS object / value.
* @param {*} x
* @returns
*/
function isPrimitive (x, preserveObject) {
if (typeof x === 'number' && (x === Infinity || x === -Infinity || Number.isNaN(x))) return false
return (
x === null ||
x === undefined ||
['Number', 'String', 'Boolean'].includes(x.constructor.name) ||
(!preserveObject && x.constructor.name === 'Object')
)
}
/**
* Checks if the method & its inputs are deterministic.
* @param {*} method
* @param {*} engine
* @param {BuildState} buildState
* @returns
*/
export function isDeterministic (method, engine, buildState) {
if (Array.isArray(method)) {
return method.every((i) => isDeterministic(i, engine, buildState))
}
if (method && typeof method === 'object') {
const func = Object.keys(method)[0]
const lower = method[func]
if (engine.isData(method, func)) return true
if (lower === undefined) return true
if (!engine.methods[func]) throw new Error(`Method '${func}' was not found in the Logic Engine.`)
if (engine.methods[func].traverse === false) {
return typeof engine.methods[func].deterministic === 'function'
? engine.methods[func].deterministic(lower, buildState)
: engine.methods[func].deterministic
}
return typeof engine.methods[func].deterministic === 'function'
? engine.methods[func].deterministic(lower, buildState)
: engine.methods[func].deterministic &&
isDeterministic(lower, engine, buildState)
}
return true
}
/**
* Checks if the method & its inputs are synchronous.
* @param {*} method
* @param {*} engine
*/
function isDeepSync (method, engine) {
if (!engine.async) return true
if (Array.isArray(method)) return method.every(i => isDeepSync(i, engine))
if (typeof method === 'object') {
const func = Object.keys(method)[0]
const lower = method[func]
if (!isSync(engine.methods[func])) return false
if (engine.methods[func].traverse === false) {
if (typeof engine.methods[func][Sync] === 'function' && engine.methods[func][Sync](method, { engine })) return true
return false
}
return isDeepSync(lower, engine)
}
return true
}
/**
* Builds the string for the function that will be evaluated.
* @param {*} method
* @param {BuildState} buildState
* @returns
*/
function buildString (method, buildState = {}) {
const {
notTraversed = [],
async,
processing = [],
values = [],
engine
} = buildState
function pushValue (value, preserveObject = false) {
if (isPrimitive(value, preserveObject)) return JSON.stringify(value)
values.push(value)
return `values[${values.length - 1}]`
}
if (Array.isArray(method)) {
let res = ''
for (let i = 0; i < method.length; i++) {
if (i > 0) res += ','
res += buildString(method[i], buildState)
}
return '[' + res + ']'
}
let asyncDetected = false
function makeAsync (result) {
buildState.asyncDetected = buildState.asyncDetected || asyncDetected
if (async && asyncDetected) return `await ${result}`
return result
}
const func = method && Object.keys(method)[0]
if (method && typeof method === 'object') {
if (!func) return pushValue(method)
if (!engine.methods[func]) {
// Check if this is supposed to be "data" rather than a function.
if (engine.isData(method, func)) return pushValue(method, true)
throw new Error(`Method '${func}' was not found in the Logic Engine.`)
}
if (
!buildState.engine.disableInline &&
engine.methods[func] &&
isDeterministic(method, engine, buildState)
) {
if (isDeepSync(method, engine)) {
return pushValue((engine.fallback || engine).run(method), true)
} else if (!buildState.avoidInlineAsync) {
processing.push(engine.run(method).then((i) => pushValue(i)))
return `__%%%${processing.length - 1}%%%__`
} else {
buildState.asyncDetected = true
return `(await ${pushValue(engine.run(method))})`
}
}
let lower = method[func]
if (!lower || typeof lower !== 'object') lower = [lower]
if (engine.methods[func] && engine.methods[func].compile) {
let str = engine.methods[func].compile(lower, buildState)
if (str[Compiled]) str = str[Compiled]
if ((str || '').startsWith('await')) buildState.asyncDetected = true
if (str !== false) return str
}
let coerce = engine.methods[func].optimizeUnary ? '' : 'coerceArray'
if (!coerce && Array.isArray(lower) && lower.length === 1 && !Array.isArray(lower[0])) lower = lower[0]
else if (coerce && Array.isArray(lower)) coerce = ''
const argumentsDict = [', context', ', context, above', ', context, above, engine']
if (typeof engine.methods[func] === 'function') {
asyncDetected = !isSync(engine.methods[func])
const argumentsNeeded = argumentsDict[countArguments(engine.methods[func]) - 1] || argumentsDict[2]
return makeAsync(`engine.methods["${func}"](${coerce}(` + buildString(lower, buildState) + ')' + argumentsNeeded + ')')
} else {
asyncDetected = Boolean(async && engine.methods[func] && engine.methods[func].asyncMethod)
const argCount = countArguments(asyncDetected ? engine.methods[func].asyncMethod : engine.methods[func].method)
const argumentsNeeded = argumentsDict[argCount - 1] || argumentsDict[2]
if (engine.methods[func] && (typeof engine.methods[func].traverse === 'undefined' ? true : engine.methods[func].traverse)) {
return makeAsync(`engine.methods["${func}"]${asyncDetected ? '.asyncMethod' : '.method'}(${coerce}(` + buildString(lower, buildState) + ')' + argumentsNeeded + ')')
} else {
notTraversed.push(lower)
return makeAsync(`engine.methods["${func}"]${asyncDetected ? '.asyncMethod' : '.method'}(` + `notTraversed[${notTraversed.length - 1}]` + argumentsNeeded + ')')
}
}
}
return pushValue(method)
}
/**
* Synchronously compiles the logic to a function that can run the logic more optimally.
* @param {*} method
* @param {BuildState} [buildState]
* @returns
*/
function build (method, buildState = {}) {
Object.assign(
buildState,
Object.assign(
{
notTraversed: [],
methods: [],
state: {},
processing: [],
async: buildState.engine.async,
asyncDetected: false,
values: [],
compile: compileTemplate
},
buildState
)
)
const str = buildString(method, buildState)
return processBuiltString(method, str, buildState)
}
/**
* Asynchronously compiles the logic to a function that can run the logic more optimally. Also supports async logic methods.
* @param {*} method
* @param {BuildState} [buildState]
* @returns
*/
async function buildAsync (method, buildState = {}) {
Object.assign(
buildState,
Object.assign(
{
notTraversed: [],
methods: [],
state: {},
processing: [],
async: buildState.engine.async,
asyncDetected: false,
values: [],
compile: compileTemplate
},
buildState
)
)
const str = buildString(method, buildState)
buildState.processing = await Promise.all(buildState.processing || [])
return processBuiltString(method, str, buildState)
}
/**
* Takes the string that's been generated and does some post-processing on it to be evaluated.
* @param {*} method
* @param {*} str
* @param {BuildState} buildState
* @returns
*/
function processBuiltString (method, str, buildState) {
const {
engine,
methods,
notTraversed,
processing = [],
values
} = buildState
const above = []
processing.forEach((item, x) => {
str = str.replace(`__%%%${x}%%%__`, item)
})
const final = `(values, methods, notTraversed, asyncIterators, engine, above, coerceArray) => ${buildState.asyncDetected ? 'async' : ''} (context ${buildState.extraArguments ? ',' + buildState.extraArguments : ''}) => { const result = ${str}; return result }`
// console.log(str)
// console.log(final)
// eslint-disable-next-line no-eval
return Object.assign(
(typeof globalThis !== 'undefined' ? globalThis : global).eval(final)(values, methods, notTraversed, asyncIterators, engine, above, coerceArray), {
[Sync]: !buildState.asyncDetected,
aboveDetected: typeof str === 'string' && str.includes(', above')
})
}
export { build }
export { buildAsync }
export { buildString }
export default {
build,
buildAsync,
buildString
}