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