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 mungeSymboltree : function()
143 // One problem with obfuscation resides in the use of undeclared
144 // and un-namespaced global symbols that are 3 characters or less
145 // in length. Here is an example:
147 // var declaredGlobalVar;
149 // function declaredGlobalFn() {
151 // localvar = abc; // abc is an undeclared global symbol
154 // In the example above, there is a slim chance that localvar may be
155 // munged to 'abc', conflicting with the undeclared global symbol
156 // abc, creating a potential bug. The following code detects such
157 // global symbols. This must be done AFTER the entire file has been
158 // parsed, and BEFORE munging the symbol tree. Note that declaring
159 // extra symbols in the global scope won't hurt.
161 // Note: Since we go through all the tokens to do this, we also use
162 // the opportunity to count how many times each identifier is used.
165 this.braceNesting = 0;
167 this.mode = 'PASS2_SYMBOL_TREE';
169 //println("MUNGING?");
171 this.parseScope(this.globalScope);
172 this.globalScope.munge();
178 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
182 //println("<B>LOG:</B>" + str + "<BR/>");
190 parseScope : function(scope) // parse a token stream..
192 //this.timerPrint("parseScope EnterScope");
193 print(">>> ENTER SCOPE");
199 var expressionBraceNesting = this.braceNesting;
200 var bracketNesting = 0;
201 var parensNesting = 0;
203 var isObjectLitAr = [ false ];
205 this.scopes.push(scope);
206 token = this.ts.lookTok(1);
208 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
210 !this.debug|| print(token.type + '.' + token.name+ ":" + token.data);
211 switch(token.type + '.' + token.name) {
213 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
215 //this.log("parseScope GOT VAR/CONST : " + token.toString());
217 token = this.ts.nextTok();
218 !this.debug|| print( token.toString());
220 if (!token) { // can return false at EOF!
223 if (token.name == "VAR") { // kludge..
226 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
227 if (token.type !="NAME") {
228 print(token.toString());
229 print( "var without ident");
234 if (this.mode == "BUILDING_SYMBOL_TREE") {
235 identifier = scope.getIdentifier(token.data) ;
237 if (identifier == false) {
238 scope.declareIdentifier(token.data, token);
240 token.identifier = identifier;
241 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
245 token = this.ts.nextTok();
246 !this.debug|| print(token.toString());
248 assert token.getType() == Token.SEMI ||
249 token.getType() == Token.ASSIGN ||
250 token.getType() == Token.COMMA ||
251 token.getType() == Token.IN;
253 if (token.name == "IN") {
256 this.parseExpression();
257 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
259 token = this.ts.lookTok(1);
260 !this.debug|| print("AFTER EXP: " + token.toString());
261 if (token.data == ';') {
267 case "KEYW.FUNCTION":
268 //println("<i>"+token.data+"</i>");
269 this.parseFunctionDeclaration();
272 case "KEYW.LEFT_CURLY": // {
273 //println("<i>"+token.data+"</i>");
274 isObjectLitAr.push(false);
275 print(">>>>>> OBJLIT PUSH(false)");
279 case "KEYW.RIGHT_CURLY": // }
280 //println("<i>"+token.data+"</i>");
283 print(">>>>>> OBJLIT POP(false)");
284 //assert braceNesting >= scope.getBraceNesting();
285 if (this.braceNesting == scope.braceN) {
286 var ls = this.scopes.pop();
288 print("<<<<<<<EXIT SCOPE");
294 //println("<i>"+token.data+"</i>");
295 if (this.mode == "BUILDING_SYMBOL_TREE") {
296 // Inside a 'with' block, it is impossible to figure out
297 // statically whether a symbol is a local variable or an
298 // object member. As a consequence, the only thing we can
299 // do is turn the obfuscation off for the highest scope
300 // containing the 'with' block.
301 this.protectScopeFromObfuscation(scope);
302 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
307 //println("<i>"+token.data+"</i>");
311 case Token.SPECIALCOMMENT:
312 if (mode == BUILDING_SYMBOL_TREE) {
313 protectScopeFromObfuscation(scope);
314 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
319 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
320 case "STRN.SINGLE_QUOTE":
321 //println("<i>"+token.data+"</i>");
322 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
323 // then we are in an object lit.. -> we need to flag the brace as such...
325 isObjectLitAr.push(true);
326 print(">>>>>> OBJLIT PUSH(true)");
328 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
330 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
331 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
332 // see if we can replace..
333 // remove the quotes..
334 // should do a bit more checking!!!! (what about wierd char's in the string..
335 var str = token.data.substring(1,token.data.length-1);
336 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
350 //print("DEAL WITH NAME:");
353 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
354 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
356 isObjectLitAr.push(true);
357 print(">>>>>> OBJLIT PUSH(true)");
358 //println("<i>"+token.data+"</i>");
361 // print("DEAL WITH obj lit:");
362 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
364 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
365 // skip, it's an object lit key..
366 //println("<i>"+token.data+"</i>");
371 // skip anyting with "." before it..!!
373 if (this.ts.lookTok(-1).data == ".") {
374 // skip, it's an object prop.
375 //println("<i>"+token.data+"</i>");
379 if (this.mode == 'PASS2_SYMBOL_TREE') {
381 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
383 //print ("MUNGE?" + symbol);
385 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
387 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
388 identifier = this.getIdentifier(symbol, scope);
390 if (identifier == false) {
391 // BUG!find out where builtin is defined...
392 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
393 // Here, we found an undeclared and un-namespaced symbol that is
394 // 3 characters or less in length. Declare it in the global scope.
395 // We don't need to declare longer symbols since they won't cause
396 // any conflict with other munged symbols.
397 this.globalScope.declareIdentifier(symbol, token);
398 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
401 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
403 token.identifier = identifier;
404 identifier.refcount++;
409 //println("<B>SID</B>");
411 if (token.type != 'KEYW') {
414 // print("Check eval:");
418 if (this.mode == 'BUILDING_SYMBOL_TREE') {
420 if (symbol == "eval") {
421 // look back one and see if we can find a comment!!!
422 if (this.ts.look(-1).type == "COMM") {
423 // look for eval:var:noreplace\n
425 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
427 var hi = _t.getIdentifier(a, scope);
428 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
430 // println("PROTECT "+a+" from munge");
440 this.protectScopeFromObfuscation(scope);
441 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);
453 //this.timerPrint("parseScope TOK : " + token.toString());
454 token = this.ts.nextTok();
455 //if (this.ts.nextT()) break;
461 parseExpression : function() {
463 // Parse the expression until we encounter a comma or a semi-colon
464 // in the same brace nesting, bracket nesting and paren nesting.
465 // Parse functions if any...
466 //println("<i>EXP</i><BR/>");
467 !this.debug || print("PARSE EXPR");
473 var expressionBraceNesting = this.braceNesting;
474 var bracketNesting = 0;
475 var parensNesting = 0;
477 var isObjectLitAr = [ false ];
478 while (token = this.ts.lookTok()) {
482 currentScope = this.scopes[this.scopes.length-1];
484 //println("<i>"+token.data+"</i>");
485 !this.debug|| print ("EXP" + token.toString());
486 switch (token.type) {
492 if (this.braceNesting == expressionBraceNesting &&
493 bracketNesting == 0 &&
494 parensNesting == 0) {
502 case '{': //Token.LC:
503 isObjectLitAr.push(false);
504 print(">>>>> OBJ PUSH(false)");
508 case '}': //Token.RC:
511 print(">>>>> OBJ POP");
512 // assert braceNesting >= expressionBraceNesting;
515 case '[': //Token.LB:
519 case ']': //Token.RB:
523 case '(': //Token.LP:
527 case ')': //Token.RP:
533 case 'STRN': // used for object lit detection..
534 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
535 // then we are in an object lit.. -> we need to flag the brace as such...
537 isObjectLitAr.push(true);
538 print(">>>>> OBJ PUSH(true)");
543 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
544 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
545 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
546 // see if we can replace..
547 // remove the quotes..
548 var str = token.data.substring(1,token.data.length-1);
549 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
564 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
565 // then we are in an object lit.. -> we need to flag the brace as such...
567 isObjectLitAr.push(true);
568 print(">>>>> OBJ PUSH(true)");
571 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
572 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
576 if (this.ts.lookTok(-1).data == ".") {
581 if (this.mode == 'PASS2_SYMBOL_TREE') {
583 identifier = this.getIdentifier(symbol, currentScope);
584 //println("<B>??</B>");
585 if (identifier == false) {
587 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
588 // Here, we found an undeclared and un-namespaced symbol that is
589 // 3 characters or less in length. Declare it in the global scope.
590 // We don't need to declare longer symbols since they won't cause
591 // any conflict with other munged symbols.
592 this.globalScope.declareIdentifier(symbol, token);
593 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
595 //println("undeclared")
600 //println("<B>++</B>");
601 token.identifier = identifier;
602 identifier.refcount++;
611 //println("<B>EID</B>");
614 if (token.name == "FUNCTION") {
616 this.parseFunctionDeclaration();
623 if (this.mode == 'BUILDING_SYMBOL_TREE') {
625 if (symbol == "eval") {
626 if (this.ts.look(-1).type == 'COMM') {
627 // look for eval:var:noreplace\n
629 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
630 var hi = _t.getIdentifier(a, currentScope);
631 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
633 // println("PROTECT "+a+" from munge");
641 this.protectScopeFromObfuscation(currentScope);
642 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
651 if (!this.ts.nextTok()) break;
656 parseCatch : function() {
663 //token = getToken(-1);
664 //assert token.getType() == Token.CATCH;
665 token = this.ts.nextTok();
666 //assert token.getType() == Token.LP; (
667 token = this.ts.nextTok();
668 //assert token.getType() == Token.NAME;
671 currentScope = this.scopes[this.scopes.length-1];
673 if (this.mode == 'BUILDING_SYMBOL_TREE') {
674 // We must declare the exception identifier in the containing function
675 // scope to avoid errors related to the obfuscation process. No need to
676 // display a warning if the symbol was already declared here...
677 currentScope.declareIdentifier(symbol, token);
679 //?? why inc the refcount?? - that should be set when building the tree???
680 identifier = this.getIdentifier(symbol, currentScope);
681 identifier.refcount++;
684 token = this.ts.nextTok();
685 //assert token.getType() == Token.RP; // )
688 parseFunctionDeclaration : function()
690 // print("PARSE FUNCTION");
693 var currentScope = false;
696 //this.logR("<B>PARSING FUNCTION</B>");
697 currentScope = this.scopes[this.scopes.length-1];
699 token = this.ts.nextTok();
700 if (token.type == "NAME") {
701 if (this.mode == 'BUILDING_SYMBOL_TREE') {
702 // Get the name of the function and declare it in the current scope.
704 if (currentScope.getIdentifier(symbol) != false) {
705 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
707 currentScope.declareIdentifier(symbol,token);
709 token = this.ts.nextTok();
712 //assert token.getType() == Token.LP;
713 if (this.mode == 'BUILDING_SYMBOL_TREE') {
714 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
716 //println("STORING SCOPE" + this.ts.cursor);
718 this.indexedScopes[this.ts.cursor] = fnScope;
721 //println("FETCHING SCOPE" + this.ts.cursor);
722 fnScope = this.indexedScopes[this.ts.cursor];
726 // Parse function arguments.
728 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
729 token = this.ts.nextTok();
730 // print ("FUNC ARGS: " + token.toString())
731 //assert token.getType() == Token.NAME ||
732 // token.getType() == Token.COMMA;
733 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
735 identifier = fnScope.declareIdentifier(symbol,token);
736 if (symbol == "$super" && argpos == 0) {
737 // Exception for Prototype 1.6...
738 identifier.preventMunging();
744 token = this.ts.nextTok();
745 // assert token.getType() == Token.LC;
748 token = this.ts.nextTok();
749 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
752 NOT SUPPORTED YET!?!!?!
754 // This is a hint. Hints are empty statements that look like
755 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
756 // to prevent specific symbols from getting obfuscated (some heretic
757 // implementations, such as Prototype 1.6, require specific variable
758 // names, such as $super for example, in order to work appropriately.
759 // Note: right now, only "nomunge" is supported in the right hand side
760 // of a hint. However, in the future, the right hand side may contain
763 String hints = token.getValue();
764 // Remove the leading and trailing quotes...
765 hints = hints.substring(1, hints.length() - 1).trim();
766 StringTokenizer st1 = new StringTokenizer(hints, ",");
767 while (st1.hasMoreTokens()) {
768 String hint = st1.nextToken();
769 int idx = hint.indexOf(':');
770 if (idx <= 0 || idx >= hint.length() - 1) {
771 if (mode == BUILDING_SYMBOL_TREE) {
772 // No need to report the error twice, hence the test...
773 this.warn("Invalid hint syntax: " + hint, true);
777 String variableName = hint.substring(0, idx).trim();
778 String variableType = hint.substring(idx + 1).trim();
779 if (mode == BUILDING_SYMBOL_TREE) {
780 fnScope.addHint(variableName, variableType);
781 } else if (mode == CHECKING_SYMBOL_TREE) {
782 identifier = fnScope.getIdentifier(variableName);
783 if (identifier != null) {
784 if (variableType.equals("nomunge")) {
785 identifier.preventMunging();
787 this.warn("Unsupported hint value: " + hint, true);
790 this.warn("Hint refers to an unknown identifier: " + hint, true);
797 this.parseScope(fnScope);
798 // now pop it off the stack!!!
804 protectScopeFromObfuscation : function(scope) {
805 //assert scope != null;
807 if (scope == this.globalScope) {
808 // The global scope does not get obfuscated,
809 // so we don't need to worry about it...
813 // Find the highest local scope containing the specified scope.
814 while (scope && scope.parent != this.globalScope) {
815 scope = scope.parent;
818 //assert scope.getParentScope() == globalScope;
819 scope.preventMunging();
822 getIdentifier: function(symbol, scope) {
824 while (scope != false) {
825 identifier = scope.getIdentifier(symbol);
826 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
830 scope = scope.parent;