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         thisScope = scope;
227         if (thisScope && thisScope.gid != this.scopes[this.scopes.length-1]) {
228             this.scopes.push(scope);
229         } else {
230             thisScope = this.scopes[this.scopes.length-1]
231         }
232        
233         //var scopeIndent = ''; 
234         //this.scopes.forEach(function() {
235         //    scopeIndent += '   '; 
236         //});
237         //print(">> ENTER SCOPE");
238         
239         
240         
241         
242         token = this.ts.lookTok(1);
243         while (token) {
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);
250             }
251             switch(token.type + '.' + token.name) {
252                 case "KEYW.VAR":
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;
256                     
257                     //this.log("parseScope GOT VAR/CONST : " + token.toString()); 
258                     while (true) {
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!
263                             break;
264                         }
265                         if (token.name == "VAR" || token.data == ',') { // kludge..
266                             continue;
267                         }
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());
272                             }
273                             
274                             print( "var without ident");
275                             Seed.quit()
276                         }
277                         
278
279                         if (this.mode == "BUILDING_SYMBOL_TREE") {
280                             identifier = thisScope.getIdentifier(token.data,token) ;
281                             
282                             if (identifier == false) {
283                                 thisScope.declareIdentifier(token.data, token);
284                             } else {
285                                 token.identifier = identifier;
286                                 this.warn("(SCOPE) The variable " + token.data  + ' (line:' + token.line + ")  has already been declared in the same scope...");
287                             }
288                         }
289
290                         token = this.ts.nextTok();
291                         !this.debug|| print(token.toString());
292                         /*
293                         assert token.getType() == Token.SEMI ||
294                                 token.getType() == Token.ASSIGN ||
295                                 token.getType() == Token.COMMA ||
296                                 token.getType() == Token.IN;
297                         */
298                         if (token.name == "IN") {
299                             break;
300                         } else {
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()); 
307                             
308                             token = this.ts.lookTok(1);
309                             !this.debug|| print("AFTER EXP: " + token.toString());
310                             if (token.data == ';') {
311                                 break;
312                             }
313                         }
314                     }
315                     
316                     //print("VAR:")
317                     //this.ts.dump(vstart , this.ts.cursor);
318                     
319                     break;
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;
327                     break;
328
329                 case "PUNC.LEFT_CURLY": // {
330                 case "PUNC.LEFT_PAREN": // (    
331                     //print('SCOPE-CURLY/PAREN:' + token.toString());
332                     //println("<i>"+token.data+"</i>");
333                     var curTS = this.ts;
334                     if (token.props) {
335                         
336                         for (var prop in token.props) {
337                             
338                             
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);
343                                 this.ts.nextTok();
344                                 this.parseFunctionDeclaration();
345                                 
346                                 continue;
347                             }
348                             // key value..
349                             
350                             this.ts = new TokenStream(token.props[prop].val);
351                             this.parseScope(false);
352                             
353                         }
354                         this.ts = curTS;
355                         
356                         // it's an object literal..
357                         // the values could be replaced..
358                         break;
359                     }
360                     
361                     
362                     var _this = this;
363                     token.items.forEach(function(expr) {
364                           _this.ts = new TokenStream(expr);
365                           _this.parseExpression()
366                     });
367                     this.ts = curTS;
368                     //print("NOT PROPS"); Seed.quit();
369                     
370                     //isObjectLitAr.push(false);
371                     //this.braceNesting++;
372                     
373                     //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
374                     break;
375
376                 case "PUNC.RIGHT_CURLY": // }
377                     //print("<< EXIT SCOPE");
378                     return;
379                 /*
380                     //println("<i>"+token.data+"</i>");
381                     this.braceNesting--;
382                     isObjectLitAr.pop();
383                     //print(">>>>>> OBJLIT POP"+ this.braceNesting);
384                         //assert braceNesting >= scope.getBra ceNesting();
385                     
386                     if (this.braceNesting < expressionBraceNesting) {
387                         var ls = this.scopes.pop();
388                         ls.getUsedSymbols();
389                         // eat symbol if we are currently at { 
390                         if (this.ts.look(0).data == '{') {
391                             this.ts.nextTok();
392                         }
393                         
394                         print("<<<<<<<EXIT SCOPE" +this.scopes.length);
395                         return;
396                     }
397                     break;
398 */
399                 case "KEYW.WITH":
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);
410                     }
411                     break;
412
413                 case "KEYW.CATCH":
414                     //print('SCOPE-CATCH:' + token.toString());
415                     //println("<i>"+token.data+"</i>");
416                     this.parseCatch();
417                     break;
418                 /*
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);
423                         }
424                         break;
425                 */
426                 
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>");
431
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...
434                         isObjectLitAr.pop();
435                         isObjectLitAr.push(true);
436                         //print(">>>>>> OBJLIT REPUSH(true)");
437                     }
438                     isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
439                     
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) {
447                             token.outData = str;
448                         }
449                         
450                          
451                         
452                     }
453                     
454                     
455                     
456                     break;
457                 
458                 case "NAME.NAME":
459                     //print('SCOPE-NAME:' + token.toString());
460                     //print("DEAL WITH NAME:");
461                     // got identifier..
462                     
463                     // look for  { ** : <- indicates obj literal.. ** this could occur with numbers ..
464                      
465                     
466                     // skip anyting with "." before it..!!
467                      
468                     if (this.ts.lookTok(-1).data == ".") {
469                         // skip, it's an object prop.
470                         //println("<i>"+token.data+"</i>");
471                         break;
472                     }
473                     //print("SYMBOL: " + token.toString());
474                     
475                     symbol = token.data;
476                     if (symbol == 'this') {
477                         break;
478                     }
479                     if (this.mode == 'PASS2_SYMBOL_TREE') {
480                         
481                         //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 :  " +  this.ts.lookT(-1).toString() + " <BR> "); 
482                         
483                         //print ("MUNGE?" + symbol);
484                         
485                         //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
486                              
487                             //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
488                         identifier = this.getIdentifier(symbol, thisScope, token);
489                         
490                         if (identifier == false) {
491 // BUG!find out where builtin is defined...
492                             if (symbol.length <= 3 &&  Scope.builtin.indexOf(symbol) < 0) {
493                                 // Here, we found an undeclared and un-namespaced symbol that is
494                                 // 3 characters or less in length. Declare it in the global scope.
495                                 // We don't need to declare longer symbols since they won't cause
496                                 // any conflict with other munged symbols.
497                                 this.globalScope.declareIdentifier(symbol, token);
498                                 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
499                             }
500                             
501                             //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
502                         } else {
503                             token.identifier = identifier;
504                             identifier.refcount++;
505                         }
506                     }   
507                     
508                     break;
509                     //println("<B>SID</B>");
510                 default:
511                     if (token.type != 'KEYW') {
512                         break;
513                     }
514                     //print('SCOPE-KEYW:' + token.toString());
515                    // print("Check eval:");
516                 
517                     symbol = token.data;
518                     
519                      if (this.mode == 'BUILDING_SYMBOL_TREE') {
520
521                         if (symbol == "eval") {
522                             // look back one and see if we can find a comment!!!
523                             if (this.ts.look(-1).type == "COMM") {
524                                 // look for eval:var:noreplace\n
525                                 var _t = this;
526                                 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
527                                     
528                                     var hi = _t.getIdentifier(a, thisScope, token);
529                                    // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
530                                     if (hi) {
531                                      //   println("PROTECT "+a+" from munge");
532                                         hi.toMunge = false;
533                                     }
534                                     
535                                 });
536                                 
537                                 
538                             } else {
539                                 
540                             
541                                 this.protectScopeFromObfuscation(thisScope);
542                                 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);
543                             }
544
545                         }
546
547                     }
548                     break;
549                 
550                 
551             } // end switch
552             
553             
554             //print("parseScope TOK : " + token.toString()); 
555             token = this.ts.nextTok();
556             //if (this.ts.nextT()) break;
557             
558         }
559         //print("<<< EXIT SCOPE");
560         //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
561     },
562
563     expN : 0,
564     parseExpression : function() {
565
566         // Parse the expression until we encounter a comma or a semi-colon
567         // in the same brace nesting, bracket nesting and paren nesting.
568         // Parse functions if any...
569         //println("<i>EXP</i><BR/>");
570         !this.debug || print("PARSE EXPR");
571         this.expN++;
572          
573         // for printing stuff..
574        
575         
576         
577         var symbol;
578         var token;
579         var currentScope;
580         var identifier;
581
582         var expressionBraceNesting = this.braceNesting + 0;
583         var bracketNesting = 0;
584         var parensNesting = 0;
585         var isInObjectLitAr;
586         var isObjectLitAr = [ false ];
587         
588         currentScope = this.scopes[this.scopes.length-1];
589             
590         
591         //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
592         while (token = this.ts.nextTok()) {
593      
594         
595             
596            /*
597             // moved out of loop?
598            currentScope = this.scopes[this.scopes.length-1];
599             
600             var scopeIndent = ''; 
601             this.scopes.forEach(function() {
602                 scopeIndent += '   '; 
603             });
604            */ 
605            
606            //this.dumpToken(token,  this.scopes, this.braceNesting );
607            //print('EXP' +  token.toString());
608             
609             
610             //println("<i>"+token.data+"</i>");
611             //this.log("EXP:" + token.data);
612             switch (token.type) {
613                 case 'PUNC':
614                     //print("EXPR-PUNC:" + token.toString());
615                     
616                     switch(token.data) {
617                          
618                         case ';':
619                             //print("<< EXIT EXPRESSION");
620                             break;
621
622                         case ',':
623                             
624                             break;
625
626                        
627                         case '(': //Token.LP:
628                         case '{': //Token.LC:
629                         case '[': //Token.LB:
630                             //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
631                             //println("<i>"+token.data+"</i>");
632                             var curTS = this.ts;
633                             if (token.props) {
634                                 
635                                 for (var prop in token.props) {
636                                     if (token.props[prop].val.data == 'function') {
637                                         // parse a function..
638                                         this.parseFunctProp(token.props[prop]);
639                                         continue;
640                                     }
641                                     // key value..
642                                     
643                                     this.ts = new TokenStream(token.props[prop].val);
644                                     this.parseScope(false);
645                                     
646                                 }
647                                 this.ts = curTS;
648                                 
649                                 // it's an object literal..
650                                 // the values could be replaced..
651                                 break;
652                             }
653                             
654                             
655                             var _this = this;
656                             token.items.forEach(function(expr) {
657                                   _this.ts = new TokenStream(expr);
658                                   _this.parseExpression()
659                             });
660                             this.ts = curTS;
661                         
662                         
663                     
664                             ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
665                             break;
666
667                        
668                         
669                          
670                             
671                         case ')': //Token.RP:
672                         case ']': //Token.RB:
673                         case '}': //Token.RB:
674                             //print("<< EXIT EXPRESSION");
675                             return;
676                            
677  
678              
679                             parensNesting++;
680                             break;
681
682                         
683                             
684                     }
685                     break;
686                     
687                 case 'STRN': // used for object lit detection..
688                     //if (this.mode == 'BUILDING_SYMBOL_TREE')    
689                         //print("EXPR-STR:" + JSON.stringify(token, null, 4));
690                
691                      
692                     break;
693                 
694                       
695              
696                 case 'NAME':
697                     if (this.mode == 'BUILDING_SYMBOL_TREE') {
698                         
699                         //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
700                     } else {
701                         //print("EXPR-NAME:" + token.toString());
702                     }
703                     symbol = token.data;
704                     //print("in NAME = " + token.toString());
705                     //print("in NAME 0: " + this.ts.look(0).toString());
706                     //print("in NAME 2: " + this.ts.lookTok(2).toString());
707                     
708                     //print(this.ts.lookTok(-1).data);
709                     // prefixed with '.'
710                     if (this.ts.lookTok(-1).data == ".") {
711                         //skip '.'
712                         break;
713                     }
714                     if (symbol == 'this') {
715                         break;
716                        }
717                     
718                     if (this.mode == 'PASS2_SYMBOL_TREE') {
719
720                         identifier = this.getIdentifier(symbol, currentScope, token);
721                         //println("<B>??</B>");
722                         if (identifier == false) {
723
724                             if (symbol.length <= 3 &&  Scope.builtin.indexOf(symbol) < 0) {
725                                 // Here, we found an undeclared and un-namespaced symbol that is
726                                 // 3 characters or less in length. Declare it in the global scope.
727                                 // We don't need to declare longer symbols since they won't cause
728                                 // any conflict with other munged symbols.
729                                 this.globalScope.declareIdentifier(symbol, token);
730                                 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
731                                 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
732                                 //throw "OOPS";
733                             } else {
734                                 //print("undeclared:" + token.toString())
735                             }
736                             
737                             
738                         } else {
739                             //println("<B>++</B>");
740                             token.identifier = identifier;
741                             identifier.refcount++;
742                         }
743                         
744                     }
745                     break;
746                     
747                     
748                     
749                     
750                     //println("<B>EID</B>");
751                 case 'KEYW':   
752                     //if (this.mode == 'BUILDING_SYMBOL_TREE') 
753                     //    print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
754                     if (token.name == "FUNCTION") {
755                         
756                         this.parseFunctionDeclaration();
757                         break;
758                     }
759                
760                     
761              
762                     symbol = token.data;
763                     if (this.mode == 'BUILDING_SYMBOL_TREE') {
764
765                         if (symbol == "eval") {
766                             if (this.ts.look(-1).type == 'COMM') {
767                                 // look for eval:var:noreplace\n
768                                 var _t = this;
769                                 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
770                                     var hi = _t.getIdentifier(a, currentScope, token);
771                                    //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
772                                     if (hi) {
773                                       //  println("PROTECT "+a+" from munge");
774                                         hi.toMunge = false;
775                                     }
776                                     
777                                     
778                                 });
779                                 
780                             } else {
781                                 this.protectScopeFromObfuscation(currentScope);
782                                 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
783                             }
784                             
785
786                         }
787                         break;
788                     } 
789                 default:
790                     //if (this.mode == 'BUILDING_SYMBOL_TREE') 
791                     //    print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
792                     break;
793             }
794             
795         }
796         //print("<< EXIT EXPRESSION");
797         this.expN--;
798     },
799
800
801     parseCatch : function() {
802
803         var symbol;
804         var token;
805         var currentScope;
806         var identifier;
807
808         //token = getToken(-1);
809         //assert token.getType() == Token.CATCH;
810         token = this.ts.nextTok();
811         //assert token.getType() == Token.LP; (
812         //token = this.ts.nextTok();
813         //assert token.getType() == Token.NAME;
814         
815         symbol = token.items[0].data;
816         currentScope = this.scopes[this.scopes.length-1];
817
818         if (this.mode == 'BUILDING_SYMBOL_TREE') {
819             // We must declare the exception identifier in the containing function
820             // scope to avoid errors related to the obfuscation process. No need to
821             // display a warning if the symbol was already declared here...
822             currentScope.declareIdentifier(symbol, token);
823         } else {
824             //?? why inc the refcount?? - that should be set when building the tree???
825             identifier = this.getIdentifier(symbol, currentScope, token);
826             identifier.refcount++;
827         }
828
829         token = this.ts.nextTok();
830         //assert token.getType() == Token.RP; // )
831     },
832     
833     parseFunctionDeclaration : function() 
834     {
835         //print("PARSE FUNCTION");
836         var symbol;
837         var token;
838         var currentScope  = false; 
839         var fnScope = false;
840         var identifier;
841         var b4braceNesting = this.braceNesting + 0;
842         
843         //this.logR("<B>PARSING FUNCTION</B>");
844         currentScope = this.scopes[this.scopes.length-1];
845
846         token = this.ts.nextTok();
847         if (token.type == "NAME") {
848             if (this.mode == 'BUILDING_SYMBOL_TREE') {
849                 // Get the name of the function and declare it in the current scope.
850                 symbol = token.data;
851                 if (currentScope.getIdentifier(symbol,token) != false) {
852                     this.warn("The function " + symbol + " has already been declared in the same scope...", true);
853                 }
854                 currentScope.declareIdentifier(symbol,token);
855             }
856             token =  this.ts.nextTok();
857         }
858
859         //assert token.getType() == Token.LP;
860         if (this.mode == 'BUILDING_SYMBOL_TREE') {
861             fnScope = new Scope(1, currentScope, token.n, '');
862             
863             //println("STORING SCOPE" + this.ts.cursor);
864             
865             this.indexedScopes[token.id] = fnScope;
866             
867         } else {
868             //qln("FETCHING SCOPE" + this.ts.cursor);
869             fnScope = this.indexedScopes[token.id];
870           
871         }
872         //if (this.mode == 'BUILDING_SYMBOL_TREE') 
873         //    print('FUNC-PARSE:' + JSON.stringify(token,null,4));
874         // Parse function arguments.
875         var args = token.items;
876         for (var argpos =0; argpos < args.length; argpos++) {
877              
878             token = args[argpos][0];
879             //print ("FUNC ARGS: " + token.toString())
880             //assert token.getType() == Token.NAME ||
881             //        token.getType() == Token.COMMA;
882             if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
883                 symbol = token.data;
884                 identifier = fnScope.declareIdentifier(symbol,token);
885                 if (symbol == "$super" && argpos == 0) {
886                     // Exception for Prototype 1.6...
887                     identifier.preventMunging();
888                 }
889                 //argpos++;
890             }
891         }
892         
893         token = this.ts.nextTok();
894         //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
895         //Seed.quit();
896         //print(token.toString());
897         // assert token.getType() == Token.LC;
898         //this.braceNesting++;
899         
900         //token = this.ts.nextTok();
901         //print(token.toString());
902         var outTS = this.ts;
903         var _this = this;
904         token.items.forEach(function(tar) {
905             _this.ts = new TokenStream(tar);
906             _this.parseScope(fnScope);
907             
908             
909         });
910         
911         //print(JSON.stringify(this.ts,null,4));
912         //this.parseScope(fnScope);
913         this.ts = outTS;
914         // now pop it off the stack!!!
915        
916         //this.braceNesting = b4braceNesting;
917         //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
918         //print("ENDFN 0: " + this.ts.lookTok(0).toString());
919         //print("ENDFN 1: " + this.ts.lookTok(1).toString());
920     },
921     
922     protectScopeFromObfuscation : function(scope) {
923             //assert scope != null;
924         
925         if (scope == this.globalScope) {
926             // The global scope does not get obfuscated,
927             // so we don't need to worry about it...
928             return;
929         }
930
931         // Find the highest local scope containing the specified scope.
932         while (scope && scope.parent != this.globalScope) {
933             scope = scope.parent;
934         }
935
936         //assert scope.getParentScope() == globalScope;
937         scope.preventMunging();
938     },
939     
940     getIdentifier: function(symbol, scope, token) {
941         var identifier;
942         while (scope != false) {
943             identifier = scope.getIdentifier(symbol, token);
944             //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
945             if (identifier) {
946                 return identifier;
947             }
948             scope = scope.parent;
949         }
950         return false;
951     }
952 };