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();
217 if (token.name == "var") { // kludge..
220 if (!token) { // can return false at EOF!
223 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
224 if (!token.type =="NAME") {
225 println(token.toString());
226 throw "var without ident";
230 if (this.mode == "BUILDING_SYMBOL_TREE") {
231 identifier = scope.getIdentifier(token.data) ;
233 if (identifier == false) {
234 scope.declareIdentifier(token.data, token);
236 token.identifier = identifier;
237 this.warn("The variable " + symbol + " has already been declared in the same scope...");
241 token = this.ts.nextTok();
243 assert token.getType() == Token.SEMI ||
244 token.getType() == Token.ASSIGN ||
245 token.getType() == Token.COMMA ||
246 token.getType() == Token.IN;
248 if (token.name == "IN") {
251 this.parseExpression();
252 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
255 if (this.ts.lookTok(0).data == ';') {
261 case "KEYW.FUNCTION":
262 //println("<i>"+token.data+"</i>");
263 this.parseFunctionDeclaration();
266 case "KEYW.LEFT_CURLY": // {
267 //println("<i>"+token.data+"</i>");
268 isObjectLitAr.push(false);
272 case "KEYW.RIGHT_CURLY": // }
273 //println("<i>"+token.data+"</i>");
276 //assert braceNesting >= scope.getBraceNesting();
277 if (this.braceNesting == scope.braceN) {
278 var ls = this.scopes.pop();
285 //println("<i>"+token.data+"</i>");
286 if (this.mode == "BUILDING_SYMBOL_TREE") {
287 // Inside a 'with' block, it is impossible to figure out
288 // statically whether a symbol is a local variable or an
289 // object member. As a consequence, the only thing we can
290 // do is turn the obfuscation off for the highest scope
291 // containing the 'with' block.
292 this.protectScopeFromObfuscation(scope);
293 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
298 //println("<i>"+token.data+"</i>");
302 case Token.SPECIALCOMMENT:
303 if (mode == BUILDING_SYMBOL_TREE) {
304 protectScopeFromObfuscation(scope);
305 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
310 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
311 case "STRN.SINGLE_QUOTE":
312 //println("<i>"+token.data+"</i>");
313 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
314 // then we are in an object lit.. -> we need to flag the brace as such...
316 isObjectLitAr.push(true);
318 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
320 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
321 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
322 // see if we can replace..
323 // remove the quotes..
324 // should do a bit more checking!!!! (what about wierd char's in the string..
325 var str = token.data.substring(1,token.data.length-1);
326 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
340 if ((token.type != "NAME") && (token.type != "KEYW")){
343 print("DEAL WITH NAME:");
346 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
347 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
349 isObjectLitAr.push(true);
350 //println("<i>"+token.data+"</i>");
353 print("DEAL WITH obj lit:");
354 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
356 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
357 // skip, it's an object lit key..
358 //println("<i>"+token.data+"</i>");
363 // skip anyting with "." before it..!!
365 if (this.ts.lookTok(-1).data(".")) {
366 // skip, it's an object prop.
367 //println("<i>"+token.data+"</i>");
371 //println("<B>SID</B>");
373 print("Check eval:");
377 if (this.mode == 'BUILDING_SYMBOL_TREE') {
379 if (symbol == "eval") {
380 // look back one and see if we can find a comment!!!
381 if (this.ts.look(-1).type == "COMM") {
382 // look for eval:var:noreplace\n
384 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
386 var hi = _t.getIdentifier(a, scope);
387 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
389 // println("PROTECT "+a+" from munge");
399 this.protectScopeFromObfuscation(scope);
400 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);
405 } else if (this.mode == 'CHECKING_SYMBOL_TREE') {
407 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
411 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
413 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
414 identifier = this.getIdentifier(symbol, scope);
416 if (identifier == false) {
417 // BUG!find out where builtin is defined...
418 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
419 // Here, we found an undeclared and un-namespaced symbol that is
420 // 3 characters or less in length. Declare it in the global scope.
421 // We don't need to declare longer symbols since they won't cause
422 // any conflict with other munged symbols.
423 this.globalScope.declareIdentifier(symbol, token);
424 this.warn("Found an undeclared symbol: " + symbol, true);
427 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
429 token.identifier = identifier;
430 identifier.refcount++;
440 //this.timerPrint("parseScope TOK : " + token.toString());
441 token = this.ts.nextTok();
442 //if (this.ts.nextT()) break;
448 parseExpression : function() {
450 // Parse the expression until we encounter a comma or a semi-colon
451 // in the same brace nesting, bracket nesting and paren nesting.
452 // Parse functions if any...
453 //println("<i>EXP</i><BR/>");
459 var expressionBraceNesting = this.braceNesting;
460 var bracketNesting = 0;
461 var parensNesting = 0;
463 var isObjectLitAr = [ false ];
464 while (token = this.ts.lookTok()) {
468 currentScope = this.scopes[this.scopes.length-1];
470 //println("<i>"+token.data+"</i>");
472 switch (token.data.toUpperCase()) {
476 if (this.braceNesting == expressionBraceNesting &&
477 bracketNesting == 0 &&
478 parensNesting == 0) {
484 this.parseFunctionDeclaration();
487 case '{': //Token.LC:
488 isObjectLitAr.push(false);
493 case '}': //Token.RC:
497 // assert braceNesting >= expressionBraceNesting;
500 case '[': //Token.LB:
504 case ']': //Token.RB:
508 case '(': //Token.LP:
512 case ')': //Token.RP:
518 case 'STRN': // used for object lit detection..
519 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
520 // then we are in an object lit.. -> we need to flag the brace as such...
522 isObjectLitAr.push(true);
527 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
528 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
529 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
530 // see if we can replace..
531 // remove the quotes..
532 var str = token.data.substring(1,token.data.length-1);
533 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
546 case Token.SPECIALCOMMENT:
547 if (mode == BUILDING_SYMBOL_TREE) {
548 protectScopeFromObfuscation(currentScope);
549 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression!" : ""), true);
556 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
557 // then we are in an object lit.. -> we need to flag the brace as such...
559 isObjectLitAr.push(true);
562 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
563 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
567 if (this.ts.lookTok(-1).data == ".") {
574 //println("<B>EID</B>");
577 if (this.mode == 'BUILDING_SYMBOL_TREE') {
579 if (symbol == "eval") {
580 if (this.ts.look(-1).type == 'COMM') {
581 // look for eval:var:noreplace\n
583 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
584 var hi = _t.getIdentifier(a, currentScope);
585 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
587 // println("PROTECT "+a+" from munge");
595 this.protectScopeFromObfuscation(currentScope);
596 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
603 if (this.mode == 'CHECKING_SYMBOL_TREE') {
605 identifier = this.getIdentifier(symbol, currentScope);
606 //println("<B>??</B>");
607 if (identifier == false) {
609 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
610 // Here, we found an undeclared and un-namespaced symbol that is
611 // 3 characters or less in length. Declare it in the global scope.
612 // We don't need to declare longer symbols since they won't cause
613 // any conflict with other munged symbols.
614 this.globalScope.declareIdentifier(symbol, token);
615 this.warn("Found an undeclared symbol: " + symbol, true);
617 //println("undeclared")
622 //println("<B>++</B>");
623 token.identifier = identifier;
624 identifier.refcount++;
630 if (!this.ts.nextTok()) break;
635 parseCatch : function() {
642 //token = getToken(-1);
643 //assert token.getType() == Token.CATCH;
644 token = this.ts.nextTok();
645 //assert token.getType() == Token.LP; (
646 token = this.ts.nextTok();
647 //assert token.getType() == Token.NAME;
650 currentScope = this.scopes[this.scopes.length-1];
652 if (this.mode == 'BUILDING_SYMBOL_TREE') {
653 // We must declare the exception identifier in the containing function
654 // scope to avoid errors related to the obfuscation process. No need to
655 // display a warning if the symbol was already declared here...
656 currentScope.declareIdentifier(symbol, token);
658 //?? why inc the refcount?? - that should be set when building the tree???
659 identifier = this.getIdentifier(symbol, currentScope);
660 identifier.refcount++;
663 token = this.ts.nextTok();
664 //assert token.getType() == Token.RP; // )
667 parseFunctionDeclaration : function()
672 var currentScope = false;
675 //this.logR("<B>PARSING FUNCTION</B>");
676 currentScope = this.scopes[this.scopes.length-1];
678 token = this.ts.nextTok();
679 if (token.type == "NAME") {
680 if (this.mode == 'BUILDING_SYMBOL_TREE') {
681 // Get the name of the function and declare it in the current scope.
683 if (currentScope.getIdentifier(symbol) != false) {
684 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
686 currentScope.declareIdentifier(symbol,token);
688 token = this.ts.nextTok();
691 //assert token.getType() == Token.LP;
692 if (this.mode == 'BUILDING_SYMBOL_TREE') {
693 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
695 //println("STORING SCOPE" + this.ts.cursor);
697 this.indexedScopes[this.ts.cursor] = fnScope;
700 //println("FETCHING SCOPE" + this.ts.cursor);
701 fnScope = this.indexedScopes[this.ts.cursor];
704 // Parse function arguments.
706 while (!this.ts.lookTok().data == ')') { //(token = consumeToken()).getType() != Token.RP) {
707 token = this.ts.nextTok();
709 //assert token.getType() == Token.NAME ||
710 // token.getType() == Token.COMMA;
711 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
713 identifier = fnScope.declareIdentifier(symbol,token);
714 if (symbol == "$super" && argpos == 0) {
715 // Exception for Prototype 1.6...
716 identifier.preventMunging();
722 token = this.ts.nextTok();
723 // assert token.getType() == Token.LC;
726 token = this.ts.nextTok();
727 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
730 NOT SUPPORTED YET!?!!?!
732 // This is a hint. Hints are empty statements that look like
733 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
734 // to prevent specific symbols from getting obfuscated (some heretic
735 // implementations, such as Prototype 1.6, require specific variable
736 // names, such as $super for example, in order to work appropriately.
737 // Note: right now, only "nomunge" is supported in the right hand side
738 // of a hint. However, in the future, the right hand side may contain
741 String hints = token.getValue();
742 // Remove the leading and trailing quotes...
743 hints = hints.substring(1, hints.length() - 1).trim();
744 StringTokenizer st1 = new StringTokenizer(hints, ",");
745 while (st1.hasMoreTokens()) {
746 String hint = st1.nextToken();
747 int idx = hint.indexOf(':');
748 if (idx <= 0 || idx >= hint.length() - 1) {
749 if (mode == BUILDING_SYMBOL_TREE) {
750 // No need to report the error twice, hence the test...
751 this.warn("Invalid hint syntax: " + hint, true);
755 String variableName = hint.substring(0, idx).trim();
756 String variableType = hint.substring(idx + 1).trim();
757 if (mode == BUILDING_SYMBOL_TREE) {
758 fnScope.addHint(variableName, variableType);
759 } else if (mode == CHECKING_SYMBOL_TREE) {
760 identifier = fnScope.getIdentifier(variableName);
761 if (identifier != null) {
762 if (variableType.equals("nomunge")) {
763 identifier.preventMunging();
765 this.warn("Unsupported hint value: " + hint, true);
768 this.warn("Hint refers to an unknown identifier: " + hint, true);
775 this.parseScope(fnScope);
776 // now pop it off the stack!!!
782 protectScopeFromObfuscation : function(scope) {
783 //assert scope != null;
785 if (scope == this.globalScope) {
786 // The global scope does not get obfuscated,
787 // so we don't need to worry about it...
791 // Find the highest local scope containing the specified scope.
792 while (scope && scope.parent != this.globalScope) {
793 scope = scope.parent;
796 //assert scope.getParentScope() == globalScope;
797 scope.preventMunging();
800 getIdentifier: function(symbol, scope) {
802 while (scope != false) {
803 identifier = scope.getIdentifier(symbol);
804 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
808 scope = scope.parent;