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 !this.debug || 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");
198 var expressionBraceNesting = this.braceNesting;
199 var bracketNesting = 0;
200 var parensNesting = 0;
202 var isObjectLitAr = [ false ];
204 this.scopes.push(scope);
205 token = this.ts.lookTok(1);
207 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
209 !this.debug|| print(token.type + '.' + token.name+ ":" + token.data);
210 switch(token.type + '.' + token.name) {
212 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
214 //this.log("parseScope GOT VAR/CONST : " + token.toString());
216 token = this.ts.nextTok();
217 !this.debug|| print( token.toString());
219 if (!token) { // can return false at EOF!
222 if (token.name == "VAR") { // kludge..
225 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
226 if (token.type !="NAME") {
227 print(token.toString());
228 print( "var without ident");
233 if (this.mode == "BUILDING_SYMBOL_TREE") {
234 identifier = scope.getIdentifier(token.data) ;
236 if (identifier == false) {
237 scope.declareIdentifier(token.data, token);
239 token.identifier = identifier;
240 this.warn("The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
244 token = this.ts.nextTok();
245 !this.debug|| print(token.toString());
247 assert token.getType() == Token.SEMI ||
248 token.getType() == Token.ASSIGN ||
249 token.getType() == Token.COMMA ||
250 token.getType() == Token.IN;
252 if (token.name == "IN") {
255 this.parseExpression();
256 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
258 token = this.ts.lookTok(1);
259 !this.debug|| print("AFTER EXP: " + token.toString());
260 if (token.data == ';') {
266 case "KEYW.FUNCTION":
267 //println("<i>"+token.data+"</i>");
268 this.parseFunctionDeclaration();
271 case "KEYW.LEFT_CURLY": // {
272 //println("<i>"+token.data+"</i>");
273 isObjectLitAr.push(false);
277 case "KEYW.RIGHT_CURLY": // }
278 //println("<i>"+token.data+"</i>");
281 //assert braceNesting >= scope.getBraceNesting();
282 if (this.braceNesting == scope.braceN) {
283 var ls = this.scopes.pop();
290 //println("<i>"+token.data+"</i>");
291 if (this.mode == "BUILDING_SYMBOL_TREE") {
292 // Inside a 'with' block, it is impossible to figure out
293 // statically whether a symbol is a local variable or an
294 // object member. As a consequence, the only thing we can
295 // do is turn the obfuscation off for the highest scope
296 // containing the 'with' block.
297 this.protectScopeFromObfuscation(scope);
298 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
303 //println("<i>"+token.data+"</i>");
307 case Token.SPECIALCOMMENT:
308 if (mode == BUILDING_SYMBOL_TREE) {
309 protectScopeFromObfuscation(scope);
310 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
315 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
316 case "STRN.SINGLE_QUOTE":
317 //println("<i>"+token.data+"</i>");
318 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
319 // then we are in an object lit.. -> we need to flag the brace as such...
321 isObjectLitAr.push(true);
323 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
325 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
326 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
327 // see if we can replace..
328 // remove the quotes..
329 // should do a bit more checking!!!! (what about wierd char's in the string..
330 var str = token.data.substring(1,token.data.length-1);
331 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
345 //print("DEAL WITH NAME:");
348 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
349 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
351 isObjectLitAr.push(true);
352 //println("<i>"+token.data+"</i>");
355 // print("DEAL WITH obj lit:");
356 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
358 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
359 // skip, it's an object lit key..
360 //println("<i>"+token.data+"</i>");
365 // skip anyting with "." before it..!!
367 if (this.ts.lookTok(-1).data == ".") {
368 // skip, it's an object prop.
369 //println("<i>"+token.data+"</i>");
373 if (this.mode == 'PASS2_SYMBOL_TREE') {
375 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
377 //print ("MUNGE?" + symbol);
379 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
381 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
382 identifier = this.getIdentifier(symbol, scope);
384 if (identifier == false) {
385 // BUG!find out where builtin is defined...
386 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
387 // Here, we found an undeclared and un-namespaced symbol that is
388 // 3 characters or less in length. Declare it in the global scope.
389 // We don't need to declare longer symbols since they won't cause
390 // any conflict with other munged symbols.
391 this.globalScope.declareIdentifier(symbol, token);
392 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
395 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
397 token.identifier = identifier;
398 identifier.refcount++;
403 //println("<B>SID</B>");
405 if (token.type != 'KEYW') {
408 // print("Check eval:");
412 if (this.mode == 'BUILDING_SYMBOL_TREE') {
414 if (symbol == "eval") {
415 // look back one and see if we can find a comment!!!
416 if (this.ts.look(-1).type == "COMM") {
417 // look for eval:var:noreplace\n
419 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
421 var hi = _t.getIdentifier(a, scope);
422 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
424 // println("PROTECT "+a+" from munge");
434 this.protectScopeFromObfuscation(scope);
435 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);
447 //this.timerPrint("parseScope TOK : " + token.toString());
448 token = this.ts.nextTok();
449 //if (this.ts.nextT()) break;
455 parseExpression : function() {
457 // Parse the expression until we encounter a comma or a semi-colon
458 // in the same brace nesting, bracket nesting and paren nesting.
459 // Parse functions if any...
460 //println("<i>EXP</i><BR/>");
461 !this.debug || print("PARSE EXPR");
467 var expressionBraceNesting = this.braceNesting;
468 var bracketNesting = 0;
469 var parensNesting = 0;
471 var isObjectLitAr = [ false ];
472 while (token = this.ts.lookTok()) {
476 currentScope = this.scopes[this.scopes.length-1];
478 //println("<i>"+token.data+"</i>");
479 !this.debug|| print ("EXP" + token.toString());
480 switch (token.type) {
486 if (this.braceNesting == expressionBraceNesting &&
487 bracketNesting == 0 &&
488 parensNesting == 0) {
496 case '{': //Token.LC:
497 isObjectLitAr.push(false);
502 case '}': //Token.RC:
506 // assert braceNesting >= expressionBraceNesting;
509 case '[': //Token.LB:
513 case ']': //Token.RB:
517 case '(': //Token.LP:
521 case ')': //Token.RP:
527 case 'STRN': // used for object lit detection..
528 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
529 // then we are in an object lit.. -> we need to flag the brace as such...
531 isObjectLitAr.push(true);
536 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
537 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
538 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
539 // see if we can replace..
540 // remove the quotes..
541 var str = token.data.substring(1,token.data.length-1);
542 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
557 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
558 // then we are in an object lit.. -> we need to flag the brace as such...
560 isObjectLitAr.push(true);
563 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
564 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
568 if (this.ts.lookTok(-1).data == ".") {
573 if (this.mode == 'PASS2_SYMBOL_TREE') {
575 identifier = this.getIdentifier(symbol, currentScope);
576 //println("<B>??</B>");
577 if (identifier == false) {
579 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
580 // Here, we found an undeclared and un-namespaced symbol that is
581 // 3 characters or less in length. Declare it in the global scope.
582 // We don't need to declare longer symbols since they won't cause
583 // any conflict with other munged symbols.
584 this.globalScope.declareIdentifier(symbol, token);
585 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
587 //println("undeclared")
592 //println("<B>++</B>");
593 token.identifier = identifier;
594 identifier.refcount++;
603 //println("<B>EID</B>");
606 if (token.name == "FUNCTION") {
608 this.parseFunctionDeclaration();
615 if (this.mode == 'BUILDING_SYMBOL_TREE') {
617 if (symbol == "eval") {
618 if (this.ts.look(-1).type == 'COMM') {
619 // look for eval:var:noreplace\n
621 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
622 var hi = _t.getIdentifier(a, currentScope);
623 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
625 // println("PROTECT "+a+" from munge");
633 this.protectScopeFromObfuscation(currentScope);
634 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
643 if (!this.ts.nextTok()) break;
648 parseCatch : function() {
655 //token = getToken(-1);
656 //assert token.getType() == Token.CATCH;
657 token = this.ts.nextTok();
658 //assert token.getType() == Token.LP; (
659 token = this.ts.nextTok();
660 //assert token.getType() == Token.NAME;
663 currentScope = this.scopes[this.scopes.length-1];
665 if (this.mode == 'BUILDING_SYMBOL_TREE') {
666 // We must declare the exception identifier in the containing function
667 // scope to avoid errors related to the obfuscation process. No need to
668 // display a warning if the symbol was already declared here...
669 currentScope.declareIdentifier(symbol, token);
671 //?? why inc the refcount?? - that should be set when building the tree???
672 identifier = this.getIdentifier(symbol, currentScope);
673 identifier.refcount++;
676 token = this.ts.nextTok();
677 //assert token.getType() == Token.RP; // )
680 parseFunctionDeclaration : function()
682 // print("PARSE FUNCTION");
685 var currentScope = false;
688 //this.logR("<B>PARSING FUNCTION</B>");
689 currentScope = this.scopes[this.scopes.length-1];
691 token = this.ts.nextTok();
692 if (token.type == "NAME") {
693 if (this.mode == 'BUILDING_SYMBOL_TREE') {
694 // Get the name of the function and declare it in the current scope.
696 if (currentScope.getIdentifier(symbol) != false) {
697 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
699 currentScope.declareIdentifier(symbol,token);
701 token = this.ts.nextTok();
704 //assert token.getType() == Token.LP;
705 if (this.mode == 'BUILDING_SYMBOL_TREE') {
706 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
708 //println("STORING SCOPE" + this.ts.cursor);
710 this.indexedScopes[this.ts.cursor] = fnScope;
713 //println("FETCHING SCOPE" + this.ts.cursor);
714 fnScope = this.indexedScopes[this.ts.cursor];
717 // Parse function arguments.
719 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
720 token = this.ts.nextTok();
721 // print ("FUNC ARGS: " + token.toString())
722 //assert token.getType() == Token.NAME ||
723 // token.getType() == Token.COMMA;
724 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
726 identifier = fnScope.declareIdentifier(symbol,token);
727 if (symbol == "$super" && argpos == 0) {
728 // Exception for Prototype 1.6...
729 identifier.preventMunging();
735 token = this.ts.nextTok();
736 // assert token.getType() == Token.LC;
739 token = this.ts.nextTok();
740 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
743 NOT SUPPORTED YET!?!!?!
745 // This is a hint. Hints are empty statements that look like
746 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
747 // to prevent specific symbols from getting obfuscated (some heretic
748 // implementations, such as Prototype 1.6, require specific variable
749 // names, such as $super for example, in order to work appropriately.
750 // Note: right now, only "nomunge" is supported in the right hand side
751 // of a hint. However, in the future, the right hand side may contain
754 String hints = token.getValue();
755 // Remove the leading and trailing quotes...
756 hints = hints.substring(1, hints.length() - 1).trim();
757 StringTokenizer st1 = new StringTokenizer(hints, ",");
758 while (st1.hasMoreTokens()) {
759 String hint = st1.nextToken();
760 int idx = hint.indexOf(':');
761 if (idx <= 0 || idx >= hint.length() - 1) {
762 if (mode == BUILDING_SYMBOL_TREE) {
763 // No need to report the error twice, hence the test...
764 this.warn("Invalid hint syntax: " + hint, true);
768 String variableName = hint.substring(0, idx).trim();
769 String variableType = hint.substring(idx + 1).trim();
770 if (mode == BUILDING_SYMBOL_TREE) {
771 fnScope.addHint(variableName, variableType);
772 } else if (mode == CHECKING_SYMBOL_TREE) {
773 identifier = fnScope.getIdentifier(variableName);
774 if (identifier != null) {
775 if (variableType.equals("nomunge")) {
776 identifier.preventMunging();
778 this.warn("Unsupported hint value: " + hint, true);
781 this.warn("Hint refers to an unknown identifier: " + hint, true);
788 this.parseScope(fnScope);
789 // now pop it off the stack!!!
795 protectScopeFromObfuscation : function(scope) {
796 //assert scope != null;
798 if (scope == this.globalScope) {
799 // The global scope does not get obfuscated,
800 // so we don't need to worry about it...
804 // Find the highest local scope containing the specified scope.
805 while (scope && scope.parent != this.globalScope) {
806 scope = scope.parent;
809 //assert scope.getParentScope() == globalScope;
810 scope.preventMunging();
813 getIdentifier: function(symbol, scope) {
815 while (scope != false) {
816 identifier = scope.getIdentifier(symbol);
817 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
821 scope = scope.parent;