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 (token.name == "EVAL") {
538 //print(JSON.stringify(token, null,4));
539 // look back one and see if we can find a comment!!!
540 //if (this.ts.look(-1).type == "COMM") {
541 if (token.prefix && token.prefix.match(/eval/)) {
542 // look for eval:var:noreplace\n
545 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
546 //print("GOT: " + a);
547 var hi = _t.getIdentifier(a, thisScope, token);
548 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
550 // print("PROTECT "+a+" from munge");
551 //print(JSON.stringify(hi,null,4));
561 this.protectScopeFromObfuscation(thisScope);
562 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);
574 //print("parseScope TOK : " + token.toString());
575 token = this.ts.nextTok();
576 //if (this.ts.nextT()) break;
579 //print("<<< EXIT SCOPE");
580 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
584 parseExpression : function() {
586 // Parse the expression until we encounter a comma or a semi-colon
587 // in the same brace nesting, bracket nesting and paren nesting.
588 // Parse functions if any...
589 //println("<i>EXP</i><BR/>");
590 !this.debug || print("PARSE EXPR");
593 // for printing stuff..
602 var expressionBraceNesting = this.braceNesting + 0;
603 var bracketNesting = 0;
604 var parensNesting = 0;
606 var isObjectLitAr = [ false ];
608 currentScope = this.scopes[this.scopes.length-1];
611 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
612 while (token = this.ts.nextTok()) {
617 // moved out of loop?
618 currentScope = this.scopes[this.scopes.length-1];
620 var scopeIndent = '';
621 this.scopes.forEach(function() {
626 //this.dumpToken(token, this.scopes, this.braceNesting );
627 //print('EXPR' + token.toString());
630 //println("<i>"+token.data+"</i>");
631 //this.log("EXP:" + token.data);
632 switch (token.type) {
634 //print("EXPR-PUNC:" + token.toString());
639 //print("<< EXIT EXPRESSION");
647 case '(': //Token.LP:
648 case '{': //Token.LC:
649 case '[': //Token.LB:
650 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
651 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
652 //println("<i>"+token.data+"</i>");
656 for (var prop in token.props) {
657 if (token.props[prop].val[0].data == 'function') {
658 // parse a function..
659 this.ts = new TokenStream(token.props[prop].val);
661 this.parseFunctionDeclaration();
666 this.ts = new TokenStream(token.props[prop].val);
667 this.parseExpression();
672 // it's an object literal..
673 // the values could be replaced..
679 token.items.forEach(function(expr) {
680 _this.ts = new TokenStream(expr);
681 _this.parseExpression()
687 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
694 case ')': //Token.RP:
695 case ']': //Token.RB:
696 case '}': //Token.RB:
697 //print("<< EXIT EXPRESSION");
710 case 'STRN': // used for object lit detection..
711 //if (this.mode == 'BUILDING_SYMBOL_TREE')
712 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
720 if (this.mode == 'BUILDING_SYMBOL_TREE') {
722 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
724 //print("EXPR-NAME:" + token.toString());
727 //print("in NAME = " + token.toString());
728 //print("in NAME 0: " + this.ts.look(0).toString());
729 //print("in NAME 2: " + this.ts.lookTok(2).toString());
731 //print(this.ts.lookTok(-1).data);
733 if (this.ts.lookTok(-1).data == ".") {
737 if (symbol == 'this') {
741 if (this.mode == 'PASS2_SYMBOL_TREE') {
743 identifier = this.getIdentifier(symbol, currentScope, token);
744 //println("<B>??</B>");
745 if (identifier == false) {
747 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
748 // Here, we found an undeclared and un-namespaced symbol that is
749 // 3 characters or less in length. Declare it in the global scope.
750 // We don't need to declare longer symbols since they won't cause
751 // any conflict with other munged symbols.
752 this.globalScope.declareIdentifier(symbol, token);
753 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
754 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
757 //print("undeclared:" + token.toString())
762 //println("<B>++</B>");
763 token.identifier = identifier;
764 identifier.refcount++;
773 //println("<B>EID</B>");
775 //if (this.mode == 'BUILDING_SYMBOL_TREE')
776 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
778 //print('EXPR-KEYW:' + token.toString());
779 if (token.name == "FUNCTION") {
781 this.parseFunctionDeclaration();
788 if (this.mode == 'BUILDING_SYMBOL_TREE') {
790 if (token.name == "EVAL") {
791 //print(JSON.stringify(token,null,4));
792 if (token.prefix && token.prefix.match(/eval:var:/g)) {
793 // look for eval:var:noreplace\n
794 // print("GOT MATCH?");
796 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
798 //print("PROTECT: " + a);
801 var hi = _t.getIdentifier(a, currentScope, token);
802 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
804 // println("PROTECT "+a+" from munge");
812 this.protectScopeFromObfuscation(currentScope);
813 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
821 //if (this.mode == 'BUILDING_SYMBOL_TREE')
822 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
827 //print("<< EXIT EXPRESSION");
832 parseCatch : function() {
839 //token = getToken(-1);
840 //assert token.getType() == Token.CATCH;
841 token = this.ts.nextTok();
843 //print(JSON.stringify(token,null,4));
844 //assert token.getType() == Token.LP; (
845 //token = this.ts.nextTok();
846 //assert token.getType() == Token.NAME;
848 symbol = token.items[0][0].data;
849 currentScope = this.scopes[this.scopes.length-1];
851 if (this.mode == 'BUILDING_SYMBOL_TREE') {
852 // We must declare the exception identifier in the containing function
853 // scope to avoid errors related to the obfuscation process. No need to
854 // display a warning if the symbol was already declared here...
855 currentScope.declareIdentifier(symbol, token.items[0][0]);
857 //?? why inc the refcount?? - that should be set when building the tree???
858 identifier = this.getIdentifier(symbol, currentScope, token.items[0][0]);
859 identifier.refcount++;
862 token = this.ts.nextTok();
863 //assert token.getType() == Token.RP; // )
866 parseFunctionDeclaration : function()
868 //print("PARSE FUNCTION");
871 var currentScope = false;
874 var b4braceNesting = this.braceNesting + 0;
876 //this.logR("<B>PARSING FUNCTION</B>");
877 currentScope = this.scopes[this.scopes.length-1];
879 token = this.ts.nextTok();
880 if (token.type == "NAME") {
881 if (this.mode == 'BUILDING_SYMBOL_TREE') {
882 // Get the name of the function and declare it in the current scope.
884 if (currentScope.getIdentifier(symbol,token) != false) {
885 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
887 currentScope.declareIdentifier(symbol,token);
889 token = this.ts.nextTok();
893 // return function() {....
894 while (token.data != "(") {
895 print(token.toString());
896 token = this.ts.nextTok();
903 //assert token.getType() == Token.LP;
904 if (this.mode == 'BUILDING_SYMBOL_TREE') {
905 fnScope = new Scope(1, currentScope, token.n, '', token);
907 //println("STORING SCOPE" + this.ts.cursor);
909 this.indexedScopes[token.id] = fnScope;
912 //qln("FETCHING SCOPE" + this.ts.cursor);
913 fnScope = this.indexedScopes[token.id];
915 //if (this.mode == 'BUILDING_SYMBOL_TREE')
916 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
917 // Parse function arguments.
918 var args = token.items;
919 for (var argpos =0; argpos < args.length; argpos++) {
921 token = args[argpos][0];
922 //print ("FUNC ARGS: " + token.toString())
923 //assert token.getType() == Token.NAME ||
924 // token.getType() == Token.COMMA;
925 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
927 identifier = fnScope.declareIdentifier(symbol,token);
928 if (symbol == "$super" && argpos == 0) {
929 // Exception for Prototype 1.6...
930 identifier.preventMunging();
936 token = this.ts.nextTok();
937 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
939 //print(token.toString());
940 // assert token.getType() == Token.LC;
941 //this.braceNesting++;
943 //token = this.ts.nextTok();
944 //print(token.toString());
947 token.items.forEach(function(tar) {
948 _this.ts = new TokenStream(tar);
949 _this.parseScope(fnScope);
954 //print(JSON.stringify(this.ts,null,4));
955 //this.parseScope(fnScope);
957 // now pop it off the stack!!!
959 //this.braceNesting = b4braceNesting;
960 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
961 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
962 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
965 protectScopeFromObfuscation : function(scope) {
966 //assert scope != null;
968 if (scope == this.globalScope) {
969 // The global scope does not get obfuscated,
970 // so we don't need to worry about it...
974 // Find the highest local scope containing the specified scope.
975 while (scope && scope.parent != this.globalScope) {
976 scope = scope.parent;
979 //assert scope.getParentScope() == globalScope;
980 scope.preventMunging();
983 getIdentifier: function(symbol, scope, token) {
985 while (scope != false) {
986 identifier = scope.getIdentifier(symbol, token);
987 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
991 scope = scope.parent;