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) {
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) {
208 // (new Array(this.dumpLine.scope)).join(" ") + '|' +
209 (new Array(this.dumpLine.brace+1)).join(" ") + this.dumpLine.str);
210 this.dumpLine.str = '';
215 // (new Array(this.dumpLine.scope)).join(" ") + '|' +
216 (new Array(this.dumpLine.brace+1)).join(" ") + this.dumpLine.str);
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 this.parseExpression();
313 //this.braceNesting = bn;
314 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
316 token = this.ts.lookTok(1);
317 !this.debug|| print("AFTER EXP: " + token.toString());
318 if (token.data == ';') {
324 case "KEYW.FUNCTION":
325 //println("<i>"+token.data+"</i>");
326 var bn = this.braceNesting;
327 this.parseFunctionDeclaration();
328 this.braceNesting = bn;
331 case "PUNC.LEFT_CURLY": // {
332 //println("<i>"+token.data+"</i>");
333 isObjectLitAr.push(false);
336 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
339 case "PUNC.RIGHT_CURLY": // }
340 //println("<i>"+token.data+"</i>");
343 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
344 //assert braceNesting >= scope.getBra ceNesting();
346 if (this.braceNesting < expressionBraceNesting) {
347 var ls = this.scopes.pop();
349 // eat symbol if we are currently at {
350 if (this.ts.look(0).data == '{') {
354 //print("<<<<<<<EXIT SCOPE" +this.scopes.length);
360 //println("<i>"+token.data+"</i>");
361 if (this.mode == "BUILDING_SYMBOL_TREE") {
362 // Inside a 'with' block, it is impossible to figure out
363 // statically whether a symbol is a local variable or an
364 // object member. As a consequence, the only thing we can
365 // do is turn the obfuscation off for the highest scope
366 // containing the 'with' block.
367 this.protectScopeFromObfuscation(scope);
368 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
373 //println("<i>"+token.data+"</i>");
377 case Token.SPECIALCOMMENT:
378 if (mode == BUILDING_SYMBOL_TREE) {
379 protectScopeFromObfuscation(scope);
380 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
385 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
386 case "STRN.SINGLE_QUOTE":
387 //println("<i>"+token.data+"</i>");
388 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
389 // then we are in an object lit.. -> we need to flag the brace as such...
391 isObjectLitAr.push(true);
392 //print(">>>>>> OBJLIT REPUSH(true)");
394 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
396 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
397 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
398 // see if we can replace..
399 // remove the quotes..
400 // should do a bit more checking!!!! (what about wierd char's in the string..
401 var str = token.data.substring(1,token.data.length-1);
402 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
416 //print("DEAL WITH NAME:");
419 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
420 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
422 isObjectLitAr.push(true);
423 //print(">>>>>> OBJLIT REPUSH(true)");
424 //println("<i>"+token.data+"</i>");
427 // print("DEAL WITH obj lit:");
428 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
430 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
431 // skip, it's an object lit key..
432 //println("<i>"+token.data+"</i>");
437 // skip anyting with "." before it..!!
439 if (this.ts.lookTok(-1).data == ".") {
440 // skip, it's an object prop.
441 //println("<i>"+token.data+"</i>");
445 if (this.mode == 'PASS2_SYMBOL_TREE') {
447 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
449 //print ("MUNGE?" + symbol);
451 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
453 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
454 identifier = this.getIdentifier(symbol, scope);
456 if (identifier == false) {
457 // BUG!find out where builtin is defined...
458 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
459 // Here, we found an undeclared and un-namespaced symbol that is
460 // 3 characters or less in length. Declare it in the global scope.
461 // We don't need to declare longer symbols since they won't cause
462 // any conflict with other munged symbols.
463 this.globalScope.declareIdentifier(symbol, token);
464 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
467 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
469 token.identifier = identifier;
470 identifier.refcount++;
475 //println("<B>SID</B>");
477 if (token.type != 'KEYW') {
480 // print("Check eval:");
484 if (this.mode == 'BUILDING_SYMBOL_TREE') {
486 if (symbol == "eval") {
487 // look back one and see if we can find a comment!!!
488 if (this.ts.look(-1).type == "COMM") {
489 // look for eval:var:noreplace\n
491 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
493 var hi = _t.getIdentifier(a, scope);
494 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
496 // println("PROTECT "+a+" from munge");
506 this.protectScopeFromObfuscation(scope);
507 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);
519 //this.timerPrint("parseScope TOK : " + token.toString());
520 token = this.ts.nextTok();
521 //if (this.ts.nextT()) break;
524 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
528 parseExpression : function() {
530 // Parse the expression until we encounter a comma or a semi-colon
531 // in the same brace nesting, bracket nesting and paren nesting.
532 // Parse functions if any...
533 //println("<i>EXP</i><BR/>");
534 !this.debug || print("PARSE EXPR");
537 // for printing stuff..
546 var expressionBraceNesting = this.braceNesting;
547 var bracketNesting = 0;
548 var parensNesting = 0;
550 var isObjectLitAr = [ false ];
552 currentScope = this.scopes[this.scopes.length-1];
554 var scopeIndent = '';
555 this.scopes.forEach(function() {
558 print(scopeIndent + ">> ENTER EXPRESSION");
559 while (token = this.ts.lookTok()) {
564 // moved out of loop?
565 currentScope = this.scopes[this.scopes.length-1];
567 var scopeIndent = '';
568 this.scopes.forEach(function() {
573 this.dumpToken(token, this.scopes, this.braceNesting );
576 //println("<i>"+token.data+"</i>");
577 //this.log("EXP:" + token.data);
578 switch (token.type) {
584 if (this.braceNesting == expressionBraceNesting &&
585 bracketNesting == 0 &&
586 parensNesting == 0) {
587 print(scopeIndent + "<< EXIT EXPRESSION");
594 case '{': //Token.LC:
595 isObjectLitAr.push(false);
598 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
601 case '}': //Token.RC:
604 //print(">>>>> EXP POP" + this.braceNesting);
605 // assert braceNesting >= expressionBraceNesting;
608 case '[': //Token.LB:
612 case ']': //Token.RB:
616 case '(': //Token.LP:
620 case ')': //Token.RP:
626 case 'STRN': // used for object lit detection..
627 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
628 // then we are in an object lit.. -> we need to flag the brace as such...
630 isObjectLitAr.push(true);
631 //print(">>>>> EXP PUSH(true)");
636 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
637 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
638 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
639 // see if we can replace..
640 // remove the quotes..
641 var str = token.data.substring(1,token.data.length-1);
642 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
657 //print("in NAME = " + token.toString());
658 //print("in NAME 0: " + this.ts.look(0).toString());
659 //print("in NAME 2: " + this.ts.lookTok(2).toString());
660 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
661 // then we are in an object lit.. -> we need to flag the brace as such...
663 isObjectLitAr.push(true);
664 //print(">>>>> EXP PUSH(true)");
668 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
669 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
671 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
674 //print(this.ts.lookTok(0).data);
675 if (this.ts.lookTok(0).data == ".") {
680 if (this.mode == 'PASS2_SYMBOL_TREE') {
682 identifier = this.getIdentifier(symbol, currentScope);
683 //println("<B>??</B>");
684 if (identifier == false) {
686 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
687 // Here, we found an undeclared and un-namespaced symbol that is
688 // 3 characters or less in length. Declare it in the global scope.
689 // We don't need to declare longer symbols since they won't cause
690 // any conflict with other munged symbols.
691 this.globalScope.declareIdentifier(symbol, token);
692 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
694 //println("undeclared")
699 //println("<B>++</B>");
700 token.identifier = identifier;
701 identifier.refcount++;
710 //println("<B>EID</B>");
713 if (token.name == "FUNCTION") {
715 this.parseFunctionDeclaration();
722 if (this.mode == 'BUILDING_SYMBOL_TREE') {
724 if (symbol == "eval") {
725 if (this.ts.look(-1).type == 'COMM') {
726 // look for eval:var:noreplace\n
728 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
729 var hi = _t.getIdentifier(a, currentScope);
730 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
732 // println("PROTECT "+a+" from munge");
740 this.protectScopeFromObfuscation(currentScope);
741 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
750 if (!this.ts.nextTok()) break;
752 print(scopeIndent + "<< EXIT EXPRESSION");
756 parseCatch : function() {
763 //token = getToken(-1);
764 //assert token.getType() == Token.CATCH;
765 token = this.ts.nextTok();
766 //assert token.getType() == Token.LP; (
767 token = this.ts.nextTok();
768 //assert token.getType() == Token.NAME;
771 currentScope = this.scopes[this.scopes.length-1];
773 if (this.mode == 'BUILDING_SYMBOL_TREE') {
774 // We must declare the exception identifier in the containing function
775 // scope to avoid errors related to the obfuscation process. No need to
776 // display a warning if the symbol was already declared here...
777 currentScope.declareIdentifier(symbol, token);
779 //?? why inc the refcount?? - that should be set when building the tree???
780 identifier = this.getIdentifier(symbol, currentScope);
781 identifier.refcount++;
784 token = this.ts.nextTok();
785 //assert token.getType() == Token.RP; // )
788 parseFunctionDeclaration : function()
790 print("PARSE FUNCTION");
793 var currentScope = false;
796 //this.logR("<B>PARSING FUNCTION</B>");
797 currentScope = this.scopes[this.scopes.length-1];
799 token = this.ts.nextTok();
800 if (token.type == "NAME") {
801 if (this.mode == 'BUILDING_SYMBOL_TREE') {
802 // Get the name of the function and declare it in the current scope.
804 if (currentScope.getIdentifier(symbol) != false) {
805 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
807 currentScope.declareIdentifier(symbol,token);
809 token = this.ts.nextTok();
812 //assert token.getType() == Token.LP;
813 if (this.mode == 'BUILDING_SYMBOL_TREE') {
814 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
816 //println("STORING SCOPE" + this.ts.cursor);
818 this.indexedScopes[this.ts.cursor] = fnScope;
821 //qln("FETCHING SCOPE" + this.ts.cursor);
822 fnScope = this.indexedScopes[this.ts.cursor];
826 // Parse function arguments.
828 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
829 token = this.ts.nextTok();
830 // print ("FUNC ARGS: " + token.toString())
831 //assert token.getType() == Token.NAME ||
832 // token.getType() == Token.COMMA;
833 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
835 identifier = fnScope.declareIdentifier(symbol,token);
836 if (symbol == "$super" && argpos == 0) {
837 // Exception for Prototype 1.6...
838 identifier.preventMunging();
844 token = this.ts.nextTok();
845 print(token.toString());
846 // assert token.getType() == Token.LC;
849 token = this.ts.nextTok();
850 print(token.toString());
851 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
854 NOT SUPPORTED YET!?!!?!
856 // This is a hint. Hints are empty statements that look like
857 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
858 // to prevent specific symbols from getting obfuscated (some heretic
859 // implementations, such as Prototype 1.6, require specific variable
860 // names, such as $super for example, in order to work appropriately.
861 // Note: right now, only "nomunge" is supported in the right hand side
862 // of a hint. However, in the future, the right hand side may contain
865 String hints = token.getValue();
866 // Remove the leading and trailing quotes...
867 hints = hints.substring(1, hints.length() - 1).trim();
868 StringTokenizer st1 = new StringTokenizer(hints, ",");
869 while (st1.hasMoreTokens()) {
870 String hint = st1.nextToken();
871 int idx = hint.indexOf(':');
872 if (idx <= 0 || idx >= hint.length() - 1) {
873 if (mode == BUILDING_SYMBOL_TREE) {
874 // No need to report the error twice, hence the test...
875 this.warn("Invalid hint syntax: " + hint, true);
879 String variableName = hint.substring(0, idx).trim();
880 String variableType = hint.substring(idx + 1).trim();
881 if (mode == BUILDING_SYMBOL_TREE) {
882 fnScope.addHint(variableName, variableType);
883 } else if (mode == CHECKING_SYMBOL_TREE) {
884 identifier = fnScope.getIdentifier(variableName);
885 if (identifier != null) {
886 if (variableType.equals("nomunge")) {
887 identifier.preventMunging();
889 this.warn("Unsupported hint value: " + hint, true);
892 this.warn("Hint refers to an unknown identifier: " + hint, true);
899 this.parseScope(fnScope);
900 // now pop it off the stack!!!
906 protectScopeFromObfuscation : function(scope) {
907 //assert scope != null;
909 if (scope == this.globalScope) {
910 // The global scope does not get obfuscated,
911 // so we don't need to worry about it...
915 // Find the highest local scope containing the specified scope.
916 while (scope && scope.parent != this.globalScope) {
917 scope = scope.parent;
920 //assert scope.getParentScope() == globalScope;
921 scope.preventMunging();
924 getIdentifier: function(symbol, scope) {
926 while (scope != false) {
927 identifier = scope.getIdentifier(symbol);
928 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
932 scope = scope.parent;