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 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
185 //println("<B>LOG:</B>" + str + "<BR/>");
193 parseScope : function(scope) // parse a token stream..
195 //this.timerPrint("parseScope EnterScope");
196 print(">>> ENTER SCOPE" + this.scopes.length);
202 var expressionBraceNesting = this.braceNesting;
204 var parensNesting = 0;
206 var isObjectLitAr = [ false ];
208 this.scopes.push(scope);
209 token = this.ts.lookTok(1);
211 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
213 !this.debug|| print(token.type + '.' + token.name+ ":" + token.data);
214 switch(token.type + '.' + token.name) {
216 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
218 //this.log("parseScope GOT VAR/CONST : " + token.toString());
220 token = this.ts.nextTok();
221 !this.debug|| print( token.toString());
223 if (!token) { // can return false at EOF!
226 if (token.name == "VAR") { // kludge..
229 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
230 if (token.type !="NAME") {
231 print(token.toString());
232 print( "var without ident");
237 if (this.mode == "BUILDING_SYMBOL_TREE") {
238 identifier = scope.getIdentifier(token.data) ;
240 if (identifier == false) {
241 scope.declareIdentifier(token.data, token);
243 token.identifier = identifier;
244 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
248 token = this.ts.nextTok();
249 !this.debug|| print(token.toString());
251 assert token.getType() == Token.SEMI ||
252 token.getType() == Token.ASSIGN ||
253 token.getType() == Token.COMMA ||
254 token.getType() == Token.IN;
256 if (token.name == "IN") {
259 var bn = this.braceNesting;
260 this.parseExpression();
261 this.braceNesting = bn;
262 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
264 token = this.ts.lookTok(1);
265 !this.debug|| print("AFTER EXP: " + token.toString());
266 if (token.data == ';') {
272 case "KEYW.FUNCTION":
273 //println("<i>"+token.data+"</i>");
274 var bn = this.braceNesting;
275 this.parseFunctionDeclaration();
276 this.braceNesting = bn;
279 case "PUNC.LEFT_CURLY": // {
280 //println("<i>"+token.data+"</i>");
281 isObjectLitAr.push(false);
284 print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
287 case "PUNC.RIGHT_CURLY": // }
288 //println("<i>"+token.data+"</i>");
291 print(">>>>>> OBJLIT POP"+ this.braceNesting);
292 //assert braceNesting >= scope.getBra ceNesting();
294 if (this.braceNesting < 0) {
295 var ls = this.scopes.pop();
297 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
303 //println("<i>"+token.data+"</i>");
304 if (this.mode == "BUILDING_SYMBOL_TREE") {
305 // Inside a 'with' block, it is impossible to figure out
306 // statically whether a symbol is a local variable or an
307 // object member. As a consequence, the only thing we can
308 // do is turn the obfuscation off for the highest scope
309 // containing the 'with' block.
310 this.protectScopeFromObfuscation(scope);
311 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
316 //println("<i>"+token.data+"</i>");
320 case Token.SPECIALCOMMENT:
321 if (mode == BUILDING_SYMBOL_TREE) {
322 protectScopeFromObfuscation(scope);
323 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
328 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
329 case "STRN.SINGLE_QUOTE":
330 //println("<i>"+token.data+"</i>");
331 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
332 // then we are in an object lit.. -> we need to flag the brace as such...
334 isObjectLitAr.push(true);
335 print(">>>>>> OBJLIT REPUSH(true)");
337 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
339 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
340 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
341 // see if we can replace..
342 // remove the quotes..
343 // should do a bit more checking!!!! (what about wierd char's in the string..
344 var str = token.data.substring(1,token.data.length-1);
345 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
359 //print("DEAL WITH NAME:");
362 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
363 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
365 isObjectLitAr.push(true);
366 print(">>>>>> OBJLIT REPUSH(true)");
367 //println("<i>"+token.data+"</i>");
370 // print("DEAL WITH obj lit:");
371 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
373 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
374 // skip, it's an object lit key..
375 //println("<i>"+token.data+"</i>");
380 // skip anyting with "." before it..!!
382 if (this.ts.lookTok(-1).data == ".") {
383 // skip, it's an object prop.
384 //println("<i>"+token.data+"</i>");
388 if (this.mode == 'PASS2_SYMBOL_TREE') {
390 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
392 //print ("MUNGE?" + symbol);
394 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
396 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
397 identifier = this.getIdentifier(symbol, scope);
399 if (identifier == false) {
400 // BUG!find out where builtin is defined...
401 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
402 // Here, we found an undeclared and un-namespaced symbol that is
403 // 3 characters or less in length. Declare it in the global scope.
404 // We don't need to declare longer symbols since they won't cause
405 // any conflict with other munged symbols.
406 this.globalScope.declareIdentifier(symbol, token);
407 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
410 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
412 token.identifier = identifier;
413 identifier.refcount++;
418 //println("<B>SID</B>");
420 if (token.type != 'KEYW') {
423 // print("Check eval:");
427 if (this.mode == 'BUILDING_SYMBOL_TREE') {
429 if (symbol == "eval") {
430 // look back one and see if we can find a comment!!!
431 if (this.ts.look(-1).type == "COMM") {
432 // look for eval:var:noreplace\n
434 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
436 var hi = _t.getIdentifier(a, scope);
437 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
439 // println("PROTECT "+a+" from munge");
449 this.protectScopeFromObfuscation(scope);
450 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);
462 //this.timerPrint("parseScope TOK : " + token.toString());
463 token = this.ts.nextTok();
464 //if (this.ts.nextT()) break;
467 print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
471 parseExpression : function() {
473 // Parse the expression until we encounter a comma or a semi-colon
474 // in the same brace nesting, bracket nesting and paren nesting.
475 // Parse functions if any...
476 //println("<i>EXP</i><BR/>");
477 !this.debug || print("PARSE EXPR");
483 var expressionBraceNesting = this.braceNesting;
484 var bracketNesting = 0;
485 var parensNesting = 0;
487 var isObjectLitAr = [ false ];
488 while (token = this.ts.lookTok()) {
492 currentScope = this.scopes[this.scopes.length-1];
494 //println("<i>"+token.data+"</i>");
495 !this.debug|| print ("EXP" + token.toString());
496 switch (token.type) {
502 if (this.braceNesting == expressionBraceNesting &&
503 bracketNesting == 0 &&
504 parensNesting == 0) {
512 case '{': //Token.LC:
513 isObjectLitAr.push(false);
516 print(">>>>> EXP PUSH(false)"+this.braceNesting);
519 case '}': //Token.RC:
522 print(">>>>> EXP POP" + this.braceNesting);
523 // assert braceNesting >= expressionBraceNesting;
526 case '[': //Token.LB:
530 case ']': //Token.RB:
534 case '(': //Token.LP:
538 case ')': //Token.RP:
544 case 'STRN': // used for object lit detection..
545 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
546 // then we are in an object lit.. -> we need to flag the brace as such...
548 isObjectLitAr.push(true);
549 print(">>>>> EXP PUSH(true)");
554 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
555 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
556 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
557 // see if we can replace..
558 // remove the quotes..
559 var str = token.data.substring(1,token.data.length-1);
560 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
575 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
576 // then we are in an object lit.. -> we need to flag the brace as such...
578 isObjectLitAr.push(true);
579 print(">>>>> EXP PUSH(true)");
582 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
583 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
587 if (this.ts.lookTok(-1).data == ".") {
592 if (this.mode == 'PASS2_SYMBOL_TREE') {
594 identifier = this.getIdentifier(symbol, currentScope);
595 //println("<B>??</B>");
596 if (identifier == false) {
598 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
599 // Here, we found an undeclared and un-namespaced symbol that is
600 // 3 characters or less in length. Declare it in the global scope.
601 // We don't need to declare longer symbols since they won't cause
602 // any conflict with other munged symbols.
603 this.globalScope.declareIdentifier(symbol, token);
604 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
606 //println("undeclared")
611 //println("<B>++</B>");
612 token.identifier = identifier;
613 identifier.refcount++;
622 //println("<B>EID</B>");
625 if (token.name == "FUNCTION") {
627 this.parseFunctionDeclaration();
634 if (this.mode == 'BUILDING_SYMBOL_TREE') {
636 if (symbol == "eval") {
637 if (this.ts.look(-1).type == 'COMM') {
638 // look for eval:var:noreplace\n
640 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
641 var hi = _t.getIdentifier(a, currentScope);
642 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
644 // println("PROTECT "+a+" from munge");
652 this.protectScopeFromObfuscation(currentScope);
653 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
662 if (!this.ts.nextTok()) break;
667 parseCatch : function() {
674 //token = getToken(-1);
675 //assert token.getType() == Token.CATCH;
676 token = this.ts.nextTok();
677 //assert token.getType() == Token.LP; (
678 token = this.ts.nextTok();
679 //assert token.getType() == Token.NAME;
682 currentScope = this.scopes[this.scopes.length-1];
684 if (this.mode == 'BUILDING_SYMBOL_TREE') {
685 // We must declare the exception identifier in the containing function
686 // scope to avoid errors related to the obfuscation process. No need to
687 // display a warning if the symbol was already declared here...
688 currentScope.declareIdentifier(symbol, token);
690 //?? why inc the refcount?? - that should be set when building the tree???
691 identifier = this.getIdentifier(symbol, currentScope);
692 identifier.refcount++;
695 token = this.ts.nextTok();
696 //assert token.getType() == Token.RP; // )
699 parseFunctionDeclaration : function()
701 // print("PARSE FUNCTION");
704 var currentScope = false;
707 //this.logR("<B>PARSING FUNCTION</B>");
708 currentScope = this.scopes[this.scopes.length-1];
710 token = this.ts.nextTok();
711 if (token.type == "NAME") {
712 if (this.mode == 'BUILDING_SYMBOL_TREE') {
713 // Get the name of the function and declare it in the current scope.
715 if (currentScope.getIdentifier(symbol) != false) {
716 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
718 currentScope.declareIdentifier(symbol,token);
720 token = this.ts.nextTok();
723 //assert token.getType() == Token.LP;
724 if (this.mode == 'BUILDING_SYMBOL_TREE') {
725 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
727 //println("STORING SCOPE" + this.ts.cursor);
729 this.indexedScopes[this.ts.cursor] = fnScope;
732 //println("FETCHING SCOPE" + this.ts.cursor);
733 fnScope = this.indexedScopes[this.ts.cursor];
737 // Parse function arguments.
739 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
740 token = this.ts.nextTok();
741 // print ("FUNC ARGS: " + token.toString())
742 //assert token.getType() == Token.NAME ||
743 // token.getType() == Token.COMMA;
744 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
746 identifier = fnScope.declareIdentifier(symbol,token);
747 if (symbol == "$super" && argpos == 0) {
748 // Exception for Prototype 1.6...
749 identifier.preventMunging();
755 token = this.ts.nextTok();
756 // assert token.getType() == Token.LC;
759 token = this.ts.nextTok();
760 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
763 NOT SUPPORTED YET!?!!?!
765 // This is a hint. Hints are empty statements that look like
766 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
767 // to prevent specific symbols from getting obfuscated (some heretic
768 // implementations, such as Prototype 1.6, require specific variable
769 // names, such as $super for example, in order to work appropriately.
770 // Note: right now, only "nomunge" is supported in the right hand side
771 // of a hint. However, in the future, the right hand side may contain
774 String hints = token.getValue();
775 // Remove the leading and trailing quotes...
776 hints = hints.substring(1, hints.length() - 1).trim();
777 StringTokenizer st1 = new StringTokenizer(hints, ",");
778 while (st1.hasMoreTokens()) {
779 String hint = st1.nextToken();
780 int idx = hint.indexOf(':');
781 if (idx <= 0 || idx >= hint.length() - 1) {
782 if (mode == BUILDING_SYMBOL_TREE) {
783 // No need to report the error twice, hence the test...
784 this.warn("Invalid hint syntax: " + hint, true);
788 String variableName = hint.substring(0, idx).trim();
789 String variableType = hint.substring(idx + 1).trim();
790 if (mode == BUILDING_SYMBOL_TREE) {
791 fnScope.addHint(variableName, variableType);
792 } else if (mode == CHECKING_SYMBOL_TREE) {
793 identifier = fnScope.getIdentifier(variableName);
794 if (identifier != null) {
795 if (variableType.equals("nomunge")) {
796 identifier.preventMunging();
798 this.warn("Unsupported hint value: " + hint, true);
801 this.warn("Hint refers to an unknown identifier: " + hint, true);
808 this.parseScope(fnScope);
809 // now pop it off the stack!!!
815 protectScopeFromObfuscation : function(scope) {
816 //assert scope != null;
818 if (scope == this.globalScope) {
819 // The global scope does not get obfuscated,
820 // so we don't need to worry about it...
824 // Find the highest local scope containing the specified scope.
825 while (scope && scope.parent != this.globalScope) {
826 scope = scope.parent;
829 //assert scope.getParentScope() == globalScope;
830 scope.preventMunging();
833 getIdentifier: function(symbol, scope) {
835 while (scope != false) {
836 identifier = scope.getIdentifier(symbol);
837 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
841 scope = scope.parent;