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