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;
144 print(JSON.stringify(this.ts.tokens, null,4));
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 ];
227 if (thisScope && thisScope.gid != this.scopes[this.scopes.length-1]) {
228 this.scopes.push(scope);
230 thisScope = this.scopes[this.scopes.length-1]
233 //var scopeIndent = '';
234 //this.scopes.forEach(function() {
235 // scopeIndent += ' ';
237 //print(">> ENTER SCOPE");
242 token = this.ts.lookTok(1);
244 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
245 //this.dumpToken(token , this.scopes, this.braceNesting);
246 //print('SCOPE:' + token.toString());
247 //this.log(token.data);
248 if (token.type == 'NAME') {
249 // print('*' + token.data);
251 switch(token.type + '.' + token.name) {
253 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
254 //print('SCOPE-VAR:' + token.toString());
255 var vstart = this.ts.cursor +1;
257 //this.log("parseScope GOT VAR/CONST : " + token.toString());
259 token = this.ts.nextTok();
260 //!this.debug|| print( token.toString());
261 print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
262 if (!token) { // can return false at EOF!
265 if (token.name == "VAR" || token.data == ',') { // kludge..
268 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
269 if (token.type != "NAME") {
270 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
271 print(this.ts.tokens[i].toString());
274 print( "var without ident");
279 if (this.mode == "BUILDING_SYMBOL_TREE") {
280 identifier = thisScope.getIdentifier(token.data,token) ;
282 if (identifier == false) {
283 thisScope.declareIdentifier(token.data, token);
285 token.identifier = identifier;
286 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
290 token = this.ts.nextTok();
291 !this.debug|| print(token.toString());
293 assert token.getType() == Token.SEMI ||
294 token.getType() == Token.ASSIGN ||
295 token.getType() == Token.COMMA ||
296 token.getType() == Token.IN;
298 if (token.name == "IN") {
301 //var bn = this.braceNesting;
302 var bn = this.braceNesting;
306 if (!token || token.type == 'VOID' || token.data == ',') {
310 token = this.ts.nextTok();
314 this.ts = new TokenStream(nts);
315 this.parseExpression();
319 this.braceNesting = bn;
320 //this.braceNesting = bn;
321 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
323 token = this.ts.lookTok(1);
324 !this.debug|| print("AFTER EXP: " + token.toString());
325 if (token.data == ';') {
332 //this.ts.dump(vstart , this.ts.cursor);
335 case "KEYW.FUNCTION":
336 //if (this.mode == 'BUILDING_SYMBOL_TREE')
337 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
338 //println("<i>"+token.data+"</i>");
339 var bn = this.braceNesting;
340 this.parseFunctionDeclaration();
341 this.braceNesting = bn;
344 case "PUNC.LEFT_CURLY": // {
345 case "PUNC.LEFT_PAREN": // (
346 case "PUNC.LEFT_BRACE": // [
347 //print('SCOPE-CURLY/PAREN:' + token.toString());
348 //println("<i>"+token.data+"</i>");
352 for (var prop in token.props) {
355 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
356 if (token.props[prop].val[0].data == 'function') {
357 // parse a function..
358 this.ts = new TokenStream(token.props[prop].val);
360 this.parseFunctionDeclaration();
366 this.ts = new TokenStream(token.props[prop].val);
367 this.parseExpression();
372 // it's an object literal..
373 // the values could be replaced..
379 token.items.forEach(function(expr) {
380 _this.ts = new TokenStream(expr);
381 _this.parseExpression()
384 //print("NOT PROPS"); Seed.quit();
386 //isObjectLitAr.push(false);
387 //this.braceNesting++;
389 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
392 case "PUNC.RIGHT_CURLY": // }
393 //print("<< EXIT SCOPE");
396 //println("<i>"+token.data+"</i>");
399 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
400 //assert braceNesting >= scope.getBra ceNesting();
402 if (this.braceNesting < expressionBraceNesting) {
403 var ls = this.scopes.pop();
405 // eat symbol if we are currently at {
406 if (this.ts.look(0).data == '{') {
410 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
416 //print('SCOPE-WITH:' + token.toString());
417 //println("<i>"+token.data+"</i>");
418 if (this.mode == "BUILDING_SYMBOL_TREE") {
419 // Inside a 'with' block, it is impossible to figure out
420 // statically whether a symbol is a local variable or an
421 // object member. As a consequence, the only thing we can
422 // do is turn the obfuscation off for the highest scope
423 // containing the 'with' block.
424 this.protectScopeFromObfuscation(thisScope);
425 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
430 //print('SCOPE-CATCH:' + token.toString());
431 //println("<i>"+token.data+"</i>");
435 case Token.SPECIALCOMMENT:
436 if (mode == BUILDING_SYMBOL_TREE) {
437 protectScopeFromObfuscation(scope);
438 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
443 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
444 case "STRN.SINGLE_QUOTE":
445 // print('SCOPE-STRING:' + token.toString());
446 //println("<i>"+token.data+"</i>");
448 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
449 // then we are in an object lit.. -> we need to flag the brace as such...
451 isObjectLitAr.push(true);
452 //print(">>>>>> OBJLIT REPUSH(true)");
454 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
456 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
457 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
458 // see if we can replace..
459 // remove the quotes..
460 // should do a bit more checking!!!! (what about wierd char's in the string..
461 var str = token.data.substring(1,token.data.length-1);
462 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
475 //print('SCOPE-NAME:' + token.toString());
476 //print("DEAL WITH NAME:");
479 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
482 // skip anyting with "." before it..!!
484 if (this.ts.lookTok(-1).data == ".") {
485 // skip, it's an object prop.
486 //println("<i>"+token.data+"</i>");
489 //print("SYMBOL: " + token.toString());
492 if (symbol == 'this') {
495 if (this.mode == 'PASS2_SYMBOL_TREE') {
497 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
499 //print ("MUNGE?" + symbol);
501 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
503 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
504 identifier = this.getIdentifier(symbol, thisScope, token);
506 if (identifier == false) {
507 // BUG!find out where builtin is defined...
508 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
509 // Here, we found an undeclared and un-namespaced symbol that is
510 // 3 characters or less in length. Declare it in the global scope.
511 // We don't need to declare longer symbols since they won't cause
512 // any conflict with other munged symbols.
513 this.globalScope.declareIdentifier(symbol, token);
514 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
517 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
519 token.identifier = identifier;
520 identifier.refcount++;
525 //println("<B>SID</B>");
527 if (token.type != 'KEYW') {
530 //print('SCOPE-KEYW:' + token.toString());
531 // print("Check eval:");
535 if (this.mode == 'BUILDING_SYMBOL_TREE') {
537 if (symbol == "eval") {
538 // look back one and see if we can find a comment!!!
539 //if (this.ts.look(-1).type == "COMM") {
540 if (token.prefix && token.prefix.match('/eval/')) {
541 // look for eval:var:noreplace\n
543 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
545 var hi = _t.getIdentifier(a, thisScope, token);
546 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
548 // println("PROTECT "+a+" from munge");
558 this.protectScopeFromObfuscation(thisScope);
559 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);
571 //print("parseScope TOK : " + token.toString());
572 token = this.ts.nextTok();
573 //if (this.ts.nextT()) break;
576 //print("<<< EXIT SCOPE");
577 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
581 parseExpression : function() {
583 // Parse the expression until we encounter a comma or a semi-colon
584 // in the same brace nesting, bracket nesting and paren nesting.
585 // Parse functions if any...
586 //println("<i>EXP</i><BR/>");
587 !this.debug || print("PARSE EXPR");
590 // for printing stuff..
599 var expressionBraceNesting = this.braceNesting + 0;
600 var bracketNesting = 0;
601 var parensNesting = 0;
603 var isObjectLitAr = [ false ];
605 currentScope = this.scopes[this.scopes.length-1];
608 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
609 while (token = this.ts.nextTok()) {
614 // moved out of loop?
615 currentScope = this.scopes[this.scopes.length-1];
617 var scopeIndent = '';
618 this.scopes.forEach(function() {
623 //this.dumpToken(token, this.scopes, this.braceNesting );
624 //print('EXP' + token.toString());
627 //println("<i>"+token.data+"</i>");
628 //this.log("EXP:" + token.data);
629 switch (token.type) {
631 //print("EXPR-PUNC:" + token.toString());
636 //print("<< EXIT EXPRESSION");
644 case '(': //Token.LP:
645 case '{': //Token.LC:
646 case '[': //Token.LB:
647 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
648 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
649 //println("<i>"+token.data+"</i>");
653 for (var prop in token.props) {
654 if (token.props[prop].val[0].data == 'function') {
655 // parse a function..
656 this.ts = new TokenStream(token.props[prop].val);
658 this.parseFunctionDeclaration();
663 this.ts = new TokenStream(token.props[prop].val);
664 this.parseExpression();
669 // it's an object literal..
670 // the values could be replaced..
676 token.items.forEach(function(expr) {
677 _this.ts = new TokenStream(expr);
678 _this.parseExpression()
684 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
691 case ')': //Token.RP:
692 case ']': //Token.RB:
693 case '}': //Token.RB:
694 //print("<< EXIT EXPRESSION");
707 case 'STRN': // used for object lit detection..
708 //if (this.mode == 'BUILDING_SYMBOL_TREE')
709 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
717 if (this.mode == 'BUILDING_SYMBOL_TREE') {
719 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
721 //print("EXPR-NAME:" + token.toString());
724 //print("in NAME = " + token.toString());
725 //print("in NAME 0: " + this.ts.look(0).toString());
726 //print("in NAME 2: " + this.ts.lookTok(2).toString());
728 //print(this.ts.lookTok(-1).data);
730 if (this.ts.lookTok(-1).data == ".") {
734 if (symbol == 'this') {
738 if (this.mode == 'PASS2_SYMBOL_TREE') {
740 identifier = this.getIdentifier(symbol, currentScope, token);
741 //println("<B>??</B>");
742 if (identifier == false) {
744 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
745 // Here, we found an undeclared and un-namespaced symbol that is
746 // 3 characters or less in length. Declare it in the global scope.
747 // We don't need to declare longer symbols since they won't cause
748 // any conflict with other munged symbols.
749 this.globalScope.declareIdentifier(symbol, token);
750 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
751 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
754 //print("undeclared:" + token.toString())
759 //println("<B>++</B>");
760 token.identifier = identifier;
761 identifier.refcount++;
770 //println("<B>EID</B>");
772 //if (this.mode == 'BUILDING_SYMBOL_TREE')
773 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
774 if (token.name == "FUNCTION") {
776 this.parseFunctionDeclaration();
783 if (this.mode == 'BUILDING_SYMBOL_TREE') {
785 if (symbol == "eval") {
786 if (token.prefix && token.prefix.match('/eval/')) {
787 // look for eval:var:noreplace\n
789 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
790 var hi = _t.getIdentifier(a, currentScope, token);
791 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
793 // println("PROTECT "+a+" from munge");
801 this.protectScopeFromObfuscation(currentScope);
802 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
810 //if (this.mode == 'BUILDING_SYMBOL_TREE')
811 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
816 //print("<< EXIT EXPRESSION");
821 parseCatch : function() {
828 //token = getToken(-1);
829 //assert token.getType() == Token.CATCH;
830 token = this.ts.nextTok();
831 //assert token.getType() == Token.LP; (
832 //token = this.ts.nextTok();
833 //assert token.getType() == Token.NAME;
835 symbol = token.items[0].data;
836 currentScope = this.scopes[this.scopes.length-1];
838 if (this.mode == 'BUILDING_SYMBOL_TREE') {
839 // We must declare the exception identifier in the containing function
840 // scope to avoid errors related to the obfuscation process. No need to
841 // display a warning if the symbol was already declared here...
842 currentScope.declareIdentifier(symbol, token);
844 //?? why inc the refcount?? - that should be set when building the tree???
845 identifier = this.getIdentifier(symbol, currentScope, token);
846 identifier.refcount++;
849 token = this.ts.nextTok();
850 //assert token.getType() == Token.RP; // )
853 parseFunctionDeclaration : function()
855 //print("PARSE FUNCTION");
858 var currentScope = false;
861 var b4braceNesting = this.braceNesting + 0;
863 //this.logR("<B>PARSING FUNCTION</B>");
864 currentScope = this.scopes[this.scopes.length-1];
866 token = this.ts.nextTok();
867 if (token.type == "NAME") {
868 if (this.mode == 'BUILDING_SYMBOL_TREE') {
869 // Get the name of the function and declare it in the current scope.
871 if (currentScope.getIdentifier(symbol,token) != false) {
872 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
874 currentScope.declareIdentifier(symbol,token);
876 token = this.ts.nextTok();
878 // return function() {....
879 if (token.name == "RETURN") {
880 token = this.ts.nextTok();
882 if (token.name == "FUNCTION") {
883 token = this.ts.nextTok();
885 //assert token.getType() == Token.LP;
886 if (this.mode == 'BUILDING_SYMBOL_TREE') {
887 fnScope = new Scope(1, currentScope, token.n, '', token);
889 //println("STORING SCOPE" + this.ts.cursor);
891 this.indexedScopes[token.id] = fnScope;
894 //qln("FETCHING SCOPE" + this.ts.cursor);
895 fnScope = this.indexedScopes[token.id];
897 //if (this.mode == 'BUILDING_SYMBOL_TREE')
898 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
899 // Parse function arguments.
900 var args = token.items;
901 for (var argpos =0; argpos < args.length; argpos++) {
903 token = args[argpos][0];
904 //print ("FUNC ARGS: " + token.toString())
905 //assert token.getType() == Token.NAME ||
906 // token.getType() == Token.COMMA;
907 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
909 identifier = fnScope.declareIdentifier(symbol,token);
910 if (symbol == "$super" && argpos == 0) {
911 // Exception for Prototype 1.6...
912 identifier.preventMunging();
918 token = this.ts.nextTok();
919 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
921 //print(token.toString());
922 // assert token.getType() == Token.LC;
923 //this.braceNesting++;
925 //token = this.ts.nextTok();
926 //print(token.toString());
929 token.items.forEach(function(tar) {
930 _this.ts = new TokenStream(tar);
931 _this.parseScope(fnScope);
936 //print(JSON.stringify(this.ts,null,4));
937 //this.parseScope(fnScope);
939 // now pop it off the stack!!!
941 //this.braceNesting = b4braceNesting;
942 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
943 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
944 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
947 protectScopeFromObfuscation : function(scope) {
948 //assert scope != null;
950 if (scope == this.globalScope) {
951 // The global scope does not get obfuscated,
952 // so we don't need to worry about it...
956 // Find the highest local scope containing the specified scope.
957 while (scope && scope.parent != this.globalScope) {
958 scope = scope.parent;
961 //assert scope.getParentScope() == globalScope;
962 scope.preventMunging();
965 getIdentifier: function(symbol, scope, token) {
967 while (scope != false) {
968 identifier = scope.getIdentifier(symbol, token);
969 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
973 scope = scope.parent;