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