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;
207 (new Array(this.dumpLine.scope)).join(" ") + '|' +
208 (new Array(brace)).join(" ") + this.dumpLine.str);
213 scope : scope.length,
221 parseScope : function(scope) // parse a token stream..
223 //this.timerPrint("parseScope EnterScope");
224 //this.log(">>> ENTER SCOPE" + this.scopes.length);
230 var expressionBraceNesting = this.braceNesting;
232 var parensNesting = 0;
234 var isObjectLitAr = [ false ];
236 this.scopes.push(scope);
238 var scopeIndent = '';
239 this.scopes.forEach(function() {
242 print(scopeIndent + ">> ENTER SCOPE");
247 token = this.ts.lookTok(1);
249 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
250 this.dumpToken(token.data, this.scopes, expressionBraceNesting);
251 //this.log(token.data);
252 if (token.type == 'NAME') {
253 // print('*' + token.data);
255 switch(token.type + '.' + token.name) {
257 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
259 //this.log("parseScope GOT VAR/CONST : " + token.toString());
261 token = this.ts.nextTok();
262 !this.debug|| print( token.toString());
264 if (!token) { // can return false at EOF!
267 if (token.name == "VAR" || token.data == ',') { // kludge..
270 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
271 if (token.type !="NAME") {
272 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
273 print(this.ts.tokens[i].toString());
276 print( "var without ident");
281 if (this.mode == "BUILDING_SYMBOL_TREE") {
282 identifier = scope.getIdentifier(token.data) ;
284 if (identifier == false) {
285 scope.declareIdentifier(token.data, token);
287 token.identifier = identifier;
288 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
292 token = this.ts.nextTok();
293 !this.debug|| print(token.toString());
295 assert token.getType() == Token.SEMI ||
296 token.getType() == Token.ASSIGN ||
297 token.getType() == Token.COMMA ||
298 token.getType() == Token.IN;
300 if (token.name == "IN") {
303 //var bn = this.braceNesting;
304 this.parseExpression();
305 //this.braceNesting = bn;
306 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
308 token = this.ts.lookTok(1);
309 !this.debug|| print("AFTER EXP: " + token.toString());
310 if (token.data == ';') {
316 case "KEYW.FUNCTION":
317 //println("<i>"+token.data+"</i>");
318 var bn = this.braceNesting;
319 this.parseFunctionDeclaration();
320 this.braceNesting = bn;
323 case "PUNC.LEFT_CURLY": // {
324 //println("<i>"+token.data+"</i>");
325 isObjectLitAr.push(false);
328 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
331 case "PUNC.RIGHT_CURLY": // }
332 //println("<i>"+token.data+"</i>");
335 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
336 //assert braceNesting >= scope.getBra ceNesting();
338 if (this.braceNesting < expressionBraceNesting) {
339 var ls = this.scopes.pop();
341 // eat symbol if we are currently at {
342 if (this.ts.look(0).data == '{') {
346 //print("<<<<<<<EXIT SCOPE" +this.scopes.length);
352 //println("<i>"+token.data+"</i>");
353 if (this.mode == "BUILDING_SYMBOL_TREE") {
354 // Inside a 'with' block, it is impossible to figure out
355 // statically whether a symbol is a local variable or an
356 // object member. As a consequence, the only thing we can
357 // do is turn the obfuscation off for the highest scope
358 // containing the 'with' block.
359 this.protectScopeFromObfuscation(scope);
360 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
365 //println("<i>"+token.data+"</i>");
369 case Token.SPECIALCOMMENT:
370 if (mode == BUILDING_SYMBOL_TREE) {
371 protectScopeFromObfuscation(scope);
372 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
377 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
378 case "STRN.SINGLE_QUOTE":
379 //println("<i>"+token.data+"</i>");
380 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
381 // then we are in an object lit.. -> we need to flag the brace as such...
383 isObjectLitAr.push(true);
384 //print(">>>>>> OBJLIT REPUSH(true)");
386 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
388 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
389 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
390 // see if we can replace..
391 // remove the quotes..
392 // should do a bit more checking!!!! (what about wierd char's in the string..
393 var str = token.data.substring(1,token.data.length-1);
394 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
408 //print("DEAL WITH NAME:");
411 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
412 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
414 isObjectLitAr.push(true);
415 //print(">>>>>> OBJLIT REPUSH(true)");
416 //println("<i>"+token.data+"</i>");
419 // print("DEAL WITH obj lit:");
420 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
422 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
423 // skip, it's an object lit key..
424 //println("<i>"+token.data+"</i>");
429 // skip anyting with "." before it..!!
431 if (this.ts.lookTok(-1).data == ".") {
432 // skip, it's an object prop.
433 //println("<i>"+token.data+"</i>");
437 if (this.mode == 'PASS2_SYMBOL_TREE') {
439 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
441 //print ("MUNGE?" + symbol);
443 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
445 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
446 identifier = this.getIdentifier(symbol, scope);
448 if (identifier == false) {
449 // BUG!find out where builtin is defined...
450 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
451 // Here, we found an undeclared and un-namespaced symbol that is
452 // 3 characters or less in length. Declare it in the global scope.
453 // We don't need to declare longer symbols since they won't cause
454 // any conflict with other munged symbols.
455 this.globalScope.declareIdentifier(symbol, token);
456 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
459 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
461 token.identifier = identifier;
462 identifier.refcount++;
467 //println("<B>SID</B>");
469 if (token.type != 'KEYW') {
472 // print("Check eval:");
476 if (this.mode == 'BUILDING_SYMBOL_TREE') {
478 if (symbol == "eval") {
479 // look back one and see if we can find a comment!!!
480 if (this.ts.look(-1).type == "COMM") {
481 // look for eval:var:noreplace\n
483 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
485 var hi = _t.getIdentifier(a, scope);
486 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
488 // println("PROTECT "+a+" from munge");
498 this.protectScopeFromObfuscation(scope);
499 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);
511 //this.timerPrint("parseScope TOK : " + token.toString());
512 token = this.ts.nextTok();
513 //if (this.ts.nextT()) break;
516 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
520 parseExpression : function() {
522 // Parse the expression until we encounter a comma or a semi-colon
523 // in the same brace nesting, bracket nesting and paren nesting.
524 // Parse functions if any...
525 //println("<i>EXP</i><BR/>");
526 !this.debug || print("PARSE EXPR");
529 // for printing stuff..
538 var expressionBraceNesting = this.braceNesting;
539 var bracketNesting = 0;
540 var parensNesting = 0;
542 var isObjectLitAr = [ false ];
544 currentScope = this.scopes[this.scopes.length-1];
546 var scopeIndent = '';
547 this.scopes.forEach(function() {
550 print(scopeIndent + ">> ENTER EXPRESSION");
551 while (token = this.ts.lookTok()) {
556 // moved out of loop?
557 currentScope = this.scopes[this.scopes.length-1];
559 var scopeIndent = '';
560 this.scopes.forEach(function() {
564 print(scopeIndent + 'OBJLIT.len='+ isObjectLitAr.length + ' ' + token.data);
566 //println("<i>"+token.data+"</i>");
567 //this.log("EXP:" + token.data);
568 switch (token.type) {
574 if (this.braceNesting == expressionBraceNesting &&
575 bracketNesting == 0 &&
576 parensNesting == 0) {
577 print(scopeIndent + "<< EXIT EXPRESSION");
584 case '{': //Token.LC:
585 isObjectLitAr.push(false);
588 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
591 case '}': //Token.RC:
594 //print(">>>>> EXP POP" + this.braceNesting);
595 // assert braceNesting >= expressionBraceNesting;
598 case '[': //Token.LB:
602 case ']': //Token.RB:
606 case '(': //Token.LP:
610 case ')': //Token.RP:
616 case 'STRN': // used for object lit detection..
617 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
618 // then we are in an object lit.. -> we need to flag the brace as such...
620 isObjectLitAr.push(true);
621 //print(">>>>> EXP PUSH(true)");
626 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
627 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
628 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
629 // see if we can replace..
630 // remove the quotes..
631 var str = token.data.substring(1,token.data.length-1);
632 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
647 //print("in NAME = " + token.toString());
648 //print("in NAME 0: " + this.ts.look(0).toString());
649 //print("in NAME 2: " + this.ts.lookTok(2).toString());
650 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
651 // then we are in an object lit.. -> we need to flag the brace as such...
653 isObjectLitAr.push(true);
654 //print(">>>>> EXP PUSH(true)");
658 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
659 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
661 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
664 //print(this.ts.lookTok(0).data);
665 if (this.ts.lookTok(0).data == ".") {
670 if (this.mode == 'PASS2_SYMBOL_TREE') {
672 identifier = this.getIdentifier(symbol, currentScope);
673 //println("<B>??</B>");
674 if (identifier == false) {
676 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
677 // Here, we found an undeclared and un-namespaced symbol that is
678 // 3 characters or less in length. Declare it in the global scope.
679 // We don't need to declare longer symbols since they won't cause
680 // any conflict with other munged symbols.
681 this.globalScope.declareIdentifier(symbol, token);
682 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
684 //println("undeclared")
689 //println("<B>++</B>");
690 token.identifier = identifier;
691 identifier.refcount++;
700 //println("<B>EID</B>");
703 if (token.name == "FUNCTION") {
705 this.parseFunctionDeclaration();
712 if (this.mode == 'BUILDING_SYMBOL_TREE') {
714 if (symbol == "eval") {
715 if (this.ts.look(-1).type == 'COMM') {
716 // look for eval:var:noreplace\n
718 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
719 var hi = _t.getIdentifier(a, currentScope);
720 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
722 // println("PROTECT "+a+" from munge");
730 this.protectScopeFromObfuscation(currentScope);
731 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
740 if (!this.ts.nextTok()) break;
742 print(scopeIndent + "<< EXIT EXPRESSION");
746 parseCatch : function() {
753 //token = getToken(-1);
754 //assert token.getType() == Token.CATCH;
755 token = this.ts.nextTok();
756 //assert token.getType() == Token.LP; (
757 token = this.ts.nextTok();
758 //assert token.getType() == Token.NAME;
761 currentScope = this.scopes[this.scopes.length-1];
763 if (this.mode == 'BUILDING_SYMBOL_TREE') {
764 // We must declare the exception identifier in the containing function
765 // scope to avoid errors related to the obfuscation process. No need to
766 // display a warning if the symbol was already declared here...
767 currentScope.declareIdentifier(symbol, token);
769 //?? why inc the refcount?? - that should be set when building the tree???
770 identifier = this.getIdentifier(symbol, currentScope);
771 identifier.refcount++;
774 token = this.ts.nextTok();
775 //assert token.getType() == Token.RP; // )
778 parseFunctionDeclaration : function()
780 // print("PARSE FUNCTION");
783 var currentScope = false;
786 //this.logR("<B>PARSING FUNCTION</B>");
787 currentScope = this.scopes[this.scopes.length-1];
789 token = this.ts.nextTok();
790 if (token.type == "NAME") {
791 if (this.mode == 'BUILDING_SYMBOL_TREE') {
792 // Get the name of the function and declare it in the current scope.
794 if (currentScope.getIdentifier(symbol) != false) {
795 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
797 currentScope.declareIdentifier(symbol,token);
799 token = this.ts.nextTok();
802 //assert token.getType() == Token.LP;
803 if (this.mode == 'BUILDING_SYMBOL_TREE') {
804 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
806 //println("STORING SCOPE" + this.ts.cursor);
808 this.indexedScopes[this.ts.cursor] = fnScope;
811 //qln("FETCHING SCOPE" + this.ts.cursor);
812 fnScope = this.indexedScopes[this.ts.cursor];
816 // Parse function arguments.
818 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
819 token = this.ts.nextTok();
820 // print ("FUNC ARGS: " + token.toString())
821 //assert token.getType() == Token.NAME ||
822 // token.getType() == Token.COMMA;
823 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
825 identifier = fnScope.declareIdentifier(symbol,token);
826 if (symbol == "$super" && argpos == 0) {
827 // Exception for Prototype 1.6...
828 identifier.preventMunging();
834 token = this.ts.nextTok();
835 // assert token.getType() == Token.LC;
838 token = this.ts.nextTok();
839 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
842 NOT SUPPORTED YET!?!!?!
844 // This is a hint. Hints are empty statements that look like
845 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
846 // to prevent specific symbols from getting obfuscated (some heretic
847 // implementations, such as Prototype 1.6, require specific variable
848 // names, such as $super for example, in order to work appropriately.
849 // Note: right now, only "nomunge" is supported in the right hand side
850 // of a hint. However, in the future, the right hand side may contain
853 String hints = token.getValue();
854 // Remove the leading and trailing quotes...
855 hints = hints.substring(1, hints.length() - 1).trim();
856 StringTokenizer st1 = new StringTokenizer(hints, ",");
857 while (st1.hasMoreTokens()) {
858 String hint = st1.nextToken();
859 int idx = hint.indexOf(':');
860 if (idx <= 0 || idx >= hint.length() - 1) {
861 if (mode == BUILDING_SYMBOL_TREE) {
862 // No need to report the error twice, hence the test...
863 this.warn("Invalid hint syntax: " + hint, true);
867 String variableName = hint.substring(0, idx).trim();
868 String variableType = hint.substring(idx + 1).trim();
869 if (mode == BUILDING_SYMBOL_TREE) {
870 fnScope.addHint(variableName, variableType);
871 } else if (mode == CHECKING_SYMBOL_TREE) {
872 identifier = fnScope.getIdentifier(variableName);
873 if (identifier != null) {
874 if (variableType.equals("nomunge")) {
875 identifier.preventMunging();
877 this.warn("Unsupported hint value: " + hint, true);
880 this.warn("Hint refers to an unknown identifier: " + hint, true);
887 this.parseScope(fnScope);
888 // now pop it off the stack!!!
894 protectScopeFromObfuscation : function(scope) {
895 //assert scope != null;
897 if (scope == this.globalScope) {
898 // The global scope does not get obfuscated,
899 // so we don't need to worry about it...
903 // Find the highest local scope containing the specified scope.
904 while (scope && scope.parent != this.globalScope) {
905 scope = scope.parent;
908 //assert scope.getParentScope() == globalScope;
909 scope.preventMunging();
912 getIdentifier: function(symbol, scope) {
914 while (scope != false) {
915 identifier = scope.getIdentifier(symbol);
916 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
920 scope = scope.parent;