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