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;
207 (new Array(this.dumpLine.scope)).join(" ") + '|' +
208 (new Array(brace)).join(" ") + this.dumpLine.str);
213 scope : scope.length,
221 parseScope : function(scope) // parse a token stream..
223 //this.timerPrint("parseScope EnterScope");
224 //this.log(">>> ENTER SCOPE" + this.scopes.length);
230 var expressionBraceNesting = this.braceNesting;
232 var parensNesting = 0;
234 var isObjectLitAr = [ false ];
236 this.scopes.push(scope);
238 var scopeIndent = '';
239 this.scopes.forEach(function() {
242 print(scopeIndent + ">> ENTER SCOPE");
247 token = this.ts.lookTok(1);
249 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
251 print(scopeIndent + expressionBraceNesting + ' SCOPE:' + token.data);
252 //this.log(token.data);
253 if (token.type == 'NAME') {
254 // print('*' + token.data);
256 switch(token.type + '.' + token.name) {
258 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
260 //this.log("parseScope GOT VAR/CONST : " + token.toString());
262 token = this.ts.nextTok();
263 !this.debug|| print( token.toString());
265 if (!token) { // can return false at EOF!
268 if (token.name == "VAR" || token.data == ',') { // kludge..
271 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
272 if (token.type !="NAME") {
273 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
274 print(this.ts.tokens[i].toString());
277 print( "var without ident");
282 if (this.mode == "BUILDING_SYMBOL_TREE") {
283 identifier = scope.getIdentifier(token.data) ;
285 if (identifier == false) {
286 scope.declareIdentifier(token.data, token);
288 token.identifier = identifier;
289 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
293 token = this.ts.nextTok();
294 !this.debug|| print(token.toString());
296 assert token.getType() == Token.SEMI ||
297 token.getType() == Token.ASSIGN ||
298 token.getType() == Token.COMMA ||
299 token.getType() == Token.IN;
301 if (token.name == "IN") {
304 //var bn = this.braceNesting;
305 this.parseExpression();
306 //this.braceNesting = bn;
307 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
309 token = this.ts.lookTok(1);
310 !this.debug|| print("AFTER EXP: " + token.toString());
311 if (token.data == ';') {
317 case "KEYW.FUNCTION":
318 //println("<i>"+token.data+"</i>");
319 var bn = this.braceNesting;
320 this.parseFunctionDeclaration();
321 this.braceNesting = bn;
324 case "PUNC.LEFT_CURLY": // {
325 //println("<i>"+token.data+"</i>");
326 isObjectLitAr.push(false);
329 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
332 case "PUNC.RIGHT_CURLY": // }
333 //println("<i>"+token.data+"</i>");
336 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
337 //assert braceNesting >= scope.getBra ceNesting();
339 if (this.braceNesting < expressionBraceNesting) {
340 var ls = this.scopes.pop();
342 // eat symbol if we are currently at {
343 if (this.ts.look(0).data == '{') {
347 //print("<<<<<<<EXIT SCOPE" +this.scopes.length);
353 //println("<i>"+token.data+"</i>");
354 if (this.mode == "BUILDING_SYMBOL_TREE") {
355 // Inside a 'with' block, it is impossible to figure out
356 // statically whether a symbol is a local variable or an
357 // object member. As a consequence, the only thing we can
358 // do is turn the obfuscation off for the highest scope
359 // containing the 'with' block.
360 this.protectScopeFromObfuscation(scope);
361 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
366 //println("<i>"+token.data+"</i>");
370 case Token.SPECIALCOMMENT:
371 if (mode == BUILDING_SYMBOL_TREE) {
372 protectScopeFromObfuscation(scope);
373 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
378 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
379 case "STRN.SINGLE_QUOTE":
380 //println("<i>"+token.data+"</i>");
381 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
382 // then we are in an object lit.. -> we need to flag the brace as such...
384 isObjectLitAr.push(true);
385 //print(">>>>>> OBJLIT REPUSH(true)");
387 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
389 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
390 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
391 // see if we can replace..
392 // remove the quotes..
393 // should do a bit more checking!!!! (what about wierd char's in the string..
394 var str = token.data.substring(1,token.data.length-1);
395 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
409 //print("DEAL WITH NAME:");
412 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
413 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
415 isObjectLitAr.push(true);
416 //print(">>>>>> OBJLIT REPUSH(true)");
417 //println("<i>"+token.data+"</i>");
420 // print("DEAL WITH obj lit:");
421 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
423 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
424 // skip, it's an object lit key..
425 //println("<i>"+token.data+"</i>");
430 // skip anyting with "." before it..!!
432 if (this.ts.lookTok(-1).data == ".") {
433 // skip, it's an object prop.
434 //println("<i>"+token.data+"</i>");
438 if (this.mode == 'PASS2_SYMBOL_TREE') {
440 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
442 //print ("MUNGE?" + symbol);
444 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
446 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
447 identifier = this.getIdentifier(symbol, scope);
449 if (identifier == false) {
450 // BUG!find out where builtin is defined...
451 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
452 // Here, we found an undeclared and un-namespaced symbol that is
453 // 3 characters or less in length. Declare it in the global scope.
454 // We don't need to declare longer symbols since they won't cause
455 // any conflict with other munged symbols.
456 this.globalScope.declareIdentifier(symbol, token);
457 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
460 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
462 token.identifier = identifier;
463 identifier.refcount++;
468 //println("<B>SID</B>");
470 if (token.type != 'KEYW') {
473 // print("Check eval:");
477 if (this.mode == 'BUILDING_SYMBOL_TREE') {
479 if (symbol == "eval") {
480 // look back one and see if we can find a comment!!!
481 if (this.ts.look(-1).type == "COMM") {
482 // look for eval:var:noreplace\n
484 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
486 var hi = _t.getIdentifier(a, scope);
487 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
489 // println("PROTECT "+a+" from munge");
499 this.protectScopeFromObfuscation(scope);
500 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);
512 //this.timerPrint("parseScope TOK : " + token.toString());
513 token = this.ts.nextTok();
514 //if (this.ts.nextT()) break;
517 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
521 parseExpression : function() {
523 // Parse the expression until we encounter a comma or a semi-colon
524 // in the same brace nesting, bracket nesting and paren nesting.
525 // Parse functions if any...
526 //println("<i>EXP</i><BR/>");
527 !this.debug || print("PARSE EXPR");
530 // for printing stuff..
539 var expressionBraceNesting = this.braceNesting;
540 var bracketNesting = 0;
541 var parensNesting = 0;
543 var isObjectLitAr = [ false ];
545 currentScope = this.scopes[this.scopes.length-1];
547 var scopeIndent = '';
548 this.scopes.forEach(function() {
551 print(scopeIndent + ">> ENTER EXPRESSION");
552 while (token = this.ts.lookTok()) {
557 // moved out of loop?
558 currentScope = this.scopes[this.scopes.length-1];
560 var scopeIndent = '';
561 this.scopes.forEach(function() {
565 print(scopeIndent + 'OBJLIT.len='+ isObjectLitAr.length + ' ' + token.data);
567 //println("<i>"+token.data+"</i>");
568 //this.log("EXP:" + token.data);
569 switch (token.type) {
575 if (this.braceNesting == expressionBraceNesting &&
576 bracketNesting == 0 &&
577 parensNesting == 0) {
578 print(scopeIndent + "<< EXIT EXPRESSION");
585 case '{': //Token.LC:
586 isObjectLitAr.push(false);
589 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
592 case '}': //Token.RC:
595 //print(">>>>> EXP POP" + this.braceNesting);
596 // assert braceNesting >= expressionBraceNesting;
599 case '[': //Token.LB:
603 case ']': //Token.RB:
607 case '(': //Token.LP:
611 case ')': //Token.RP:
617 case 'STRN': // used for object lit detection..
618 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
619 // then we are in an object lit.. -> we need to flag the brace as such...
621 isObjectLitAr.push(true);
622 //print(">>>>> EXP PUSH(true)");
627 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
628 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
629 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
630 // see if we can replace..
631 // remove the quotes..
632 var str = token.data.substring(1,token.data.length-1);
633 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
648 //print("in NAME = " + token.toString());
649 //print("in NAME 0: " + this.ts.look(0).toString());
650 //print("in NAME 2: " + this.ts.lookTok(2).toString());
651 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
652 // then we are in an object lit.. -> we need to flag the brace as such...
654 isObjectLitAr.push(true);
655 //print(">>>>> EXP PUSH(true)");
659 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
660 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
662 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
665 //print(this.ts.lookTok(0).data);
666 if (this.ts.lookTok(0).data == ".") {
671 if (this.mode == 'PASS2_SYMBOL_TREE') {
673 identifier = this.getIdentifier(symbol, currentScope);
674 //println("<B>??</B>");
675 if (identifier == false) {
677 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
678 // Here, we found an undeclared and un-namespaced symbol that is
679 // 3 characters or less in length. Declare it in the global scope.
680 // We don't need to declare longer symbols since they won't cause
681 // any conflict with other munged symbols.
682 this.globalScope.declareIdentifier(symbol, token);
683 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
685 //println("undeclared")
690 //println("<B>++</B>");
691 token.identifier = identifier;
692 identifier.refcount++;
701 //println("<B>EID</B>");
704 if (token.name == "FUNCTION") {
706 this.parseFunctionDeclaration();
713 if (this.mode == 'BUILDING_SYMBOL_TREE') {
715 if (symbol == "eval") {
716 if (this.ts.look(-1).type == 'COMM') {
717 // look for eval:var:noreplace\n
719 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
720 var hi = _t.getIdentifier(a, currentScope);
721 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
723 // println("PROTECT "+a+" from munge");
731 this.protectScopeFromObfuscation(currentScope);
732 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
741 if (!this.ts.nextTok()) break;
743 print(scopeIndent + "<< EXIT EXPRESSION");
747 parseCatch : function() {
754 //token = getToken(-1);
755 //assert token.getType() == Token.CATCH;
756 token = this.ts.nextTok();
757 //assert token.getType() == Token.LP; (
758 token = this.ts.nextTok();
759 //assert token.getType() == Token.NAME;
762 currentScope = this.scopes[this.scopes.length-1];
764 if (this.mode == 'BUILDING_SYMBOL_TREE') {
765 // We must declare the exception identifier in the containing function
766 // scope to avoid errors related to the obfuscation process. No need to
767 // display a warning if the symbol was already declared here...
768 currentScope.declareIdentifier(symbol, token);
770 //?? why inc the refcount?? - that should be set when building the tree???
771 identifier = this.getIdentifier(symbol, currentScope);
772 identifier.refcount++;
775 token = this.ts.nextTok();
776 //assert token.getType() == Token.RP; // )
779 parseFunctionDeclaration : function()
781 // print("PARSE FUNCTION");
784 var currentScope = false;
787 //this.logR("<B>PARSING FUNCTION</B>");
788 currentScope = this.scopes[this.scopes.length-1];
790 token = this.ts.nextTok();
791 if (token.type == "NAME") {
792 if (this.mode == 'BUILDING_SYMBOL_TREE') {
793 // Get the name of the function and declare it in the current scope.
795 if (currentScope.getIdentifier(symbol) != false) {
796 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
798 currentScope.declareIdentifier(symbol,token);
800 token = this.ts.nextTok();
803 //assert token.getType() == Token.LP;
804 if (this.mode == 'BUILDING_SYMBOL_TREE') {
805 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
807 //println("STORING SCOPE" + this.ts.cursor);
809 this.indexedScopes[this.ts.cursor] = fnScope;
812 //qln("FETCHING SCOPE" + this.ts.cursor);
813 fnScope = this.indexedScopes[this.ts.cursor];
817 // Parse function arguments.
819 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
820 token = this.ts.nextTok();
821 // print ("FUNC ARGS: " + token.toString())
822 //assert token.getType() == Token.NAME ||
823 // token.getType() == Token.COMMA;
824 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
826 identifier = fnScope.declareIdentifier(symbol,token);
827 if (symbol == "$super" && argpos == 0) {
828 // Exception for Prototype 1.6...
829 identifier.preventMunging();
835 token = this.ts.nextTok();
836 // assert token.getType() == Token.LC;
839 token = this.ts.nextTok();
840 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
843 NOT SUPPORTED YET!?!!?!
845 // This is a hint. Hints are empty statements that look like
846 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
847 // to prevent specific symbols from getting obfuscated (some heretic
848 // implementations, such as Prototype 1.6, require specific variable
849 // names, such as $super for example, in order to work appropriately.
850 // Note: right now, only "nomunge" is supported in the right hand side
851 // of a hint. However, in the future, the right hand side may contain
854 String hints = token.getValue();
855 // Remove the leading and trailing quotes...
856 hints = hints.substring(1, hints.length() - 1).trim();
857 StringTokenizer st1 = new StringTokenizer(hints, ",");
858 while (st1.hasMoreTokens()) {
859 String hint = st1.nextToken();
860 int idx = hint.indexOf(':');
861 if (idx <= 0 || idx >= hint.length() - 1) {
862 if (mode == BUILDING_SYMBOL_TREE) {
863 // No need to report the error twice, hence the test...
864 this.warn("Invalid hint syntax: " + hint, true);
868 String variableName = hint.substring(0, idx).trim();
869 String variableType = hint.substring(idx + 1).trim();
870 if (mode == BUILDING_SYMBOL_TREE) {
871 fnScope.addHint(variableName, variableType);
872 } else if (mode == CHECKING_SYMBOL_TREE) {
873 identifier = fnScope.getIdentifier(variableName);
874 if (identifier != null) {
875 if (variableType.equals("nomunge")) {
876 identifier.preventMunging();
878 this.warn("Unsupported hint value: " + hint, true);
881 this.warn("Hint refers to an unknown identifier: " + hint, true);
888 this.parseScope(fnScope);
889 // now pop it off the stack!!!
895 protectScopeFromObfuscation : function(scope) {
896 //assert scope != null;
898 if (scope == this.globalScope) {
899 // The global scope does not get obfuscated,
900 // so we don't need to worry about it...
904 // Find the highest local scope containing the specified scope.
905 while (scope && scope.parent != this.globalScope) {
906 scope = scope.parent;
909 //assert scope.getParentScope() == globalScope;
910 scope.preventMunging();
913 getIdentifier: function(symbol, scope) {
915 while (scope != false) {
916 identifier = scope.getIdentifier(symbol);
917 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
921 scope = scope.parent;