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;
144 print(JSON.stringify(this.ts.tokens, null,4));
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 ];
227 if (thisScope && thisScope.gid != this.scopes[this.scopes.length-1]) {
228 this.scopes.push(scope);
230 thisScope = this.scopes[this.scopes.length-1]
233 //var scopeIndent = '';
234 //this.scopes.forEach(function() {
235 // scopeIndent += ' ';
237 //print(">> ENTER SCOPE");
242 token = this.ts.lookTok(1);
244 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
245 //this.dumpToken(token , this.scopes, this.braceNesting);
246 //print('SCOPE:' + token.toString());
247 //this.log(token.data);
248 if (token.type == 'NAME') {
249 // print('*' + token.data);
251 switch(token.type + '.' + token.name) {
253 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
254 //print('SCOPE-VAR:' + token.toString());
255 var vstart = this.ts.cursor +1;
257 //this.log("parseScope GOT VAR/CONST : " + token.toString());
259 token = this.ts.nextTok();
260 //!this.debug|| print( token.toString());
261 print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
262 if (!token) { // can return false at EOF!
265 if (token.name == "VAR" || token.data == ',') { // kludge..
268 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
269 if (token.type != "NAME") {
270 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
271 print(this.ts.tokens[i].toString());
274 print( "var without ident");
279 if (this.mode == "BUILDING_SYMBOL_TREE") {
280 identifier = thisScope.getIdentifier(token.data,token) ;
282 if (identifier == false) {
283 thisScope.declareIdentifier(token.data, token);
285 token.identifier = identifier;
286 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
290 token = this.ts.nextTok();
291 !this.debug|| print(token.toString());
293 assert token.getType() == Token.SEMI ||
294 token.getType() == Token.ASSIGN ||
295 token.getType() == Token.COMMA ||
296 token.getType() == Token.IN;
298 if (token.name == "IN") {
301 //var bn = this.braceNesting;
302 var bn = this.braceNesting;
305 if (!token || token.type == 'VOID' || token.data == ',') {
309 token = this.ts.nextTok();
313 this.ts = new TokenStream(nts);
314 this.parseExpression();
318 this.braceNesting = bn;
319 //this.braceNesting = bn;
320 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
322 token = this.ts.lookTok(1);
323 !this.debug|| print("AFTER EXP: " + token.toString());
324 if (token.data == ';') {
331 //this.ts.dump(vstart , this.ts.cursor);
334 case "KEYW.FUNCTION":
335 //if (this.mode == 'BUILDING_SYMBOL_TREE')
336 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
337 //println("<i>"+token.data+"</i>");
338 var bn = this.braceNesting;
339 this.parseFunctionDeclaration();
340 this.braceNesting = bn;
343 case "PUNC.LEFT_CURLY": // {
344 case "PUNC.LEFT_PAREN": // (
345 case "PUNC.LEFT_BRACE": // [
346 //print('SCOPE-CURLY/PAREN:' + token.toString());
347 //println("<i>"+token.data+"</i>");
351 for (var prop in token.props) {
354 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
355 if (token.props[prop].val[0].data == 'function') {
356 // parse a function..
357 this.ts = new TokenStream(token.props[prop].val);
359 this.parseFunctionDeclaration();
365 this.ts = new TokenStream(token.props[prop].val);
366 this.parseExpression();
371 // it's an object literal..
372 // the values could be replaced..
378 token.items.forEach(function(expr) {
379 _this.ts = new TokenStream(expr);
380 _this.parseExpression()
383 //print("NOT PROPS"); Seed.quit();
385 //isObjectLitAr.push(false);
386 //this.braceNesting++;
388 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
391 case "PUNC.RIGHT_CURLY": // }
392 //print("<< EXIT SCOPE");
395 //println("<i>"+token.data+"</i>");
398 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
399 //assert braceNesting >= scope.getBra ceNesting();
401 if (this.braceNesting < expressionBraceNesting) {
402 var ls = this.scopes.pop();
404 // eat symbol if we are currently at {
405 if (this.ts.look(0).data == '{') {
409 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
415 //print('SCOPE-WITH:' + token.toString());
416 //println("<i>"+token.data+"</i>");
417 if (this.mode == "BUILDING_SYMBOL_TREE") {
418 // Inside a 'with' block, it is impossible to figure out
419 // statically whether a symbol is a local variable or an
420 // object member. As a consequence, the only thing we can
421 // do is turn the obfuscation off for the highest scope
422 // containing the 'with' block.
423 this.protectScopeFromObfuscation(thisScope);
424 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
429 //print('SCOPE-CATCH:' + token.toString());
430 //println("<i>"+token.data+"</i>");
434 case Token.SPECIALCOMMENT:
435 if (mode == BUILDING_SYMBOL_TREE) {
436 protectScopeFromObfuscation(scope);
437 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
442 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
443 case "STRN.SINGLE_QUOTE":
444 // print('SCOPE-STRING:' + token.toString());
445 //println("<i>"+token.data+"</i>");
447 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
448 // then we are in an object lit.. -> we need to flag the brace as such...
450 isObjectLitAr.push(true);
451 //print(">>>>>> OBJLIT REPUSH(true)");
453 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
455 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
456 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
457 // see if we can replace..
458 // remove the quotes..
459 // should do a bit more checking!!!! (what about wierd char's in the string..
460 var str = token.data.substring(1,token.data.length-1);
461 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
474 //print('SCOPE-NAME:' + token.toString());
475 //print("DEAL WITH NAME:");
478 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
481 // skip anyting with "." before it..!!
483 if (this.ts.lookTok(-1).data == ".") {
484 // skip, it's an object prop.
485 //println("<i>"+token.data+"</i>");
488 //print("SYMBOL: " + token.toString());
491 if (symbol == 'this') {
494 if (this.mode == 'PASS2_SYMBOL_TREE') {
496 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
498 //print ("MUNGE?" + symbol);
500 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
502 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
503 identifier = this.getIdentifier(symbol, thisScope, token);
505 if (identifier == false) {
506 // BUG!find out where builtin is defined...
507 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
508 // Here, we found an undeclared and un-namespaced symbol that is
509 // 3 characters or less in length. Declare it in the global scope.
510 // We don't need to declare longer symbols since they won't cause
511 // any conflict with other munged symbols.
512 this.globalScope.declareIdentifier(symbol, token);
513 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
516 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
518 token.identifier = identifier;
519 identifier.refcount++;
524 //println("<B>SID</B>");
526 if (token.type != 'KEYW') {
529 //print('SCOPE-KEYW:' + token.toString());
530 // print("Check eval:");
534 if (this.mode == 'BUILDING_SYMBOL_TREE') {
536 if (symbol == "eval") {
537 // look back one and see if we can find a comment!!!
538 //if (this.ts.look(-1).type == "COMM") {
539 if (token.prefix && token.prefix.match('/eval/')) {
540 // look for eval:var:noreplace\n
542 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
544 var hi = _t.getIdentifier(a, thisScope, token);
545 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
547 // println("PROTECT "+a+" from munge");
557 this.protectScopeFromObfuscation(thisScope);
558 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);
570 //print("parseScope TOK : " + token.toString());
571 token = this.ts.nextTok();
572 //if (this.ts.nextT()) break;
575 //print("<<< EXIT SCOPE");
576 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
580 parseExpression : function() {
582 // Parse the expression until we encounter a comma or a semi-colon
583 // in the same brace nesting, bracket nesting and paren nesting.
584 // Parse functions if any...
585 //println("<i>EXP</i><BR/>");
586 !this.debug || print("PARSE EXPR");
589 // for printing stuff..
598 var expressionBraceNesting = this.braceNesting + 0;
599 var bracketNesting = 0;
600 var parensNesting = 0;
602 var isObjectLitAr = [ false ];
604 currentScope = this.scopes[this.scopes.length-1];
607 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
608 while (token = this.ts.nextTok()) {
613 // moved out of loop?
614 currentScope = this.scopes[this.scopes.length-1];
616 var scopeIndent = '';
617 this.scopes.forEach(function() {
622 //this.dumpToken(token, this.scopes, this.braceNesting );
623 //print('EXP' + token.toString());
626 //println("<i>"+token.data+"</i>");
627 //this.log("EXP:" + token.data);
628 switch (token.type) {
630 //print("EXPR-PUNC:" + token.toString());
635 //print("<< EXIT EXPRESSION");
643 case '(': //Token.LP:
644 case '{': //Token.LC:
645 case '[': //Token.LB:
646 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
647 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
648 //println("<i>"+token.data+"</i>");
652 for (var prop in token.props) {
653 if (token.props[prop].val[0].data == 'function') {
654 // parse a function..
655 this.ts = new TokenStream(token.props[prop].val);
657 this.parseFunctionDeclaration();
662 this.ts = new TokenStream(token.props[prop].val);
663 this.parseExpression();
668 // it's an object literal..
669 // the values could be replaced..
675 token.items.forEach(function(expr) {
676 _this.ts = new TokenStream(expr);
677 _this.parseExpression()
683 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
690 case ')': //Token.RP:
691 case ']': //Token.RB:
692 case '}': //Token.RB:
693 //print("<< EXIT EXPRESSION");
706 case 'STRN': // used for object lit detection..
707 //if (this.mode == 'BUILDING_SYMBOL_TREE')
708 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
716 if (this.mode == 'BUILDING_SYMBOL_TREE') {
718 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
720 //print("EXPR-NAME:" + token.toString());
723 //print("in NAME = " + token.toString());
724 //print("in NAME 0: " + this.ts.look(0).toString());
725 //print("in NAME 2: " + this.ts.lookTok(2).toString());
727 //print(this.ts.lookTok(-1).data);
729 if (this.ts.lookTok(-1).data == ".") {
733 if (symbol == 'this') {
737 if (this.mode == 'PASS2_SYMBOL_TREE') {
739 identifier = this.getIdentifier(symbol, currentScope, token);
740 //println("<B>??</B>");
741 if (identifier == false) {
743 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
744 // Here, we found an undeclared and un-namespaced symbol that is
745 // 3 characters or less in length. Declare it in the global scope.
746 // We don't need to declare longer symbols since they won't cause
747 // any conflict with other munged symbols.
748 this.globalScope.declareIdentifier(symbol, token);
749 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
750 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
753 //print("undeclared:" + token.toString())
758 //println("<B>++</B>");
759 token.identifier = identifier;
760 identifier.refcount++;
769 //println("<B>EID</B>");
771 //if (this.mode == 'BUILDING_SYMBOL_TREE')
772 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
773 if (token.name == "FUNCTION") {
775 this.parseFunctionDeclaration();
782 if (this.mode == 'BUILDING_SYMBOL_TREE') {
784 if (symbol == "eval") {
785 if (token.prefix && token.prefix.match('/eval/')) {
786 // look for eval:var:noreplace\n
788 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
789 var hi = _t.getIdentifier(a, currentScope, token);
790 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
792 // println("PROTECT "+a+" from munge");
800 this.protectScopeFromObfuscation(currentScope);
801 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
809 //if (this.mode == 'BUILDING_SYMBOL_TREE')
810 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
815 //print("<< EXIT EXPRESSION");
820 parseCatch : function() {
827 //token = getToken(-1);
828 //assert token.getType() == Token.CATCH;
829 token = this.ts.nextTok();
830 //assert token.getType() == Token.LP; (
831 //token = this.ts.nextTok();
832 //assert token.getType() == Token.NAME;
834 symbol = token.items[0].data;
835 currentScope = this.scopes[this.scopes.length-1];
837 if (this.mode == 'BUILDING_SYMBOL_TREE') {
838 // We must declare the exception identifier in the containing function
839 // scope to avoid errors related to the obfuscation process. No need to
840 // display a warning if the symbol was already declared here...
841 currentScope.declareIdentifier(symbol, token);
843 //?? why inc the refcount?? - that should be set when building the tree???
844 identifier = this.getIdentifier(symbol, currentScope, token);
845 identifier.refcount++;
848 token = this.ts.nextTok();
849 //assert token.getType() == Token.RP; // )
852 parseFunctionDeclaration : function()
854 //print("PARSE FUNCTION");
857 var currentScope = false;
860 var b4braceNesting = this.braceNesting + 0;
862 //this.logR("<B>PARSING FUNCTION</B>");
863 currentScope = this.scopes[this.scopes.length-1];
865 token = this.ts.nextTok();
866 if (token.type == "NAME") {
867 if (this.mode == 'BUILDING_SYMBOL_TREE') {
868 // Get the name of the function and declare it in the current scope.
870 if (currentScope.getIdentifier(symbol,token) != false) {
871 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
873 currentScope.declareIdentifier(symbol,token);
875 token = this.ts.nextTok();
877 // return function() {....
878 if (token.name == "RETURN") {
879 token = this.ts.nextTok();
881 if (token.name == "FUNCTION") {
882 token = this.ts.nextTok();
884 //assert token.getType() == Token.LP;
885 if (this.mode == 'BUILDING_SYMBOL_TREE') {
886 fnScope = new Scope(1, currentScope, token.n, '', token);
888 //println("STORING SCOPE" + this.ts.cursor);
890 this.indexedScopes[token.id] = fnScope;
893 //qln("FETCHING SCOPE" + this.ts.cursor);
894 fnScope = this.indexedScopes[token.id];
896 //if (this.mode == 'BUILDING_SYMBOL_TREE')
897 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
898 // Parse function arguments.
899 var args = token.items;
900 for (var argpos =0; argpos < args.length; argpos++) {
902 token = args[argpos][0];
903 //print ("FUNC ARGS: " + token.toString())
904 //assert token.getType() == Token.NAME ||
905 // token.getType() == Token.COMMA;
906 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
908 identifier = fnScope.declareIdentifier(symbol,token);
909 if (symbol == "$super" && argpos == 0) {
910 // Exception for Prototype 1.6...
911 identifier.preventMunging();
917 token = this.ts.nextTok();
918 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
920 //print(token.toString());
921 // assert token.getType() == Token.LC;
922 //this.braceNesting++;
924 //token = this.ts.nextTok();
925 //print(token.toString());
928 token.items.forEach(function(tar) {
929 _this.ts = new TokenStream(tar);
930 _this.parseScope(fnScope);
935 //print(JSON.stringify(this.ts,null,4));
936 //this.parseScope(fnScope);
938 // now pop it off the stack!!!
940 //this.braceNesting = b4braceNesting;
941 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
942 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
943 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
946 protectScopeFromObfuscation : function(scope) {
947 //assert scope != null;
949 if (scope == this.globalScope) {
950 // The global scope does not get obfuscated,
951 // so we don't need to worry about it...
955 // Find the highest local scope containing the specified scope.
956 while (scope && scope.parent != this.globalScope) {
957 scope = scope.parent;
960 //assert scope.getParentScope() == globalScope;
961 scope.preventMunging();
964 getIdentifier: function(symbol, scope, token) {
966 while (scope != false) {
967 identifier = scope.getIdentifier(symbol, token);
968 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
972 scope = scope.parent;