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 this.warnings.push(s);
102 //println("WARNING:" + htmlescape(s) + "<BR>");
104 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
109 mode : "", //"BUILDING_SYMBOL_TREE",
111 indexedScopes : false,
118 buildSymbolTree : function()
123 this.braceNesting = 0;
129 this.globalScope = new Scope(-1, false, -1, '');
130 indexedScopes = { 0 : this.globalScope };
132 this.mode = 'BUILDING_SYMBOL_TREE';
133 this.parseScope(this.globalScope);
135 mungeSymboltree : function()
142 // One problem with obfuscation resides in the use of undeclared
143 // and un-namespaced global symbols that are 3 characters or less
144 // in length. Here is an example:
146 // var declaredGlobalVar;
148 // function declaredGlobalFn() {
150 // localvar = abc; // abc is an undeclared global symbol
153 // In the example above, there is a slim chance that localvar may be
154 // munged to 'abc', conflicting with the undeclared global symbol
155 // abc, creating a potential bug. The following code detects such
156 // global symbols. This must be done AFTER the entire file has been
157 // parsed, and BEFORE munging the symbol tree. Note that declaring
158 // extra symbols in the global scope won't hurt.
160 // Note: Since we go through all the tokens to do this, we also use
161 // the opportunity to count how many times each identifier is used.
164 this.braceNesting = 0;
166 this.mode = 'CHECKING_SYMBOL_TREE';
168 //println("MUNGING?");
170 this.parseScope(this.globalScope);
171 this.globalScope.munge();
177 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
181 //println("<B>LOG:</B>" + str + "<BR/>");
189 parseScope : function(scope) // parse a token stream..
191 //this.timerPrint("parseScope EnterScope");
197 var expressionBraceNesting = this.braceNesting;
198 var bracketNesting = 0;
199 var parensNesting = 0;
201 var isObjectLitAr = [ false ];
203 this.scopes.push(scope);
204 token = this.ts.lookTok(1);
206 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
208 print(token.type + '.' + token.name+ ":" + token.data);
209 switch(token.type + '.' + token.name) {
211 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
213 //this.log("parseScope GOT VAR/CONST : " + token.toString());
215 token = this.ts.nextTok();
218 if (!token) { // can return false at EOF!
221 if (token.name != "VAR") { // kludge..
224 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
225 if (token.type !="NAME") {
226 print(token.toString());
227 throw "var without ident";
231 if (this.mode == "BUILDING_SYMBOL_TREE") {
232 identifier = scope.getIdentifier(token.data) ;
234 if (identifier == false) {
235 scope.declareIdentifier(token.data, token);
237 token.identifier = identifier;
238 this.warn("The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
242 token = this.ts.nextTok();
244 assert token.getType() == Token.SEMI ||
245 token.getType() == Token.ASSIGN ||
246 token.getType() == Token.COMMA ||
247 token.getType() == Token.IN;
249 if (token.name == "IN") {
252 this.parseExpression();
253 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
256 if (this.ts.lookTok(0).data == ';') {
262 case "KEYW.FUNCTION":
263 //println("<i>"+token.data+"</i>");
264 this.parseFunctionDeclaration();
267 case "KEYW.LEFT_CURLY": // {
268 //println("<i>"+token.data+"</i>");
269 isObjectLitAr.push(false);
273 case "KEYW.RIGHT_CURLY": // }
274 //println("<i>"+token.data+"</i>");
277 //assert braceNesting >= scope.getBraceNesting();
278 if (this.braceNesting == scope.braceN) {
279 var ls = this.scopes.pop();
286 //println("<i>"+token.data+"</i>");
287 if (this.mode == "BUILDING_SYMBOL_TREE") {
288 // Inside a 'with' block, it is impossible to figure out
289 // statically whether a symbol is a local variable or an
290 // object member. As a consequence, the only thing we can
291 // do is turn the obfuscation off for the highest scope
292 // containing the 'with' block.
293 this.protectScopeFromObfuscation(scope);
294 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
299 //println("<i>"+token.data+"</i>");
303 case Token.SPECIALCOMMENT:
304 if (mode == BUILDING_SYMBOL_TREE) {
305 protectScopeFromObfuscation(scope);
306 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
311 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
312 case "STRN.SINGLE_QUOTE":
313 //println("<i>"+token.data+"</i>");
314 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
315 // then we are in an object lit.. -> we need to flag the brace as such...
317 isObjectLitAr.push(true);
319 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
321 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
322 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
323 // see if we can replace..
324 // remove the quotes..
325 // should do a bit more checking!!!! (what about wierd char's in the string..
326 var str = token.data.substring(1,token.data.length-1);
327 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
341 //print("DEAL WITH NAME:");
344 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
345 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
347 isObjectLitAr.push(true);
348 //println("<i>"+token.data+"</i>");
351 // print("DEAL WITH obj lit:");
352 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
354 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
355 // skip, it's an object lit key..
356 //println("<i>"+token.data+"</i>");
361 // skip anyting with "." before it..!!
363 if (this.ts.lookTok(-1).data == ".") {
364 // skip, it's an object prop.
365 //println("<i>"+token.data+"</i>");
369 if (this.mode == 'CHECKING_SYMBOL_TREE') {
371 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
375 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
377 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
378 identifier = this.getIdentifier(symbol, scope);
380 if (identifier == false) {
381 // BUG!find out where builtin is defined...
382 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
383 // Here, we found an undeclared and un-namespaced symbol that is
384 // 3 characters or less in length. Declare it in the global scope.
385 // We don't need to declare longer symbols since they won't cause
386 // any conflict with other munged symbols.
387 this.globalScope.declareIdentifier(symbol, token);
388 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
391 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
393 token.identifier = identifier;
394 identifier.refcount++;
399 //println("<B>SID</B>");
401 if (token.type != 'KEYW') {
404 // print("Check eval:");
408 if (this.mode == 'BUILDING_SYMBOL_TREE') {
410 if (symbol == "eval") {
411 // look back one and see if we can find a comment!!!
412 if (this.ts.look(-1).type == "COMM") {
413 // look for eval:var:noreplace\n
415 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
417 var hi = _t.getIdentifier(a, scope);
418 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
420 // println("PROTECT "+a+" from munge");
430 this.protectScopeFromObfuscation(scope);
431 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);
443 //this.timerPrint("parseScope TOK : " + token.toString());
444 token = this.ts.nextTok();
445 //if (this.ts.nextT()) break;
451 parseExpression : function() {
453 // Parse the expression until we encounter a comma or a semi-colon
454 // in the same brace nesting, bracket nesting and paren nesting.
455 // Parse functions if any...
456 //println("<i>EXP</i><BR/>");
462 var expressionBraceNesting = this.braceNesting;
463 var bracketNesting = 0;
464 var parensNesting = 0;
466 var isObjectLitAr = [ false ];
467 while (token = this.ts.lookTok()) {
471 currentScope = this.scopes[this.scopes.length-1];
473 //println("<i>"+token.data+"</i>");
475 switch (token.data.toUpperCase()) {
479 if (this.braceNesting == expressionBraceNesting &&
480 bracketNesting == 0 &&
481 parensNesting == 0) {
487 this.parseFunctionDeclaration();
490 case '{': //Token.LC:
491 isObjectLitAr.push(false);
496 case '}': //Token.RC:
500 // assert braceNesting >= expressionBraceNesting;
503 case '[': //Token.LB:
507 case ']': //Token.RB:
511 case '(': //Token.LP:
515 case ')': //Token.RP:
521 case 'STRN': // used for object lit detection..
522 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
523 // then we are in an object lit.. -> we need to flag the brace as such...
525 isObjectLitAr.push(true);
530 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
531 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
532 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
533 // see if we can replace..
534 // remove the quotes..
535 var str = token.data.substring(1,token.data.length-1);
536 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
549 case Token.SPECIALCOMMENT:
550 if (mode == BUILDING_SYMBOL_TREE) {
551 protectScopeFromObfuscation(currentScope);
552 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression!" : ""), true);
559 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
560 // then we are in an object lit.. -> we need to flag the brace as such...
562 isObjectLitAr.push(true);
565 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
566 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
570 if (this.ts.lookTok(-1).data == ".") {
575 if (this.mode == 'CHECKING_SYMBOL_TREE') {
577 identifier = this.getIdentifier(symbol, currentScope);
578 //println("<B>??</B>");
579 if (identifier == false) {
581 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
582 // Here, we found an undeclared and un-namespaced symbol that is
583 // 3 characters or less in length. Declare it in the global scope.
584 // We don't need to declare longer symbols since they won't cause
585 // any conflict with other munged symbols.
586 this.globalScope.declareIdentifier(symbol, token);
587 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
589 //println("undeclared")
594 //println("<B>++</B>");
595 token.identifier = identifier;
596 identifier.refcount++;
605 //println("<B>EID</B>");
608 if (this.mode == 'BUILDING_SYMBOL_TREE') {
610 if (symbol == "eval") {
611 if (this.ts.look(-1).type == 'COMM') {
612 // look for eval:var:noreplace\n
614 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
615 var hi = _t.getIdentifier(a, currentScope);
616 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
618 // println("PROTECT "+a+" from munge");
626 this.protectScopeFromObfuscation(currentScope);
627 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
636 if (!this.ts.nextTok()) break;
641 parseCatch : function() {
648 //token = getToken(-1);
649 //assert token.getType() == Token.CATCH;
650 token = this.ts.nextTok();
651 //assert token.getType() == Token.LP; (
652 token = this.ts.nextTok();
653 //assert token.getType() == Token.NAME;
656 currentScope = this.scopes[this.scopes.length-1];
658 if (this.mode == 'BUILDING_SYMBOL_TREE') {
659 // We must declare the exception identifier in the containing function
660 // scope to avoid errors related to the obfuscation process. No need to
661 // display a warning if the symbol was already declared here...
662 currentScope.declareIdentifier(symbol, token);
664 //?? why inc the refcount?? - that should be set when building the tree???
665 identifier = this.getIdentifier(symbol, currentScope);
666 identifier.refcount++;
669 token = this.ts.nextTok();
670 //assert token.getType() == Token.RP; // )
673 parseFunctionDeclaration : function()
678 var currentScope = false;
681 //this.logR("<B>PARSING FUNCTION</B>");
682 currentScope = this.scopes[this.scopes.length-1];
684 token = this.ts.nextTok();
685 if (token.type == "NAME") {
686 if (this.mode == 'BUILDING_SYMBOL_TREE') {
687 // Get the name of the function and declare it in the current scope.
689 if (currentScope.getIdentifier(symbol) != false) {
690 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
692 currentScope.declareIdentifier(symbol,token);
694 token = this.ts.nextTok();
697 //assert token.getType() == Token.LP;
698 if (this.mode == 'BUILDING_SYMBOL_TREE') {
699 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
701 //println("STORING SCOPE" + this.ts.cursor);
703 this.indexedScopes[this.ts.cursor] = fnScope;
706 //println("FETCHING SCOPE" + this.ts.cursor);
707 fnScope = this.indexedScopes[this.ts.cursor];
710 // Parse function arguments.
712 while (!this.ts.lookTok().data == ')') { //(token = consumeToken()).getType() != Token.RP) {
713 token = this.ts.nextTok();
715 //assert token.getType() == Token.NAME ||
716 // token.getType() == Token.COMMA;
717 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
719 identifier = fnScope.declareIdentifier(symbol,token);
720 if (symbol == "$super" && argpos == 0) {
721 // Exception for Prototype 1.6...
722 identifier.preventMunging();
728 token = this.ts.nextTok();
729 // assert token.getType() == Token.LC;
732 token = this.ts.nextTok();
733 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
736 NOT SUPPORTED YET!?!!?!
738 // This is a hint. Hints are empty statements that look like
739 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
740 // to prevent specific symbols from getting obfuscated (some heretic
741 // implementations, such as Prototype 1.6, require specific variable
742 // names, such as $super for example, in order to work appropriately.
743 // Note: right now, only "nomunge" is supported in the right hand side
744 // of a hint. However, in the future, the right hand side may contain
747 String hints = token.getValue();
748 // Remove the leading and trailing quotes...
749 hints = hints.substring(1, hints.length() - 1).trim();
750 StringTokenizer st1 = new StringTokenizer(hints, ",");
751 while (st1.hasMoreTokens()) {
752 String hint = st1.nextToken();
753 int idx = hint.indexOf(':');
754 if (idx <= 0 || idx >= hint.length() - 1) {
755 if (mode == BUILDING_SYMBOL_TREE) {
756 // No need to report the error twice, hence the test...
757 this.warn("Invalid hint syntax: " + hint, true);
761 String variableName = hint.substring(0, idx).trim();
762 String variableType = hint.substring(idx + 1).trim();
763 if (mode == BUILDING_SYMBOL_TREE) {
764 fnScope.addHint(variableName, variableType);
765 } else if (mode == CHECKING_SYMBOL_TREE) {
766 identifier = fnScope.getIdentifier(variableName);
767 if (identifier != null) {
768 if (variableType.equals("nomunge")) {
769 identifier.preventMunging();
771 this.warn("Unsupported hint value: " + hint, true);
774 this.warn("Hint refers to an unknown identifier: " + hint, true);
781 this.parseScope(fnScope);
782 // now pop it off the stack!!!
788 protectScopeFromObfuscation : function(scope) {
789 //assert scope != null;
791 if (scope == this.globalScope) {
792 // The global scope does not get obfuscated,
793 // so we don't need to worry about it...
797 // Find the highest local scope containing the specified scope.
798 while (scope && scope.parent != this.globalScope) {
799 scope = scope.parent;
802 //assert scope.getParentScope() == globalScope;
803 scope.preventMunging();
806 getIdentifier: function(symbol, scope) {
808 while (scope != false) {
809 identifier = scope.getIdentifier(symbol);
810 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
814 scope = scope.parent;