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