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 ];
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) ;
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 print('SCOPE-CURLY/PAREN:' + token.toString());
332 //println("<i>"+token.data+"</i>");
336 for (var prop in token.props) {
339 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
340 if (token.props[prop].val[0].data == 'function') {
341 // parse a function..
342 this.ts = new TokenStream(token.props[prop].val);
344 this.parseFunctionDeclaration();
350 this.ts = new TokenStream(token.props[prop].val);
351 this.parseScope(false);
356 // it's an object literal..
357 // the values could be replaced..
363 token.items.forEach(function(expr) {
364 _this.ts = new TokenStream(expr);
365 _this.parseExpression()
368 //print("NOT PROPS"); Seed.quit();
370 //isObjectLitAr.push(false);
371 //this.braceNesting++;
373 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
376 case "PUNC.RIGHT_CURLY": // }
377 print("<< EXIT SCOPE");
380 //println("<i>"+token.data+"</i>");
383 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
384 //assert braceNesting >= scope.getBra ceNesting();
386 if (this.braceNesting < expressionBraceNesting) {
387 var ls = this.scopes.pop();
389 // eat symbol if we are currently at {
390 if (this.ts.look(0).data == '{') {
394 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
400 print('SCOPE-WITH:' + token.toString());
401 //println("<i>"+token.data+"</i>");
402 if (this.mode == "BUILDING_SYMBOL_TREE") {
403 // Inside a 'with' block, it is impossible to figure out
404 // statically whether a symbol is a local variable or an
405 // object member. As a consequence, the only thing we can
406 // do is turn the obfuscation off for the highest scope
407 // containing the 'with' block.
408 this.protectScopeFromObfuscation(thisScope);
409 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
414 print('SCOPE-CATCH:' + token.toString());
415 //println("<i>"+token.data+"</i>");
419 case Token.SPECIALCOMMENT:
420 if (mode == BUILDING_SYMBOL_TREE) {
421 protectScopeFromObfuscation(scope);
422 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
427 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
428 case "STRN.SINGLE_QUOTE":
429 print('SCOPE-STRING:' + token.toString());
430 //println("<i>"+token.data+"</i>");
432 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
433 // then we are in an object lit.. -> we need to flag the brace as such...
435 isObjectLitAr.push(true);
436 //print(">>>>>> OBJLIT REPUSH(true)");
438 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
440 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
441 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
442 // see if we can replace..
443 // remove the quotes..
444 // should do a bit more checking!!!! (what about wierd char's in the string..
445 var str = token.data.substring(1,token.data.length-1);
446 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
459 print('SCOPE-NAME:' + token.toString());
460 //print("DEAL WITH NAME:");
463 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
464 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
466 isObjectLitAr.push(true);
467 //print(">>>>>> OBJLIT REPUSH(true)");
468 //println("<i>"+token.data+"</i>");
471 // print("DEAL WITH obj lit:");
472 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
474 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
475 // skip, it's an object lit key..
476 //println("<i>"+token.data+"</i>");
481 // skip anyting with "." before it..!!
483 if (this.ts.lookTok(-1).data == ".") {
484 // skip, it's an object prop.
485 //println("<i>"+token.data+"</i>");
488 //print("SYMBOL: " + token.toString());
491 if (this.mode == 'PASS2_SYMBOL_TREE') {
493 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
495 //print ("MUNGE?" + symbol);
497 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
499 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
500 identifier = this.getIdentifier(symbol, thisScope);
502 if (identifier == false) {
503 // BUG!find out where builtin is defined...
504 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
505 // Here, we found an undeclared and un-namespaced symbol that is
506 // 3 characters or less in length. Declare it in the global scope.
507 // We don't need to declare longer symbols since they won't cause
508 // any conflict with other munged symbols.
509 this.globalScope.declareIdentifier(symbol, token);
510 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
513 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
515 token.identifier = identifier;
516 identifier.refcount++;
521 //println("<B>SID</B>");
523 if (token.type != 'KEYW') {
526 print('SCOPE-KEYW:' + token.toString());
527 // print("Check eval:");
531 if (this.mode == 'BUILDING_SYMBOL_TREE') {
533 if (symbol == "eval") {
534 // look back one and see if we can find a comment!!!
535 if (this.ts.look(-1).type == "COMM") {
536 // look for eval:var:noreplace\n
538 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
540 var hi = _t.getIdentifier(a, thisScope);
541 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
543 // println("PROTECT "+a+" from munge");
553 this.protectScopeFromObfuscation(thisScope);
554 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);
566 //print("parseScope TOK : " + token.toString());
567 token = this.ts.nextTok();
568 //if (this.ts.nextT()) break;
571 print("<<< EXIT SCOPE");
572 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
576 parseExpression : function() {
578 // Parse the expression until we encounter a comma or a semi-colon
579 // in the same brace nesting, bracket nesting and paren nesting.
580 // Parse functions if any...
581 //println("<i>EXP</i><BR/>");
582 !this.debug || print("PARSE EXPR");
585 // for printing stuff..
594 var expressionBraceNesting = this.braceNesting + 0;
595 var bracketNesting = 0;
596 var parensNesting = 0;
598 var isObjectLitAr = [ false ];
600 currentScope = this.scopes[this.scopes.length-1];
603 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
604 while (token = this.ts.nextTok()) {
609 // moved out of loop?
610 currentScope = this.scopes[this.scopes.length-1];
612 var scopeIndent = '';
613 this.scopes.forEach(function() {
618 //this.dumpToken(token, this.scopes, this.braceNesting );
619 print('EXP' + token.toString());
622 //println("<i>"+token.data+"</i>");
623 //this.log("EXP:" + token.data);
624 switch (token.type) {
626 print("EXPR-PUNC:" + token.toString());
631 print("<< EXIT EXPRESSION");
639 case '(': //Token.LP:
640 case '{': //Token.LC:
641 case '[': //Token.LB:
642 print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
643 //println("<i>"+token.data+"</i>");
647 for (var prop in token.props) {
648 if (token.props[prop].val.data == 'function') {
649 // parse a function..
650 this.parseFunctProp(token.props[prop]);
655 this.ts = new TokenStream(token.props[prop].val);
656 this.parseScope(currentScope);
661 // it's an object literal..
662 // the values could be replaced..
668 token.items.forEach(function(expr) {
669 _this.ts = new TokenStream(expr);
670 _this.parseExpression()
676 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
683 case ')': //Token.RP:
684 case ']': //Token.RB:
685 case '}': //Token.RB:
686 print("<< EXIT EXPRESSION");
699 case 'STRN': // used for object lit detection..
700 if (this.mode == 'BUILDING_SYMBOL_TREE')
701 print("EXPR-STR:" + JSON.stringify(token, null, 4));
709 if (this.mode == 'BUILDING_SYMBOL_TREE') {
711 print("EXPR-NAME:" + JSON.stringify(token, null, 4));
713 print("EXPR-NAME:" + token.toString());
716 //print("in NAME = " + token.toString());
717 //print("in NAME 0: " + this.ts.look(0).toString());
718 //print("in NAME 2: " + this.ts.lookTok(2).toString());
720 //print(this.ts.lookTok(0).data);
722 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);
741 print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
743 print("undeclared:" + token.toString())
748 //println("<B>++</B>");
749 token.identifier = identifier;
750 identifier.refcount++;
759 //println("<B>EID</B>");
761 if (this.mode == 'BUILDING_SYMBOL_TREE')
762 print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
763 if (token.name == "FUNCTION") {
765 this.parseFunctionDeclaration();
772 if (this.mode == 'BUILDING_SYMBOL_TREE') {
774 if (symbol == "eval") {
775 if (this.ts.look(-1).type == 'COMM') {
776 // look for eval:var:noreplace\n
778 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
779 var hi = _t.getIdentifier(a, currentScope);
780 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
782 // println("PROTECT "+a+" from munge");
790 this.protectScopeFromObfuscation(currentScope);
791 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
799 if (this.mode == 'BUILDING_SYMBOL_TREE')
800 print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
805 print("<< EXIT EXPRESSION");
810 parseCatch : function() {
817 //token = getToken(-1);
818 //assert token.getType() == Token.CATCH;
819 token = this.ts.nextTok();
820 //assert token.getType() == Token.LP; (
821 token = this.ts.nextTok();
822 //assert token.getType() == Token.NAME;
825 currentScope = this.scopes[this.scopes.length-1];
827 if (this.mode == 'BUILDING_SYMBOL_TREE') {
828 // We must declare the exception identifier in the containing function
829 // scope to avoid errors related to the obfuscation process. No need to
830 // display a warning if the symbol was already declared here...
831 currentScope.declareIdentifier(symbol, token);
833 //?? why inc the refcount?? - that should be set when building the tree???
834 identifier = this.getIdentifier(symbol, currentScope);
835 identifier.refcount++;
838 token = this.ts.nextTok();
839 //assert token.getType() == Token.RP; // )
842 parseFunctionDeclaration : function()
844 //print("PARSE FUNCTION");
847 var currentScope = false;
850 var b4braceNesting = this.braceNesting + 0;
852 //this.logR("<B>PARSING FUNCTION</B>");
853 currentScope = this.scopes[this.scopes.length-1];
855 token = this.ts.nextTok();
856 if (token.type == "NAME") {
857 if (this.mode == 'BUILDING_SYMBOL_TREE') {
858 // Get the name of the function and declare it in the current scope.
860 if (currentScope.getIdentifier(symbol) != false) {
861 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
863 currentScope.declareIdentifier(symbol,token);
865 token = this.ts.nextTok();
868 //assert token.getType() == Token.LP;
869 if (this.mode == 'BUILDING_SYMBOL_TREE') {
870 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
872 //println("STORING SCOPE" + this.ts.cursor);
874 this.indexedScopes[this.ts.cursor] = fnScope;
877 //qln("FETCHING SCOPE" + this.ts.cursor);
878 fnScope = this.indexedScopes[this.ts.cursor];
881 if (this.mode == 'BUILDING_SYMBOL_TREE')
882 print('FUNC-PARSE:' + JSON.stringify(token,null,4));
883 // Parse function arguments.
884 var args = token.items;
885 for (var argpos =0; argpos < args.length; argpos++) {
887 token = args[argpos][0];
888 print ("FUNC ARGS: " + token.toString())
889 //assert token.getType() == Token.NAME ||
890 // token.getType() == Token.COMMA;
891 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
893 identifier = fnScope.declareIdentifier(symbol,token);
894 if (symbol == "$super" && argpos == 0) {
895 // Exception for Prototype 1.6...
896 identifier.preventMunging();
902 token = this.ts.nextTok();
903 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
905 //print(token.toString());
906 // assert token.getType() == Token.LC;
907 //this.braceNesting++;
909 //token = this.ts.nextTok();
910 //print(token.toString());
913 token.items.forEach(function(tar) {
914 _this.ts = new TokenStream(tar);
915 _this.parseScope(fnScope);
919 //print(JSON.stringify(this.ts,null,4));
920 //this.parseScope(fnScope);
922 // now pop it off the stack!!!
924 //this.braceNesting = b4braceNesting;
925 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
926 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
927 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
930 protectScopeFromObfuscation : function(scope) {
931 //assert scope != null;
933 if (scope == this.globalScope) {
934 // The global scope does not get obfuscated,
935 // so we don't need to worry about it...
939 // Find the highest local scope containing the specified scope.
940 while (scope && scope.parent != this.globalScope) {
941 scope = scope.parent;
944 //assert scope.getParentScope() == globalScope;
945 scope.preventMunging();
948 getIdentifier: function(symbol, scope) {
950 while (scope != false) {
951 identifier = scope.getIdentifier(symbol);
952 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
956 scope = scope.parent;