1 //<Script type="text/javascript">
3 Scope = imports['JSDOC/Scope.js'].Scope;
8 * // FIXME - I need this to do next() without doccomments..
11 ScopeParser = function(ts) {
12 this.ts = ts; // {TokenStream}
15 this.indexedScopes = {};
16 this.timer = new Date() * 1;
20 // list of keywords that should not be used in object literals.
21 ScopeParser.idents = [
87 ScopeParser.prototype = {
89 timerPrint: function (str) {
90 var ntime = new Date() * 1;
91 var tdif = ntime -this.timer;
94 if (tdif > 100) { //slower ones..
97 println(pref+'['+tdif+']'+str);
101 //print('****************' + s);
102 this.warnings.push(s);
103 //println("WARNING:" + htmlescape(s) + "<BR>");
105 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
110 mode : "", //"BUILDING_SYMBOL_TREE",
112 indexedScopes : false,
119 buildSymbolTree : function()
124 this.braceNesting = 0;
130 this.globalScope = new Scope(-1, false, -1, '');
131 indexedScopes = { 0 : this.globalScope };
133 this.mode = 'BUILDING_SYMBOL_TREE';
134 this.parseScope(this.globalScope);
136 //print("---------------END PASS 1 ---------------- ");
139 mungeSymboltree : function()
146 // One problem with obfuscation resides in the use of undeclared
147 // and un-namespaced global symbols that are 3 characters or less
148 // in length. Here is an example:
150 // var declaredGlobalVar;
152 // function declaredGlobalFn() {
154 // localvar = abc; // abc is an undeclared global symbol
157 // In the example above, there is a slim chance that localvar may be
158 // munged to 'abc', conflicting with the undeclared global symbol
159 // abc, creating a potential bug. The following code detects such
160 // global symbols. This must be done AFTER the entire file has been
161 // parsed, and BEFORE munging the symbol tree. Note that declaring
162 // extra symbols in the global scope won't hurt.
164 // Note: Since we go through all the tokens to do this, we also use
165 // the opportunity to count how many times each identifier is used.
168 this.braceNesting = 0;
170 this.mode = 'PASS2_SYMBOL_TREE';
172 //println("MUNGING?");
174 this.parseScope(this.globalScope);
175 this.globalScope.munge();
181 print (" ".substring(0, this.braceNesting*2) + str);
183 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
187 //println("<B>LOG:</B>" + str + "<BR/>");
192 dumpToken: function (tok, scope, brace) {
193 if (this.dumpLine == false) {
195 str : tok.data + ' ',
196 scope : scope.length,
202 if (this.dumpLine.scope == scope.length && this.dumpLine.brace == brace) {
203 this.dumpLine.str += tok.data + ' ';
204 if (this.dumpLine.str.length > 80 || tok.data ==';') {
207 // (new Array(this.dumpLine.scope)).join(" ") + '|' +
208 (new Array(this.dumpLine.brace+1)).join(" ") + this.dumpLine.str);
209 this.dumpLine.str = '';
215 // (new Array(this.dumpLine.scope)).join(" ") + '|' +
216 (new Array(this.dumpLine.brace+1)).join(" ") + this.dumpLine.str);
220 str : tok.data + ' ',
221 scope : scope.length,
229 parseScope : function(scope) // parse a token stream..
231 //this.timerPrint("parseScope EnterScope");
232 //this.log(">>> ENTER SCOPE" + this.scopes.length);
238 var expressionBraceNesting = this.braceNesting + 0;
240 var parensNesting = 0;
242 var isObjectLitAr = [ false ];
244 this.scopes.push(scope);
246 var scopeIndent = '';
247 this.scopes.forEach(function() {
250 print(scopeIndent + ">> ENTER SCOPE");
255 token = this.ts.lookTok(1);
257 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
258 this.dumpToken(token , this.scopes, this.braceNesting);
259 //this.log(token.data);
260 if (token.type == 'NAME') {
261 // print('*' + token.data);
263 switch(token.type + '.' + token.name) {
265 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
267 //this.log("parseScope GOT VAR/CONST : " + token.toString());
269 token = this.ts.nextTok();
270 !this.debug|| print( token.toString());
272 if (!token) { // can return false at EOF!
275 if (token.name == "VAR" || token.data == ',') { // kludge..
278 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
279 if (token.type !="NAME") {
280 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
281 print(this.ts.tokens[i].toString());
284 print( "var without ident");
289 if (this.mode == "BUILDING_SYMBOL_TREE") {
290 identifier = scope.getIdentifier(token.data) ;
292 if (identifier == false) {
293 scope.declareIdentifier(token.data, token);
295 token.identifier = identifier;
296 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
300 token = this.ts.nextTok();
301 !this.debug|| print(token.toString());
303 assert token.getType() == Token.SEMI ||
304 token.getType() == Token.ASSIGN ||
305 token.getType() == Token.COMMA ||
306 token.getType() == Token.IN;
308 if (token.name == "IN") {
311 //var bn = this.braceNesting;
312 var bn = this.braceNesting;
313 this.parseExpression();
314 this.braceNesting = bn;
315 //this.braceNesting = bn;
316 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
318 token = this.ts.lookTok(1);
319 !this.debug|| print("AFTER EXP: " + token.toString());
320 if (token.data == ';') {
326 case "KEYW.FUNCTION":
327 //println("<i>"+token.data+"</i>");
328 var bn = this.braceNesting;
329 this.parseFunctionDeclaration();
330 this.braceNesting = bn;
333 case "PUNC.LEFT_CURLY": // {
334 //println("<i>"+token.data+"</i>");
335 isObjectLitAr.push(false);
338 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
341 case "PUNC.RIGHT_CURLY": // }
342 //println("<i>"+token.data+"</i>");
345 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
346 //assert braceNesting >= scope.getBra ceNesting();
348 if (this.braceNesting < expressionBraceNesting) {
349 var ls = this.scopes.pop();
351 // eat symbol if we are currently at {
352 if (this.ts.look(0).data == '{') {
357 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
363 //println("<i>"+token.data+"</i>");
364 if (this.mode == "BUILDING_SYMBOL_TREE") {
365 // Inside a 'with' block, it is impossible to figure out
366 // statically whether a symbol is a local variable or an
367 // object member. As a consequence, the only thing we can
368 // do is turn the obfuscation off for the highest scope
369 // containing the 'with' block.
370 this.protectScopeFromObfuscation(scope);
371 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
376 //println("<i>"+token.data+"</i>");
380 case Token.SPECIALCOMMENT:
381 if (mode == BUILDING_SYMBOL_TREE) {
382 protectScopeFromObfuscation(scope);
383 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
388 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
389 case "STRN.SINGLE_QUOTE":
390 //println("<i>"+token.data+"</i>");
391 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
392 // then we are in an object lit.. -> we need to flag the brace as such...
394 isObjectLitAr.push(true);
395 //print(">>>>>> OBJLIT REPUSH(true)");
397 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
399 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
400 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
401 // see if we can replace..
402 // remove the quotes..
403 // should do a bit more checking!!!! (what about wierd char's in the string..
404 var str = token.data.substring(1,token.data.length-1);
405 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
419 //print("DEAL WITH NAME:");
422 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
423 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
425 isObjectLitAr.push(true);
426 //print(">>>>>> OBJLIT REPUSH(true)");
427 //println("<i>"+token.data+"</i>");
430 // print("DEAL WITH obj lit:");
431 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
433 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
434 // skip, it's an object lit key..
435 //println("<i>"+token.data+"</i>");
440 // skip anyting with "." before it..!!
442 if (this.ts.lookTok(-1).data == ".") {
443 // skip, it's an object prop.
444 //println("<i>"+token.data+"</i>");
448 if (this.mode == 'PASS2_SYMBOL_TREE') {
450 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
452 //print ("MUNGE?" + symbol);
454 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
456 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
457 identifier = this.getIdentifier(symbol, scope);
459 if (identifier == false) {
460 // BUG!find out where builtin is defined...
461 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
462 // Here, we found an undeclared and un-namespaced symbol that is
463 // 3 characters or less in length. Declare it in the global scope.
464 // We don't need to declare longer symbols since they won't cause
465 // any conflict with other munged symbols.
466 this.globalScope.declareIdentifier(symbol, token);
467 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
470 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
472 token.identifier = identifier;
473 identifier.refcount++;
478 //println("<B>SID</B>");
480 if (token.type != 'KEYW') {
483 // print("Check eval:");
487 if (this.mode == 'BUILDING_SYMBOL_TREE') {
489 if (symbol == "eval") {
490 // look back one and see if we can find a comment!!!
491 if (this.ts.look(-1).type == "COMM") {
492 // look for eval:var:noreplace\n
494 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
496 var hi = _t.getIdentifier(a, scope);
497 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
499 // println("PROTECT "+a+" from munge");
509 this.protectScopeFromObfuscation(scope);
510 this.warn("Using 'eval' is not recommended. (use eval:var:noreplace in comments to optimize) " + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
522 this.timerPrint("parseScope TOK : " + token.toString());
523 token = this.ts.nextTok();
524 //if (this.ts.nextT()) break;
527 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
531 parseExpression : function() {
533 // Parse the expression until we encounter a comma or a semi-colon
534 // in the same brace nesting, bracket nesting and paren nesting.
535 // Parse functions if any...
536 //println("<i>EXP</i><BR/>");
537 !this.debug || print("PARSE EXPR");
540 // for printing stuff..
549 var expressionBraceNesting = this.braceNesting + 0;
550 var bracketNesting = 0;
551 var parensNesting = 0;
553 var isObjectLitAr = [ false ];
555 currentScope = this.scopes[this.scopes.length-1];
557 var scopeIndent = '';
558 this.scopes.forEach(function() {
561 print(scopeIndent + ">> ENTER EXPRESSION");
562 while (token = this.ts.lookTok()) {
567 // moved out of loop?
568 currentScope = this.scopes[this.scopes.length-1];
570 var scopeIndent = '';
571 this.scopes.forEach(function() {
576 this.dumpToken(token, this.scopes, this.braceNesting );
579 //println("<i>"+token.data+"</i>");
580 //this.log("EXP:" + token.data);
581 switch (token.type) {
587 if (this.braceNesting == expressionBraceNesting &&
588 bracketNesting == 0 &&
589 parensNesting == 0) {
590 print(scopeIndent + "<< EXIT EXPRESSION");
597 case '{': //Token.LC:
598 isObjectLitAr.push(false);
601 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
604 case '}': //Token.RC:
607 //print(">>>>> EXP POP" + this.braceNesting);
608 // assert braceNesting >= expressionBraceNesting;
611 case '[': //Token.LB:
615 case ']': //Token.RB:
619 case '(': //Token.LP:
623 case ')': //Token.RP:
629 case 'STRN': // used for object lit detection..
630 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
631 // then we are in an object lit.. -> we need to flag the brace as such...
633 isObjectLitAr.push(true);
634 //print(">>>>> EXP PUSH(true)");
639 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
640 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
641 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
642 // see if we can replace..
643 // remove the quotes..
644 var str = token.data.substring(1,token.data.length-1);
645 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
660 //print("in NAME = " + token.toString());
661 //print("in NAME 0: " + this.ts.look(0).toString());
662 //print("in NAME 2: " + this.ts.lookTok(2).toString());
663 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
664 // then we are in an object lit.. -> we need to flag the brace as such...
666 isObjectLitAr.push(true);
667 //print(">>>>> EXP PUSH(true)");
671 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
672 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
674 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
677 //print(this.ts.lookTok(0).data);
678 if (this.ts.lookTok(0).data == ".") {
683 if (this.mode == 'PASS2_SYMBOL_TREE') {
685 identifier = this.getIdentifier(symbol, currentScope);
686 //println("<B>??</B>");
687 if (identifier == false) {
689 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
690 // Here, we found an undeclared and un-namespaced symbol that is
691 // 3 characters or less in length. Declare it in the global scope.
692 // We don't need to declare longer symbols since they won't cause
693 // any conflict with other munged symbols.
694 this.globalScope.declareIdentifier(symbol, token);
695 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
697 //println("undeclared")
702 //println("<B>++</B>");
703 token.identifier = identifier;
704 identifier.refcount++;
713 //println("<B>EID</B>");
716 if (token.name == "FUNCTION") {
718 this.parseFunctionDeclaration();
725 if (this.mode == 'BUILDING_SYMBOL_TREE') {
727 if (symbol == "eval") {
728 if (this.ts.look(-1).type == 'COMM') {
729 // look for eval:var:noreplace\n
731 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
732 var hi = _t.getIdentifier(a, currentScope);
733 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
735 // println("PROTECT "+a+" from munge");
743 this.protectScopeFromObfuscation(currentScope);
744 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
753 if (!this.ts.nextTok()) break;
755 print(scopeIndent + "<< EXIT EXPRESSION");
759 parseCatch : function() {
766 //token = getToken(-1);
767 //assert token.getType() == Token.CATCH;
768 token = this.ts.nextTok();
769 //assert token.getType() == Token.LP; (
770 token = this.ts.nextTok();
771 //assert token.getType() == Token.NAME;
774 currentScope = this.scopes[this.scopes.length-1];
776 if (this.mode == 'BUILDING_SYMBOL_TREE') {
777 // We must declare the exception identifier in the containing function
778 // scope to avoid errors related to the obfuscation process. No need to
779 // display a warning if the symbol was already declared here...
780 currentScope.declareIdentifier(symbol, token);
782 //?? why inc the refcount?? - that should be set when building the tree???
783 identifier = this.getIdentifier(symbol, currentScope);
784 identifier.refcount++;
787 token = this.ts.nextTok();
788 //assert token.getType() == Token.RP; // )
791 parseFunctionDeclaration : function()
793 print("PARSE FUNCTION");
796 var currentScope = false;
799 var b4braceNesting = this.braceNesting + 0;
801 //this.logR("<B>PARSING FUNCTION</B>");
802 currentScope = this.scopes[this.scopes.length-1];
804 token = this.ts.nextTok();
805 if (token.type == "NAME") {
806 if (this.mode == 'BUILDING_SYMBOL_TREE') {
807 // Get the name of the function and declare it in the current scope.
809 if (currentScope.getIdentifier(symbol) != false) {
810 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
812 currentScope.declareIdentifier(symbol,token);
814 token = this.ts.nextTok();
817 //assert token.getType() == Token.LP;
818 if (this.mode == 'BUILDING_SYMBOL_TREE') {
819 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
821 //println("STORING SCOPE" + this.ts.cursor);
823 this.indexedScopes[this.ts.cursor] = fnScope;
826 //qln("FETCHING SCOPE" + this.ts.cursor);
827 fnScope = this.indexedScopes[this.ts.cursor];
831 // Parse function arguments.
833 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
834 token = this.ts.nextTok();
835 // print ("FUNC ARGS: " + token.toString())
836 //assert token.getType() == Token.NAME ||
837 // token.getType() == Token.COMMA;
838 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
840 identifier = fnScope.declareIdentifier(symbol,token);
841 if (symbol == "$super" && argpos == 0) {
842 // Exception for Prototype 1.6...
843 identifier.preventMunging();
849 token = this.ts.nextTok();
850 print(token.toString());
851 // assert token.getType() == Token.LC;
854 token = this.ts.nextTok();
855 print(token.toString());
856 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
859 NOT SUPPORTED YET!?!!?!
861 // This is a hint. Hints are empty statements that look like
862 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
863 // to prevent specific symbols from getting obfuscated (some heretic
864 // implementations, such as Prototype 1.6, require specific variable
865 // names, such as $super for example, in order to work appropriately.
866 // Note: right now, only "nomunge" is supported in the right hand side
867 // of a hint. However, in the future, the right hand side may contain
870 String hints = token.getValue();
871 // Remove the leading and trailing quotes...
872 hints = hints.substring(1, hints.length() - 1).trim();
873 StringTokenizer st1 = new StringTokenizer(hints, ",");
874 while (st1.hasMoreTokens()) {
875 String hint = st1.nextToken();
876 int idx = hint.indexOf(':');
877 if (idx <= 0 || idx >= hint.length() - 1) {
878 if (mode == BUILDING_SYMBOL_TREE) {
879 // No need to report the error twice, hence the test...
880 this.warn("Invalid hint syntax: " + hint, true);
884 String variableName = hint.substring(0, idx).trim();
885 String variableType = hint.substring(idx + 1).trim();
886 if (mode == BUILDING_SYMBOL_TREE) {
887 fnScope.addHint(variableName, variableType);
888 } else if (mode == CHECKING_SYMBOL_TREE) {
889 identifier = fnScope.getIdentifier(variableName);
890 if (identifier != null) {
891 if (variableType.equals("nomunge")) {
892 identifier.preventMunging();
894 this.warn("Unsupported hint value: " + hint, true);
897 this.warn("Hint refers to an unknown identifier: " + hint, true);
904 this.parseScope(fnScope);
905 // now pop it off the stack!!!
907 this.braceNesting = b4braceNesting;
908 print("ENDFN -1: " + this.ts.lookTok(-1).toString());
909 print("ENDFN 0: " + this.ts.lookTok(0).toString());
910 print("ENDFN 1: " + this.ts.lookTok(1).toString());
913 protectScopeFromObfuscation : function(scope) {
914 //assert scope != null;
916 if (scope == this.globalScope) {
917 // The global scope does not get obfuscated,
918 // so we don't need to worry about it...
922 // Find the highest local scope containing the specified scope.
923 while (scope && scope.parent != this.globalScope) {
924 scope = scope.parent;
927 //assert scope.getParentScope() == globalScope;
928 scope.preventMunging();
931 getIdentifier: function(symbol, scope) {
933 while (scope != false) {
934 identifier = scope.getIdentifier(symbol);
935 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
939 scope = scope.parent;