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/>");
192 dumpToken: function (tok, scope, brace) {
193 if (this.dumpLine == false) {
195 str : tok.data + ' ',
196 scope : scope.length,
202 if (this.dumpLine.scope == scope.length && this.dumpLine.brace == brace) {
203 this.dumpLine.str += tok.data + ' ';
204 if (this.dumpLine.str.length > 80 || tok.data ==';') {
207 // (new Array(this.dumpLine.scope)).join(" ") + '|' +
208 (new Array(this.dumpLine.brace+1)).join(" ") + this.dumpLine.str);
209 this.dumpLine.str = '';
215 // (new Array(this.dumpLine.scope)).join(" ") + '|' +
216 (new Array(this.dumpLine.brace+1)).join(" ") + this.dumpLine.str);
220 str : tok.data + ' ',
221 scope : scope.length,
229 parseScope : function(scope) // parse a token stream..
231 //this.timerPrint("parseScope EnterScope");
232 //this.log(">>> ENTER SCOPE" + this.scopes.length);
238 var expressionBraceNesting = this.braceNesting + 0;
240 var parensNesting = 0;
242 var isObjectLitAr = [ false ];
244 this.scopes.push(scope);
246 var scopeIndent = '';
247 this.scopes.forEach(function() {
250 print(scopeIndent + ">> ENTER SCOPE");
255 token = this.ts.lookTok(1);
257 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
258 //this.dumpToken(token , this.scopes, this.braceNesting);
259 print('SCOPE:' + token.toString());
260 //this.log(token.data);
261 if (token.type == 'NAME') {
262 // print('*' + token.data);
264 switch(token.type + '.' + token.name) {
266 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
269 //this.log("parseScope GOT VAR/CONST : " + token.toString());
271 token = this.ts.nextTok();
272 !this.debug|| print( token.toString());
274 if (!token) { // can return false at EOF!
277 if (token.name == "VAR" || token.data == ',') { // kludge..
280 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
281 if (token.type !="NAME") {
282 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
283 print(this.ts.tokens[i].toString());
286 print( "var without ident");
291 if (this.mode == "BUILDING_SYMBOL_TREE") {
292 identifier = scope.getIdentifier(token.data) ;
294 if (identifier == false) {
295 scope.declareIdentifier(token.data, token);
297 token.identifier = identifier;
298 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
302 token = this.ts.nextTok();
303 !this.debug|| print(token.toString());
305 assert token.getType() == Token.SEMI ||
306 token.getType() == Token.ASSIGN ||
307 token.getType() == Token.COMMA ||
308 token.getType() == Token.IN;
310 if (token.name == "IN") {
313 //var bn = this.braceNesting;
314 var bn = this.braceNesting;
315 this.parseExpression();
316 this.braceNesting = bn;
317 //this.braceNesting = bn;
318 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
320 token = this.ts.lookTok(1);
321 !this.debug|| print("AFTER EXP: " + token.toString());
322 if (token.data == ';') {
328 case "KEYW.FUNCTION":
329 //println("<i>"+token.data+"</i>");
330 var bn = this.braceNesting;
331 this.parseFunctionDeclaration();
332 this.braceNesting = bn;
335 case "PUNC.LEFT_CURLY": // {
336 //println("<i>"+token.data+"</i>");
337 isObjectLitAr.push(false);
340 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
343 case "PUNC.RIGHT_CURLY": // }
344 //println("<i>"+token.data+"</i>");
347 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
348 //assert braceNesting >= scope.getBra ceNesting();
350 if (this.braceNesting < expressionBraceNesting) {
351 var ls = this.scopes.pop();
353 // eat symbol if we are currently at {
354 if (this.ts.look(0).data == '{') {
358 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
364 //println("<i>"+token.data+"</i>");
365 if (this.mode == "BUILDING_SYMBOL_TREE") {
366 // Inside a 'with' block, it is impossible to figure out
367 // statically whether a symbol is a local variable or an
368 // object member. As a consequence, the only thing we can
369 // do is turn the obfuscation off for the highest scope
370 // containing the 'with' block.
371 this.protectScopeFromObfuscation(scope);
372 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
377 //println("<i>"+token.data+"</i>");
381 case Token.SPECIALCOMMENT:
382 if (mode == BUILDING_SYMBOL_TREE) {
383 protectScopeFromObfuscation(scope);
384 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
389 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
390 case "STRN.SINGLE_QUOTE":
391 //println("<i>"+token.data+"</i>");
392 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
393 // then we are in an object lit.. -> we need to flag the brace as such...
395 isObjectLitAr.push(true);
396 //print(">>>>>> OBJLIT REPUSH(true)");
398 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
400 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
401 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
402 // see if we can replace..
403 // remove the quotes..
404 // should do a bit more checking!!!! (what about wierd char's in the string..
405 var str = token.data.substring(1,token.data.length-1);
406 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
420 //print("DEAL WITH NAME:");
423 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
424 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
426 isObjectLitAr.push(true);
427 //print(">>>>>> OBJLIT REPUSH(true)");
428 //println("<i>"+token.data+"</i>");
431 // print("DEAL WITH obj lit:");
432 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
434 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
435 // skip, it's an object lit key..
436 //println("<i>"+token.data+"</i>");
441 // skip anyting with "." before it..!!
443 if (this.ts.lookTok(-1).data == ".") {
444 // skip, it's an object prop.
445 //println("<i>"+token.data+"</i>");
449 if (this.mode == 'PASS2_SYMBOL_TREE') {
451 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
453 //print ("MUNGE?" + symbol);
455 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
457 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
458 identifier = this.getIdentifier(symbol, scope);
460 if (identifier == false) {
461 // BUG!find out where builtin is defined...
462 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
463 // Here, we found an undeclared and un-namespaced symbol that is
464 // 3 characters or less in length. Declare it in the global scope.
465 // We don't need to declare longer symbols since they won't cause
466 // any conflict with other munged symbols.
467 this.globalScope.declareIdentifier(symbol, token);
468 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
471 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
473 token.identifier = identifier;
474 identifier.refcount++;
479 //println("<B>SID</B>");
481 if (token.type != 'KEYW') {
484 // print("Check eval:");
488 if (this.mode == 'BUILDING_SYMBOL_TREE') {
490 if (symbol == "eval") {
491 // look back one and see if we can find a comment!!!
492 if (this.ts.look(-1).type == "COMM") {
493 // look for eval:var:noreplace\n
495 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
497 var hi = _t.getIdentifier(a, scope);
498 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
500 // println("PROTECT "+a+" from munge");
510 this.protectScopeFromObfuscation(scope);
511 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);
523 //print("parseScope TOK : " + token.toString());
524 token = this.ts.nextTok();
525 //if (this.ts.nextT()) break;
528 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
532 parseExpression : function() {
534 // Parse the expression until we encounter a comma or a semi-colon
535 // in the same brace nesting, bracket nesting and paren nesting.
536 // Parse functions if any...
537 //println("<i>EXP</i><BR/>");
538 !this.debug || print("PARSE EXPR");
541 // for printing stuff..
550 var expressionBraceNesting = this.braceNesting + 0;
551 var bracketNesting = 0;
552 var parensNesting = 0;
554 var isObjectLitAr = [ false ];
556 currentScope = this.scopes[this.scopes.length-1];
558 var scopeIndent = '';
559 this.scopes.forEach(function() {
562 print(scopeIndent + ">> ENTER EXPRESSION");
563 while (token = this.ts.lookTok()) {
568 // moved out of loop?
569 currentScope = this.scopes[this.scopes.length-1];
571 var scopeIndent = '';
572 this.scopes.forEach(function() {
577 //this.dumpToken(token, this.scopes, this.braceNesting );
578 print('EXPRN:' + token.toString());
581 //println("<i>"+token.data+"</i>");
582 //this.log("EXP:" + token.data);
583 switch (token.type) {
589 if (this.braceNesting == expressionBraceNesting &&
590 bracketNesting == 0 &&
591 parensNesting == 0) {
592 print(scopeIndent + "<< EXIT EXPRESSION");
599 case '{': //Token.LC:
600 isObjectLitAr.push(false);
603 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
606 case '}': //Token.RC:
609 //print(">>>>> EXP POP" + this.braceNesting);
610 // assert braceNesting >= expressionBraceNesting;
613 case '[': //Token.LB:
617 case ']': //Token.RB:
621 case '(': //Token.LP:
625 case ')': //Token.RP:
631 case 'STRN': // used for object lit detection..
632 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
633 // then we are in an object lit.. -> we need to flag the brace as such...
635 isObjectLitAr.push(true);
636 //print(">>>>> EXP PUSH(true)");
641 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
642 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
643 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
644 // see if we can replace..
645 // remove the quotes..
646 var str = token.data.substring(1,token.data.length-1);
647 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
662 //print("in NAME = " + token.toString());
663 //print("in NAME 0: " + this.ts.look(0).toString());
664 //print("in NAME 2: " + this.ts.lookTok(2).toString());
665 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
666 // then we are in an object lit.. -> we need to flag the brace as such...
668 isObjectLitAr.push(true);
669 //print(">>>>> EXP PUSH(true)");
673 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
674 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
676 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
679 //print(this.ts.lookTok(0).data);
680 if (this.ts.lookTok(0).data == ".") {
685 if (this.mode == 'PASS2_SYMBOL_TREE') {
687 identifier = this.getIdentifier(symbol, currentScope);
688 //println("<B>??</B>");
689 if (identifier == false) {
691 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
692 // Here, we found an undeclared and un-namespaced symbol that is
693 // 3 characters or less in length. Declare it in the global scope.
694 // We don't need to declare longer symbols since they won't cause
695 // any conflict with other munged symbols.
696 this.globalScope.declareIdentifier(symbol, token);
697 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
699 //println("undeclared")
704 //println("<B>++</B>");
705 token.identifier = identifier;
706 identifier.refcount++;
715 //println("<B>EID</B>");
718 if (token.name == "FUNCTION") {
720 this.parseFunctionDeclaration();
727 if (this.mode == 'BUILDING_SYMBOL_TREE') {
729 if (symbol == "eval") {
730 if (this.ts.look(-1).type == 'COMM') {
731 // look for eval:var:noreplace\n
733 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
734 var hi = _t.getIdentifier(a, currentScope);
735 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
737 // println("PROTECT "+a+" from munge");
745 this.protectScopeFromObfuscation(currentScope);
746 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
755 if (!this.ts.nextTok()) break;
757 print(scopeIndent + "<< EXIT EXPRESSION");
761 parseCatch : function() {
768 //token = getToken(-1);
769 //assert token.getType() == Token.CATCH;
770 token = this.ts.nextTok();
771 //assert token.getType() == Token.LP; (
772 token = this.ts.nextTok();
773 //assert token.getType() == Token.NAME;
776 currentScope = this.scopes[this.scopes.length-1];
778 if (this.mode == 'BUILDING_SYMBOL_TREE') {
779 // We must declare the exception identifier in the containing function
780 // scope to avoid errors related to the obfuscation process. No need to
781 // display a warning if the symbol was already declared here...
782 currentScope.declareIdentifier(symbol, token);
784 //?? why inc the refcount?? - that should be set when building the tree???
785 identifier = this.getIdentifier(symbol, currentScope);
786 identifier.refcount++;
789 token = this.ts.nextTok();
790 //assert token.getType() == Token.RP; // )
793 parseFunctionDeclaration : function()
795 print("PARSE FUNCTION");
798 var currentScope = false;
801 var b4braceNesting = this.braceNesting + 0;
803 //this.logR("<B>PARSING FUNCTION</B>");
804 currentScope = this.scopes[this.scopes.length-1];
806 token = this.ts.nextTok();
807 if (token.type == "NAME") {
808 if (this.mode == 'BUILDING_SYMBOL_TREE') {
809 // Get the name of the function and declare it in the current scope.
811 if (currentScope.getIdentifier(symbol) != false) {
812 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
814 currentScope.declareIdentifier(symbol,token);
816 token = this.ts.nextTok();
819 //assert token.getType() == Token.LP;
820 if (this.mode == 'BUILDING_SYMBOL_TREE') {
821 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
823 //println("STORING SCOPE" + this.ts.cursor);
825 this.indexedScopes[this.ts.cursor] = fnScope;
828 //qln("FETCHING SCOPE" + this.ts.cursor);
829 fnScope = this.indexedScopes[this.ts.cursor];
833 // Parse function arguments.
835 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
836 token = this.ts.nextTok();
837 // print ("FUNC ARGS: " + token.toString())
838 //assert token.getType() == Token.NAME ||
839 // token.getType() == Token.COMMA;
840 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
842 identifier = fnScope.declareIdentifier(symbol,token);
843 if (symbol == "$super" && argpos == 0) {
844 // Exception for Prototype 1.6...
845 identifier.preventMunging();
851 token = this.ts.nextTok();
852 print(token.toString());
853 // assert token.getType() == Token.LC;
856 token = this.ts.nextTok();
857 print(token.toString());
858 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
861 NOT SUPPORTED YET!?!!?!
863 // This is a hint. Hints are empty statements that look like
864 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
865 // to prevent specific symbols from getting obfuscated (some heretic
866 // implementations, such as Prototype 1.6, require specific variable
867 // names, such as $super for example, in order to work appropriately.
868 // Note: right now, only "nomunge" is supported in the right hand side
869 // of a hint. However, in the future, the right hand side may contain
872 String hints = token.getValue();
873 // Remove the leading and trailing quotes...
874 hints = hints.substring(1, hints.length() - 1).trim();
875 StringTokenizer st1 = new StringTokenizer(hints, ",");
876 while (st1.hasMoreTokens()) {
877 String hint = st1.nextToken();
878 int idx = hint.indexOf(':');
879 if (idx <= 0 || idx >= hint.length() - 1) {
880 if (mode == BUILDING_SYMBOL_TREE) {
881 // No need to report the error twice, hence the test...
882 this.warn("Invalid hint syntax: " + hint, true);
886 String variableName = hint.substring(0, idx).trim();
887 String variableType = hint.substring(idx + 1).trim();
888 if (mode == BUILDING_SYMBOL_TREE) {
889 fnScope.addHint(variableName, variableType);
890 } else if (mode == CHECKING_SYMBOL_TREE) {
891 identifier = fnScope.getIdentifier(variableName);
892 if (identifier != null) {
893 if (variableType.equals("nomunge")) {
894 identifier.preventMunging();
896 this.warn("Unsupported hint value: " + hint, true);
899 this.warn("Hint refers to an unknown identifier: " + hint, true);
906 this.parseScope(fnScope);
907 // now pop it off the stack!!!
909 this.braceNesting = b4braceNesting;
910 print("ENDFN -1: " + this.ts.lookTok(-1).toString());
911 print("ENDFN 0: " + this.ts.lookTok(0).toString());
912 print("ENDFN 1: " + this.ts.lookTok(1).toString());
915 protectScopeFromObfuscation : function(scope) {
916 //assert scope != null;
918 if (scope == this.globalScope) {
919 // The global scope does not get obfuscated,
920 // so we don't need to worry about it...
924 // Find the highest local scope containing the specified scope.
925 while (scope && scope.parent != this.globalScope) {
926 scope = scope.parent;
929 //assert scope.getParentScope() == globalScope;
930 scope.preventMunging();
933 getIdentifier: function(symbol, scope) {
935 while (scope != false) {
936 identifier = scope.getIdentifier(symbol);
937 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
941 scope = scope.parent;