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);
212 var scopeIndent = '';
213 this.scopes.forEach(function() {
217 token = this.ts.lookTok(1);
219 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
221 //this.log(token.data);
222 if (token.type == 'NAME') {
223 // print('*' + token.data);
225 switch(token.type + '.' + token.name) {
227 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
229 //this.log("parseScope GOT VAR/CONST : " + token.toString());
231 token = this.ts.nextTok();
232 !this.debug|| print( token.toString());
234 if (!token) { // can return false at EOF!
237 if (token.name == "VAR" || token.data == ',') { // kludge..
240 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
241 if (token.type !="NAME") {
242 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
243 print(this.ts.tokens[i].toString());
246 print( "var without ident");
251 if (this.mode == "BUILDING_SYMBOL_TREE") {
252 identifier = scope.getIdentifier(token.data) ;
254 if (identifier == false) {
255 scope.declareIdentifier(token.data, token);
257 token.identifier = identifier;
258 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
262 token = this.ts.nextTok();
263 !this.debug|| print(token.toString());
265 assert token.getType() == Token.SEMI ||
266 token.getType() == Token.ASSIGN ||
267 token.getType() == Token.COMMA ||
268 token.getType() == Token.IN;
270 if (token.name == "IN") {
273 //var bn = this.braceNesting;
274 this.parseExpression();
275 //this.braceNesting = bn;
276 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
278 token = this.ts.lookTok(1);
279 !this.debug|| print("AFTER EXP: " + token.toString());
280 if (token.data == ';') {
286 case "KEYW.FUNCTION":
287 //println("<i>"+token.data+"</i>");
288 var bn = this.braceNesting;
289 this.parseFunctionDeclaration();
290 this.braceNesting = bn;
293 case "PUNC.LEFT_CURLY": // {
294 //println("<i>"+token.data+"</i>");
295 isObjectLitAr.push(false);
298 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
301 case "PUNC.RIGHT_CURLY": // }
302 //println("<i>"+token.data+"</i>");
305 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
306 //assert braceNesting >= scope.getBra ceNesting();
308 if (this.braceNesting < expressionBraceNesting) {
309 var ls = this.scopes.pop();
311 // eat symbol if we are currently at {
312 if (this.ts.look(0).data == '{') {
316 //print("<<<<<<<EXIT SCOPE" +this.scopes.length);
322 //println("<i>"+token.data+"</i>");
323 if (this.mode == "BUILDING_SYMBOL_TREE") {
324 // Inside a 'with' block, it is impossible to figure out
325 // statically whether a symbol is a local variable or an
326 // object member. As a consequence, the only thing we can
327 // do is turn the obfuscation off for the highest scope
328 // containing the 'with' block.
329 this.protectScopeFromObfuscation(scope);
330 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
335 //println("<i>"+token.data+"</i>");
339 case Token.SPECIALCOMMENT:
340 if (mode == BUILDING_SYMBOL_TREE) {
341 protectScopeFromObfuscation(scope);
342 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
347 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
348 case "STRN.SINGLE_QUOTE":
349 //println("<i>"+token.data+"</i>");
350 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
351 // then we are in an object lit.. -> we need to flag the brace as such...
353 isObjectLitAr.push(true);
354 //print(">>>>>> OBJLIT REPUSH(true)");
356 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
358 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
359 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
360 // see if we can replace..
361 // remove the quotes..
362 // should do a bit more checking!!!! (what about wierd char's in the string..
363 var str = token.data.substring(1,token.data.length-1);
364 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
378 //print("DEAL WITH NAME:");
381 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
382 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
384 isObjectLitAr.push(true);
385 //print(">>>>>> OBJLIT REPUSH(true)");
386 //println("<i>"+token.data+"</i>");
389 // print("DEAL WITH obj lit:");
390 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
392 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
393 // skip, it's an object lit key..
394 //println("<i>"+token.data+"</i>");
399 // skip anyting with "." before it..!!
401 if (this.ts.lookTok(-1).data == ".") {
402 // skip, it's an object prop.
403 //println("<i>"+token.data+"</i>");
407 if (this.mode == 'PASS2_SYMBOL_TREE') {
409 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
411 //print ("MUNGE?" + symbol);
413 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
415 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
416 identifier = this.getIdentifier(symbol, scope);
418 if (identifier == false) {
419 // BUG!find out where builtin is defined...
420 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
421 // Here, we found an undeclared and un-namespaced symbol that is
422 // 3 characters or less in length. Declare it in the global scope.
423 // We don't need to declare longer symbols since they won't cause
424 // any conflict with other munged symbols.
425 this.globalScope.declareIdentifier(symbol, token);
426 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
429 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
431 token.identifier = identifier;
432 identifier.refcount++;
437 //println("<B>SID</B>");
439 if (token.type != 'KEYW') {
442 // print("Check eval:");
446 if (this.mode == 'BUILDING_SYMBOL_TREE') {
448 if (symbol == "eval") {
449 // look back one and see if we can find a comment!!!
450 if (this.ts.look(-1).type == "COMM") {
451 // look for eval:var:noreplace\n
453 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
455 var hi = _t.getIdentifier(a, scope);
456 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
458 // println("PROTECT "+a+" from munge");
468 this.protectScopeFromObfuscation(scope);
469 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);
481 //this.timerPrint("parseScope TOK : " + token.toString());
482 token = this.ts.nextTok();
483 //if (this.ts.nextT()) break;
486 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
490 parseExpression : function() {
492 // Parse the expression until we encounter a comma or a semi-colon
493 // in the same brace nesting, bracket nesting and paren nesting.
494 // Parse functions if any...
495 //println("<i>EXP</i><BR/>");
496 !this.debug || print("PARSE EXPR");
502 var expressionBraceNesting = this.braceNesting;
503 var bracketNesting = 0;
504 var parensNesting = 0;
506 var isObjectLitAr = [ false ];
507 while (token = this.ts.lookTok()) {
511 currentScope = this.scopes[this.scopes.length-1];
513 //println("<i>"+token.data+"</i>");
514 //this.log("EXP:" + token.data);
515 switch (token.type) {
521 if (this.braceNesting == expressionBraceNesting &&
522 bracketNesting == 0 &&
523 parensNesting == 0) {
531 case '{': //Token.LC:
532 isObjectLitAr.push(false);
535 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
538 case '}': //Token.RC:
541 //print(">>>>> EXP POP" + this.braceNesting);
542 // assert braceNesting >= expressionBraceNesting;
545 case '[': //Token.LB:
549 case ']': //Token.RB:
553 case '(': //Token.LP:
557 case ')': //Token.RP:
563 case 'STRN': // used for object lit detection..
564 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
565 // then we are in an object lit.. -> we need to flag the brace as such...
567 isObjectLitAr.push(true);
568 //print(">>>>> EXP PUSH(true)");
573 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
574 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
575 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
576 // see if we can replace..
577 // remove the quotes..
578 var str = token.data.substring(1,token.data.length-1);
579 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
594 print("in NAME = " + token.toString());
595 print("in NAME 0: " + this.ts.look(0).toString());
596 print("in NAME 2: " + this.ts.lookTok(2).toString());
597 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
598 // then we are in an object lit.. -> we need to flag the brace as such...
600 isObjectLitAr.push(true);
601 //print(">>>>> EXP PUSH(true)");
605 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
606 print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
608 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
611 //print(this.ts.lookTok(0).data);
612 if (this.ts.lookTok(0).data == ".") {
617 if (this.mode == 'PASS2_SYMBOL_TREE') {
619 identifier = this.getIdentifier(symbol, currentScope);
620 //println("<B>??</B>");
621 if (identifier == false) {
623 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
624 // Here, we found an undeclared and un-namespaced symbol that is
625 // 3 characters or less in length. Declare it in the global scope.
626 // We don't need to declare longer symbols since they won't cause
627 // any conflict with other munged symbols.
628 this.globalScope.declareIdentifier(symbol, token);
629 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
631 //println("undeclared")
636 //println("<B>++</B>");
637 token.identifier = identifier;
638 identifier.refcount++;
647 //println("<B>EID</B>");
650 if (token.name == "FUNCTION") {
652 this.parseFunctionDeclaration();
659 if (this.mode == 'BUILDING_SYMBOL_TREE') {
661 if (symbol == "eval") {
662 if (this.ts.look(-1).type == 'COMM') {
663 // look for eval:var:noreplace\n
665 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
666 var hi = _t.getIdentifier(a, currentScope);
667 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
669 // println("PROTECT "+a+" from munge");
677 this.protectScopeFromObfuscation(currentScope);
678 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
687 if (!this.ts.nextTok()) break;
692 parseCatch : function() {
699 //token = getToken(-1);
700 //assert token.getType() == Token.CATCH;
701 token = this.ts.nextTok();
702 //assert token.getType() == Token.LP; (
703 token = this.ts.nextTok();
704 //assert token.getType() == Token.NAME;
707 currentScope = this.scopes[this.scopes.length-1];
709 if (this.mode == 'BUILDING_SYMBOL_TREE') {
710 // We must declare the exception identifier in the containing function
711 // scope to avoid errors related to the obfuscation process. No need to
712 // display a warning if the symbol was already declared here...
713 currentScope.declareIdentifier(symbol, token);
715 //?? why inc the refcount?? - that should be set when building the tree???
716 identifier = this.getIdentifier(symbol, currentScope);
717 identifier.refcount++;
720 token = this.ts.nextTok();
721 //assert token.getType() == Token.RP; // )
724 parseFunctionDeclaration : function()
726 // print("PARSE FUNCTION");
729 var currentScope = false;
732 //this.logR("<B>PARSING FUNCTION</B>");
733 currentScope = this.scopes[this.scopes.length-1];
735 token = this.ts.nextTok();
736 if (token.type == "NAME") {
737 if (this.mode == 'BUILDING_SYMBOL_TREE') {
738 // Get the name of the function and declare it in the current scope.
740 if (currentScope.getIdentifier(symbol) != false) {
741 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
743 currentScope.declareIdentifier(symbol,token);
745 token = this.ts.nextTok();
748 //assert token.getType() == Token.LP;
749 if (this.mode == 'BUILDING_SYMBOL_TREE') {
750 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
752 //println("STORING SCOPE" + this.ts.cursor);
754 this.indexedScopes[this.ts.cursor] = fnScope;
757 //qln("FETCHING SCOPE" + this.ts.cursor);
758 fnScope = this.indexedScopes[this.ts.cursor];
762 // Parse function arguments.
764 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
765 token = this.ts.nextTok();
766 // print ("FUNC ARGS: " + token.toString())
767 //assert token.getType() == Token.NAME ||
768 // token.getType() == Token.COMMA;
769 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
771 identifier = fnScope.declareIdentifier(symbol,token);
772 if (symbol == "$super" && argpos == 0) {
773 // Exception for Prototype 1.6...
774 identifier.preventMunging();
780 token = this.ts.nextTok();
781 // assert token.getType() == Token.LC;
784 token = this.ts.nextTok();
785 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
788 NOT SUPPORTED YET!?!!?!
790 // This is a hint. Hints are empty statements that look like
791 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
792 // to prevent specific symbols from getting obfuscated (some heretic
793 // implementations, such as Prototype 1.6, require specific variable
794 // names, such as $super for example, in order to work appropriately.
795 // Note: right now, only "nomunge" is supported in the right hand side
796 // of a hint. However, in the future, the right hand side may contain
799 String hints = token.getValue();
800 // Remove the leading and trailing quotes...
801 hints = hints.substring(1, hints.length() - 1).trim();
802 StringTokenizer st1 = new StringTokenizer(hints, ",");
803 while (st1.hasMoreTokens()) {
804 String hint = st1.nextToken();
805 int idx = hint.indexOf(':');
806 if (idx <= 0 || idx >= hint.length() - 1) {
807 if (mode == BUILDING_SYMBOL_TREE) {
808 // No need to report the error twice, hence the test...
809 this.warn("Invalid hint syntax: " + hint, true);
813 String variableName = hint.substring(0, idx).trim();
814 String variableType = hint.substring(idx + 1).trim();
815 if (mode == BUILDING_SYMBOL_TREE) {
816 fnScope.addHint(variableName, variableType);
817 } else if (mode == CHECKING_SYMBOL_TREE) {
818 identifier = fnScope.getIdentifier(variableName);
819 if (identifier != null) {
820 if (variableType.equals("nomunge")) {
821 identifier.preventMunging();
823 this.warn("Unsupported hint value: " + hint, true);
826 this.warn("Hint refers to an unknown identifier: " + hint, true);
833 this.parseScope(fnScope);
834 // now pop it off the stack!!!
840 protectScopeFromObfuscation : function(scope) {
841 //assert scope != null;
843 if (scope == this.globalScope) {
844 // The global scope does not get obfuscated,
845 // so we don't need to worry about it...
849 // Find the highest local scope containing the specified scope.
850 while (scope && scope.parent != this.globalScope) {
851 scope = scope.parent;
854 //assert scope.getParentScope() == globalScope;
855 scope.preventMunging();
858 getIdentifier: function(symbol, scope) {
860 while (scope != false) {
861 identifier = scope.getIdentifier(symbol);
862 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
866 scope = scope.parent;