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 if (this.mode == 'BUILDING_SYMBOL_TREE')
317 print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
318 //println("<i>"+token.data+"</i>");
319 var bn = this.braceNesting;
320 this.parseFunctionDeclaration();
321 this.braceNesting = bn;
324 case "PUNC.LEFT_CURLY": // {
325 case "PUNC.LEFT_PAREN": // (
326 print('SCOPE-CURLY/PAREN:' + token.toString());
327 //println("<i>"+token.data+"</i>");
331 for (var prop in token.props) {
334 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
335 if (token.props[prop].val[0].data == 'function') {
336 // parse a function..
337 this.ts = new TokenStream(token.props[prop].val);
339 this.parseFunctionDeclaration();
345 this.ts = new TokenStream(token.props[prop].val);
346 this.parseScope(scope);
351 // it's an object literal..
352 // the values could be replaced..
358 token.items.forEach(function(expr) {
359 _this.ts = new TokenStream(expr);
360 _this.parseExpression(scope)
363 //print("NOT PROPS"); Seed.quit();
365 //isObjectLitAr.push(false);
366 //this.braceNesting++;
368 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
371 case "PUNC.RIGHT_CURLY": // }
372 print("<< EXIT SCOPE");
375 //println("<i>"+token.data+"</i>");
378 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
379 //assert braceNesting >= scope.getBra ceNesting();
381 if (this.braceNesting < expressionBraceNesting) {
382 var ls = this.scopes.pop();
384 // eat symbol if we are currently at {
385 if (this.ts.look(0).data == '{') {
389 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
395 print('SCOPE-WITH:' + token.toString());
396 //println("<i>"+token.data+"</i>");
397 if (this.mode == "BUILDING_SYMBOL_TREE") {
398 // Inside a 'with' block, it is impossible to figure out
399 // statically whether a symbol is a local variable or an
400 // object member. As a consequence, the only thing we can
401 // do is turn the obfuscation off for the highest scope
402 // containing the 'with' block.
403 this.protectScopeFromObfuscation(scope);
404 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
409 print('SCOPE-CATCH:' + token.toString());
410 //println("<i>"+token.data+"</i>");
414 case Token.SPECIALCOMMENT:
415 if (mode == BUILDING_SYMBOL_TREE) {
416 protectScopeFromObfuscation(scope);
417 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
422 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
423 case "STRN.SINGLE_QUOTE":
424 print('SCOPE-STRING:' + token.toString());
425 //println("<i>"+token.data+"</i>");
427 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
428 // then we are in an object lit.. -> we need to flag the brace as such...
430 isObjectLitAr.push(true);
431 //print(">>>>>> OBJLIT REPUSH(true)");
433 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
435 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
436 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
437 // see if we can replace..
438 // remove the quotes..
439 // should do a bit more checking!!!! (what about wierd char's in the string..
440 var str = token.data.substring(1,token.data.length-1);
441 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
454 print('SCOPE-NAME:' + token.toString());
455 //print("DEAL WITH NAME:");
458 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
459 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
461 isObjectLitAr.push(true);
462 //print(">>>>>> OBJLIT REPUSH(true)");
463 //println("<i>"+token.data+"</i>");
466 // print("DEAL WITH obj lit:");
467 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
469 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
470 // skip, it's an object lit key..
471 //println("<i>"+token.data+"</i>");
476 // skip anyting with "." before it..!!
478 if (this.ts.lookTok(-1).data == ".") {
479 // skip, it's an object prop.
480 //println("<i>"+token.data+"</i>");
483 //print("SYMBOL: " + token.toString());
486 if (this.mode == 'PASS2_SYMBOL_TREE') {
488 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
490 //print ("MUNGE?" + symbol);
492 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
494 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
495 identifier = this.getIdentifier(symbol, scope);
497 if (identifier == false) {
498 // BUG!find out where builtin is defined...
499 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
500 // Here, we found an undeclared and un-namespaced symbol that is
501 // 3 characters or less in length. Declare it in the global scope.
502 // We don't need to declare longer symbols since they won't cause
503 // any conflict with other munged symbols.
504 this.globalScope.declareIdentifier(symbol, token);
505 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
508 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
510 token.identifier = identifier;
511 identifier.refcount++;
516 //println("<B>SID</B>");
518 if (token.type != 'KEYW') {
521 print('SCOPE-KEYW:' + token.toString());
522 // print("Check eval:");
526 if (this.mode == 'BUILDING_SYMBOL_TREE') {
528 if (symbol == "eval") {
529 // look back one and see if we can find a comment!!!
530 if (this.ts.look(-1).type == "COMM") {
531 // look for eval:var:noreplace\n
533 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
535 var hi = _t.getIdentifier(a, scope);
536 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
538 // println("PROTECT "+a+" from munge");
548 this.protectScopeFromObfuscation(scope);
549 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);
561 //print("parseScope TOK : " + token.toString());
562 token = this.ts.nextTok();
563 //if (this.ts.nextT()) break;
566 print("<<< EXIT SCOPE");
567 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
571 parseExpression : function() {
573 // Parse the expression until we encounter a comma or a semi-colon
574 // in the same brace nesting, bracket nesting and paren nesting.
575 // Parse functions if any...
576 //println("<i>EXP</i><BR/>");
577 !this.debug || print("PARSE EXPR");
580 // for printing stuff..
589 var expressionBraceNesting = this.braceNesting + 0;
590 var bracketNesting = 0;
591 var parensNesting = 0;
593 var isObjectLitAr = [ false ];
595 currentScope = this.scopes[this.scopes.length-1];
598 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
599 while (token = this.ts.nextTok()) {
604 // moved out of loop?
605 currentScope = this.scopes[this.scopes.length-1];
607 var scopeIndent = '';
608 this.scopes.forEach(function() {
613 //this.dumpToken(token, this.scopes, this.braceNesting );
614 print('EXP' + token.toString());
617 //println("<i>"+token.data+"</i>");
618 //this.log("EXP:" + token.data);
619 switch (token.type) {
621 print("EXPR-PUNC:" + token.toString());
626 print("<< EXIT EXPRESSION");
634 case '(': //Token.LP:
635 case '{': //Token.LC:
636 case '[': //Token.LB:
637 print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
638 //println("<i>"+token.data+"</i>");
642 for (var prop in token.props) {
643 if (token.props[prop].val.data == 'function') {
644 // parse a function..
645 this.parseFunctProp(token.props[prop]);
650 this.ts = new TokenStream(token.props[prop].val);
651 this.parseScope(currentScope);
656 // it's an object literal..
657 // the values could be replaced..
663 token.items.forEach(function(expr) {
664 _this.ts = new TokenStream(expr);
665 _this.parseExpression()
671 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
678 case ')': //Token.RP:
679 case ']': //Token.RB:
680 case '}': //Token.RB:
681 print("<< EXIT EXPRESSION");
694 case 'STRN': // used for object lit detection..
695 if (this.mode == 'BUILDING_SYMBOL_TREE')
696 print("EXPR-STR:" + JSON.stringify(token, null, 4));
704 if (this.mode == 'BUILDING_SYMBOL_TREE')
705 print("EXPR-NAME:" + JSON.stringify(token, null, 4));
707 //print("in NAME = " + token.toString());
708 //print("in NAME 0: " + this.ts.look(0).toString());
709 //print("in NAME 2: " + this.ts.lookTok(2).toString());
711 //print(this.ts.lookTok(0).data);
713 if (this.ts.lookTok(0).data == ".") {
719 if (this.mode == 'PASS2_SYMBOL_TREE') {
721 identifier = this.getIdentifier(symbol, currentScope);
722 //println("<B>??</B>");
723 if (identifier == false) {
725 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
726 // Here, we found an undeclared and un-namespaced symbol that is
727 // 3 characters or less in length. Declare it in the global scope.
728 // We don't need to declare longer symbols since they won't cause
729 // any conflict with other munged symbols.
730 this.globalScope.declareIdentifier(symbol, token);
731 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
733 println("undeclared:" + symbol)
738 //println("<B>++</B>");
739 token.identifier = identifier;
740 identifier.refcount++;
749 //println("<B>EID</B>");
751 if (this.mode == 'BUILDING_SYMBOL_TREE')
752 print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
753 if (token.name == "FUNCTION") {
755 this.parseFunctionDeclaration();
762 if (this.mode == 'BUILDING_SYMBOL_TREE') {
764 if (symbol == "eval") {
765 if (this.ts.look(-1).type == 'COMM') {
766 // look for eval:var:noreplace\n
768 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
769 var hi = _t.getIdentifier(a, currentScope);
770 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
772 // println("PROTECT "+a+" from munge");
780 this.protectScopeFromObfuscation(currentScope);
781 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
789 if (this.mode == 'BUILDING_SYMBOL_TREE')
790 print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
795 print("<< EXIT EXPRESSION");
800 parseCatch : function() {
807 //token = getToken(-1);
808 //assert token.getType() == Token.CATCH;
809 token = this.ts.nextTok();
810 //assert token.getType() == Token.LP; (
811 token = this.ts.nextTok();
812 //assert token.getType() == Token.NAME;
815 currentScope = this.scopes[this.scopes.length-1];
817 if (this.mode == 'BUILDING_SYMBOL_TREE') {
818 // We must declare the exception identifier in the containing function
819 // scope to avoid errors related to the obfuscation process. No need to
820 // display a warning if the symbol was already declared here...
821 currentScope.declareIdentifier(symbol, token);
823 //?? why inc the refcount?? - that should be set when building the tree???
824 identifier = this.getIdentifier(symbol, currentScope);
825 identifier.refcount++;
828 token = this.ts.nextTok();
829 //assert token.getType() == Token.RP; // )
832 parseFunctionDeclaration : function()
834 //print("PARSE FUNCTION");
837 var currentScope = false;
840 var b4braceNesting = this.braceNesting + 0;
842 //this.logR("<B>PARSING FUNCTION</B>");
843 currentScope = this.scopes[this.scopes.length-1];
845 token = this.ts.nextTok();
846 if (token.type == "NAME") {
847 if (this.mode == 'BUILDING_SYMBOL_TREE') {
848 // Get the name of the function and declare it in the current scope.
850 if (currentScope.getIdentifier(symbol) != false) {
851 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
853 currentScope.declareIdentifier(symbol,token);
855 token = this.ts.nextTok();
858 //assert token.getType() == Token.LP;
859 if (this.mode == 'BUILDING_SYMBOL_TREE') {
860 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
862 //println("STORING SCOPE" + this.ts.cursor);
864 this.indexedScopes[this.ts.cursor] = fnScope;
867 //qln("FETCHING SCOPE" + this.ts.cursor);
868 fnScope = this.indexedScopes[this.ts.cursor];
871 if (this.mode == 'BUILDING_SYMBOL_TREE')
872 print('FUNC-PARSE:' + JSON.stringify(token,null,4));
873 // Parse function arguments.
874 var args = token.items;
875 for (var argpos =0; argpos < args.length; argpos++) {
877 token = args[argpos][0];
878 print ("FUNC ARGS: " + token.toString())
879 //assert token.getType() == Token.NAME ||
880 // token.getType() == Token.COMMA;
881 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
883 identifier = fnScope.declareIdentifier(symbol,token);
884 if (symbol == "$super" && argpos == 0) {
885 // Exception for Prototype 1.6...
886 identifier.preventMunging();
892 token = this.ts.nextTok();
893 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
895 //print(token.toString());
896 // assert token.getType() == Token.LC;
897 //this.braceNesting++;
899 //token = this.ts.nextTok();
900 //print(token.toString());
903 token.items.forEach(function(tar) {
904 _this.ts = new TokenStream(tar);
905 _this.parseScope(fnScope);
909 //print(JSON.stringify(this.ts,null,4));
910 //this.parseScope(fnScope);
912 // now pop it off the stack!!!
914 //this.braceNesting = b4braceNesting;
915 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
916 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
917 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
920 protectScopeFromObfuscation : function(scope) {
921 //assert scope != null;
923 if (scope == this.globalScope) {
924 // The global scope does not get obfuscated,
925 // so we don't need to worry about it...
929 // Find the highest local scope containing the specified scope.
930 while (scope && scope.parent != this.globalScope) {
931 scope = scope.parent;
934 //assert scope.getParentScope() == globalScope;
935 scope.preventMunging();
938 getIdentifier: function(symbol, scope) {
940 while (scope != false) {
941 identifier = scope.getIdentifier(symbol);
942 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
946 scope = scope.parent;