1 //<Script type="text/javascript">
3 Scope = imports.Scope.Scope;
4 TokenStream = imports.TokenStream.TokenStream;
6 * This code now uses the collapsed tree
7 * Used by packer to determine scope
15 ScopeParser = function(ts) {
16 this.ts = ts; // {TokenStream}
19 this.timer = new Date() * 1;
25 * list of keywords that should not be used in object literals.
28 ScopeParser.idents = [
94 ScopeParser.prototype = {
96 timerPrint: function (str) {
97 var ntime = new Date() * 1;
98 var tdif = ntime -this.timer;
101 if (tdif > 100) { //slower ones..
104 println(pref+'['+tdif+']'+str);
108 //print('****************' + s);
109 this.warnings.push(s);
110 //println("WARNING:" + htmlescape(s) + "<BR>");
112 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
116 mode : "", //"BUILDING_SYMBOL_TREE",
118 indexedScopes : false,
125 buildSymbolTree : function()
130 this.braceNesting = 0;
132 // print(JSON.stringify(this.ts.tokens, null,4));
135 this.globalScope = new Scope(-1, false, -1, '');
136 this.indexedScopes = { 0 : this.globalScope };
138 this.mode = 'BUILDING_SYMBOL_TREE';
139 this.parseScope(this.globalScope);
141 //print("---------------END PASS 1 ---------------- ");
144 mungeSymboltree : function()
151 // One problem with obfuscation resides in the use of undeclared
152 // and un-namespaced global symbols that are 3 characters or less
153 // in length. Here is an example:
155 // var declaredGlobalVar;
157 // function declaredGlobalFn() {
159 // localvar = abc; // abc is an undeclared global symbol
162 // In the example above, there is a slim chance that localvar may be
163 // munged to 'abc', conflicting with the undeclared global symbol
164 // abc, creating a potential bug. The following code detects such
165 // global symbols. This must be done AFTER the entire file has been
166 // parsed, and BEFORE munging the symbol tree. Note that declaring
167 // extra symbols in the global scope won't hurt.
169 // Note: Since we go through all the tokens to do this, we also use
170 // the opportunity to count how many times each identifier is used.
173 this.braceNesting = 0;
174 this.mode = 'PASS2_SYMBOL_TREE';
176 //println("MUNGING?");
178 this.parseScope(this.globalScope);
180 //this.globalScope.dump();
183 this.globalScope.munge();
189 print (" ".substring(0, this.braceNesting*2) + str);
191 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
195 //println("<B>LOG:</B>" + str + "<BR/>");
202 parseScope : function(scope) // parse a token stream..
204 //this.timerPrint("parseScope EnterScope");
205 //this.log(">>> ENTER SCOPE" + this.scopes.length);
211 var expressionBraceNesting = this.braceNesting + 0;
213 var parensNesting = 0;
215 var isObjectLitAr = [ false ];
219 //var scopeIndent = '';
220 //this.scopes.forEach(function() {
221 // scopeIndent += ' ';
223 //print(">> ENTER SCOPE");
228 token = this.ts.lookTok(1);
230 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
231 //this.dumpToken(token , this.scopes, this.braceNesting);
232 //print('SCOPE:' + token.toString());
233 //this.log(token.data);
234 if (token.type == 'NAME') {
235 // print('*' + token.data);
237 switch(token.type + '.' + token.name) {
239 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
240 //print('SCOPE-VAR:' + token.toString());
241 var vstart = this.ts.cursor +1;
243 //this.log("parseScope GOT VAR/CONST : " + token.toString());
245 token = this.ts.nextTok();
246 //!this.debug|| print( token.toString());
247 // print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
248 if (!token) { // can return false at EOF!
251 if (token.name == "VAR" || token.data == ',') { // kludge..
254 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
255 if (token.type != "NAME") {
256 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
257 print(this.ts.tokens[i].toString());
260 print( "var without ident");
265 if (this.mode == "BUILDING_SYMBOL_TREE") {
266 identifier = scope.getIdentifier(token.data,token) ;
268 if (identifier == false) {
269 scope.declareIdentifier(token.data, token);
271 token.identifier = identifier;
272 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
276 token = this.ts.nextTok();
277 !this.debug|| print(token.toString());
279 assert token.getType() == Token.SEMI ||
280 token.getType() == Token.ASSIGN ||
281 token.getType() == Token.COMMA ||
282 token.getType() == Token.IN;
284 if (token.name == "IN") {
287 //var bn = this.braceNesting;
288 var bn = this.braceNesting;
291 if (!token || token.type == 'VOID' || token.data == ',') {
295 token = this.ts.nextTok();
299 this.ts = new TokenStream(nts);
300 this.parseExpression(scope);
304 this.braceNesting = bn;
305 //this.braceNesting = bn;
306 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
308 token = this.ts.lookTok(1);
310 // print("AFTER EXP: " + token.toString());
311 if (token.data == ';') {
318 //this.ts.dump(vstart , this.ts.cursor);
323 case "KEYW.FUNCTION":
324 //if (this.mode == 'BUILDING_SYMBOL_TREE')
325 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
326 //println("<i>"+token.data+"</i>");
327 var bn = this.braceNesting;
328 this.parseFunctionDeclaration(scope);
329 this.braceNesting = bn;
332 case "PUNC.LEFT_CURLY": // {
333 case "PUNC.LEFT_PAREN": // (
334 case "PUNC.LEFT_BRACE": // [
335 //print('SCOPE-CURLY/PAREN:' + token.toString());
336 //println("<i>"+token.data+"</i>");
340 for (var prop in token.props) {
343 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
344 if (token.props[prop].val[0].data == 'function') {
345 // parse a function..
346 this.ts = new TokenStream(token.props[prop].val);
348 this.parseFunctionDeclaration(scope);
354 this.ts = new TokenStream(token.props[prop].val);
355 this.parseExpression(scope);
360 // it's an object literal..
361 // the values could be replaced..
367 token.items.forEach(function(expr) {
368 //print(JSON.stringify(expr, null,4));
369 _this.ts = new TokenStream(expr);
370 //if (curTS.data == '(') {
371 _this.parseScope(scope)
373 // _this.parseExpression(scope)
378 //print("NOT PROPS"); Seed.quit();
380 //isObjectLitAr.push(false);
381 //this.braceNesting++;
383 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
386 case "PUNC.RIGHT_CURLY": // }
387 //print("<< EXIT SCOPE");
391 //print('SCOPE-WITH:' + token.toString());
392 //println("<i>"+token.data+"</i>");
393 if (this.mode == "BUILDING_SYMBOL_TREE") {
394 // Inside a 'with' block, it is impossible to figure out
395 // statically whether a symbol is a local variable or an
396 // object member. As a consequence, the only thing we can
397 // do is turn the obfuscation off for the highest scope
398 // containing the 'with' block.
399 this.protectScopeFromObfuscation(scope);
400 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
405 //print('SCOPE-CATCH:' + token.toString());
406 //println("<i>"+token.data+"</i>");
407 this.parseCatch(scope);
410 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
411 case "STRN.SINGLE_QUOTE":
412 // print('SCOPE-STRING:' + token.toString());
413 //println("<i>"+token.data+"</i>");
415 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
416 // then we are in an object lit.. -> we need to flag the brace as such...
418 isObjectLitAr.push(true);
419 //print(">>>>>> OBJLIT REPUSH(true)");
421 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
423 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
424 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
425 // see if we can replace..
426 // remove the quotes..
427 // should do a bit more checking!!!! (what about wierd char's in the string..
428 var str = token.data.substring(1,token.data.length-1);
429 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
440 //print('SCOPE-NAME:' + token.toString());
441 //print("DEAL WITH NAME:");
443 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
444 // skip anyting with "." before it..!!
446 if (this.ts.lookTok(-1).data == ".") {
447 // skip, it's an object prop.
448 //println("<i>"+token.data+"</i>");
451 //print("SYMBOL: " + token.toString());
454 if (symbol == 'this') {
457 if (this.mode == 'PASS2_SYMBOL_TREE') {
459 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
461 //print ("MUNGE?" + symbol);
463 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
465 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
466 identifier = this.getIdentifier(symbol, scope, token);
468 if (identifier == false) {
469 // BUG!find out where builtin is defined...
470 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
471 // Here, we found an undeclared and un-namespaced symbol that is
472 // 3 characters or less in length. Declare it in the global scope.
473 // We don't need to declare longer symbols since they won't cause
474 // any conflict with other munged symbols.
475 this.globalScope.declareIdentifier(symbol, token);
476 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
479 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
481 token.identifier = identifier;
482 identifier.refcount++;
487 //println("<B>SID</B>");
489 if (token.type != 'KEYW') {
492 //print('SCOPE-KEYW:' + token.toString());
493 // print("Check eval:");
497 if (this.mode == 'BUILDING_SYMBOL_TREE') {
499 if (token.name == "EVAL") {
501 //print(JSON.stringify(token, null,4));
502 // look back one and see if we can find a comment!!!
503 //if (this.ts.look(-1).type == "COMM") {
504 if (token.prefix && token.prefix.match(/eval/)) {
505 // look for eval:var:noreplace\n
508 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
509 //print("GOT: " + a);
510 var hi = _t.getIdentifier(a, scope, token);
511 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
513 // print("PROTECT "+a+" from munge");
514 //print(JSON.stringify(hi,null,4));
524 this.protectScopeFromObfuscation(scope);
525 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);
537 //print("parseScope TOK : " + token.toString());
538 token = this.ts.nextTok();
539 //if (this.ts.nextT()) break;
542 //print("<<< EXIT SCOPE");
543 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
547 parseExpression : function(scope) {
549 // Parse the expression until we encounter a comma or a semi-colon
550 // in the same brace nesting, bracket nesting and paren nesting.
551 // Parse functions if any...
552 //println("<i>EXP</i><BR/>");
553 !this.debug || print("PARSE EXPR");
556 // for printing stuff..
565 var expressionBraceNesting = this.braceNesting + 0;
566 var bracketNesting = 0;
567 var parensNesting = 0;
569 var isObjectLitAr = [ false ];
574 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
575 while (token = this.ts.nextTok()) {
580 // moved out of loop?
581 currentScope = this.scopes[this.scopes.length-1];
583 var scopeIndent = '';
584 this.scopes.forEach(function() {
589 //this.dumpToken(token, this.scopes, this.braceNesting );
590 //print('EXPR' + token.toString());
593 //println("<i>"+token.data+"</i>");
594 //this.log("EXP:" + token.data);
595 switch (token.type) {
597 //print("EXPR-PUNC:" + token.toString());
602 //print("<< EXIT EXPRESSION");
610 case '(': //Token.LP:
611 case '{': //Token.LC:
612 case '[': //Token.LB:
613 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
614 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
615 //println("<i>"+token.data+"</i>");
619 for (var prop in token.props) {
620 //if (!token.props[prop].val.length) {
621 //print(JSON.stringify(token.props, null,4));
624 if (token.props[prop].val[0].data == 'function') {
625 // parse a function..
626 this.ts = new TokenStream(token.props[prop].val);
628 this.parseFunctionDeclaration(scope);
633 this.ts = new TokenStream(token.props[prop].val);
634 this.parseExpression(scope);
639 // it's an object literal..
640 // the values could be replaced..
646 token.items.forEach(function(expr) {
647 _this.ts = new TokenStream(expr);
648 _this.parseExpression(scope)
654 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
661 case ')': //Token.RP:
662 case ']': //Token.RB:
663 case '}': //Token.RB:
664 //print("<< EXIT EXPRESSION");
677 case 'STRN': // used for object lit detection..
678 //if (this.mode == 'BUILDING_SYMBOL_TREE')
679 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
687 if (this.mode == 'BUILDING_SYMBOL_TREE') {
689 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
691 //print("EXPR-NAME:" + token.toString());
694 //print("in NAME = " + token.toString());
695 //print("in NAME 0: " + this.ts.look(0).toString());
696 //print("in NAME 2: " + this.ts.lookTok(2).toString());
698 //print(this.ts.lookTok(-1).data);
700 if (this.ts.lookTok(-1).data == ".") {
704 if (symbol == 'this') {
708 if (this.mode == 'PASS2_SYMBOL_TREE') {
710 identifier = this.getIdentifier(symbol, scope, token);
711 //println("<B>??</B>");
712 if (identifier == false) {
714 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
715 // Here, we found an undeclared and un-namespaced symbol that is
716 // 3 characters or less in length. Declare it in the global scope.
717 // We don't need to declare longer symbols since they won't cause
718 // any conflict with other munged symbols.
719 this.globalScope.declareIdentifier(symbol, token);
720 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
721 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
724 //print("undeclared:" + token.toString())
729 //println("<B>++</B>");
730 token.identifier = identifier;
731 identifier.refcount++;
740 //println("<B>EID</B>");
742 //if (this.mode == 'BUILDING_SYMBOL_TREE')
743 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
745 //print('EXPR-KEYW:' + token.toString());
746 if (token.name == "FUNCTION") {
748 this.parseFunctionDeclaration(scope);
754 if (this.mode == 'BUILDING_SYMBOL_TREE') {
756 if (token.name == "EVAL") {
757 //print(JSON.stringify(token,null,4));
758 if (token.prefix && token.prefix.match(/eval:var:/g)) {
759 // look for eval:var:noreplace\n
760 // print("GOT MATCH?");
762 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
764 //print("PROTECT: " + a);
767 var hi = _t.getIdentifier(a, scope, token);
768 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
770 // println("PROTECT "+a+" from munge");
778 this.protectScopeFromObfuscation(scope);
779 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
787 //if (this.mode == 'BUILDING_SYMBOL_TREE')
788 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
793 //print("<< EXIT EXPRESSION");
798 parseCatch : function(scope) {
805 //token = getToken(-1);
806 //assert token.getType() == Token.CATCH;
807 token = this.ts.nextTok(1);
808 token = this.ts.nextTok(1);
811 //print(JSON.stringify(this.ts,null,4));
812 //assert token.getType() == Token.LP; (
813 //token = this.ts.nextTok();
814 //assert token.getType() == Token.NAME;
816 symbol = token.items[0][0].data;
819 if (this.mode == 'BUILDING_SYMBOL_TREE') {
820 // We must declare the exception identifier in the containing function
821 // scope to avoid errors related to the obfuscation process. No need to
822 // display a warning if the symbol was already declared here...
823 scope.declareIdentifier(symbol, token.items[0][0]);
825 //?? why inc the refcount?? - that should be set when building the tree???
826 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
827 identifier.refcount++;
830 token = this.ts.nextTok();
831 //assert token.getType() == Token.RP; // )
834 parseFunctionDeclaration : function(scope)
836 //print("PARSE FUNCTION");
842 var b4braceNesting = this.braceNesting + 0;
844 //this.logR("<B>PARSING FUNCTION</B>");
847 token = this.ts.nextTok();
848 if (token.type == "NAME") {
849 if (this.mode == 'BUILDING_SYMBOL_TREE') {
850 // Get the name of the function and declare it in the current scope.
852 if (scope.getIdentifier(symbol,token) != false) {
853 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
855 scope.declareIdentifier(symbol,token);
857 token = this.ts.nextTok();
861 // return function() {....
862 while (token.data != "(") {
863 //print(token.toString());
864 token = this.ts.nextTok();
871 //assert token.getType() == Token.LP;
872 if (this.mode == 'BUILDING_SYMBOL_TREE') {
873 fnScope = new Scope(1, scope, token.n, '', token);
875 //println("STORING SCOPE" + this.ts.cursor);
877 this.indexedScopes[token.id] = fnScope;
880 //qln("FETCHING SCOPE" + this.ts.cursor);
881 fnScope = this.indexedScopes[token.id];
883 //if (this.mode == 'BUILDING_SYMBOL_TREE')
884 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
885 // Parse function arguments.
886 var args = token.items;
887 for (var argpos =0; argpos < args.length; argpos++) {
889 token = args[argpos][0];
890 //print ("FUNC ARGS: " + token.toString())
891 //assert token.getType() == Token.NAME ||
892 // token.getType() == Token.COMMA;
893 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
895 identifier = fnScope.declareIdentifier(symbol,token);
896 if (symbol == "$super" && argpos == 0) {
897 // Exception for Prototype 1.6...
898 identifier.preventMunging();
904 token = this.ts.nextTok();
905 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
907 //print(token.toString());
908 // assert token.getType() == Token.LC;
909 //this.braceNesting++;
911 //token = this.ts.nextTok();
912 //print(token.toString());
915 token.items.forEach(function(tar) {
916 _this.ts = new TokenStream(tar);
917 _this.parseScope(fnScope);
922 //print(JSON.stringify(this.ts,null,4));
923 //this.parseScope(fnScope);
925 // now pop it off the stack!!!
927 //this.braceNesting = b4braceNesting;
928 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
929 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
930 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
933 protectScopeFromObfuscation : function(scope) {
934 //assert scope != null;
936 if (scope == this.globalScope) {
937 // The global scope does not get obfuscated,
938 // so we don't need to worry about it...
942 // Find the highest local scope containing the specified scope.
943 while (scope && scope.parent != this.globalScope) {
944 scope = scope.parent;
947 //assert scope.getParentScope() == globalScope;
948 scope.preventMunging();
951 getIdentifier: function(symbol, scope, token) {
953 while (scope != false) {
954 identifier = scope.getIdentifier(symbol, token);
955 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
959 scope = scope.parent;