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