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": // {
324 case "PUNC.LEFT_PAREN": // (
325 print('SCOPE-CURLY/PAREN:' + token.toString());
326 //println("<i>"+token.data+"</i>");
330 for (var prop in token.props) {
331 if (token.props[prop].val.data == 'function') {
332 // parse a function..
333 this.parseFunctProp(token.props[prop]);
338 this.ts = new TokenStream(token.props[prop].val);
339 this.parseScope(scope);
344 // it's an object literal..
345 // the values could be replaced..
351 token.items.forEach(function(expr) {
352 _this.ts = new TokenStream(expr);
353 _this.parseExpression(scope)
356 //print("NOT PROPS"); Seed.quit();
358 //isObjectLitAr.push(false);
359 //this.braceNesting++;
361 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
364 case "PUNC.RIGHT_CURLY": // }
365 print("<< EXIT SCOPE");
368 //println("<i>"+token.data+"</i>");
371 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
372 //assert braceNesting >= scope.getBra ceNesting();
374 if (this.braceNesting < expressionBraceNesting) {
375 var ls = this.scopes.pop();
377 // eat symbol if we are currently at {
378 if (this.ts.look(0).data == '{') {
382 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
388 print('SCOPE-WITH:' + token.toString());
389 //println("<i>"+token.data+"</i>");
390 if (this.mode == "BUILDING_SYMBOL_TREE") {
391 // Inside a 'with' block, it is impossible to figure out
392 // statically whether a symbol is a local variable or an
393 // object member. As a consequence, the only thing we can
394 // do is turn the obfuscation off for the highest scope
395 // containing the 'with' block.
396 this.protectScopeFromObfuscation(scope);
397 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
402 print('SCOPE-CATCH:' + token.toString());
403 //println("<i>"+token.data+"</i>");
407 case Token.SPECIALCOMMENT:
408 if (mode == BUILDING_SYMBOL_TREE) {
409 protectScopeFromObfuscation(scope);
410 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
415 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
416 case "STRN.SINGLE_QUOTE":
417 print('SCOPE-STRING:' + token.toString());
418 //println("<i>"+token.data+"</i>");
420 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
421 // then we are in an object lit.. -> we need to flag the brace as such...
423 isObjectLitAr.push(true);
424 //print(">>>>>> OBJLIT REPUSH(true)");
426 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
428 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
429 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
430 // see if we can replace..
431 // remove the quotes..
432 // should do a bit more checking!!!! (what about wierd char's in the string..
433 var str = token.data.substring(1,token.data.length-1);
434 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
447 print('SCOPE-NAME:' + token.toString());
448 //print("DEAL WITH NAME:");
451 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
452 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
454 isObjectLitAr.push(true);
455 //print(">>>>>> OBJLIT REPUSH(true)");
456 //println("<i>"+token.data+"</i>");
459 // print("DEAL WITH obj lit:");
460 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
462 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
463 // skip, it's an object lit key..
464 //println("<i>"+token.data+"</i>");
469 // skip anyting with "." before it..!!
471 if (this.ts.lookTok(-1).data == ".") {
472 // skip, it's an object prop.
473 //println("<i>"+token.data+"</i>");
476 //print("SYMBOL: " + token.toString());
479 if (this.mode == 'PASS2_SYMBOL_TREE') {
481 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
483 //print ("MUNGE?" + symbol);
485 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
487 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
488 identifier = this.getIdentifier(symbol, scope);
490 if (identifier == false) {
491 // BUG!find out where builtin is defined...
492 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
493 // Here, we found an undeclared and un-namespaced symbol that is
494 // 3 characters or less in length. Declare it in the global scope.
495 // We don't need to declare longer symbols since they won't cause
496 // any conflict with other munged symbols.
497 this.globalScope.declareIdentifier(symbol, token);
498 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
501 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
503 token.identifier = identifier;
504 identifier.refcount++;
509 //println("<B>SID</B>");
511 if (token.type != 'KEYW') {
514 print('SCOPE-KEYW:' + token.toString());
515 // print("Check eval:");
519 if (this.mode == 'BUILDING_SYMBOL_TREE') {
521 if (symbol == "eval") {
522 // look back one and see if we can find a comment!!!
523 if (this.ts.look(-1).type == "COMM") {
524 // look for eval:var:noreplace\n
526 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
528 var hi = _t.getIdentifier(a, scope);
529 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
531 // println("PROTECT "+a+" from munge");
541 this.protectScopeFromObfuscation(scope);
542 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);
554 //print("parseScope TOK : " + token.toString());
555 token = this.ts.nextTok();
556 //if (this.ts.nextT()) break;
559 print("<<< EXIT SCOPE");
560 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
564 parseExpression : function() {
566 // Parse the expression until we encounter a comma or a semi-colon
567 // in the same brace nesting, bracket nesting and paren nesting.
568 // Parse functions if any...
569 //println("<i>EXP</i><BR/>");
570 !this.debug || print("PARSE EXPR");
573 // for printing stuff..
582 var expressionBraceNesting = this.braceNesting + 0;
583 var bracketNesting = 0;
584 var parensNesting = 0;
586 var isObjectLitAr = [ false ];
588 currentScope = this.scopes[this.scopes.length-1];
591 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
592 while (token = this.ts.nextTok()) {
597 // moved out of loop?
598 currentScope = this.scopes[this.scopes.length-1];
600 var scopeIndent = '';
601 this.scopes.forEach(function() {
606 //this.dumpToken(token, this.scopes, this.braceNesting );
607 print('EXP' + token.toString());
610 //println("<i>"+token.data+"</i>");
611 //this.log("EXP:" + token.data);
612 switch (token.type) {
614 print("EXPR-PUNC:" + token.toString());
619 print("<< EXIT EXPRESSION");
627 case '(': //Token.LP:
628 case '{': //Token.LC:
629 case '[': //Token.LB:
630 print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
631 //println("<i>"+token.data+"</i>");
635 for (var prop in token.props) {
636 if (token.props[prop].val.data == 'function') {
637 // parse a function..
638 this.parseFunctProp(token.props[prop]);
643 this.ts = new TokenStream(token.props[prop].val);
644 this.parseScope(currentScope);
649 // it's an object literal..
650 // the values could be replaced..
656 token.items.forEach(function(expr) {
657 _this.ts = new TokenStream(expr);
658 _this.parseExpression()
664 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
671 case ')': //Token.RP:
672 case ']': //Token.RB:
673 case '}': //Token.RB:
674 print("<< EXIT EXPRESSION");
687 case 'STRN': // used for object lit detection..
688 print("EXPR-STR:" + JSON.stringify(token, null, 4));
689 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
690 // then we are in an object lit.. -> we need to flag the brace as such...
692 isObjectLitAr.push(true);
693 //print(">>>>> EXP PUSH(true)");
698 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
699 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
700 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
701 // see if we can replace..
702 // remove the quotes..
703 var str = token.data.substring(1,token.data.length-1);
704 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
717 print("EXPR-NAME:" + JSON.stringify(token, null, 4));
719 //print("in NAME = " + token.toString());
720 //print("in NAME 0: " + this.ts.look(0).toString());
721 //print("in NAME 2: " + this.ts.lookTok(2).toString());
722 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
723 // then we are in an object lit.. -> we need to flag the brace as such...
725 isObjectLitAr.push(true);
726 //print(">>>>> EXP PUSH(true)");
730 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
731 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
733 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
736 //print(this.ts.lookTok(0).data);
737 if (this.ts.lookTok(0).data == ".") {
742 if (this.mode == 'PASS2_SYMBOL_TREE') {
744 identifier = this.getIdentifier(symbol, currentScope);
745 //println("<B>??</B>");
746 if (identifier == false) {
748 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
749 // Here, we found an undeclared and un-namespaced symbol that is
750 // 3 characters or less in length. Declare it in the global scope.
751 // We don't need to declare longer symbols since they won't cause
752 // any conflict with other munged symbols.
753 this.globalScope.declareIdentifier(symbol, token);
754 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
756 //println("undeclared")
761 //println("<B>++</B>");
762 token.identifier = identifier;
763 identifier.refcount++;
772 //println("<B>EID</B>");
774 print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
775 if (token.name == "FUNCTION") {
777 this.parseFunctionDeclaration();
784 if (this.mode == 'BUILDING_SYMBOL_TREE') {
786 if (symbol == "eval") {
787 if (this.ts.look(-1).type == 'COMM') {
788 // look for eval:var:noreplace\n
790 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
791 var hi = _t.getIdentifier(a, currentScope);
792 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
794 // println("PROTECT "+a+" from munge");
802 this.protectScopeFromObfuscation(currentScope);
803 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
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;
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);
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) != 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();
879 //assert token.getType() == Token.LP;
880 if (this.mode == 'BUILDING_SYMBOL_TREE') {
881 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
883 //println("STORING SCOPE" + this.ts.cursor);
885 this.indexedScopes[this.ts.cursor] = fnScope;
888 //qln("FETCHING SCOPE" + this.ts.cursor);
889 fnScope = this.indexedScopes[this.ts.cursor];
893 print('FUNC-PARSE:' + JSON.stringify(token,null,4));
894 // Parse function arguments.
895 var args = token.items;
896 for (var argpos =0; argpos < args.length; argpos++) {
898 token = args[argpos][0];
899 // print ("FUNC ARGS: " + token.toString())
900 //assert token.getType() == Token.NAME ||
901 // token.getType() == Token.COMMA;
902 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
904 identifier = fnScope.declareIdentifier(symbol,token);
905 if (symbol == "$super" && argpos == 0) {
906 // Exception for Prototype 1.6...
907 identifier.preventMunging();
913 token = this.ts.nextTok();
914 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
916 //print(token.toString());
917 // assert token.getType() == Token.LC;
918 //this.braceNesting++;
920 //token = this.ts.nextTok();
921 //print(token.toString());
924 token.items.forEach(function(tar) {
925 _this.ts = new TokenStream(tar);
926 _this.parseScope(fnScope);
930 //print(JSON.stringify(this.ts,null,4));
931 //this.parseScope(fnScope);
933 // now pop it off the stack!!!
935 //this.braceNesting = b4braceNesting;
936 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
937 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
938 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
941 protectScopeFromObfuscation : function(scope) {
942 //assert scope != null;
944 if (scope == this.globalScope) {
945 // The global scope does not get obfuscated,
946 // so we don't need to worry about it...
950 // Find the highest local scope containing the specified scope.
951 while (scope && scope.parent != this.globalScope) {
952 scope = scope.parent;
955 //assert scope.getParentScope() == globalScope;
956 scope.preventMunging();
959 getIdentifier: function(symbol, scope) {
961 while (scope != false) {
962 identifier = scope.getIdentifier(symbol);
963 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
967 scope = scope.parent;