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