1 //<Script type="text/javascript">
3 Scope = imports.Scope.Scope;
4 TokenStream = imports.TokenStream.TokenStream;
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() {
230 // scopeIndent += ' ';
232 print(">> 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.
249 print('SCOPE-VAR:' + token.toString());
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());
256 print('SCOPE-VAR:' + 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 if (this.mode == 'BUILDING_SYMBOL_TREE')
317 print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
318 //println("<i>"+token.data+"</i>");
319 var bn = this.braceNesting;
320 this.parseFunctionDeclaration();
321 this.braceNesting = bn;
324 case "PUNC.LEFT_CURLY": // {
325 case "PUNC.LEFT_PAREN": // (
326 print('SCOPE-CURLY/PAREN:' + token.toString());
327 //println("<i>"+token.data+"</i>");
331 for (var prop in token.props) {
333 print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
334 if (token.props[prop].val[0].data == 'function') {
335 // parse a function..
336 this.ts = new TokenStream(token.props[prop].val);
337 this.parseFunctionDeclaration();
343 this.ts = new TokenStream(token.props[prop].val);
344 this.parseScope(scope);
349 // it's an object literal..
350 // the values could be replaced..
356 token.items.forEach(function(expr) {
357 _this.ts = new TokenStream(expr);
358 _this.parseExpression(scope)
361 //print("NOT PROPS"); Seed.quit();
363 //isObjectLitAr.push(false);
364 //this.braceNesting++;
366 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
369 case "PUNC.RIGHT_CURLY": // }
370 print("<< EXIT SCOPE");
373 //println("<i>"+token.data+"</i>");
376 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
377 //assert braceNesting >= scope.getBra ceNesting();
379 if (this.braceNesting < expressionBraceNesting) {
380 var ls = this.scopes.pop();
382 // eat symbol if we are currently at {
383 if (this.ts.look(0).data == '{') {
387 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
393 print('SCOPE-WITH:' + token.toString());
394 //println("<i>"+token.data+"</i>");
395 if (this.mode == "BUILDING_SYMBOL_TREE") {
396 // Inside a 'with' block, it is impossible to figure out
397 // statically whether a symbol is a local variable or an
398 // object member. As a consequence, the only thing we can
399 // do is turn the obfuscation off for the highest scope
400 // containing the 'with' block.
401 this.protectScopeFromObfuscation(scope);
402 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
407 print('SCOPE-CATCH:' + token.toString());
408 //println("<i>"+token.data+"</i>");
412 case Token.SPECIALCOMMENT:
413 if (mode == BUILDING_SYMBOL_TREE) {
414 protectScopeFromObfuscation(scope);
415 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
420 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
421 case "STRN.SINGLE_QUOTE":
422 print('SCOPE-STRING:' + token.toString());
423 //println("<i>"+token.data+"</i>");
425 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
426 // then we are in an object lit.. -> we need to flag the brace as such...
428 isObjectLitAr.push(true);
429 //print(">>>>>> OBJLIT REPUSH(true)");
431 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
433 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
434 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
435 // see if we can replace..
436 // remove the quotes..
437 // should do a bit more checking!!!! (what about wierd char's in the string..
438 var str = token.data.substring(1,token.data.length-1);
439 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
452 print('SCOPE-NAME:' + token.toString());
453 //print("DEAL WITH NAME:");
456 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
457 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
459 isObjectLitAr.push(true);
460 //print(">>>>>> OBJLIT REPUSH(true)");
461 //println("<i>"+token.data+"</i>");
464 // print("DEAL WITH obj lit:");
465 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
467 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
468 // skip, it's an object lit key..
469 //println("<i>"+token.data+"</i>");
474 // skip anyting with "." before it..!!
476 if (this.ts.lookTok(-1).data == ".") {
477 // skip, it's an object prop.
478 //println("<i>"+token.data+"</i>");
481 //print("SYMBOL: " + token.toString());
484 if (this.mode == 'PASS2_SYMBOL_TREE') {
486 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
488 //print ("MUNGE?" + symbol);
490 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
492 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
493 identifier = this.getIdentifier(symbol, scope);
495 if (identifier == false) {
496 // BUG!find out where builtin is defined...
497 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
498 // Here, we found an undeclared and un-namespaced symbol that is
499 // 3 characters or less in length. Declare it in the global scope.
500 // We don't need to declare longer symbols since they won't cause
501 // any conflict with other munged symbols.
502 this.globalScope.declareIdentifier(symbol, token);
503 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
506 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
508 token.identifier = identifier;
509 identifier.refcount++;
514 //println("<B>SID</B>");
516 if (token.type != 'KEYW') {
519 print('SCOPE-KEYW:' + token.toString());
520 // print("Check eval:");
524 if (this.mode == 'BUILDING_SYMBOL_TREE') {
526 if (symbol == "eval") {
527 // look back one and see if we can find a comment!!!
528 if (this.ts.look(-1).type == "COMM") {
529 // look for eval:var:noreplace\n
531 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
533 var hi = _t.getIdentifier(a, scope);
534 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
536 // println("PROTECT "+a+" from munge");
546 this.protectScopeFromObfuscation(scope);
547 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);
559 //print("parseScope TOK : " + token.toString());
560 token = this.ts.nextTok();
561 //if (this.ts.nextT()) break;
564 print("<<< EXIT SCOPE");
565 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
569 parseExpression : function() {
571 // Parse the expression until we encounter a comma or a semi-colon
572 // in the same brace nesting, bracket nesting and paren nesting.
573 // Parse functions if any...
574 //println("<i>EXP</i><BR/>");
575 !this.debug || print("PARSE EXPR");
578 // for printing stuff..
587 var expressionBraceNesting = this.braceNesting + 0;
588 var bracketNesting = 0;
589 var parensNesting = 0;
591 var isObjectLitAr = [ false ];
593 currentScope = this.scopes[this.scopes.length-1];
596 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
597 while (token = this.ts.nextTok()) {
602 // moved out of loop?
603 currentScope = this.scopes[this.scopes.length-1];
605 var scopeIndent = '';
606 this.scopes.forEach(function() {
611 //this.dumpToken(token, this.scopes, this.braceNesting );
612 print('EXP' + token.toString());
615 //println("<i>"+token.data+"</i>");
616 //this.log("EXP:" + token.data);
617 switch (token.type) {
619 print("EXPR-PUNC:" + token.toString());
624 print("<< EXIT EXPRESSION");
632 case '(': //Token.LP:
633 case '{': //Token.LC:
634 case '[': //Token.LB:
635 print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
636 //println("<i>"+token.data+"</i>");
640 for (var prop in token.props) {
641 if (token.props[prop].val.data == 'function') {
642 // parse a function..
643 this.parseFunctProp(token.props[prop]);
648 this.ts = new TokenStream(token.props[prop].val);
649 this.parseScope(currentScope);
654 // it's an object literal..
655 // the values could be replaced..
661 token.items.forEach(function(expr) {
662 _this.ts = new TokenStream(expr);
663 _this.parseExpression()
669 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
676 case ')': //Token.RP:
677 case ']': //Token.RB:
678 case '}': //Token.RB:
679 print("<< EXIT EXPRESSION");
692 case 'STRN': // used for object lit detection..
693 if (this.mode == 'BUILDING_SYMBOL_TREE')
694 print("EXPR-STR:" + JSON.stringify(token, null, 4));
695 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
696 // then we are in an object lit.. -> we need to flag the brace as such...
698 isObjectLitAr.push(true);
699 //print(">>>>> EXP PUSH(true)");
704 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
705 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
706 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
707 // see if we can replace..
708 // remove the quotes..
709 var str = token.data.substring(1,token.data.length-1);
710 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
723 if (this.mode == 'BUILDING_SYMBOL_TREE')
724 print("EXPR-NAME:" + JSON.stringify(token, null, 4));
726 //print("in NAME = " + token.toString());
727 //print("in NAME 0: " + this.ts.look(0).toString());
728 //print("in NAME 2: " + this.ts.lookTok(2).toString());
729 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
730 // then we are in an object lit.. -> we need to flag the brace as such...
732 isObjectLitAr.push(true);
733 //print(">>>>> EXP PUSH(true)");
737 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
738 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
740 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
743 //print(this.ts.lookTok(0).data);
744 if (this.ts.lookTok(0).data == ".") {
749 if (this.mode == 'PASS2_SYMBOL_TREE') {
751 identifier = this.getIdentifier(symbol, currentScope);
752 //println("<B>??</B>");
753 if (identifier == false) {
755 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
756 // Here, we found an undeclared and un-namespaced symbol that is
757 // 3 characters or less in length. Declare it in the global scope.
758 // We don't need to declare longer symbols since they won't cause
759 // any conflict with other munged symbols.
760 this.globalScope.declareIdentifier(symbol, token);
761 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
763 //println("undeclared")
768 //println("<B>++</B>");
769 token.identifier = identifier;
770 identifier.refcount++;
779 //println("<B>EID</B>");
781 if (this.mode == 'BUILDING_SYMBOL_TREE')
782 print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
783 if (token.name == "FUNCTION") {
785 this.parseFunctionDeclaration();
792 if (this.mode == 'BUILDING_SYMBOL_TREE') {
794 if (symbol == "eval") {
795 if (this.ts.look(-1).type == 'COMM') {
796 // look for eval:var:noreplace\n
798 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
799 var hi = _t.getIdentifier(a, currentScope);
800 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
802 // println("PROTECT "+a+" from munge");
810 this.protectScopeFromObfuscation(currentScope);
811 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
819 if (this.mode == 'BUILDING_SYMBOL_TREE')
820 print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
825 print("<< EXIT EXPRESSION");
830 parseCatch : function() {
837 //token = getToken(-1);
838 //assert token.getType() == Token.CATCH;
839 token = this.ts.nextTok();
840 //assert token.getType() == Token.LP; (
841 token = this.ts.nextTok();
842 //assert token.getType() == Token.NAME;
845 currentScope = this.scopes[this.scopes.length-1];
847 if (this.mode == 'BUILDING_SYMBOL_TREE') {
848 // We must declare the exception identifier in the containing function
849 // scope to avoid errors related to the obfuscation process. No need to
850 // display a warning if the symbol was already declared here...
851 currentScope.declareIdentifier(symbol, token);
853 //?? why inc the refcount?? - that should be set when building the tree???
854 identifier = this.getIdentifier(symbol, currentScope);
855 identifier.refcount++;
858 token = this.ts.nextTok();
859 //assert token.getType() == Token.RP; // )
862 parseFunctionDeclaration : function()
864 //print("PARSE FUNCTION");
867 var currentScope = false;
870 var b4braceNesting = this.braceNesting + 0;
872 //this.logR("<B>PARSING FUNCTION</B>");
873 currentScope = this.scopes[this.scopes.length-1];
875 token = this.ts.nextTok();
876 if (token.type == "NAME") {
877 if (this.mode == 'BUILDING_SYMBOL_TREE') {
878 // Get the name of the function and declare it in the current scope.
880 if (currentScope.getIdentifier(symbol) != false) {
881 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
883 currentScope.declareIdentifier(symbol,token);
885 token = this.ts.nextTok();
888 //assert token.getType() == Token.LP;
889 if (this.mode == 'BUILDING_SYMBOL_TREE') {
890 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
892 //println("STORING SCOPE" + this.ts.cursor);
894 this.indexedScopes[this.ts.cursor] = fnScope;
897 //qln("FETCHING SCOPE" + this.ts.cursor);
898 fnScope = this.indexedScopes[this.ts.cursor];
901 if (this.mode == 'BUILDING_SYMBOL_TREE')
902 print('FUNC-PARSE:' + JSON.stringify(token,null,4));
903 // Parse function arguments.
904 var args = token.items;
905 for (var argpos =0; argpos < args.length; argpos++) {
907 token = args[argpos][0];
908 // print ("FUNC ARGS: " + token.toString())
909 //assert token.getType() == Token.NAME ||
910 // token.getType() == Token.COMMA;
911 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
913 identifier = fnScope.declareIdentifier(symbol,token);
914 if (symbol == "$super" && argpos == 0) {
915 // Exception for Prototype 1.6...
916 identifier.preventMunging();
922 token = this.ts.nextTok();
923 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
925 //print(token.toString());
926 // assert token.getType() == Token.LC;
927 //this.braceNesting++;
929 //token = this.ts.nextTok();
930 //print(token.toString());
933 token.items.forEach(function(tar) {
934 _this.ts = new TokenStream(tar);
935 _this.parseScope(fnScope);
939 //print(JSON.stringify(this.ts,null,4));
940 //this.parseScope(fnScope);
942 // now pop it off the stack!!!
944 //this.braceNesting = b4braceNesting;
945 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
946 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
947 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
950 protectScopeFromObfuscation : function(scope) {
951 //assert scope != null;
953 if (scope == this.globalScope) {
954 // The global scope does not get obfuscated,
955 // so we don't need to worry about it...
959 // Find the highest local scope containing the specified scope.
960 while (scope && scope.parent != this.globalScope) {
961 scope = scope.parent;
964 //assert scope.getParentScope() == globalScope;
965 scope.preventMunging();
968 getIdentifier: function(symbol, scope) {
970 while (scope != false) {
971 identifier = scope.getIdentifier(symbol);
972 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
976 scope = scope.parent;