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