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