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());
257 token = this.ts.lookTok(0);
258 print("AFTER EXP: " + token.toString());
259 if (token.data == ';') {
265 case "KEYW.FUNCTION":
266 //println("<i>"+token.data+"</i>");
267 this.parseFunctionDeclaration();
270 case "KEYW.LEFT_CURLY": // {
271 //println("<i>"+token.data+"</i>");
272 isObjectLitAr.push(false);
276 case "KEYW.RIGHT_CURLY": // }
277 //println("<i>"+token.data+"</i>");
280 //assert braceNesting >= scope.getBraceNesting();
281 if (this.braceNesting == scope.braceN) {
282 var ls = this.scopes.pop();
289 //println("<i>"+token.data+"</i>");
290 if (this.mode == "BUILDING_SYMBOL_TREE") {
291 // Inside a 'with' block, it is impossible to figure out
292 // statically whether a symbol is a local variable or an
293 // object member. As a consequence, the only thing we can
294 // do is turn the obfuscation off for the highest scope
295 // containing the 'with' block.
296 this.protectScopeFromObfuscation(scope);
297 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
302 //println("<i>"+token.data+"</i>");
306 case Token.SPECIALCOMMENT:
307 if (mode == BUILDING_SYMBOL_TREE) {
308 protectScopeFromObfuscation(scope);
309 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
314 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
315 case "STRN.SINGLE_QUOTE":
316 //println("<i>"+token.data+"</i>");
317 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
318 // then we are in an object lit.. -> we need to flag the brace as such...
320 isObjectLitAr.push(true);
322 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
324 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
325 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
326 // see if we can replace..
327 // remove the quotes..
328 // should do a bit more checking!!!! (what about wierd char's in the string..
329 var str = token.data.substring(1,token.data.length-1);
330 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
344 //print("DEAL WITH NAME:");
347 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
348 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
350 isObjectLitAr.push(true);
351 //println("<i>"+token.data+"</i>");
354 // print("DEAL WITH obj lit:");
355 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
357 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
358 // skip, it's an object lit key..
359 //println("<i>"+token.data+"</i>");
364 // skip anyting with "." before it..!!
366 if (this.ts.lookTok(-1).data == ".") {
367 // skip, it's an object prop.
368 //println("<i>"+token.data+"</i>");
372 if (this.mode == 'CHECKING_SYMBOL_TREE') {
374 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
378 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
380 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
381 identifier = this.getIdentifier(symbol, scope);
383 if (identifier == false) {
384 // BUG!find out where builtin is defined...
385 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
386 // Here, we found an undeclared and un-namespaced symbol that is
387 // 3 characters or less in length. Declare it in the global scope.
388 // We don't need to declare longer symbols since they won't cause
389 // any conflict with other munged symbols.
390 this.globalScope.declareIdentifier(symbol, token);
391 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
394 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
396 token.identifier = identifier;
397 identifier.refcount++;
402 //println("<B>SID</B>");
404 if (token.type != 'KEYW') {
407 // print("Check eval:");
411 if (this.mode == 'BUILDING_SYMBOL_TREE') {
413 if (symbol == "eval") {
414 // look back one and see if we can find a comment!!!
415 if (this.ts.look(-1).type == "COMM") {
416 // look for eval:var:noreplace\n
418 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
420 var hi = _t.getIdentifier(a, scope);
421 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
423 // println("PROTECT "+a+" from munge");
433 this.protectScopeFromObfuscation(scope);
434 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);
446 //this.timerPrint("parseScope TOK : " + token.toString());
447 token = this.ts.nextTok();
448 //if (this.ts.nextT()) break;
454 parseExpression : function() {
456 // Parse the expression until we encounter a comma or a semi-colon
457 // in the same brace nesting, bracket nesting and paren nesting.
458 // Parse functions if any...
459 //println("<i>EXP</i><BR/>");
466 var expressionBraceNesting = this.braceNesting;
467 var bracketNesting = 0;
468 var parensNesting = 0;
470 var isObjectLitAr = [ false ];
471 while (token = this.ts.lookTok()) {
475 currentScope = this.scopes[this.scopes.length-1];
477 //println("<i>"+token.data+"</i>");
478 print ("EXP" + token.ToString());
479 switch (token.type) {
485 if (this.braceNesting == expressionBraceNesting &&
486 bracketNesting == 0 &&
487 parensNesting == 0) {
495 case '{': //Token.LC:
496 isObjectLitAr.push(false);
501 case '}': //Token.RC:
505 // assert braceNesting >= expressionBraceNesting;
508 case '[': //Token.LB:
512 case ']': //Token.RB:
516 case '(': //Token.LP:
520 case ')': //Token.RP:
526 case 'STRN': // used for object lit detection..
527 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
528 // then we are in an object lit.. -> we need to flag the brace as such...
530 isObjectLitAr.push(true);
535 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
536 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
537 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
538 // see if we can replace..
539 // remove the quotes..
540 var str = token.data.substring(1,token.data.length-1);
541 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
556 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
557 // then we are in an object lit.. -> we need to flag the brace as such...
559 isObjectLitAr.push(true);
562 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
563 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
567 if (this.ts.lookTok(-1).data == ".") {
572 if (this.mode == 'CHECKING_SYMBOL_TREE') {
574 identifier = this.getIdentifier(symbol, currentScope);
575 //println("<B>??</B>");
576 if (identifier == false) {
578 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
579 // Here, we found an undeclared and un-namespaced symbol that is
580 // 3 characters or less in length. Declare it in the global scope.
581 // We don't need to declare longer symbols since they won't cause
582 // any conflict with other munged symbols.
583 this.globalScope.declareIdentifier(symbol, token);
584 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
586 //println("undeclared")
591 //println("<B>++</B>");
592 token.identifier = identifier;
593 identifier.refcount++;
602 //println("<B>EID</B>");
605 if (token.name == "FUNCTION") {
607 this.parseFunctionDeclaration();
614 if (this.mode == 'BUILDING_SYMBOL_TREE') {
616 if (symbol == "eval") {
617 if (this.ts.look(-1).type == 'COMM') {
618 // look for eval:var:noreplace\n
620 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
621 var hi = _t.getIdentifier(a, currentScope);
622 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
624 // println("PROTECT "+a+" from munge");
632 this.protectScopeFromObfuscation(currentScope);
633 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
642 if (!this.ts.nextTok()) break;
647 parseCatch : function() {
654 //token = getToken(-1);
655 //assert token.getType() == Token.CATCH;
656 token = this.ts.nextTok();
657 //assert token.getType() == Token.LP; (
658 token = this.ts.nextTok();
659 //assert token.getType() == Token.NAME;
662 currentScope = this.scopes[this.scopes.length-1];
664 if (this.mode == 'BUILDING_SYMBOL_TREE') {
665 // We must declare the exception identifier in the containing function
666 // scope to avoid errors related to the obfuscation process. No need to
667 // display a warning if the symbol was already declared here...
668 currentScope.declareIdentifier(symbol, token);
670 //?? why inc the refcount?? - that should be set when building the tree???
671 identifier = this.getIdentifier(symbol, currentScope);
672 identifier.refcount++;
675 token = this.ts.nextTok();
676 //assert token.getType() == Token.RP; // )
679 parseFunctionDeclaration : function()
684 var currentScope = false;
687 //this.logR("<B>PARSING FUNCTION</B>");
688 currentScope = this.scopes[this.scopes.length-1];
690 token = this.ts.nextTok();
691 if (token.type == "NAME") {
692 if (this.mode == 'BUILDING_SYMBOL_TREE') {
693 // Get the name of the function and declare it in the current scope.
695 if (currentScope.getIdentifier(symbol) != false) {
696 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
698 currentScope.declareIdentifier(symbol,token);
700 token = this.ts.nextTok();
703 //assert token.getType() == Token.LP;
704 if (this.mode == 'BUILDING_SYMBOL_TREE') {
705 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
707 //println("STORING SCOPE" + this.ts.cursor);
709 this.indexedScopes[this.ts.cursor] = fnScope;
712 //println("FETCHING SCOPE" + this.ts.cursor);
713 fnScope = this.indexedScopes[this.ts.cursor];
716 // Parse function arguments.
718 while (!this.ts.lookTok().data == ')') { //(token = consumeToken()).getType() != Token.RP) {
719 token = this.ts.nextTok();
721 //assert token.getType() == Token.NAME ||
722 // token.getType() == Token.COMMA;
723 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
725 identifier = fnScope.declareIdentifier(symbol,token);
726 if (symbol == "$super" && argpos == 0) {
727 // Exception for Prototype 1.6...
728 identifier.preventMunging();
734 token = this.ts.nextTok();
735 // assert token.getType() == Token.LC;
738 token = this.ts.nextTok();
739 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
742 NOT SUPPORTED YET!?!!?!
744 // This is a hint. Hints are empty statements that look like
745 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
746 // to prevent specific symbols from getting obfuscated (some heretic
747 // implementations, such as Prototype 1.6, require specific variable
748 // names, such as $super for example, in order to work appropriately.
749 // Note: right now, only "nomunge" is supported in the right hand side
750 // of a hint. However, in the future, the right hand side may contain
753 String hints = token.getValue();
754 // Remove the leading and trailing quotes...
755 hints = hints.substring(1, hints.length() - 1).trim();
756 StringTokenizer st1 = new StringTokenizer(hints, ",");
757 while (st1.hasMoreTokens()) {
758 String hint = st1.nextToken();
759 int idx = hint.indexOf(':');
760 if (idx <= 0 || idx >= hint.length() - 1) {
761 if (mode == BUILDING_SYMBOL_TREE) {
762 // No need to report the error twice, hence the test...
763 this.warn("Invalid hint syntax: " + hint, true);
767 String variableName = hint.substring(0, idx).trim();
768 String variableType = hint.substring(idx + 1).trim();
769 if (mode == BUILDING_SYMBOL_TREE) {
770 fnScope.addHint(variableName, variableType);
771 } else if (mode == CHECKING_SYMBOL_TREE) {
772 identifier = fnScope.getIdentifier(variableName);
773 if (identifier != null) {
774 if (variableType.equals("nomunge")) {
775 identifier.preventMunging();
777 this.warn("Unsupported hint value: " + hint, true);
780 this.warn("Hint refers to an unknown identifier: " + hint, true);
787 this.parseScope(fnScope);
788 // now pop it off the stack!!!
794 protectScopeFromObfuscation : function(scope) {
795 //assert scope != null;
797 if (scope == this.globalScope) {
798 // The global scope does not get obfuscated,
799 // so we don't need to worry about it...
803 // Find the highest local scope containing the specified scope.
804 while (scope && scope.parent != this.globalScope) {
805 scope = scope.parent;
808 //assert scope.getParentScope() == globalScope;
809 scope.preventMunging();
812 getIdentifier: function(symbol, scope) {
814 while (scope != false) {
815 identifier = scope.getIdentifier(symbol);
816 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
820 scope = scope.parent;