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);
213 token = this.ts.lookTok(1);
215 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
216 //print(scopeIndent + 'OBJLIT.len='+ isObjectLitAr.length + ' ' + token.toString());
217 //this.log(token.data);
218 if (token.type == 'NAME') {
219 // print('*' + token.data);
221 switch(token.type + '.' + token.name) {
223 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
225 //this.log("parseScope GOT VAR/CONST : " + token.toString());
227 token = this.ts.nextTok();
228 !this.debug|| print( token.toString());
230 if (!token) { // can return false at EOF!
233 if (token.name == "VAR" || token.data == ',') { // kludge..
236 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
237 if (token.type !="NAME") {
238 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
239 print(this.ts.tokens[i].toString());
242 print( "var without ident");
247 if (this.mode == "BUILDING_SYMBOL_TREE") {
248 identifier = scope.getIdentifier(token.data) ;
250 if (identifier == false) {
251 scope.declareIdentifier(token.data, token);
253 token.identifier = identifier;
254 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
258 token = this.ts.nextTok();
259 !this.debug|| print(token.toString());
261 assert token.getType() == Token.SEMI ||
262 token.getType() == Token.ASSIGN ||
263 token.getType() == Token.COMMA ||
264 token.getType() == Token.IN;
266 if (token.name == "IN") {
269 //var bn = this.braceNesting;
270 this.parseExpression();
271 //this.braceNesting = bn;
272 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
274 token = this.ts.lookTok(1);
275 !this.debug|| print("AFTER EXP: " + token.toString());
276 if (token.data == ';') {
282 case "KEYW.FUNCTION":
283 //println("<i>"+token.data+"</i>");
284 var bn = this.braceNesting;
285 this.parseFunctionDeclaration();
286 this.braceNesting = bn;
289 case "PUNC.LEFT_CURLY": // {
290 //println("<i>"+token.data+"</i>");
291 isObjectLitAr.push(false);
294 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
297 case "PUNC.RIGHT_CURLY": // }
298 //println("<i>"+token.data+"</i>");
301 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
302 //assert braceNesting >= scope.getBra ceNesting();
304 if (this.braceNesting < expressionBraceNesting) {
305 var ls = this.scopes.pop();
307 // eat symbol if we are currently at {
308 if (this.ts.look(0).data == '{') {
312 //print("<<<<<<<EXIT SCOPE" +this.scopes.length);
318 //println("<i>"+token.data+"</i>");
319 if (this.mode == "BUILDING_SYMBOL_TREE") {
320 // Inside a 'with' block, it is impossible to figure out
321 // statically whether a symbol is a local variable or an
322 // object member. As a consequence, the only thing we can
323 // do is turn the obfuscation off for the highest scope
324 // containing the 'with' block.
325 this.protectScopeFromObfuscation(scope);
326 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
331 //println("<i>"+token.data+"</i>");
335 case Token.SPECIALCOMMENT:
336 if (mode == BUILDING_SYMBOL_TREE) {
337 protectScopeFromObfuscation(scope);
338 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
343 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
344 case "STRN.SINGLE_QUOTE":
345 //println("<i>"+token.data+"</i>");
346 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
347 // then we are in an object lit.. -> we need to flag the brace as such...
349 isObjectLitAr.push(true);
350 //print(">>>>>> OBJLIT REPUSH(true)");
352 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
354 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
355 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
356 // see if we can replace..
357 // remove the quotes..
358 // should do a bit more checking!!!! (what about wierd char's in the string..
359 var str = token.data.substring(1,token.data.length-1);
360 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
374 //print("DEAL WITH NAME:");
377 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
378 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
380 isObjectLitAr.push(true);
381 //print(">>>>>> OBJLIT REPUSH(true)");
382 //println("<i>"+token.data+"</i>");
385 // print("DEAL WITH obj lit:");
386 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
388 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
389 // skip, it's an object lit key..
390 //println("<i>"+token.data+"</i>");
395 // skip anyting with "." before it..!!
397 if (this.ts.lookTok(-1).data == ".") {
398 // skip, it's an object prop.
399 //println("<i>"+token.data+"</i>");
403 if (this.mode == 'PASS2_SYMBOL_TREE') {
405 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
407 //print ("MUNGE?" + symbol);
409 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
411 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
412 identifier = this.getIdentifier(symbol, scope);
414 if (identifier == false) {
415 // BUG!find out where builtin is defined...
416 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
417 // Here, we found an undeclared and un-namespaced symbol that is
418 // 3 characters or less in length. Declare it in the global scope.
419 // We don't need to declare longer symbols since they won't cause
420 // any conflict with other munged symbols.
421 this.globalScope.declareIdentifier(symbol, token);
422 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
425 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
427 token.identifier = identifier;
428 identifier.refcount++;
433 //println("<B>SID</B>");
435 if (token.type != 'KEYW') {
438 // print("Check eval:");
442 if (this.mode == 'BUILDING_SYMBOL_TREE') {
444 if (symbol == "eval") {
445 // look back one and see if we can find a comment!!!
446 if (this.ts.look(-1).type == "COMM") {
447 // look for eval:var:noreplace\n
449 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
451 var hi = _t.getIdentifier(a, scope);
452 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
454 // println("PROTECT "+a+" from munge");
464 this.protectScopeFromObfuscation(scope);
465 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);
477 //this.timerPrint("parseScope TOK : " + token.toString());
478 token = this.ts.nextTok();
479 //if (this.ts.nextT()) break;
482 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
486 parseExpression : function() {
488 // Parse the expression until we encounter a comma or a semi-colon
489 // in the same brace nesting, bracket nesting and paren nesting.
490 // Parse functions if any...
491 //println("<i>EXP</i><BR/>");
492 !this.debug || print("PARSE EXPR");
495 // for printing stuff..
504 var expressionBraceNesting = this.braceNesting;
505 var bracketNesting = 0;
506 var parensNesting = 0;
508 var isObjectLitAr = [ false ];
510 currentScope = this.scopes[this.scopes.length-1];
512 var scopeIndent = '';
513 this.scopes.forEach(function() {
516 print(scopeIndent + ">> ENTER EXPRESSION");
517 while (token = this.ts.lookTok()) {
522 // moved out of loop?
523 currentScope = this.scopes[this.scopes.length-1];
525 var scopeIndent = '';
526 this.scopes.forEach(function() {
530 print(scopeIndent + 'OBJLIT.len='+ isObjectLitAr.length + ' ' + token.data);
532 //println("<i>"+token.data+"</i>");
533 //this.log("EXP:" + token.data);
534 switch (token.type) {
540 if (this.braceNesting == expressionBraceNesting &&
541 bracketNesting == 0 &&
542 parensNesting == 0) {
543 print(scopeIndent + "<< EXIT EXPRESSION");
550 case '{': //Token.LC:
551 isObjectLitAr.push(false);
554 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
557 case '}': //Token.RC:
560 //print(">>>>> EXP POP" + this.braceNesting);
561 // assert braceNesting >= expressionBraceNesting;
564 case '[': //Token.LB:
568 case ']': //Token.RB:
572 case '(': //Token.LP:
576 case ')': //Token.RP:
582 case 'STRN': // used for object lit detection..
583 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
584 // then we are in an object lit.. -> we need to flag the brace as such...
586 isObjectLitAr.push(true);
587 //print(">>>>> EXP PUSH(true)");
592 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
593 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
594 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
595 // see if we can replace..
596 // remove the quotes..
597 var str = token.data.substring(1,token.data.length-1);
598 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
613 //print("in NAME = " + token.toString());
614 //print("in NAME 0: " + this.ts.look(0).toString());
615 //print("in NAME 2: " + this.ts.lookTok(2).toString());
616 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
617 // then we are in an object lit.. -> we need to flag the brace as such...
619 isObjectLitAr.push(true);
620 //print(">>>>> EXP PUSH(true)");
624 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
625 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
627 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
630 //print(this.ts.lookTok(0).data);
631 if (this.ts.lookTok(0).data == ".") {
636 if (this.mode == 'PASS2_SYMBOL_TREE') {
638 identifier = this.getIdentifier(symbol, currentScope);
639 //println("<B>??</B>");
640 if (identifier == false) {
642 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
643 // Here, we found an undeclared and un-namespaced symbol that is
644 // 3 characters or less in length. Declare it in the global scope.
645 // We don't need to declare longer symbols since they won't cause
646 // any conflict with other munged symbols.
647 this.globalScope.declareIdentifier(symbol, token);
648 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
650 //println("undeclared")
655 //println("<B>++</B>");
656 token.identifier = identifier;
657 identifier.refcount++;
666 //println("<B>EID</B>");
669 if (token.name == "FUNCTION") {
671 this.parseFunctionDeclaration();
678 if (this.mode == 'BUILDING_SYMBOL_TREE') {
680 if (symbol == "eval") {
681 if (this.ts.look(-1).type == 'COMM') {
682 // look for eval:var:noreplace\n
684 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
685 var hi = _t.getIdentifier(a, currentScope);
686 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
688 // println("PROTECT "+a+" from munge");
696 this.protectScopeFromObfuscation(currentScope);
697 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
706 if (!this.ts.nextTok()) break;
708 print(scopeIndent + "<< EXIT EXPRESSION");
712 parseCatch : function() {
719 //token = getToken(-1);
720 //assert token.getType() == Token.CATCH;
721 token = this.ts.nextTok();
722 //assert token.getType() == Token.LP; (
723 token = this.ts.nextTok();
724 //assert token.getType() == Token.NAME;
727 currentScope = this.scopes[this.scopes.length-1];
729 if (this.mode == 'BUILDING_SYMBOL_TREE') {
730 // We must declare the exception identifier in the containing function
731 // scope to avoid errors related to the obfuscation process. No need to
732 // display a warning if the symbol was already declared here...
733 currentScope.declareIdentifier(symbol, token);
735 //?? why inc the refcount?? - that should be set when building the tree???
736 identifier = this.getIdentifier(symbol, currentScope);
737 identifier.refcount++;
740 token = this.ts.nextTok();
741 //assert token.getType() == Token.RP; // )
744 parseFunctionDeclaration : function()
746 // print("PARSE FUNCTION");
749 var currentScope = false;
752 //this.logR("<B>PARSING FUNCTION</B>");
753 currentScope = this.scopes[this.scopes.length-1];
755 token = this.ts.nextTok();
756 if (token.type == "NAME") {
757 if (this.mode == 'BUILDING_SYMBOL_TREE') {
758 // Get the name of the function and declare it in the current scope.
760 if (currentScope.getIdentifier(symbol) != false) {
761 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
763 currentScope.declareIdentifier(symbol,token);
765 token = this.ts.nextTok();
768 //assert token.getType() == Token.LP;
769 if (this.mode == 'BUILDING_SYMBOL_TREE') {
770 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
772 //println("STORING SCOPE" + this.ts.cursor);
774 this.indexedScopes[this.ts.cursor] = fnScope;
777 //qln("FETCHING SCOPE" + this.ts.cursor);
778 fnScope = this.indexedScopes[this.ts.cursor];
782 // Parse function arguments.
784 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
785 token = this.ts.nextTok();
786 // print ("FUNC ARGS: " + token.toString())
787 //assert token.getType() == Token.NAME ||
788 // token.getType() == Token.COMMA;
789 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
791 identifier = fnScope.declareIdentifier(symbol,token);
792 if (symbol == "$super" && argpos == 0) {
793 // Exception for Prototype 1.6...
794 identifier.preventMunging();
800 token = this.ts.nextTok();
801 // assert token.getType() == Token.LC;
804 token = this.ts.nextTok();
805 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
808 NOT SUPPORTED YET!?!!?!
810 // This is a hint. Hints are empty statements that look like
811 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
812 // to prevent specific symbols from getting obfuscated (some heretic
813 // implementations, such as Prototype 1.6, require specific variable
814 // names, such as $super for example, in order to work appropriately.
815 // Note: right now, only "nomunge" is supported in the right hand side
816 // of a hint. However, in the future, the right hand side may contain
819 String hints = token.getValue();
820 // Remove the leading and trailing quotes...
821 hints = hints.substring(1, hints.length() - 1).trim();
822 StringTokenizer st1 = new StringTokenizer(hints, ",");
823 while (st1.hasMoreTokens()) {
824 String hint = st1.nextToken();
825 int idx = hint.indexOf(':');
826 if (idx <= 0 || idx >= hint.length() - 1) {
827 if (mode == BUILDING_SYMBOL_TREE) {
828 // No need to report the error twice, hence the test...
829 this.warn("Invalid hint syntax: " + hint, true);
833 String variableName = hint.substring(0, idx).trim();
834 String variableType = hint.substring(idx + 1).trim();
835 if (mode == BUILDING_SYMBOL_TREE) {
836 fnScope.addHint(variableName, variableType);
837 } else if (mode == CHECKING_SYMBOL_TREE) {
838 identifier = fnScope.getIdentifier(variableName);
839 if (identifier != null) {
840 if (variableType.equals("nomunge")) {
841 identifier.preventMunging();
843 this.warn("Unsupported hint value: " + hint, true);
846 this.warn("Hint refers to an unknown identifier: " + hint, true);
853 this.parseScope(fnScope);
854 // now pop it off the stack!!!
860 protectScopeFromObfuscation : function(scope) {
861 //assert scope != null;
863 if (scope == this.globalScope) {
864 // The global scope does not get obfuscated,
865 // so we don't need to worry about it...
869 // Find the highest local scope containing the specified scope.
870 while (scope && scope.parent != this.globalScope) {
871 scope = scope.parent;
874 //assert scope.getParentScope() == globalScope;
875 scope.preventMunging();
878 getIdentifier: function(symbol, scope) {
880 while (scope != false) {
881 identifier = scope.getIdentifier(symbol);
882 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
886 scope = scope.parent;