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) {
589 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
590 // then we are in an object lit.. -> we need to flag the brace as such...
592 isObjectLitAr.push(true);
593 //print(">>>>> EXP PUSH(true)");
596 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
597 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
600 //print(this.ts.lookTok(0).data);
601 if (this.ts.lookTok(0).data == ".") {
606 if (this.mode == 'PASS2_SYMBOL_TREE') {
608 identifier = this.getIdentifier(symbol, currentScope);
609 //println("<B>??</B>");
610 if (identifier == false) {
612 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
613 // Here, we found an undeclared and un-namespaced symbol that is
614 // 3 characters or less in length. Declare it in the global scope.
615 // We don't need to declare longer symbols since they won't cause
616 // any conflict with other munged symbols.
617 this.globalScope.declareIdentifier(symbol, token);
618 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
620 //println("undeclared")
625 //println("<B>++</B>");
626 token.identifier = identifier;
627 identifier.refcount++;
636 //println("<B>EID</B>");
639 if (token.name == "FUNCTION") {
641 this.parseFunctionDeclaration();
648 if (this.mode == 'BUILDING_SYMBOL_TREE') {
650 if (symbol == "eval") {
651 if (this.ts.look(-1).type == 'COMM') {
652 // look for eval:var:noreplace\n
654 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
655 var hi = _t.getIdentifier(a, currentScope);
656 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
658 // println("PROTECT "+a+" from munge");
666 this.protectScopeFromObfuscation(currentScope);
667 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
676 if (!this.ts.nextTok()) break;
681 parseCatch : function() {
688 //token = getToken(-1);
689 //assert token.getType() == Token.CATCH;
690 token = this.ts.nextTok();
691 //assert token.getType() == Token.LP; (
692 token = this.ts.nextTok();
693 //assert token.getType() == Token.NAME;
696 currentScope = this.scopes[this.scopes.length-1];
698 if (this.mode == 'BUILDING_SYMBOL_TREE') {
699 // We must declare the exception identifier in the containing function
700 // scope to avoid errors related to the obfuscation process. No need to
701 // display a warning if the symbol was already declared here...
702 currentScope.declareIdentifier(symbol, token);
704 //?? why inc the refcount?? - that should be set when building the tree???
705 identifier = this.getIdentifier(symbol, currentScope);
706 identifier.refcount++;
709 token = this.ts.nextTok();
710 //assert token.getType() == Token.RP; // )
713 parseFunctionDeclaration : function()
715 // print("PARSE FUNCTION");
718 var currentScope = false;
721 //this.logR("<B>PARSING FUNCTION</B>");
722 currentScope = this.scopes[this.scopes.length-1];
724 token = this.ts.nextTok();
725 if (token.type == "NAME") {
726 if (this.mode == 'BUILDING_SYMBOL_TREE') {
727 // Get the name of the function and declare it in the current scope.
729 if (currentScope.getIdentifier(symbol) != false) {
730 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
732 currentScope.declareIdentifier(symbol,token);
734 token = this.ts.nextTok();
737 //assert token.getType() == Token.LP;
738 if (this.mode == 'BUILDING_SYMBOL_TREE') {
739 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
741 //println("STORING SCOPE" + this.ts.cursor);
743 this.indexedScopes[this.ts.cursor] = fnScope;
746 //qln("FETCHING SCOPE" + this.ts.cursor);
747 fnScope = this.indexedScopes[this.ts.cursor];
751 // Parse function arguments.
753 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
754 token = this.ts.nextTok();
755 // print ("FUNC ARGS: " + token.toString())
756 //assert token.getType() == Token.NAME ||
757 // token.getType() == Token.COMMA;
758 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
760 identifier = fnScope.declareIdentifier(symbol,token);
761 if (symbol == "$super" && argpos == 0) {
762 // Exception for Prototype 1.6...
763 identifier.preventMunging();
769 token = this.ts.nextTok();
770 // assert token.getType() == Token.LC;
773 token = this.ts.nextTok();
774 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
777 NOT SUPPORTED YET!?!!?!
779 // This is a hint. Hints are empty statements that look like
780 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
781 // to prevent specific symbols from getting obfuscated (some heretic
782 // implementations, such as Prototype 1.6, require specific variable
783 // names, such as $super for example, in order to work appropriately.
784 // Note: right now, only "nomunge" is supported in the right hand side
785 // of a hint. However, in the future, the right hand side may contain
788 String hints = token.getValue();
789 // Remove the leading and trailing quotes...
790 hints = hints.substring(1, hints.length() - 1).trim();
791 StringTokenizer st1 = new StringTokenizer(hints, ",");
792 while (st1.hasMoreTokens()) {
793 String hint = st1.nextToken();
794 int idx = hint.indexOf(':');
795 if (idx <= 0 || idx >= hint.length() - 1) {
796 if (mode == BUILDING_SYMBOL_TREE) {
797 // No need to report the error twice, hence the test...
798 this.warn("Invalid hint syntax: " + hint, true);
802 String variableName = hint.substring(0, idx).trim();
803 String variableType = hint.substring(idx + 1).trim();
804 if (mode == BUILDING_SYMBOL_TREE) {
805 fnScope.addHint(variableName, variableType);
806 } else if (mode == CHECKING_SYMBOL_TREE) {
807 identifier = fnScope.getIdentifier(variableName);
808 if (identifier != null) {
809 if (variableType.equals("nomunge")) {
810 identifier.preventMunging();
812 this.warn("Unsupported hint value: " + hint, true);
815 this.warn("Hint refers to an unknown identifier: " + hint, true);
822 this.parseScope(fnScope);
823 // now pop it off the stack!!!
829 protectScopeFromObfuscation : function(scope) {
830 //assert scope != null;
832 if (scope == this.globalScope) {
833 // The global scope does not get obfuscated,
834 // so we don't need to worry about it...
838 // Find the highest local scope containing the specified scope.
839 while (scope && scope.parent != this.globalScope) {
840 scope = scope.parent;
843 //assert scope.getParentScope() == globalScope;
844 scope.preventMunging();
847 getIdentifier: function(symbol, scope) {
849 while (scope != false) {
850 identifier = scope.getIdentifier(symbol);
851 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
855 scope = scope.parent;