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 var scopeIndent = '';
213 this.scopes.forEach(function() {
216 print(scopeIndent + ">> ENTER SCOPE");
219 token = this.ts.lookTok(1);
221 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
223 print(scopeIndent + ' SCOPE:' + token.data);
224 //this.log(token.data);
225 if (token.type == 'NAME') {
226 // print('*' + token.data);
228 switch(token.type + '.' + token.name) {
230 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
232 //this.log("parseScope GOT VAR/CONST : " + token.toString());
234 token = this.ts.nextTok();
235 !this.debug|| print( token.toString());
237 if (!token) { // can return false at EOF!
240 if (token.name == "VAR" || token.data == ',') { // kludge..
243 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
244 if (token.type !="NAME") {
245 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
246 print(this.ts.tokens[i].toString());
249 print( "var without ident");
254 if (this.mode == "BUILDING_SYMBOL_TREE") {
255 identifier = scope.getIdentifier(token.data) ;
257 if (identifier == false) {
258 scope.declareIdentifier(token.data, token);
260 token.identifier = identifier;
261 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
265 token = this.ts.nextTok();
266 !this.debug|| print(token.toString());
268 assert token.getType() == Token.SEMI ||
269 token.getType() == Token.ASSIGN ||
270 token.getType() == Token.COMMA ||
271 token.getType() == Token.IN;
273 if (token.name == "IN") {
276 //var bn = this.braceNesting;
277 this.parseExpression();
278 //this.braceNesting = bn;
279 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
281 token = this.ts.lookTok(1);
282 !this.debug|| print("AFTER EXP: " + token.toString());
283 if (token.data == ';') {
289 case "KEYW.FUNCTION":
290 //println("<i>"+token.data+"</i>");
291 var bn = this.braceNesting;
292 this.parseFunctionDeclaration();
293 this.braceNesting = bn;
296 case "PUNC.LEFT_CURLY": // {
297 //println("<i>"+token.data+"</i>");
298 isObjectLitAr.push(false);
301 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
304 case "PUNC.RIGHT_CURLY": // }
305 //println("<i>"+token.data+"</i>");
308 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
309 //assert braceNesting >= scope.getBra ceNesting();
311 if (this.braceNesting < expressionBraceNesting) {
312 var ls = this.scopes.pop();
314 // eat symbol if we are currently at {
315 if (this.ts.look(0).data == '{') {
319 //print("<<<<<<<EXIT SCOPE" +this.scopes.length);
325 //println("<i>"+token.data+"</i>");
326 if (this.mode == "BUILDING_SYMBOL_TREE") {
327 // Inside a 'with' block, it is impossible to figure out
328 // statically whether a symbol is a local variable or an
329 // object member. As a consequence, the only thing we can
330 // do is turn the obfuscation off for the highest scope
331 // containing the 'with' block.
332 this.protectScopeFromObfuscation(scope);
333 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
338 //println("<i>"+token.data+"</i>");
342 case Token.SPECIALCOMMENT:
343 if (mode == BUILDING_SYMBOL_TREE) {
344 protectScopeFromObfuscation(scope);
345 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
350 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
351 case "STRN.SINGLE_QUOTE":
352 //println("<i>"+token.data+"</i>");
353 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
354 // then we are in an object lit.. -> we need to flag the brace as such...
356 isObjectLitAr.push(true);
357 //print(">>>>>> OBJLIT REPUSH(true)");
359 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
361 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
362 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
363 // see if we can replace..
364 // remove the quotes..
365 // should do a bit more checking!!!! (what about wierd char's in the string..
366 var str = token.data.substring(1,token.data.length-1);
367 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
381 //print("DEAL WITH NAME:");
384 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
385 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
387 isObjectLitAr.push(true);
388 //print(">>>>>> OBJLIT REPUSH(true)");
389 //println("<i>"+token.data+"</i>");
392 // print("DEAL WITH obj lit:");
393 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
395 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
396 // skip, it's an object lit key..
397 //println("<i>"+token.data+"</i>");
402 // skip anyting with "." before it..!!
404 if (this.ts.lookTok(-1).data == ".") {
405 // skip, it's an object prop.
406 //println("<i>"+token.data+"</i>");
410 if (this.mode == 'PASS2_SYMBOL_TREE') {
412 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
414 //print ("MUNGE?" + symbol);
416 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
418 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
419 identifier = this.getIdentifier(symbol, scope);
421 if (identifier == false) {
422 // BUG!find out where builtin is defined...
423 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
424 // Here, we found an undeclared and un-namespaced symbol that is
425 // 3 characters or less in length. Declare it in the global scope.
426 // We don't need to declare longer symbols since they won't cause
427 // any conflict with other munged symbols.
428 this.globalScope.declareIdentifier(symbol, token);
429 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
432 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
434 token.identifier = identifier;
435 identifier.refcount++;
440 //println("<B>SID</B>");
442 if (token.type != 'KEYW') {
445 // print("Check eval:");
449 if (this.mode == 'BUILDING_SYMBOL_TREE') {
451 if (symbol == "eval") {
452 // look back one and see if we can find a comment!!!
453 if (this.ts.look(-1).type == "COMM") {
454 // look for eval:var:noreplace\n
456 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
458 var hi = _t.getIdentifier(a, scope);
459 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
461 // println("PROTECT "+a+" from munge");
471 this.protectScopeFromObfuscation(scope);
472 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);
484 //this.timerPrint("parseScope TOK : " + token.toString());
485 token = this.ts.nextTok();
486 //if (this.ts.nextT()) break;
489 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
493 parseExpression : function() {
495 // Parse the expression until we encounter a comma or a semi-colon
496 // in the same brace nesting, bracket nesting and paren nesting.
497 // Parse functions if any...
498 //println("<i>EXP</i><BR/>");
499 !this.debug || print("PARSE EXPR");
502 // for printing stuff..
511 var expressionBraceNesting = this.braceNesting;
512 var bracketNesting = 0;
513 var parensNesting = 0;
515 var isObjectLitAr = [ false ];
517 currentScope = this.scopes[this.scopes.length-1];
519 var scopeIndent = '';
520 this.scopes.forEach(function() {
523 print(scopeIndent + ">> ENTER EXPRESSION");
524 while (token = this.ts.lookTok()) {
529 // moved out of loop?
530 currentScope = this.scopes[this.scopes.length-1];
532 var scopeIndent = '';
533 this.scopes.forEach(function() {
537 print(scopeIndent + 'OBJLIT.len='+ isObjectLitAr.length + ' ' + token.data);
539 //println("<i>"+token.data+"</i>");
540 //this.log("EXP:" + token.data);
541 switch (token.type) {
547 if (this.braceNesting == expressionBraceNesting &&
548 bracketNesting == 0 &&
549 parensNesting == 0) {
550 print(scopeIndent + "<< EXIT EXPRESSION");
557 case '{': //Token.LC:
558 isObjectLitAr.push(false);
561 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
564 case '}': //Token.RC:
567 //print(">>>>> EXP POP" + this.braceNesting);
568 // assert braceNesting >= expressionBraceNesting;
571 case '[': //Token.LB:
575 case ']': //Token.RB:
579 case '(': //Token.LP:
583 case ')': //Token.RP:
589 case 'STRN': // used for object lit detection..
590 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
591 // then we are in an object lit.. -> we need to flag the brace as such...
593 isObjectLitAr.push(true);
594 //print(">>>>> EXP PUSH(true)");
599 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
600 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
601 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
602 // see if we can replace..
603 // remove the quotes..
604 var str = token.data.substring(1,token.data.length-1);
605 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
620 //print("in NAME = " + token.toString());
621 //print("in NAME 0: " + this.ts.look(0).toString());
622 //print("in NAME 2: " + this.ts.lookTok(2).toString());
623 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
624 // then we are in an object lit.. -> we need to flag the brace as such...
626 isObjectLitAr.push(true);
627 //print(">>>>> EXP PUSH(true)");
631 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
632 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
634 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
637 //print(this.ts.lookTok(0).data);
638 if (this.ts.lookTok(0).data == ".") {
643 if (this.mode == 'PASS2_SYMBOL_TREE') {
645 identifier = this.getIdentifier(symbol, currentScope);
646 //println("<B>??</B>");
647 if (identifier == false) {
649 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
650 // Here, we found an undeclared and un-namespaced symbol that is
651 // 3 characters or less in length. Declare it in the global scope.
652 // We don't need to declare longer symbols since they won't cause
653 // any conflict with other munged symbols.
654 this.globalScope.declareIdentifier(symbol, token);
655 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
657 //println("undeclared")
662 //println("<B>++</B>");
663 token.identifier = identifier;
664 identifier.refcount++;
673 //println("<B>EID</B>");
676 if (token.name == "FUNCTION") {
678 this.parseFunctionDeclaration();
685 if (this.mode == 'BUILDING_SYMBOL_TREE') {
687 if (symbol == "eval") {
688 if (this.ts.look(-1).type == 'COMM') {
689 // look for eval:var:noreplace\n
691 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
692 var hi = _t.getIdentifier(a, currentScope);
693 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
695 // println("PROTECT "+a+" from munge");
703 this.protectScopeFromObfuscation(currentScope);
704 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
713 if (!this.ts.nextTok()) break;
715 print(scopeIndent + "<< EXIT EXPRESSION");
719 parseCatch : function() {
726 //token = getToken(-1);
727 //assert token.getType() == Token.CATCH;
728 token = this.ts.nextTok();
729 //assert token.getType() == Token.LP; (
730 token = this.ts.nextTok();
731 //assert token.getType() == Token.NAME;
734 currentScope = this.scopes[this.scopes.length-1];
736 if (this.mode == 'BUILDING_SYMBOL_TREE') {
737 // We must declare the exception identifier in the containing function
738 // scope to avoid errors related to the obfuscation process. No need to
739 // display a warning if the symbol was already declared here...
740 currentScope.declareIdentifier(symbol, token);
742 //?? why inc the refcount?? - that should be set when building the tree???
743 identifier = this.getIdentifier(symbol, currentScope);
744 identifier.refcount++;
747 token = this.ts.nextTok();
748 //assert token.getType() == Token.RP; // )
751 parseFunctionDeclaration : function()
753 // print("PARSE FUNCTION");
756 var currentScope = false;
759 //this.logR("<B>PARSING FUNCTION</B>");
760 currentScope = this.scopes[this.scopes.length-1];
762 token = this.ts.nextTok();
763 if (token.type == "NAME") {
764 if (this.mode == 'BUILDING_SYMBOL_TREE') {
765 // Get the name of the function and declare it in the current scope.
767 if (currentScope.getIdentifier(symbol) != false) {
768 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
770 currentScope.declareIdentifier(symbol,token);
772 token = this.ts.nextTok();
775 //assert token.getType() == Token.LP;
776 if (this.mode == 'BUILDING_SYMBOL_TREE') {
777 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
779 //println("STORING SCOPE" + this.ts.cursor);
781 this.indexedScopes[this.ts.cursor] = fnScope;
784 //qln("FETCHING SCOPE" + this.ts.cursor);
785 fnScope = this.indexedScopes[this.ts.cursor];
789 // Parse function arguments.
791 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
792 token = this.ts.nextTok();
793 // print ("FUNC ARGS: " + token.toString())
794 //assert token.getType() == Token.NAME ||
795 // token.getType() == Token.COMMA;
796 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
798 identifier = fnScope.declareIdentifier(symbol,token);
799 if (symbol == "$super" && argpos == 0) {
800 // Exception for Prototype 1.6...
801 identifier.preventMunging();
807 token = this.ts.nextTok();
808 // assert token.getType() == Token.LC;
811 token = this.ts.nextTok();
812 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
815 NOT SUPPORTED YET!?!!?!
817 // This is a hint. Hints are empty statements that look like
818 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
819 // to prevent specific symbols from getting obfuscated (some heretic
820 // implementations, such as Prototype 1.6, require specific variable
821 // names, such as $super for example, in order to work appropriately.
822 // Note: right now, only "nomunge" is supported in the right hand side
823 // of a hint. However, in the future, the right hand side may contain
826 String hints = token.getValue();
827 // Remove the leading and trailing quotes...
828 hints = hints.substring(1, hints.length() - 1).trim();
829 StringTokenizer st1 = new StringTokenizer(hints, ",");
830 while (st1.hasMoreTokens()) {
831 String hint = st1.nextToken();
832 int idx = hint.indexOf(':');
833 if (idx <= 0 || idx >= hint.length() - 1) {
834 if (mode == BUILDING_SYMBOL_TREE) {
835 // No need to report the error twice, hence the test...
836 this.warn("Invalid hint syntax: " + hint, true);
840 String variableName = hint.substring(0, idx).trim();
841 String variableType = hint.substring(idx + 1).trim();
842 if (mode == BUILDING_SYMBOL_TREE) {
843 fnScope.addHint(variableName, variableType);
844 } else if (mode == CHECKING_SYMBOL_TREE) {
845 identifier = fnScope.getIdentifier(variableName);
846 if (identifier != null) {
847 if (variableType.equals("nomunge")) {
848 identifier.preventMunging();
850 this.warn("Unsupported hint value: " + hint, true);
853 this.warn("Hint refers to an unknown identifier: " + hint, true);
860 this.parseScope(fnScope);
861 // now pop it off the stack!!!
867 protectScopeFromObfuscation : function(scope) {
868 //assert scope != null;
870 if (scope == this.globalScope) {
871 // The global scope does not get obfuscated,
872 // so we don't need to worry about it...
876 // Find the highest local scope containing the specified scope.
877 while (scope && scope.parent != this.globalScope) {
878 scope = scope.parent;
881 //assert scope.getParentScope() == globalScope;
882 scope.preventMunging();
885 getIdentifier: function(symbol, scope) {
887 while (scope != false) {
888 identifier = scope.getIdentifier(symbol);
889 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
893 scope = scope.parent;