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 print(">>> 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") { // kludge..
234 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
235 if (token.type !="NAME") {
236 print(token.toString());
237 print( "var without ident");
242 if (this.mode == "BUILDING_SYMBOL_TREE") {
243 identifier = scope.getIdentifier(token.data) ;
245 if (identifier == false) {
246 scope.declareIdentifier(token.data, token);
248 token.identifier = identifier;
249 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
253 token = this.ts.nextTok();
254 !this.debug|| print(token.toString());
256 assert token.getType() == Token.SEMI ||
257 token.getType() == Token.ASSIGN ||
258 token.getType() == Token.COMMA ||
259 token.getType() == Token.IN;
261 if (token.name == "IN") {
264 //var bn = this.braceNesting;
265 this.parseExpression();
266 //this.braceNesting = bn;
267 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
269 token = this.ts.lookTok(1);
270 !this.debug|| print("AFTER EXP: " + token.toString());
271 if (token.data == ';') {
277 case "KEYW.FUNCTION":
278 //println("<i>"+token.data+"</i>");
279 var bn = this.braceNesting;
280 this.parseFunctionDeclaration();
281 this.braceNesting = bn;
284 case "PUNC.LEFT_CURLY": // {
285 //println("<i>"+token.data+"</i>");
286 isObjectLitAr.push(false);
289 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
292 case "PUNC.RIGHT_CURLY": // }
293 //println("<i>"+token.data+"</i>");
296 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
297 //assert braceNesting >= scope.getBra ceNesting();
299 if (this.braceNesting < expressionBraceNesting) {
300 var ls = this.scopes.pop();
302 // eat symbol if we are currently at {
303 if (this.ts.look(0).data == '{') {
307 //print("<<<<<<<EXIT SCOPE" +this.scopes.length);
313 //println("<i>"+token.data+"</i>");
314 if (this.mode == "BUILDING_SYMBOL_TREE") {
315 // Inside a 'with' block, it is impossible to figure out
316 // statically whether a symbol is a local variable or an
317 // object member. As a consequence, the only thing we can
318 // do is turn the obfuscation off for the highest scope
319 // containing the 'with' block.
320 this.protectScopeFromObfuscation(scope);
321 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
326 //println("<i>"+token.data+"</i>");
330 case Token.SPECIALCOMMENT:
331 if (mode == BUILDING_SYMBOL_TREE) {
332 protectScopeFromObfuscation(scope);
333 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
338 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
339 case "STRN.SINGLE_QUOTE":
340 //println("<i>"+token.data+"</i>");
341 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
342 // then we are in an object lit.. -> we need to flag the brace as such...
344 isObjectLitAr.push(true);
345 //print(">>>>>> OBJLIT REPUSH(true)");
347 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
349 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
350 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
351 // see if we can replace..
352 // remove the quotes..
353 // should do a bit more checking!!!! (what about wierd char's in the string..
354 var str = token.data.substring(1,token.data.length-1);
355 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
369 //print("DEAL WITH NAME:");
372 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
373 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
375 isObjectLitAr.push(true);
376 //print(">>>>>> OBJLIT REPUSH(true)");
377 //println("<i>"+token.data+"</i>");
380 // print("DEAL WITH obj lit:");
381 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
383 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
384 // skip, it's an object lit key..
385 //println("<i>"+token.data+"</i>");
390 // skip anyting with "." before it..!!
392 if (this.ts.lookTok(-1).data == ".") {
393 // skip, it's an object prop.
394 //println("<i>"+token.data+"</i>");
398 if (this.mode == 'PASS2_SYMBOL_TREE') {
400 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
402 //print ("MUNGE?" + symbol);
404 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
406 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
407 identifier = this.getIdentifier(symbol, scope);
409 if (identifier == false) {
410 // BUG!find out where builtin is defined...
411 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
412 // Here, we found an undeclared and un-namespaced symbol that is
413 // 3 characters or less in length. Declare it in the global scope.
414 // We don't need to declare longer symbols since they won't cause
415 // any conflict with other munged symbols.
416 this.globalScope.declareIdentifier(symbol, token);
417 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
420 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
422 token.identifier = identifier;
423 identifier.refcount++;
428 //println("<B>SID</B>");
430 if (token.type != 'KEYW') {
433 // print("Check eval:");
437 if (this.mode == 'BUILDING_SYMBOL_TREE') {
439 if (symbol == "eval") {
440 // look back one and see if we can find a comment!!!
441 if (this.ts.look(-1).type == "COMM") {
442 // look for eval:var:noreplace\n
444 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
446 var hi = _t.getIdentifier(a, scope);
447 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
449 // println("PROTECT "+a+" from munge");
459 this.protectScopeFromObfuscation(scope);
460 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);
472 //this.timerPrint("parseScope TOK : " + token.toString());
473 token = this.ts.nextTok();
474 //if (this.ts.nextT()) break;
477 print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
481 parseExpression : function() {
483 // Parse the expression until we encounter a comma or a semi-colon
484 // in the same brace nesting, bracket nesting and paren nesting.
485 // Parse functions if any...
486 //println("<i>EXP</i><BR/>");
487 !this.debug || print("PARSE EXPR");
493 var expressionBraceNesting = this.braceNesting;
494 var bracketNesting = 0;
495 var parensNesting = 0;
497 var isObjectLitAr = [ false ];
498 while (token = this.ts.lookTok()) {
502 currentScope = this.scopes[this.scopes.length-1];
504 //println("<i>"+token.data+"</i>");
505 !this.debug|| print ("EXP" + token.toString());
506 switch (token.type) {
512 if (this.braceNesting == expressionBraceNesting &&
513 bracketNesting == 0 &&
514 parensNesting == 0) {
522 case '{': //Token.LC:
523 isObjectLitAr.push(false);
526 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
529 case '}': //Token.RC:
532 //print(">>>>> EXP POP" + this.braceNesting);
533 // assert braceNesting >= expressionBraceNesting;
536 case '[': //Token.LB:
540 case ']': //Token.RB:
544 case '(': //Token.LP:
548 case ')': //Token.RP:
554 case 'STRN': // used for object lit detection..
555 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
556 // then we are in an object lit.. -> we need to flag the brace as such...
558 isObjectLitAr.push(true);
559 //print(">>>>> EXP PUSH(true)");
564 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
565 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
566 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
567 // see if we can replace..
568 // remove the quotes..
569 var str = token.data.substring(1,token.data.length-1);
570 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
585 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
586 // then we are in an object lit.. -> we need to flag the brace as such...
588 isObjectLitAr.push(true);
589 //print(">>>>> EXP PUSH(true)");
592 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
593 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
597 if (this.ts.lookTok(-1).data == ".") {
602 if (this.mode == 'PASS2_SYMBOL_TREE') {
604 identifier = this.getIdentifier(symbol, currentScope);
605 //println("<B>??</B>");
606 if (identifier == false) {
608 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
609 // Here, we found an undeclared and un-namespaced symbol that is
610 // 3 characters or less in length. Declare it in the global scope.
611 // We don't need to declare longer symbols since they won't cause
612 // any conflict with other munged symbols.
613 this.globalScope.declareIdentifier(symbol, token);
614 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
616 //println("undeclared")
621 //println("<B>++</B>");
622 token.identifier = identifier;
623 identifier.refcount++;
632 //println("<B>EID</B>");
635 if (token.name == "FUNCTION") {
637 this.parseFunctionDeclaration();
644 if (this.mode == 'BUILDING_SYMBOL_TREE') {
646 if (symbol == "eval") {
647 if (this.ts.look(-1).type == 'COMM') {
648 // look for eval:var:noreplace\n
650 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
651 var hi = _t.getIdentifier(a, currentScope);
652 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
654 // println("PROTECT "+a+" from munge");
662 this.protectScopeFromObfuscation(currentScope);
663 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
672 if (!this.ts.nextTok()) break;
677 parseCatch : function() {
684 //token = getToken(-1);
685 //assert token.getType() == Token.CATCH;
686 token = this.ts.nextTok();
687 //assert token.getType() == Token.LP; (
688 token = this.ts.nextTok();
689 //assert token.getType() == Token.NAME;
692 currentScope = this.scopes[this.scopes.length-1];
694 if (this.mode == 'BUILDING_SYMBOL_TREE') {
695 // We must declare the exception identifier in the containing function
696 // scope to avoid errors related to the obfuscation process. No need to
697 // display a warning if the symbol was already declared here...
698 currentScope.declareIdentifier(symbol, token);
700 //?? why inc the refcount?? - that should be set when building the tree???
701 identifier = this.getIdentifier(symbol, currentScope);
702 identifier.refcount++;
705 token = this.ts.nextTok();
706 //assert token.getType() == Token.RP; // )
709 parseFunctionDeclaration : function()
711 // print("PARSE FUNCTION");
714 var currentScope = false;
717 //this.logR("<B>PARSING FUNCTION</B>");
718 currentScope = this.scopes[this.scopes.length-1];
720 token = this.ts.nextTok();
721 if (token.type == "NAME") {
722 if (this.mode == 'BUILDING_SYMBOL_TREE') {
723 // Get the name of the function and declare it in the current scope.
725 if (currentScope.getIdentifier(symbol) != false) {
726 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
728 currentScope.declareIdentifier(symbol,token);
730 token = this.ts.nextTok();
733 //assert token.getType() == Token.LP;
734 if (this.mode == 'BUILDING_SYMBOL_TREE') {
735 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
737 //println("STORING SCOPE" + this.ts.cursor);
739 this.indexedScopes[this.ts.cursor] = fnScope;
742 //qln("FETCHING SCOPE" + this.ts.cursor);
743 fnScope = this.indexedScopes[this.ts.cursor];
747 // Parse function arguments.
749 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
750 token = this.ts.nextTok();
751 // print ("FUNC ARGS: " + token.toString())
752 //assert token.getType() == Token.NAME ||
753 // token.getType() == Token.COMMA;
754 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
756 identifier = fnScope.declareIdentifier(symbol,token);
757 if (symbol == "$super" && argpos == 0) {
758 // Exception for Prototype 1.6...
759 identifier.preventMunging();
765 token = this.ts.nextTok();
766 // assert token.getType() == Token.LC;
769 token = this.ts.nextTok();
770 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
773 NOT SUPPORTED YET!?!!?!
775 // This is a hint. Hints are empty statements that look like
776 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
777 // to prevent specific symbols from getting obfuscated (some heretic
778 // implementations, such as Prototype 1.6, require specific variable
779 // names, such as $super for example, in order to work appropriately.
780 // Note: right now, only "nomunge" is supported in the right hand side
781 // of a hint. However, in the future, the right hand side may contain
784 String hints = token.getValue();
785 // Remove the leading and trailing quotes...
786 hints = hints.substring(1, hints.length() - 1).trim();
787 StringTokenizer st1 = new StringTokenizer(hints, ",");
788 while (st1.hasMoreTokens()) {
789 String hint = st1.nextToken();
790 int idx = hint.indexOf(':');
791 if (idx <= 0 || idx >= hint.length() - 1) {
792 if (mode == BUILDING_SYMBOL_TREE) {
793 // No need to report the error twice, hence the test...
794 this.warn("Invalid hint syntax: " + hint, true);
798 String variableName = hint.substring(0, idx).trim();
799 String variableType = hint.substring(idx + 1).trim();
800 if (mode == BUILDING_SYMBOL_TREE) {
801 fnScope.addHint(variableName, variableType);
802 } else if (mode == CHECKING_SYMBOL_TREE) {
803 identifier = fnScope.getIdentifier(variableName);
804 if (identifier != null) {
805 if (variableType.equals("nomunge")) {
806 identifier.preventMunging();
808 this.warn("Unsupported hint value: " + hint, true);
811 this.warn("Hint refers to an unknown identifier: " + hint, true);
818 this.parseScope(fnScope);
819 // now pop it off the stack!!!
825 protectScopeFromObfuscation : function(scope) {
826 //assert scope != null;
828 if (scope == this.globalScope) {
829 // The global scope does not get obfuscated,
830 // so we don't need to worry about it...
834 // Find the highest local scope containing the specified scope.
835 while (scope && scope.parent != this.globalScope) {
836 scope = scope.parent;
839 //assert scope.getParentScope() == globalScope;
840 scope.preventMunging();
843 getIdentifier: function(symbol, scope) {
845 while (scope != false) {
846 identifier = scope.getIdentifier(symbol);
847 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
851 scope = scope.parent;