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 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
185 //println("<B>LOG:</B>" + str + "<BR/>");
193 parseScope : function(scope) // parse a token stream..
195 //this.timerPrint("parseScope EnterScope");
196 print(">>> ENTER SCOPE" + this.scopes.length);
202 var expressionBraceNesting = this.braceNesting;
204 var parensNesting = 0;
206 var isObjectLitAr = [ false ];
208 this.scopes.push(scope);
209 token = this.ts.lookTok(1);
211 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
213 !this.debug|| print(token.type + '.' + token.name+ ":" + token.data);
214 switch(token.type + '.' + token.name) {
216 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
218 //this.log("parseScope GOT VAR/CONST : " + token.toString());
220 token = this.ts.nextTok();
221 !this.debug|| print( token.toString());
223 if (!token) { // can return false at EOF!
226 if (token.name == "VAR") { // kludge..
229 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
230 if (token.type !="NAME") {
231 print(token.toString());
232 print( "var without ident");
237 if (this.mode == "BUILDING_SYMBOL_TREE") {
238 identifier = scope.getIdentifier(token.data) ;
240 if (identifier == false) {
241 scope.declareIdentifier(token.data, token);
243 token.identifier = identifier;
244 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
248 token = this.ts.nextTok();
249 !this.debug|| print(token.toString());
251 assert token.getType() == Token.SEMI ||
252 token.getType() == Token.ASSIGN ||
253 token.getType() == Token.COMMA ||
254 token.getType() == Token.IN;
256 if (token.name == "IN") {
259 this.parseExpression();
260 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
262 token = this.ts.lookTok(1);
263 !this.debug|| print("AFTER EXP: " + token.toString());
264 if (token.data == ';') {
270 case "KEYW.FUNCTION":
271 //println("<i>"+token.data+"</i>");
272 this.parseFunctionDeclaration();
275 case "PUNC.LEFT_CURLY": // {
276 //println("<i>"+token.data+"</i>");
277 isObjectLitAr.push(false);
278 print(">>>>>> OBJLIT PUSH(false)");
282 case "PUNC.RIGHT_CURLY": // }
283 //println("<i>"+token.data+"</i>");
286 print(">>>>>> OBJLIT POP"+ this.braceNesting);
287 //assert braceNesting >= scope.getBra ceNesting();
289 if (this.braceNesting < 0) {
290 var ls = this.scopes.pop();
292 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
298 //println("<i>"+token.data+"</i>");
299 if (this.mode == "BUILDING_SYMBOL_TREE") {
300 // Inside a 'with' block, it is impossible to figure out
301 // statically whether a symbol is a local variable or an
302 // object member. As a consequence, the only thing we can
303 // do is turn the obfuscation off for the highest scope
304 // containing the 'with' block.
305 this.protectScopeFromObfuscation(scope);
306 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
311 //println("<i>"+token.data+"</i>");
315 case Token.SPECIALCOMMENT:
316 if (mode == BUILDING_SYMBOL_TREE) {
317 protectScopeFromObfuscation(scope);
318 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
323 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
324 case "STRN.SINGLE_QUOTE":
325 //println("<i>"+token.data+"</i>");
326 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
327 // then we are in an object lit.. -> we need to flag the brace as such...
329 isObjectLitAr.push(true);
330 print(">>>>>> OBJLIT PUSH(true)");
332 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
334 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
335 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
336 // see if we can replace..
337 // remove the quotes..
338 // should do a bit more checking!!!! (what about wierd char's in the string..
339 var str = token.data.substring(1,token.data.length-1);
340 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
354 //print("DEAL WITH NAME:");
357 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
358 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
360 isObjectLitAr.push(true);
361 print(">>>>>> OBJLIT PUSH(true)");
362 //println("<i>"+token.data+"</i>");
365 // print("DEAL WITH obj lit:");
366 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
368 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
369 // skip, it's an object lit key..
370 //println("<i>"+token.data+"</i>");
375 // skip anyting with "." before it..!!
377 if (this.ts.lookTok(-1).data == ".") {
378 // skip, it's an object prop.
379 //println("<i>"+token.data+"</i>");
383 if (this.mode == 'PASS2_SYMBOL_TREE') {
385 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
387 //print ("MUNGE?" + symbol);
389 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
391 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
392 identifier = this.getIdentifier(symbol, scope);
394 if (identifier == false) {
395 // BUG!find out where builtin is defined...
396 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
397 // Here, we found an undeclared and un-namespaced symbol that is
398 // 3 characters or less in length. Declare it in the global scope.
399 // We don't need to declare longer symbols since they won't cause
400 // any conflict with other munged symbols.
401 this.globalScope.declareIdentifier(symbol, token);
402 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
405 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
407 token.identifier = identifier;
408 identifier.refcount++;
413 //println("<B>SID</B>");
415 if (token.type != 'KEYW') {
418 // print("Check eval:");
422 if (this.mode == 'BUILDING_SYMBOL_TREE') {
424 if (symbol == "eval") {
425 // look back one and see if we can find a comment!!!
426 if (this.ts.look(-1).type == "COMM") {
427 // look for eval:var:noreplace\n
429 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
431 var hi = _t.getIdentifier(a, scope);
432 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
434 // println("PROTECT "+a+" from munge");
444 this.protectScopeFromObfuscation(scope);
445 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);
457 //this.timerPrint("parseScope TOK : " + token.toString());
458 token = this.ts.nextTok();
459 //if (this.ts.nextT()) break;
462 print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
466 parseExpression : function() {
468 // Parse the expression until we encounter a comma or a semi-colon
469 // in the same brace nesting, bracket nesting and paren nesting.
470 // Parse functions if any...
471 //println("<i>EXP</i><BR/>");
472 !this.debug || print("PARSE EXPR");
478 var expressionBraceNesting = this.braceNesting;
479 var bracketNesting = 0;
480 var parensNesting = 0;
482 var isObjectLitAr = [ false ];
483 while (token = this.ts.lookTok()) {
487 currentScope = this.scopes[this.scopes.length-1];
489 //println("<i>"+token.data+"</i>");
490 !this.debug|| print ("EXP" + token.toString());
491 switch (token.type) {
497 if (this.braceNesting == expressionBraceNesting &&
498 bracketNesting == 0 &&
499 parensNesting == 0) {
507 case '{': //Token.LC:
508 isObjectLitAr.push(false);
511 print(">>>>> EXP PUSH(false)"+this.braceNesting);
514 case '}': //Token.RC:
517 print(">>>>> EXP POP" + this.braceNesting);
518 // assert braceNesting >= expressionBraceNesting;
521 case '[': //Token.LB:
525 case ']': //Token.RB:
529 case '(': //Token.LP:
533 case ')': //Token.RP:
539 case 'STRN': // used for object lit detection..
540 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
541 // then we are in an object lit.. -> we need to flag the brace as such...
543 isObjectLitAr.push(true);
544 print(">>>>> EXP PUSH(true)");
549 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
550 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
551 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
552 // see if we can replace..
553 // remove the quotes..
554 var str = token.data.substring(1,token.data.length-1);
555 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
570 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
571 // then we are in an object lit.. -> we need to flag the brace as such...
573 isObjectLitAr.push(true);
574 print(">>>>> EXP PUSH(true)");
577 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
578 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
582 if (this.ts.lookTok(-1).data == ".") {
587 if (this.mode == 'PASS2_SYMBOL_TREE') {
589 identifier = this.getIdentifier(symbol, currentScope);
590 //println("<B>??</B>");
591 if (identifier == false) {
593 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
594 // Here, we found an undeclared and un-namespaced symbol that is
595 // 3 characters or less in length. Declare it in the global scope.
596 // We don't need to declare longer symbols since they won't cause
597 // any conflict with other munged symbols.
598 this.globalScope.declareIdentifier(symbol, token);
599 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
601 //println("undeclared")
606 //println("<B>++</B>");
607 token.identifier = identifier;
608 identifier.refcount++;
617 //println("<B>EID</B>");
620 if (token.name == "FUNCTION") {
622 this.parseFunctionDeclaration();
629 if (this.mode == 'BUILDING_SYMBOL_TREE') {
631 if (symbol == "eval") {
632 if (this.ts.look(-1).type == 'COMM') {
633 // look for eval:var:noreplace\n
635 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
636 var hi = _t.getIdentifier(a, currentScope);
637 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
639 // println("PROTECT "+a+" from munge");
647 this.protectScopeFromObfuscation(currentScope);
648 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
657 if (!this.ts.nextTok()) break;
662 parseCatch : function() {
669 //token = getToken(-1);
670 //assert token.getType() == Token.CATCH;
671 token = this.ts.nextTok();
672 //assert token.getType() == Token.LP; (
673 token = this.ts.nextTok();
674 //assert token.getType() == Token.NAME;
677 currentScope = this.scopes[this.scopes.length-1];
679 if (this.mode == 'BUILDING_SYMBOL_TREE') {
680 // We must declare the exception identifier in the containing function
681 // scope to avoid errors related to the obfuscation process. No need to
682 // display a warning if the symbol was already declared here...
683 currentScope.declareIdentifier(symbol, token);
685 //?? why inc the refcount?? - that should be set when building the tree???
686 identifier = this.getIdentifier(symbol, currentScope);
687 identifier.refcount++;
690 token = this.ts.nextTok();
691 //assert token.getType() == Token.RP; // )
694 parseFunctionDeclaration : function()
696 // print("PARSE FUNCTION");
699 var currentScope = false;
702 //this.logR("<B>PARSING FUNCTION</B>");
703 currentScope = this.scopes[this.scopes.length-1];
705 token = this.ts.nextTok();
706 if (token.type == "NAME") {
707 if (this.mode == 'BUILDING_SYMBOL_TREE') {
708 // Get the name of the function and declare it in the current scope.
710 if (currentScope.getIdentifier(symbol) != false) {
711 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
713 currentScope.declareIdentifier(symbol,token);
715 token = this.ts.nextTok();
718 //assert token.getType() == Token.LP;
719 if (this.mode == 'BUILDING_SYMBOL_TREE') {
720 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
722 //println("STORING SCOPE" + this.ts.cursor);
724 this.indexedScopes[this.ts.cursor] = fnScope;
727 //println("FETCHING SCOPE" + this.ts.cursor);
728 fnScope = this.indexedScopes[this.ts.cursor];
732 // Parse function arguments.
734 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
735 token = this.ts.nextTok();
736 // print ("FUNC ARGS: " + token.toString())
737 //assert token.getType() == Token.NAME ||
738 // token.getType() == Token.COMMA;
739 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
741 identifier = fnScope.declareIdentifier(symbol,token);
742 if (symbol == "$super" && argpos == 0) {
743 // Exception for Prototype 1.6...
744 identifier.preventMunging();
750 token = this.ts.nextTok();
751 // assert token.getType() == Token.LC;
754 token = this.ts.nextTok();
755 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
758 NOT SUPPORTED YET!?!!?!
760 // This is a hint. Hints are empty statements that look like
761 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
762 // to prevent specific symbols from getting obfuscated (some heretic
763 // implementations, such as Prototype 1.6, require specific variable
764 // names, such as $super for example, in order to work appropriately.
765 // Note: right now, only "nomunge" is supported in the right hand side
766 // of a hint. However, in the future, the right hand side may contain
769 String hints = token.getValue();
770 // Remove the leading and trailing quotes...
771 hints = hints.substring(1, hints.length() - 1).trim();
772 StringTokenizer st1 = new StringTokenizer(hints, ",");
773 while (st1.hasMoreTokens()) {
774 String hint = st1.nextToken();
775 int idx = hint.indexOf(':');
776 if (idx <= 0 || idx >= hint.length() - 1) {
777 if (mode == BUILDING_SYMBOL_TREE) {
778 // No need to report the error twice, hence the test...
779 this.warn("Invalid hint syntax: " + hint, true);
783 String variableName = hint.substring(0, idx).trim();
784 String variableType = hint.substring(idx + 1).trim();
785 if (mode == BUILDING_SYMBOL_TREE) {
786 fnScope.addHint(variableName, variableType);
787 } else if (mode == CHECKING_SYMBOL_TREE) {
788 identifier = fnScope.getIdentifier(variableName);
789 if (identifier != null) {
790 if (variableType.equals("nomunge")) {
791 identifier.preventMunging();
793 this.warn("Unsupported hint value: " + hint, true);
796 this.warn("Hint refers to an unknown identifier: " + hint, true);
803 this.parseScope(fnScope);
804 // now pop it off the stack!!!
810 protectScopeFromObfuscation : function(scope) {
811 //assert scope != null;
813 if (scope == this.globalScope) {
814 // The global scope does not get obfuscated,
815 // so we don't need to worry about it...
819 // Find the highest local scope containing the specified scope.
820 while (scope && scope.parent != this.globalScope) {
821 scope = scope.parent;
824 //assert scope.getParentScope() == globalScope;
825 scope.preventMunging();
828 getIdentifier: function(symbol, scope) {
830 while (scope != false) {
831 identifier = scope.getIdentifier(symbol);
832 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
836 scope = scope.parent;