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 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:' + token.toString());
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;
303 this.parseExpression();
304 this.braceNesting = bn;
305 //this.braceNesting = bn;
306 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
308 token = this.ts.lookTok(1);
309 !this.debug|| print("AFTER EXP: " + token.toString());
310 if (token.data == ';') {
317 //this.ts.dump(vstart , this.ts.cursor);
320 case "KEYW.FUNCTION":
321 //if (this.mode == 'BUILDING_SYMBOL_TREE')
322 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
323 //println("<i>"+token.data+"</i>");
324 var bn = this.braceNesting;
325 this.parseFunctionDeclaration();
326 this.braceNesting = bn;
329 case "PUNC.LEFT_CURLY": // {
330 case "PUNC.LEFT_PAREN": // (
331 case "PUNC.LEFT_BRACE": // [
332 //print('SCOPE-CURLY/PAREN:' + token.toString());
333 //println("<i>"+token.data+"</i>");
337 for (var prop in token.props) {
340 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
341 if (token.props[prop].val[0].data == 'function') {
342 // parse a function..
343 this.ts = new TokenStream(token.props[prop].val);
345 this.parseFunctionDeclaration();
351 this.ts = new TokenStream(token.props[prop].val);
352 this.parseExpression();
357 // it's an object literal..
358 // the values could be replaced..
364 token.items.forEach(function(expr) {
365 _this.ts = new TokenStream(expr);
366 _this.parseExpression()
369 //print("NOT PROPS"); Seed.quit();
371 //isObjectLitAr.push(false);
372 //this.braceNesting++;
374 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
377 case "PUNC.RIGHT_CURLY": // }
378 //print("<< EXIT SCOPE");
381 //println("<i>"+token.data+"</i>");
384 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
385 //assert braceNesting >= scope.getBra ceNesting();
387 if (this.braceNesting < expressionBraceNesting) {
388 var ls = this.scopes.pop();
390 // eat symbol if we are currently at {
391 if (this.ts.look(0).data == '{') {
395 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
401 //print('SCOPE-WITH:' + token.toString());
402 //println("<i>"+token.data+"</i>");
403 if (this.mode == "BUILDING_SYMBOL_TREE") {
404 // Inside a 'with' block, it is impossible to figure out
405 // statically whether a symbol is a local variable or an
406 // object member. As a consequence, the only thing we can
407 // do is turn the obfuscation off for the highest scope
408 // containing the 'with' block.
409 this.protectScopeFromObfuscation(thisScope);
410 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
415 //print('SCOPE-CATCH:' + token.toString());
416 //println("<i>"+token.data+"</i>");
420 case Token.SPECIALCOMMENT:
421 if (mode == BUILDING_SYMBOL_TREE) {
422 protectScopeFromObfuscation(scope);
423 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
428 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
429 case "STRN.SINGLE_QUOTE":
430 // print('SCOPE-STRING:' + token.toString());
431 //println("<i>"+token.data+"</i>");
433 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
434 // then we are in an object lit.. -> we need to flag the brace as such...
436 isObjectLitAr.push(true);
437 //print(">>>>>> OBJLIT REPUSH(true)");
439 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
441 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
442 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
443 // see if we can replace..
444 // remove the quotes..
445 // should do a bit more checking!!!! (what about wierd char's in the string..
446 var str = token.data.substring(1,token.data.length-1);
447 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
460 //print('SCOPE-NAME:' + token.toString());
461 //print("DEAL WITH NAME:");
464 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
467 // skip anyting with "." before it..!!
469 if (this.ts.lookTok(-1).data == ".") {
470 // skip, it's an object prop.
471 //println("<i>"+token.data+"</i>");
474 //print("SYMBOL: " + token.toString());
477 if (symbol == 'this') {
480 if (this.mode == 'PASS2_SYMBOL_TREE') {
482 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
484 //print ("MUNGE?" + symbol);
486 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
488 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
489 identifier = this.getIdentifier(symbol, thisScope, token);
491 if (identifier == false) {
492 // BUG!find out where builtin is defined...
493 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
494 // Here, we found an undeclared and un-namespaced symbol that is
495 // 3 characters or less in length. Declare it in the global scope.
496 // We don't need to declare longer symbols since they won't cause
497 // any conflict with other munged symbols.
498 this.globalScope.declareIdentifier(symbol, token);
499 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
502 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
504 token.identifier = identifier;
505 identifier.refcount++;
510 //println("<B>SID</B>");
512 if (token.type != 'KEYW') {
515 //print('SCOPE-KEYW:' + token.toString());
516 // print("Check eval:");
520 if (this.mode == 'BUILDING_SYMBOL_TREE') {
522 if (symbol == "eval") {
523 // look back one and see if we can find a comment!!!
524 if (this.ts.look(-1).type == "COMM") {
525 // look for eval:var:noreplace\n
527 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
529 var hi = _t.getIdentifier(a, thisScope, token);
530 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
532 // println("PROTECT "+a+" from munge");
542 this.protectScopeFromObfuscation(thisScope);
543 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);
555 //print("parseScope TOK : " + token.toString());
556 token = this.ts.nextTok();
557 //if (this.ts.nextT()) break;
560 //print("<<< EXIT SCOPE");
561 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
565 parseExpression : function() {
567 // Parse the expression until we encounter a comma or a semi-colon
568 // in the same brace nesting, bracket nesting and paren nesting.
569 // Parse functions if any...
570 //println("<i>EXP</i><BR/>");
571 !this.debug || print("PARSE EXPR");
574 // for printing stuff..
583 var expressionBraceNesting = this.braceNesting + 0;
584 var bracketNesting = 0;
585 var parensNesting = 0;
587 var isObjectLitAr = [ false ];
589 currentScope = this.scopes[this.scopes.length-1];
592 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
593 while (token = this.ts.nextTok()) {
598 // moved out of loop?
599 currentScope = this.scopes[this.scopes.length-1];
601 var scopeIndent = '';
602 this.scopes.forEach(function() {
607 //this.dumpToken(token, this.scopes, this.braceNesting );
608 //print('EXP' + token.toString());
611 //println("<i>"+token.data+"</i>");
612 //this.log("EXP:" + token.data);
613 switch (token.type) {
615 //print("EXPR-PUNC:" + token.toString());
620 //print("<< EXIT EXPRESSION");
628 case '(': //Token.LP:
629 case '{': //Token.LC:
630 case '[': //Token.LB:
631 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
632 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
633 //println("<i>"+token.data+"</i>");
637 for (var prop in token.props) {
638 if (token.props[prop].val[0].data == 'function') {
639 // parse a function..
640 this.ts = new TokenStream(token.props[prop].val);
642 this.parseFunctionDeclaration();
647 this.ts = new TokenStream(token.props[prop].val);
648 this.parseExpression();
653 // it's an object literal..
654 // the values could be replaced..
660 token.items.forEach(function(expr) {
661 _this.ts = new TokenStream(expr);
662 _this.parseExpression()
668 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
675 case ')': //Token.RP:
676 case ']': //Token.RB:
677 case '}': //Token.RB:
678 //print("<< EXIT EXPRESSION");
691 case 'STRN': // used for object lit detection..
692 //if (this.mode == 'BUILDING_SYMBOL_TREE')
693 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
701 if (this.mode == 'BUILDING_SYMBOL_TREE') {
703 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
705 //print("EXPR-NAME:" + token.toString());
708 //print("in NAME = " + token.toString());
709 //print("in NAME 0: " + this.ts.look(0).toString());
710 //print("in NAME 2: " + this.ts.lookTok(2).toString());
712 //print(this.ts.lookTok(-1).data);
714 if (this.ts.lookTok(-1).data == ".") {
718 if (symbol == 'this') {
722 if (this.mode == 'PASS2_SYMBOL_TREE') {
724 identifier = this.getIdentifier(symbol, currentScope, token);
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);
735 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
738 //print("undeclared:" + token.toString())
743 //println("<B>++</B>");
744 token.identifier = identifier;
745 identifier.refcount++;
754 //println("<B>EID</B>");
756 //if (this.mode == 'BUILDING_SYMBOL_TREE')
757 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
758 if (token.name == "FUNCTION") {
760 this.parseFunctionDeclaration();
767 if (this.mode == 'BUILDING_SYMBOL_TREE') {
769 if (symbol == "eval") {
770 if (this.ts.look(-1).type == 'COMM') {
771 // look for eval:var:noreplace\n
773 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
774 var hi = _t.getIdentifier(a, currentScope, token);
775 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
777 // println("PROTECT "+a+" from munge");
785 this.protectScopeFromObfuscation(currentScope);
786 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
794 //if (this.mode == 'BUILDING_SYMBOL_TREE')
795 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
800 //print("<< EXIT EXPRESSION");
805 parseCatch : function() {
812 //token = getToken(-1);
813 //assert token.getType() == Token.CATCH;
814 token = this.ts.nextTok();
815 //assert token.getType() == Token.LP; (
816 //token = this.ts.nextTok();
817 //assert token.getType() == Token.NAME;
819 symbol = token.items[0].data;
820 currentScope = this.scopes[this.scopes.length-1];
822 if (this.mode == 'BUILDING_SYMBOL_TREE') {
823 // We must declare the exception identifier in the containing function
824 // scope to avoid errors related to the obfuscation process. No need to
825 // display a warning if the symbol was already declared here...
826 currentScope.declareIdentifier(symbol, token);
828 //?? why inc the refcount?? - that should be set when building the tree???
829 identifier = this.getIdentifier(symbol, currentScope, token);
830 identifier.refcount++;
833 token = this.ts.nextTok();
834 //assert token.getType() == Token.RP; // )
837 parseFunctionDeclaration : function()
839 //print("PARSE FUNCTION");
842 var currentScope = false;
845 var b4braceNesting = this.braceNesting + 0;
847 //this.logR("<B>PARSING FUNCTION</B>");
848 currentScope = this.scopes[this.scopes.length-1];
850 token = this.ts.nextTok();
851 if (token.type == "NAME") {
852 if (this.mode == 'BUILDING_SYMBOL_TREE') {
853 // Get the name of the function and declare it in the current scope.
855 if (currentScope.getIdentifier(symbol,token) != false) {
856 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
858 currentScope.declareIdentifier(symbol,token);
860 token = this.ts.nextTok();
863 //assert token.getType() == Token.LP;
864 if (this.mode == 'BUILDING_SYMBOL_TREE') {
865 fnScope = new Scope(1, currentScope, token.n, '', token);
867 //println("STORING SCOPE" + this.ts.cursor);
869 this.indexedScopes[token.id] = fnScope;
872 //qln("FETCHING SCOPE" + this.ts.cursor);
873 fnScope = this.indexedScopes[token.id];
876 //if (this.mode == 'BUILDING_SYMBOL_TREE')
877 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
878 // Parse function arguments.
879 var args = token.items;
880 for (var argpos =0; argpos < args.length; argpos++) {
882 token = args[argpos][0];
883 //print ("FUNC ARGS: " + token.toString())
884 //assert token.getType() == Token.NAME ||
885 // token.getType() == Token.COMMA;
886 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
888 identifier = fnScope.declareIdentifier(symbol,token);
889 if (symbol == "$super" && argpos == 0) {
890 // Exception for Prototype 1.6...
891 identifier.preventMunging();
897 token = this.ts.nextTok();
898 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
900 //print(token.toString());
901 // assert token.getType() == Token.LC;
902 //this.braceNesting++;
904 //token = this.ts.nextTok();
905 //print(token.toString());
908 token.items.forEach(function(tar) {
909 _this.ts = new TokenStream(tar);
910 _this.parseScope(fnScope);
915 //print(JSON.stringify(this.ts,null,4));
916 //this.parseScope(fnScope);
918 // now pop it off the stack!!!
920 //this.braceNesting = b4braceNesting;
921 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
922 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
923 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
926 protectScopeFromObfuscation : function(scope) {
927 //assert scope != null;
929 if (scope == this.globalScope) {
930 // The global scope does not get obfuscated,
931 // so we don't need to worry about it...
935 // Find the highest local scope containing the specified scope.
936 while (scope && scope.parent != this.globalScope) {
937 scope = scope.parent;
940 //assert scope.getParentScope() == globalScope;
941 scope.preventMunging();
944 getIdentifier: function(symbol, scope, token) {
946 while (scope != false) {
947 identifier = scope.getIdentifier(symbol, token);
948 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
952 scope = scope.parent;