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 print (" ".substring(0, this.braceNesting*2) + str);
183 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
187 //println("<B>LOG:</B>" + str + "<BR/>");
192 dumpToken: function (tok, scope, brace) {
193 if (this.dumpLine == false) {
196 scope : scope.length,
202 if (this.dumpLine.scope == scope.length && this.dumpLine.brace == brace) {
203 this.dumpLine.str += ' ' + tok.data;
204 if (this.dumpLine.str.length < 80) {
208 (new Array(this.dumpLine.scope)).join(" ") + '|' +
209 (new Array(this.dumpLine.brace)).join(" ") + this.dumpLine.str);
210 this.dumpLine.str = '';
214 (new Array(this.dumpLine.scope)).join(" ") + '|' +
215 (new Array(this.dumpLine.brace)).join(" ") + this.dumpLine.str);
220 scope : scope.length,
228 parseScope : function(scope) // parse a token stream..
230 //this.timerPrint("parseScope EnterScope");
231 //this.log(">>> ENTER SCOPE" + this.scopes.length);
237 var expressionBraceNesting = this.braceNesting;
239 var parensNesting = 0;
241 var isObjectLitAr = [ false ];
243 this.scopes.push(scope);
245 var scopeIndent = '';
246 this.scopes.forEach(function() {
249 print(scopeIndent + ">> ENTER SCOPE");
254 token = this.ts.lookTok(1);
256 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
257 this.dumpToken(token , this.scopes, expressionBraceNesting);
258 //this.log(token.data);
259 if (token.type == 'NAME') {
260 // print('*' + token.data);
262 switch(token.type + '.' + token.name) {
264 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
266 //this.log("parseScope GOT VAR/CONST : " + token.toString());
268 token = this.ts.nextTok();
269 !this.debug|| print( token.toString());
271 if (!token) { // can return false at EOF!
274 if (token.name == "VAR" || token.data == ',') { // kludge..
277 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
278 if (token.type !="NAME") {
279 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
280 print(this.ts.tokens[i].toString());
283 print( "var without ident");
288 if (this.mode == "BUILDING_SYMBOL_TREE") {
289 identifier = scope.getIdentifier(token.data) ;
291 if (identifier == false) {
292 scope.declareIdentifier(token.data, token);
294 token.identifier = identifier;
295 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
299 token = this.ts.nextTok();
300 !this.debug|| print(token.toString());
302 assert token.getType() == Token.SEMI ||
303 token.getType() == Token.ASSIGN ||
304 token.getType() == Token.COMMA ||
305 token.getType() == Token.IN;
307 if (token.name == "IN") {
310 //var bn = this.braceNesting;
311 this.parseExpression();
312 //this.braceNesting = bn;
313 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
315 token = this.ts.lookTok(1);
316 !this.debug|| print("AFTER EXP: " + token.toString());
317 if (token.data == ';') {
323 case "KEYW.FUNCTION":
324 //println("<i>"+token.data+"</i>");
325 var bn = this.braceNesting;
326 this.parseFunctionDeclaration();
327 this.braceNesting = bn;
330 case "PUNC.LEFT_CURLY": // {
331 //println("<i>"+token.data+"</i>");
332 isObjectLitAr.push(false);
335 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
338 case "PUNC.RIGHT_CURLY": // }
339 //println("<i>"+token.data+"</i>");
342 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
343 //assert braceNesting >= scope.getBra ceNesting();
345 if (this.braceNesting < expressionBraceNesting) {
346 var ls = this.scopes.pop();
348 // eat symbol if we are currently at {
349 if (this.ts.look(0).data == '{') {
353 //print("<<<<<<<EXIT SCOPE" +this.scopes.length);
359 //println("<i>"+token.data+"</i>");
360 if (this.mode == "BUILDING_SYMBOL_TREE") {
361 // Inside a 'with' block, it is impossible to figure out
362 // statically whether a symbol is a local variable or an
363 // object member. As a consequence, the only thing we can
364 // do is turn the obfuscation off for the highest scope
365 // containing the 'with' block.
366 this.protectScopeFromObfuscation(scope);
367 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
372 //println("<i>"+token.data+"</i>");
376 case Token.SPECIALCOMMENT:
377 if (mode == BUILDING_SYMBOL_TREE) {
378 protectScopeFromObfuscation(scope);
379 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
384 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
385 case "STRN.SINGLE_QUOTE":
386 //println("<i>"+token.data+"</i>");
387 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
388 // then we are in an object lit.. -> we need to flag the brace as such...
390 isObjectLitAr.push(true);
391 //print(">>>>>> OBJLIT REPUSH(true)");
393 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
395 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
396 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
397 // see if we can replace..
398 // remove the quotes..
399 // should do a bit more checking!!!! (what about wierd char's in the string..
400 var str = token.data.substring(1,token.data.length-1);
401 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
415 //print("DEAL WITH NAME:");
418 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
419 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
421 isObjectLitAr.push(true);
422 //print(">>>>>> OBJLIT REPUSH(true)");
423 //println("<i>"+token.data+"</i>");
426 // print("DEAL WITH obj lit:");
427 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
429 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
430 // skip, it's an object lit key..
431 //println("<i>"+token.data+"</i>");
436 // skip anyting with "." before it..!!
438 if (this.ts.lookTok(-1).data == ".") {
439 // skip, it's an object prop.
440 //println("<i>"+token.data+"</i>");
444 if (this.mode == 'PASS2_SYMBOL_TREE') {
446 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
448 //print ("MUNGE?" + symbol);
450 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
452 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
453 identifier = this.getIdentifier(symbol, scope);
455 if (identifier == false) {
456 // BUG!find out where builtin is defined...
457 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
458 // Here, we found an undeclared and un-namespaced symbol that is
459 // 3 characters or less in length. Declare it in the global scope.
460 // We don't need to declare longer symbols since they won't cause
461 // any conflict with other munged symbols.
462 this.globalScope.declareIdentifier(symbol, token);
463 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
466 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
468 token.identifier = identifier;
469 identifier.refcount++;
474 //println("<B>SID</B>");
476 if (token.type != 'KEYW') {
479 // print("Check eval:");
483 if (this.mode == 'BUILDING_SYMBOL_TREE') {
485 if (symbol == "eval") {
486 // look back one and see if we can find a comment!!!
487 if (this.ts.look(-1).type == "COMM") {
488 // look for eval:var:noreplace\n
490 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
492 var hi = _t.getIdentifier(a, scope);
493 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
495 // println("PROTECT "+a+" from munge");
505 this.protectScopeFromObfuscation(scope);
506 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);
518 //this.timerPrint("parseScope TOK : " + token.toString());
519 token = this.ts.nextTok();
520 //if (this.ts.nextT()) break;
523 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
527 parseExpression : function() {
529 // Parse the expression until we encounter a comma or a semi-colon
530 // in the same brace nesting, bracket nesting and paren nesting.
531 // Parse functions if any...
532 //println("<i>EXP</i><BR/>");
533 !this.debug || print("PARSE EXPR");
536 // for printing stuff..
545 var expressionBraceNesting = this.braceNesting;
546 var bracketNesting = 0;
547 var parensNesting = 0;
549 var isObjectLitAr = [ false ];
551 currentScope = this.scopes[this.scopes.length-1];
553 var scopeIndent = '';
554 this.scopes.forEach(function() {
557 print(scopeIndent + ">> ENTER EXPRESSION");
558 while (token = this.ts.lookTok()) {
563 // moved out of loop?
564 currentScope = this.scopes[this.scopes.length-1];
566 var scopeIndent = '';
567 this.scopes.forEach(function() {
572 this.dumpToken(token, this.scopes, this.braceNesting );
575 //println("<i>"+token.data+"</i>");
576 //this.log("EXP:" + token.data);
577 switch (token.type) {
583 if (this.braceNesting == expressionBraceNesting &&
584 bracketNesting == 0 &&
585 parensNesting == 0) {
586 print(scopeIndent + "<< EXIT EXPRESSION");
593 case '{': //Token.LC:
594 isObjectLitAr.push(false);
597 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
600 case '}': //Token.RC:
603 //print(">>>>> EXP POP" + this.braceNesting);
604 // assert braceNesting >= expressionBraceNesting;
607 case '[': //Token.LB:
611 case ']': //Token.RB:
615 case '(': //Token.LP:
619 case ')': //Token.RP:
625 case 'STRN': // used for object lit detection..
626 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
627 // then we are in an object lit.. -> we need to flag the brace as such...
629 isObjectLitAr.push(true);
630 //print(">>>>> EXP PUSH(true)");
635 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
636 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
637 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
638 // see if we can replace..
639 // remove the quotes..
640 var str = token.data.substring(1,token.data.length-1);
641 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
656 //print("in NAME = " + token.toString());
657 //print("in NAME 0: " + this.ts.look(0).toString());
658 //print("in NAME 2: " + this.ts.lookTok(2).toString());
659 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
660 // then we are in an object lit.. -> we need to flag the brace as such...
662 isObjectLitAr.push(true);
663 //print(">>>>> EXP PUSH(true)");
667 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
668 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
670 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
673 //print(this.ts.lookTok(0).data);
674 if (this.ts.lookTok(0).data == ".") {
679 if (this.mode == 'PASS2_SYMBOL_TREE') {
681 identifier = this.getIdentifier(symbol, currentScope);
682 //println("<B>??</B>");
683 if (identifier == false) {
685 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
686 // Here, we found an undeclared and un-namespaced symbol that is
687 // 3 characters or less in length. Declare it in the global scope.
688 // We don't need to declare longer symbols since they won't cause
689 // any conflict with other munged symbols.
690 this.globalScope.declareIdentifier(symbol, token);
691 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
693 //println("undeclared")
698 //println("<B>++</B>");
699 token.identifier = identifier;
700 identifier.refcount++;
709 //println("<B>EID</B>");
712 if (token.name == "FUNCTION") {
714 this.parseFunctionDeclaration();
721 if (this.mode == 'BUILDING_SYMBOL_TREE') {
723 if (symbol == "eval") {
724 if (this.ts.look(-1).type == 'COMM') {
725 // look for eval:var:noreplace\n
727 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
728 var hi = _t.getIdentifier(a, currentScope);
729 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
731 // println("PROTECT "+a+" from munge");
739 this.protectScopeFromObfuscation(currentScope);
740 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
749 if (!this.ts.nextTok()) break;
751 print(scopeIndent + "<< EXIT EXPRESSION");
755 parseCatch : function() {
762 //token = getToken(-1);
763 //assert token.getType() == Token.CATCH;
764 token = this.ts.nextTok();
765 //assert token.getType() == Token.LP; (
766 token = this.ts.nextTok();
767 //assert token.getType() == Token.NAME;
770 currentScope = this.scopes[this.scopes.length-1];
772 if (this.mode == 'BUILDING_SYMBOL_TREE') {
773 // We must declare the exception identifier in the containing function
774 // scope to avoid errors related to the obfuscation process. No need to
775 // display a warning if the symbol was already declared here...
776 currentScope.declareIdentifier(symbol, token);
778 //?? why inc the refcount?? - that should be set when building the tree???
779 identifier = this.getIdentifier(symbol, currentScope);
780 identifier.refcount++;
783 token = this.ts.nextTok();
784 //assert token.getType() == Token.RP; // )
787 parseFunctionDeclaration : function()
789 // print("PARSE FUNCTION");
792 var currentScope = false;
795 //this.logR("<B>PARSING FUNCTION</B>");
796 currentScope = this.scopes[this.scopes.length-1];
798 token = this.ts.nextTok();
799 if (token.type == "NAME") {
800 if (this.mode == 'BUILDING_SYMBOL_TREE') {
801 // Get the name of the function and declare it in the current scope.
803 if (currentScope.getIdentifier(symbol) != false) {
804 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
806 currentScope.declareIdentifier(symbol,token);
808 token = this.ts.nextTok();
811 //assert token.getType() == Token.LP;
812 if (this.mode == 'BUILDING_SYMBOL_TREE') {
813 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
815 //println("STORING SCOPE" + this.ts.cursor);
817 this.indexedScopes[this.ts.cursor] = fnScope;
820 //qln("FETCHING SCOPE" + this.ts.cursor);
821 fnScope = this.indexedScopes[this.ts.cursor];
825 // Parse function arguments.
827 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
828 token = this.ts.nextTok();
829 // print ("FUNC ARGS: " + token.toString())
830 //assert token.getType() == Token.NAME ||
831 // token.getType() == Token.COMMA;
832 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
834 identifier = fnScope.declareIdentifier(symbol,token);
835 if (symbol == "$super" && argpos == 0) {
836 // Exception for Prototype 1.6...
837 identifier.preventMunging();
843 token = this.ts.nextTok();
844 // assert token.getType() == Token.LC;
847 token = this.ts.nextTok();
848 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
851 NOT SUPPORTED YET!?!!?!
853 // This is a hint. Hints are empty statements that look like
854 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
855 // to prevent specific symbols from getting obfuscated (some heretic
856 // implementations, such as Prototype 1.6, require specific variable
857 // names, such as $super for example, in order to work appropriately.
858 // Note: right now, only "nomunge" is supported in the right hand side
859 // of a hint. However, in the future, the right hand side may contain
862 String hints = token.getValue();
863 // Remove the leading and trailing quotes...
864 hints = hints.substring(1, hints.length() - 1).trim();
865 StringTokenizer st1 = new StringTokenizer(hints, ",");
866 while (st1.hasMoreTokens()) {
867 String hint = st1.nextToken();
868 int idx = hint.indexOf(':');
869 if (idx <= 0 || idx >= hint.length() - 1) {
870 if (mode == BUILDING_SYMBOL_TREE) {
871 // No need to report the error twice, hence the test...
872 this.warn("Invalid hint syntax: " + hint, true);
876 String variableName = hint.substring(0, idx).trim();
877 String variableType = hint.substring(idx + 1).trim();
878 if (mode == BUILDING_SYMBOL_TREE) {
879 fnScope.addHint(variableName, variableType);
880 } else if (mode == CHECKING_SYMBOL_TREE) {
881 identifier = fnScope.getIdentifier(variableName);
882 if (identifier != null) {
883 if (variableType.equals("nomunge")) {
884 identifier.preventMunging();
886 this.warn("Unsupported hint value: " + hint, true);
889 this.warn("Hint refers to an unknown identifier: " + hint, true);
896 this.parseScope(fnScope);
897 // now pop it off the stack!!!
903 protectScopeFromObfuscation : function(scope) {
904 //assert scope != null;
906 if (scope == this.globalScope) {
907 // The global scope does not get obfuscated,
908 // so we don't need to worry about it...
912 // Find the highest local scope containing the specified scope.
913 while (scope && scope.parent != this.globalScope) {
914 scope = scope.parent;
917 //assert scope.getParentScope() == globalScope;
918 scope.preventMunging();
921 getIdentifier: function(symbol, scope) {
923 while (scope != false) {
924 identifier = scope.getIdentifier(symbol);
925 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
929 scope = scope.parent;