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