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") { // 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.log("EXP:" + token.data);
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) {
586 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
587 // then we are in an object lit.. -> we need to flag the brace as such...
589 isObjectLitAr.push(true);
590 //print(">>>>> EXP PUSH(true)");
593 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
594 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
597 //print(this.ts.lookTok(0).data);
598 if (this.ts.lookTok(0).data == ".") {
603 if (this.mode == 'PASS2_SYMBOL_TREE') {
605 identifier = this.getIdentifier(symbol, currentScope);
606 //println("<B>??</B>");
607 if (identifier == false) {
609 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
610 // Here, we found an undeclared and un-namespaced symbol that is
611 // 3 characters or less in length. Declare it in the global scope.
612 // We don't need to declare longer symbols since they won't cause
613 // any conflict with other munged symbols.
614 this.globalScope.declareIdentifier(symbol, token);
615 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
617 //println("undeclared")
622 //println("<B>++</B>");
623 token.identifier = identifier;
624 identifier.refcount++;
633 //println("<B>EID</B>");
636 if (token.name == "FUNCTION") {
638 this.parseFunctionDeclaration();
645 if (this.mode == 'BUILDING_SYMBOL_TREE') {
647 if (symbol == "eval") {
648 if (this.ts.look(-1).type == 'COMM') {
649 // look for eval:var:noreplace\n
651 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
652 var hi = _t.getIdentifier(a, currentScope);
653 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
655 // println("PROTECT "+a+" from munge");
663 this.protectScopeFromObfuscation(currentScope);
664 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
673 if (!this.ts.nextTok()) break;
678 parseCatch : function() {
685 //token = getToken(-1);
686 //assert token.getType() == Token.CATCH;
687 token = this.ts.nextTok();
688 //assert token.getType() == Token.LP; (
689 token = this.ts.nextTok();
690 //assert token.getType() == Token.NAME;
693 currentScope = this.scopes[this.scopes.length-1];
695 if (this.mode == 'BUILDING_SYMBOL_TREE') {
696 // We must declare the exception identifier in the containing function
697 // scope to avoid errors related to the obfuscation process. No need to
698 // display a warning if the symbol was already declared here...
699 currentScope.declareIdentifier(symbol, token);
701 //?? why inc the refcount?? - that should be set when building the tree???
702 identifier = this.getIdentifier(symbol, currentScope);
703 identifier.refcount++;
706 token = this.ts.nextTok();
707 //assert token.getType() == Token.RP; // )
710 parseFunctionDeclaration : function()
712 // print("PARSE FUNCTION");
715 var currentScope = false;
718 //this.logR("<B>PARSING FUNCTION</B>");
719 currentScope = this.scopes[this.scopes.length-1];
721 token = this.ts.nextTok();
722 if (token.type == "NAME") {
723 if (this.mode == 'BUILDING_SYMBOL_TREE') {
724 // Get the name of the function and declare it in the current scope.
726 if (currentScope.getIdentifier(symbol) != false) {
727 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
729 currentScope.declareIdentifier(symbol,token);
731 token = this.ts.nextTok();
734 //assert token.getType() == Token.LP;
735 if (this.mode == 'BUILDING_SYMBOL_TREE') {
736 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
738 //println("STORING SCOPE" + this.ts.cursor);
740 this.indexedScopes[this.ts.cursor] = fnScope;
743 //qln("FETCHING SCOPE" + this.ts.cursor);
744 fnScope = this.indexedScopes[this.ts.cursor];
748 // Parse function arguments.
750 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
751 token = this.ts.nextTok();
752 // print ("FUNC ARGS: " + token.toString())
753 //assert token.getType() == Token.NAME ||
754 // token.getType() == Token.COMMA;
755 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
757 identifier = fnScope.declareIdentifier(symbol,token);
758 if (symbol == "$super" && argpos == 0) {
759 // Exception for Prototype 1.6...
760 identifier.preventMunging();
766 token = this.ts.nextTok();
767 // assert token.getType() == Token.LC;
770 token = this.ts.nextTok();
771 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
774 NOT SUPPORTED YET!?!!?!
776 // This is a hint. Hints are empty statements that look like
777 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
778 // to prevent specific symbols from getting obfuscated (some heretic
779 // implementations, such as Prototype 1.6, require specific variable
780 // names, such as $super for example, in order to work appropriately.
781 // Note: right now, only "nomunge" is supported in the right hand side
782 // of a hint. However, in the future, the right hand side may contain
785 String hints = token.getValue();
786 // Remove the leading and trailing quotes...
787 hints = hints.substring(1, hints.length() - 1).trim();
788 StringTokenizer st1 = new StringTokenizer(hints, ",");
789 while (st1.hasMoreTokens()) {
790 String hint = st1.nextToken();
791 int idx = hint.indexOf(':');
792 if (idx <= 0 || idx >= hint.length() - 1) {
793 if (mode == BUILDING_SYMBOL_TREE) {
794 // No need to report the error twice, hence the test...
795 this.warn("Invalid hint syntax: " + hint, true);
799 String variableName = hint.substring(0, idx).trim();
800 String variableType = hint.substring(idx + 1).trim();
801 if (mode == BUILDING_SYMBOL_TREE) {
802 fnScope.addHint(variableName, variableType);
803 } else if (mode == CHECKING_SYMBOL_TREE) {
804 identifier = fnScope.getIdentifier(variableName);
805 if (identifier != null) {
806 if (variableType.equals("nomunge")) {
807 identifier.preventMunging();
809 this.warn("Unsupported hint value: " + hint, true);
812 this.warn("Hint refers to an unknown identifier: " + hint, true);
819 this.parseScope(fnScope);
820 // now pop it off the stack!!!
826 protectScopeFromObfuscation : function(scope) {
827 //assert scope != null;
829 if (scope == this.globalScope) {
830 // The global scope does not get obfuscated,
831 // so we don't need to worry about it...
835 // Find the highest local scope containing the specified scope.
836 while (scope && scope.parent != this.globalScope) {
837 scope = scope.parent;
840 //assert scope.getParentScope() == globalScope;
841 scope.preventMunging();
844 getIdentifier: function(symbol, scope) {
846 while (scope != false) {
847 identifier = scope.getIdentifier(symbol);
848 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
852 scope = scope.parent;