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 // { a : ... , c : .... }
337 for (var prop in token.props) {
340 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
341 if (token.props[prop].val[0].data == 'function') {
342 // parse a function..
343 this.ts = new TokenStream(token.props[prop].val);
345 this.parseFunctionDeclaration(scope);
351 this.ts = new TokenStream(token.props[prop].val);
352 this.parseExpression(scope);
357 // it's an object literal..
358 // the values could be replaced..
362 // ( ... ) or { .... } not object literals..
365 token.items.forEach(function(expr) {
366 print(expr.toString());
367 //print(JSON.stringify(expr, null,4));
368 _this.ts = new TokenStream(expr);
369 //if (curTS.data == '(') {
370 _this.parseScope(scope)
372 // _this.parseExpression(scope)
377 //print("NOT PROPS"); Seed.quit();
379 //isObjectLitAr.push(false);
380 //this.braceNesting++;
382 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
385 case "PUNC.RIGHT_CURLY": // }
386 //print("<< EXIT SCOPE");
390 //print('SCOPE-WITH:' + token.toString());
391 //println("<i>"+token.data+"</i>");
392 if (this.mode == "BUILDING_SYMBOL_TREE") {
393 // Inside a 'with' block, it is impossible to figure out
394 // statically whether a symbol is a local variable or an
395 // object member. As a consequence, the only thing we can
396 // do is turn the obfuscation off for the highest scope
397 // containing the 'with' block.
398 this.protectScopeFromObfuscation(scope);
399 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
404 //print('SCOPE-CATCH:' + token.toString());
405 //println("<i>"+token.data+"</i>");
406 this.parseCatch(scope);
409 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
410 case "STRN.SINGLE_QUOTE":
411 // print('SCOPE-STRING:' + token.toString());
412 //println("<i>"+token.data+"</i>");
414 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
415 // then we are in an object lit.. -> we need to flag the brace as such...
417 isObjectLitAr.push(true);
418 //print(">>>>>> OBJLIT REPUSH(true)");
420 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
422 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
423 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
424 // see if we can replace..
425 // remove the quotes..
426 // should do a bit more checking!!!! (what about wierd char's in the string..
427 var str = token.data.substring(1,token.data.length-1);
428 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
439 //print('SCOPE-NAME:' + token.toString());
440 //print("DEAL WITH NAME:");
442 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
443 // skip anyting with "." before it..!!
445 if (this.ts.lookTok(-1).data == ".") {
446 // skip, it's an object prop.
447 //println("<i>"+token.data+"</i>");
450 //print("SYMBOL: " + token.toString());
453 if (symbol == 'this') {
456 if (this.mode == 'PASS2_SYMBOL_TREE') {
458 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
460 //print ("MUNGE?" + symbol);
462 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
464 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
465 identifier = this.getIdentifier(symbol, scope, token);
467 if (identifier == false) {
468 // BUG!find out where builtin is defined...
469 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
470 // Here, we found an undeclared and un-namespaced symbol that is
471 // 3 characters or less in length. Declare it in the global scope.
472 // We don't need to declare longer symbols since they won't cause
473 // any conflict with other munged symbols.
474 this.globalScope.declareIdentifier(symbol, token);
475 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
478 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
480 token.identifier = identifier;
481 identifier.refcount++;
486 //println("<B>SID</B>");
488 if (token.type != 'KEYW') {
491 //print('SCOPE-KEYW:' + token.toString());
492 // print("Check eval:");
496 if (this.mode == 'BUILDING_SYMBOL_TREE') {
498 if (token.name == "EVAL") {
500 //print(JSON.stringify(token, null,4));
501 // look back one and see if we can find a comment!!!
502 //if (this.ts.look(-1).type == "COMM") {
503 if (token.prefix && token.prefix.match(/eval/)) {
504 // look for eval:var:noreplace\n
507 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
508 //print("GOT: " + a);
509 var hi = _t.getIdentifier(a, scope, token);
510 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
512 // print("PROTECT "+a+" from munge");
513 //print(JSON.stringify(hi,null,4));
523 this.protectScopeFromObfuscation(scope);
524 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);
536 //print("parseScope TOK : " + token.toString());
537 token = this.ts.nextTok();
538 //if (this.ts.nextT()) break;
541 //print("<<< EXIT SCOPE");
542 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
546 parseExpression : function(scope) {
548 // Parse the expression until we encounter a comma or a semi-colon
549 // in the same brace nesting, bracket nesting and paren nesting.
550 // Parse functions if any...
551 //println("<i>EXP</i><BR/>");
552 !this.debug || print("PARSE EXPR");
555 // for printing stuff..
564 var expressionBraceNesting = this.braceNesting + 0;
565 var bracketNesting = 0;
566 var parensNesting = 0;
568 var isObjectLitAr = [ false ];
573 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
574 while (token = this.ts.nextTok()) {
579 // moved out of loop?
580 currentScope = this.scopes[this.scopes.length-1];
582 var scopeIndent = '';
583 this.scopes.forEach(function() {
588 //this.dumpToken(token, this.scopes, this.braceNesting );
589 //print('EXPR' + token.toString());
592 //println("<i>"+token.data+"</i>");
593 //this.log("EXP:" + token.data);
594 switch (token.type) {
596 //print("EXPR-PUNC:" + token.toString());
601 //print("<< EXIT EXPRESSION");
609 case '(': //Token.LP:
610 case '{': //Token.LC:
611 case '[': //Token.LB:
612 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
613 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
614 //println("<i>"+token.data+"</i>");
618 for (var prop in token.props) {
619 if (!token.props[prop].val.length) {
620 print(JSON.stringify(token.props, null,4));
623 if (token.props[prop].val[0].data == 'function') {
624 // parse a function..
625 this.ts = new TokenStream(token.props[prop].val);
627 this.parseFunctionDeclaration(scope);
632 this.ts = new TokenStream(token.props[prop].val);
633 this.parseExpression(scope);
638 // it's an object literal..
639 // the values could be replaced..
645 token.items.forEach(function(expr) {
646 _this.ts = new TokenStream(expr);
647 _this.parseExpression(scope)
653 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
660 case ')': //Token.RP:
661 case ']': //Token.RB:
662 case '}': //Token.RB:
663 //print("<< EXIT EXPRESSION");
676 case 'STRN': // used for object lit detection..
677 //if (this.mode == 'BUILDING_SYMBOL_TREE')
678 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
686 if (this.mode == 'BUILDING_SYMBOL_TREE') {
688 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
690 //print("EXPR-NAME:" + token.toString());
693 //print("in NAME = " + token.toString());
694 //print("in NAME 0: " + this.ts.look(0).toString());
695 //print("in NAME 2: " + this.ts.lookTok(2).toString());
697 //print(this.ts.lookTok(-1).data);
699 if (this.ts.lookTok(-1).data == ".") {
703 if (symbol == 'this') {
707 if (this.mode == 'PASS2_SYMBOL_TREE') {
709 identifier = this.getIdentifier(symbol, scope, token);
710 //println("<B>??</B>");
711 if (identifier == false) {
713 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
714 // Here, we found an undeclared and un-namespaced symbol that is
715 // 3 characters or less in length. Declare it in the global scope.
716 // We don't need to declare longer symbols since they won't cause
717 // any conflict with other munged symbols.
718 this.globalScope.declareIdentifier(symbol, token);
719 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
720 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
723 //print("undeclared:" + token.toString())
728 //println("<B>++</B>");
729 token.identifier = identifier;
730 identifier.refcount++;
739 //println("<B>EID</B>");
741 //if (this.mode == 'BUILDING_SYMBOL_TREE')
742 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
744 //print('EXPR-KEYW:' + token.toString());
745 if (token.name == "FUNCTION") {
747 this.parseFunctionDeclaration(scope);
753 if (this.mode == 'BUILDING_SYMBOL_TREE') {
755 if (token.name == "EVAL") {
756 //print(JSON.stringify(token,null,4));
757 if (token.prefix && token.prefix.match(/eval:var:/g)) {
758 // look for eval:var:noreplace\n
759 // print("GOT MATCH?");
761 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
763 //print("PROTECT: " + a);
766 var hi = _t.getIdentifier(a, scope, token);
767 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
769 // println("PROTECT "+a+" from munge");
777 this.protectScopeFromObfuscation(scope);
778 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
786 //if (this.mode == 'BUILDING_SYMBOL_TREE')
787 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
792 //print("<< EXIT EXPRESSION");
797 parseCatch : function(scope) {
804 //token = getToken(-1);
805 //assert token.getType() == Token.CATCH;
806 token = this.ts.nextTok(1);
807 token = this.ts.nextTok(1);
810 //print(JSON.stringify(this.ts,null,4));
811 //assert token.getType() == Token.LP; (
812 //token = this.ts.nextTok();
813 //assert token.getType() == Token.NAME;
815 symbol = token.items[0][0].data;
818 if (this.mode == 'BUILDING_SYMBOL_TREE') {
819 // We must declare the exception identifier in the containing function
820 // scope to avoid errors related to the obfuscation process. No need to
821 // display a warning if the symbol was already declared here...
822 scope.declareIdentifier(symbol, token.items[0][0]);
824 //?? why inc the refcount?? - that should be set when building the tree???
825 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
826 identifier.refcount++;
829 token = this.ts.nextTok();
830 //assert token.getType() == Token.RP; // )
833 parseFunctionDeclaration : function(scope)
835 //print("PARSE FUNCTION");
841 var b4braceNesting = this.braceNesting + 0;
843 //this.logR("<B>PARSING FUNCTION</B>");
846 token = this.ts.nextTok();
847 if (token.type == "NAME") {
848 if (this.mode == 'BUILDING_SYMBOL_TREE') {
849 // Get the name of the function and declare it in the current scope.
851 if (scope.getIdentifier(symbol,token) != false) {
852 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
854 scope.declareIdentifier(symbol,token);
856 token = this.ts.nextTok();
860 // return function() {....
861 while (token.data != "(") {
862 //print(token.toString());
863 token = this.ts.nextTok();
870 //assert token.getType() == Token.LP;
871 if (this.mode == 'BUILDING_SYMBOL_TREE') {
872 fnScope = new Scope(1, scope, token.n, '', token);
874 //println("STORING SCOPE" + this.ts.cursor);
876 this.indexedScopes[token.id] = fnScope;
879 //qln("FETCHING SCOPE" + this.ts.cursor);
880 fnScope = this.indexedScopes[token.id];
882 //if (this.mode == 'BUILDING_SYMBOL_TREE')
883 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
884 // Parse function arguments.
885 var args = token.items;
886 for (var argpos =0; argpos < args.length; argpos++) {
888 token = args[argpos][0];
889 //print ("FUNC ARGS: " + token.toString())
890 //assert token.getType() == Token.NAME ||
891 // token.getType() == Token.COMMA;
892 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
894 identifier = fnScope.declareIdentifier(symbol,token);
895 if (symbol == "$super" && argpos == 0) {
896 // Exception for Prototype 1.6...
897 identifier.preventMunging();
903 token = this.ts.nextTok();
904 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
906 //print(token.toString());
907 // assert token.getType() == Token.LC;
908 //this.braceNesting++;
910 //token = this.ts.nextTok();
911 //print(token.toString());
914 token.items.forEach(function(tar) {
915 _this.ts = new TokenStream(tar);
916 _this.parseScope(fnScope);
921 //print(JSON.stringify(this.ts,null,4));
922 //this.parseScope(fnScope);
924 // now pop it off the stack!!!
926 //this.braceNesting = b4braceNesting;
927 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
928 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
929 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
932 protectScopeFromObfuscation : function(scope) {
933 //assert scope != null;
935 if (scope == this.globalScope) {
936 // The global scope does not get obfuscated,
937 // so we don't need to worry about it...
941 // Find the highest local scope containing the specified scope.
942 while (scope && scope.parent != this.globalScope) {
943 scope = scope.parent;
946 //assert scope.getParentScope() == globalScope;
947 scope.preventMunging();
950 getIdentifier: function(symbol, scope, token) {
952 while (scope != false) {
953 identifier = scope.getIdentifier(symbol, token);
954 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
958 scope = scope.parent;