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 !this.debug || 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 mungeSymboltree : function()
143 // One problem with obfuscation resides in the use of undeclared
144 // and un-namespaced global symbols that are 3 characters or less
145 // in length. Here is an example:
147 // var declaredGlobalVar;
149 // function declaredGlobalFn() {
151 // localvar = abc; // abc is an undeclared global symbol
154 // In the example above, there is a slim chance that localvar may be
155 // munged to 'abc', conflicting with the undeclared global symbol
156 // abc, creating a potential bug. The following code detects such
157 // global symbols. This must be done AFTER the entire file has been
158 // parsed, and BEFORE munging the symbol tree. Note that declaring
159 // extra symbols in the global scope won't hurt.
161 // Note: Since we go through all the tokens to do this, we also use
162 // the opportunity to count how many times each identifier is used.
165 this.braceNesting = 0;
167 this.mode = 'PASS2_SYMBOL_TREE';
169 //println("MUNGING?");
171 this.parseScope(this.globalScope);
172 this.globalScope.munge();
178 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
182 //println("<B>LOG:</B>" + str + "<BR/>");
190 parseScope : function(scope) // parse a token stream..
192 //this.timerPrint("parseScope EnterScope");
198 var expressionBraceNesting = this.braceNesting;
199 var bracketNesting = 0;
200 var parensNesting = 0;
202 var isObjectLitAr = [ false ];
204 this.scopes.push(scope);
205 token = this.ts.lookTok(1);
207 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
209 !this.debug|| print(token.type + '.' + token.name+ ":" + token.data);
210 switch(token.type + '.' + token.name) {
212 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
214 //this.log("parseScope GOT VAR/CONST : " + token.toString());
216 token = this.ts.nextTok();
217 !this.debug|| print( token.toString());
219 if (!token) { // can return false at EOF!
222 if (token.name == "VAR") { // kludge..
225 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
226 if (token.type !="NAME") {
227 print(token.toString());
228 print( "var without ident");
233 if (this.mode == "BUILDING_SYMBOL_TREE") {
234 identifier = scope.getIdentifier(token.data) ;
236 if (identifier == false) {
237 scope.declareIdentifier(token.data, token);
239 token.identifier = identifier;
240 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
244 token = this.ts.nextTok();
245 !this.debug|| print(token.toString());
247 assert token.getType() == Token.SEMI ||
248 token.getType() == Token.ASSIGN ||
249 token.getType() == Token.COMMA ||
250 token.getType() == Token.IN;
252 if (token.name == "IN") {
255 this.parseExpression();
256 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
258 token = this.ts.lookTok(1);
259 !this.debug|| print("AFTER EXP: " + token.toString());
260 if (token.data == ';') {
266 case "KEYW.FUNCTION":
267 //println("<i>"+token.data+"</i>");
268 this.parseFunctionDeclaration();
271 case "KEYW.LEFT_CURLY": // {
272 //println("<i>"+token.data+"</i>");
273 isObjectLitAr.push(false);
274 print(">>>>>> OBJLIT PUSH(false)");
278 case "KEYW.RIGHT_CURLY": // }
279 //println("<i>"+token.data+"</i>");
282 print(">>>>>> OBJLIT POP(false)");
283 //assert braceNesting >= scope.getBraceNesting();
284 if (this.braceNesting == scope.braceN) {
285 var ls = this.scopes.pop();
292 //println("<i>"+token.data+"</i>");
293 if (this.mode == "BUILDING_SYMBOL_TREE") {
294 // Inside a 'with' block, it is impossible to figure out
295 // statically whether a symbol is a local variable or an
296 // object member. As a consequence, the only thing we can
297 // do is turn the obfuscation off for the highest scope
298 // containing the 'with' block.
299 this.protectScopeFromObfuscation(scope);
300 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
305 //println("<i>"+token.data+"</i>");
309 case Token.SPECIALCOMMENT:
310 if (mode == BUILDING_SYMBOL_TREE) {
311 protectScopeFromObfuscation(scope);
312 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
317 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
318 case "STRN.SINGLE_QUOTE":
319 //println("<i>"+token.data+"</i>");
320 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
321 // then we are in an object lit.. -> we need to flag the brace as such...
323 isObjectLitAr.push(true);
324 print(">>>>>> OBJLIT PUSH(true)");
326 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
328 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
329 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
330 // see if we can replace..
331 // remove the quotes..
332 // should do a bit more checking!!!! (what about wierd char's in the string..
333 var str = token.data.substring(1,token.data.length-1);
334 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
348 //print("DEAL WITH NAME:");
351 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
352 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
354 isObjectLitAr.push(true);
355 print(">>>>>> OBJLIT PUSH(true)");
356 //println("<i>"+token.data+"</i>");
359 // print("DEAL WITH obj lit:");
360 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
362 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
363 // skip, it's an object lit key..
364 //println("<i>"+token.data+"</i>");
369 // skip anyting with "." before it..!!
371 if (this.ts.lookTok(-1).data == ".") {
372 // skip, it's an object prop.
373 //println("<i>"+token.data+"</i>");
377 if (this.mode == 'PASS2_SYMBOL_TREE') {
379 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
381 //print ("MUNGE?" + symbol);
383 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
385 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
386 identifier = this.getIdentifier(symbol, scope);
388 if (identifier == false) {
389 // BUG!find out where builtin is defined...
390 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
391 // Here, we found an undeclared and un-namespaced symbol that is
392 // 3 characters or less in length. Declare it in the global scope.
393 // We don't need to declare longer symbols since they won't cause
394 // any conflict with other munged symbols.
395 this.globalScope.declareIdentifier(symbol, token);
396 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
399 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
401 token.identifier = identifier;
402 identifier.refcount++;
407 //println("<B>SID</B>");
409 if (token.type != 'KEYW') {
412 // print("Check eval:");
416 if (this.mode == 'BUILDING_SYMBOL_TREE') {
418 if (symbol == "eval") {
419 // look back one and see if we can find a comment!!!
420 if (this.ts.look(-1).type == "COMM") {
421 // look for eval:var:noreplace\n
423 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
425 var hi = _t.getIdentifier(a, scope);
426 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
428 // println("PROTECT "+a+" from munge");
438 this.protectScopeFromObfuscation(scope);
439 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);
451 //this.timerPrint("parseScope TOK : " + token.toString());
452 token = this.ts.nextTok();
453 //if (this.ts.nextT()) break;
459 parseExpression : function() {
461 // Parse the expression until we encounter a comma or a semi-colon
462 // in the same brace nesting, bracket nesting and paren nesting.
463 // Parse functions if any...
464 //println("<i>EXP</i><BR/>");
465 !this.debug || print("PARSE EXPR");
471 var expressionBraceNesting = this.braceNesting;
472 var bracketNesting = 0;
473 var parensNesting = 0;
475 var isObjectLitAr = [ false ];
476 while (token = this.ts.lookTok()) {
480 currentScope = this.scopes[this.scopes.length-1];
482 //println("<i>"+token.data+"</i>");
483 !this.debug|| print ("EXP" + token.toString());
484 switch (token.type) {
490 if (this.braceNesting == expressionBraceNesting &&
491 bracketNesting == 0 &&
492 parensNesting == 0) {
500 case '{': //Token.LC:
501 isObjectLitAr.push(false);
502 print(">>>>> OBJ PUSH(false)");
506 case '}': //Token.RC:
509 print(">>>>> OBJ POP");
510 // assert braceNesting >= expressionBraceNesting;
513 case '[': //Token.LB:
517 case ']': //Token.RB:
521 case '(': //Token.LP:
525 case ')': //Token.RP:
531 case 'STRN': // used for object lit detection..
532 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
533 // then we are in an object lit.. -> we need to flag the brace as such...
535 isObjectLitAr.push(true);
536 print(">>>>> OBJ PUSH(true)");
541 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
542 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
543 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
544 // see if we can replace..
545 // remove the quotes..
546 var str = token.data.substring(1,token.data.length-1);
547 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
562 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
563 // then we are in an object lit.. -> we need to flag the brace as such...
565 isObjectLitAr.push(true);
566 print(">>>>> OBJ PUSH(true)");
569 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
570 if (isInObjectLitAr && this.ts.lookTok(-1).data == "," && this.ts.lookTok(1).data == ":") {
574 if (this.ts.lookTok(-1).data == ".") {
579 if (this.mode == 'PASS2_SYMBOL_TREE') {
581 identifier = this.getIdentifier(symbol, currentScope);
582 //println("<B>??</B>");
583 if (identifier == false) {
585 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
586 // Here, we found an undeclared and un-namespaced symbol that is
587 // 3 characters or less in length. Declare it in the global scope.
588 // We don't need to declare longer symbols since they won't cause
589 // any conflict with other munged symbols.
590 this.globalScope.declareIdentifier(symbol, token);
591 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
593 //println("undeclared")
598 //println("<B>++</B>");
599 token.identifier = identifier;
600 identifier.refcount++;
609 //println("<B>EID</B>");
612 if (token.name == "FUNCTION") {
614 this.parseFunctionDeclaration();
621 if (this.mode == 'BUILDING_SYMBOL_TREE') {
623 if (symbol == "eval") {
624 if (this.ts.look(-1).type == 'COMM') {
625 // look for eval:var:noreplace\n
627 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
628 var hi = _t.getIdentifier(a, currentScope);
629 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
631 // println("PROTECT "+a+" from munge");
639 this.protectScopeFromObfuscation(currentScope);
640 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
649 if (!this.ts.nextTok()) break;
654 parseCatch : function() {
661 //token = getToken(-1);
662 //assert token.getType() == Token.CATCH;
663 token = this.ts.nextTok();
664 //assert token.getType() == Token.LP; (
665 token = this.ts.nextTok();
666 //assert token.getType() == Token.NAME;
669 currentScope = this.scopes[this.scopes.length-1];
671 if (this.mode == 'BUILDING_SYMBOL_TREE') {
672 // We must declare the exception identifier in the containing function
673 // scope to avoid errors related to the obfuscation process. No need to
674 // display a warning if the symbol was already declared here...
675 currentScope.declareIdentifier(symbol, token);
677 //?? why inc the refcount?? - that should be set when building the tree???
678 identifier = this.getIdentifier(symbol, currentScope);
679 identifier.refcount++;
682 token = this.ts.nextTok();
683 //assert token.getType() == Token.RP; // )
686 parseFunctionDeclaration : function()
688 // print("PARSE FUNCTION");
691 var currentScope = false;
694 //this.logR("<B>PARSING FUNCTION</B>");
695 currentScope = this.scopes[this.scopes.length-1];
697 token = this.ts.nextTok();
698 if (token.type == "NAME") {
699 if (this.mode == 'BUILDING_SYMBOL_TREE') {
700 // Get the name of the function and declare it in the current scope.
702 if (currentScope.getIdentifier(symbol) != false) {
703 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
705 currentScope.declareIdentifier(symbol,token);
707 token = this.ts.nextTok();
710 //assert token.getType() == Token.LP;
711 if (this.mode == 'BUILDING_SYMBOL_TREE') {
712 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
714 //println("STORING SCOPE" + this.ts.cursor);
716 this.indexedScopes[this.ts.cursor] = fnScope;
719 //println("FETCHING SCOPE" + this.ts.cursor);
720 fnScope = this.indexedScopes[this.ts.cursor];
723 // Parse function arguments.
725 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
726 token = this.ts.nextTok();
727 // print ("FUNC ARGS: " + token.toString())
728 //assert token.getType() == Token.NAME ||
729 // token.getType() == Token.COMMA;
730 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
732 identifier = fnScope.declareIdentifier(symbol,token);
733 if (symbol == "$super" && argpos == 0) {
734 // Exception for Prototype 1.6...
735 identifier.preventMunging();
741 token = this.ts.nextTok();
742 // assert token.getType() == Token.LC;
745 token = this.ts.nextTok();
746 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
749 NOT SUPPORTED YET!?!!?!
751 // This is a hint. Hints are empty statements that look like
752 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
753 // to prevent specific symbols from getting obfuscated (some heretic
754 // implementations, such as Prototype 1.6, require specific variable
755 // names, such as $super for example, in order to work appropriately.
756 // Note: right now, only "nomunge" is supported in the right hand side
757 // of a hint. However, in the future, the right hand side may contain
760 String hints = token.getValue();
761 // Remove the leading and trailing quotes...
762 hints = hints.substring(1, hints.length() - 1).trim();
763 StringTokenizer st1 = new StringTokenizer(hints, ",");
764 while (st1.hasMoreTokens()) {
765 String hint = st1.nextToken();
766 int idx = hint.indexOf(':');
767 if (idx <= 0 || idx >= hint.length() - 1) {
768 if (mode == BUILDING_SYMBOL_TREE) {
769 // No need to report the error twice, hence the test...
770 this.warn("Invalid hint syntax: " + hint, true);
774 String variableName = hint.substring(0, idx).trim();
775 String variableType = hint.substring(idx + 1).trim();
776 if (mode == BUILDING_SYMBOL_TREE) {
777 fnScope.addHint(variableName, variableType);
778 } else if (mode == CHECKING_SYMBOL_TREE) {
779 identifier = fnScope.getIdentifier(variableName);
780 if (identifier != null) {
781 if (variableType.equals("nomunge")) {
782 identifier.preventMunging();
784 this.warn("Unsupported hint value: " + hint, true);
787 this.warn("Hint refers to an unknown identifier: " + hint, true);
794 this.parseScope(fnScope);
795 // now pop it off the stack!!!
801 protectScopeFromObfuscation : function(scope) {
802 //assert scope != null;
804 if (scope == this.globalScope) {
805 // The global scope does not get obfuscated,
806 // so we don't need to worry about it...
810 // Find the highest local scope containing the specified scope.
811 while (scope && scope.parent != this.globalScope) {
812 scope = scope.parent;
815 //assert scope.getParentScope() == globalScope;
816 scope.preventMunging();
819 getIdentifier: function(symbol, scope) {
821 while (scope != false) {
822 identifier = scope.getIdentifier(symbol);
823 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
827 scope = scope.parent;