JSDOC/ScopeParser.js
[gnome.introspection-doc-generator] / JSDOC / ScopeParser.js
1 //<Script type="text/javascript">
2
3 Scope = imports.Scope.Scope;
4 TokenStream = imports.TokenStream.TokenStream;
5 /**
6 * Scope stuff
7
8 * // FIXME - I need this to do next() without doccomments..
9
10
11
12 * Need to make this alot simpler...
13
14 * so debugging is possible.
15
16
17 * at present it just runs along the stream and finds stuff then calls parseExpr .. etc,,
18
19
20 * It would be better to parse blocks of code rather than the whole stream..
21
22
23
24
25
26 */
27
28 ScopeParser = function(ts) {
29     this.ts = ts; // {TokenStream}
30     this.warnings = [];
31     this.scopes = [];
32     this.indexedScopes = {};
33     this.timer = new Date() * 1;
34     this.debug = false;
35 }
36
37 // list of keywords that should not be used in object literals.
38 ScopeParser.idents = [
39         "break",         
40         "case",          
41         "continue",     
42         "default",      
43         "delete",       
44         "do",            
45         "else",         
46         "export",       
47         "false",        
48         "for",          
49         "function",     
50         "if",           
51         "import",       
52         "in",           
53         "new",          
54         "null",         
55         "return",       
56         "switch",       
57         "this",         
58         "true",         
59         "typeof",       
60         "var",          
61         "void",         
62         "while",        
63         "with",         
64
65         "catch",        
66         "class",        
67         "const",        
68         "debugger",     
69         "enum",         
70         "extends",      
71         "finally",      
72         "super",        
73         "throw",         
74         "try",          
75
76         "abstract",     
77         "boolean",      
78         "byte",         
79         "char",         
80         "double",       
81         "final",        
82         "float",        
83         "goto",         
84         "implements", 
85         "instanceof",
86         "int",           
87         "interface",     
88         "long",          
89         "native",       
90         "package",      
91         "private",      
92         "protected",     
93         "public",        
94         "short",        
95         "static",       
96         "synchronized",  
97         "throws",        
98         "transient",     
99                 "include",       
100                 "undefined"
101 ];
102
103
104 ScopeParser.prototype = {
105     timer: 0,
106     timerPrint: function (str) {
107         var ntime = new Date() * 1;
108         var tdif =  ntime -this.timer;
109         this.timer = ntime;
110         var pref = '';
111         if (tdif > 100) { //slower ones..
112             pref = '***';
113         }
114         println(pref+'['+tdif+']'+str);
115         
116     },
117     warn: function(s) {
118         //print('****************' + s);
119         this.warnings.push(s);
120         //println("WARNING:" + htmlescape(s) + "<BR>");
121     },
122     // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
123     warnings : false,
124     ts : false,
125     scopes : false,
126     global : false,
127     mode : "", //"BUILDING_SYMBOL_TREE",
128     braceNesting : 0,
129     indexedScopes : false,
130     munge: true,
131
132
133
134
135
136     buildSymbolTree : function()
137     {
138         //println("<PRE>");
139         
140         this.ts.rewind();
141         this.braceNesting = 0;
142         this.scopes = [];
143         
144         
145         
146         
147         this.globalScope = new  Scope(-1, false, -1, '');
148         indexedScopes = { 0 : this.globalScope };
149         
150         this.mode = 'BUILDING_SYMBOL_TREE';
151         this.parseScope(this.globalScope);
152         
153         //print("---------------END PASS 1 ---------------- ");
154         
155     },
156     mungeSymboltree : function()
157     {
158
159         if (!this.munge) {
160             return;
161         }
162
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:
166         //
167         //     var declaredGlobalVar;
168         //
169         //     function declaredGlobalFn() {
170         //         var localvar;
171         //         localvar = abc; // abc is an undeclared global symbol
172         //     }
173         //
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.
180         //
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.
183
184         this.ts.rewind();
185         this.braceNesting = 0;
186         this.scopes= [];
187         this.mode = 'PASS2_SYMBOL_TREE';
188         
189         //println("MUNGING?");
190         
191         this.parseScope(this.globalScope);
192         this.globalScope.munge();
193     },
194
195
196     log : function(str)
197     {
198         print ("                    ".substring(0, this.braceNesting*2) + str);
199         
200         //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
201     },
202     logR : function(str)
203     {
204             //println("<B>LOG:</B>" + str + "<BR/>");
205     },
206
207      
208     
209
210
211     parseScope : function(scope) // parse a token stream..
212     {
213         //this.timerPrint("parseScope EnterScope"); 
214         //this.log(">>> ENTER SCOPE" + this.scopes.length);
215         var symbol;
216         var token;
217         
218         var identifier;
219
220         var expressionBraceNesting = this.braceNesting + 0;
221         
222         var parensNesting = 0;
223         
224         var isObjectLitAr = [ false ];
225         var isInObjectLitAr;
226         this.scopes.push(scope);
227        
228         //var scopeIndent = ''; 
229         //this.scopes.forEach(function() {
230         //    scopeIndent += '   '; 
231         //});
232         print(">> ENTER SCOPE");
233         
234         
235         
236         
237         token = this.ts.lookTok(1);
238         while (token) {
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);
245             }
246             switch(token.type + '.' + token.name) {
247                 case "KEYW.VAR":
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;
251                     
252                     //this.log("parseScope GOT VAR/CONST : " + token.toString()); 
253                     while (true) {
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!
258                             break;
259                         }
260                         if (token.name == "VAR" || token.data == ',') { // kludge..
261                             continue;
262                         }
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());
267                             }
268                             
269                             print( "var without ident");
270                             Seed.quit()
271                         }
272                         
273
274                         if (this.mode == "BUILDING_SYMBOL_TREE") {
275                             identifier = scope.getIdentifier(token.data) ;
276                             
277                             if (identifier == false) {
278                                 scope.declareIdentifier(token.data, token);
279                             } else {
280                                 token.identifier = identifier;
281                                 this.warn("(SCOPE) The variable " + token.data  + ' (line:' + token.line + ")  has already been declared in the same scope...");
282                             }
283                         }
284
285                         token = this.ts.nextTok();
286                         !this.debug|| print(token.toString());
287                         /*
288                         assert token.getType() == Token.SEMI ||
289                                 token.getType() == Token.ASSIGN ||
290                                 token.getType() == Token.COMMA ||
291                                 token.getType() == Token.IN;
292                         */
293                         if (token.name == "IN") {
294                             break;
295                         } else {
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()); 
302                             
303                             token = this.ts.lookTok(1);
304                             !this.debug|| print("AFTER EXP: " + token.toString());
305                             if (token.data == ';') {
306                                 break;
307                             }
308                         }
309                     }
310                     
311                     //print("VAR:")
312                     //this.ts.dump(vstart , this.ts.cursor);
313                     
314                     break;
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;
321                     break;
322
323                 case "PUNC.LEFT_CURLY": // {
324                     
325                     //println("<i>"+token.data+"</i>");
326                     
327                     if (token.props) {
328                         var curTS = this.ts;
329                         for (var prop in token.props) {
330                             if (token.props[prop].val.data == 'function') {
331                                 // parse a function..
332                                 this.parseFunctProp(token.props[prop]);
333                                 continue;
334                             }
335                             // key value..
336                             
337                             this.ts = new TokenStream(token.props[prop].val);
338                             this.parseScope(scope);
339                             
340                         }
341                         this.ts = curTS;
342                         
343                         // it's an object literal..
344                         // the values could be replaced..
345                         
346                     }
347                     print('SCOPE-CURLY:' + JSON.stringify(token,null,4));
348                     print("NOT PROPS"); Seed.quit();
349                     
350                     isObjectLitAr.push(false);
351                     this.braceNesting++;
352                     
353                     //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
354                     break;
355 /*
356                 case "PUNC.RIGHT_CURLY": // }
357                     //println("<i>"+token.data+"</i>");
358                     this.braceNesting--;
359                     isObjectLitAr.pop();
360                     //print(">>>>>> OBJLIT POP"+ this.braceNesting);
361                         //assert braceNesting >= scope.getBra ceNesting();
362                     
363                     if (this.braceNesting < expressionBraceNesting) {
364                         var ls = this.scopes.pop();
365                         ls.getUsedSymbols();
366                         // eat symbol if we are currently at { 
367                         if (this.ts.look(0).data == '{') {
368                             this.ts.nextTok();
369                         }
370                         
371                         print("<<<<<<<EXIT SCOPE" +this.scopes.length);
372                         return;
373                     }
374                     break;
375 */
376                 case "KEYW.WITH":
377                     print('SCOPE-WITH:' + token.toString());
378                     //println("<i>"+token.data+"</i>");   
379                     if (this.mode == "BUILDING_SYMBOL_TREE") {
380                         // Inside a 'with' block, it is impossible to figure out
381                         // statically whether a symbol is a local variable or an
382                         // object member. As a consequence, the only thing we can
383                         // do is turn the obfuscation off for the highest scope
384                         // containing the 'with' block.
385                         this.protectScopeFromObfuscation(scope);
386                         this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
387                     }
388                     break;
389
390                 case "KEYW.CATCH":
391                     print('SCOPE-CATCH:' + token.toString());
392                     //println("<i>"+token.data+"</i>");
393                     this.parseCatch();
394                     break;
395                 /*
396                 case Token.SPECIALCOMMENT:
397                         if (mode == BUILDING_SYMBOL_TREE) {
398                             protectScopeFromObfuscation(scope);
399                             this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
400                         }
401                         break;
402                 */
403                 
404                 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
405                 case "STRN.SINGLE_QUOTE":
406                     print('SCOPE-STRING:' + token.toString());
407                     //println("<i>"+token.data+"</i>");
408
409                     if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
410                         // then we are in an object lit.. -> we need to flag the brace as such...
411                         isObjectLitAr.pop();
412                         isObjectLitAr.push(true);
413                         //print(">>>>>> OBJLIT REPUSH(true)");
414                     }
415                     isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
416                     
417                     if (isInObjectLitAr &&  this.ts.lookTok(1).data == ':' &&
418                         ( this.ts.lookTok(-1).data == '{'  ||  this.ts.lookTok(-1).data == ':' )) {
419                         // see if we can replace..
420                         // remove the quotes..
421                         // should do a bit more checking!!!! (what about wierd char's in the string..
422                         var str = token.data.substring(1,token.data.length-1);
423                         if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
424                             token.outData = str;
425                         }
426                         
427                          
428                         
429                     }
430                     
431                     
432                     
433                     break;
434                 
435                 case "NAME.NAME":
436                     print('SCOPE-NAME:' + token.toString());
437                     //print("DEAL WITH NAME:");
438                     // got identifier..
439                     
440                     // look for  { ** : <- indicates obj literal.. ** this could occur with numbers ..
441                     if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
442                         isObjectLitAr.pop();
443                         isObjectLitAr.push(true);
444                         //print(">>>>>> OBJLIT REPUSH(true)");
445                         //println("<i>"+token.data+"</i>");
446                         break;
447                     }
448                    // print("DEAL WITH obj lit:");
449                     isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
450                     
451                     if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
452                         // skip, it's an object lit key..
453                         //println("<i>"+token.data+"</i>");
454                         break;
455                     }
456                     
457                     
458                     // skip anyting with "." before it..!!
459                      
460                     if (this.ts.lookTok(-1).data == ".") {
461                         // skip, it's an object prop.
462                         //println("<i>"+token.data+"</i>");
463                         break;
464                     }
465                     //print("SYMBOL: " + token.toString());
466                     
467                     symbol = token.data;
468                     if (this.mode == 'PASS2_SYMBOL_TREE') {
469                         
470                         //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 :  " +  this.ts.lookT(-1).toString() + " <BR> "); 
471                         
472                         //print ("MUNGE?" + symbol);
473                         
474                         //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
475                              
476                             //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
477                         identifier = this.getIdentifier(symbol, scope);
478                         
479                         if (identifier == false) {
480 // BUG!find out where builtin is defined...
481                             if (symbol.length <= 3 &&  Scope.builtin.indexOf(symbol) < 0) {
482                                 // Here, we found an undeclared and un-namespaced symbol that is
483                                 // 3 characters or less in length. Declare it in the global scope.
484                                 // We don't need to declare longer symbols since they won't cause
485                                 // any conflict with other munged symbols.
486                                 this.globalScope.declareIdentifier(symbol, token);
487                                 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
488                             }
489                             
490                             //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
491                         } else {
492                             token.identifier = identifier;
493                             identifier.refcount++;
494                         }
495                     }   
496                     
497                     break;
498                     //println("<B>SID</B>");
499                 default:
500                     if (token.type != 'KEYW') {
501                         break;
502                     }
503                     print('SCOPE-KEYW:' + token.toString());
504                    // print("Check eval:");
505                 
506                     symbol = token.data;
507                     
508                      if (this.mode == 'BUILDING_SYMBOL_TREE') {
509
510                         if (symbol == "eval") {
511                             // look back one and see if we can find a comment!!!
512                             if (this.ts.look(-1).type == "COMM") {
513                                 // look for eval:var:noreplace\n
514                                 var _t = this;
515                                 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
516                                     
517                                     var hi = _t.getIdentifier(a, scope);
518                                    // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
519                                     if (hi) {
520                                      //   println("PROTECT "+a+" from munge");
521                                         hi.toMunge = false;
522                                     }
523                                     
524                                 });
525                                 
526                                 
527                             } else {
528                                 
529                             
530                                 this.protectScopeFromObfuscation(scope);
531                                 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);
532                             }
533
534                         }
535
536                     }
537                     break;
538                 
539                 
540             } // end switch
541             
542             
543             //print("parseScope TOK : " + token.toString()); 
544             token = this.ts.nextTok();
545             //if (this.ts.nextT()) break;
546             
547         }
548         //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
549     },
550
551     expN : 0,
552     parseExpression : function() {
553
554         // Parse the expression until we encounter a comma or a semi-colon
555         // in the same brace nesting, bracket nesting and paren nesting.
556         // Parse functions if any...
557         //println("<i>EXP</i><BR/>");
558         !this.debug || print("PARSE EXPR");
559         this.expN++;
560          
561         // for printing stuff..
562        
563         
564         
565         var symbol;
566         var token;
567         var currentScope;
568         var identifier;
569
570         var expressionBraceNesting = this.braceNesting + 0;
571         var bracketNesting = 0;
572         var parensNesting = 0;
573         var isInObjectLitAr;
574         var isObjectLitAr = [ false ];
575         
576         currentScope = this.scopes[this.scopes.length-1];
577             
578         
579         //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
580         while (token = this.ts.lookTok()) {
581      
582
583             
584            /*
585             // moved out of loop?
586            currentScope = this.scopes[this.scopes.length-1];
587             
588             var scopeIndent = ''; 
589             this.scopes.forEach(function() {
590                 scopeIndent += '   '; 
591             });
592            */ 
593            
594            //this.dumpToken(token,  this.scopes, this.braceNesting );
595            //print('EXP' + this.expN + ':' + token.toString());
596             
597             
598             //println("<i>"+token.data+"</i>");
599             //this.log("EXP:" + token.data);
600             switch (token.type) {
601                 case 'PUNC':
602                     print("EXPR-PUNC:" + JSON.stringify(token, null, 4));
603                     
604                     switch(token.data) {
605                          
606                         case ';':
607                         case ',':
608                             if (this.braceNesting == expressionBraceNesting &&
609                                     bracketNesting == 0 &&
610                                     parensNesting == 0) {
611                                 print("<< EXIT EXPRESSION");
612                                 this.expN--;
613                                 return;
614                             }
615                             break;
616
617                        
618
619                         case '{': //Token.LC:
620                             isObjectLitAr.push(false);
621                             
622                             this.braceNesting++;
623                             ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
624                             break;
625
626                         case '}': //Token.RC:
627                             this.braceNesting--;
628                             isObjectLitAr.pop();
629                             //print(">>>>> EXP POP" + this.braceNesting);    
630                            // assert braceNesting >= expressionBraceNesting;
631                             break;
632
633                         case '[': //Token.LB:
634                         
635                             var ts = this.ts;
636                             var _this = this;
637                             token.items.forEach(function(ns) {
638                                  print("EXPR-PUNC[:" + JSON.stringify(ns, null, 4));
639                                 _this.ts = new TokenStream(ns);
640                                 _this.parseExpression();
641                             });
642                             this.ts = ts;
643                             
644                             break;
645 /*
646                         case ']': //Token.RB:
647                             bracketNesting--;
648                             break;
649 */
650                         case '(': //Token.LP:
651                             parensNesting++;
652                             break;
653
654                         case ')': //Token.RP:
655                             parensNesting--;
656                             break;
657                     }
658                     break;
659                     
660                 case 'STRN': // used for object lit detection..
661                     print("EXPR-STR:" + JSON.stringify(token, null, 4));
662                     if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
663                         // then we are in an object lit.. -> we need to flag the brace as such...
664                         isObjectLitAr.pop();
665                         isObjectLitAr.push(true);
666                         //print(">>>>> EXP PUSH(true)");
667                     }
668                     
669                     
670                      
671                     isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
672                     if (isInObjectLitAr &&  this.ts.lookTok(1).data == ":"  &&
673                         ( this.ts.lookTok(-1).data == "{"  ||  this.ts.lookTok(-1).data == "," )) {
674                         // see if we can replace..
675                         // remove the quotes..
676                         var str = token.data.substring(1,token.data.length-1);
677                         if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
678                             token.outData = str;
679                         }
680                         
681                          
682                         
683                     }
684                     
685                     break;
686                 
687                       
688              
689                 case 'NAME':
690                     print("EXPR-NAME:" + JSON.stringify(token, null, 4));
691                     symbol = token.data;
692                     //print("in NAME = " + token.toString());
693                     //print("in NAME 0: " + this.ts.look(0).toString());
694                     //print("in NAME 2: " + this.ts.lookTok(2).toString());
695                     if (this.ts.look(0).data == "{"  && this.ts.lookTok(2).data == ":") {
696                         // then we are in an object lit.. -> we need to flag the brace as such...
697                         isObjectLitAr.pop();
698                         isObjectLitAr.push(true);
699                          //print(">>>>> EXP  PUSH(true)");
700                         break;
701                     }
702                     
703                     isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
704                     //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
705                     
706                     if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
707                         break;
708                     }
709                     //print(this.ts.lookTok(0).data);
710                     if (this.ts.lookTok(0).data == ".") {
711                         //skip '.'
712                         break;
713                     }
714                     
715                      if (this.mode == 'PASS2_SYMBOL_TREE') {
716
717                         identifier = this.getIdentifier(symbol, currentScope);
718                         //println("<B>??</B>");
719                         if (identifier == false) {
720
721                             if (symbol.length <= 3 &&  Scope.builtin.indexOf(symbol) < 0) {
722                                 // Here, we found an undeclared and un-namespaced symbol that is
723                                 // 3 characters or less in length. Declare it in the global scope.
724                                 // We don't need to declare longer symbols since they won't cause
725                                 // any conflict with other munged symbols.
726                                 this.globalScope.declareIdentifier(symbol, token);
727                                 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
728                             } else {
729                                 //println("undeclared")
730                             }
731                             
732                             
733                         } else {
734                             //println("<B>++</B>");
735                             token.identifier = identifier;
736                             identifier.refcount++;
737                         }
738                         
739                     }
740                     break;
741                     
742                     
743                     
744                     
745                     //println("<B>EID</B>");
746                  case 'KEYW':   
747                     print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
748                     if (token.name == "FUNCTION") {
749                         
750                         this.parseFunctionDeclaration();
751                         break;
752                     }
753                
754                     
755              
756                     symbol = token.data;
757                     if (this.mode == 'BUILDING_SYMBOL_TREE') {
758
759                         if (symbol == "eval") {
760                             if (this.ts.look(-1).type == 'COMM') {
761                                 // look for eval:var:noreplace\n
762                                 var _t = this;
763                                 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
764                                     var hi = _t.getIdentifier(a, currentScope);
765                                    //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
766                                     if (hi) {
767                                       //  println("PROTECT "+a+" from munge");
768                                         hi.toMunge = false;
769                                     }
770                                     
771                                     
772                                 });
773                                 
774                             } else {
775                                 this.protectScopeFromObfuscation(currentScope);
776                                 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
777                             }
778                             
779
780                         }
781                         break;
782                     } 
783                    
784             }
785             if (!this.ts.nextTok()) break;
786         }
787         print("<< EXIT EXPRESSION");
788         this.expN--;
789     },
790
791
792     parseCatch : function() {
793
794         var symbol;
795         var token;
796         var currentScope;
797         var identifier;
798
799         //token = getToken(-1);
800         //assert token.getType() == Token.CATCH;
801         token = this.ts.nextTok();
802         //assert token.getType() == Token.LP; (
803         token = this.ts.nextTok();
804         //assert token.getType() == Token.NAME;
805         
806         symbol = token.data;
807         currentScope = this.scopes[this.scopes.length-1];
808
809         if (this.mode == 'BUILDING_SYMBOL_TREE') {
810             // We must declare the exception identifier in the containing function
811             // scope to avoid errors related to the obfuscation process. No need to
812             // display a warning if the symbol was already declared here...
813             currentScope.declareIdentifier(symbol, token);
814         } else {
815             //?? why inc the refcount?? - that should be set when building the tree???
816             identifier = this.getIdentifier(symbol, currentScope);
817             identifier.refcount++;
818         }
819
820         token = this.ts.nextTok();
821         //assert token.getType() == Token.RP; // )
822     },
823     
824     parseFunctionDeclaration : function() 
825     {
826         //print("PARSE FUNCTION");
827         var symbol;
828         var token;
829         var currentScope  = false; 
830         var fnScope = false;
831         var identifier;
832         var b4braceNesting = this.braceNesting + 0;
833         
834         //this.logR("<B>PARSING FUNCTION</B>");
835         currentScope = this.scopes[this.scopes.length-1];
836
837         token = this.ts.nextTok();
838         if (token.type == "NAME") {
839             if (this.mode == 'BUILDING_SYMBOL_TREE') {
840                 // Get the name of the function and declare it in the current scope.
841                 symbol = token.data;
842                 if (currentScope.getIdentifier(symbol) != false) {
843                     this.warn("The function " + symbol + " has already been declared in the same scope...", true);
844                 }
845                 currentScope.declareIdentifier(symbol,token);
846             }
847             token =  this.ts.nextTok();
848         }
849
850         //assert token.getType() == Token.LP;
851         if (this.mode == 'BUILDING_SYMBOL_TREE') {
852             fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
853             
854             //println("STORING SCOPE" + this.ts.cursor);
855             
856             this.indexedScopes[this.ts.cursor] = fnScope;
857             
858         } else {
859             //qln("FETCHING SCOPE" + this.ts.cursor);
860             fnScope = this.indexedScopes[this.ts.cursor];
861           
862         }
863         
864         print('FUNC-PARSE:' + JSON.stringify(token,null,4));
865         // Parse function arguments.
866         var args = token.items;
867         for (var argpos =0; argpos < args.length; argpos++) {
868              
869             token = args[argpos][0];
870            // print ("FUNC ARGS: " + token.toString())
871             //assert token.getType() == Token.NAME ||
872             //        token.getType() == Token.COMMA;
873             if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
874                 symbol = token.data;
875                 identifier = fnScope.declareIdentifier(symbol,token);
876                 if (symbol == "$super" && argpos == 0) {
877                     // Exception for Prototype 1.6...
878                     identifier.preventMunging();
879                 }
880                 argpos++;
881             }
882         }
883         
884         token = this.ts.nextTok();
885         //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
886         //Seed.quit();
887         //print(token.toString());
888         // assert token.getType() == Token.LC;
889         //this.braceNesting++;
890         
891         //token = this.ts.nextTok();
892         //print(token.toString());
893         var outTS = this.ts;
894         var _this = this;
895         token.items.forEach(function(tar) {
896             _this.ts = new TokenStream(tar);
897             _this.parseScope(fnScope);
898             
899         });
900         
901         //print(JSON.stringify(this.ts,null,4));
902         //this.parseScope(fnScope);
903         this.ts = outTS;
904         // now pop it off the stack!!!
905        
906         //this.braceNesting = b4braceNesting;
907         //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
908         //print("ENDFN 0: " + this.ts.lookTok(0).toString());
909         //print("ENDFN 1: " + this.ts.lookTok(1).toString());
910     },
911     
912     protectScopeFromObfuscation : function(scope) {
913             //assert scope != null;
914         
915         if (scope == this.globalScope) {
916             // The global scope does not get obfuscated,
917             // so we don't need to worry about it...
918             return;
919         }
920
921         // Find the highest local scope containing the specified scope.
922         while (scope && scope.parent != this.globalScope) {
923             scope = scope.parent;
924         }
925
926         //assert scope.getParentScope() == globalScope;
927         scope.preventMunging();
928     },
929     
930     getIdentifier: function(symbol, scope) {
931         var identifier;
932         while (scope != false) {
933             identifier = scope.getIdentifier(symbol);
934             //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
935             if (identifier) {
936                 return identifier;
937             }
938             scope = scope.parent;
939         }
940         return false;
941     }
942 };