1 //<Script type="text/javascript">
3 Scope = imports['JSDOC/Scope.js'].Scope;
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() {
232 //print(scopeIndent + ">> 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());
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:' + token.toString());
317 //println("<i>"+token.data+"</i>");
318 var bn = this.braceNesting;
319 this.parseFunctionDeclaration();
320 this.braceNesting = bn;
323 case "PUNC.LEFT_CURLY": // {
324 print('SCOPE-CURLY:' + JSON.stringify(token,null,4));
325 //println("<i>"+token.data+"</i>");
328 // it's an object literal..
329 // the values could be replaced..
332 isObjectLitAr.push(false);
335 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
338 case "PUNC.RIGHT_CURLY": // }
339 //println("<i>"+token.data+"</i>");
342 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
343 //assert braceNesting >= scope.getBra ceNesting();
345 if (this.braceNesting < expressionBraceNesting) {
346 var ls = this.scopes.pop();
348 // eat symbol if we are currently at {
349 if (this.ts.look(0).data == '{') {
353 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
359 print('SCOPE-WITH:' + token.toString());
360 //println("<i>"+token.data+"</i>");
361 if (this.mode == "BUILDING_SYMBOL_TREE") {
362 // Inside a 'with' block, it is impossible to figure out
363 // statically whether a symbol is a local variable or an
364 // object member. As a consequence, the only thing we can
365 // do is turn the obfuscation off for the highest scope
366 // containing the 'with' block.
367 this.protectScopeFromObfuscation(scope);
368 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
373 print('SCOPE-CATCH:' + token.toString());
374 //println("<i>"+token.data+"</i>");
378 case Token.SPECIALCOMMENT:
379 if (mode == BUILDING_SYMBOL_TREE) {
380 protectScopeFromObfuscation(scope);
381 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
386 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
387 case "STRN.SINGLE_QUOTE":
388 print('SCOPE-STRING:' + token.toString());
389 //println("<i>"+token.data+"</i>");
391 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
392 // then we are in an object lit.. -> we need to flag the brace as such...
394 isObjectLitAr.push(true);
395 //print(">>>>>> OBJLIT REPUSH(true)");
397 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
399 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
400 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
401 // see if we can replace..
402 // remove the quotes..
403 // should do a bit more checking!!!! (what about wierd char's in the string..
404 var str = token.data.substring(1,token.data.length-1);
405 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
418 print('SCOPE-NAME:' + token.toString());
419 //print("DEAL WITH NAME:");
422 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
423 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
425 isObjectLitAr.push(true);
426 //print(">>>>>> OBJLIT REPUSH(true)");
427 //println("<i>"+token.data+"</i>");
430 // print("DEAL WITH obj lit:");
431 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
433 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
434 // skip, it's an object lit key..
435 //println("<i>"+token.data+"</i>");
440 // skip anyting with "." before it..!!
442 if (this.ts.lookTok(-1).data == ".") {
443 // skip, it's an object prop.
444 //println("<i>"+token.data+"</i>");
447 //print("SYMBOL: " + token.toString());
450 if (this.mode == 'PASS2_SYMBOL_TREE') {
452 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
454 //print ("MUNGE?" + symbol);
456 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
458 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
459 identifier = this.getIdentifier(symbol, scope);
461 if (identifier == false) {
462 // BUG!find out where builtin is defined...
463 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
464 // Here, we found an undeclared and un-namespaced symbol that is
465 // 3 characters or less in length. Declare it in the global scope.
466 // We don't need to declare longer symbols since they won't cause
467 // any conflict with other munged symbols.
468 this.globalScope.declareIdentifier(symbol, token);
469 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
472 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
474 token.identifier = identifier;
475 identifier.refcount++;
480 //println("<B>SID</B>");
482 if (token.type != 'KEYW') {
485 print('SCOPE-KEYW:' + token.toString());
486 // print("Check eval:");
490 if (this.mode == 'BUILDING_SYMBOL_TREE') {
492 if (symbol == "eval") {
493 // look back one and see if we can find a comment!!!
494 if (this.ts.look(-1).type == "COMM") {
495 // look for eval:var:noreplace\n
497 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
499 var hi = _t.getIdentifier(a, scope);
500 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
502 // println("PROTECT "+a+" from munge");
512 this.protectScopeFromObfuscation(scope);
513 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);
525 //print("parseScope TOK : " + token.toString());
526 token = this.ts.nextTok();
527 //if (this.ts.nextT()) break;
530 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
534 parseExpression : function() {
536 // Parse the expression until we encounter a comma or a semi-colon
537 // in the same brace nesting, bracket nesting and paren nesting.
538 // Parse functions if any...
539 //println("<i>EXP</i><BR/>");
540 !this.debug || print("PARSE EXPR");
543 // for printing stuff..
552 var expressionBraceNesting = this.braceNesting + 0;
553 var bracketNesting = 0;
554 var parensNesting = 0;
556 var isObjectLitAr = [ false ];
558 currentScope = this.scopes[this.scopes.length-1];
560 var scopeIndent = '';
561 this.scopes.forEach(function() {
564 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
565 while (token = this.ts.lookTok()) {
570 // moved out of loop?
571 currentScope = this.scopes[this.scopes.length-1];
573 var scopeIndent = '';
574 this.scopes.forEach(function() {
579 //this.dumpToken(token, this.scopes, this.braceNesting );
580 //print('EXP' + this.expN + ':' + token.toString());
583 //println("<i>"+token.data+"</i>");
584 //this.log("EXP:" + token.data);
585 switch (token.type) {
591 if (this.braceNesting == expressionBraceNesting &&
592 bracketNesting == 0 &&
593 parensNesting == 0) {
594 print(scopeIndent + "<< EXIT EXPRESSION");
602 case '{': //Token.LC:
603 isObjectLitAr.push(false);
606 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
609 case '}': //Token.RC:
612 //print(">>>>> EXP POP" + this.braceNesting);
613 // assert braceNesting >= expressionBraceNesting;
616 case '[': //Token.LB:
620 case ']': //Token.RB:
624 case '(': //Token.LP:
628 case ')': //Token.RP:
634 case 'STRN': // used for object lit detection..
635 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
636 // then we are in an object lit.. -> we need to flag the brace as such...
638 isObjectLitAr.push(true);
639 //print(">>>>> EXP PUSH(true)");
644 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
645 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
646 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
647 // see if we can replace..
648 // remove the quotes..
649 var str = token.data.substring(1,token.data.length-1);
650 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
665 //print("in NAME = " + token.toString());
666 //print("in NAME 0: " + this.ts.look(0).toString());
667 //print("in NAME 2: " + this.ts.lookTok(2).toString());
668 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
669 // then we are in an object lit.. -> we need to flag the brace as such...
671 isObjectLitAr.push(true);
672 //print(">>>>> EXP PUSH(true)");
676 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
677 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
679 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
682 //print(this.ts.lookTok(0).data);
683 if (this.ts.lookTok(0).data == ".") {
688 if (this.mode == 'PASS2_SYMBOL_TREE') {
690 identifier = this.getIdentifier(symbol, currentScope);
691 //println("<B>??</B>");
692 if (identifier == false) {
694 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
695 // Here, we found an undeclared and un-namespaced symbol that is
696 // 3 characters or less in length. Declare it in the global scope.
697 // We don't need to declare longer symbols since they won't cause
698 // any conflict with other munged symbols.
699 this.globalScope.declareIdentifier(symbol, token);
700 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
702 //println("undeclared")
707 //println("<B>++</B>");
708 token.identifier = identifier;
709 identifier.refcount++;
718 //println("<B>EID</B>");
721 if (token.name == "FUNCTION") {
723 this.parseFunctionDeclaration();
730 if (this.mode == 'BUILDING_SYMBOL_TREE') {
732 if (symbol == "eval") {
733 if (this.ts.look(-1).type == 'COMM') {
734 // look for eval:var:noreplace\n
736 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
737 var hi = _t.getIdentifier(a, currentScope);
738 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
740 // println("PROTECT "+a+" from munge");
748 this.protectScopeFromObfuscation(currentScope);
749 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
758 if (!this.ts.nextTok()) break;
760 print(scopeIndent + "<< EXIT EXPRESSION");
765 parseCatch : function() {
772 //token = getToken(-1);
773 //assert token.getType() == Token.CATCH;
774 token = this.ts.nextTok();
775 //assert token.getType() == Token.LP; (
776 token = this.ts.nextTok();
777 //assert token.getType() == Token.NAME;
780 currentScope = this.scopes[this.scopes.length-1];
782 if (this.mode == 'BUILDING_SYMBOL_TREE') {
783 // We must declare the exception identifier in the containing function
784 // scope to avoid errors related to the obfuscation process. No need to
785 // display a warning if the symbol was already declared here...
786 currentScope.declareIdentifier(symbol, token);
788 //?? why inc the refcount?? - that should be set when building the tree???
789 identifier = this.getIdentifier(symbol, currentScope);
790 identifier.refcount++;
793 token = this.ts.nextTok();
794 //assert token.getType() == Token.RP; // )
797 parseFunctionDeclaration : function()
799 //print("PARSE FUNCTION");
802 var currentScope = false;
805 var b4braceNesting = this.braceNesting + 0;
807 //this.logR("<B>PARSING FUNCTION</B>");
808 currentScope = this.scopes[this.scopes.length-1];
810 token = this.ts.nextTok();
811 if (token.type == "NAME") {
812 if (this.mode == 'BUILDING_SYMBOL_TREE') {
813 // Get the name of the function and declare it in the current scope.
815 if (currentScope.getIdentifier(symbol) != false) {
816 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
818 currentScope.declareIdentifier(symbol,token);
820 token = this.ts.nextTok();
823 //assert token.getType() == Token.LP;
824 if (this.mode == 'BUILDING_SYMBOL_TREE') {
825 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
827 //println("STORING SCOPE" + this.ts.cursor);
829 this.indexedScopes[this.ts.cursor] = fnScope;
832 //qln("FETCHING SCOPE" + this.ts.cursor);
833 fnScope = this.indexedScopes[this.ts.cursor];
837 // Parse function arguments.
839 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
840 token = this.ts.nextTok();
841 // print ("FUNC ARGS: " + token.toString())
842 //assert token.getType() == Token.NAME ||
843 // token.getType() == Token.COMMA;
844 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
846 identifier = fnScope.declareIdentifier(symbol,token);
847 if (symbol == "$super" && argpos == 0) {
848 // Exception for Prototype 1.6...
849 identifier.preventMunging();
855 token = this.ts.nextTok();
856 //print(token.toString());
857 // assert token.getType() == Token.LC;
860 token = this.ts.nextTok();
861 //print(token.toString());
864 this.parseScope(fnScope);
865 // now pop it off the stack!!!
867 this.braceNesting = b4braceNesting;
868 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
869 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
870 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
873 protectScopeFromObfuscation : function(scope) {
874 //assert scope != null;
876 if (scope == this.globalScope) {
877 // The global scope does not get obfuscated,
878 // so we don't need to worry about it...
882 // Find the highest local scope containing the specified scope.
883 while (scope && scope.parent != this.globalScope) {
884 scope = scope.parent;
887 //assert scope.getParentScope() == globalScope;
888 scope.preventMunging();
891 getIdentifier: function(symbol, scope) {
893 while (scope != false) {
894 identifier = scope.getIdentifier(symbol);
895 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
899 scope = scope.parent;