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);
304 !this.debug|| print("AFTER EXP: " + token.toString());
305 if (token.data == ';') {
312 //this.ts.dump(vstart , this.ts.cursor);
317 case "KEYW.FUNCTION":
318 //if (this.mode == 'BUILDING_SYMBOL_TREE')
319 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
320 //println("<i>"+token.data+"</i>");
321 var bn = this.braceNesting;
322 this.parseFunctionDeclaration(scope);
323 this.braceNesting = bn;
326 case "PUNC.LEFT_CURLY": // {
327 case "PUNC.LEFT_PAREN": // (
328 case "PUNC.LEFT_BRACE": // [
329 //print('SCOPE-CURLY/PAREN:' + token.toString());
330 //println("<i>"+token.data+"</i>");
334 for (var prop in token.props) {
337 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
338 if (token.props[prop].val[0].data == 'function') {
339 // parse a function..
340 this.ts = new TokenStream(token.props[prop].val);
342 this.parseFunctionDeclaration(scope);
348 this.ts = new TokenStream(token.props[prop].val);
349 this.parseExpression(scope);
354 // it's an object literal..
355 // the values could be replaced..
361 token.items.forEach(function(expr) {
362 _this.ts = new TokenStream(expr);
363 _this.parseExpression(scope)
366 //print("NOT PROPS"); Seed.quit();
368 //isObjectLitAr.push(false);
369 //this.braceNesting++;
371 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
374 case "PUNC.RIGHT_CURLY": // }
375 //print("<< EXIT SCOPE");
379 //print('SCOPE-WITH:' + token.toString());
380 //println("<i>"+token.data+"</i>");
381 if (this.mode == "BUILDING_SYMBOL_TREE") {
382 // Inside a 'with' block, it is impossible to figure out
383 // statically whether a symbol is a local variable or an
384 // object member. As a consequence, the only thing we can
385 // do is turn the obfuscation off for the highest scope
386 // containing the 'with' block.
387 this.protectScopeFromObfuscation(scope);
388 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
393 //print('SCOPE-CATCH:' + token.toString());
394 //println("<i>"+token.data+"</i>");
395 this.parseCatch(scope);
398 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
399 case "STRN.SINGLE_QUOTE":
400 // print('SCOPE-STRING:' + token.toString());
401 //println("<i>"+token.data+"</i>");
403 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
404 // then we are in an object lit.. -> we need to flag the brace as such...
406 isObjectLitAr.push(true);
407 //print(">>>>>> OBJLIT REPUSH(true)");
409 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
411 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
412 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
413 // see if we can replace..
414 // remove the quotes..
415 // should do a bit more checking!!!! (what about wierd char's in the string..
416 var str = token.data.substring(1,token.data.length-1);
417 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
428 //print('SCOPE-NAME:' + token.toString());
429 //print("DEAL WITH NAME:");
431 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
432 // skip anyting with "." before it..!!
434 if (this.ts.lookTok(-1).data == ".") {
435 // skip, it's an object prop.
436 //println("<i>"+token.data+"</i>");
439 //print("SYMBOL: " + token.toString());
442 if (symbol == 'this') {
445 if (this.mode == 'PASS2_SYMBOL_TREE') {
447 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
449 //print ("MUNGE?" + symbol);
451 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
453 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
454 identifier = this.getIdentifier(symbol, scope, token);
456 if (identifier == false) {
457 // BUG!find out where builtin is defined...
458 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
459 // Here, we found an undeclared and un-namespaced symbol that is
460 // 3 characters or less in length. Declare it in the global scope.
461 // We don't need to declare longer symbols since they won't cause
462 // any conflict with other munged symbols.
463 this.globalScope.declareIdentifier(symbol, token);
464 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
467 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
469 token.identifier = identifier;
470 identifier.refcount++;
475 //println("<B>SID</B>");
477 if (token.type != 'KEYW') {
480 //print('SCOPE-KEYW:' + token.toString());
481 // print("Check eval:");
485 if (this.mode == 'BUILDING_SYMBOL_TREE') {
487 if (token.name == "EVAL") {
489 //print(JSON.stringify(token, null,4));
490 // look back one and see if we can find a comment!!!
491 //if (this.ts.look(-1).type == "COMM") {
492 if (token.prefix && token.prefix.match(/eval/)) {
493 // look for eval:var:noreplace\n
496 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
497 //print("GOT: " + a);
498 var hi = _t.getIdentifier(a, scope, token);
499 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
501 // print("PROTECT "+a+" from munge");
502 //print(JSON.stringify(hi,null,4));
512 this.protectScopeFromObfuscation(scope);
513 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);
525 //print("parseScope TOK : " + token.toString());
526 token = this.ts.nextTok();
527 //if (this.ts.nextT()) break;
530 //print("<<< EXIT SCOPE");
531 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
535 parseExpression : function(scope) {
537 // Parse the expression until we encounter a comma or a semi-colon
538 // in the same brace nesting, bracket nesting and paren nesting.
539 // Parse functions if any...
540 //println("<i>EXP</i><BR/>");
541 !this.debug || print("PARSE EXPR");
544 // for printing stuff..
553 var expressionBraceNesting = this.braceNesting + 0;
554 var bracketNesting = 0;
555 var parensNesting = 0;
557 var isObjectLitAr = [ false ];
562 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
563 while (token = this.ts.nextTok()) {
568 // moved out of loop?
569 currentScope = this.scopes[this.scopes.length-1];
571 var scopeIndent = '';
572 this.scopes.forEach(function() {
577 //this.dumpToken(token, this.scopes, this.braceNesting );
578 //print('EXPR' + token.toString());
581 //println("<i>"+token.data+"</i>");
582 //this.log("EXP:" + token.data);
583 switch (token.type) {
585 //print("EXPR-PUNC:" + token.toString());
590 //print("<< EXIT EXPRESSION");
598 case '(': //Token.LP:
599 case '{': //Token.LC:
600 case '[': //Token.LB:
601 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
602 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
603 //println("<i>"+token.data+"</i>");
607 for (var prop in token.props) {
608 if (!token.props[prop].val.length) {
609 print(JSON.stringify(token.props, null,4));
612 if (token.props[prop].val[0].data == 'function') {
613 // parse a function..
614 this.ts = new TokenStream(token.props[prop].val);
616 this.parseFunctionDeclaration(scope);
621 this.ts = new TokenStream(token.props[prop].val);
622 this.parseExpression(scope);
627 // it's an object literal..
628 // the values could be replaced..
634 token.items.forEach(function(expr) {
635 _this.ts = new TokenStream(expr);
636 _this.parseExpression(scope)
642 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
649 case ')': //Token.RP:
650 case ']': //Token.RB:
651 case '}': //Token.RB:
652 //print("<< EXIT EXPRESSION");
665 case 'STRN': // used for object lit detection..
666 //if (this.mode == 'BUILDING_SYMBOL_TREE')
667 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
675 if (this.mode == 'BUILDING_SYMBOL_TREE') {
677 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
679 //print("EXPR-NAME:" + token.toString());
682 //print("in NAME = " + token.toString());
683 //print("in NAME 0: " + this.ts.look(0).toString());
684 //print("in NAME 2: " + this.ts.lookTok(2).toString());
686 //print(this.ts.lookTok(-1).data);
688 if (this.ts.lookTok(-1).data == ".") {
692 if (symbol == 'this') {
696 if (this.mode == 'PASS2_SYMBOL_TREE') {
698 identifier = this.getIdentifier(symbol, scope, token);
699 //println("<B>??</B>");
700 if (identifier == false) {
702 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
703 // Here, we found an undeclared and un-namespaced symbol that is
704 // 3 characters or less in length. Declare it in the global scope.
705 // We don't need to declare longer symbols since they won't cause
706 // any conflict with other munged symbols.
707 this.globalScope.declareIdentifier(symbol, token);
708 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
709 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
712 //print("undeclared:" + token.toString())
717 //println("<B>++</B>");
718 token.identifier = identifier;
719 identifier.refcount++;
728 //println("<B>EID</B>");
730 //if (this.mode == 'BUILDING_SYMBOL_TREE')
731 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
733 //print('EXPR-KEYW:' + token.toString());
734 if (token.name == "FUNCTION") {
736 this.parseFunctionDeclaration(scope);
743 if (this.mode == 'BUILDING_SYMBOL_TREE') {
745 if (token.name == "EVAL") {
746 //print(JSON.stringify(token,null,4));
747 if (token.prefix && token.prefix.match(/eval:var:/g)) {
748 // look for eval:var:noreplace\n
749 // print("GOT MATCH?");
751 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
753 //print("PROTECT: " + a);
756 var hi = _t.getIdentifier(a, scope, token);
757 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
759 // println("PROTECT "+a+" from munge");
767 this.protectScopeFromObfuscation(scope);
768 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
776 //if (this.mode == 'BUILDING_SYMBOL_TREE')
777 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
782 //print("<< EXIT EXPRESSION");
787 parseCatch : function(scope) {
794 //token = getToken(-1);
795 //assert token.getType() == Token.CATCH;
796 token = this.ts.nextTok();
798 //print(JSON.stringify(token,null,4));
799 //assert token.getType() == Token.LP; (
800 //token = this.ts.nextTok();
801 //assert token.getType() == Token.NAME;
803 symbol = token.items[0][0].data;
806 if (this.mode == 'BUILDING_SYMBOL_TREE') {
807 // We must declare the exception identifier in the containing function
808 // scope to avoid errors related to the obfuscation process. No need to
809 // display a warning if the symbol was already declared here...
810 scope.declareIdentifier(symbol, token.items[0][0]);
812 //?? why inc the refcount?? - that should be set when building the tree???
813 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
814 identifier.refcount++;
817 token = this.ts.nextTok();
818 //assert token.getType() == Token.RP; // )
821 parseFunctionDeclaration : function(scope)
823 //print("PARSE FUNCTION");
829 var b4braceNesting = this.braceNesting + 0;
831 //this.logR("<B>PARSING FUNCTION</B>");
834 token = this.ts.nextTok();
835 if (token.type == "NAME") {
836 if (this.mode == 'BUILDING_SYMBOL_TREE') {
837 // Get the name of the function and declare it in the current scope.
839 if (scope.getIdentifier(symbol,token) != false) {
840 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
842 scope.declareIdentifier(symbol,token);
844 token = this.ts.nextTok();
848 // return function() {....
849 while (token.data != "(") {
850 print(token.toString());
851 token = this.ts.nextTok();
858 //assert token.getType() == Token.LP;
859 if (this.mode == 'BUILDING_SYMBOL_TREE') {
860 fnScope = new Scope(1, scope, token.n, '', token);
862 //println("STORING SCOPE" + this.ts.cursor);
864 this.indexedScopes[token.id] = fnScope;
867 //qln("FETCHING SCOPE" + this.ts.cursor);
868 fnScope = this.indexedScopes[token.id];
870 //if (this.mode == 'BUILDING_SYMBOL_TREE')
871 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
872 // Parse function arguments.
873 var args = token.items;
874 for (var argpos =0; argpos < args.length; argpos++) {
876 token = args[argpos][0];
877 //print ("FUNC ARGS: " + token.toString())
878 //assert token.getType() == Token.NAME ||
879 // token.getType() == Token.COMMA;
880 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
882 identifier = fnScope.declareIdentifier(symbol,token);
883 if (symbol == "$super" && argpos == 0) {
884 // Exception for Prototype 1.6...
885 identifier.preventMunging();
891 token = this.ts.nextTok();
892 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
894 //print(token.toString());
895 // assert token.getType() == Token.LC;
896 //this.braceNesting++;
898 //token = this.ts.nextTok();
899 //print(token.toString());
902 token.items.forEach(function(tar) {
903 _this.ts = new TokenStream(tar);
904 _this.parseScope(fnScope);
909 //print(JSON.stringify(this.ts,null,4));
910 //this.parseScope(fnScope);
912 // now pop it off the stack!!!
914 //this.braceNesting = b4braceNesting;
915 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
916 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
917 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
920 protectScopeFromObfuscation : function(scope) {
921 //assert scope != null;
923 if (scope == this.globalScope) {
924 // The global scope does not get obfuscated,
925 // so we don't need to worry about it...
929 // Find the highest local scope containing the specified scope.
930 while (scope && scope.parent != this.globalScope) {
931 scope = scope.parent;
934 //assert scope.getParentScope() == globalScope;
935 scope.preventMunging();
938 getIdentifier: function(symbol, scope, token) {
940 while (scope != false) {
941 identifier = scope.getIdentifier(symbol, token);
942 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
946 scope = scope.parent;