1 //<Script type="text/javascript">
3 Scope = imports['JSDOC/Scope.js'].Scope;
8 * // FIXME - I need this to do next() without doccomments..
12 * Need to make this alot simpler...
14 * so debugging is possible.
17 * at present it just runs along the stream and finds stuff then calls parseExpr .. etc,,
20 * It would be better to parse blocks of code rather than the whole stream..
28 ScopeParser = function(ts) {
29 this.ts = ts; // {TokenStream}
32 this.indexedScopes = {};
33 this.timer = new Date() * 1;
37 // list of keywords that should not be used in object literals.
38 ScopeParser.idents = [
104 ScopeParser.prototype = {
106 timerPrint: function (str) {
107 var ntime = new Date() * 1;
108 var tdif = ntime -this.timer;
111 if (tdif > 100) { //slower ones..
114 println(pref+'['+tdif+']'+str);
118 //print('****************' + s);
119 this.warnings.push(s);
120 //println("WARNING:" + htmlescape(s) + "<BR>");
122 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
127 mode : "", //"BUILDING_SYMBOL_TREE",
129 indexedScopes : false,
136 buildSymbolTree : function()
141 this.braceNesting = 0;
147 this.globalScope = new Scope(-1, false, -1, '');
148 indexedScopes = { 0 : this.globalScope };
150 this.mode = 'BUILDING_SYMBOL_TREE';
151 this.parseScope(this.globalScope);
153 //print("---------------END PASS 1 ---------------- ");
156 mungeSymboltree : function()
163 // One problem with obfuscation resides in the use of undeclared
164 // and un-namespaced global symbols that are 3 characters or less
165 // in length. Here is an example:
167 // var declaredGlobalVar;
169 // function declaredGlobalFn() {
171 // localvar = abc; // abc is an undeclared global symbol
174 // In the example above, there is a slim chance that localvar may be
175 // munged to 'abc', conflicting with the undeclared global symbol
176 // abc, creating a potential bug. The following code detects such
177 // global symbols. This must be done AFTER the entire file has been
178 // parsed, and BEFORE munging the symbol tree. Note that declaring
179 // extra symbols in the global scope won't hurt.
181 // Note: Since we go through all the tokens to do this, we also use
182 // the opportunity to count how many times each identifier is used.
185 this.braceNesting = 0;
187 this.mode = 'PASS2_SYMBOL_TREE';
189 //println("MUNGING?");
191 this.parseScope(this.globalScope);
192 this.globalScope.munge();
198 print (" ".substring(0, this.braceNesting*2) + str);
200 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
204 //println("<B>LOG:</B>" + str + "<BR/>");
211 parseScope : function(scope) // parse a token stream..
213 //this.timerPrint("parseScope EnterScope");
214 //this.log(">>> ENTER SCOPE" + this.scopes.length);
220 var expressionBraceNesting = this.braceNesting + 0;
222 var parensNesting = 0;
224 var isObjectLitAr = [ false ];
226 this.scopes.push(scope);
228 var scopeIndent = '';
229 this.scopes.forEach(function() {
232 //print(scopeIndent + ">> ENTER SCOPE");
237 token = this.ts.lookTok(1);
239 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
240 //this.dumpToken(token , this.scopes, this.braceNesting);
241 //print('SCOPE:' + token.toString());
242 //this.log(token.data);
243 if (token.type == 'NAME') {
244 // print('*' + token.data);
246 switch(token.type + '.' + token.name) {
248 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
250 var vstart = this.ts.cursor +1;
252 //this.log("parseScope GOT VAR/CONST : " + token.toString());
254 token = this.ts.nextTok();
255 !this.debug|| print( token.toString());
257 if (!token) { // can return false at EOF!
260 if (token.name == "VAR" || token.data == ',') { // kludge..
263 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
264 if (token.type !="NAME") {
265 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
266 print(this.ts.tokens[i].toString());
269 print( "var without ident");
274 if (this.mode == "BUILDING_SYMBOL_TREE") {
275 identifier = scope.getIdentifier(token.data) ;
277 if (identifier == false) {
278 scope.declareIdentifier(token.data, token);
280 token.identifier = identifier;
281 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
285 token = this.ts.nextTok();
286 !this.debug|| print(token.toString());
288 assert token.getType() == Token.SEMI ||
289 token.getType() == Token.ASSIGN ||
290 token.getType() == Token.COMMA ||
291 token.getType() == Token.IN;
293 if (token.name == "IN") {
296 //var bn = this.braceNesting;
297 var bn = this.braceNesting;
298 this.parseExpression();
299 this.braceNesting = bn;
300 //this.braceNesting = bn;
301 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
303 token = this.ts.lookTok(1);
304 !this.debug|| print("AFTER EXP: " + token.toString());
305 if (token.data == ';') {
312 this.ts.dump(vstart , this.ts.cursor);
315 case "KEYW.FUNCTION":
316 //println("<i>"+token.data+"</i>");
317 var bn = this.braceNesting;
318 this.parseFunctionDeclaration();
319 this.braceNesting = bn;
322 case "PUNC.LEFT_CURLY": // {
323 //println("<i>"+token.data+"</i>");
324 isObjectLitAr.push(false);
327 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
330 case "PUNC.RIGHT_CURLY": // }
331 //println("<i>"+token.data+"</i>");
334 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
335 //assert braceNesting >= scope.getBra ceNesting();
337 if (this.braceNesting < expressionBraceNesting) {
338 var ls = this.scopes.pop();
340 // eat symbol if we are currently at {
341 if (this.ts.look(0).data == '{') {
345 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
351 //println("<i>"+token.data+"</i>");
352 if (this.mode == "BUILDING_SYMBOL_TREE") {
353 // Inside a 'with' block, it is impossible to figure out
354 // statically whether a symbol is a local variable or an
355 // object member. As a consequence, the only thing we can
356 // do is turn the obfuscation off for the highest scope
357 // containing the 'with' block.
358 this.protectScopeFromObfuscation(scope);
359 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
364 //println("<i>"+token.data+"</i>");
368 case Token.SPECIALCOMMENT:
369 if (mode == BUILDING_SYMBOL_TREE) {
370 protectScopeFromObfuscation(scope);
371 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
376 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
377 case "STRN.SINGLE_QUOTE":
378 //println("<i>"+token.data+"</i>");
379 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
380 // then we are in an object lit.. -> we need to flag the brace as such...
382 isObjectLitAr.push(true);
383 //print(">>>>>> OBJLIT REPUSH(true)");
385 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
387 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
388 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
389 // see if we can replace..
390 // remove the quotes..
391 // should do a bit more checking!!!! (what about wierd char's in the string..
392 var str = token.data.substring(1,token.data.length-1);
393 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
407 //print("DEAL WITH NAME:");
410 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
411 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
413 isObjectLitAr.push(true);
414 //print(">>>>>> OBJLIT REPUSH(true)");
415 //println("<i>"+token.data+"</i>");
418 // print("DEAL WITH obj lit:");
419 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
421 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
422 // skip, it's an object lit key..
423 //println("<i>"+token.data+"</i>");
428 // skip anyting with "." before it..!!
430 if (this.ts.lookTok(-1).data == ".") {
431 // skip, it's an object prop.
432 //println("<i>"+token.data+"</i>");
436 if (this.mode == 'PASS2_SYMBOL_TREE') {
438 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
440 //print ("MUNGE?" + symbol);
442 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
444 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
445 identifier = this.getIdentifier(symbol, scope);
447 if (identifier == false) {
448 // BUG!find out where builtin is defined...
449 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
450 // Here, we found an undeclared and un-namespaced symbol that is
451 // 3 characters or less in length. Declare it in the global scope.
452 // We don't need to declare longer symbols since they won't cause
453 // any conflict with other munged symbols.
454 this.globalScope.declareIdentifier(symbol, token);
455 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
458 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
460 token.identifier = identifier;
461 identifier.refcount++;
466 //println("<B>SID</B>");
468 if (token.type != 'KEYW') {
471 // print("Check eval:");
475 if (this.mode == 'BUILDING_SYMBOL_TREE') {
477 if (symbol == "eval") {
478 // look back one and see if we can find a comment!!!
479 if (this.ts.look(-1).type == "COMM") {
480 // look for eval:var:noreplace\n
482 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
484 var hi = _t.getIdentifier(a, scope);
485 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
487 // println("PROTECT "+a+" from munge");
497 this.protectScopeFromObfuscation(scope);
498 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);
510 //print("parseScope TOK : " + token.toString());
511 token = this.ts.nextTok();
512 //if (this.ts.nextT()) break;
515 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
519 parseExpression : function() {
521 // Parse the expression until we encounter a comma or a semi-colon
522 // in the same brace nesting, bracket nesting and paren nesting.
523 // Parse functions if any...
524 //println("<i>EXP</i><BR/>");
525 !this.debug || print("PARSE EXPR");
528 // for printing stuff..
537 var expressionBraceNesting = this.braceNesting + 0;
538 var bracketNesting = 0;
539 var parensNesting = 0;
541 var isObjectLitAr = [ false ];
543 currentScope = this.scopes[this.scopes.length-1];
545 var scopeIndent = '';
546 this.scopes.forEach(function() {
549 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
550 while (token = this.ts.lookTok()) {
555 // moved out of loop?
556 currentScope = this.scopes[this.scopes.length-1];
558 var scopeIndent = '';
559 this.scopes.forEach(function() {
564 //this.dumpToken(token, this.scopes, this.braceNesting );
565 //print('EXP' + this.expN + ':' + token.toString());
568 //println("<i>"+token.data+"</i>");
569 //this.log("EXP:" + token.data);
570 switch (token.type) {
576 if (this.braceNesting == expressionBraceNesting &&
577 bracketNesting == 0 &&
578 parensNesting == 0) {
579 print(scopeIndent + "<< EXIT EXPRESSION");
587 case '{': //Token.LC:
588 isObjectLitAr.push(false);
591 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
594 case '}': //Token.RC:
597 //print(">>>>> EXP POP" + this.braceNesting);
598 // assert braceNesting >= expressionBraceNesting;
601 case '[': //Token.LB:
605 case ']': //Token.RB:
609 case '(': //Token.LP:
613 case ')': //Token.RP:
619 case 'STRN': // used for object lit detection..
620 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
621 // then we are in an object lit.. -> we need to flag the brace as such...
623 isObjectLitAr.push(true);
624 //print(">>>>> EXP PUSH(true)");
629 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
630 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
631 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
632 // see if we can replace..
633 // remove the quotes..
634 var str = token.data.substring(1,token.data.length-1);
635 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
650 //print("in NAME = " + token.toString());
651 //print("in NAME 0: " + this.ts.look(0).toString());
652 //print("in NAME 2: " + this.ts.lookTok(2).toString());
653 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
654 // then we are in an object lit.. -> we need to flag the brace as such...
656 isObjectLitAr.push(true);
657 //print(">>>>> EXP PUSH(true)");
661 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
662 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
664 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
667 //print(this.ts.lookTok(0).data);
668 if (this.ts.lookTok(0).data == ".") {
673 if (this.mode == 'PASS2_SYMBOL_TREE') {
675 identifier = this.getIdentifier(symbol, currentScope);
676 //println("<B>??</B>");
677 if (identifier == false) {
679 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
680 // Here, we found an undeclared and un-namespaced symbol that is
681 // 3 characters or less in length. Declare it in the global scope.
682 // We don't need to declare longer symbols since they won't cause
683 // any conflict with other munged symbols.
684 this.globalScope.declareIdentifier(symbol, token);
685 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
687 //println("undeclared")
692 //println("<B>++</B>");
693 token.identifier = identifier;
694 identifier.refcount++;
703 //println("<B>EID</B>");
706 if (token.name == "FUNCTION") {
708 this.parseFunctionDeclaration();
715 if (this.mode == 'BUILDING_SYMBOL_TREE') {
717 if (symbol == "eval") {
718 if (this.ts.look(-1).type == 'COMM') {
719 // look for eval:var:noreplace\n
721 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
722 var hi = _t.getIdentifier(a, currentScope);
723 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
725 // println("PROTECT "+a+" from munge");
733 this.protectScopeFromObfuscation(currentScope);
734 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
743 if (!this.ts.nextTok()) break;
745 print(scopeIndent + "<< EXIT EXPRESSION");
750 parseCatch : function() {
757 //token = getToken(-1);
758 //assert token.getType() == Token.CATCH;
759 token = this.ts.nextTok();
760 //assert token.getType() == Token.LP; (
761 token = this.ts.nextTok();
762 //assert token.getType() == Token.NAME;
765 currentScope = this.scopes[this.scopes.length-1];
767 if (this.mode == 'BUILDING_SYMBOL_TREE') {
768 // We must declare the exception identifier in the containing function
769 // scope to avoid errors related to the obfuscation process. No need to
770 // display a warning if the symbol was already declared here...
771 currentScope.declareIdentifier(symbol, token);
773 //?? why inc the refcount?? - that should be set when building the tree???
774 identifier = this.getIdentifier(symbol, currentScope);
775 identifier.refcount++;
778 token = this.ts.nextTok();
779 //assert token.getType() == Token.RP; // )
782 parseFunctionDeclaration : function()
784 print("PARSE FUNCTION");
787 var currentScope = false;
790 var b4braceNesting = this.braceNesting + 0;
792 //this.logR("<B>PARSING FUNCTION</B>");
793 currentScope = this.scopes[this.scopes.length-1];
795 token = this.ts.nextTok();
796 if (token.type == "NAME") {
797 if (this.mode == 'BUILDING_SYMBOL_TREE') {
798 // Get the name of the function and declare it in the current scope.
800 if (currentScope.getIdentifier(symbol) != false) {
801 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
803 currentScope.declareIdentifier(symbol,token);
805 token = this.ts.nextTok();
808 //assert token.getType() == Token.LP;
809 if (this.mode == 'BUILDING_SYMBOL_TREE') {
810 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
812 //println("STORING SCOPE" + this.ts.cursor);
814 this.indexedScopes[this.ts.cursor] = fnScope;
817 //qln("FETCHING SCOPE" + this.ts.cursor);
818 fnScope = this.indexedScopes[this.ts.cursor];
822 // Parse function arguments.
824 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
825 token = this.ts.nextTok();
826 // print ("FUNC ARGS: " + token.toString())
827 //assert token.getType() == Token.NAME ||
828 // token.getType() == Token.COMMA;
829 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
831 identifier = fnScope.declareIdentifier(symbol,token);
832 if (symbol == "$super" && argpos == 0) {
833 // Exception for Prototype 1.6...
834 identifier.preventMunging();
840 token = this.ts.nextTok();
841 print(token.toString());
842 // assert token.getType() == Token.LC;
845 token = this.ts.nextTok();
846 print(token.toString());
847 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
850 NOT SUPPORTED YET!?!!?!
852 // This is a hint. Hints are empty statements that look like
853 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
854 // to prevent specific symbols from getting obfuscated (some heretic
855 // implementations, such as Prototype 1.6, require specific variable
856 // names, such as $super for example, in order to work appropriately.
857 // Note: right now, only "nomunge" is supported in the right hand side
858 // of a hint. However, in the future, the right hand side may contain
861 String hints = token.getValue();
862 // Remove the leading and trailing quotes...
863 hints = hints.substring(1, hints.length() - 1).trim();
864 StringTokenizer st1 = new StringTokenizer(hints, ",");
865 while (st1.hasMoreTokens()) {
866 String hint = st1.nextToken();
867 int idx = hint.indexOf(':');
868 if (idx <= 0 || idx >= hint.length() - 1) {
869 if (mode == BUILDING_SYMBOL_TREE) {
870 // No need to report the error twice, hence the test...
871 this.warn("Invalid hint syntax: " + hint, true);
875 String variableName = hint.substring(0, idx).trim();
876 String variableType = hint.substring(idx + 1).trim();
877 if (mode == BUILDING_SYMBOL_TREE) {
878 fnScope.addHint(variableName, variableType);
879 } else if (mode == CHECKING_SYMBOL_TREE) {
880 identifier = fnScope.getIdentifier(variableName);
881 if (identifier != null) {
882 if (variableType.equals("nomunge")) {
883 identifier.preventMunging();
885 this.warn("Unsupported hint value: " + hint, true);
888 this.warn("Hint refers to an unknown identifier: " + hint, true);
895 this.parseScope(fnScope);
896 // now pop it off the stack!!!
898 this.braceNesting = b4braceNesting;
899 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
900 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
901 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
904 protectScopeFromObfuscation : function(scope) {
905 //assert scope != null;
907 if (scope == this.globalScope) {
908 // The global scope does not get obfuscated,
909 // so we don't need to worry about it...
913 // Find the highest local scope containing the specified scope.
914 while (scope && scope.parent != this.globalScope) {
915 scope = scope.parent;
918 //assert scope.getParentScope() == globalScope;
919 scope.preventMunging();
922 getIdentifier: function(symbol, scope) {
924 while (scope != false) {
925 identifier = scope.getIdentifier(symbol);
926 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
930 scope = scope.parent;