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 this.warnings.push(s);
102 //println("WARNING:" + htmlescape(s) + "<BR>");
104 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
109 mode : "", //"BUILDING_SYMBOL_TREE",
111 indexedScopes : false,
118 buildSymbolTree : function()
123 this.braceNesting = 0;
129 this.globalScope = new Scope(-1, false, -1, '');
130 indexedScopes = { 0 : this.globalScope };
132 this.mode = 'BUILDING_SYMBOL_TREE';
133 this.parseScope(this.globalScope);
135 mungeSymboltree : function()
142 // One problem with obfuscation resides in the use of undeclared
143 // and un-namespaced global symbols that are 3 characters or less
144 // in length. Here is an example:
146 // var declaredGlobalVar;
148 // function declaredGlobalFn() {
150 // localvar = abc; // abc is an undeclared global symbol
153 // In the example above, there is a slim chance that localvar may be
154 // munged to 'abc', conflicting with the undeclared global symbol
155 // abc, creating a potential bug. The following code detects such
156 // global symbols. This must be done AFTER the entire file has been
157 // parsed, and BEFORE munging the symbol tree. Note that declaring
158 // extra symbols in the global scope won't hurt.
160 // Note: Since we go through all the tokens to do this, we also use
161 // the opportunity to count how many times each identifier is used.
164 this.braceNesting = 0;
166 this.mode = 'CHECKING_SYMBOL_TREE';
168 //println("MUNGING?");
170 this.parseScope(this.globalScope);
171 this.globalScope.munge();
177 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
181 //println("<B>LOG:</B>" + str + "<BR/>");
189 parseScope : function(scope) // parse a token stream..
191 //this.timerPrint("parseScope EnterScope");
197 var expressionBraceNesting = this.braceNesting;
198 var bracketNesting = 0;
199 var parensNesting = 0;
201 var isObjectLitAr = [ false ];
203 this.scopes.push(scope);
204 token = this.ts.lookTok(1);
206 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
208 print(token.type + '.' + token.name+ ":" + token.data);
209 switch(token.type + '.' + token.name) {
211 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
213 //this.log("parseScope GOT VAR/CONST : " + token.toString());
215 token = this.ts.nextTok();
216 print(token.toString());
218 if (!token) { // can return false at EOF!
221 if (token.name == "VAR") { // kludge..
224 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
225 if (token.type !="NAME") {
226 print(token.toString());
227 print( "var without ident");
232 if (this.mode == "BUILDING_SYMBOL_TREE") {
233 identifier = scope.getIdentifier(token.data) ;
235 if (identifier == false) {
236 scope.declareIdentifier(token.data, token);
238 token.identifier = identifier;
239 this.warn("The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
243 token = this.ts.nextTok();
244 print(token.toString());
246 assert token.getType() == Token.SEMI ||
247 token.getType() == Token.ASSIGN ||
248 token.getType() == Token.COMMA ||
249 token.getType() == Token.IN;
251 if (token.name == "IN") {
254 this.parseExpression();
255 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
258 if (token.data == ';') {
264 case "KEYW.FUNCTION":
265 //println("<i>"+token.data+"</i>");
266 this.parseFunctionDeclaration();
269 case "KEYW.LEFT_CURLY": // {
270 //println("<i>"+token.data+"</i>");
271 isObjectLitAr.push(false);
275 case "KEYW.RIGHT_CURLY": // }
276 //println("<i>"+token.data+"</i>");
279 //assert braceNesting >= scope.getBraceNesting();
280 if (this.braceNesting == scope.braceN) {
281 var ls = this.scopes.pop();
288 //println("<i>"+token.data+"</i>");
289 if (this.mode == "BUILDING_SYMBOL_TREE") {
290 // Inside a 'with' block, it is impossible to figure out
291 // statically whether a symbol is a local variable or an
292 // object member. As a consequence, the only thing we can
293 // do is turn the obfuscation off for the highest scope
294 // containing the 'with' block.
295 this.protectScopeFromObfuscation(scope);
296 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
301 //println("<i>"+token.data+"</i>");
305 case Token.SPECIALCOMMENT:
306 if (mode == BUILDING_SYMBOL_TREE) {
307 protectScopeFromObfuscation(scope);
308 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
313 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
314 case "STRN.SINGLE_QUOTE":
315 //println("<i>"+token.data+"</i>");
316 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
317 // then we are in an object lit.. -> we need to flag the brace as such...
319 isObjectLitAr.push(true);
321 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
323 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
324 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
325 // see if we can replace..
326 // remove the quotes..
327 // should do a bit more checking!!!! (what about wierd char's in the string..
328 var str = token.data.substring(1,token.data.length-1);
329 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
343 //print("DEAL WITH NAME:");
346 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
347 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
349 isObjectLitAr.push(true);
350 //println("<i>"+token.data+"</i>");
353 // print("DEAL WITH obj lit:");
354 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
356 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
357 // skip, it's an object lit key..
358 //println("<i>"+token.data+"</i>");
363 // skip anyting with "." before it..!!
365 if (this.ts.lookTok(-1).data == ".") {
366 // skip, it's an object prop.
367 //println("<i>"+token.data+"</i>");
371 if (this.mode == 'CHECKING_SYMBOL_TREE') {
373 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
377 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
379 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
380 identifier = this.getIdentifier(symbol, scope);
382 if (identifier == false) {
383 // BUG!find out where builtin is defined...
384 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
385 // Here, we found an undeclared and un-namespaced symbol that is
386 // 3 characters or less in length. Declare it in the global scope.
387 // We don't need to declare longer symbols since they won't cause
388 // any conflict with other munged symbols.
389 this.globalScope.declareIdentifier(symbol, token);
390 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
393 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
395 token.identifier = identifier;
396 identifier.refcount++;
401 //println("<B>SID</B>");
403 if (token.type != 'KEYW') {
406 // print("Check eval:");
410 if (this.mode == 'BUILDING_SYMBOL_TREE') {
412 if (symbol == "eval") {
413 // look back one and see if we can find a comment!!!
414 if (this.ts.look(-1).type == "COMM") {
415 // look for eval:var:noreplace\n
417 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
419 var hi = _t.getIdentifier(a, scope);
420 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
422 // println("PROTECT "+a+" from munge");
432 this.protectScopeFromObfuscation(scope);
433 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);
445 //this.timerPrint("parseScope TOK : " + token.toString());
446 token = this.ts.nextTok();
447 //if (this.ts.nextT()) break;
453 parseExpression : function() {
455 // Parse the expression until we encounter a comma or a semi-colon
456 // in the same brace nesting, bracket nesting and paren nesting.
457 // Parse functions if any...
458 //println("<i>EXP</i><BR/>");
465 var expressionBraceNesting = this.braceNesting;
466 var bracketNesting = 0;
467 var parensNesting = 0;
469 var isObjectLitAr = [ false ];
470 while (token = this.ts.lookTok()) {
474 currentScope = this.scopes[this.scopes.length-1];
476 //println("<i>"+token.data+"</i>");
478 switch (token.data.toUpperCase()) {
482 if (this.braceNesting == expressionBraceNesting &&
483 bracketNesting == 0 &&
484 parensNesting == 0) {
490 this.parseFunctionDeclaration();
493 case '{': //Token.LC:
494 isObjectLitAr.push(false);
499 case '}': //Token.RC:
503 // assert braceNesting >= expressionBraceNesting;
506 case '[': //Token.LB:
510 case ']': //Token.RB:
514 case '(': //Token.LP:
518 case ')': //Token.RP:
524 case 'STRN': // used for object lit detection..
525 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
526 // then we are in an object lit.. -> we need to flag the brace as such...
528 isObjectLitAr.push(true);
533 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
534 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
535 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
536 // see if we can replace..
537 // remove the quotes..
538 var str = token.data.substring(1,token.data.length-1);
539 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
552 case Token.SPECIALCOMMENT:
553 if (mode == BUILDING_SYMBOL_TREE) {
554 protectScopeFromObfuscation(currentScope);
555 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression!" : ""), true);
562 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
563 // then we are in an object lit.. -> we need to flag the brace as such...
565 isObjectLitAr.push(true);
568 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
569 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
573 if (this.ts.lookTok(-1).data == ".") {
578 if (this.mode == 'CHECKING_SYMBOL_TREE') {
580 identifier = this.getIdentifier(symbol, currentScope);
581 //println("<B>??</B>");
582 if (identifier == false) {
584 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
585 // Here, we found an undeclared and un-namespaced symbol that is
586 // 3 characters or less in length. Declare it in the global scope.
587 // We don't need to declare longer symbols since they won't cause
588 // any conflict with other munged symbols.
589 this.globalScope.declareIdentifier(symbol, token);
590 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
592 //println("undeclared")
597 //println("<B>++</B>");
598 token.identifier = identifier;
599 identifier.refcount++;
608 //println("<B>EID</B>");
611 if (this.mode == 'BUILDING_SYMBOL_TREE') {
613 if (symbol == "eval") {
614 if (this.ts.look(-1).type == 'COMM') {
615 // look for eval:var:noreplace\n
617 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
618 var hi = _t.getIdentifier(a, currentScope);
619 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
621 // println("PROTECT "+a+" from munge");
629 this.protectScopeFromObfuscation(currentScope);
630 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
639 if (!this.ts.nextTok()) break;
644 parseCatch : function() {
651 //token = getToken(-1);
652 //assert token.getType() == Token.CATCH;
653 token = this.ts.nextTok();
654 //assert token.getType() == Token.LP; (
655 token = this.ts.nextTok();
656 //assert token.getType() == Token.NAME;
659 currentScope = this.scopes[this.scopes.length-1];
661 if (this.mode == 'BUILDING_SYMBOL_TREE') {
662 // We must declare the exception identifier in the containing function
663 // scope to avoid errors related to the obfuscation process. No need to
664 // display a warning if the symbol was already declared here...
665 currentScope.declareIdentifier(symbol, token);
667 //?? why inc the refcount?? - that should be set when building the tree???
668 identifier = this.getIdentifier(symbol, currentScope);
669 identifier.refcount++;
672 token = this.ts.nextTok();
673 //assert token.getType() == Token.RP; // )
676 parseFunctionDeclaration : function()
681 var currentScope = false;
684 //this.logR("<B>PARSING FUNCTION</B>");
685 currentScope = this.scopes[this.scopes.length-1];
687 token = this.ts.nextTok();
688 if (token.type == "NAME") {
689 if (this.mode == 'BUILDING_SYMBOL_TREE') {
690 // Get the name of the function and declare it in the current scope.
692 if (currentScope.getIdentifier(symbol) != false) {
693 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
695 currentScope.declareIdentifier(symbol,token);
697 token = this.ts.nextTok();
700 //assert token.getType() == Token.LP;
701 if (this.mode == 'BUILDING_SYMBOL_TREE') {
702 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
704 //println("STORING SCOPE" + this.ts.cursor);
706 this.indexedScopes[this.ts.cursor] = fnScope;
709 //println("FETCHING SCOPE" + this.ts.cursor);
710 fnScope = this.indexedScopes[this.ts.cursor];
713 // Parse function arguments.
715 while (!this.ts.lookTok().data == ')') { //(token = consumeToken()).getType() != Token.RP) {
716 token = this.ts.nextTok();
718 //assert token.getType() == Token.NAME ||
719 // token.getType() == Token.COMMA;
720 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
722 identifier = fnScope.declareIdentifier(symbol,token);
723 if (symbol == "$super" && argpos == 0) {
724 // Exception for Prototype 1.6...
725 identifier.preventMunging();
731 token = this.ts.nextTok();
732 // assert token.getType() == Token.LC;
735 token = this.ts.nextTok();
736 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
739 NOT SUPPORTED YET!?!!?!
741 // This is a hint. Hints are empty statements that look like
742 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
743 // to prevent specific symbols from getting obfuscated (some heretic
744 // implementations, such as Prototype 1.6, require specific variable
745 // names, such as $super for example, in order to work appropriately.
746 // Note: right now, only "nomunge" is supported in the right hand side
747 // of a hint. However, in the future, the right hand side may contain
750 String hints = token.getValue();
751 // Remove the leading and trailing quotes...
752 hints = hints.substring(1, hints.length() - 1).trim();
753 StringTokenizer st1 = new StringTokenizer(hints, ",");
754 while (st1.hasMoreTokens()) {
755 String hint = st1.nextToken();
756 int idx = hint.indexOf(':');
757 if (idx <= 0 || idx >= hint.length() - 1) {
758 if (mode == BUILDING_SYMBOL_TREE) {
759 // No need to report the error twice, hence the test...
760 this.warn("Invalid hint syntax: " + hint, true);
764 String variableName = hint.substring(0, idx).trim();
765 String variableType = hint.substring(idx + 1).trim();
766 if (mode == BUILDING_SYMBOL_TREE) {
767 fnScope.addHint(variableName, variableType);
768 } else if (mode == CHECKING_SYMBOL_TREE) {
769 identifier = fnScope.getIdentifier(variableName);
770 if (identifier != null) {
771 if (variableType.equals("nomunge")) {
772 identifier.preventMunging();
774 this.warn("Unsupported hint value: " + hint, true);
777 this.warn("Hint refers to an unknown identifier: " + hint, true);
784 this.parseScope(fnScope);
785 // now pop it off the stack!!!
791 protectScopeFromObfuscation : function(scope) {
792 //assert scope != null;
794 if (scope == this.globalScope) {
795 // The global scope does not get obfuscated,
796 // so we don't need to worry about it...
800 // Find the highest local scope containing the specified scope.
801 while (scope && scope.parent != this.globalScope) {
802 scope = scope.parent;
805 //assert scope.getParentScope() == globalScope;
806 scope.preventMunging();
809 getIdentifier: function(symbol, scope) {
811 while (scope != false) {
812 identifier = scope.getIdentifier(symbol);
813 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
817 scope = scope.parent;