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 , 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() {
565 this.dumpToken(token, this.scopes, this.braceNesting );
568 //println("<i>"+token.data+"</i>");
569 //this.log("EXP:" + token.data);
570 switch (token.type) {
576 if (this.braceNesting == expressionBraceNesting &&
577 bracketNesting == 0 &&
578 parensNesting == 0) {
579 print(scopeIndent + "<< EXIT EXPRESSION");
586 case '{': //Token.LC:
587 isObjectLitAr.push(false);
590 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
593 case '}': //Token.RC:
596 //print(">>>>> EXP POP" + this.braceNesting);
597 // assert braceNesting >= expressionBraceNesting;
600 case '[': //Token.LB:
604 case ']': //Token.RB:
608 case '(': //Token.LP:
612 case ')': //Token.RP:
618 case 'STRN': // used for object lit detection..
619 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
620 // then we are in an object lit.. -> we need to flag the brace as such...
622 isObjectLitAr.push(true);
623 //print(">>>>> EXP PUSH(true)");
628 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
629 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
630 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
631 // see if we can replace..
632 // remove the quotes..
633 var str = token.data.substring(1,token.data.length-1);
634 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
649 //print("in NAME = " + token.toString());
650 //print("in NAME 0: " + this.ts.look(0).toString());
651 //print("in NAME 2: " + this.ts.lookTok(2).toString());
652 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
653 // then we are in an object lit.. -> we need to flag the brace as such...
655 isObjectLitAr.push(true);
656 //print(">>>>> EXP PUSH(true)");
660 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
661 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
663 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
666 //print(this.ts.lookTok(0).data);
667 if (this.ts.lookTok(0).data == ".") {
672 if (this.mode == 'PASS2_SYMBOL_TREE') {
674 identifier = this.getIdentifier(symbol, currentScope);
675 //println("<B>??</B>");
676 if (identifier == false) {
678 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
679 // Here, we found an undeclared and un-namespaced symbol that is
680 // 3 characters or less in length. Declare it in the global scope.
681 // We don't need to declare longer symbols since they won't cause
682 // any conflict with other munged symbols.
683 this.globalScope.declareIdentifier(symbol, token);
684 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
686 //println("undeclared")
691 //println("<B>++</B>");
692 token.identifier = identifier;
693 identifier.refcount++;
702 //println("<B>EID</B>");
705 if (token.name == "FUNCTION") {
707 this.parseFunctionDeclaration();
714 if (this.mode == 'BUILDING_SYMBOL_TREE') {
716 if (symbol == "eval") {
717 if (this.ts.look(-1).type == 'COMM') {
718 // look for eval:var:noreplace\n
720 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
721 var hi = _t.getIdentifier(a, currentScope);
722 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
724 // println("PROTECT "+a+" from munge");
732 this.protectScopeFromObfuscation(currentScope);
733 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
742 if (!this.ts.nextTok()) break;
744 print(scopeIndent + "<< EXIT EXPRESSION");
748 parseCatch : function() {
755 //token = getToken(-1);
756 //assert token.getType() == Token.CATCH;
757 token = this.ts.nextTok();
758 //assert token.getType() == Token.LP; (
759 token = this.ts.nextTok();
760 //assert token.getType() == Token.NAME;
763 currentScope = this.scopes[this.scopes.length-1];
765 if (this.mode == 'BUILDING_SYMBOL_TREE') {
766 // We must declare the exception identifier in the containing function
767 // scope to avoid errors related to the obfuscation process. No need to
768 // display a warning if the symbol was already declared here...
769 currentScope.declareIdentifier(symbol, token);
771 //?? why inc the refcount?? - that should be set when building the tree???
772 identifier = this.getIdentifier(symbol, currentScope);
773 identifier.refcount++;
776 token = this.ts.nextTok();
777 //assert token.getType() == Token.RP; // )
780 parseFunctionDeclaration : function()
782 // print("PARSE FUNCTION");
785 var currentScope = false;
788 //this.logR("<B>PARSING FUNCTION</B>");
789 currentScope = this.scopes[this.scopes.length-1];
791 token = this.ts.nextTok();
792 if (token.type == "NAME") {
793 if (this.mode == 'BUILDING_SYMBOL_TREE') {
794 // Get the name of the function and declare it in the current scope.
796 if (currentScope.getIdentifier(symbol) != false) {
797 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
799 currentScope.declareIdentifier(symbol,token);
801 token = this.ts.nextTok();
804 //assert token.getType() == Token.LP;
805 if (this.mode == 'BUILDING_SYMBOL_TREE') {
806 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
808 //println("STORING SCOPE" + this.ts.cursor);
810 this.indexedScopes[this.ts.cursor] = fnScope;
813 //qln("FETCHING SCOPE" + this.ts.cursor);
814 fnScope = this.indexedScopes[this.ts.cursor];
818 // Parse function arguments.
820 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
821 token = this.ts.nextTok();
822 // print ("FUNC ARGS: " + token.toString())
823 //assert token.getType() == Token.NAME ||
824 // token.getType() == Token.COMMA;
825 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
827 identifier = fnScope.declareIdentifier(symbol,token);
828 if (symbol == "$super" && argpos == 0) {
829 // Exception for Prototype 1.6...
830 identifier.preventMunging();
836 token = this.ts.nextTok();
837 // assert token.getType() == Token.LC;
840 token = this.ts.nextTok();
841 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
844 NOT SUPPORTED YET!?!!?!
846 // This is a hint. Hints are empty statements that look like
847 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
848 // to prevent specific symbols from getting obfuscated (some heretic
849 // implementations, such as Prototype 1.6, require specific variable
850 // names, such as $super for example, in order to work appropriately.
851 // Note: right now, only "nomunge" is supported in the right hand side
852 // of a hint. However, in the future, the right hand side may contain
855 String hints = token.getValue();
856 // Remove the leading and trailing quotes...
857 hints = hints.substring(1, hints.length() - 1).trim();
858 StringTokenizer st1 = new StringTokenizer(hints, ",");
859 while (st1.hasMoreTokens()) {
860 String hint = st1.nextToken();
861 int idx = hint.indexOf(':');
862 if (idx <= 0 || idx >= hint.length() - 1) {
863 if (mode == BUILDING_SYMBOL_TREE) {
864 // No need to report the error twice, hence the test...
865 this.warn("Invalid hint syntax: " + hint, true);
869 String variableName = hint.substring(0, idx).trim();
870 String variableType = hint.substring(idx + 1).trim();
871 if (mode == BUILDING_SYMBOL_TREE) {
872 fnScope.addHint(variableName, variableType);
873 } else if (mode == CHECKING_SYMBOL_TREE) {
874 identifier = fnScope.getIdentifier(variableName);
875 if (identifier != null) {
876 if (variableType.equals("nomunge")) {
877 identifier.preventMunging();
879 this.warn("Unsupported hint value: " + hint, true);
882 this.warn("Hint refers to an unknown identifier: " + hint, true);
889 this.parseScope(fnScope);
890 // now pop it off the stack!!!
896 protectScopeFromObfuscation : function(scope) {
897 //assert scope != null;
899 if (scope == this.globalScope) {
900 // The global scope does not get obfuscated,
901 // so we don't need to worry about it...
905 // Find the highest local scope containing the specified scope.
906 while (scope && scope.parent != this.globalScope) {
907 scope = scope.parent;
910 //assert scope.getParentScope() == globalScope;
911 scope.preventMunging();
914 getIdentifier: function(symbol, scope) {
916 while (scope != false) {
917 identifier = scope.getIdentifier(symbol);
918 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
922 scope = scope.parent;