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);
509 print(">>>>> OBJ PUSH(false)");
513 case '}': //Token.RC:
516 print(">>>>> OBJ POP");
517 // assert braceNesting >= expressionBraceNesting;
520 case '[': //Token.LB:
524 case ']': //Token.RB:
528 case '(': //Token.LP:
532 case ')': //Token.RP:
538 case 'STRN': // used for object lit detection..
539 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
540 // then we are in an object lit.. -> we need to flag the brace as such...
542 isObjectLitAr.push(true);
543 print(">>>>> OBJ PUSH(true)");
548 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
549 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
550 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
551 // see if we can replace..
552 // remove the quotes..
553 var str = token.data.substring(1,token.data.length-1);
554 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
569 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
570 // then we are in an object lit.. -> we need to flag the brace as such...
572 isObjectLitAr.push(true);
573 print(">>>>> OBJ PUSH(true)");
576 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
577 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
581 if (this.ts.lookTok(-1).data == ".") {
586 if (this.mode == 'PASS2_SYMBOL_TREE') {
588 identifier = this.getIdentifier(symbol, currentScope);
589 //println("<B>??</B>");
590 if (identifier == false) {
592 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
593 // Here, we found an undeclared and un-namespaced symbol that is
594 // 3 characters or less in length. Declare it in the global scope.
595 // We don't need to declare longer symbols since they won't cause
596 // any conflict with other munged symbols.
597 this.globalScope.declareIdentifier(symbol, token);
598 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
600 //println("undeclared")
605 //println("<B>++</B>");
606 token.identifier = identifier;
607 identifier.refcount++;
616 //println("<B>EID</B>");
619 if (token.name == "FUNCTION") {
621 this.parseFunctionDeclaration();
628 if (this.mode == 'BUILDING_SYMBOL_TREE') {
630 if (symbol == "eval") {
631 if (this.ts.look(-1).type == 'COMM') {
632 // look for eval:var:noreplace\n
634 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
635 var hi = _t.getIdentifier(a, currentScope);
636 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
638 // println("PROTECT "+a+" from munge");
646 this.protectScopeFromObfuscation(currentScope);
647 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
656 if (!this.ts.nextTok()) break;
661 parseCatch : function() {
668 //token = getToken(-1);
669 //assert token.getType() == Token.CATCH;
670 token = this.ts.nextTok();
671 //assert token.getType() == Token.LP; (
672 token = this.ts.nextTok();
673 //assert token.getType() == Token.NAME;
676 currentScope = this.scopes[this.scopes.length-1];
678 if (this.mode == 'BUILDING_SYMBOL_TREE') {
679 // We must declare the exception identifier in the containing function
680 // scope to avoid errors related to the obfuscation process. No need to
681 // display a warning if the symbol was already declared here...
682 currentScope.declareIdentifier(symbol, token);
684 //?? why inc the refcount?? - that should be set when building the tree???
685 identifier = this.getIdentifier(symbol, currentScope);
686 identifier.refcount++;
689 token = this.ts.nextTok();
690 //assert token.getType() == Token.RP; // )
693 parseFunctionDeclaration : function()
695 // print("PARSE FUNCTION");
698 var currentScope = false;
701 //this.logR("<B>PARSING FUNCTION</B>");
702 currentScope = this.scopes[this.scopes.length-1];
704 token = this.ts.nextTok();
705 if (token.type == "NAME") {
706 if (this.mode == 'BUILDING_SYMBOL_TREE') {
707 // Get the name of the function and declare it in the current scope.
709 if (currentScope.getIdentifier(symbol) != false) {
710 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
712 currentScope.declareIdentifier(symbol,token);
714 token = this.ts.nextTok();
717 //assert token.getType() == Token.LP;
718 if (this.mode == 'BUILDING_SYMBOL_TREE') {
719 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
721 //println("STORING SCOPE" + this.ts.cursor);
723 this.indexedScopes[this.ts.cursor] = fnScope;
726 //println("FETCHING SCOPE" + this.ts.cursor);
727 fnScope = this.indexedScopes[this.ts.cursor];
731 // Parse function arguments.
733 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
734 token = this.ts.nextTok();
735 // print ("FUNC ARGS: " + token.toString())
736 //assert token.getType() == Token.NAME ||
737 // token.getType() == Token.COMMA;
738 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
740 identifier = fnScope.declareIdentifier(symbol,token);
741 if (symbol == "$super" && argpos == 0) {
742 // Exception for Prototype 1.6...
743 identifier.preventMunging();
749 token = this.ts.nextTok();
750 // assert token.getType() == Token.LC;
753 token = this.ts.nextTok();
754 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
757 NOT SUPPORTED YET!?!!?!
759 // This is a hint. Hints are empty statements that look like
760 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
761 // to prevent specific symbols from getting obfuscated (some heretic
762 // implementations, such as Prototype 1.6, require specific variable
763 // names, such as $super for example, in order to work appropriately.
764 // Note: right now, only "nomunge" is supported in the right hand side
765 // of a hint. However, in the future, the right hand side may contain
768 String hints = token.getValue();
769 // Remove the leading and trailing quotes...
770 hints = hints.substring(1, hints.length() - 1).trim();
771 StringTokenizer st1 = new StringTokenizer(hints, ",");
772 while (st1.hasMoreTokens()) {
773 String hint = st1.nextToken();
774 int idx = hint.indexOf(':');
775 if (idx <= 0 || idx >= hint.length() - 1) {
776 if (mode == BUILDING_SYMBOL_TREE) {
777 // No need to report the error twice, hence the test...
778 this.warn("Invalid hint syntax: " + hint, true);
782 String variableName = hint.substring(0, idx).trim();
783 String variableType = hint.substring(idx + 1).trim();
784 if (mode == BUILDING_SYMBOL_TREE) {
785 fnScope.addHint(variableName, variableType);
786 } else if (mode == CHECKING_SYMBOL_TREE) {
787 identifier = fnScope.getIdentifier(variableName);
788 if (identifier != null) {
789 if (variableType.equals("nomunge")) {
790 identifier.preventMunging();
792 this.warn("Unsupported hint value: " + hint, true);
795 this.warn("Hint refers to an unknown identifier: " + hint, true);
802 this.parseScope(fnScope);
803 // now pop it off the stack!!!
809 protectScopeFromObfuscation : function(scope) {
810 //assert scope != null;
812 if (scope == this.globalScope) {
813 // The global scope does not get obfuscated,
814 // so we don't need to worry about it...
818 // Find the highest local scope containing the specified scope.
819 while (scope && scope.parent != this.globalScope) {
820 scope = scope.parent;
823 //assert scope.getParentScope() == globalScope;
824 scope.preventMunging();
827 getIdentifier: function(symbol, scope) {
829 while (scope != false) {
830 identifier = scope.getIdentifier(symbol);
831 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
835 scope = scope.parent;