1 //<Script type="text/javascript">
3 Scope = imports.Scope.Scope;
4 TokenStream = imports.TokenStream.TokenStream;
8 * This code now uses the collapsed tree
14 ScopeParser = function(ts) {
15 this.ts = ts; // {TokenStream}
18 this.timer = new Date() * 1;
22 // list of keywords that should not be used in object literals.
23 ScopeParser.idents = [
89 ScopeParser.prototype = {
91 timerPrint: function (str) {
92 var ntime = new Date() * 1;
93 var tdif = ntime -this.timer;
96 if (tdif > 100) { //slower ones..
99 println(pref+'['+tdif+']'+str);
103 //print('****************' + s);
104 this.warnings.push(s);
105 //println("WARNING:" + htmlescape(s) + "<BR>");
107 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
111 mode : "", //"BUILDING_SYMBOL_TREE",
113 indexedScopes : false,
120 buildSymbolTree : function()
125 this.braceNesting = 0;
127 // print(JSON.stringify(this.ts.tokens, null,4));
130 this.globalScope = new Scope(-1, false, -1, '');
131 this.indexedScopes = { 0 : this.globalScope };
133 this.mode = 'BUILDING_SYMBOL_TREE';
134 this.parseScope(this.globalScope);
136 //print("---------------END PASS 1 ---------------- ");
139 mungeSymboltree : function()
146 // One problem with obfuscation resides in the use of undeclared
147 // and un-namespaced global symbols that are 3 characters or less
148 // in length. Here is an example:
150 // var declaredGlobalVar;
152 // function declaredGlobalFn() {
154 // localvar = abc; // abc is an undeclared global symbol
157 // In the example above, there is a slim chance that localvar may be
158 // munged to 'abc', conflicting with the undeclared global symbol
159 // abc, creating a potential bug. The following code detects such
160 // global symbols. This must be done AFTER the entire file has been
161 // parsed, and BEFORE munging the symbol tree. Note that declaring
162 // extra symbols in the global scope won't hurt.
164 // Note: Since we go through all the tokens to do this, we also use
165 // the opportunity to count how many times each identifier is used.
168 this.braceNesting = 0;
169 this.mode = 'PASS2_SYMBOL_TREE';
171 //println("MUNGING?");
173 this.parseScope(this.globalScope);
175 //this.globalScope.dump();
178 this.globalScope.munge();
184 print (" ".substring(0, this.braceNesting*2) + str);
186 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
190 //println("<B>LOG:</B>" + str + "<BR/>");
197 parseScope : function(scope) // parse a token stream..
199 //this.timerPrint("parseScope EnterScope");
200 //this.log(">>> ENTER SCOPE" + this.scopes.length);
206 var expressionBraceNesting = this.braceNesting + 0;
208 var parensNesting = 0;
210 var isObjectLitAr = [ false ];
214 //var scopeIndent = '';
215 //this.scopes.forEach(function() {
216 // scopeIndent += ' ';
218 //print(">> ENTER SCOPE");
223 token = this.ts.lookTok(1);
225 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
226 //this.dumpToken(token , this.scopes, this.braceNesting);
227 //print('SCOPE:' + token.toString());
228 //this.log(token.data);
229 if (token.type == 'NAME') {
230 // print('*' + token.data);
232 switch(token.type + '.' + token.name) {
234 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
235 //print('SCOPE-VAR:' + token.toString());
236 var vstart = this.ts.cursor +1;
238 //this.log("parseScope GOT VAR/CONST : " + token.toString());
240 token = this.ts.nextTok();
241 //!this.debug|| print( token.toString());
242 // print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
243 if (!token) { // can return false at EOF!
246 if (token.name == "VAR" || token.data == ',') { // kludge..
249 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
250 if (token.type != "NAME") {
251 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
252 print(this.ts.tokens[i].toString());
255 print( "var without ident");
260 if (this.mode == "BUILDING_SYMBOL_TREE") {
261 identifier = scope.getIdentifier(token.data,token) ;
263 if (identifier == false) {
264 scope.declareIdentifier(token.data, token);
266 token.identifier = identifier;
267 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
271 token = this.ts.nextTok();
272 !this.debug|| print(token.toString());
274 assert token.getType() == Token.SEMI ||
275 token.getType() == Token.ASSIGN ||
276 token.getType() == Token.COMMA ||
277 token.getType() == Token.IN;
279 if (token.name == "IN") {
282 //var bn = this.braceNesting;
283 var bn = this.braceNesting;
286 if (!token || token.type == 'VOID' || token.data == ',') {
290 token = this.ts.nextTok();
294 this.ts = new TokenStream(nts);
295 this.parseExpression(scope);
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);
305 // print("AFTER EXP: " + token.toString());
306 if (token.data == ';') {
313 //this.ts.dump(vstart , this.ts.cursor);
318 case "KEYW.FUNCTION":
319 //if (this.mode == 'BUILDING_SYMBOL_TREE')
320 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
321 //println("<i>"+token.data+"</i>");
322 var bn = this.braceNesting;
323 this.parseFunctionDeclaration(scope);
324 this.braceNesting = bn;
327 case "PUNC.LEFT_CURLY": // {
328 case "PUNC.LEFT_PAREN": // (
329 case "PUNC.LEFT_BRACE": // [
330 //print('SCOPE-CURLY/PAREN:' + token.toString());
331 //println("<i>"+token.data+"</i>");
335 for (var prop in token.props) {
338 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
339 if (token.props[prop].val[0].data == 'function') {
340 // parse a function..
341 this.ts = new TokenStream(token.props[prop].val);
343 this.parseFunctionDeclaration(scope);
349 this.ts = new TokenStream(token.props[prop].val);
350 this.parseExpression(scope);
355 // it's an object literal..
356 // the values could be replaced..
362 token.items.forEach(function(expr) {
363 //print(JSON.stringify(expr, null,4));
364 _this.ts = new TokenStream(expr);
365 //if (curTS.data == '(') {
366 _this.parseScope(scope)
368 // _this.parseExpression(scope)
373 //print("NOT PROPS"); Seed.quit();
375 //isObjectLitAr.push(false);
376 //this.braceNesting++;
378 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
381 case "PUNC.RIGHT_CURLY": // }
382 //print("<< EXIT SCOPE");
386 //print('SCOPE-WITH:' + token.toString());
387 //println("<i>"+token.data+"</i>");
388 if (this.mode == "BUILDING_SYMBOL_TREE") {
389 // Inside a 'with' block, it is impossible to figure out
390 // statically whether a symbol is a local variable or an
391 // object member. As a consequence, the only thing we can
392 // do is turn the obfuscation off for the highest scope
393 // containing the 'with' block.
394 this.protectScopeFromObfuscation(scope);
395 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
400 //print('SCOPE-CATCH:' + token.toString());
401 //println("<i>"+token.data+"</i>");
402 this.parseCatch(scope);
405 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
406 case "STRN.SINGLE_QUOTE":
407 // print('SCOPE-STRING:' + token.toString());
408 //println("<i>"+token.data+"</i>");
410 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
411 // then we are in an object lit.. -> we need to flag the brace as such...
413 isObjectLitAr.push(true);
414 //print(">>>>>> OBJLIT REPUSH(true)");
416 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
418 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
419 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
420 // see if we can replace..
421 // remove the quotes..
422 // should do a bit more checking!!!! (what about wierd char's in the string..
423 var str = token.data.substring(1,token.data.length-1);
424 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
435 //print('SCOPE-NAME:' + token.toString());
436 //print("DEAL WITH NAME:");
438 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
439 // skip anyting with "." before it..!!
441 if (this.ts.lookTok(-1).data == ".") {
442 // skip, it's an object prop.
443 //println("<i>"+token.data+"</i>");
446 //print("SYMBOL: " + token.toString());
449 if (symbol == 'this') {
452 if (this.mode == 'PASS2_SYMBOL_TREE') {
454 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
456 //print ("MUNGE?" + symbol);
458 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
460 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
461 identifier = this.getIdentifier(symbol, scope, token);
463 if (identifier == false) {
464 // BUG!find out where builtin is defined...
465 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
466 // Here, we found an undeclared and un-namespaced symbol that is
467 // 3 characters or less in length. Declare it in the global scope.
468 // We don't need to declare longer symbols since they won't cause
469 // any conflict with other munged symbols.
470 this.globalScope.declareIdentifier(symbol, token);
471 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
474 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
476 token.identifier = identifier;
477 identifier.refcount++;
482 //println("<B>SID</B>");
484 if (token.type != 'KEYW') {
487 //print('SCOPE-KEYW:' + token.toString());
488 // print("Check eval:");
492 if (this.mode == 'BUILDING_SYMBOL_TREE') {
494 if (token.name == "EVAL") {
496 //print(JSON.stringify(token, null,4));
497 // look back one and see if we can find a comment!!!
498 //if (this.ts.look(-1).type == "COMM") {
499 if (token.prefix && token.prefix.match(/eval/)) {
500 // look for eval:var:noreplace\n
503 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
504 //print("GOT: " + a);
505 var hi = _t.getIdentifier(a, scope, token);
506 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
508 // print("PROTECT "+a+" from munge");
509 //print(JSON.stringify(hi,null,4));
519 this.protectScopeFromObfuscation(scope);
520 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);
532 //print("parseScope TOK : " + token.toString());
533 token = this.ts.nextTok();
534 //if (this.ts.nextT()) break;
537 //print("<<< EXIT SCOPE");
538 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
542 parseExpression : function(scope) {
544 // Parse the expression until we encounter a comma or a semi-colon
545 // in the same brace nesting, bracket nesting and paren nesting.
546 // Parse functions if any...
547 //println("<i>EXP</i><BR/>");
548 !this.debug || print("PARSE EXPR");
551 // for printing stuff..
560 var expressionBraceNesting = this.braceNesting + 0;
561 var bracketNesting = 0;
562 var parensNesting = 0;
564 var isObjectLitAr = [ false ];
569 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
570 while (token = this.ts.nextTok()) {
575 // moved out of loop?
576 currentScope = this.scopes[this.scopes.length-1];
578 var scopeIndent = '';
579 this.scopes.forEach(function() {
584 //this.dumpToken(token, this.scopes, this.braceNesting );
585 //print('EXPR' + token.toString());
588 //println("<i>"+token.data+"</i>");
589 //this.log("EXP:" + token.data);
590 switch (token.type) {
592 //print("EXPR-PUNC:" + token.toString());
597 //print("<< EXIT EXPRESSION");
605 case '(': //Token.LP:
606 case '{': //Token.LC:
607 case '[': //Token.LB:
608 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
609 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
610 //println("<i>"+token.data+"</i>");
614 for (var prop in token.props) {
615 if (!token.props[prop].val.length) {
616 print(JSON.stringify(token.props, null,4));
619 if (token.props[prop].val[0].data == 'function') {
620 // parse a function..
621 this.ts = new TokenStream(token.props[prop].val);
623 this.parseFunctionDeclaration(scope);
628 this.ts = new TokenStream(token.props[prop].val);
629 this.parseExpression(scope);
634 // it's an object literal..
635 // the values could be replaced..
641 token.items.forEach(function(expr) {
642 _this.ts = new TokenStream(expr);
643 _this.parseExpression(scope)
649 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
656 case ')': //Token.RP:
657 case ']': //Token.RB:
658 case '}': //Token.RB:
659 //print("<< EXIT EXPRESSION");
672 case 'STRN': // used for object lit detection..
673 //if (this.mode == 'BUILDING_SYMBOL_TREE')
674 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
682 if (this.mode == 'BUILDING_SYMBOL_TREE') {
684 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
686 //print("EXPR-NAME:" + token.toString());
689 //print("in NAME = " + token.toString());
690 //print("in NAME 0: " + this.ts.look(0).toString());
691 //print("in NAME 2: " + this.ts.lookTok(2).toString());
693 //print(this.ts.lookTok(-1).data);
695 if (this.ts.lookTok(-1).data == ".") {
699 if (symbol == 'this') {
703 if (this.mode == 'PASS2_SYMBOL_TREE') {
705 identifier = this.getIdentifier(symbol, scope, token);
706 //println("<B>??</B>");
707 if (identifier == false) {
709 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
710 // Here, we found an undeclared and un-namespaced symbol that is
711 // 3 characters or less in length. Declare it in the global scope.
712 // We don't need to declare longer symbols since they won't cause
713 // any conflict with other munged symbols.
714 this.globalScope.declareIdentifier(symbol, token);
715 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
716 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
719 //print("undeclared:" + token.toString())
724 //println("<B>++</B>");
725 token.identifier = identifier;
726 identifier.refcount++;
735 //println("<B>EID</B>");
737 //if (this.mode == 'BUILDING_SYMBOL_TREE')
738 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
740 //print('EXPR-KEYW:' + token.toString());
741 if (token.name == "FUNCTION") {
743 this.parseFunctionDeclaration(scope);
749 if (this.mode == 'BUILDING_SYMBOL_TREE') {
751 if (token.name == "EVAL") {
752 //print(JSON.stringify(token,null,4));
753 if (token.prefix && token.prefix.match(/eval:var:/g)) {
754 // look for eval:var:noreplace\n
755 // print("GOT MATCH?");
757 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
759 //print("PROTECT: " + a);
762 var hi = _t.getIdentifier(a, scope, token);
763 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
765 // println("PROTECT "+a+" from munge");
773 this.protectScopeFromObfuscation(scope);
774 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
782 //if (this.mode == 'BUILDING_SYMBOL_TREE')
783 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
788 //print("<< EXIT EXPRESSION");
793 parseCatch : function(scope) {
800 //token = getToken(-1);
801 //assert token.getType() == Token.CATCH;
802 token = this.ts.nextTok(1);
803 token = this.ts.nextTok(1);
806 //print(JSON.stringify(this.ts,null,4));
807 //assert token.getType() == Token.LP; (
808 //token = this.ts.nextTok();
809 //assert token.getType() == Token.NAME;
811 symbol = token.items[0][0].data;
814 if (this.mode == 'BUILDING_SYMBOL_TREE') {
815 // We must declare the exception identifier in the containing function
816 // scope to avoid errors related to the obfuscation process. No need to
817 // display a warning if the symbol was already declared here...
818 scope.declareIdentifier(symbol, token.items[0][0]);
820 //?? why inc the refcount?? - that should be set when building the tree???
821 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
822 identifier.refcount++;
825 token = this.ts.nextTok();
826 //assert token.getType() == Token.RP; // )
829 parseFunctionDeclaration : function(scope)
831 //print("PARSE FUNCTION");
837 var b4braceNesting = this.braceNesting + 0;
839 //this.logR("<B>PARSING FUNCTION</B>");
842 token = this.ts.nextTok();
843 if (token.type == "NAME") {
844 if (this.mode == 'BUILDING_SYMBOL_TREE') {
845 // Get the name of the function and declare it in the current scope.
847 if (scope.getIdentifier(symbol,token) != false) {
848 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
850 scope.declareIdentifier(symbol,token);
852 token = this.ts.nextTok();
856 // return function() {....
857 while (token.data != "(") {
858 //print(token.toString());
859 token = this.ts.nextTok();
866 //assert token.getType() == Token.LP;
867 if (this.mode == 'BUILDING_SYMBOL_TREE') {
868 fnScope = new Scope(1, scope, token.n, '', token);
870 //println("STORING SCOPE" + this.ts.cursor);
872 this.indexedScopes[token.id] = fnScope;
875 //qln("FETCHING SCOPE" + this.ts.cursor);
876 fnScope = this.indexedScopes[token.id];
878 //if (this.mode == 'BUILDING_SYMBOL_TREE')
879 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
880 // Parse function arguments.
881 var args = token.items;
882 for (var argpos =0; argpos < args.length; argpos++) {
884 token = args[argpos][0];
885 //print ("FUNC ARGS: " + token.toString())
886 //assert token.getType() == Token.NAME ||
887 // token.getType() == Token.COMMA;
888 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
890 identifier = fnScope.declareIdentifier(symbol,token);
891 if (symbol == "$super" && argpos == 0) {
892 // Exception for Prototype 1.6...
893 identifier.preventMunging();
899 token = this.ts.nextTok();
900 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
902 //print(token.toString());
903 // assert token.getType() == Token.LC;
904 //this.braceNesting++;
906 //token = this.ts.nextTok();
907 //print(token.toString());
910 token.items.forEach(function(tar) {
911 _this.ts = new TokenStream(tar);
912 _this.parseScope(fnScope);
917 //print(JSON.stringify(this.ts,null,4));
918 //this.parseScope(fnScope);
920 // now pop it off the stack!!!
922 //this.braceNesting = b4braceNesting;
923 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
924 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
925 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
928 protectScopeFromObfuscation : function(scope) {
929 //assert scope != null;
931 if (scope == this.globalScope) {
932 // The global scope does not get obfuscated,
933 // so we don't need to worry about it...
937 // Find the highest local scope containing the specified scope.
938 while (scope && scope.parent != this.globalScope) {
939 scope = scope.parent;
942 //assert scope.getParentScope() == globalScope;
943 scope.preventMunging();
946 getIdentifier: function(symbol, scope, token) {
948 while (scope != false) {
949 identifier = scope.getIdentifier(symbol, token);
950 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
954 scope = scope.parent;