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);
211 token = this.ts.lookTok(1);
213 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
215 //this.log(token.data);
216 if (token.type == 'NAME') {
217 // print('*' + token.data);
219 switch(token.type + '.' + token.name) {
221 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
223 //this.log("parseScope GOT VAR/CONST : " + token.toString());
225 token = this.ts.nextTok();
226 !this.debug|| print( token.toString());
228 if (!token) { // can return false at EOF!
231 if (token.name == "VAR" || token.data == ',') { // kludge..
234 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
235 if (token.type !="NAME") {
236 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
237 print(this.ts.tokens[i].toString());
240 print( "var without ident");
245 if (this.mode == "BUILDING_SYMBOL_TREE") {
246 identifier = scope.getIdentifier(token.data) ;
248 if (identifier == false) {
249 scope.declareIdentifier(token.data, token);
251 token.identifier = identifier;
252 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
256 token = this.ts.nextTok();
257 !this.debug|| print(token.toString());
259 assert token.getType() == Token.SEMI ||
260 token.getType() == Token.ASSIGN ||
261 token.getType() == Token.COMMA ||
262 token.getType() == Token.IN;
264 if (token.name == "IN") {
267 //var bn = this.braceNesting;
268 this.parseExpression();
269 //this.braceNesting = bn;
270 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
272 token = this.ts.lookTok(1);
273 !this.debug|| print("AFTER EXP: " + token.toString());
274 if (token.data == ';') {
280 case "KEYW.FUNCTION":
281 //println("<i>"+token.data+"</i>");
282 var bn = this.braceNesting;
283 this.parseFunctionDeclaration();
284 this.braceNesting = bn;
287 case "PUNC.LEFT_CURLY": // {
288 //println("<i>"+token.data+"</i>");
289 isObjectLitAr.push(false);
292 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
295 case "PUNC.RIGHT_CURLY": // }
296 //println("<i>"+token.data+"</i>");
299 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
300 //assert braceNesting >= scope.getBra ceNesting();
302 if (this.braceNesting < expressionBraceNesting) {
303 var ls = this.scopes.pop();
305 // eat symbol if we are currently at {
306 if (this.ts.look(0).data == '{') {
310 //print("<<<<<<<EXIT SCOPE" +this.scopes.length);
316 //println("<i>"+token.data+"</i>");
317 if (this.mode == "BUILDING_SYMBOL_TREE") {
318 // Inside a 'with' block, it is impossible to figure out
319 // statically whether a symbol is a local variable or an
320 // object member. As a consequence, the only thing we can
321 // do is turn the obfuscation off for the highest scope
322 // containing the 'with' block.
323 this.protectScopeFromObfuscation(scope);
324 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
329 //println("<i>"+token.data+"</i>");
333 case Token.SPECIALCOMMENT:
334 if (mode == BUILDING_SYMBOL_TREE) {
335 protectScopeFromObfuscation(scope);
336 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
341 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
342 case "STRN.SINGLE_QUOTE":
343 //println("<i>"+token.data+"</i>");
344 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
345 // then we are in an object lit.. -> we need to flag the brace as such...
347 isObjectLitAr.push(true);
348 //print(">>>>>> OBJLIT REPUSH(true)");
350 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
352 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
353 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
354 // see if we can replace..
355 // remove the quotes..
356 // should do a bit more checking!!!! (what about wierd char's in the string..
357 var str = token.data.substring(1,token.data.length-1);
358 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
372 //print("DEAL WITH NAME:");
375 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
376 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
378 isObjectLitAr.push(true);
379 //print(">>>>>> OBJLIT REPUSH(true)");
380 //println("<i>"+token.data+"</i>");
383 // print("DEAL WITH obj lit:");
384 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
386 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
387 // skip, it's an object lit key..
388 //println("<i>"+token.data+"</i>");
393 // skip anyting with "." before it..!!
395 if (this.ts.lookTok(-1).data == ".") {
396 // skip, it's an object prop.
397 //println("<i>"+token.data+"</i>");
401 if (this.mode == 'PASS2_SYMBOL_TREE') {
403 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
405 //print ("MUNGE?" + symbol);
407 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
409 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
410 identifier = this.getIdentifier(symbol, scope);
412 if (identifier == false) {
413 // BUG!find out where builtin is defined...
414 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
415 // Here, we found an undeclared and un-namespaced symbol that is
416 // 3 characters or less in length. Declare it in the global scope.
417 // We don't need to declare longer symbols since they won't cause
418 // any conflict with other munged symbols.
419 this.globalScope.declareIdentifier(symbol, token);
420 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
423 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
425 token.identifier = identifier;
426 identifier.refcount++;
431 //println("<B>SID</B>");
433 if (token.type != 'KEYW') {
436 // print("Check eval:");
440 if (this.mode == 'BUILDING_SYMBOL_TREE') {
442 if (symbol == "eval") {
443 // look back one and see if we can find a comment!!!
444 if (this.ts.look(-1).type == "COMM") {
445 // look for eval:var:noreplace\n
447 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
449 var hi = _t.getIdentifier(a, scope);
450 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
452 // println("PROTECT "+a+" from munge");
462 this.protectScopeFromObfuscation(scope);
463 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);
475 //this.timerPrint("parseScope TOK : " + token.toString());
476 token = this.ts.nextTok();
477 //if (this.ts.nextT()) break;
480 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
484 parseExpression : function() {
486 // Parse the expression until we encounter a comma or a semi-colon
487 // in the same brace nesting, bracket nesting and paren nesting.
488 // Parse functions if any...
489 //println("<i>EXP</i><BR/>");
490 !this.debug || print("PARSE EXPR");
496 var expressionBraceNesting = this.braceNesting;
497 var bracketNesting = 0;
498 var parensNesting = 0;
500 var isObjectLitAr = [ false ];
501 while (token = this.ts.lookTok()) {
505 currentScope = this.scopes[this.scopes.length-1];
507 //println("<i>"+token.data+"</i>");
508 //this.log("EXP:" + token.data);
509 switch (token.type) {
515 if (this.braceNesting == expressionBraceNesting &&
516 bracketNesting == 0 &&
517 parensNesting == 0) {
525 case '{': //Token.LC:
526 isObjectLitAr.push(false);
529 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
532 case '}': //Token.RC:
535 //print(">>>>> EXP POP" + this.braceNesting);
536 // assert braceNesting >= expressionBraceNesting;
539 case '[': //Token.LB:
543 case ']': //Token.RB:
547 case '(': //Token.LP:
551 case ')': //Token.RP:
557 case 'STRN': // used for object lit detection..
558 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
559 // then we are in an object lit.. -> we need to flag the brace as such...
561 isObjectLitAr.push(true);
562 //print(">>>>> EXP PUSH(true)");
567 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
568 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
569 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
570 // see if we can replace..
571 // remove the quotes..
572 var str = token.data.substring(1,token.data.length-1);
573 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
588 print("in NAME = " + token.toString());
589 print("in NAME 0: " + this.ts.look(0).toString());
590 print("in NAME 2: " + this.ts.lookTok(2).toString());
591 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
592 // then we are in an object lit.. -> we need to flag the brace as such...
594 isObjectLitAr.push(true);
595 //print(">>>>> EXP PUSH(true)");
599 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
600 print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
602 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
605 //print(this.ts.lookTok(0).data);
606 if (this.ts.lookTok(0).data == ".") {
611 if (this.mode == 'PASS2_SYMBOL_TREE') {
613 identifier = this.getIdentifier(symbol, currentScope);
614 //println("<B>??</B>");
615 if (identifier == false) {
617 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
618 // Here, we found an undeclared and un-namespaced symbol that is
619 // 3 characters or less in length. Declare it in the global scope.
620 // We don't need to declare longer symbols since they won't cause
621 // any conflict with other munged symbols.
622 this.globalScope.declareIdentifier(symbol, token);
623 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
625 //println("undeclared")
630 //println("<B>++</B>");
631 token.identifier = identifier;
632 identifier.refcount++;
641 //println("<B>EID</B>");
644 if (token.name == "FUNCTION") {
646 this.parseFunctionDeclaration();
653 if (this.mode == 'BUILDING_SYMBOL_TREE') {
655 if (symbol == "eval") {
656 if (this.ts.look(-1).type == 'COMM') {
657 // look for eval:var:noreplace\n
659 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
660 var hi = _t.getIdentifier(a, currentScope);
661 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
663 // println("PROTECT "+a+" from munge");
671 this.protectScopeFromObfuscation(currentScope);
672 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
681 if (!this.ts.nextTok()) break;
686 parseCatch : function() {
693 //token = getToken(-1);
694 //assert token.getType() == Token.CATCH;
695 token = this.ts.nextTok();
696 //assert token.getType() == Token.LP; (
697 token = this.ts.nextTok();
698 //assert token.getType() == Token.NAME;
701 currentScope = this.scopes[this.scopes.length-1];
703 if (this.mode == 'BUILDING_SYMBOL_TREE') {
704 // We must declare the exception identifier in the containing function
705 // scope to avoid errors related to the obfuscation process. No need to
706 // display a warning if the symbol was already declared here...
707 currentScope.declareIdentifier(symbol, token);
709 //?? why inc the refcount?? - that should be set when building the tree???
710 identifier = this.getIdentifier(symbol, currentScope);
711 identifier.refcount++;
714 token = this.ts.nextTok();
715 //assert token.getType() == Token.RP; // )
718 parseFunctionDeclaration : function()
720 // print("PARSE FUNCTION");
723 var currentScope = false;
726 //this.logR("<B>PARSING FUNCTION</B>");
727 currentScope = this.scopes[this.scopes.length-1];
729 token = this.ts.nextTok();
730 if (token.type == "NAME") {
731 if (this.mode == 'BUILDING_SYMBOL_TREE') {
732 // Get the name of the function and declare it in the current scope.
734 if (currentScope.getIdentifier(symbol) != false) {
735 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
737 currentScope.declareIdentifier(symbol,token);
739 token = this.ts.nextTok();
742 //assert token.getType() == Token.LP;
743 if (this.mode == 'BUILDING_SYMBOL_TREE') {
744 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
746 //println("STORING SCOPE" + this.ts.cursor);
748 this.indexedScopes[this.ts.cursor] = fnScope;
751 //qln("FETCHING SCOPE" + this.ts.cursor);
752 fnScope = this.indexedScopes[this.ts.cursor];
756 // Parse function arguments.
758 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
759 token = this.ts.nextTok();
760 // print ("FUNC ARGS: " + token.toString())
761 //assert token.getType() == Token.NAME ||
762 // token.getType() == Token.COMMA;
763 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
765 identifier = fnScope.declareIdentifier(symbol,token);
766 if (symbol == "$super" && argpos == 0) {
767 // Exception for Prototype 1.6...
768 identifier.preventMunging();
774 token = this.ts.nextTok();
775 // assert token.getType() == Token.LC;
778 token = this.ts.nextTok();
779 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
782 NOT SUPPORTED YET!?!!?!
784 // This is a hint. Hints are empty statements that look like
785 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
786 // to prevent specific symbols from getting obfuscated (some heretic
787 // implementations, such as Prototype 1.6, require specific variable
788 // names, such as $super for example, in order to work appropriately.
789 // Note: right now, only "nomunge" is supported in the right hand side
790 // of a hint. However, in the future, the right hand side may contain
793 String hints = token.getValue();
794 // Remove the leading and trailing quotes...
795 hints = hints.substring(1, hints.length() - 1).trim();
796 StringTokenizer st1 = new StringTokenizer(hints, ",");
797 while (st1.hasMoreTokens()) {
798 String hint = st1.nextToken();
799 int idx = hint.indexOf(':');
800 if (idx <= 0 || idx >= hint.length() - 1) {
801 if (mode == BUILDING_SYMBOL_TREE) {
802 // No need to report the error twice, hence the test...
803 this.warn("Invalid hint syntax: " + hint, true);
807 String variableName = hint.substring(0, idx).trim();
808 String variableType = hint.substring(idx + 1).trim();
809 if (mode == BUILDING_SYMBOL_TREE) {
810 fnScope.addHint(variableName, variableType);
811 } else if (mode == CHECKING_SYMBOL_TREE) {
812 identifier = fnScope.getIdentifier(variableName);
813 if (identifier != null) {
814 if (variableType.equals("nomunge")) {
815 identifier.preventMunging();
817 this.warn("Unsupported hint value: " + hint, true);
820 this.warn("Hint refers to an unknown identifier: " + hint, true);
827 this.parseScope(fnScope);
828 // now pop it off the stack!!!
834 protectScopeFromObfuscation : function(scope) {
835 //assert scope != null;
837 if (scope == this.globalScope) {
838 // The global scope does not get obfuscated,
839 // so we don't need to worry about it...
843 // Find the highest local scope containing the specified scope.
844 while (scope && scope.parent != this.globalScope) {
845 scope = scope.parent;
848 //assert scope.getParentScope() == globalScope;
849 scope.preventMunging();
852 getIdentifier: function(symbol, scope) {
854 while (scope != false) {
855 identifier = scope.getIdentifier(symbol);
856 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
860 scope = scope.parent;