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);
213 token = this.ts.lookTok(1);
215 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
216 //print(scopeIndent + 'OBJLIT.len='+ isObjectLitAr.length + ' ' + token.toString());
217 //this.log(token.data);
218 if (token.type == 'NAME') {
219 // print('*' + token.data);
221 switch(token.type + '.' + token.name) {
223 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
225 //this.log("parseScope GOT VAR/CONST : " + token.toString());
227 token = this.ts.nextTok();
228 !this.debug|| print( token.toString());
230 if (!token) { // can return false at EOF!
233 if (token.name == "VAR" || token.data == ',') { // kludge..
236 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
237 if (token.type !="NAME") {
238 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
239 print(this.ts.tokens[i].toString());
242 print( "var without ident");
247 if (this.mode == "BUILDING_SYMBOL_TREE") {
248 identifier = scope.getIdentifier(token.data) ;
250 if (identifier == false) {
251 scope.declareIdentifier(token.data, token);
253 token.identifier = identifier;
254 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
258 token = this.ts.nextTok();
259 !this.debug|| print(token.toString());
261 assert token.getType() == Token.SEMI ||
262 token.getType() == Token.ASSIGN ||
263 token.getType() == Token.COMMA ||
264 token.getType() == Token.IN;
266 if (token.name == "IN") {
269 //var bn = this.braceNesting;
270 this.parseExpression();
271 //this.braceNesting = bn;
272 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
274 token = this.ts.lookTok(1);
275 !this.debug|| print("AFTER EXP: " + token.toString());
276 if (token.data == ';') {
282 case "KEYW.FUNCTION":
283 //println("<i>"+token.data+"</i>");
284 var bn = this.braceNesting;
285 this.parseFunctionDeclaration();
286 this.braceNesting = bn;
289 case "PUNC.LEFT_CURLY": // {
290 //println("<i>"+token.data+"</i>");
291 isObjectLitAr.push(false);
294 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
297 case "PUNC.RIGHT_CURLY": // }
298 //println("<i>"+token.data+"</i>");
301 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
302 //assert braceNesting >= scope.getBra ceNesting();
304 if (this.braceNesting < expressionBraceNesting) {
305 var ls = this.scopes.pop();
307 // eat symbol if we are currently at {
308 if (this.ts.look(0).data == '{') {
312 //print("<<<<<<<EXIT SCOPE" +this.scopes.length);
318 //println("<i>"+token.data+"</i>");
319 if (this.mode == "BUILDING_SYMBOL_TREE") {
320 // Inside a 'with' block, it is impossible to figure out
321 // statically whether a symbol is a local variable or an
322 // object member. As a consequence, the only thing we can
323 // do is turn the obfuscation off for the highest scope
324 // containing the 'with' block.
325 this.protectScopeFromObfuscation(scope);
326 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
331 //println("<i>"+token.data+"</i>");
335 case Token.SPECIALCOMMENT:
336 if (mode == BUILDING_SYMBOL_TREE) {
337 protectScopeFromObfuscation(scope);
338 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
343 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
344 case "STRN.SINGLE_QUOTE":
345 //println("<i>"+token.data+"</i>");
346 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
347 // then we are in an object lit.. -> we need to flag the brace as such...
349 isObjectLitAr.push(true);
350 //print(">>>>>> OBJLIT REPUSH(true)");
352 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
354 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
355 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
356 // see if we can replace..
357 // remove the quotes..
358 // should do a bit more checking!!!! (what about wierd char's in the string..
359 var str = token.data.substring(1,token.data.length-1);
360 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
374 //print("DEAL WITH NAME:");
377 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
378 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
380 isObjectLitAr.push(true);
381 //print(">>>>>> OBJLIT REPUSH(true)");
382 //println("<i>"+token.data+"</i>");
385 // print("DEAL WITH obj lit:");
386 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
388 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
389 // skip, it's an object lit key..
390 //println("<i>"+token.data+"</i>");
395 // skip anyting with "." before it..!!
397 if (this.ts.lookTok(-1).data == ".") {
398 // skip, it's an object prop.
399 //println("<i>"+token.data+"</i>");
403 if (this.mode == 'PASS2_SYMBOL_TREE') {
405 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
407 //print ("MUNGE?" + symbol);
409 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
411 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
412 identifier = this.getIdentifier(symbol, scope);
414 if (identifier == false) {
415 // BUG!find out where builtin is defined...
416 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
417 // Here, we found an undeclared and un-namespaced symbol that is
418 // 3 characters or less in length. Declare it in the global scope.
419 // We don't need to declare longer symbols since they won't cause
420 // any conflict with other munged symbols.
421 this.globalScope.declareIdentifier(symbol, token);
422 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
425 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
427 token.identifier = identifier;
428 identifier.refcount++;
433 //println("<B>SID</B>");
435 if (token.type != 'KEYW') {
438 // print("Check eval:");
442 if (this.mode == 'BUILDING_SYMBOL_TREE') {
444 if (symbol == "eval") {
445 // look back one and see if we can find a comment!!!
446 if (this.ts.look(-1).type == "COMM") {
447 // look for eval:var:noreplace\n
449 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
451 var hi = _t.getIdentifier(a, scope);
452 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
454 // println("PROTECT "+a+" from munge");
464 this.protectScopeFromObfuscation(scope);
465 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);
477 //this.timerPrint("parseScope TOK : " + token.toString());
478 token = this.ts.nextTok();
479 //if (this.ts.nextT()) break;
482 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
486 parseExpression : function() {
488 // Parse the expression until we encounter a comma or a semi-colon
489 // in the same brace nesting, bracket nesting and paren nesting.
490 // Parse functions if any...
491 //println("<i>EXP</i><BR/>");
492 !this.debug || print("PARSE EXPR");
493 print(">> ENTER EXPRESSION");
495 // for printing stuff..
504 var expressionBraceNesting = this.braceNesting;
505 var bracketNesting = 0;
506 var parensNesting = 0;
508 var isObjectLitAr = [ false ];
509 while (token = this.ts.lookTok()) {
513 currentScope = this.scopes[this.scopes.length-1];
515 var scopeIndent = '';
516 this.scopes.forEach(function() {
520 print(scopeIndent + 'OBJLIT.len='+ isObjectLitAr.length + ' ' + token.data);
522 //println("<i>"+token.data+"</i>");
523 //this.log("EXP:" + token.data);
524 switch (token.type) {
530 if (this.braceNesting == expressionBraceNesting &&
531 bracketNesting == 0 &&
532 parensNesting == 0) {
533 print(scopeIndent + "<< EXIT EXPRESSION");
540 case '{': //Token.LC:
541 isObjectLitAr.push(false);
544 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
547 case '}': //Token.RC:
550 //print(">>>>> EXP POP" + this.braceNesting);
551 // assert braceNesting >= expressionBraceNesting;
554 case '[': //Token.LB:
558 case ']': //Token.RB:
562 case '(': //Token.LP:
566 case ')': //Token.RP:
572 case 'STRN': // used for object lit detection..
573 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
574 // then we are in an object lit.. -> we need to flag the brace as such...
576 isObjectLitAr.push(true);
577 //print(">>>>> EXP PUSH(true)");
582 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
583 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
584 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
585 // see if we can replace..
586 // remove the quotes..
587 var str = token.data.substring(1,token.data.length-1);
588 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
603 //print("in NAME = " + token.toString());
604 //print("in NAME 0: " + this.ts.look(0).toString());
605 //print("in NAME 2: " + this.ts.lookTok(2).toString());
606 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
607 // then we are in an object lit.. -> we need to flag the brace as such...
609 isObjectLitAr.push(true);
610 //print(">>>>> EXP PUSH(true)");
614 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
615 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
617 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
620 //print(this.ts.lookTok(0).data);
621 if (this.ts.lookTok(0).data == ".") {
626 if (this.mode == 'PASS2_SYMBOL_TREE') {
628 identifier = this.getIdentifier(symbol, currentScope);
629 //println("<B>??</B>");
630 if (identifier == false) {
632 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
633 // Here, we found an undeclared and un-namespaced symbol that is
634 // 3 characters or less in length. Declare it in the global scope.
635 // We don't need to declare longer symbols since they won't cause
636 // any conflict with other munged symbols.
637 this.globalScope.declareIdentifier(symbol, token);
638 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
640 //println("undeclared")
645 //println("<B>++</B>");
646 token.identifier = identifier;
647 identifier.refcount++;
656 //println("<B>EID</B>");
659 if (token.name == "FUNCTION") {
661 this.parseFunctionDeclaration();
668 if (this.mode == 'BUILDING_SYMBOL_TREE') {
670 if (symbol == "eval") {
671 if (this.ts.look(-1).type == 'COMM') {
672 // look for eval:var:noreplace\n
674 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
675 var hi = _t.getIdentifier(a, currentScope);
676 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
678 // println("PROTECT "+a+" from munge");
686 this.protectScopeFromObfuscation(currentScope);
687 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
696 if (!this.ts.nextTok()) break;
698 print(scopeIndent + "<< EXIT EXPRESSION");
702 parseCatch : function() {
709 //token = getToken(-1);
710 //assert token.getType() == Token.CATCH;
711 token = this.ts.nextTok();
712 //assert token.getType() == Token.LP; (
713 token = this.ts.nextTok();
714 //assert token.getType() == Token.NAME;
717 currentScope = this.scopes[this.scopes.length-1];
719 if (this.mode == 'BUILDING_SYMBOL_TREE') {
720 // We must declare the exception identifier in the containing function
721 // scope to avoid errors related to the obfuscation process. No need to
722 // display a warning if the symbol was already declared here...
723 currentScope.declareIdentifier(symbol, token);
725 //?? why inc the refcount?? - that should be set when building the tree???
726 identifier = this.getIdentifier(symbol, currentScope);
727 identifier.refcount++;
730 token = this.ts.nextTok();
731 //assert token.getType() == Token.RP; // )
734 parseFunctionDeclaration : function()
736 // print("PARSE FUNCTION");
739 var currentScope = false;
742 //this.logR("<B>PARSING FUNCTION</B>");
743 currentScope = this.scopes[this.scopes.length-1];
745 token = this.ts.nextTok();
746 if (token.type == "NAME") {
747 if (this.mode == 'BUILDING_SYMBOL_TREE') {
748 // Get the name of the function and declare it in the current scope.
750 if (currentScope.getIdentifier(symbol) != false) {
751 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
753 currentScope.declareIdentifier(symbol,token);
755 token = this.ts.nextTok();
758 //assert token.getType() == Token.LP;
759 if (this.mode == 'BUILDING_SYMBOL_TREE') {
760 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
762 //println("STORING SCOPE" + this.ts.cursor);
764 this.indexedScopes[this.ts.cursor] = fnScope;
767 //qln("FETCHING SCOPE" + this.ts.cursor);
768 fnScope = this.indexedScopes[this.ts.cursor];
772 // Parse function arguments.
774 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
775 token = this.ts.nextTok();
776 // print ("FUNC ARGS: " + token.toString())
777 //assert token.getType() == Token.NAME ||
778 // token.getType() == Token.COMMA;
779 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
781 identifier = fnScope.declareIdentifier(symbol,token);
782 if (symbol == "$super" && argpos == 0) {
783 // Exception for Prototype 1.6...
784 identifier.preventMunging();
790 token = this.ts.nextTok();
791 // assert token.getType() == Token.LC;
794 token = this.ts.nextTok();
795 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
798 NOT SUPPORTED YET!?!!?!
800 // This is a hint. Hints are empty statements that look like
801 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
802 // to prevent specific symbols from getting obfuscated (some heretic
803 // implementations, such as Prototype 1.6, require specific variable
804 // names, such as $super for example, in order to work appropriately.
805 // Note: right now, only "nomunge" is supported in the right hand side
806 // of a hint. However, in the future, the right hand side may contain
809 String hints = token.getValue();
810 // Remove the leading and trailing quotes...
811 hints = hints.substring(1, hints.length() - 1).trim();
812 StringTokenizer st1 = new StringTokenizer(hints, ",");
813 while (st1.hasMoreTokens()) {
814 String hint = st1.nextToken();
815 int idx = hint.indexOf(':');
816 if (idx <= 0 || idx >= hint.length() - 1) {
817 if (mode == BUILDING_SYMBOL_TREE) {
818 // No need to report the error twice, hence the test...
819 this.warn("Invalid hint syntax: " + hint, true);
823 String variableName = hint.substring(0, idx).trim();
824 String variableType = hint.substring(idx + 1).trim();
825 if (mode == BUILDING_SYMBOL_TREE) {
826 fnScope.addHint(variableName, variableType);
827 } else if (mode == CHECKING_SYMBOL_TREE) {
828 identifier = fnScope.getIdentifier(variableName);
829 if (identifier != null) {
830 if (variableType.equals("nomunge")) {
831 identifier.preventMunging();
833 this.warn("Unsupported hint value: " + hint, true);
836 this.warn("Hint refers to an unknown identifier: " + hint, true);
843 this.parseScope(fnScope);
844 // now pop it off the stack!!!
850 protectScopeFromObfuscation : function(scope) {
851 //assert scope != null;
853 if (scope == this.globalScope) {
854 // The global scope does not get obfuscated,
855 // so we don't need to worry about it...
859 // Find the highest local scope containing the specified scope.
860 while (scope && scope.parent != this.globalScope) {
861 scope = scope.parent;
864 //assert scope.getParentScope() == globalScope;
865 scope.preventMunging();
868 getIdentifier: function(symbol, scope) {
870 while (scope != false) {
871 identifier = scope.getIdentifier(symbol);
872 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
876 scope = scope.parent;