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:' + token.toString());
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                     if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
385                         // then we are in an object lit.. -> we need to flag the brace as such...
386                         isObjectLitAr.pop();
387                         isObjectLitAr.push(true);
388                         //print(">>>>>> OBJLIT REPUSH(true)");
389                     }
390                     isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
391                     
392                     if (isInObjectLitAr &&  this.ts.lookTok(1).data == ':' &&
393                         ( this.ts.lookTok(-1).data == '{'  ||  this.ts.lookTok(-1).data == ':' )) {
394                         // see if we can replace..
395                         // remove the quotes..
396                         // should do a bit more checking!!!! (what about wierd char's in the string..
397                         var str = token.data.substring(1,token.data.length-1);
398                         if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
399                             token.outData = str;
400                         }
401                         
402                          
403                         
404                     }
405                     
406                     
407                     
408                     break;
409                 
410                 case "NAME.NAME":
411                     print('SCOPE-NAME:' + token.toString());
412                     //print("DEAL WITH NAME:");
413                     // got identifier..
414                     
415                     // look for  { ** : <- indicates obj literal.. ** this could occur with numbers ..
416                     if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
417                         isObjectLitAr.pop();
418                         isObjectLitAr.push(true);
419                         //print(">>>>>> OBJLIT REPUSH(true)");
420                         //println("<i>"+token.data+"</i>");
421                         break;
422                     }
423                    // print("DEAL WITH obj lit:");
424                     isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
425                     
426                     if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
427                         // skip, it's an object lit key..
428                         //println("<i>"+token.data+"</i>");
429                         break;
430                     }
431                     
432                     
433                     // skip anyting with "." before it..!!
434                      
435                     if (this.ts.lookTok(-1).data == ".") {
436                         // skip, it's an object prop.
437                         //println("<i>"+token.data+"</i>");
438                         break;
439                     }
440                     //print("SYMBOL: " + token.toString());
441                     
442                     symbol = token.data;
443                     if (this.mode == 'PASS2_SYMBOL_TREE') {
444                         
445                         //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 :  " +  this.ts.lookT(-1).toString() + " <BR> "); 
446                         
447                         //print ("MUNGE?" + symbol);
448                         
449                         //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
450                              
451                             //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
452                         identifier = this.getIdentifier(symbol, scope);
453                         
454                         if (identifier == false) {
455 // BUG!find out where builtin is defined...
456                             if (symbol.length <= 3 &&  Scope.builtin.indexOf(symbol) < 0) {
457                                 // Here, we found an undeclared and un-namespaced symbol that is
458                                 // 3 characters or less in length. Declare it in the global scope.
459                                 // We don't need to declare longer symbols since they won't cause
460                                 // any conflict with other munged symbols.
461                                 this.globalScope.declareIdentifier(symbol, token);
462                                 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
463                             }
464                             
465                             //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
466                         } else {
467                             token.identifier = identifier;
468                             identifier.refcount++;
469                         }
470                     }   
471                     
472                     break;
473                     //println("<B>SID</B>");
474                 default:
475                     if (token.type != 'KEYW') {
476                         break;
477                     }
478                     print('SCOPE-KEYW:' + token.toString());
479                    // print("Check eval:");
480                 
481                     symbol = token.data;
482                     
483                      if (this.mode == 'BUILDING_SYMBOL_TREE') {
484
485                         if (symbol == "eval") {
486                             // look back one and see if we can find a comment!!!
487                             if (this.ts.look(-1).type == "COMM") {
488                                 // look for eval:var:noreplace\n
489                                 var _t = this;
490                                 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
491                                     
492                                     var hi = _t.getIdentifier(a, scope);
493                                    // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
494                                     if (hi) {
495                                      //   println("PROTECT "+a+" from munge");
496                                         hi.toMunge = false;
497                                     }
498                                     
499                                 });
500                                 
501                                 
502                             } else {
503                                 
504                             
505                                 this.protectScopeFromObfuscation(scope);
506                                 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);
507                             }
508
509                         }
510
511                     }
512                     break;
513                 
514                 
515             } // end switch
516             
517             
518             //print("parseScope TOK : " + token.toString()); 
519             token = this.ts.nextTok();
520             //if (this.ts.nextT()) break;
521             
522         }
523         //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
524     },
525
526     expN : 0,
527     parseExpression : function() {
528
529         // Parse the expression until we encounter a comma or a semi-colon
530         // in the same brace nesting, bracket nesting and paren nesting.
531         // Parse functions if any...
532         //println("<i>EXP</i><BR/>");
533         !this.debug || print("PARSE EXPR");
534         this.expN++;
535          
536         // for printing stuff..
537        
538         
539         
540         var symbol;
541         var token;
542         var currentScope;
543         var identifier;
544
545         var expressionBraceNesting = this.braceNesting + 0;
546         var bracketNesting = 0;
547         var parensNesting = 0;
548         var isInObjectLitAr;
549         var isObjectLitAr = [ false ];
550         
551         currentScope = this.scopes[this.scopes.length-1];
552             
553         var scopeIndent = ''; 
554         this.scopes.forEach(function() {
555             scopeIndent += '   '; 
556         });
557         //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
558         while (token = this.ts.lookTok()) {
559      
560
561             
562            /*
563             // moved out of loop?
564            currentScope = this.scopes[this.scopes.length-1];
565             
566             var scopeIndent = ''; 
567             this.scopes.forEach(function() {
568                 scopeIndent += '   '; 
569             });
570            */ 
571            
572            //this.dumpToken(token,  this.scopes, this.braceNesting );
573            //print('EXP' + this.expN + ':' + token.toString());
574             
575             
576             //println("<i>"+token.data+"</i>");
577             //this.log("EXP:" + token.data);
578             switch (token.type) {
579                 case 'PUNC':
580                     switch(token.data) {
581                          
582                         case ';':
583                         case ',':
584                             if (this.braceNesting == expressionBraceNesting &&
585                                     bracketNesting == 0 &&
586                                     parensNesting == 0) {
587                                 print(scopeIndent + "<< EXIT EXPRESSION");
588                                 this.expN--;
589                                 return;
590                             }
591                             break;
592
593                        
594
595                         case '{': //Token.LC:
596                             isObjectLitAr.push(false);
597                             
598                             this.braceNesting++;
599                             ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
600                             break;
601
602                         case '}': //Token.RC:
603                             this.braceNesting--;
604                             isObjectLitAr.pop();
605                             //print(">>>>> EXP POP" + this.braceNesting);    
606                            // assert braceNesting >= expressionBraceNesting;
607                             break;
608
609                         case '[': //Token.LB:
610                             bracketNesting++;
611                             break;
612
613                         case ']': //Token.RB:
614                             bracketNesting--;
615                             break;
616
617                         case '(': //Token.LP:
618                             parensNesting++;
619                             break;
620
621                         case ')': //Token.RP:
622                             parensNesting--;
623                             break;
624                     }
625                     break;
626                     
627                 case 'STRN': // used for object lit detection..
628                     if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
629                         // then we are in an object lit.. -> we need to flag the brace as such...
630                         isObjectLitAr.pop();
631                         isObjectLitAr.push(true);
632                         //print(">>>>> EXP PUSH(true)");
633                     }
634                     
635                     
636                      
637                     isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
638                     if (isInObjectLitAr &&  this.ts.lookTok(1).data == ":"  &&
639                         ( this.ts.lookTok(-1).data == "{"  ||  this.ts.lookTok(-1).data == "," )) {
640                         // see if we can replace..
641                         // remove the quotes..
642                         var str = token.data.substring(1,token.data.length-1);
643                         if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
644                             token.outData = str;
645                         }
646                         
647                          
648                         
649                     }
650                     
651                     break;
652                 
653                       
654              
655                 case 'NAME':
656                
657                     symbol = token.data;
658                     //print("in NAME = " + token.toString());
659                     //print("in NAME 0: " + this.ts.look(0).toString());
660                     //print("in NAME 2: " + this.ts.lookTok(2).toString());
661                     if (this.ts.look(0).data == "{"  && this.ts.lookTok(2).data == ":") {
662                         // then we are in an object lit.. -> we need to flag the brace as such...
663                         isObjectLitAr.pop();
664                         isObjectLitAr.push(true);
665                          //print(">>>>> EXP  PUSH(true)");
666                         break;
667                     }
668                     
669                     isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
670                     //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
671                     
672                     if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
673                         break;
674                     }
675                     //print(this.ts.lookTok(0).data);
676                     if (this.ts.lookTok(0).data == ".") {
677                         //skip '.'
678                         break;
679                     }
680                     
681                      if (this.mode == 'PASS2_SYMBOL_TREE') {
682
683                         identifier = this.getIdentifier(symbol, currentScope);
684                         //println("<B>??</B>");
685                         if (identifier == false) {
686
687                             if (symbol.length <= 3 &&  Scope.builtin.indexOf(symbol) < 0) {
688                                 // Here, we found an undeclared and un-namespaced symbol that is
689                                 // 3 characters or less in length. Declare it in the global scope.
690                                 // We don't need to declare longer symbols since they won't cause
691                                 // any conflict with other munged symbols.
692                                 this.globalScope.declareIdentifier(symbol, token);
693                                 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
694                             } else {
695                                 //println("undeclared")
696                             }
697                             
698                             
699                         } else {
700                             //println("<B>++</B>");
701                             token.identifier = identifier;
702                             identifier.refcount++;
703                         }
704                         
705                     }
706                     break;
707                     
708                     
709                     
710                     
711                     //println("<B>EID</B>");
712                  case 'KEYW':   
713                  
714                     if (token.name == "FUNCTION") {
715                         
716                         this.parseFunctionDeclaration();
717                         break;
718                     }
719                
720                     
721              
722                     symbol = token.data;
723                     if (this.mode == 'BUILDING_SYMBOL_TREE') {
724
725                         if (symbol == "eval") {
726                             if (this.ts.look(-1).type == 'COMM') {
727                                 // look for eval:var:noreplace\n
728                                 var _t = this;
729                                 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
730                                     var hi = _t.getIdentifier(a, currentScope);
731                                    //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
732                                     if (hi) {
733                                       //  println("PROTECT "+a+" from munge");
734                                         hi.toMunge = false;
735                                     }
736                                     
737                                     
738                                 });
739                                 
740                             } else {
741                                 this.protectScopeFromObfuscation(currentScope);
742                                 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
743                             }
744                             
745
746                         }
747                         break;
748                     } 
749                    
750             }
751             if (!this.ts.nextTok()) break;
752         }
753         print(scopeIndent + "<< EXIT EXPRESSION");
754         this.expN--;
755     },
756
757
758     parseCatch : function() {
759
760         var symbol;
761         var token;
762         var currentScope;
763         var identifier;
764
765         //token = getToken(-1);
766         //assert token.getType() == Token.CATCH;
767         token = this.ts.nextTok();
768         //assert token.getType() == Token.LP; (
769         token = this.ts.nextTok();
770         //assert token.getType() == Token.NAME;
771         
772         symbol = token.data;
773         currentScope = this.scopes[this.scopes.length-1];
774
775         if (this.mode == 'BUILDING_SYMBOL_TREE') {
776             // We must declare the exception identifier in the containing function
777             // scope to avoid errors related to the obfuscation process. No need to
778             // display a warning if the symbol was already declared here...
779             currentScope.declareIdentifier(symbol, token);
780         } else {
781             //?? why inc the refcount?? - that should be set when building the tree???
782             identifier = this.getIdentifier(symbol, currentScope);
783             identifier.refcount++;
784         }
785
786         token = this.ts.nextTok();
787         //assert token.getType() == Token.RP; // )
788     },
789     
790     parseFunctionDeclaration : function() 
791     {
792         //print("PARSE FUNCTION");
793         var symbol;
794         var token;
795         var currentScope  = false; 
796         var fnScope = false;
797         var identifier;
798         var b4braceNesting = this.braceNesting + 0;
799         
800         //this.logR("<B>PARSING FUNCTION</B>");
801         currentScope = this.scopes[this.scopes.length-1];
802
803         token = this.ts.nextTok();
804         if (token.type == "NAME") {
805             if (this.mode == 'BUILDING_SYMBOL_TREE') {
806                 // Get the name of the function and declare it in the current scope.
807                 symbol = token.data;
808                 if (currentScope.getIdentifier(symbol) != false) {
809                     this.warn("The function " + symbol + " has already been declared in the same scope...", true);
810                 }
811                 currentScope.declareIdentifier(symbol,token);
812             }
813             token =  this.ts.nextTok();
814         }
815
816         //assert token.getType() == Token.LP;
817         if (this.mode == 'BUILDING_SYMBOL_TREE') {
818             fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
819             
820             //println("STORING SCOPE" + this.ts.cursor);
821             
822             this.indexedScopes[this.ts.cursor] = fnScope;
823             
824         } else {
825             //qln("FETCHING SCOPE" + this.ts.cursor);
826             fnScope = this.indexedScopes[this.ts.cursor];
827           
828         }
829         
830         // Parse function arguments.
831         var argpos = 0;
832         while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
833             token = this.ts.nextTok();
834            // print ("FUNC ARGS: " + token.toString())
835             //assert token.getType() == Token.NAME ||
836             //        token.getType() == Token.COMMA;
837             if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
838                 symbol = token.data;
839                 identifier = fnScope.declareIdentifier(symbol,token);
840                 if (symbol == "$super" && argpos == 0) {
841                     // Exception for Prototype 1.6...
842                     identifier.preventMunging();
843                 }
844                 argpos++;
845             }
846         }
847
848         token = this.ts.nextTok();
849         //print(token.toString());
850         // assert token.getType() == Token.LC;
851         this.braceNesting++;
852
853         token = this.ts.nextTok();
854         //print(token.toString());
855      
856
857         this.parseScope(fnScope);
858         // now pop it off the stack!!!
859        
860         this.braceNesting = b4braceNesting;
861         //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
862         //print("ENDFN 0: " + this.ts.lookTok(0).toString());
863         //print("ENDFN 1: " + this.ts.lookTok(1).toString());
864     },
865     
866     protectScopeFromObfuscation : function(scope) {
867             //assert scope != null;
868         
869         if (scope == this.globalScope) {
870             // The global scope does not get obfuscated,
871             // so we don't need to worry about it...
872             return;
873         }
874
875         // Find the highest local scope containing the specified scope.
876         while (scope && scope.parent != this.globalScope) {
877             scope = scope.parent;
878         }
879
880         //assert scope.getParentScope() == globalScope;
881         scope.preventMunging();
882     },
883     
884     getIdentifier: function(symbol, scope) {
885         var identifier;
886         while (scope != false) {
887             identifier = scope.getIdentifier(symbol);
888             //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
889             if (identifier) {
890                 return identifier;
891             }
892             scope = scope.parent;
893         }
894         return false;
895     }
896 };