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 print( "var without ident");
232 if (this.mode == "BUILDING_SYMBOL_TREE") {
233 identifier = scope.getIdentifier(token.data) ;
235 if (identifier == false) {
236 scope.declareIdentifier(token.data, token);
238 token.identifier = identifier;
239 this.warn("The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
243 token = this.ts.nextTok();
245 assert token.getType() == Token.SEMI ||
246 token.getType() == Token.ASSIGN ||
247 token.getType() == Token.COMMA ||
248 token.getType() == Token.IN;
250 if (token.name == "IN") {
253 this.parseExpression();
254 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
257 if (this.ts.lookTok(0).data == ';') {
263 case "KEYW.FUNCTION":
264 //println("<i>"+token.data+"</i>");
265 this.parseFunctionDeclaration();
268 case "KEYW.LEFT_CURLY": // {
269 //println("<i>"+token.data+"</i>");
270 isObjectLitAr.push(false);
274 case "KEYW.RIGHT_CURLY": // }
275 //println("<i>"+token.data+"</i>");
278 //assert braceNesting >= scope.getBraceNesting();
279 if (this.braceNesting == scope.braceN) {
280 var ls = this.scopes.pop();
287 //println("<i>"+token.data+"</i>");
288 if (this.mode == "BUILDING_SYMBOL_TREE") {
289 // Inside a 'with' block, it is impossible to figure out
290 // statically whether a symbol is a local variable or an
291 // object member. As a consequence, the only thing we can
292 // do is turn the obfuscation off for the highest scope
293 // containing the 'with' block.
294 this.protectScopeFromObfuscation(scope);
295 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
300 //println("<i>"+token.data+"</i>");
304 case Token.SPECIALCOMMENT:
305 if (mode == BUILDING_SYMBOL_TREE) {
306 protectScopeFromObfuscation(scope);
307 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
312 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
313 case "STRN.SINGLE_QUOTE":
314 //println("<i>"+token.data+"</i>");
315 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
316 // then we are in an object lit.. -> we need to flag the brace as such...
318 isObjectLitAr.push(true);
320 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
322 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
323 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
324 // see if we can replace..
325 // remove the quotes..
326 // should do a bit more checking!!!! (what about wierd char's in the string..
327 var str = token.data.substring(1,token.data.length-1);
328 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
342 //print("DEAL WITH NAME:");
345 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
346 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
348 isObjectLitAr.push(true);
349 //println("<i>"+token.data+"</i>");
352 // print("DEAL WITH obj lit:");
353 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
355 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
356 // skip, it's an object lit key..
357 //println("<i>"+token.data+"</i>");
362 // skip anyting with "." before it..!!
364 if (this.ts.lookTok(-1).data == ".") {
365 // skip, it's an object prop.
366 //println("<i>"+token.data+"</i>");
370 if (this.mode == 'CHECKING_SYMBOL_TREE') {
372 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
376 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
378 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
379 identifier = this.getIdentifier(symbol, scope);
381 if (identifier == false) {
382 // BUG!find out where builtin is defined...
383 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
384 // Here, we found an undeclared and un-namespaced symbol that is
385 // 3 characters or less in length. Declare it in the global scope.
386 // We don't need to declare longer symbols since they won't cause
387 // any conflict with other munged symbols.
388 this.globalScope.declareIdentifier(symbol, token);
389 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
392 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
394 token.identifier = identifier;
395 identifier.refcount++;
400 //println("<B>SID</B>");
402 if (token.type != 'KEYW') {
405 // print("Check eval:");
409 if (this.mode == 'BUILDING_SYMBOL_TREE') {
411 if (symbol == "eval") {
412 // look back one and see if we can find a comment!!!
413 if (this.ts.look(-1).type == "COMM") {
414 // look for eval:var:noreplace\n
416 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
418 var hi = _t.getIdentifier(a, scope);
419 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
421 // println("PROTECT "+a+" from munge");
431 this.protectScopeFromObfuscation(scope);
432 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);
444 //this.timerPrint("parseScope TOK : " + token.toString());
445 token = this.ts.nextTok();
446 //if (this.ts.nextT()) break;
452 parseExpression : function() {
454 // Parse the expression until we encounter a comma or a semi-colon
455 // in the same brace nesting, bracket nesting and paren nesting.
456 // Parse functions if any...
457 //println("<i>EXP</i><BR/>");
463 var expressionBraceNesting = this.braceNesting;
464 var bracketNesting = 0;
465 var parensNesting = 0;
467 var isObjectLitAr = [ false ];
468 while (token = this.ts.lookTok()) {
472 currentScope = this.scopes[this.scopes.length-1];
474 //println("<i>"+token.data+"</i>");
476 switch (token.data.toUpperCase()) {
480 if (this.braceNesting == expressionBraceNesting &&
481 bracketNesting == 0 &&
482 parensNesting == 0) {
488 this.parseFunctionDeclaration();
491 case '{': //Token.LC:
492 isObjectLitAr.push(false);
497 case '}': //Token.RC:
501 // assert braceNesting >= expressionBraceNesting;
504 case '[': //Token.LB:
508 case ']': //Token.RB:
512 case '(': //Token.LP:
516 case ')': //Token.RP:
522 case 'STRN': // used for object lit detection..
523 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
524 // then we are in an object lit.. -> we need to flag the brace as such...
526 isObjectLitAr.push(true);
531 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
532 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
533 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
534 // see if we can replace..
535 // remove the quotes..
536 var str = token.data.substring(1,token.data.length-1);
537 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
550 case Token.SPECIALCOMMENT:
551 if (mode == BUILDING_SYMBOL_TREE) {
552 protectScopeFromObfuscation(currentScope);
553 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression!" : ""), true);
560 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
561 // then we are in an object lit.. -> we need to flag the brace as such...
563 isObjectLitAr.push(true);
566 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
567 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
571 if (this.ts.lookTok(-1).data == ".") {
576 if (this.mode == 'CHECKING_SYMBOL_TREE') {
578 identifier = this.getIdentifier(symbol, currentScope);
579 //println("<B>??</B>");
580 if (identifier == false) {
582 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
583 // Here, we found an undeclared and un-namespaced symbol that is
584 // 3 characters or less in length. Declare it in the global scope.
585 // We don't need to declare longer symbols since they won't cause
586 // any conflict with other munged symbols.
587 this.globalScope.declareIdentifier(symbol, token);
588 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
590 //println("undeclared")
595 //println("<B>++</B>");
596 token.identifier = identifier;
597 identifier.refcount++;
606 //println("<B>EID</B>");
609 if (this.mode == 'BUILDING_SYMBOL_TREE') {
611 if (symbol == "eval") {
612 if (this.ts.look(-1).type == 'COMM') {
613 // look for eval:var:noreplace\n
615 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
616 var hi = _t.getIdentifier(a, currentScope);
617 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
619 // println("PROTECT "+a+" from munge");
627 this.protectScopeFromObfuscation(currentScope);
628 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
637 if (!this.ts.nextTok()) break;
642 parseCatch : function() {
649 //token = getToken(-1);
650 //assert token.getType() == Token.CATCH;
651 token = this.ts.nextTok();
652 //assert token.getType() == Token.LP; (
653 token = this.ts.nextTok();
654 //assert token.getType() == Token.NAME;
657 currentScope = this.scopes[this.scopes.length-1];
659 if (this.mode == 'BUILDING_SYMBOL_TREE') {
660 // We must declare the exception identifier in the containing function
661 // scope to avoid errors related to the obfuscation process. No need to
662 // display a warning if the symbol was already declared here...
663 currentScope.declareIdentifier(symbol, token);
665 //?? why inc the refcount?? - that should be set when building the tree???
666 identifier = this.getIdentifier(symbol, currentScope);
667 identifier.refcount++;
670 token = this.ts.nextTok();
671 //assert token.getType() == Token.RP; // )
674 parseFunctionDeclaration : function()
679 var currentScope = false;
682 //this.logR("<B>PARSING FUNCTION</B>");
683 currentScope = this.scopes[this.scopes.length-1];
685 token = this.ts.nextTok();
686 if (token.type == "NAME") {
687 if (this.mode == 'BUILDING_SYMBOL_TREE') {
688 // Get the name of the function and declare it in the current scope.
690 if (currentScope.getIdentifier(symbol) != false) {
691 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
693 currentScope.declareIdentifier(symbol,token);
695 token = this.ts.nextTok();
698 //assert token.getType() == Token.LP;
699 if (this.mode == 'BUILDING_SYMBOL_TREE') {
700 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
702 //println("STORING SCOPE" + this.ts.cursor);
704 this.indexedScopes[this.ts.cursor] = fnScope;
707 //println("FETCHING SCOPE" + this.ts.cursor);
708 fnScope = this.indexedScopes[this.ts.cursor];
711 // Parse function arguments.
713 while (!this.ts.lookTok().data == ')') { //(token = consumeToken()).getType() != Token.RP) {
714 token = this.ts.nextTok();
716 //assert token.getType() == Token.NAME ||
717 // token.getType() == Token.COMMA;
718 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
720 identifier = fnScope.declareIdentifier(symbol,token);
721 if (symbol == "$super" && argpos == 0) {
722 // Exception for Prototype 1.6...
723 identifier.preventMunging();
729 token = this.ts.nextTok();
730 // assert token.getType() == Token.LC;
733 token = this.ts.nextTok();
734 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
737 NOT SUPPORTED YET!?!!?!
739 // This is a hint. Hints are empty statements that look like
740 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
741 // to prevent specific symbols from getting obfuscated (some heretic
742 // implementations, such as Prototype 1.6, require specific variable
743 // names, such as $super for example, in order to work appropriately.
744 // Note: right now, only "nomunge" is supported in the right hand side
745 // of a hint. However, in the future, the right hand side may contain
748 String hints = token.getValue();
749 // Remove the leading and trailing quotes...
750 hints = hints.substring(1, hints.length() - 1).trim();
751 StringTokenizer st1 = new StringTokenizer(hints, ",");
752 while (st1.hasMoreTokens()) {
753 String hint = st1.nextToken();
754 int idx = hint.indexOf(':');
755 if (idx <= 0 || idx >= hint.length() - 1) {
756 if (mode == BUILDING_SYMBOL_TREE) {
757 // No need to report the error twice, hence the test...
758 this.warn("Invalid hint syntax: " + hint, true);
762 String variableName = hint.substring(0, idx).trim();
763 String variableType = hint.substring(idx + 1).trim();
764 if (mode == BUILDING_SYMBOL_TREE) {
765 fnScope.addHint(variableName, variableType);
766 } else if (mode == CHECKING_SYMBOL_TREE) {
767 identifier = fnScope.getIdentifier(variableName);
768 if (identifier != null) {
769 if (variableType.equals("nomunge")) {
770 identifier.preventMunging();
772 this.warn("Unsupported hint value: " + hint, true);
775 this.warn("Hint refers to an unknown identifier: " + hint, true);
782 this.parseScope(fnScope);
783 // now pop it off the stack!!!
789 protectScopeFromObfuscation : function(scope) {
790 //assert scope != null;
792 if (scope == this.globalScope) {
793 // The global scope does not get obfuscated,
794 // so we don't need to worry about it...
798 // Find the highest local scope containing the specified scope.
799 while (scope && scope.parent != this.globalScope) {
800 scope = scope.parent;
803 //assert scope.getParentScope() == globalScope;
804 scope.preventMunging();
807 getIdentifier: function(symbol, scope) {
809 while (scope != false) {
810 identifier = scope.getIdentifier(symbol);
811 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
815 scope = scope.parent;