-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpreprocessAST.js
1391 lines (1162 loc) · 49.8 KB
/
preprocessAST.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
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const Parser = require("@babel/parser");
const traverse = require('@babel/traverse').default;
const generate = require('@babel/generator').default;
const t = require('@babel/types');
const fs = require('fs');
const prettier = require('prettier');
const jshint = require('jshint').JSHINT;
let __FIXME_ERRCNT = 0;
// NOTE:
// Here's the current state of PreprocessAST for future me:
// - Dynamic whitelisting isn't fool proof, its completely basic in favour of better static and runtime perf + less
// complexity
//
// Code:
// do.a.thing();
// do.a.thingTwo();
//
// Basic dynamic whitelisting
// CHECK(do) && CHECK(do.a) && CHECK(do.a.thing);
// do.a.thing();
// CHECK(do.a.thingTwo);
// do.a.thingTwo();
//
// Safer dynamic whitelisting
// CHECK(do) && CHECK(do.a) && CHECK(do.a.thing);
// do.a.thing();
// CHECK(do) && CHECK(do.a) && CHECK(do.a.thingTwo);
// do.a.thingTwo();
//
//
// This considers if our whitelist has changed in other code. If we really wanted to do that we would want to
// preprocess *all* code and keep an obj-like file that provides a whitelist for functions across the scope of
// the project. Unfortunately because of JS typeless nature its not easy to determine which function is being
// called, so its not easy to point to the right function when whitelisting. Worse this makes things far more
// complicated and more perf heavy. I think having a basic whitelisting mode is better. If we really needed we
// could simply provide an option to make whitelisting less trustworthy so that we only whitelist safe types
// (Env, Math, Array, Object, etc.) and use that mode for soak tests or something
//
//
// - I'm not sure how much I trust the loc for sourcemaps; that may need some cleaning
// - Further preprocess would be nice: SCRIPT_INJECT, Assert, LOG_DEBUG, etc.
// - Profiling/optimizations: I haven't done any profiling, so I'm not sure how well this performs and if there's
// any easy speed ups
// TODO:
// - SCRIPT_INJECT in here as opposed to bash?
// - Have to check leadingComments on all nodes for this
// - Could take an argument that specifies if we need to check for SCRPIT_INJECT; also could only look until we
// find it, then stop looking
// - MACRO files for shared code across client/server/webworkers/test
// - eg. Error checking in Errors.js: OBJECT_TYPES, CHECK; requirejs configs (between client/client-worker, and server/server-worker), etc.
// - FIXME: Do we need CHeckNode(topNode === true) to be a block statement? If so we should Assert this
// * FIXME: Dependency Graph / re-ordering nodes
// * CallExpression currying
// - var s = GetTile().LocalPos().x
// - if(GetTile(isPlayer ? x : y).SwapPlayer().LocalPos(isPlayer ? y : x).x < 0)
//
// The solution is probably to recursively check the node and inject these dependency nodes BEFORE the dependent node
//
// var __RESULTS = GetTile();
// __RESULTS = __RESULTS.LocalPos();
// __RESULTS = __RESULTS.x;
// var s = __RESULTS;
//
//
// var __RESULTS = isPlayer ? x : y;
// __RESULTS = GetTile(__RESULTS);
// __RESULTS = __RESULTS.SwapPlayer();
// __RESULTS2 = isPlayer ? y : x;
// __RESULTS = __RESULTS.LocalPos(__RESULTS2);
// __RESULTS = __RESULTS.x;
// if (__RESULTS < 0)
//
//
// First we'd have to order the dependency graph and swap our nodes with dependent-ordered nodes. Then we'd go
// through and check each node
// * FIXME: LocalExpression, BinaryExpression
// These are allowed to fail since we may have previous checks:
// _.isObject(notAnObj) && notAnObj.a.b.c.d()
//
// We could make our checks like: { CHECK(a) && CHECK(a.b) && CHECK(a.b.c) }
// With binary/logical expressions we could include them as so:
// { (CHECK(a) && { CHECK(a.b) || CHECK(a.c) }) || (CHECK(b) }
//
// - Inline static functions: DEBUGGER, etc.
// We could inline with the expression:
// (_.isObject(notAnObj) && (CHECK(notAnObj) && CHECK(notAnObj.a) && CHECK(notAnObj.a.b) &&
// CHECK(notAnObj.a.b.c) && CHECK(notAnObj.a.b.c.d) && notAnObj.a.b.c.d()))
// - Smoke tests would be nice for this. Parse & CHECK code that's supposed to fail at parts, and will only crash if
// preprocessed incorrectly
// - Lint for less safe code / unable to check code
// - More accurate copying of loc for sourcemaps
// * FIXME: Dynamic whitelist on type checking (list of known values as we traverse through nodes)
// - HAS_KEY unecessary if we're about to test that key: IS_OBJECT(a), HAS_KEY(a, 'b'), IS_OBJECT(a.b)
// - scopedWhitelist: BodyStatement pushes a new scope to this array, then goes through each expression in body
// - Each preCheck/replacementCheck adds to scopedWhitelist
// - Pop scopedWhitelist at end of BodyStatement processing
// - whitelist: hash of node/check?
// * Inline checks: CHECK( (typeof a === 'object') && ('b' in a) && (typeof a.b === 'object') )
// - Check not null/undefined:
// a[c.d] -- c.d should be defined, and probably a raw type (NumericLiteral, string)
//
//
// - How would we prevent checks if we've already done a manual check?
// if (a && a.b && a.b.c) { ... }
// - Whitelist check: be ready for mutations in-between:
//
// a.b.c.d = 1
// if (x) Transform(a)
// a.b.c.e = 2
//
//
// Maybe we can keep track of type intrinsic while parsing, and then when a call is made we kill nuke any
// intrinsics that we can't trust anymore. Then when we want to CHECK we first see if the check is already safe
//
// Would need this to also be safe with block scope (conditions/etc.)
//
// - Profile to determine overhead for extra assertion checking (no whitelist? nuke part of whitelist after
// mutation call)
//
// - Profiler speeds for larger files
// - Could keep track of all available variables based off scope as we traverse through node. For any CHECK(..) points
// we could also provide a list of variables in the scope, add it all to a string (for better perf) and pass that
// string to an eval that allows us to fetch those variables and then pass to DEBUG or errorReport
// CHECK(typeof a.b === "object", "a;x;f")
// --> Assert(typeof a.b === "object") ? {} : { var scopedVars = eval(codeFromScopedVarsStr("a;x;f")); DEBUGGER(assertStatement, scopedVars); };
// false? build variable fetch from str
// scopedVarsCode = "scopedVars.push(a, x, f)"
// eval(scopedVarsCode)
// DEBUGGER(assertStatement, scopedVars)
// - Fix output:
// const
// a; CHECK(b);
//
// a = b.c;
// - Clean CheckNode input: (curNode, assert, state)
// assert: things we want to check/confirm
// state: modifyNode, scopeNode, scopedWhitelist
// TESTS BELOW
//let code = "const a = function() {\nconst b = 1; const c = 3; c.call(); assert(Log(b) && 1 && true && b.yup()); a.b.c.thing(); b(); a[b.c].d; return b.that(); }; assert(Log(a) && console.log(b)); Log(a()); console.log(a()); a[b.c].d; var x = { b:1, c:[1,2] };";
//let code = "{ CALL({ check: 1, args: [{ node: a.b.c }] }); }";
//let code = "{ a[b.c.d].e.f(); }";
//let code = "{ a[b.c] = 2; }";
//let code = "{ a.b(3); }";
//let code = " { a.b().c(); }";
//let code = "{ a.b.c; }";
//let code = "{ a.b[c].d; }";
//let code = "{ a.b[0].d; }";
//let code = "{ a.b['s'].d; }";
//let code = "{ var f = () => { if(a.b.c.d) { { var a = c.d; } return b.x(); } else return 2; }; }";
//let code = "{ for(var a in b.c.d) { x(); a(); } }";
//let code = "{ var f = () => { const obj = { x: 1}, a = obj, b = a.x, c = obj.x(1, 2); } }";
//let code = "{ const obj = { x: 1}, a = obj, b = a.x, c = obj.x(1, 2); }";
//let code = "{ const a = x(j.k.y / z.w, 10),\
// b = x(j.k.x / z.w, 10),\
// c = this.y(z, y); }";
//let code = "{ this.charComponent = function(name) {\
// return this.charComponents.find((c) => c.name === name);\
// }; }";
//let code = "{ f((c) => c.name === name); }";
//let code = "{ const fxmgrPath = Env.isBot ? 'test/pseudofxmgr' : 'client/fxmgr',\n\
// rendererPath = Env.isBot ? 'test/pseudoRenderer' : 'client/renderer',\n\
// uiPath = Env.isBot ? 'test/pseudoUI' : 'client/ui'; }";
//let code = "{ ( ( typeof defensiveInfo == 'object' || DEBUGGER('a') ) && ( typeof target == 'object' || DEBUGGER('b') ) && ( typeof target.entity == 'object' || DEBUGGER('c') ) && ( typeof target.entity.npc == 'object' || DEBUGGER('d') ) ) }";
//let code = "{ var OBJECT_TYPES = ['object', 'function']; var a = 1; OBJECT_TYPES.includes(typeof a); }";
//let code = "{ The.area.pathfinding.workerHandlePath({\
// movableID: character.entity.id,\
// start: { x: fromTiles[0].x, y: fromTiles[0].y },\
// }); }";
/*
let code = "{\
character.entity.cancelPath();\n\
character.entity.page.area.pathfinding.workerHandlePath({\
movableID: The.player.id,\
startPt: { x: playerX, y: playerY },\
endPt: { x: toGlobal.x, y: toGlobal.y }\
}).then((data) => {\
if (data.ptPath.ALREADY_THERE) {\
addedPath = ALREADY_THERE;\
return;\
}\
const path = new Path();\
data.ptPath.walks.forEach((walk) => {\
path.walks.push(walk);\
});\
path.start = { x: playerX, y: playerY };\
if (maxWalk && path.length() > maxWalk) {\
addedPath = PATH_TOO_FAR;\
} else {\
path.flag = PATH_CHASE;\
addedPath = character.entity.addPath(path);\
pathId = character.entity.path.id;\
character.entity.recordNewPath(path);\
}\
}).catch((data) => {\
console.log(`FAILED TO FIND PATH: (${playerX}, ${playerY}) -> (${toX}, ${toY})`);\
});\
}";
*/
//let code = "{\
// workerHandlePath().then((data) => {\
// Taco.bell();\
// });\
//}";
//let code = "{ let taco = [1,2,3].filter((i) => i > 1).map((i) => i * 2); }";
//let code = "{\
// server.handler(EVT_REGENERATE).set(function (evt, data) {\
// UI.postMessage(`Regenerating ${data.entityId} to health ${data.health}`, MESSAGE_INFO);\
// The.area.movables[data.entityId].character.doHook(RegenerateEvt).post(data);\
// });\
//}";
//let code = "{ const area = this.entity.page.area; }";
//let code = "{ var t = (mouse) => { const x = (mouse.clientX - taco.bell.meat); }; }";
let code = "{ this.Log(`e == ${e}`, LOG_DEBUG);\n\
this.Log(`Do we have a target? ${this.target ? 1 : 2}`, LOG_DEBUG);\n\
this.Log(`Does our target have a character? ${this.target.character.a.b.c ? target.character.a.b.c : target.character.a.b()}`, LOG_DEBUG); }";
const Settings = {
output: null,
verbose: true
//checkSyntax: true
};
const ModifyNode = function() {
this.preCheck = []; // preCheck: Checks made *before* the node
this.replaceNode = []; // replaceNode: Replace node with these
this.hoistNodes = []; // hostNodes: Hoist these nodes to the top of the scope
};
let sourceFile = 'a.js';
// Process Server arguments
for (let i = 0; i < process.argv.length; ++i) {
const arg = process.argv[i];
if (arg === "--file") {
sourceFile = process.argv[++i];
code = fs.readFileSync(sourceFile, 'utf8');
} else if (arg == "--output") {
Settings.output = process.argv[++i];
Settings.verbose = false;
}
}
const codeLines = code.split('\n');
const OBJECT_TYPE = "OBJECT",
FUNCTION_TYPE = "FUNCTION";
const HAS_KEY = "HAS_KEY",
IS_TYPE = "IS_TYPE";
// Clone a node
const cloneNode = (node) => {
const clonedNode = {};
if (node.type === 'ExpressionStatement') {
console.error("FIXME: Unexpected cloning ExpressionStatement");
return null;
} else if (node.type === 'Identifier') {
clonedNode.type = node.type;
clonedNode.name = node.name;
} else if (node.type === 'MemberExpression') {
clonedNode.type = node.type;
clonedNode.object = cloneNode(node.object);
clonedNode.property = cloneNode(node.property);
clonedNode.computed = node.computed;
//if (clonedNode.property.type === 'MemberExpression') {
// clonedNode.computed = true;
//}
} else if (node.type === 'ThisExpression') {
clonedNode.type = node.type;
} else if (node.type === 'CallExpression') {
clonedNode.type = node.type;
clonedNode.callee = cloneNode(node.callee);
clonedNode.arguments = [];
node.arguments.forEach((arg) => {
const clonedArg = cloneNode(arg);
clonedNode.arguments.push(clonedArg);
});
} else if (node.type === 'NumericLiteral') {
clonedNode.type = node.type;
clonedNode.value = node.value;
} else if (node.type === 'StringLiteral') {
clonedNode.type = node.type;
clonedNode.value = node.value;
} else if (node.type === 'ThisExpression') {
clonedNode.type = node.type;
} else if (node.type === 'BinaryExpression') {
clonedNode.type = node.type;
clonedNode.operator = node.operator;
clonedNode.left = cloneNode(node.left);
clonedNode.right = cloneNode(node.right);
} else {
console.error(`FIXME: Unexpected cloning type ${node.type}`);
for (let key in node) {
if(['loc','start','end','type'].indexOf(key) >= 0) continue;
console.error(` node.${key}`);
}
return null;
}
return clonedNode;
};
// Convert a child node to a BlockStatement if necessary
// eg. var a = () => return 1;
// into: var a = () => { return 1; }
const blockChildNode = (node, prop) => {
if (node[prop].type !== 'BlockStatement') {
const blockNode = {
type: 'BlockStatement',
directives: [],
body: [node[prop]],
loc: {
filename: sourceFile,
start: {
line: node.loc.start.line,
column: node.loc.start.column
},
end: {
line: node.loc.end.line,
column: node.loc.end.column
}
}
};
node[prop] = blockNode;
return blockNode;
}
return node[prop];
};
// Create a node from a CHECK block
// eg. { checker: IS_TYPE, args: [node, OBJECT_TYPE] }
const buildNodeFromCheck = (checkItem, loc) => {
const setNodeLoc = (node) => {
//node.start = 0;
//node.end = 0;
node.loc = {
filename: loc.filename,
start: {
line: loc.start.line,
column: loc.start.column
},
end: {
line: loc.end.line,
column: loc.end.column
}
}
};
//const checkNodeArr = [];
const checkNodeExpr = {
type: 'ExpressionStatement',
expression: {
type: 'LogicalExpression',
NODE_CHECKTYPE: true,
left: {},
operator: '||',
right: {
type: 'CallExpression',
callee: {
type: 'Identifier',
name: 'DEBUGGER'
},
arguments: [{
type: 'StringLiteral',
value: `ERROR MESSAGE HERE: ${++__FIXME_ERRCNT} (${Settings.output})` // FIXME
}]
}
}
};
const canCheckType = (node) => {
if (node.type === 'Identifier' || node.type === 'ThisExpression') {
return true;
} else if (node.type === 'MemberExpression') {
return canCheckType(node.object) && canCheckType(node.property);
}
return false;
};
setNodeLoc(checkNodeExpr);
const checkItemNode = {};
checkNodeExpr.expression.left = checkItemNode;
setNodeLoc(checkItemNode);
if (checkItem.checker === IS_TYPE) {
// Whitelisted types for checking
if (!canCheckType(checkItem.args[0])) {
return null;
}
/*
// Type Comparison
const typeCmpNode = {
type: 'ObjectProperty',
key: {
type: 'Identifier',
name: 'typeCmp'
},
value: {
// FIXME: We'll change this to numeric literal later
type: 'Identifier',
name: checkItem.args[1]
},
kind: 'init'
};
setNodeLoc(typeCmpNode);
checkItemNode.properties.push(typeCmpNode);
*/
// Node to check
const clonedNode = cloneNode(checkItem.args[0]);
//const objNode = {
// type: 'ObjectProperty',
// key: {
// type: 'Identifier',
// name: 'node'
// },
// value: clonedNode,
// kind: 'init'
//};
checkItemNode.type = 'CallExpression';
checkItemNode.callee = {
object: {
type: 'Identifier',
name: 'OBJECT_TYPES'
},
property: {
type: 'Identifier',
name: 'includes'
},
computed: false,
type: 'MemberExpression'
};
checkItemNode.arguments = [{
type: 'UnaryExpression',
operator: 'typeof',
argument: clonedNode
}];
setNodeLoc(checkItemNode.callee);
setNodeLoc(checkItemNode.arguments[0]);
//checkItemNode.properties.push(objNode);
} else if (checkItem.checker === HAS_KEY) {
let value, type;
if (checkItem.args[2].type === 'Identifier') {
value = checkItem.args[2].name;
} else if (checkItem.args[2].type === 'Literal') {
value = checkItem.args[2].value;
} else if (checkItem.args[2].type === 'NumericLiteral') {
value = checkItem.args[2].value;
} else if (checkItem.args[2].type === 'MemberExpression') {
} else {
// FIXME: Property may not be a literal/identifier, eg. a[b.c.d]
console.error(`FIXME: Unhandled property type ${checkItem.args[2].type} for HAS_KEY check`);
return;
}
let propNode = {};
// Computed node?
if (checkItem.args[3]) {
propNode.type = 'Identifier';
propNode.name = value;
} else {
propNode.type = 'StringLiteral';
propNode.value = value;
}
if (checkItem.args[2].type === 'MemberExpression') {
propNode = cloneNode(checkItem.args[2]);
}
// Object
const clonedObjNode = cloneNode(checkItem.args[1]);
//const objInitNode = {
// type: 'ObjectProperty',
// key: {
// type: 'Identifier',
// name: 'object'
// },
// value: clonedObjNode,
// kind: 'init'
//};
//setNodeLoc(objInitNode);
//checkItemNode.properties.push(objInitNode);
//// Property
//const objPropNode = {
// type: 'ObjectProperty',
// key: {
// type: 'Identifier',
// name: 'property'
// },
// value: propNode,
// kind: 'init'
//};
//setNodeLoc(objPropNode);
//checkItemNode.properties.push(objPropNode);
checkItemNode.type = 'BinaryExpression';
checkItemNode.operator = 'in';
checkItemNode.left = propNode;
checkItemNode.right = clonedObjNode;
setNodeLoc(checkItemNode);
}
//checkNodeArr.push(checkItemNode);
return checkNodeExpr;
};
const stringifyNode = (node, topNode) => {
if (node.type === 'MemberExpression') {
if (topNode) {
const objStr = stringifyNode(node.object, true);
if (!objStr) return;
return `${objStr}`;
} else {
const objStr = stringifyNode(node.object),
valStr = stringifyNode(node.property);
if (!objStr || !valStr) return;
if (node.computed) {
return `${objStr}[${valStr}]`;
} else {
return `${objStr}.${valStr}`;
}
}
} else if (node.type === 'Identifier') {
return node.name;
} else if (node.type === 'ThisExpression') {
return 'this';
} else if (node.type === 'StringLiteral') {
return node.value;
} else if (node.type === 'NumericLiteral') {
return node.value;
} else if (node.type === 'BinaryExpression') {
const left = stringifyNode(node.left),
right = stringifyNode(node.right);
if (!left || !right) return;
return `${left}${node.operator}${right}`;
}
};
const isSafeIdentifier = (node) => {
let identifier = stringifyNode(node, true);
if (!identifier) return false;
// Global node object?
// FIXME: What about window objects for user? Or mismatch between window/GLOBAL in user/server tests?
if (SafeIdentifiers.indexOf(identifier) >= 0) {
return true;
}
// FIXME: Check against common node libs?
// FIXME: Custom list of global objects in game: Err, Env
};
// isCheckWhitelisted
// Check if we've already whitelisted this check
const isCheckWhitelisted = (checkItem, builtCheck, scopedWhitelist) => {
//let checks = builtCheck.expression.left.arguments[0] .left.argument;
let hashedCheck = '';
let validHashCheck = false;
if (checkItem.checker === IS_TYPE) {
//let check = checks[2];
let check = checkItem.args[0];
if (checkItem.args[1] === OBJECT_TYPE) {
hashedCheck = 'IS_TYPE:OBJECT_TYPE:';
} else if (checkItem.args[1] === FUNCTION_TYPE) {
hashedCheck = 'IS_TYPE:FUNCTION_TYPE:';
}
// Is this a globally safe object?
if (isSafeIdentifier(check)) {
return true;
}
let nodeCheckStr = stringifyNode(check);
if (nodeCheckStr) {
hashedCheck += nodeCheckStr;
validHashCheck = true;
}
} else if (checkItem.checker === HAS_KEY) {
//let obj = checks[1], prop = checks[2];
let obj = checkItem.args[1], prop = checkItem.args[2];
let objCheckStr = stringifyNode(obj.value);
let valCheckStr = stringifyNode(prop.value);
// Is this a globally safe object?
if (isSafeIdentifier(obj.value)) {
return true;
}
if (objCheckStr && valCheckStr) {
hashedCheck = `HAS_KEY:${objCheckStr}:${valCheckStr}`;
validHashCheck = true;
}
}
if (!validHashCheck) {
console.error("FIXME: Unexpected check against whitelist");
return false;
}
// Does this hash exist in our whitelist?
let checkScope = scopedWhitelist;
do {
if (checkScope.whitelist.indexOf(hashedCheck) >= 0) {
return true;
}
checkScope = checkScope.parentScope;
} while (checkScope);
// Not whitelisted? Add to whitelist
scopedWhitelist.whitelist.push(hashedCheck);
return false;
};
// CheckNodeBody
// Check all elements in the body of the node, and handle any preChecks, replacements or hoisting returned from checks
const checkNodeBody = (node, state) => {
const body = node.body;
const thisScope = state.scope;
const innerScope = { parentScope: thisScope, whitelist: [] };
state.scope = innerScope;
const modifyNode = state.modifyNode;
for(let i = 0; i < body.length; ++i) {
// Begin checking this expression
const node = body[i];
const innerModifyNode = new ModifyNode();
let prevLen = body.length;
state.modifyNode = innerModifyNode;
CheckNode(node, null, state);
let lastAssertLine = -2,
lastAssert = null;
// Prepend all preChecks before node
if (innerModifyNode.preCheck.length > 0) {
innerModifyNode.preCheck.forEach((checkItem) => {
// { checker: IS_TYPE, args: [NODE, TYPE] }
// { checker: HAS_KEY, args: [NODE, NODE.OBJECT, NODE.PROPERTY] }
const checkNode = buildNodeFromCheck(checkItem, node.loc);
if (checkNode) {
if (isCheckWhitelisted(checkItem, checkNode, innerScope)) return;
// Can we flatten this assert into the previous line?
if (lastAssertLine === (i - 1)) {
// Find rightmost node and splice as logicalExpression there to branch this check
let rightMostNode = lastAssert.expression, rightMostNodeParent = null;
while (rightMostNode.right && rightMostNode.right.NODE_CHECKTYPE) {
rightMostNodeParent = rightMostNode;
rightMostNode = rightMostNode.right;
}
if (!rightMostNodeParent) {
lastAssert.expression = {
type: 'LogicalExpression',
NODE_CHECKTYPE: true,
left: rightMostNode,
operator: '&&',
right: checkNode.expression
};
} else {
rightMostNodeParent.right = {
type: 'LogicalExpression',
NODE_CHECKTYPE: true,
left: rightMostNode,
operator: '&&',
right: checkNode.expression
};
rightMostNodeParent.right.loc = rightMostNodeParent.loc;
}
// Steal loc from lastAssert
checkNode.loc = lastAssert.expression.loc;
//lastAssert.expression.arguments[0].elements.push(
// checkNode.expression.arguments[0].elements[0]
//);
} else {
lastAssertLine = i;
lastAssert = checkNode;
body.splice(i, 0, checkNode);
++i;
}
}
});
if (lastAssert && lastAssert.loc) {
let source = codeLines[lastAssert.loc.start.line - 1];
if (source) {
source = source.trim();
let rightMostNode = lastAssert.expression, rightMostNodeParent = null;
while (rightMostNode.right && rightMostNode.right.NODE_CHECKTYPE) {
rightMostNodeParent = rightMostNode;
rightMostNode = rightMostNode.right;
}
const sourceNodeDebug = {
type: 'StringLiteral',
value: source
};
if (!rightMostNodeParent) {
lastAssert.expression = {
type: 'LogicalExpression',
NODE_CHECKTYPE: true,
left: rightMostNode,
operator: '&&',
right: sourceNodeDebug
};
} else {
rightMostNodeParent.right = {
type: 'LogicalExpression',
NODE_CHECKTYPE: true,
left: rightMostNode,
operator: '&&',
right: sourceNodeDebug
};
rightMostNodeParent.right.loc = rightMostNodeParent.loc;
}
}
}
}
// Replace node with replacement nodes
if (innerModifyNode.replaceNode.length > 0) {
const leadingComments = node.leadingComments;
for (let j = 0; j < innerModifyNode.replaceNode.length; ++j) {
// TODO: This is a poor way to see if this is a check or an actual node
if (innerModifyNode.replaceNode[j].checker) {
const checkItem = innerModifyNode.replaceNode[j];
const replaceNode = buildNodeFromCheck(checkItem, node.loc);
innerModifyNode.replaceNode[j] = replaceNode;
if (!replaceNode) {
innerModifyNode.replaceNode.splice(j, 1);
--j;
} else if (isCheckWhitelisted(checkItem, replaceNode, innerScope)) {
innerModifyNode.replaceNode.splice(j, 1);
--j;
// FIXME: We only want to remove checks, not the replaced variableDeclaration
}
}
}
body[i].leadingComments = leadingComments;
body.splice(i, 1, ...innerModifyNode.replaceNode);
i += innerModifyNode.replaceNode.length - 1;
}
// Hoist nodes to the top
if (innerModifyNode.hoistNodes.length > 0) {
for (let j = 0; j < innerModifyNode.hoistNodes.length; ++j) {
body.splice(0, 0, ...innerModifyNode.hoistNodes);
i += innerModifyNode.hoistNodes.length;
}
}
}
state.modifyNode = modifyNode;
state.scope = thisScope;
};
let gUid = 0;
const Assertion = (assertList, assertion, scope) => {
// whitelist: array of subsequent inner scopes, each an array of assertions. Check whitelist from innermost -> outermost
let assertionHash = "";
// FIXME: Come up with a unique hash for the assertion (checker: args: [node, ...])
// - Could recursively traverse through node and hash that node, then mix w/ child node hashes
// - Can mark each node w/ a uid of that hash (if it isn't marked already); that way in the future if we come
// across a uid in a node, we can skip hashing that one
// - Then hash the check itself and mix with the node hash: "AAA_BBBBBBBBBBB" AAA is checker hash, BBBBBBBBB is
// node hash
//
// As we hit nodes add scopedNode and point that node to scopedNode. If scopedNode already exists then point node
// to that scopedNode. Use scopedNode for scopedWhitelist
//
// OR we could do this during assertion build up time: pass a scope id to Assertion, and then add that scope to
// assertion object. Assertions are built linearly so we should go through scopes in order; however if we ever do
// parallelize this then we can order assertions before processing (in which case only this way would work). Then
// processing assertions we build whitelist as we process and store that whitelist in scope
//
// scope: { parentScope: ..., scopeWhitelist: [] }
assertion.scope = scope;
// FIXME: This won't work, because
// Env.a = 1;
// Env.b = 2; // Both of these are different nodes for Env
//const getNodeId = (node) => {
// if (node.uid) return node.uid;
// node.uid = gUid++;
//};
//let checkerHash = 10 * (assertion.checker === HAS_KEY ? 1 : 2);
assertList.push(assertion);
};
// CheckNode
// Recursively build checks through the node based off the type, and any children nodes it may have
//const CheckNode = (curNode, expectType, modifyNode, topLevel, scopeNode, scopedWhitelist) => {
const CheckNode = (curNode, expectType, state) => {
//let codeStr = "";
//if (curNode.start && curNode.end) {
// code.substr(curNode.start, curNode.end - curNode.start);
//}
let codeStr = code.substr(curNode.start, curNode.end - curNode.start);
if (curNode.type === 'Program') {
// Top-most node in the file
checkNodeBody(curNode, state);
} else if (curNode.type === 'ExpressionStatement') {
// We're assuming ExpressionStatement is the entire expression, and cannot contain an
// ExpressionStatement
const computed = CheckNode(curNode.expression, null, state);
return computed;
} else if (curNode.type === 'MemberExpression') {
// FIXME: Should confirm curNode.object is NOT a CallExpression (lint)
let computed = CheckNode(curNode.object, OBJECT_TYPE, state);
if (computed) {
//console.error("FIXME: Computed node in MemberExpression");
// eg. extendClass(this).with(that)
// $(el).position
return true;
}
// Property may be an object
// I believe the only way this could happen is if its an array: a.b.c[XXXXXX]
if (curNode.property.type === 'MemberExpression') {
// FIXME: We may want an IS_NOT_NULL check here
// FIXME: may also want IS_NOT_COMPUTED lint check here eg. a[c()], a[b ? c() : d+1]
computed = CheckNode(curNode.property, null, state);
}
if (computed) {
//console.error("FIXME: Computed node in MemberExpression");
return true;
}
if (expectType !== null) {
// We'll need to handle checks on member expressions in 2 different ways:
// FIXME: Better to have a check for is prop is an identifier or literal, or maybe
// curNode.computed works?
// a.b ===> a.hasOwnProperty('b')
// a[b] ===> a.hasOwnProperty(b) // computed
const propComputed = curNode.computed;// curNode.property.type === 'MemberExpression';
// FIXME: Can we get rid of the HAS_KEY check? Since we're about to check that prop is an object anyways, we
// can piggyback off that check
//let preCheck = {
// checker: HAS_KEY,
// args: [curNode, curNode.object, curNode.property, propComputed]
//};
//Assertion(state.modifyNode.preCheck, preCheck, state.scope);
preCheck = {
checker: IS_TYPE,
args: [curNode, OBJECT_TYPE]
};
Assertion(state.modifyNode.preCheck, preCheck, state.scope);
}
return false;
} else if (curNode.type === 'CallExpression') {
const safeCallObjectTypes = ['MemberExpression', 'ThisExpression', 'Identifier'];
if (curNode.callee.object && safeCallObjectTypes.indexOf(curNode.callee.object.type) === -1) {
// eg. CallExpression: GetTile().LocalPos()
console.error("FIXME: Unexpected call object type " + curNode.callee.object.type);
return false;
}
// If curNode.callee is computed, we can't proceed any further
const computed = CheckNode(curNode.callee, null, state);
if (computed) {
// eg. do(this).then(that);
return true;
}
// In some cases we can't or don't want to bother checking the callee
// eg. var a = ((() => return { a: 1 })())
const safeFunctionCallees = ['Identifier', 'MemberExpression'];
if (safeFunctionCallees.indexOf(curNode.callee.type) !== -1) {
let preCheck = {
checker: IS_TYPE,
args: [curNode.callee, FUNCTION_TYPE]
};
Assertion(state.modifyNode.preCheck, preCheck, state.scope);
}
// Check arguments in call
curNode.arguments.forEach((callArg) => {
CheckNode(callArg, null, state);
});
return true;
} else if (curNode.type === 'Identifier') {
if (expectType !== null) {
let preCheck = {
checker: IS_TYPE,
args: [curNode, expectType]
};
Assertion(state.modifyNode.preCheck, preCheck, state.scope);
}
return false;
} else if (curNode.type === 'ObjectExpression') {
curNode.properties.forEach((objProp) => {
if (objProp.type === 'ObjectProperty') {
CheckNode(objProp.value, null, state);
} else if (objProp.type === 'ObjectMethod') {
CheckNode(objProp.body, null, state);
}
});
} else if (curNode.type === 'ArrayExpression') {
curNode.elements.forEach((objElem) => {
CheckNode(objElem, null, state);
});
} else if (curNode.type === 'AssignmentExpression') {