-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunction.js
More file actions
447 lines (412 loc) · 19 KB
/
function.js
File metadata and controls
447 lines (412 loc) · 19 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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
const assert = require('assert');
const { evalExpressionNode, evalBlockStatement, evalBuiltInMethodImpl, NODE_BLOCK_STATEMENT, NODE_BUILTIN_METHOD_IMPL } = require('./eval');
const { Context } = require('./context');
class AbstractFunction {
exec() {
const target = this.targetClass ? `${this.targetClass}.prototype` : 'target';
throw new Error('Not implemented yet' + (this.name ? `: ${target}.${this.name}()` : ''));
}
bindThis(newTarget) {
return new AbstractFunction();
}
toString() {
// @todo(feat) support toString() for non-native functions
const isNative = this.body.type === NODE_BUILTIN_METHOD_IMPL;
return isNative ? `function ${this.body.name ? this.body.name : ''}() { [native code] }` : undefined;
}
toJSON() { return void 0; }
}
class GenericFunction extends AbstractFunction {
constructor(body, paramDefs, thisTarget, { isVariadic, isLambda, context } = { isVariadic: undefined, isLambda: undefined, context: null }) {
super();
assert(body, 'Function body cannot be empty');
this.body = body;
this.paramDefs = Array.isArray(paramDefs) ? paramDefs : [];
this.thisTarget = thisTarget;
this.isVariadic = !!isVariadic;
this.isLambda = !!isLambda;
this.context = context;
assert(!this.isVariadic || this.paramDefs.length > 0, 'Variadic functions must have at least one parameter');
}
exec(params, context, options, runState) { // @todo deprecated parameter 'context'
// If runState is defined, preserve the same object. Otherwise create a new one (when user is using .exec() directly)
runState = runState || { startTime: Date.now() };
options = Object.assign({ timeout: 100 }, options || {}); // @todo(refactor) unify default values
// @todo check if this freeze can be removed
Object.freeze(options); // Even if this object is passed in the context, it cannot be altered. If it would be possible, a custom code would be able to increase the timeout for example.
const fnVars = this.paramDefs.reduce((acc, { name, optional }, i) => {
const paramWasProvided = i <= params.length - 1;
const autoInitParam = !optional;
if (paramWasProvided || autoInitParam) {
acc[name] = { value: params[i], isConst: false };
} else {
assert(`Not provided parameter ${name} calling ${this.body.name}(...)`);
}
return acc;
}, {});
// If it is variadic, last parameter is overridden with an array of the "rest" of the parameters (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters)
if (this.isVariadic) {
const lastParamName = this.paramDefs[this.paramDefs.length - 1].name;
fnVars[lastParamName] = { value: params.slice(this.paramDefs.length - 1), isConst: false };
}
const fnContext = new Context(fnVars, this.context);
// @todo support function body with a single statement without block (without { and })?
switch (this.body.type) {
case NODE_BLOCK_STATEMENT: return evalBlockStatement(this.body, fnContext, this.thisTarget, options, runState).result;
case NODE_BUILTIN_METHOD_IMPL: return evalBuiltInMethodImpl(this.body, fnContext, this.thisTarget, options, runState);
default: return evalExpressionNode(this.body, fnContext, this.thisTarget, options, runState);
}
}
bindThis(newTarget) {
return new GenericFunction(this.body, this.paramDefs, newTarget, { isVariadic: this.isVariadic, isLambda: this.isLambda, context: this.context });
}
}
const builtIns = {
Array: {
// @todo(feat) priority 1
find: new AbstractFunction(),
findIndex: new AbstractFunction(),
indexOf: new AbstractFunction(),
lastIndexOf: new AbstractFunction(),
// @todo(feat) priority 2
join: new AbstractFunction(),
sort: new AbstractFunction(),
concat: new AbstractFunction(),
// @todo(feat) priority 3
keys: new AbstractFunction(),
values: new AbstractFunction(),
entries: new AbstractFunction(),
toString: new AbstractFunction(),
// @todo(feat) priority 4
every: new AbstractFunction(),
fill: new AbstractFunction(),
flat: new AbstractFunction(),
at: new AbstractFunction(),
copyWithin: new AbstractFunction(),
flatMap: new AbstractFunction(),
groupBy: new AbstractFunction(),
groupByToMap: new AbstractFunction(),
reduceRight: new AbstractFunction(),
reverse: new AbstractFunction(),
some: new AbstractFunction(),
toLocaleString: new AbstractFunction(),
// Available
map: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'Array', name: 'map' }, [{ name: 'callbackFn' }, { name: 'thisArg' }]),
push: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'Array', name: 'push' }, [{ name: 'elementN' }], undefined, { isVariadic: true }),
reduce: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'Array', name: 'reduce' }, [{ name: 'callbackFn' }, { name: 'initialValue', optional: true }]),
includes: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'Array', name: 'includes' }, [{ name: 'searchElement' }, { name: 'fromIndex' }]),
filter: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'Array', name: 'filter' }, [{ name: 'callbackFn' }, { name: 'thisArg' }]),
pop: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'Array', name: 'pop' }),
shift: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'Array', name: 'shift' }),
unshift: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'Array', name: 'unshift' }, [{ name: 'elementN' }], undefined, { isVariadic: true }),
slice: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'Array', name: 'slice' }, [{ name: 'start' }, { name: 'end' }]),
splice: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'Array', name: 'splice' }, [{ name: 'start', optional: true }, { name: 'deleteCount', optional: true }, { name: 'itemN' }], undefined, { isVariadic: true }),
forEach: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'Array', name: 'forEach' }, [{ name: 'callbackFn' }, { name: 'thisArg' }]),
},
Object: {
hasOwnProperty: new AbstractFunction(),
isPrototypeOf: new AbstractFunction(),
propertyIsEnumerable: new AbstractFunction(),
toLocaleString: new AbstractFunction(),
toSource: new AbstractFunction(),
toString: new AbstractFunction(),
valueOf: new AbstractFunction(),
},
String: {
toLowerCase: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'toLowerCase' }),
toUpperCase: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'toUpperCase' }),
trim: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'trim' }),
trimStart: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'trimStart' }),
trimLeft: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'trimLeft' }),
trimEnd: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'trimEnd' }),
trimRight: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'trimRight' }),
toString: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'toString' }),
valueOf: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'valueOf' }),
at: new AbstractFunction(),
charAt: new AbstractFunction(),
charCodeAt: new AbstractFunction(),
fromCharCode: new AbstractFunction(),
codePointAt: new AbstractFunction(),
fromCodePoint: new AbstractFunction(),
concat: new AbstractFunction(),
endsWith: new AbstractFunction(),
includes: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'includes' }, [{ name: 'searchElement' }, { name: 'fromIndex' }]),
indexOf: new AbstractFunction(),
lastIndexOf: new AbstractFunction(),
localeCompare: new AbstractFunction(),
match: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'match' }, [{ name: 'pattern' }]),
matchAll: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'matchAll' }, [{ name: 'pattern' }]),
normalize: new AbstractFunction(),
padEnd: new AbstractFunction(),
padStart: new AbstractFunction(),
repeat: new AbstractFunction(),
replace: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'replace' }, [{ name: 'searchValue' }, { name: 'newValue' }]),
replaceAll: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'replaceAll' }, [{ name: 'searchValue' }, { name: 'newValue' }]),
search: new GenericFunction({ type: NODE_BUILTIN_METHOD_IMPL, targetClass: 'String', name: 'search' }, [{ name: 'pattern' }]),
slice: new AbstractFunction(),
split: new AbstractFunction(),
startsWith: new AbstractFunction(),
substring: new AbstractFunction(),
toLocaleLowerCase: new AbstractFunction(),
toLocaleUpperCase: new AbstractFunction(),
},
};
// @todo implement static methods for Array
// Array.from()
// Array.isArray()
// Array.of()
// @todo implement static methods for Object
// Object.assign()
// Object.create()
// Object.fromEntries()
// Object.defineProperties()
// Object.defineProperty()
// Object.freeze()
// Object.getOwnPropertyDescriptor()
// Object.getOwnPropertyDescriptors()
// Object.getOwnPropertyNames()
// Object.getOwnPropertySymbols()
// Object.getPrototypeOf()
// Object.hasOwn()
// Object.is()
// Object.isExtensible()
// Object.isFrozen()
// Object.isSealed()
// Object.preventExtensions()
// Object.seal()
// Object.setPrototypeOf()
const builtInsImpls = {
Array: {
isArray: (target, context, options, runState) => {
const value = context.get('value');
return Array.isArray(value);
},
push: (target, context, options, runState) => {
return target.push(...context.get('elementN'));
},
map: (target, context, options, runState) => {
// @todo support thisArg
const fn = context.get('callbackFn');
// @todo check if fn is not nullish
return target.map((elem, i, array) => fn.exec([elem, i, array], context, options, runState));
},
reduce: (target, context, options, runState) => {
const fn = context.get('callbackFn');
if (context.isDefined('initialValue')) {
const initial = context.get('initialValue');
return target.reduce((acc, elem, i) => fn.exec([acc, elem, i, target], context, options, runState), initial);
} else {
return target.reduce((acc, elem, i) => fn.exec([acc, elem, i, target], context, options, runState));
}
},
includes: (target, context, options, runState) => {
const elem = context.get('searchElement');
const from = context.get('fromIndex');
return target.includes(elem, from);
},
filter: (target, context, options, runState) => {
const thisArg = context.get('thisArg');
const callbackFn = context.get('callbackFn');
const isFunc = callbackFn instanceof AbstractFunction;
assert(isFunc, 'Function expected');
const fn = (elem, i, array) => callbackFn.bindThis(thisArg).exec([elem, i, array], context, options, runState);
return target.filter(fn);
},
pop: (target, context, options, runState) => {
return target.pop();
},
shift: (target, context, options, runState) => {
return target.shift();
},
unshift: (target, context, options, runState) => {
return target.unshift(...context.get('elementN'));
},
slice: (target, context, options, runState) => {
const start = context.get('start');
const end = context.get('end');
return target.slice(start, end);
},
splice: (target, context, options, runState) => {
const params = [];
if (context.isDefined('start')) { params.push(context.get('start')); }
if (context.isDefined('deleteCount')) { params.push(context.get('deleteCount')); }
const itemN = context.get('itemN');
return target.splice(...params, ...itemN);
},
forEach: (target, context, options, runState) => {
const thisArg = context.get('thisArg');
const callbackFn = context.get('callbackFn');
const isFunc = callbackFn instanceof AbstractFunction;
assert(isFunc, 'Function expected');
const fn = (elem, i, array) => callbackFn.bindThis(thisArg).exec([elem, i, array], context, options, runState);
return target.forEach(fn);
},
},
Object: {
entries: (target, context, options, runState) => {
const obj = context.get('obj');
if (obj instanceof AbstractFunction) { return []; }
return Object.entries(obj);
},
keys: (target, context, options, runState) => {
const obj = context.get('obj');
if (obj instanceof AbstractFunction) { return []; }
return Object.keys(obj);
},
values: (target, context, options, runState) => {
const obj = context.get('obj');
if (obj instanceof AbstractFunction) { return []; }
return Object.values(obj);
},
},
String: {
toLowerCase: (target, context, options, runState) => {
return target.toLowerCase();
},
toUpperCase: (target, context, options, runState) => {
return target.toUpperCase();
},
trim: (target, context, options, runState) => {
return target.trim();
},
trimStart: (target, context, options, runState) => {
return target.trimStart();
},
trimLeft: (target, context, options, runState) => {
return target.trimLeft();
},
trimEnd: (target, context, options, runState) => {
return target.trimEnd();
},
trimRight: (target, context, options, runState) => {
return target.trimRight();
},
toString: (target, context, options, runState) => {
return target.toString();
},
valueOf: (target, context, options, runState) => {
return target.valueOf();
},
includes: (target, context, options, runState) => {
const elem = context.get('searchElement');
const from = context.get('fromIndex');
return target.includes(elem, from);
},
match: (target, context, options, runState) => {
const pattern = context.get('pattern');
return target.match(pattern);
},
matchAll: (target, context, options, runState) => {
const pattern = context.get('pattern');
return target.matchAll(pattern);
},
replace: (target, context, options, runState) => {
const searchValue = context.get('searchValue');
const newValue = context.get('newValue');
return target.replace(
searchValue,
newValue instanceof AbstractFunction ?
(x) => newValue.exec([x], context, options, runState) :
newValue
)
},
replaceAll: (target, context, options, runState) => {
const searchValue = context.get('searchValue');
const newValue = context.get('newValue');
return target.replaceAll(
searchValue,
newValue instanceof AbstractFunction ?
(x) => newValue.exec([x], context, options, runState) :
newValue
);
},
search: (target, context, options, runState) => {
const pattern = context.get('pattern');
return target.search(pattern);
},
},
JSON: {
parse: (target, context, options, runState) => {
const text = context.get('text');
const reviver = context.get('reviver');
const fn = reviver && ((key, value) => reviver.exec([key, value], context, options, runState));
return JSON.parse(text, fn);
},
stringify: (target, context, options, runState) => {
const value = context.get('value');
const replacer = context.get('replacer');
const space = context.get('space');
const isFunc = replacer instanceof AbstractFunction; // @todo create helper for this check
let replacerParam = replacer; // Replacer could be an array
if (isFunc) {
replacerParam = (key, value) => replacer.exec([key, value], context, options, runState);
}
let valueParam = value;
const hasCustomToJSON = Object.prototype.hasOwnProperty.call(value, 'toJSON') && value.toJSON instanceof AbstractFunction;
if (hasCustomToJSON) {
const customToJSON = () => value.toJSON.exec([], context, options, runState); // @todo check 'this' behavior in this function
valueParam = { ...value, toJSON: customToJSON };
}
return JSON.stringify(valueParam, replacerParam, space);
},
},
Math: {
random: (target, context, options, runState) => {
return Math.random();
},
floor: (target, context, options, runState) => {
const x = context.get('x');
if (x instanceof AbstractFunction) { return NaN; }
return Math.floor(x);
},
ceil: (target, context, options, runState) => {
const x = context.get('x');
if (x instanceof AbstractFunction) { return NaN; }
return Math.ceil(x);
},
round: (target, context, options, runState) => {
const x = context.get('x');
if (x instanceof AbstractFunction) { return NaN; }
return Math.round(x);
},
min: (target, context, options, runState) => {
const values = context.get('valueN').map(value => value instanceof AbstractFunction ? NaN : value);
return Math.min(...values);
},
max: (target, context, options, runState) => {
const values = context.get('valueN').map(value => value instanceof AbstractFunction ? NaN : value);
return Math.max(...values);
},
},
globalThis: {
isNaN: (target, context, options, runState) => {
const value = context.get('value');
return isNaN(value);
},
isFinite: (target, context, options, runState) => {
const value = context.get('testValue');
return isFinite(value);
},
parseFloat: (target, context, options, runState) => {
const string = context.get('string');
// @todo Check if `string` has the method `toString`, and in that case run it before passing it to `parseFloat`. This would support cases like parseFloat({ toString: () => '1.2' })
return parseFloat(string);
},
parseInt: (target, context, options, runState) => {
const string = context.get('string');
// @todo Check if `string` has the method `toString`, and in that case run it before passing it to `parseInt`. This would support cases like parseInt({ toString: () => '1.2' })
if (context.isDefined('radix')) {
const radix = context.get('radix');
return parseInt(string, radix);
} else {
return parseInt(string);
}
},
},
};
module.exports = {
AbstractFunction,
GenericFunction,
builtIns,
builtInsImpls,
};