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 mungeSymboltree : function()
143 // One problem with obfuscation resides in the use of undeclared
144 // and un-namespaced global symbols that are 3 characters or less
145 // in length. Here is an example:
147 // var declaredGlobalVar;
149 // function declaredGlobalFn() {
151 // localvar = abc; // abc is an undeclared global symbol
154 // In the example above, there is a slim chance that localvar may be
155 // munged to 'abc', conflicting with the undeclared global symbol
156 // abc, creating a potential bug. The following code detects such
157 // global symbols. This must be done AFTER the entire file has been
158 // parsed, and BEFORE munging the symbol tree. Note that declaring
159 // extra symbols in the global scope won't hurt.
161 // Note: Since we go through all the tokens to do this, we also use
162 // the opportunity to count how many times each identifier is used.
165 this.braceNesting = 0;
167 this.mode = 'PASS2_SYMBOL_TREE';
169 //println("MUNGING?");
171 this.parseScope(this.globalScope);
172 this.globalScope.munge();
178 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
182 //println("<B>LOG:</B>" + str + "<BR/>");
190 parseScope : function(scope) // parse a token stream..
192 //this.timerPrint("parseScope EnterScope");
193 print(">>> ENTER SCOPE" + this.scopes.length);
199 var expressionBraceNesting = this.braceNesting;
200 var bracketNesting = 0;
201 var parensNesting = 0;
203 var isObjectLitAr = [ false ];
205 this.scopes.push(scope);
206 token = this.ts.lookTok(1);
208 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
210 !this.debug|| print(token.type + '.' + token.name+ ":" + token.data);
211 switch(token.type + '.' + token.name) {
213 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
215 //this.log("parseScope GOT VAR/CONST : " + token.toString());
217 token = this.ts.nextTok();
218 !this.debug|| print( token.toString());
220 if (!token) { // can return false at EOF!
223 if (token.name == "VAR") { // kludge..
226 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
227 if (token.type !="NAME") {
228 print(token.toString());
229 print( "var without ident");
234 if (this.mode == "BUILDING_SYMBOL_TREE") {
235 identifier = scope.getIdentifier(token.data) ;
237 if (identifier == false) {
238 scope.declareIdentifier(token.data, token);
240 token.identifier = identifier;
241 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
245 token = this.ts.nextTok();
246 !this.debug|| print(token.toString());
248 assert token.getType() == Token.SEMI ||
249 token.getType() == Token.ASSIGN ||
250 token.getType() == Token.COMMA ||
251 token.getType() == Token.IN;
253 if (token.name == "IN") {
256 this.parseExpression();
257 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
259 token = this.ts.lookTok(1);
260 !this.debug|| print("AFTER EXP: " + token.toString());
261 if (token.data == ';') {
267 case "KEYW.FUNCTION":
268 //println("<i>"+token.data+"</i>");
269 this.parseFunctionDeclaration();
272 case "PUNC.LEFT_CURLY": // {
273 //println("<i>"+token.data+"</i>");
274 isObjectLitAr.push(false);
275 print(">>>>>> OBJLIT PUSH(false)");
279 case "PUNC.RIGHT_CURLY": // }
280 //println("<i>"+token.data+"</i>");
283 print(">>>>>> OBJLIT POP(false)");
284 //assert braceNesting >= scope.getBraceNesting();
285 print("compare BN : "+ this.braceNesting +" ?=" + scope.braceNesting);
286 if (this.braceNesting == scope.braceNesting) {
287 var ls = this.scopes.pop();
289 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
295 //println("<i>"+token.data+"</i>");
296 if (this.mode == "BUILDING_SYMBOL_TREE") {
297 // Inside a 'with' block, it is impossible to figure out
298 // statically whether a symbol is a local variable or an
299 // object member. As a consequence, the only thing we can
300 // do is turn the obfuscation off for the highest scope
301 // containing the 'with' block.
302 this.protectScopeFromObfuscation(scope);
303 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
308 //println("<i>"+token.data+"</i>");
312 case Token.SPECIALCOMMENT:
313 if (mode == BUILDING_SYMBOL_TREE) {
314 protectScopeFromObfuscation(scope);
315 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
320 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
321 case "STRN.SINGLE_QUOTE":
322 //println("<i>"+token.data+"</i>");
323 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
324 // then we are in an object lit.. -> we need to flag the brace as such...
326 isObjectLitAr.push(true);
327 print(">>>>>> OBJLIT PUSH(true)");
329 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
331 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
332 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
333 // see if we can replace..
334 // remove the quotes..
335 // should do a bit more checking!!!! (what about wierd char's in the string..
336 var str = token.data.substring(1,token.data.length-1);
337 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
351 //print("DEAL WITH NAME:");
354 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
355 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
357 isObjectLitAr.push(true);
358 print(">>>>>> OBJLIT PUSH(true)");
359 //println("<i>"+token.data+"</i>");
362 // print("DEAL WITH obj lit:");
363 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
365 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
366 // skip, it's an object lit key..
367 //println("<i>"+token.data+"</i>");
372 // skip anyting with "." before it..!!
374 if (this.ts.lookTok(-1).data == ".") {
375 // skip, it's an object prop.
376 //println("<i>"+token.data+"</i>");
380 if (this.mode == 'PASS2_SYMBOL_TREE') {
382 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
384 //print ("MUNGE?" + symbol);
386 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
388 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
389 identifier = this.getIdentifier(symbol, scope);
391 if (identifier == false) {
392 // BUG!find out where builtin is defined...
393 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
394 // Here, we found an undeclared and un-namespaced symbol that is
395 // 3 characters or less in length. Declare it in the global scope.
396 // We don't need to declare longer symbols since they won't cause
397 // any conflict with other munged symbols.
398 this.globalScope.declareIdentifier(symbol, token);
399 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
402 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
404 token.identifier = identifier;
405 identifier.refcount++;
410 //println("<B>SID</B>");
412 if (token.type != 'KEYW') {
415 // print("Check eval:");
419 if (this.mode == 'BUILDING_SYMBOL_TREE') {
421 if (symbol == "eval") {
422 // look back one and see if we can find a comment!!!
423 if (this.ts.look(-1).type == "COMM") {
424 // look for eval:var:noreplace\n
426 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
428 var hi = _t.getIdentifier(a, scope);
429 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
431 // println("PROTECT "+a+" from munge");
441 this.protectScopeFromObfuscation(scope);
442 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);
454 //this.timerPrint("parseScope TOK : " + token.toString());
455 token = this.ts.nextTok();
456 //if (this.ts.nextT()) break;
459 print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
463 parseExpression : function() {
465 // Parse the expression until we encounter a comma or a semi-colon
466 // in the same brace nesting, bracket nesting and paren nesting.
467 // Parse functions if any...
468 //println("<i>EXP</i><BR/>");
469 !this.debug || print("PARSE EXPR");
475 var expressionBraceNesting = this.braceNesting;
476 var bracketNesting = 0;
477 var parensNesting = 0;
479 var isObjectLitAr = [ false ];
480 while (token = this.ts.lookTok()) {
484 currentScope = this.scopes[this.scopes.length-1];
486 //println("<i>"+token.data+"</i>");
487 !this.debug|| print ("EXP" + token.toString());
488 switch (token.type) {
494 if (this.braceNesting == expressionBraceNesting &&
495 bracketNesting == 0 &&
496 parensNesting == 0) {
504 case '{': //Token.LC:
505 isObjectLitAr.push(false);
506 print(">>>>> OBJ PUSH(false)");
510 case '}': //Token.RC:
513 print(">>>>> OBJ POP");
514 // assert braceNesting >= expressionBraceNesting;
517 case '[': //Token.LB:
521 case ']': //Token.RB:
525 case '(': //Token.LP:
529 case ')': //Token.RP:
535 case 'STRN': // used for object lit detection..
536 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
537 // then we are in an object lit.. -> we need to flag the brace as such...
539 isObjectLitAr.push(true);
540 print(">>>>> OBJ PUSH(true)");
545 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
546 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
547 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
548 // see if we can replace..
549 // remove the quotes..
550 var str = token.data.substring(1,token.data.length-1);
551 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
566 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
567 // then we are in an object lit.. -> we need to flag the brace as such...
569 isObjectLitAr.push(true);
570 print(">>>>> OBJ PUSH(true)");
573 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
574 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
578 if (this.ts.lookTok(-1).data == ".") {
583 if (this.mode == 'PASS2_SYMBOL_TREE') {
585 identifier = this.getIdentifier(symbol, currentScope);
586 //println("<B>??</B>");
587 if (identifier == false) {
589 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
590 // Here, we found an undeclared and un-namespaced symbol that is
591 // 3 characters or less in length. Declare it in the global scope.
592 // We don't need to declare longer symbols since they won't cause
593 // any conflict with other munged symbols.
594 this.globalScope.declareIdentifier(symbol, token);
595 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
597 //println("undeclared")
602 //println("<B>++</B>");
603 token.identifier = identifier;
604 identifier.refcount++;
613 //println("<B>EID</B>");
616 if (token.name == "FUNCTION") {
618 this.parseFunctionDeclaration();
625 if (this.mode == 'BUILDING_SYMBOL_TREE') {
627 if (symbol == "eval") {
628 if (this.ts.look(-1).type == 'COMM') {
629 // look for eval:var:noreplace\n
631 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
632 var hi = _t.getIdentifier(a, currentScope);
633 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
635 // println("PROTECT "+a+" from munge");
643 this.protectScopeFromObfuscation(currentScope);
644 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
653 if (!this.ts.nextTok()) break;
658 parseCatch : function() {
665 //token = getToken(-1);
666 //assert token.getType() == Token.CATCH;
667 token = this.ts.nextTok();
668 //assert token.getType() == Token.LP; (
669 token = this.ts.nextTok();
670 //assert token.getType() == Token.NAME;
673 currentScope = this.scopes[this.scopes.length-1];
675 if (this.mode == 'BUILDING_SYMBOL_TREE') {
676 // We must declare the exception identifier in the containing function
677 // scope to avoid errors related to the obfuscation process. No need to
678 // display a warning if the symbol was already declared here...
679 currentScope.declareIdentifier(symbol, token);
681 //?? why inc the refcount?? - that should be set when building the tree???
682 identifier = this.getIdentifier(symbol, currentScope);
683 identifier.refcount++;
686 token = this.ts.nextTok();
687 //assert token.getType() == Token.RP; // )
690 parseFunctionDeclaration : function()
692 // print("PARSE FUNCTION");
695 var currentScope = false;
698 //this.logR("<B>PARSING FUNCTION</B>");
699 currentScope = this.scopes[this.scopes.length-1];
701 token = this.ts.nextTok();
702 if (token.type == "NAME") {
703 if (this.mode == 'BUILDING_SYMBOL_TREE') {
704 // Get the name of the function and declare it in the current scope.
706 if (currentScope.getIdentifier(symbol) != false) {
707 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
709 currentScope.declareIdentifier(symbol,token);
711 token = this.ts.nextTok();
714 //assert token.getType() == Token.LP;
715 if (this.mode == 'BUILDING_SYMBOL_TREE') {
716 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
718 //println("STORING SCOPE" + this.ts.cursor);
720 this.indexedScopes[this.ts.cursor] = fnScope;
723 //println("FETCHING SCOPE" + this.ts.cursor);
724 fnScope = this.indexedScopes[this.ts.cursor];
728 // Parse function arguments.
730 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
731 token = this.ts.nextTok();
732 // print ("FUNC ARGS: " + token.toString())
733 //assert token.getType() == Token.NAME ||
734 // token.getType() == Token.COMMA;
735 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
737 identifier = fnScope.declareIdentifier(symbol,token);
738 if (symbol == "$super" && argpos == 0) {
739 // Exception for Prototype 1.6...
740 identifier.preventMunging();
746 token = this.ts.nextTok();
747 // assert token.getType() == Token.LC;
750 token = this.ts.nextTok();
751 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
754 NOT SUPPORTED YET!?!!?!
756 // This is a hint. Hints are empty statements that look like
757 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
758 // to prevent specific symbols from getting obfuscated (some heretic
759 // implementations, such as Prototype 1.6, require specific variable
760 // names, such as $super for example, in order to work appropriately.
761 // Note: right now, only "nomunge" is supported in the right hand side
762 // of a hint. However, in the future, the right hand side may contain
765 String hints = token.getValue();
766 // Remove the leading and trailing quotes...
767 hints = hints.substring(1, hints.length() - 1).trim();
768 StringTokenizer st1 = new StringTokenizer(hints, ",");
769 while (st1.hasMoreTokens()) {
770 String hint = st1.nextToken();
771 int idx = hint.indexOf(':');
772 if (idx <= 0 || idx >= hint.length() - 1) {
773 if (mode == BUILDING_SYMBOL_TREE) {
774 // No need to report the error twice, hence the test...
775 this.warn("Invalid hint syntax: " + hint, true);
779 String variableName = hint.substring(0, idx).trim();
780 String variableType = hint.substring(idx + 1).trim();
781 if (mode == BUILDING_SYMBOL_TREE) {
782 fnScope.addHint(variableName, variableType);
783 } else if (mode == CHECKING_SYMBOL_TREE) {
784 identifier = fnScope.getIdentifier(variableName);
785 if (identifier != null) {
786 if (variableType.equals("nomunge")) {
787 identifier.preventMunging();
789 this.warn("Unsupported hint value: " + hint, true);
792 this.warn("Hint refers to an unknown identifier: " + hint, true);
799 this.parseScope(fnScope);
800 // now pop it off the stack!!!
806 protectScopeFromObfuscation : function(scope) {
807 //assert scope != null;
809 if (scope == this.globalScope) {
810 // The global scope does not get obfuscated,
811 // so we don't need to worry about it...
815 // Find the highest local scope containing the specified scope.
816 while (scope && scope.parent != this.globalScope) {
817 scope = scope.parent;
820 //assert scope.getParentScope() == globalScope;
821 scope.preventMunging();
824 getIdentifier: function(symbol, scope) {
826 while (scope != false) {
827 identifier = scope.getIdentifier(symbol);
828 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
832 scope = scope.parent;