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