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