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;
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 ];
226 this.scopes.push(scope);
228 //var scopeIndent = '';
229 //this.scopes.forEach(function() {
230 // scopeIndent += ' ';
232 print(">> ENTER SCOPE");
237 token = this.ts.lookTok(1);
239 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
240 //this.dumpToken(token , this.scopes, this.braceNesting);
241 print('SCOPE:' + token.toString());
242 //this.log(token.data);
243 if (token.type == 'NAME') {
244 // print('*' + token.data);
246 switch(token.type + '.' + token.name) {
248 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
249 print('SCOPE-VAR:' + token.toString());
250 var vstart = this.ts.cursor +1;
252 //this.log("parseScope GOT VAR/CONST : " + token.toString());
254 token = this.ts.nextTok();
255 //!this.debug|| print( token.toString());
256 print('SCOPE-VAR:' + token.toString());
257 if (!token) { // can return false at EOF!
260 if (token.name == "VAR" || token.data == ',') { // kludge..
263 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
264 if (token.type != "NAME") {
265 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
266 print(this.ts.tokens[i].toString());
269 print( "var without ident");
274 if (this.mode == "BUILDING_SYMBOL_TREE") {
275 identifier = scope.getIdentifier(token.data) ;
277 if (identifier == false) {
278 scope.declareIdentifier(token.data, token);
280 token.identifier = identifier;
281 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
285 token = this.ts.nextTok();
286 !this.debug|| print(token.toString());
288 assert token.getType() == Token.SEMI ||
289 token.getType() == Token.ASSIGN ||
290 token.getType() == Token.COMMA ||
291 token.getType() == Token.IN;
293 if (token.name == "IN") {
296 //var bn = this.braceNesting;
297 var bn = this.braceNesting;
298 this.parseExpression();
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);
315 case "KEYW.FUNCTION":
316 print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
317 //println("<i>"+token.data+"</i>");
318 var bn = this.braceNesting;
319 this.parseFunctionDeclaration();
320 this.braceNesting = bn;
323 case "PUNC.LEFT_CURLY": // {
325 //println("<i>"+token.data+"</i>");
329 for (var prop in token.props) {
330 if (token.props[prop].val.data == 'function') {
331 // parse a function..
332 this.parseFunctProp(token.props[prop]);
337 this.ts = new TokenStream(token.props[prop].val);
338 this.parseScope(scope);
343 // it's an object literal..
344 // the values could be replaced..
347 print('SCOPE-CURLY:' + JSON.stringify(token,null,4));
348 print("NOT PROPS"); Seed.quit();
350 isObjectLitAr.push(false);
353 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
356 case "PUNC.RIGHT_CURLY": // }
357 //println("<i>"+token.data+"</i>");
360 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
361 //assert braceNesting >= scope.getBra ceNesting();
363 if (this.braceNesting < expressionBraceNesting) {
364 var ls = this.scopes.pop();
366 // eat symbol if we are currently at {
367 if (this.ts.look(0).data == '{') {
371 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
377 print('SCOPE-WITH:' + token.toString());
378 //println("<i>"+token.data+"</i>");
379 if (this.mode == "BUILDING_SYMBOL_TREE") {
380 // Inside a 'with' block, it is impossible to figure out
381 // statically whether a symbol is a local variable or an
382 // object member. As a consequence, the only thing we can
383 // do is turn the obfuscation off for the highest scope
384 // containing the 'with' block.
385 this.protectScopeFromObfuscation(scope);
386 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
391 print('SCOPE-CATCH:' + token.toString());
392 //println("<i>"+token.data+"</i>");
396 case Token.SPECIALCOMMENT:
397 if (mode == BUILDING_SYMBOL_TREE) {
398 protectScopeFromObfuscation(scope);
399 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
404 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
405 case "STRN.SINGLE_QUOTE":
406 print('SCOPE-STRING:' + token.toString());
407 //println("<i>"+token.data+"</i>");
409 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
410 // then we are in an object lit.. -> we need to flag the brace as such...
412 isObjectLitAr.push(true);
413 //print(">>>>>> OBJLIT REPUSH(true)");
415 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
417 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
418 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
419 // see if we can replace..
420 // remove the quotes..
421 // should do a bit more checking!!!! (what about wierd char's in the string..
422 var str = token.data.substring(1,token.data.length-1);
423 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
436 print('SCOPE-NAME:' + token.toString());
437 //print("DEAL WITH NAME:");
440 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
441 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
443 isObjectLitAr.push(true);
444 //print(">>>>>> OBJLIT REPUSH(true)");
445 //println("<i>"+token.data+"</i>");
448 // print("DEAL WITH obj lit:");
449 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
451 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
452 // skip, it's an object lit key..
453 //println("<i>"+token.data+"</i>");
458 // skip anyting with "." before it..!!
460 if (this.ts.lookTok(-1).data == ".") {
461 // skip, it's an object prop.
462 //println("<i>"+token.data+"</i>");
465 //print("SYMBOL: " + token.toString());
468 if (this.mode == 'PASS2_SYMBOL_TREE') {
470 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
472 //print ("MUNGE?" + symbol);
474 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
476 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
477 identifier = this.getIdentifier(symbol, scope);
479 if (identifier == false) {
480 // BUG!find out where builtin is defined...
481 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
482 // Here, we found an undeclared and un-namespaced symbol that is
483 // 3 characters or less in length. Declare it in the global scope.
484 // We don't need to declare longer symbols since they won't cause
485 // any conflict with other munged symbols.
486 this.globalScope.declareIdentifier(symbol, token);
487 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
490 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
492 token.identifier = identifier;
493 identifier.refcount++;
498 //println("<B>SID</B>");
500 if (token.type != 'KEYW') {
503 print('SCOPE-KEYW:' + token.toString());
504 // print("Check eval:");
508 if (this.mode == 'BUILDING_SYMBOL_TREE') {
510 if (symbol == "eval") {
511 // look back one and see if we can find a comment!!!
512 if (this.ts.look(-1).type == "COMM") {
513 // look for eval:var:noreplace\n
515 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
517 var hi = _t.getIdentifier(a, scope);
518 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
520 // println("PROTECT "+a+" from munge");
530 this.protectScopeFromObfuscation(scope);
531 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);
543 //print("parseScope TOK : " + token.toString());
544 token = this.ts.nextTok();
545 //if (this.ts.nextT()) break;
548 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
552 parseExpression : function() {
554 // Parse the expression until we encounter a comma or a semi-colon
555 // in the same brace nesting, bracket nesting and paren nesting.
556 // Parse functions if any...
557 //println("<i>EXP</i><BR/>");
558 !this.debug || print("PARSE EXPR");
561 // for printing stuff..
570 var expressionBraceNesting = this.braceNesting + 0;
571 var bracketNesting = 0;
572 var parensNesting = 0;
574 var isObjectLitAr = [ false ];
576 currentScope = this.scopes[this.scopes.length-1];
579 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
580 while (token = this.ts.nextTok()) {
585 // moved out of loop?
586 currentScope = this.scopes[this.scopes.length-1];
588 var scopeIndent = '';
589 this.scopes.forEach(function() {
594 //this.dumpToken(token, this.scopes, this.braceNesting );
595 print('EXP' + token.toString());
598 //println("<i>"+token.data+"</i>");
599 //this.log("EXP:" + token.data);
600 switch (token.type) {
602 print("EXPR-PUNC:" + JSON.stringify(token, null, 4));
608 if (this.braceNesting == expressionBraceNesting &&
609 bracketNesting == 0 &&
610 parensNesting == 0) {
611 print("<< EXIT EXPRESSION");
619 case '{': //Token.LC:
620 isObjectLitAr.push(false);
623 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
626 case '}': //Token.RC:
629 //print(">>>>> EXP POP" + this.braceNesting);
630 // assert braceNesting >= expressionBraceNesting;
633 case '[': //Token.LB:
637 token.items.forEach(function(ns) {
638 print("EXPR-PUNC-MAKE:" + JSON.stringify(ns, null, 4));
639 _this.ts = new TokenStream(ns);
641 _this.parseExpression();
647 case ']': //Token.RB:
651 case '(': //Token.LP:
655 case ')': //Token.RP:
661 case 'STRN': // used for object lit detection..
662 print("EXPR-STR:" + JSON.stringify(token, null, 4));
663 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
664 // then we are in an object lit.. -> we need to flag the brace as such...
666 isObjectLitAr.push(true);
667 //print(">>>>> EXP PUSH(true)");
672 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
673 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
674 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
675 // see if we can replace..
676 // remove the quotes..
677 var str = token.data.substring(1,token.data.length-1);
678 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
691 print("EXPR-NAME:" + JSON.stringify(token, null, 4));
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());
696 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
697 // then we are in an object lit.. -> we need to flag the brace as such...
699 isObjectLitAr.push(true);
700 //print(">>>>> EXP PUSH(true)");
704 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
705 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
707 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
710 //print(this.ts.lookTok(0).data);
711 if (this.ts.lookTok(0).data == ".") {
716 if (this.mode == 'PASS2_SYMBOL_TREE') {
718 identifier = this.getIdentifier(symbol, currentScope);
719 //println("<B>??</B>");
720 if (identifier == false) {
722 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
723 // Here, we found an undeclared and un-namespaced symbol that is
724 // 3 characters or less in length. Declare it in the global scope.
725 // We don't need to declare longer symbols since they won't cause
726 // any conflict with other munged symbols.
727 this.globalScope.declareIdentifier(symbol, token);
728 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
730 //println("undeclared")
735 //println("<B>++</B>");
736 token.identifier = identifier;
737 identifier.refcount++;
746 //println("<B>EID</B>");
748 print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
749 if (token.name == "FUNCTION") {
751 this.parseFunctionDeclaration();
758 if (this.mode == 'BUILDING_SYMBOL_TREE') {
760 if (symbol == "eval") {
761 if (this.ts.look(-1).type == 'COMM') {
762 // look for eval:var:noreplace\n
764 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
765 var hi = _t.getIdentifier(a, currentScope);
766 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
768 // println("PROTECT "+a+" from munge");
776 this.protectScopeFromObfuscation(currentScope);
777 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
785 print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
790 print("<< EXIT EXPRESSION");
795 parseCatch : function() {
802 //token = getToken(-1);
803 //assert token.getType() == Token.CATCH;
804 token = this.ts.nextTok();
805 //assert token.getType() == Token.LP; (
806 token = this.ts.nextTok();
807 //assert token.getType() == Token.NAME;
810 currentScope = this.scopes[this.scopes.length-1];
812 if (this.mode == 'BUILDING_SYMBOL_TREE') {
813 // We must declare the exception identifier in the containing function
814 // scope to avoid errors related to the obfuscation process. No need to
815 // display a warning if the symbol was already declared here...
816 currentScope.declareIdentifier(symbol, token);
818 //?? why inc the refcount?? - that should be set when building the tree???
819 identifier = this.getIdentifier(symbol, currentScope);
820 identifier.refcount++;
823 token = this.ts.nextTok();
824 //assert token.getType() == Token.RP; // )
827 parseFunctionDeclaration : function()
829 //print("PARSE FUNCTION");
832 var currentScope = false;
835 var b4braceNesting = this.braceNesting + 0;
837 //this.logR("<B>PARSING FUNCTION</B>");
838 currentScope = this.scopes[this.scopes.length-1];
840 token = this.ts.nextTok();
841 if (token.type == "NAME") {
842 if (this.mode == 'BUILDING_SYMBOL_TREE') {
843 // Get the name of the function and declare it in the current scope.
845 if (currentScope.getIdentifier(symbol) != false) {
846 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
848 currentScope.declareIdentifier(symbol,token);
850 token = this.ts.nextTok();
853 //assert token.getType() == Token.LP;
854 if (this.mode == 'BUILDING_SYMBOL_TREE') {
855 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
857 //println("STORING SCOPE" + this.ts.cursor);
859 this.indexedScopes[this.ts.cursor] = fnScope;
862 //qln("FETCHING SCOPE" + this.ts.cursor);
863 fnScope = this.indexedScopes[this.ts.cursor];
867 print('FUNC-PARSE:' + JSON.stringify(token,null,4));
868 // Parse function arguments.
869 var args = token.items;
870 for (var argpos =0; argpos < args.length; argpos++) {
872 token = args[argpos][0];
873 // print ("FUNC ARGS: " + token.toString())
874 //assert token.getType() == Token.NAME ||
875 // token.getType() == Token.COMMA;
876 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
878 identifier = fnScope.declareIdentifier(symbol,token);
879 if (symbol == "$super" && argpos == 0) {
880 // Exception for Prototype 1.6...
881 identifier.preventMunging();
887 token = this.ts.nextTok();
888 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
890 //print(token.toString());
891 // assert token.getType() == Token.LC;
892 //this.braceNesting++;
894 //token = this.ts.nextTok();
895 //print(token.toString());
898 token.items.forEach(function(tar) {
899 _this.ts = new TokenStream(tar);
900 _this.parseScope(fnScope);
904 //print(JSON.stringify(this.ts,null,4));
905 //this.parseScope(fnScope);
907 // now pop it off the stack!!!
909 //this.braceNesting = b4braceNesting;
910 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
911 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
912 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
915 protectScopeFromObfuscation : function(scope) {
916 //assert scope != null;
918 if (scope == this.globalScope) {
919 // The global scope does not get obfuscated,
920 // so we don't need to worry about it...
924 // Find the highest local scope containing the specified scope.
925 while (scope && scope.parent != this.globalScope) {
926 scope = scope.parent;
929 //assert scope.getParentScope() == globalScope;
930 scope.preventMunging();
933 getIdentifier: function(symbol, scope) {
935 while (scope != false) {
936 identifier = scope.getIdentifier(symbol);
937 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
941 scope = scope.parent;