-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathZeon.js
executable file
·4903 lines (4486 loc) · 200 KB
/
Zeon.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
// http://testsuites.opera.com/JSON/performance/001.html
// http://krakenbenchmark.mozilla.org/
// http://cs.au.dk/~amoeller/papers/jsrefactor/
// http://wingolog.org/archives/2011/08/02/a-closer-look-at-crankshaft-v8s-optimizing-compiler
// http://www.mail-archive.com/[email protected]/msg09590.html
// funfuzz http://www.squarefree.com/2007/08/02/introducing-jsfunfuzz/ http://www.squarefree.com/categories/fuzzing/
//what you actually should do is that whenever an assignment is found, the type tracking should return
//the expression and the type of the expression extracted at a later point. this would complicate limiting
//operators though, specifically the + and +=. not sure but i'll have to somehow resolve that later.
// tofix: legacy typing may be thrown out...
// tofix: flow stuff for break with label...
// tofix: properly handle +=, rather than chicken out
// H certain operators are static too (void, typeof on primitives), take into account with static expressions
// M if some token is an array and .push or .unshift is called on on it, maybe add the type to the array types too...
// M rewriter tool should accept granularity
// M with
// M highlight all search hits
// M variable grouping tool should crop trailing whitespace generated by the tool, and it should re-connect single variable declarations if immediately followed by an initializer
// L top padding issue so that it behaves the same regardless of where zeon is used. maybe use caret popup to match alignment
// L fix cli integration in node and whatever
// L this should be an error... for (x=5 in o) ... is illegal; lhs assignments in for-in must be warpped in parens
// L branch coverage tool ( http://ged.msu.edu/courses/2009-fall-cse-491/cse491-2009-lab10.html )
// L code coverage tool
// L remove blocks under a certain condition (if (debug) ...)
// L remove single-statement non-required blocks: if (foo) { bar; }
// L static dead code (like if(false) ...)
// L alternative jsdoc syntax
// L evals ( http://kangax.github.com/jstests/indirect-eval-testsuite/ )
// L folding
// L warn for dangerous asi's (simple patterns)
// L remember values (if var x = y; and x is determined to have certain properties later, y should probably get them as well) --> value tracking
// L concrete typing; using tokens for types until they have been resolved, solving the lookahead problem
// L strict mode: http://www.java-script.limewebs.com/strictMode/test_hosted.html
// L http://www.rkcole.com/articles/other/CodeMetrics-CCN.html
// L aggressive dead code checks; is a function called?
// L investigate undo stack stuff... i think its a mine-field, but whatever
// jsdoc:
// http://code.google.com/intl/nl/closure/compiler/docs/js-for-compiler.html#types
// http://code.google.com/p/jsdoc-toolkit/
// http://code.google.com/p/jsdoc-toolkit/wiki/FAQ
// extension fun
/*
http://blog.mozilla.com/addons/2011/06/21/add-on_sdk-builder-_beta/
https://builder.addons.mozilla.org/
http://twitter.com/paul_irish/statuses/85092057659604992
http://code.google.com/chrome/extensions/experimental.webInspector.panels.html
http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/api/tabs/inspector/tabs_api.html?content-type=text/plain
*/
var Zeon = function(input, config){
this.scopes = [];
this.lastInput = input;
this.config = config || {};
};
Zeon.getNewConfig = function(){
return {
// general
'zeon visual output': true,
// visual
'warnings': true,
'markers': true,
'scope depth': true,
'warn if scope depth exceeds': 2,
'ruler': true,
'type annotations': true,
'trailing whitespace cue': true,
// tooling
'caret popup': true,
'dim undefined ifdefs': true,
'minify variable names too': true,
'minify property names too': true,
'minify property names always': false,
'minify uses newlines for semis': true,
'hoisting fix moves func decl to top': true,
'load saved code at start': true,
// ==== warning toggles ====
'missing block good': true,
'missing block bad': true,
'assignment in header': true,
'weak comparison': true,
'dangling underscore': true,
'dot and not can be confusing': true,
'inc dec operator': true,
'comma in group makes inc/dec fail': true,
'binary operator': true,
'use dot access': true,
'continue only in loops': true,
'break needs loop or label': true,
'return only in function': true,
'trailing decimal': true,
'leading decimal': true,
'regex confusion': true,
'number dot': true,
'assignment bad': true,
'assignment this': true,
'bad string escapement': true,
'unlikely regex escapement': true,
'avoid hex': true,
'caller callee': true,
'octal escape': true,
'00': true,
'regexp call': true,
'confusing plusses': true,
'confusing minusses': true,
'double bang': true,
'control char': true,
'unsafe char': true,
'invalid unicode escape in string': true,
'invalid unicode escape in regex': true,
'invalid hex escape in string': true,
'invalid hex escape in regex': true,
'catch var assignment': true,
'bad constructor': true,
'array constructor': true,
'error constructor': true,
'very bad constructor': true,
'Function is eval': true,
'function wrapped': true,
'document.write': true,
'iteration function': true,
'empty block': true,
'eval': true,
'empty regex char class': true,
'extra comma': true,
'double new': true,
'double delete': true,
'undefined': true,
'duplicate objlit prop': true,
'timer eval': true,
'group vars': true,
'func decl at top': true,
'is label': true,
'math call': true,
'new wants parens': true,
'missing radix': true,
'nested comment': true,
'new statement': true,
'dont use __proto__': true,
'empty switch': true,
'quasi empty switch': true,
'empty clause': true,
'clause should break': true,
'switch is an if': true,
'unwrapped for-in': true,
'in out of for': true,
'use {}': true,
'use []': true,
'double block': true,
'useless block': true,
'use capital namespacing': true,
'constructor called as function': true,
'cannot inc/dec on call expression': true,
'inc/dec only valid on vars': true,
'bad asi pattern': true,
'unlikely typeof result': true,
'weird typeof op': true,
'typeof always string': true,
'static expression': true,
'static condition': true,
'pragma requires name parameter': true,
'pragma requires value parameter': true,
'missing ifdef': true,
'missing inline': true,
'pragma start missing end': true,
'macro name should be identifier': true,
'is dev relic': true,
'multiple operators on same level': true,
'useless multiple throw args': true,
'unnecessary parentheses': true,
'uninitialized value in loop': true,
'jsdoc type mismatch': true,
'prop not declared on proto': true,
'trailing comma': true,
'ASI': true,
'empty statement': true,
'premature usage': true,
'unused': true,
'dead code': true,
'useless parens': true,
'known implicit global': true,
'unknown implicit global': true,
'duplicate label': true,
'label not found': true,
'silly delete construct': true,
'delete not a function': true,
'weird delete operand': true,
'cannot call/apply that': true,
'func expr name is read-only': true
};
};
Zeon.getUniqueItems = function(arr){
var newarr = [];
if (!arr) return [];
for (var i=0; i<arr.length; ++i) {
if (newarr.indexOf(arr[i]) < 0) newarr.push(arr[i]);
}
return newarr;
};
Zeon.uniqueInline = function(arr){
// filter arr and make sure it only has unique occurrences
for (var i=0; i<arr.length-1; ++i) {
var j = arr.length;
while (--j > i) {
if (arr[i] == arr[j]) {
arr.splice(j, 1);
}
}
}
// arr should now only contain unique var names
};
Zeon.uniqueNamesByValue = function(arr){
var newarr = [];
for (var i=0; i<arr.length; ++i) {
var found = false;
for (var j=0; j<newarr.length; ++j) {
if (newarr[j].value == arr[i].value) {
found = true;
break;
}
}
if (!found) newarr.push(arr[i]);
}
return newarr;
};
Zeon.prototype = {
config: null,
// source
lastInput: '',
tree: null,
tokenizer: null,
parser: null,
hasError:null,
lastJsdoc:null,
root: null,
scopes:null,
globalScope: null,
collects: null,
pragmas: null,
has: {}.hasOwnProperty,
hasOwn: function(obj, key){ return this.has.call(obj, key); }, //#macro this.hasOwn this.has.call
regexEcma: /^Object$|^Array$|^String$|^Number$|^Boolean$|^Date$|^Function$|^RegExp$|^Error$|^arguments$|^Math$|^JSON$|^parseInt$|^parseFloat$|^isFinite$|^isNaN$|^undefined$|^eval$|^true$|^false$|^null$/,
regexBrowser: /^document$|^window$|^setTimeout$|^setInterval$|^clearInterval$|^clearTimeout$|^console$|^navigator$|^Image$|^alert$|^confirm$|^XMLHttpRequest$/,
regexDevSigns: /^console$|^log$|^debug$|^debugger$|^alert$|^foo$|^bar$|^baz$|^boo$|^tmp$|^temp$|^test$/,
regexBuiltinObjects: /^Object$|^Array$|^String$|^Number$|^Boolean$|^Date$|^Function$|^RegExp$|^Error$|^Math$|^JSON$/,
regexBuiltinBadConstructors: /^Object$|^Array$|^String$|^Number$|^Boolean$|^Function$|^RegExp$|^Error$|^Math$|^JSON$/,
regexBinaryOps: /^\&$|^\|$|^\^$|^\~$|^<<$|^>>$|^>>>$/,
regexControlChars: /[\u0000-\u001F]/,
regexStringEscapement: /(?:^|[^\\])\\[^'"\\bxfnrtvu]/, // first group is to make sure prev char is not a backslash
regexRegexEscapement: /(?:^|[^\\])\\[^$\\\/.*+?()[\]{}|\^fnrtvdDsSwWu\-]/, // first group is to make sure prev char is not a backslash
regexBoolOps: /^<=$|^>=$|^<$|^>$|^==$|^!=$|^===$|^\!==$|^in$|^instanceof$/,
regexNumberOps: /^\*=?$|^\/=?$|^%=?$|^-=?$|^<<=?$|^>>>=?$|^\&=?$|^\|=?$|^\^=?$/,
regexInvalidUnicodeEscape: /\\u[0-9A-Fa-f]{0,3}[^0-9A-Fa-f]/,
regexInvalidHexEscape: /\\x[0-9A-Fa-f]?[^0-9A-Fa-f]/,
regexToDoFix: /(todo)|(tofix)|(fixme)|(to-do)/i,
regexPragmas: /^\/\/#((?:define)|(?:(?:else)?ifdef)|(?:elsedef)|(?:endif)|(?:macro)|(?:f?inline)|(?:f?endline))(?:\s+(\S+)(?:\s+(.+))?)?/i, // optionally also match the args
regexValidMacro: /^[a-zA-Z\$_](?:\.?[a-zA-Z0-9\$_])+$/, // macros may contain dots but must otherwise be valid identifiers / property access
// http://tech.groups.yahoo.com/group/jslint_com/message/22
regexUnsafeCharacters: /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/,
// [*] @(name)[ ((param)[ (param)[ (rest)]]])
// result: [match, name, rest-after-name, param1, param2, rest-after-params]
regexJsDoc: /^(\s*\/?\**\s*)(\@)([a-zA-Z0-9]+)(?:(\s+)(([^\s]+)(?:(\s+)([^\s]+)(?:(\s+)(.+))?)?))?$/,
regexJsDocScrub: /^(.*)?\s*\*+\/\s*$/, // removes trailing */ if it exists
// https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence
// this only contains binary operators.
// only ternary (?:) and assignments are right associative: x=y=z => x=(y=z). ternary is done implicitly by the parser
// and assignments explicitly :) so all others are left associative (when precedence is equal, evaluate left to right)
precedence: {
'*':1, '/':1, '%':1,
'+':2, '-':2,
'<<':3, '>>':3, '>>>':3,
'<':4, '<=':4, '>':4, '>=':4, 'in':4, 'instanceof':4,
'==':5, '!=':5, '===':5, '!==':5,
'&':6,
'^':7,
'|':8,
'&&':9,
'||':10,
'?':11, ':':11, // always put ? left of :
'=':12, '<<=':12, '>>=':12, '>>>=':12, '+=':12, '-=':12, '*=':12, '/=':12, '%=':12, '&=':12, '^=':12, '|=':12,
',':13
},
// initialized during process
_currentLine: null, // temp during process, refs the top of the lines array
lines: null, // an array of arrays, for each line contains the tokens in that line. each line array has a start and stop property, referring to the input length
wtree: null, // all tokens of the parse tree in a single linear array
btree: null, // also all tokens in single array, but without "whitespace" (WhiteSpace, LineTerminators, Comments)
// order flow statements from weak to strong.
IS_CONTINUE: 1, //#macro this.IS_CONTINUE 1
IS_BREAK: 2, //#macro this.IS_BREAK 2
IS_LABELED_BREAK: 3, //#macro this.IS_LABELED_BREAK 3
IS_RETURN: 4, //#macro this.IS_RETURN 4
IS_THROW: 5, //#macro this.IS_THROW 5
// parsing phase (directive, var, func, rest)
PHASE_DIRECTIVE: 0, //#macro this.PHASE_DIRECTIVE 0
PHASE_VAR: 1, //#macro this.PHASE_VAR 1
PHASE_FUNC: 2, //#macro this.PHASE_FUNC 2
PHASE_REST: 3, //#macro this.PHASE_REST 3
getProperFunctionName: function(token){
// function foo(){}
if (token.isFuncDeclKeyword) {
// there is just one keyword responsible for this function. use it.
var name = token.funcName;
} else if (token.isFuncExprKeyword) {
// look for these patterns:
// var foo = function(){}
// foo = function(){}
// obj.foo = function(){}
// (foo) = fu...
// (obj.foo) = fu...
// {foo: function(){} }, foo may not be a label (would be bad anyways)
// {"foo": function(){} }
// {599: function(){} }
// so the previous token should be a colon or an equal sign. else we stop
// (ps: a function expression must be preceeded by at least some token, else it would be a decl)
var btree = this.btree;
var prev = btree[token.tokposb-1];
if (prev.value == '=' || prev.value == ':') {
var name = btree[token.tokposb-2];
} else if (prev.value != '(' && prev.value != '+' && prev.value != 'new' && prev.value != ',' && prev.value != '?' && prev.value != ':' && prev.value != '[' && prev.value == 'in' && !prev.forEachHeaderStop) {
if (!this.hasError) console.error("getProperFunctionName: Expected a colon or assignment before, was", 'prev', prev.value, prev, 'token', token.value, token, 'same?',token==prev, [this.lastInput]);
}
} else {
if (!this.hasError) console.warn(['unknown function type. expected func or expr, found neither.', token,[this.lastInput]]);
}
return name;
},
getJspath: function(match, absolute){
// for jspath:
// object properties get dot
// scopes are denoted by /
// global scope causes all paths to start with /
// prototype methods get # (for any path, simply replace ".prototype." with a hash (#))
// catch variable get a ! prefix: foo!e (catch var is usually the end of the line anyways)
// all functions can also be addressed with (n), where n is the nth function defined like that in the current scope
// likewise, you can address objects like {n}
// likewise, you can address arrays like [n]
// the (n), {n} and [n] will safely give you an absolute path, where naming might not (assignment of two object literals to the same var)
// if there are multiple occurrences and you want a specific one, they are indexed like arrays: foo>str[2] is the third mention of str in the function foo
// if there's a dynamic property that's static but illegal identifier, just quote it after the dot: obj."illegal stuff">foo
// obj.foo = function(){ function Person(){} Person.prototype.print = function(){ out = ""; alert('jspath', out.length); }; };
// jspath for out.length would be:
// obj.foo>Person#print>out.length
if ((absolute && !match.jspathAbsolute) || (!absolute && !match.jspathRelative)) {
var returnValue = '[unknown]';
if (match.global) returnValue = '/';
else if (match.scopeFor) {
returnValue = this.getJspath(match.scopeFor, absolute)+'/';
} else if (match.isObjectLiteralStart) {
var name = this.getProperObjectName(match);
if (name && !absolute) returnValue = this.getJspath(name, absolute);
else returnValue = this.getJspath(match.targetScope, absolute)+'{'+match.objectId+'}';
} else if (match.isArrayLiteralStart) {
returnValue = this.getJspath(match.targetScope, absolute)+'['+match.arrayId+']';
} else if (match.isPropertyOf) {
// forgot why i'm checking explicitly for an object literal start... :)
//if (match.isPropertyOf.isObjectLiteralStart) returnValue = this.getJspath(match.isPropertyOf)+'.'+match.value;
//else
returnValue = this.getJspath(match.isPropertyOf, absolute)+'.'+match.value;
} else if (match.functionId >= 0) {
var name = this.getProperFunctionName(match);
if (name && !absolute) returnValue = this.getJspath(name, absolute);
else returnValue = this.getJspath(match.scope[0], absolute)+'('+match.functionId+')';
} else if (match.value) {
if (match.catchId >= 0) returnValue = this.getJspath(match.targetScope, absolute)+'!'+match.catchId;
else if (!match.targetScope) {
// console.log('No scope ref found (happens for object literal properties and property names with dynamic access before it)');
// console.log("for error", match);
// throw "every ref should have a scope ref...";
} else if (!match.targetScope.isGlobal) {
returnValue = this.getJspath(match.targetScope, absolute)+match.value;
} else {
returnValue = '/'+match.value;
}
} else {
if (!this.hasError) console.log(["getJspath problem", match, this.lastInput]);
}
if (absolute) match.jspathAbsolute = returnValue.replace(/\.prototype\./g, '#');
else match.jspathRelative = returnValue.replace(/\.prototype\./g, '#');
}
if (absolute) return match.jspathAbsolute;
return match.jspathRelative;
},
getProperObjectName: function(token){
// look for these patterns:
// var foo = {}
// obj.foo = {}
// {foo: {} }, foo may not be a label (would be bad anyways)
// so the previous token should be a colon or an equal sign. else we stop
// (ps: a objects must be preceeded by at least some token, else it would be a block)
var nwtree = this.btree;
var prev = nwtree[token.tokposb-1];
if (prev.value == '=' || prev.value == ':') {
var name = nwtree[token.tokposb-2];
} else if (prev.value != '(' && prev.value != ',') {
if (!this.hasError) console.log("getProperObjectName: Expected a colon or assignment before, was", 'prev', prev.value, prev, 'token', token.value, token, 'same?',token==prev,[this.lastInput]);
}
return name;
},
//#ifdef DEV_MODE (not meant for release)
/**
* Quickly create a tokenstream from the (raw) parse tree.
* The function walks the parse tree and puts all non-whitespace
* tokens in an array and returns that array.
* You can use this to get the two arrays without running the other zeon stuff
* @recursive
* @param {Array} stack
* @param {string|undefined} input when supplied, all tokens that dont have a value property will get it (contains the actual string they span)
* @param {Array|undefined} noWhite will contain actual "token stream", so without the whitespace tokens (that also excludes line terminators and comments)
* @param {Array|undefined} all will contain any token of the input source
* @return {Array|undefined} noWhite||all
*/
toTokenStream: function(stack, input, noWhite, all){
for (var i=0; i<stack.length; ++i) {
var token = stack[i];
if (token instanceof Array) {
this.toTokenStream(token, input, noWhite, all);
} else {
// set .value if not already (and input source was given)
if (input && !token.value) {
token.value = input.substring(token.start, token.stop);
}
// create list with all tokens, if all array is supplied
if (all) {
all.push(token);
}
// create actual token stream, if noWhite array is supplied
if (noWhite && token.name != 7/*COMMENT_SINGLE*/ && token.name != 9/*WHITE_SPACE*/ && token.name != 8/*COMMENT_MULTI*/ && token.name != 10/*LINETERMINATOR*/) {
noWhite.push(token);
}
}
}
return noWhite||all;
},
//#endif
parse: function(){
this.tokenizer = new Tokenizer(this.lastInput);
this.tree = [];
this.wtree = this.tokenizer.wtree;
this.btree = this.tokenizer.btree;
this.parser = new ZeParser(this.lastInput, this.tokenizer, this.tree);
this.parser.parse();
this.hasError = this.tokenizer.errorStack.length || this.parser.errorStack.length;
},
startProcess: function(){
this.reset();
// we need the global scope to track the implicit globals we encounter
var globalScope = this.globalScope = this.tree.scope;
// adds known "auto-globals" to the global scope. prevents lookup misses
this.addEcmaBuiltIns(globalScope);
// actual post-processing
var start = Date.now();
this.phase1(this.tree);
var one = Date.now() - start;
start = Date.now();
this.phase2(this.tree);
var two = Date.now() - start;
start = Date.now();
this.phase3(this.tree);
var three = Date.now() - start;
start = Date.now();
this.extraTyping(this.tree);
var four = Date.now() - start;
this._currentLine.stop = this.lastInput.length;
delete this._currentLine;
return [one,two,three,four];
},
reset: function(){
// root of recursive call tree
this._currentLine = [];
this._currentLine.lineId = 0;
this._currentLine.start = 0;
this.lines = [this._currentLine];
// problem tracking
this.collects = {
errors: [],
warnings: [],
implicitGlobals: [], // all unexpected variable references which can not be found in a scope reachable from that position
knownGlobals: [], // all ecma and browser globals
jsdocs: [],
functions: [],
objlits: [],
arrlits: [],
todofix: [], // todo, tofix, fixme
pragmas: [], // define, ifdef, endif, macro, inline, endline
defines: [] // collection of defined tokens with #define <token>
};
this.pragmas = {
ifdefs: [],
inlines: [],
inlineNames: [],
macros: []
};
},
addEcmaBuiltIns: function(scope){
// this is not everything, just some more common ones. common dom apis, html5 apis, etc.
// http://code.google.com/p/closure-compiler/source/browse/#svn%2Ftrunk%2Fexterns
var nodejs = [
['require','Function'],
['module','Object',[
['exports','Object']
]]
];
// http://www.whatwg.org/specs/web-apps/current-work/multipage/browsers.html#window
var browsers = [
['window','Object',null,null,true],
['global','Object',null,null,true],
// Timer api
[[
'setTimeout',
'clearTimeout',
'setInterval',
'clearInterval'
],'Function'],
// File api (and related)
[[
'Blob',
'File',
'FileError',
'FileList',
'FileReader'
],'Function', null, true],
// crypto
['crypto','Function'],
// web sockets
['WebSocket','Function', null, true],
// ajax
[[
'XMLHttpRequest',
'XDomainRequest',
'XMLHttpRequestUpload'
],'Function', null, true],
// storage
[[
'globalStorage',
'localStorage',
'openDatabase',
'sessionStorage',
'applicationCache'
],'Function'],
// web workers
[[
'Worker',
'MessageChannel',
'MessageEvent',
'MessagePort',
'SharedWorker'
],'Function', null, true],
['postMessage','Function'], // not a constructor
// general
[[
'ActiveXObject',
'addEventListener',
'alert',
'atob',
'attachEvent',
'back',
'blur',
'btoa',
'close',
'confirm',
'detachEvent',
'dispatchEvent',
'escape',
'execScript',
'find',
'focus',
'forward',
'getAttention',
'getComputedStyle',
'getSelection',
'home',
'Image',
'innerHeight',
'innerWidth',
'open',
'openDialog',
'outerHeight',
'outerWidth',
'pageXOffset',
'pageYOffset',
'print',
'prompt',
'Range',
'releaseEvents',
'removeEventListener',
'scrollByLines',
'scrollByPages',
'scrollX',
'scrollY',
'Selection',
'showModelDialog',
'stop',
'TimeRanges',
'unescape',
'XMLDOMDocument'
],'Function'],
[[
'console',
'document',
'event',
'external',
'find',
'frameElement',
'frames',
'history',
'length',
'location',
'locationbar',
'menubar',
'navigator',
'name',
'opener',
'parent',
'personalbar',
'screen',
'screenX',
'screenY',
'scrollbars',
'self',
'status',
'statusbar',
'toolbar',
'top',
'undoManager'
],'Object']
];
var ecmas = [
['NaN','number'],
['Infinity','number'],
['undefined','undefined'],
['eval','Function'],
['parseInt','Function'],
['parseFloat','Function'],
['isNaN','Function'],
['isFinite','Function'],
['decodeURI','Function'],
['decodeURIComponent','Function'],
['encodeURI','Function'],
['encodeURIComponent','Function'],
['String','Function',[
['prototype','Object',[
[[
'toString',
'valueOf',
'charAt',
'charCodeAt',
'concat',
'indexOf',
'lastIndexOf',
'localeCompare',
'match',
'replace',
'search',
'slice',
'splice',
'substring',
'toLowerCase',
'toLocaleLowerCase',
'toUpperCase',
'toLocaleUpperCase',
'trim'
], 'Function']
]],
['fromCharCode', 'Function'],
['length', 'number']
], true],
['Number', 'Function', [
['prototype', 'Object', [
[[
'toString',
'valueOf',
'toLocaleString',
'toFixed',
'toExponential',
'toPrecision'
], 'Function']
]],
[[
'MIN_VALUE',
'MAX_VALUE',
'NaN',
'POSITIVE_INFINITY',
'NEGATIVE_INFINITY'
], 'number']
], true],
['Boolean','Function',[
['prototype','Object',[
[['toString','valueOf'],'Function']
]]
],true],
['Function','Function',[
['prototype','Object',[
[[
'toString',
'apply',
'call',
'bind'
],'Function']
]]
],true],
['Array','Function',[
['prototype','Object',[
[[
'toString',
'toLocaleString',
'concat',
'join',
'pop',
'push',
'reverse',
'shift',
'slice',
'sort',
'splice',
'unshift',
'indexOf',
'lastIndexOf',
'every',
'some',
'forEach',
'map',
'filter',
'reduce',
'reduceRight'
],'Function']
]],
['isArray','Function'],
['length','number']
],true],
['RegExp','Function',[
['prototype','Object',[
[['exec','test','toString'],'Function']
]],
['length','number']
],true],
['Date','Function',[
['prototype','Object',[
[[
'toString',
'toDateString',
'toTimeString',
'toLocaleString',
'toLocaleDateString',
'toLocaleTimeString',
'valueOf',
'getTime',
'getFullYear',
'getUTCFullYear',
'getMonth',
'getUTCMonth',
'getDate',
'getUTCDate',
'getDay',
'getUTCDay',
'getHours',
'getUTCHours',
'getMinutes',
'getUTCMinutes',
'getSeconds',
'getUTCSeconds',
'getMilliseconds',
'getUTCMilliseconds',
'getTimezoneOffset',
'setTime',
'setMilliseconds',
'setUTCMilliseconds',
'setSeconds',
'setUTCSeconds',
'setMinutes',
'setUTCMinutes',
'setHours',
'setUTCHours',
'setDate',
'setUTCDate',
'setMonth',
'setUTCMonth',
'setFullYear',
'setUTCFullYear',
'toUTCString',
'toISOString',
'toJSON'
],'Function']
]],
['length','number'],
['parse','Function'],
['UTC','Function'],
['now','Function']
],true],
['Math','Object',[
[[
'E',
'LN10',
'LN2',
'LOG2E',
'LOG10E',
'PI',
'SQRT1_2',
'SQRT2'
],'number'],
[[
'abs',
'acos',
'asin',
'atan',
'atan2',
'ceil',
'cos',
'exp',
'floor',
'log',
'max',
'min',
'pow',
'random',
'round',
'sin',
'sqrt',
'tan'
],'Function']
]],
['JSON','Object',[
['parse','Function'],
['stringify','Function']
]],
['Object','Function',[
['prototype','Object',[
[[
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable'
],'Function']
]],
[[
'getPrototypeOf',
'create',
'defineProperty',
'defineProperties',
'seal',
'freeze',
'preventExtensions',
'isSealed',
'isFrozen',
'isExtensible',
'keys'
],'Function']
],true]
];
var addProperties = function(props, obj){
obj.properties = {};
props.forEach(function(prop){
if (typeof prop[0] == 'string') prop[0] = [prop[0]]; // make sure the first item is an array (of names)
prop[0].forEach(function(name){
var probj = {
value: name,
varType: [prop[1]]
};
if (prop[2]) addProperties(prop[2], probj);
obj.properties[name] = probj;
});
});
};
var addGlobal = function(item,forBrowser){
if (!(item[0] instanceof Array)) item[0] = [item[0]];
item[0].forEach(function(name){
var obj = {
implicit: true,
isDeclared: true,
value: name,
varType: [item[1]]
};
if (forBrowser) obj.isBrowser = true;
else obj.isEcma = true;
// properties
if (item[2]) addProperties(item[2], obj);
// is constructor
if (item[3]) {
obj.isConstructor = true;
obj.constructorName = item[0];
}
// is global
if (item[4]) obj.isGlobalObject = true;
scope.push(obj);
});
};
browsers.forEach(function(o){ addGlobal(o, true); });
nodejs.forEach(function(o){ addGlobal(o, true); });
ecmas.forEach(function(o){ addGlobal(o); });
},
addWarning: function(token, msg){
if (!token.warning) token.warning = msg;
if (!token.warnings) token.warnings = [];
token.warnings.push(msg);
},
hasWarning: function(token, msg){
return token.warning == msg || (token.warnings && token.warnings.indexOf(msg) >= 0);
},
/**
* Post parser processing. First phase. Takes care of anything that
* doesn't require knowledge about the future of the code. This includes:
* - makes scope contents unique
* - disambiguates expressions
* - jsdoc attachment (processing in phase 2)
* - some warning detection
* - make sure token.value is present on all tokens
* - fill both linear trees
* - assign line number per token
* - collect special tokens (asis, jsdocs, etc)
* - process variable declarations
* - process lead values
* - make sure all lead values and declared vars have a trackingObject
* - check identifiers for being known (ecma, browser, dev, etc)
* - do line administration
*
* @param {Object[]} stack Branch of the parse tree
* @param {Object[]} [_scope] Contains all variables and outer scopes reachable from current code (inc. this and if applicable also arguments)
* @param {String[]} [_labels] Contains all valid labels from the current code (break, continue)
* @param {boolean} [_insideConditional] Are we currently inside condition? like the if or while statement header... warning stuff for =
* @param {boolean} [_insideFunction] Are we currently inside any function? Check for return keyword
* @param {boolean} [_insideSwitch] Are we currently inside a switch? Allows anonymous break
* @param {boolean} [_insideIteration] Are we currently inside an iteration? Allows anonymous break and continue and warns for functions
* @param {number} [_phase] Indicates whether we want to parse a string, var, func or other
*/
phase1: function(stack, _scope, _labels, _insideConditional, _insideFunction, _insideSwitch, _insideIteration, _phase){
if (!_phase) _phase = 0;
// all variables have been tracked and locked into their corresponding scope by the parser
if (stack.scope) {
// entering new scope
_scope = stack.scope;
// in theory, all scopes are only reached and entered once...
this.processScope(_scope);
}
// same goes for labels, all accounted for by the parser
if (stack.labels) {
// entering new statement / function
_labels = stack.labels;
}