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