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 mungeSymboltree : function()
143 // One problem with obfuscation resides in the use of undeclared
144 // and un-namespaced global symbols that are 3 characters or less
145 // in length. Here is an example:
147 // var declaredGlobalVar;
149 // function declaredGlobalFn() {
151 // localvar = abc; // abc is an undeclared global symbol
154 // In the example above, there is a slim chance that localvar may be
155 // munged to 'abc', conflicting with the undeclared global symbol
156 // abc, creating a potential bug. The following code detects such
157 // global symbols. This must be done AFTER the entire file has been
158 // parsed, and BEFORE munging the symbol tree. Note that declaring
159 // extra symbols in the global scope won't hurt.
161 // Note: Since we go through all the tokens to do this, we also use
162 // the opportunity to count how many times each identifier is used.
165 this.braceNesting = 0;
167 this.mode = 'PASS2_SYMBOL_TREE';
169 //println("MUNGING?");
171 this.parseScope(this.globalScope);
172 this.globalScope.munge();
178 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
182 //println("<B>LOG:</B>" + str + "<BR/>");
190 parseScope : function(scope) // parse a token stream..
192 //this.timerPrint("parseScope EnterScope");
193 print(">>> ENTER SCOPE" + this.scopes.length);
199 var expressionBraceNesting = this.braceNesting;
200 var bracketNesting = 0;
201 var parensNesting = 0;
203 var isObjectLitAr = [ false ];
205 this.scopes.push(scope);
206 token = this.ts.lookTok(1);
208 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
210 !this.debug|| print(token.type + '.' + token.name+ ":" + token.data);
211 switch(token.type + '.' + token.name) {
213 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
215 //this.log("parseScope GOT VAR/CONST : " + token.toString());
217 token = this.ts.nextTok();
218 !this.debug|| print( token.toString());
220 if (!token) { // can return false at EOF!
223 if (token.name == "VAR") { // kludge..
226 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
227 if (token.type !="NAME") {
228 print(token.toString());
229 print( "var without ident");
234 if (this.mode == "BUILDING_SYMBOL_TREE") {
235 identifier = scope.getIdentifier(token.data) ;
237 if (identifier == false) {
238 scope.declareIdentifier(token.data, token);
240 token.identifier = identifier;
241 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
245 token = this.ts.nextTok();
246 !this.debug|| print(token.toString());
248 assert token.getType() == Token.SEMI ||
249 token.getType() == Token.ASSIGN ||
250 token.getType() == Token.COMMA ||
251 token.getType() == Token.IN;
253 if (token.name == "IN") {
256 this.parseExpression();
257 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
259 token = this.ts.lookTok(1);
260 !this.debug|| print("AFTER EXP: " + token.toString());
261 if (token.data == ';') {
267 case "KEYW.FUNCTION":
268 //println("<i>"+token.data+"</i>");
269 this.parseFunctionDeclaration();
272 case "KEYW.LEFT_CURLY": // {
273 //println("<i>"+token.data+"</i>");
274 isObjectLitAr.push(false);
275 print(">>>>>> OBJLIT PUSH(false)");
279 case "KEYW.RIGHT_CURLY": // }
280 //println("<i>"+token.data+"</i>");
283 print(">>>>>> OBJLIT POP(false)");
284 //assert braceNesting >= scope.getBraceNesting();
285 if (this.braceNesting == scope.braceNesting) {
286 var ls = this.scopes.pop();
288 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
294 //println("<i>"+token.data+"</i>");
295 if (this.mode == "BUILDING_SYMBOL_TREE") {
296 // Inside a 'with' block, it is impossible to figure out
297 // statically whether a symbol is a local variable or an
298 // object member. As a consequence, the only thing we can
299 // do is turn the obfuscation off for the highest scope
300 // containing the 'with' block.
301 this.protectScopeFromObfuscation(scope);
302 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
307 //println("<i>"+token.data+"</i>");
311 case Token.SPECIALCOMMENT:
312 if (mode == BUILDING_SYMBOL_TREE) {
313 protectScopeFromObfuscation(scope);
314 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
319 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
320 case "STRN.SINGLE_QUOTE":
321 //println("<i>"+token.data+"</i>");
322 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
323 // then we are in an object lit.. -> we need to flag the brace as such...
325 isObjectLitAr.push(true);
326 print(">>>>>> OBJLIT PUSH(true)");
328 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
330 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
331 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
332 // see if we can replace..
333 // remove the quotes..
334 // should do a bit more checking!!!! (what about wierd char's in the string..
335 var str = token.data.substring(1,token.data.length-1);
336 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
350 //print("DEAL WITH NAME:");
353 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
354 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
356 isObjectLitAr.push(true);
357 print(">>>>>> OBJLIT PUSH(true)");
358 //println("<i>"+token.data+"</i>");
361 // print("DEAL WITH obj lit:");
362 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
364 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
365 // skip, it's an object lit key..
366 //println("<i>"+token.data+"</i>");
371 // skip anyting with "." before it..!!
373 if (this.ts.lookTok(-1).data == ".") {
374 // skip, it's an object prop.
375 //println("<i>"+token.data+"</i>");
379 if (this.mode == 'PASS2_SYMBOL_TREE') {
381 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
383 //print ("MUNGE?" + symbol);
385 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
387 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
388 identifier = this.getIdentifier(symbol, scope);
390 if (identifier == false) {
391 // BUG!find out where builtin is defined...
392 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
393 // Here, we found an undeclared and un-namespaced symbol that is
394 // 3 characters or less in length. Declare it in the global scope.
395 // We don't need to declare longer symbols since they won't cause
396 // any conflict with other munged symbols.
397 this.globalScope.declareIdentifier(symbol, token);
398 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
401 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
403 token.identifier = identifier;
404 identifier.refcount++;
409 //println("<B>SID</B>");
411 if (token.type != 'KEYW') {
414 // print("Check eval:");
418 if (this.mode == 'BUILDING_SYMBOL_TREE') {
420 if (symbol == "eval") {
421 // look back one and see if we can find a comment!!!
422 if (this.ts.look(-1).type == "COMM") {
423 // look for eval:var:noreplace\n
425 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
427 var hi = _t.getIdentifier(a, scope);
428 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
430 // println("PROTECT "+a+" from munge");
440 this.protectScopeFromObfuscation(scope);
441 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);
453 //this.timerPrint("parseScope TOK : " + token.toString());
454 token = this.ts.nextTok();
455 //if (this.ts.nextT()) break;
458 print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
462 parseExpression : function() {
464 // Parse the expression until we encounter a comma or a semi-colon
465 // in the same brace nesting, bracket nesting and paren nesting.
466 // Parse functions if any...
467 //println("<i>EXP</i><BR/>");
468 !this.debug || print("PARSE EXPR");
474 var expressionBraceNesting = this.braceNesting;
475 var bracketNesting = 0;
476 var parensNesting = 0;
478 var isObjectLitAr = [ false ];
479 while (token = this.ts.lookTok()) {
483 currentScope = this.scopes[this.scopes.length-1];
485 //println("<i>"+token.data+"</i>");
486 !this.debug|| print ("EXP" + token.toString());
487 switch (token.type) {
493 if (this.braceNesting == expressionBraceNesting &&
494 bracketNesting == 0 &&
495 parensNesting == 0) {
503 case '{': //Token.LC:
504 isObjectLitAr.push(false);
505 print(">>>>> OBJ PUSH(false)");
509 case '}': //Token.RC:
512 print(">>>>> OBJ POP");
513 // assert braceNesting >= expressionBraceNesting;
516 case '[': //Token.LB:
520 case ']': //Token.RB:
524 case '(': //Token.LP:
528 case ')': //Token.RP:
534 case 'STRN': // used for object lit detection..
535 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
536 // then we are in an object lit.. -> we need to flag the brace as such...
538 isObjectLitAr.push(true);
539 print(">>>>> OBJ PUSH(true)");
544 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
545 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
546 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
547 // see if we can replace..
548 // remove the quotes..
549 var str = token.data.substring(1,token.data.length-1);
550 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
565 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
566 // then we are in an object lit.. -> we need to flag the brace as such...
568 isObjectLitAr.push(true);
569 print(">>>>> OBJ PUSH(true)");
572 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
573 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
577 if (this.ts.lookTok(-1).data == ".") {
582 if (this.mode == 'PASS2_SYMBOL_TREE') {
584 identifier = this.getIdentifier(symbol, currentScope);
585 //println("<B>??</B>");
586 if (identifier == false) {
588 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
589 // Here, we found an undeclared and un-namespaced symbol that is
590 // 3 characters or less in length. Declare it in the global scope.
591 // We don't need to declare longer symbols since they won't cause
592 // any conflict with other munged symbols.
593 this.globalScope.declareIdentifier(symbol, token);
594 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
596 //println("undeclared")
601 //println("<B>++</B>");
602 token.identifier = identifier;
603 identifier.refcount++;
612 //println("<B>EID</B>");
615 if (token.name == "FUNCTION") {
617 this.parseFunctionDeclaration();
624 if (this.mode == 'BUILDING_SYMBOL_TREE') {
626 if (symbol == "eval") {
627 if (this.ts.look(-1).type == 'COMM') {
628 // look for eval:var:noreplace\n
630 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
631 var hi = _t.getIdentifier(a, currentScope);
632 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
634 // println("PROTECT "+a+" from munge");
642 this.protectScopeFromObfuscation(currentScope);
643 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
652 if (!this.ts.nextTok()) break;
657 parseCatch : function() {
664 //token = getToken(-1);
665 //assert token.getType() == Token.CATCH;
666 token = this.ts.nextTok();
667 //assert token.getType() == Token.LP; (
668 token = this.ts.nextTok();
669 //assert token.getType() == Token.NAME;
672 currentScope = this.scopes[this.scopes.length-1];
674 if (this.mode == 'BUILDING_SYMBOL_TREE') {
675 // We must declare the exception identifier in the containing function
676 // scope to avoid errors related to the obfuscation process. No need to
677 // display a warning if the symbol was already declared here...
678 currentScope.declareIdentifier(symbol, token);
680 //?? why inc the refcount?? - that should be set when building the tree???
681 identifier = this.getIdentifier(symbol, currentScope);
682 identifier.refcount++;
685 token = this.ts.nextTok();
686 //assert token.getType() == Token.RP; // )
689 parseFunctionDeclaration : function()
691 // print("PARSE FUNCTION");
694 var currentScope = false;
697 //this.logR("<B>PARSING FUNCTION</B>");
698 currentScope = this.scopes[this.scopes.length-1];
700 token = this.ts.nextTok();
701 if (token.type == "NAME") {
702 if (this.mode == 'BUILDING_SYMBOL_TREE') {
703 // Get the name of the function and declare it in the current scope.
705 if (currentScope.getIdentifier(symbol) != false) {
706 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
708 currentScope.declareIdentifier(symbol,token);
710 token = this.ts.nextTok();
713 //assert token.getType() == Token.LP;
714 if (this.mode == 'BUILDING_SYMBOL_TREE') {
715 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
717 //println("STORING SCOPE" + this.ts.cursor);
719 this.indexedScopes[this.ts.cursor] = fnScope;
722 //println("FETCHING SCOPE" + this.ts.cursor);
723 fnScope = this.indexedScopes[this.ts.cursor];
727 // Parse function arguments.
729 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
730 token = this.ts.nextTok();
731 // print ("FUNC ARGS: " + token.toString())
732 //assert token.getType() == Token.NAME ||
733 // token.getType() == Token.COMMA;
734 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
736 identifier = fnScope.declareIdentifier(symbol,token);
737 if (symbol == "$super" && argpos == 0) {
738 // Exception for Prototype 1.6...
739 identifier.preventMunging();
745 token = this.ts.nextTok();
746 // assert token.getType() == Token.LC;
749 token = this.ts.nextTok();
750 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
753 NOT SUPPORTED YET!?!!?!
755 // This is a hint. Hints are empty statements that look like
756 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
757 // to prevent specific symbols from getting obfuscated (some heretic
758 // implementations, such as Prototype 1.6, require specific variable
759 // names, such as $super for example, in order to work appropriately.
760 // Note: right now, only "nomunge" is supported in the right hand side
761 // of a hint. However, in the future, the right hand side may contain
764 String hints = token.getValue();
765 // Remove the leading and trailing quotes...
766 hints = hints.substring(1, hints.length() - 1).trim();
767 StringTokenizer st1 = new StringTokenizer(hints, ",");
768 while (st1.hasMoreTokens()) {
769 String hint = st1.nextToken();
770 int idx = hint.indexOf(':');
771 if (idx <= 0 || idx >= hint.length() - 1) {
772 if (mode == BUILDING_SYMBOL_TREE) {
773 // No need to report the error twice, hence the test...
774 this.warn("Invalid hint syntax: " + hint, true);
778 String variableName = hint.substring(0, idx).trim();
779 String variableType = hint.substring(idx + 1).trim();
780 if (mode == BUILDING_SYMBOL_TREE) {
781 fnScope.addHint(variableName, variableType);
782 } else if (mode == CHECKING_SYMBOL_TREE) {
783 identifier = fnScope.getIdentifier(variableName);
784 if (identifier != null) {
785 if (variableType.equals("nomunge")) {
786 identifier.preventMunging();
788 this.warn("Unsupported hint value: " + hint, true);
791 this.warn("Hint refers to an unknown identifier: " + hint, true);
798 this.parseScope(fnScope);
799 // now pop it off the stack!!!
805 protectScopeFromObfuscation : function(scope) {
806 //assert scope != null;
808 if (scope == this.globalScope) {
809 // The global scope does not get obfuscated,
810 // so we don't need to worry about it...
814 // Find the highest local scope containing the specified scope.
815 while (scope && scope.parent != this.globalScope) {
816 scope = scope.parent;
819 //assert scope.getParentScope() == globalScope;
820 scope.preventMunging();
823 getIdentifier: function(symbol, scope) {
825 while (scope != false) {
826 identifier = scope.getIdentifier(symbol);
827 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
831 scope = scope.parent;