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) {
491 this.parseFunctionDeclaration();
494 case '{': //Token.LC:
495 isObjectLitAr.push(false);
500 case '}': //Token.RC:
504 // assert braceNesting >= expressionBraceNesting;
507 case '[': //Token.LB:
511 case ']': //Token.RB:
515 case '(': //Token.LP:
519 case ')': //Token.RP:
525 case 'STRN': // used for object lit detection..
526 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
527 // then we are in an object lit.. -> we need to flag the brace as such...
529 isObjectLitAr.push(true);
534 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
535 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
536 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
537 // see if we can replace..
538 // remove the quotes..
539 var str = token.data.substring(1,token.data.length-1);
540 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
553 case Token.SPECIALCOMMENT:
554 if (mode == BUILDING_SYMBOL_TREE) {
555 protectScopeFromObfuscation(currentScope);
556 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression!" : ""), true);
563 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
564 // then we are in an object lit.. -> we need to flag the brace as such...
566 isObjectLitAr.push(true);
569 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
570 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
574 if (this.ts.lookTok(-1).data == ".") {
579 if (this.mode == 'CHECKING_SYMBOL_TREE') {
581 identifier = this.getIdentifier(symbol, currentScope);
582 //println("<B>??</B>");
583 if (identifier == false) {
585 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
586 // Here, we found an undeclared and un-namespaced symbol that is
587 // 3 characters or less in length. Declare it in the global scope.
588 // We don't need to declare longer symbols since they won't cause
589 // any conflict with other munged symbols.
590 this.globalScope.declareIdentifier(symbol, token);
591 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
593 //println("undeclared")
598 //println("<B>++</B>");
599 token.identifier = identifier;
600 identifier.refcount++;
609 //println("<B>EID</B>");
612 if (this.mode == 'BUILDING_SYMBOL_TREE') {
614 if (symbol == "eval") {
615 if (this.ts.look(-1).type == 'COMM') {
616 // look for eval:var:noreplace\n
618 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
619 var hi = _t.getIdentifier(a, currentScope);
620 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
622 // println("PROTECT "+a+" from munge");
630 this.protectScopeFromObfuscation(currentScope);
631 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
640 if (!this.ts.nextTok()) break;
645 parseCatch : function() {
652 //token = getToken(-1);
653 //assert token.getType() == Token.CATCH;
654 token = this.ts.nextTok();
655 //assert token.getType() == Token.LP; (
656 token = this.ts.nextTok();
657 //assert token.getType() == Token.NAME;
660 currentScope = this.scopes[this.scopes.length-1];
662 if (this.mode == 'BUILDING_SYMBOL_TREE') {
663 // We must declare the exception identifier in the containing function
664 // scope to avoid errors related to the obfuscation process. No need to
665 // display a warning if the symbol was already declared here...
666 currentScope.declareIdentifier(symbol, token);
668 //?? why inc the refcount?? - that should be set when building the tree???
669 identifier = this.getIdentifier(symbol, currentScope);
670 identifier.refcount++;
673 token = this.ts.nextTok();
674 //assert token.getType() == Token.RP; // )
677 parseFunctionDeclaration : function()
682 var currentScope = false;
685 //this.logR("<B>PARSING FUNCTION</B>");
686 currentScope = this.scopes[this.scopes.length-1];
688 token = this.ts.nextTok();
689 if (token.type == "NAME") {
690 if (this.mode == 'BUILDING_SYMBOL_TREE') {
691 // Get the name of the function and declare it in the current scope.
693 if (currentScope.getIdentifier(symbol) != false) {
694 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
696 currentScope.declareIdentifier(symbol,token);
698 token = this.ts.nextTok();
701 //assert token.getType() == Token.LP;
702 if (this.mode == 'BUILDING_SYMBOL_TREE') {
703 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
705 //println("STORING SCOPE" + this.ts.cursor);
707 this.indexedScopes[this.ts.cursor] = fnScope;
710 //println("FETCHING SCOPE" + this.ts.cursor);
711 fnScope = this.indexedScopes[this.ts.cursor];
714 // Parse function arguments.
716 while (!this.ts.lookTok().data == ')') { //(token = consumeToken()).getType() != Token.RP) {
717 token = this.ts.nextTok();
719 //assert token.getType() == Token.NAME ||
720 // token.getType() == Token.COMMA;
721 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
723 identifier = fnScope.declareIdentifier(symbol,token);
724 if (symbol == "$super" && argpos == 0) {
725 // Exception for Prototype 1.6...
726 identifier.preventMunging();
732 token = this.ts.nextTok();
733 // assert token.getType() == Token.LC;
736 token = this.ts.nextTok();
737 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
740 NOT SUPPORTED YET!?!!?!
742 // This is a hint. Hints are empty statements that look like
743 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
744 // to prevent specific symbols from getting obfuscated (some heretic
745 // implementations, such as Prototype 1.6, require specific variable
746 // names, such as $super for example, in order to work appropriately.
747 // Note: right now, only "nomunge" is supported in the right hand side
748 // of a hint. However, in the future, the right hand side may contain
751 String hints = token.getValue();
752 // Remove the leading and trailing quotes...
753 hints = hints.substring(1, hints.length() - 1).trim();
754 StringTokenizer st1 = new StringTokenizer(hints, ",");
755 while (st1.hasMoreTokens()) {
756 String hint = st1.nextToken();
757 int idx = hint.indexOf(':');
758 if (idx <= 0 || idx >= hint.length() - 1) {
759 if (mode == BUILDING_SYMBOL_TREE) {
760 // No need to report the error twice, hence the test...
761 this.warn("Invalid hint syntax: " + hint, true);
765 String variableName = hint.substring(0, idx).trim();
766 String variableType = hint.substring(idx + 1).trim();
767 if (mode == BUILDING_SYMBOL_TREE) {
768 fnScope.addHint(variableName, variableType);
769 } else if (mode == CHECKING_SYMBOL_TREE) {
770 identifier = fnScope.getIdentifier(variableName);
771 if (identifier != null) {
772 if (variableType.equals("nomunge")) {
773 identifier.preventMunging();
775 this.warn("Unsupported hint value: " + hint, true);
778 this.warn("Hint refers to an unknown identifier: " + hint, true);
785 this.parseScope(fnScope);
786 // now pop it off the stack!!!
792 protectScopeFromObfuscation : function(scope) {
793 //assert scope != null;
795 if (scope == this.globalScope) {
796 // The global scope does not get obfuscated,
797 // so we don't need to worry about it...
801 // Find the highest local scope containing the specified scope.
802 while (scope && scope.parent != this.globalScope) {
803 scope = scope.parent;
806 //assert scope.getParentScope() == globalScope;
807 scope.preventMunging();
810 getIdentifier: function(symbol, scope) {
812 while (scope != false) {
813 identifier = scope.getIdentifier(symbol);
814 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
818 scope = scope.parent;