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