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