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/>");
195 parseScope : function(scope) // parse a token stream..
197 //this.timerPrint("parseScope EnterScope");
198 //this.log(">>> ENTER SCOPE" + this.scopes.length);
204 var expressionBraceNesting = this.braceNesting;
206 var parensNesting = 0;
208 var isObjectLitAr = [ false ];
210 this.scopes.push(scope);
212 // for printing stuff..
213 var scopeIndent = '';
214 this.scopes.forEach(function() {
218 token = this.ts.lookTok(1);
220 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
222 //this.log(token.data);
223 if (token.type == 'NAME') {
224 // print('*' + token.data);
226 switch(token.type + '.' + token.name) {
228 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
230 //this.log("parseScope GOT VAR/CONST : " + token.toString());
232 token = this.ts.nextTok();
233 !this.debug|| print( token.toString());
235 if (!token) { // can return false at EOF!
238 if (token.name == "VAR" || token.data == ',') { // kludge..
241 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
242 if (token.type !="NAME") {
243 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
244 print(this.ts.tokens[i].toString());
247 print( "var without ident");
252 if (this.mode == "BUILDING_SYMBOL_TREE") {
253 identifier = scope.getIdentifier(token.data) ;
255 if (identifier == false) {
256 scope.declareIdentifier(token.data, token);
258 token.identifier = identifier;
259 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
263 token = this.ts.nextTok();
264 !this.debug|| print(token.toString());
266 assert token.getType() == Token.SEMI ||
267 token.getType() == Token.ASSIGN ||
268 token.getType() == Token.COMMA ||
269 token.getType() == Token.IN;
271 if (token.name == "IN") {
274 //var bn = this.braceNesting;
275 this.parseExpression();
276 //this.braceNesting = bn;
277 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
279 token = this.ts.lookTok(1);
280 !this.debug|| print("AFTER EXP: " + token.toString());
281 if (token.data == ';') {
287 case "KEYW.FUNCTION":
288 //println("<i>"+token.data+"</i>");
289 var bn = this.braceNesting;
290 this.parseFunctionDeclaration();
291 this.braceNesting = bn;
294 case "PUNC.LEFT_CURLY": // {
295 //println("<i>"+token.data+"</i>");
296 isObjectLitAr.push(false);
299 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
302 case "PUNC.RIGHT_CURLY": // }
303 //println("<i>"+token.data+"</i>");
306 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
307 //assert braceNesting >= scope.getBra ceNesting();
309 if (this.braceNesting < expressionBraceNesting) {
310 var ls = this.scopes.pop();
312 // eat symbol if we are currently at {
313 if (this.ts.look(0).data == '{') {
317 //print("<<<<<<<EXIT SCOPE" +this.scopes.length);
323 //println("<i>"+token.data+"</i>");
324 if (this.mode == "BUILDING_SYMBOL_TREE") {
325 // Inside a 'with' block, it is impossible to figure out
326 // statically whether a symbol is a local variable or an
327 // object member. As a consequence, the only thing we can
328 // do is turn the obfuscation off for the highest scope
329 // containing the 'with' block.
330 this.protectScopeFromObfuscation(scope);
331 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
336 //println("<i>"+token.data+"</i>");
340 case Token.SPECIALCOMMENT:
341 if (mode == BUILDING_SYMBOL_TREE) {
342 protectScopeFromObfuscation(scope);
343 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
348 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
349 case "STRN.SINGLE_QUOTE":
350 //println("<i>"+token.data+"</i>");
351 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
352 // then we are in an object lit.. -> we need to flag the brace as such...
354 isObjectLitAr.push(true);
355 //print(">>>>>> OBJLIT REPUSH(true)");
357 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
359 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
360 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
361 // see if we can replace..
362 // remove the quotes..
363 // should do a bit more checking!!!! (what about wierd char's in the string..
364 var str = token.data.substring(1,token.data.length-1);
365 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
379 //print("DEAL WITH NAME:");
382 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
383 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
385 isObjectLitAr.push(true);
386 //print(">>>>>> OBJLIT REPUSH(true)");
387 //println("<i>"+token.data+"</i>");
390 // print("DEAL WITH obj lit:");
391 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
393 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
394 // skip, it's an object lit key..
395 //println("<i>"+token.data+"</i>");
400 // skip anyting with "." before it..!!
402 if (this.ts.lookTok(-1).data == ".") {
403 // skip, it's an object prop.
404 //println("<i>"+token.data+"</i>");
408 if (this.mode == 'PASS2_SYMBOL_TREE') {
410 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
412 //print ("MUNGE?" + symbol);
414 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
416 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
417 identifier = this.getIdentifier(symbol, scope);
419 if (identifier == false) {
420 // BUG!find out where builtin is defined...
421 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
422 // Here, we found an undeclared and un-namespaced symbol that is
423 // 3 characters or less in length. Declare it in the global scope.
424 // We don't need to declare longer symbols since they won't cause
425 // any conflict with other munged symbols.
426 this.globalScope.declareIdentifier(symbol, token);
427 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
430 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
432 token.identifier = identifier;
433 identifier.refcount++;
438 //println("<B>SID</B>");
440 if (token.type != 'KEYW') {
443 // print("Check eval:");
447 if (this.mode == 'BUILDING_SYMBOL_TREE') {
449 if (symbol == "eval") {
450 // look back one and see if we can find a comment!!!
451 if (this.ts.look(-1).type == "COMM") {
452 // look for eval:var:noreplace\n
454 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
456 var hi = _t.getIdentifier(a, scope);
457 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
459 // println("PROTECT "+a+" from munge");
469 this.protectScopeFromObfuscation(scope);
470 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);
482 //this.timerPrint("parseScope TOK : " + token.toString());
483 token = this.ts.nextTok();
484 //if (this.ts.nextT()) break;
487 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
491 parseExpression : function() {
493 // Parse the expression until we encounter a comma or a semi-colon
494 // in the same brace nesting, bracket nesting and paren nesting.
495 // Parse functions if any...
496 //println("<i>EXP</i><BR/>");
497 !this.debug || print("PARSE EXPR");
503 var expressionBraceNesting = this.braceNesting;
504 var bracketNesting = 0;
505 var parensNesting = 0;
507 var isObjectLitAr = [ false ];
508 while (token = this.ts.lookTok()) {
512 currentScope = this.scopes[this.scopes.length-1];
514 //println("<i>"+token.data+"</i>");
515 //this.log("EXP:" + token.data);
516 switch (token.type) {
522 if (this.braceNesting == expressionBraceNesting &&
523 bracketNesting == 0 &&
524 parensNesting == 0) {
532 case '{': //Token.LC:
533 isObjectLitAr.push(false);
536 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
539 case '}': //Token.RC:
542 //print(">>>>> EXP POP" + this.braceNesting);
543 // assert braceNesting >= expressionBraceNesting;
546 case '[': //Token.LB:
550 case ']': //Token.RB:
554 case '(': //Token.LP:
558 case ')': //Token.RP:
564 case 'STRN': // used for object lit detection..
565 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
566 // then we are in an object lit.. -> we need to flag the brace as such...
568 isObjectLitAr.push(true);
569 //print(">>>>> EXP PUSH(true)");
574 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
575 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
576 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
577 // see if we can replace..
578 // remove the quotes..
579 var str = token.data.substring(1,token.data.length-1);
580 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
595 print("in NAME = " + token.toString());
596 print("in NAME 0: " + this.ts.look(0).toString());
597 print("in NAME 2: " + this.ts.lookTok(2).toString());
598 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
599 // then we are in an object lit.. -> we need to flag the brace as such...
601 isObjectLitAr.push(true);
602 //print(">>>>> EXP PUSH(true)");
606 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
607 print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
609 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
612 //print(this.ts.lookTok(0).data);
613 if (this.ts.lookTok(0).data == ".") {
618 if (this.mode == 'PASS2_SYMBOL_TREE') {
620 identifier = this.getIdentifier(symbol, currentScope);
621 //println("<B>??</B>");
622 if (identifier == false) {
624 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
625 // Here, we found an undeclared and un-namespaced symbol that is
626 // 3 characters or less in length. Declare it in the global scope.
627 // We don't need to declare longer symbols since they won't cause
628 // any conflict with other munged symbols.
629 this.globalScope.declareIdentifier(symbol, token);
630 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
632 //println("undeclared")
637 //println("<B>++</B>");
638 token.identifier = identifier;
639 identifier.refcount++;
648 //println("<B>EID</B>");
651 if (token.name == "FUNCTION") {
653 this.parseFunctionDeclaration();
660 if (this.mode == 'BUILDING_SYMBOL_TREE') {
662 if (symbol == "eval") {
663 if (this.ts.look(-1).type == 'COMM') {
664 // look for eval:var:noreplace\n
666 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
667 var hi = _t.getIdentifier(a, currentScope);
668 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
670 // println("PROTECT "+a+" from munge");
678 this.protectScopeFromObfuscation(currentScope);
679 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
688 if (!this.ts.nextTok()) break;
693 parseCatch : function() {
700 //token = getToken(-1);
701 //assert token.getType() == Token.CATCH;
702 token = this.ts.nextTok();
703 //assert token.getType() == Token.LP; (
704 token = this.ts.nextTok();
705 //assert token.getType() == Token.NAME;
708 currentScope = this.scopes[this.scopes.length-1];
710 if (this.mode == 'BUILDING_SYMBOL_TREE') {
711 // We must declare the exception identifier in the containing function
712 // scope to avoid errors related to the obfuscation process. No need to
713 // display a warning if the symbol was already declared here...
714 currentScope.declareIdentifier(symbol, token);
716 //?? why inc the refcount?? - that should be set when building the tree???
717 identifier = this.getIdentifier(symbol, currentScope);
718 identifier.refcount++;
721 token = this.ts.nextTok();
722 //assert token.getType() == Token.RP; // )
725 parseFunctionDeclaration : function()
727 // print("PARSE FUNCTION");
730 var currentScope = false;
733 //this.logR("<B>PARSING FUNCTION</B>");
734 currentScope = this.scopes[this.scopes.length-1];
736 token = this.ts.nextTok();
737 if (token.type == "NAME") {
738 if (this.mode == 'BUILDING_SYMBOL_TREE') {
739 // Get the name of the function and declare it in the current scope.
741 if (currentScope.getIdentifier(symbol) != false) {
742 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
744 currentScope.declareIdentifier(symbol,token);
746 token = this.ts.nextTok();
749 //assert token.getType() == Token.LP;
750 if (this.mode == 'BUILDING_SYMBOL_TREE') {
751 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
753 //println("STORING SCOPE" + this.ts.cursor);
755 this.indexedScopes[this.ts.cursor] = fnScope;
758 //qln("FETCHING SCOPE" + this.ts.cursor);
759 fnScope = this.indexedScopes[this.ts.cursor];
763 // Parse function arguments.
765 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
766 token = this.ts.nextTok();
767 // print ("FUNC ARGS: " + token.toString())
768 //assert token.getType() == Token.NAME ||
769 // token.getType() == Token.COMMA;
770 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
772 identifier = fnScope.declareIdentifier(symbol,token);
773 if (symbol == "$super" && argpos == 0) {
774 // Exception for Prototype 1.6...
775 identifier.preventMunging();
781 token = this.ts.nextTok();
782 // assert token.getType() == Token.LC;
785 token = this.ts.nextTok();
786 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
789 NOT SUPPORTED YET!?!!?!
791 // This is a hint. Hints are empty statements that look like
792 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
793 // to prevent specific symbols from getting obfuscated (some heretic
794 // implementations, such as Prototype 1.6, require specific variable
795 // names, such as $super for example, in order to work appropriately.
796 // Note: right now, only "nomunge" is supported in the right hand side
797 // of a hint. However, in the future, the right hand side may contain
800 String hints = token.getValue();
801 // Remove the leading and trailing quotes...
802 hints = hints.substring(1, hints.length() - 1).trim();
803 StringTokenizer st1 = new StringTokenizer(hints, ",");
804 while (st1.hasMoreTokens()) {
805 String hint = st1.nextToken();
806 int idx = hint.indexOf(':');
807 if (idx <= 0 || idx >= hint.length() - 1) {
808 if (mode == BUILDING_SYMBOL_TREE) {
809 // No need to report the error twice, hence the test...
810 this.warn("Invalid hint syntax: " + hint, true);
814 String variableName = hint.substring(0, idx).trim();
815 String variableType = hint.substring(idx + 1).trim();
816 if (mode == BUILDING_SYMBOL_TREE) {
817 fnScope.addHint(variableName, variableType);
818 } else if (mode == CHECKING_SYMBOL_TREE) {
819 identifier = fnScope.getIdentifier(variableName);
820 if (identifier != null) {
821 if (variableType.equals("nomunge")) {
822 identifier.preventMunging();
824 this.warn("Unsupported hint value: " + hint, true);
827 this.warn("Hint refers to an unknown identifier: " + hint, true);
834 this.parseScope(fnScope);
835 // now pop it off the stack!!!
841 protectScopeFromObfuscation : function(scope) {
842 //assert scope != null;
844 if (scope == this.globalScope) {
845 // The global scope does not get obfuscated,
846 // so we don't need to worry about it...
850 // Find the highest local scope containing the specified scope.
851 while (scope && scope.parent != this.globalScope) {
852 scope = scope.parent;
855 //assert scope.getParentScope() == globalScope;
856 scope.preventMunging();
859 getIdentifier: function(symbol, scope) {
861 while (scope != false) {
862 identifier = scope.getIdentifier(symbol);
863 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
867 scope = scope.parent;