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