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