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..
348 print('SCOPE-CURLY:' + JSON.stringify(token,null,4));
350 token.items.forEach(function(expr) {
351 _this.ts = new TokenStream(expr);
352 _this.parseExpression(scope)
355 //print("NOT PROPS"); Seed.quit();
357 //isObjectLitAr.push(false);
358 //this.braceNesting++;
360 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
363 case "PUNC.RIGHT_CURLY": // }
364 print("<< EXIT SCOPE");
367 //println("<i>"+token.data+"</i>");
370 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
371 //assert braceNesting >= scope.getBra ceNesting();
373 if (this.braceNesting < expressionBraceNesting) {
374 var ls = this.scopes.pop();
376 // eat symbol if we are currently at {
377 if (this.ts.look(0).data == '{') {
381 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
387 print('SCOPE-WITH:' + token.toString());
388 //println("<i>"+token.data+"</i>");
389 if (this.mode == "BUILDING_SYMBOL_TREE") {
390 // Inside a 'with' block, it is impossible to figure out
391 // statically whether a symbol is a local variable or an
392 // object member. As a consequence, the only thing we can
393 // do is turn the obfuscation off for the highest scope
394 // containing the 'with' block.
395 this.protectScopeFromObfuscation(scope);
396 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
401 print('SCOPE-CATCH:' + token.toString());
402 //println("<i>"+token.data+"</i>");
406 case Token.SPECIALCOMMENT:
407 if (mode == BUILDING_SYMBOL_TREE) {
408 protectScopeFromObfuscation(scope);
409 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
414 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
415 case "STRN.SINGLE_QUOTE":
416 print('SCOPE-STRING:' + token.toString());
417 //println("<i>"+token.data+"</i>");
419 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
420 // then we are in an object lit.. -> we need to flag the brace as such...
422 isObjectLitAr.push(true);
423 //print(">>>>>> OBJLIT REPUSH(true)");
425 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
427 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
428 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
429 // see if we can replace..
430 // remove the quotes..
431 // should do a bit more checking!!!! (what about wierd char's in the string..
432 var str = token.data.substring(1,token.data.length-1);
433 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
446 print('SCOPE-NAME:' + token.toString());
447 //print("DEAL WITH NAME:");
450 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
451 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
453 isObjectLitAr.push(true);
454 //print(">>>>>> OBJLIT REPUSH(true)");
455 //println("<i>"+token.data+"</i>");
458 // print("DEAL WITH obj lit:");
459 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
461 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
462 // skip, it's an object lit key..
463 //println("<i>"+token.data+"</i>");
468 // skip anyting with "." before it..!!
470 if (this.ts.lookTok(-1).data == ".") {
471 // skip, it's an object prop.
472 //println("<i>"+token.data+"</i>");
475 //print("SYMBOL: " + token.toString());
478 if (this.mode == 'PASS2_SYMBOL_TREE') {
480 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
482 //print ("MUNGE?" + symbol);
484 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
486 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
487 identifier = this.getIdentifier(symbol, scope);
489 if (identifier == false) {
490 // BUG!find out where builtin is defined...
491 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
492 // Here, we found an undeclared and un-namespaced symbol that is
493 // 3 characters or less in length. Declare it in the global scope.
494 // We don't need to declare longer symbols since they won't cause
495 // any conflict with other munged symbols.
496 this.globalScope.declareIdentifier(symbol, token);
497 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
500 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
502 token.identifier = identifier;
503 identifier.refcount++;
508 //println("<B>SID</B>");
510 if (token.type != 'KEYW') {
513 print('SCOPE-KEYW:' + token.toString());
514 // print("Check eval:");
518 if (this.mode == 'BUILDING_SYMBOL_TREE') {
520 if (symbol == "eval") {
521 // look back one and see if we can find a comment!!!
522 if (this.ts.look(-1).type == "COMM") {
523 // look for eval:var:noreplace\n
525 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
527 var hi = _t.getIdentifier(a, scope);
528 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
530 // println("PROTECT "+a+" from munge");
540 this.protectScopeFromObfuscation(scope);
541 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);
553 //print("parseScope TOK : " + token.toString());
554 token = this.ts.nextTok();
555 //if (this.ts.nextT()) break;
558 print("<<< EXIT SCOPE");
559 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
563 parseExpression : function() {
565 // Parse the expression until we encounter a comma or a semi-colon
566 // in the same brace nesting, bracket nesting and paren nesting.
567 // Parse functions if any...
568 //println("<i>EXP</i><BR/>");
569 !this.debug || print("PARSE EXPR");
572 // for printing stuff..
581 var expressionBraceNesting = this.braceNesting + 0;
582 var bracketNesting = 0;
583 var parensNesting = 0;
585 var isObjectLitAr = [ false ];
587 currentScope = this.scopes[this.scopes.length-1];
590 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
591 while (token = this.ts.nextTok()) {
596 // moved out of loop?
597 currentScope = this.scopes[this.scopes.length-1];
599 var scopeIndent = '';
600 this.scopes.forEach(function() {
605 //this.dumpToken(token, this.scopes, this.braceNesting );
606 print('EXP' + token.toString());
609 //println("<i>"+token.data+"</i>");
610 //this.log("EXP:" + token.data);
611 switch (token.type) {
613 print("EXPR-PUNC:" + JSON.stringify(token, null, 4));
619 if (this.braceNesting == expressionBraceNesting &&
620 bracketNesting == 0 &&
621 parensNesting == 0) {
622 print("<< EXIT EXPRESSION");
630 case '{': //Token.LC:
631 isObjectLitAr.push(false);
634 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
637 case '}': //Token.RC:
640 //print(">>>>> EXP POP" + this.braceNesting);
641 // assert braceNesting >= expressionBraceNesting;
644 case '[': //Token.LB:
648 token.items.forEach(function(ns) {
649 print("EXPR-PUNC-MAKE:" + JSON.stringify(ns, null, 4));
650 _this.ts = new TokenStream(ns);
652 _this.parseExpression();
658 case ']': //Token.RB:
659 print("<< EXIT EXPRESSION");
663 case '(': //Token.LP:
667 case ')': //Token.RP:
673 case 'STRN': // used for object lit detection..
674 print("EXPR-STR:" + JSON.stringify(token, null, 4));
675 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
676 // then we are in an object lit.. -> we need to flag the brace as such...
678 isObjectLitAr.push(true);
679 //print(">>>>> EXP PUSH(true)");
684 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
685 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
686 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
687 // see if we can replace..
688 // remove the quotes..
689 var str = token.data.substring(1,token.data.length-1);
690 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
703 print("EXPR-NAME:" + JSON.stringify(token, null, 4));
705 //print("in NAME = " + token.toString());
706 //print("in NAME 0: " + this.ts.look(0).toString());
707 //print("in NAME 2: " + this.ts.lookTok(2).toString());
708 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
709 // then we are in an object lit.. -> we need to flag the brace as such...
711 isObjectLitAr.push(true);
712 //print(">>>>> EXP PUSH(true)");
716 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
717 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
719 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
722 //print(this.ts.lookTok(0).data);
723 if (this.ts.lookTok(0).data == ".") {
728 if (this.mode == 'PASS2_SYMBOL_TREE') {
730 identifier = this.getIdentifier(symbol, currentScope);
731 //println("<B>??</B>");
732 if (identifier == false) {
734 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
735 // Here, we found an undeclared and un-namespaced symbol that is
736 // 3 characters or less in length. Declare it in the global scope.
737 // We don't need to declare longer symbols since they won't cause
738 // any conflict with other munged symbols.
739 this.globalScope.declareIdentifier(symbol, token);
740 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
742 //println("undeclared")
747 //println("<B>++</B>");
748 token.identifier = identifier;
749 identifier.refcount++;
758 //println("<B>EID</B>");
760 print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
761 if (token.name == "FUNCTION") {
763 this.parseFunctionDeclaration();
770 if (this.mode == 'BUILDING_SYMBOL_TREE') {
772 if (symbol == "eval") {
773 if (this.ts.look(-1).type == 'COMM') {
774 // look for eval:var:noreplace\n
776 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
777 var hi = _t.getIdentifier(a, currentScope);
778 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
780 // println("PROTECT "+a+" from munge");
788 this.protectScopeFromObfuscation(currentScope);
789 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
797 print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
802 print("<< EXIT EXPRESSION");
807 parseCatch : function() {
814 //token = getToken(-1);
815 //assert token.getType() == Token.CATCH;
816 token = this.ts.nextTok();
817 //assert token.getType() == Token.LP; (
818 token = this.ts.nextTok();
819 //assert token.getType() == Token.NAME;
822 currentScope = this.scopes[this.scopes.length-1];
824 if (this.mode == 'BUILDING_SYMBOL_TREE') {
825 // We must declare the exception identifier in the containing function
826 // scope to avoid errors related to the obfuscation process. No need to
827 // display a warning if the symbol was already declared here...
828 currentScope.declareIdentifier(symbol, token);
830 //?? why inc the refcount?? - that should be set when building the tree???
831 identifier = this.getIdentifier(symbol, currentScope);
832 identifier.refcount++;
835 token = this.ts.nextTok();
836 //assert token.getType() == Token.RP; // )
839 parseFunctionDeclaration : function()
841 //print("PARSE FUNCTION");
844 var currentScope = false;
847 var b4braceNesting = this.braceNesting + 0;
849 //this.logR("<B>PARSING FUNCTION</B>");
850 currentScope = this.scopes[this.scopes.length-1];
852 token = this.ts.nextTok();
853 if (token.type == "NAME") {
854 if (this.mode == 'BUILDING_SYMBOL_TREE') {
855 // Get the name of the function and declare it in the current scope.
857 if (currentScope.getIdentifier(symbol) != false) {
858 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
860 currentScope.declareIdentifier(symbol,token);
862 token = this.ts.nextTok();
865 //assert token.getType() == Token.LP;
866 if (this.mode == 'BUILDING_SYMBOL_TREE') {
867 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
869 //println("STORING SCOPE" + this.ts.cursor);
871 this.indexedScopes[this.ts.cursor] = fnScope;
874 //qln("FETCHING SCOPE" + this.ts.cursor);
875 fnScope = this.indexedScopes[this.ts.cursor];
879 print('FUNC-PARSE:' + JSON.stringify(token,null,4));
880 // Parse function arguments.
881 var args = token.items;
882 for (var argpos =0; argpos < args.length; argpos++) {
884 token = args[argpos][0];
885 // print ("FUNC ARGS: " + token.toString())
886 //assert token.getType() == Token.NAME ||
887 // token.getType() == Token.COMMA;
888 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
890 identifier = fnScope.declareIdentifier(symbol,token);
891 if (symbol == "$super" && argpos == 0) {
892 // Exception for Prototype 1.6...
893 identifier.preventMunging();
899 token = this.ts.nextTok();
900 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
902 //print(token.toString());
903 // assert token.getType() == Token.LC;
904 //this.braceNesting++;
906 //token = this.ts.nextTok();
907 //print(token.toString());
910 token.items.forEach(function(tar) {
911 _this.ts = new TokenStream(tar);
912 _this.parseScope(fnScope);
916 //print(JSON.stringify(this.ts,null,4));
917 //this.parseScope(fnScope);
919 // now pop it off the stack!!!
921 //this.braceNesting = b4braceNesting;
922 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
923 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
924 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
927 protectScopeFromObfuscation : function(scope) {
928 //assert scope != null;
930 if (scope == this.globalScope) {
931 // The global scope does not get obfuscated,
932 // so we don't need to worry about it...
936 // Find the highest local scope containing the specified scope.
937 while (scope && scope.parent != this.globalScope) {
938 scope = scope.parent;
941 //assert scope.getParentScope() == globalScope;
942 scope.preventMunging();
945 getIdentifier: function(symbol, scope) {
947 while (scope != false) {
948 identifier = scope.getIdentifier(symbol);
949 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
953 scope = scope.parent;