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 ];
227 this.scopes.push(scope);
231 //var scopeIndent = '';
232 //this.scopes.forEach(function() {
233 // scopeIndent += ' ';
235 print(">> ENTER SCOPE");
240 token = this.ts.lookTok(1);
242 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
243 //this.dumpToken(token , this.scopes, this.braceNesting);
244 print('SCOPE:' + token.toString());
245 //this.log(token.data);
246 if (token.type == 'NAME') {
247 // print('*' + token.data);
249 switch(token.type + '.' + token.name) {
251 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
252 print('SCOPE-VAR:' + token.toString());
253 var vstart = this.ts.cursor +1;
255 //this.log("parseScope GOT VAR/CONST : " + token.toString());
257 token = this.ts.nextTok();
258 //!this.debug|| print( token.toString());
259 print('SCOPE-VAR-VAL:' + token.toString());
260 if (!token) { // can return false at EOF!
263 if (token.name == "VAR" || token.data == ',') { // kludge..
266 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
267 if (token.type != "NAME") {
268 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
269 print(this.ts.tokens[i].toString());
272 print( "var without ident");
277 if (this.mode == "BUILDING_SYMBOL_TREE") {
278 identifier = scope.getIdentifier(token.data) ;
280 if (identifier == false) {
281 scope.declareIdentifier(token.data, token);
283 token.identifier = identifier;
284 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
288 token = this.ts.nextTok();
289 !this.debug|| print(token.toString());
291 assert token.getType() == Token.SEMI ||
292 token.getType() == Token.ASSIGN ||
293 token.getType() == Token.COMMA ||
294 token.getType() == Token.IN;
296 if (token.name == "IN") {
299 //var bn = this.braceNesting;
300 var bn = this.braceNesting;
301 this.parseExpression();
302 this.braceNesting = bn;
303 //this.braceNesting = bn;
304 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
306 token = this.ts.lookTok(1);
307 !this.debug|| print("AFTER EXP: " + token.toString());
308 if (token.data == ';') {
315 //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();
324 this.braceNesting = bn;
327 case "PUNC.LEFT_CURLY": // {
328 case "PUNC.LEFT_PAREN": // (
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();
348 this.ts = new TokenStream(token.props[prop].val);
349 this.parseScope(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");
378 //println("<i>"+token.data+"</i>");
381 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
382 //assert braceNesting >= scope.getBra ceNesting();
384 if (this.braceNesting < expressionBraceNesting) {
385 var ls = this.scopes.pop();
387 // eat symbol if we are currently at {
388 if (this.ts.look(0).data == '{') {
392 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
398 print('SCOPE-WITH:' + token.toString());
399 //println("<i>"+token.data+"</i>");
400 if (this.mode == "BUILDING_SYMBOL_TREE") {
401 // Inside a 'with' block, it is impossible to figure out
402 // statically whether a symbol is a local variable or an
403 // object member. As a consequence, the only thing we can
404 // do is turn the obfuscation off for the highest scope
405 // containing the 'with' block.
406 this.protectScopeFromObfuscation(scope);
407 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
412 print('SCOPE-CATCH:' + token.toString());
413 //println("<i>"+token.data+"</i>");
417 case Token.SPECIALCOMMENT:
418 if (mode == BUILDING_SYMBOL_TREE) {
419 protectScopeFromObfuscation(scope);
420 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
425 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
426 case "STRN.SINGLE_QUOTE":
427 print('SCOPE-STRING:' + token.toString());
428 //println("<i>"+token.data+"</i>");
430 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
431 // then we are in an object lit.. -> we need to flag the brace as such...
433 isObjectLitAr.push(true);
434 //print(">>>>>> OBJLIT REPUSH(true)");
436 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
438 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
439 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
440 // see if we can replace..
441 // remove the quotes..
442 // should do a bit more checking!!!! (what about wierd char's in the string..
443 var str = token.data.substring(1,token.data.length-1);
444 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
457 print('SCOPE-NAME:' + token.toString());
458 //print("DEAL WITH NAME:");
461 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
462 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
464 isObjectLitAr.push(true);
465 //print(">>>>>> OBJLIT REPUSH(true)");
466 //println("<i>"+token.data+"</i>");
469 // print("DEAL WITH obj lit:");
470 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
472 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
473 // skip, it's an object lit key..
474 //println("<i>"+token.data+"</i>");
479 // skip anyting with "." before it..!!
481 if (this.ts.lookTok(-1).data == ".") {
482 // skip, it's an object prop.
483 //println("<i>"+token.data+"</i>");
486 //print("SYMBOL: " + token.toString());
489 if (this.mode == 'PASS2_SYMBOL_TREE') {
491 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
493 //print ("MUNGE?" + symbol);
495 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
497 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
498 identifier = this.getIdentifier(symbol, scope);
500 if (identifier == false) {
501 // BUG!find out where builtin is defined...
502 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
503 // Here, we found an undeclared and un-namespaced symbol that is
504 // 3 characters or less in length. Declare it in the global scope.
505 // We don't need to declare longer symbols since they won't cause
506 // any conflict with other munged symbols.
507 this.globalScope.declareIdentifier(symbol, token);
508 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
511 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
513 token.identifier = identifier;
514 identifier.refcount++;
519 //println("<B>SID</B>");
521 if (token.type != 'KEYW') {
524 print('SCOPE-KEYW:' + token.toString());
525 // print("Check eval:");
529 if (this.mode == 'BUILDING_SYMBOL_TREE') {
531 if (symbol == "eval") {
532 // look back one and see if we can find a comment!!!
533 if (this.ts.look(-1).type == "COMM") {
534 // look for eval:var:noreplace\n
536 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
538 var hi = _t.getIdentifier(a, scope);
539 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
541 // println("PROTECT "+a+" from munge");
551 this.protectScopeFromObfuscation(scope);
552 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);
564 //print("parseScope TOK : " + token.toString());
565 token = this.ts.nextTok();
566 //if (this.ts.nextT()) break;
569 print("<<< EXIT SCOPE");
570 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
574 parseExpression : function() {
576 // Parse the expression until we encounter a comma or a semi-colon
577 // in the same brace nesting, bracket nesting and paren nesting.
578 // Parse functions if any...
579 //println("<i>EXP</i><BR/>");
580 !this.debug || print("PARSE EXPR");
583 // for printing stuff..
592 var expressionBraceNesting = this.braceNesting + 0;
593 var bracketNesting = 0;
594 var parensNesting = 0;
596 var isObjectLitAr = [ false ];
598 currentScope = this.scopes[this.scopes.length-1];
601 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
602 while (token = this.ts.nextTok()) {
607 // moved out of loop?
608 currentScope = this.scopes[this.scopes.length-1];
610 var scopeIndent = '';
611 this.scopes.forEach(function() {
616 //this.dumpToken(token, this.scopes, this.braceNesting );
617 print('EXP' + token.toString());
620 //println("<i>"+token.data+"</i>");
621 //this.log("EXP:" + token.data);
622 switch (token.type) {
624 print("EXPR-PUNC:" + token.toString());
629 print("<< EXIT EXPRESSION");
637 case '(': //Token.LP:
638 case '{': //Token.LC:
639 case '[': //Token.LB:
640 print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
641 //println("<i>"+token.data+"</i>");
645 for (var prop in token.props) {
646 if (token.props[prop].val.data == 'function') {
647 // parse a function..
648 this.parseFunctProp(token.props[prop]);
653 this.ts = new TokenStream(token.props[prop].val);
654 this.parseScope(currentScope);
659 // it's an object literal..
660 // the values could be replaced..
666 token.items.forEach(function(expr) {
667 _this.ts = new TokenStream(expr);
668 _this.parseExpression()
674 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
681 case ')': //Token.RP:
682 case ']': //Token.RB:
683 case '}': //Token.RB:
684 print("<< EXIT EXPRESSION");
697 case 'STRN': // used for object lit detection..
698 if (this.mode == 'BUILDING_SYMBOL_TREE')
699 print("EXPR-STR:" + JSON.stringify(token, null, 4));
707 if (this.mode == 'BUILDING_SYMBOL_TREE')
708 print("EXPR-NAME:" + JSON.stringify(token, null, 4));
710 //print("in NAME = " + token.toString());
711 //print("in NAME 0: " + this.ts.look(0).toString());
712 //print("in NAME 2: " + this.ts.lookTok(2).toString());
714 //print(this.ts.lookTok(0).data);
716 if (this.ts.lookTok(0).data == ".") {
722 if (this.mode == 'PASS2_SYMBOL_TREE') {
724 identifier = this.getIdentifier(symbol, currentScope);
725 //println("<B>??</B>");
726 if (identifier == false) {
728 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
729 // Here, we found an undeclared and un-namespaced symbol that is
730 // 3 characters or less in length. Declare it in the global scope.
731 // We don't need to declare longer symbols since they won't cause
732 // any conflict with other munged symbols.
733 this.globalScope.declareIdentifier(symbol, token);
734 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
736 print("undeclared:" + token.toString())
741 //println("<B>++</B>");
742 token.identifier = identifier;
743 identifier.refcount++;
752 //println("<B>EID</B>");
754 if (this.mode == 'BUILDING_SYMBOL_TREE')
755 print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
756 if (token.name == "FUNCTION") {
758 this.parseFunctionDeclaration();
765 if (this.mode == 'BUILDING_SYMBOL_TREE') {
767 if (symbol == "eval") {
768 if (this.ts.look(-1).type == 'COMM') {
769 // look for eval:var:noreplace\n
771 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
772 var hi = _t.getIdentifier(a, currentScope);
773 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
775 // println("PROTECT "+a+" from munge");
783 this.protectScopeFromObfuscation(currentScope);
784 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
792 if (this.mode == 'BUILDING_SYMBOL_TREE')
793 print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
798 print("<< EXIT EXPRESSION");
803 parseCatch : function() {
810 //token = getToken(-1);
811 //assert token.getType() == Token.CATCH;
812 token = this.ts.nextTok();
813 //assert token.getType() == Token.LP; (
814 token = this.ts.nextTok();
815 //assert token.getType() == Token.NAME;
818 currentScope = this.scopes[this.scopes.length-1];
820 if (this.mode == 'BUILDING_SYMBOL_TREE') {
821 // We must declare the exception identifier in the containing function
822 // scope to avoid errors related to the obfuscation process. No need to
823 // display a warning if the symbol was already declared here...
824 currentScope.declareIdentifier(symbol, token);
826 //?? why inc the refcount?? - that should be set when building the tree???
827 identifier = this.getIdentifier(symbol, currentScope);
828 identifier.refcount++;
831 token = this.ts.nextTok();
832 //assert token.getType() == Token.RP; // )
835 parseFunctionDeclaration : function()
837 //print("PARSE FUNCTION");
840 var currentScope = false;
843 var b4braceNesting = this.braceNesting + 0;
845 //this.logR("<B>PARSING FUNCTION</B>");
846 currentScope = this.scopes[this.scopes.length-1];
848 token = this.ts.nextTok();
849 if (token.type == "NAME") {
850 if (this.mode == 'BUILDING_SYMBOL_TREE') {
851 // Get the name of the function and declare it in the current scope.
853 if (currentScope.getIdentifier(symbol) != false) {
854 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
856 currentScope.declareIdentifier(symbol,token);
858 token = this.ts.nextTok();
861 //assert token.getType() == Token.LP;
862 if (this.mode == 'BUILDING_SYMBOL_TREE') {
863 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
865 //println("STORING SCOPE" + this.ts.cursor);
867 this.indexedScopes[this.ts.cursor] = fnScope;
870 //qln("FETCHING SCOPE" + this.ts.cursor);
871 fnScope = this.indexedScopes[this.ts.cursor];
874 if (this.mode == 'BUILDING_SYMBOL_TREE')
875 print('FUNC-PARSE:' + JSON.stringify(token,null,4));
876 // Parse function arguments.
877 var args = token.items;
878 for (var argpos =0; argpos < args.length; argpos++) {
880 token = args[argpos][0];
881 print ("FUNC ARGS: " + token.toString())
882 //assert token.getType() == Token.NAME ||
883 // token.getType() == Token.COMMA;
884 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
886 identifier = fnScope.declareIdentifier(symbol,token);
887 if (symbol == "$super" && argpos == 0) {
888 // Exception for Prototype 1.6...
889 identifier.preventMunging();
895 token = this.ts.nextTok();
896 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
898 //print(token.toString());
899 // assert token.getType() == Token.LC;
900 //this.braceNesting++;
902 //token = this.ts.nextTok();
903 //print(token.toString());
906 token.items.forEach(function(tar) {
907 _this.ts = new TokenStream(tar);
908 _this.parseScope(fnScope);
912 //print(JSON.stringify(this.ts,null,4));
913 //this.parseScope(fnScope);
915 // now pop it off the stack!!!
917 //this.braceNesting = b4braceNesting;
918 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
919 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
920 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
923 protectScopeFromObfuscation : function(scope) {
924 //assert scope != null;
926 if (scope == this.globalScope) {
927 // The global scope does not get obfuscated,
928 // so we don't need to worry about it...
932 // Find the highest local scope containing the specified scope.
933 while (scope && scope.parent != this.globalScope) {
934 scope = scope.parent;
937 //assert scope.getParentScope() == globalScope;
938 scope.preventMunging();
941 getIdentifier: function(symbol, scope) {
943 while (scope != false) {
944 identifier = scope.getIdentifier(symbol);
945 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
949 scope = scope.parent;