just add some verbosity
[mono.git] / mcs / mbas / statement.cs
1 //
2 // statement.cs: Statement representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Martin Baulig (martin@gnome.org)
7 //
8 // (C) 2001, 2002 Ximian, Inc.
9 //
10
11 using System;
12 using System.Text;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
16
17 namespace Mono.CSharp {
18
19         using System.Collections;
20         
21         public abstract class Statement {
22                 public Location loc;
23                 
24                 ///
25                 /// Resolves the statement, true means that all sub-statements
26                 /// did resolve ok.
27                 //
28                 public virtual bool Resolve (EmitContext ec)
29                 {
30                         return true;
31                 }
32                 
33                 /// <summary>
34                 ///   Return value indicates whether all code paths emitted return.
35                 /// </summary>
36                 protected abstract bool DoEmit (EmitContext ec);
37
38                 /// <summary>
39                 ///   Return value indicates whether all code paths emitted return.
40                 /// </summary>
41                 public virtual bool Emit (EmitContext ec)
42                 {
43                         ec.Mark (loc);
44                         Report.Debug (8, "MARK", this, loc);
45                         return DoEmit (ec);
46                 }
47                 
48                 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
49                 {
50                         e = e.Resolve (ec);
51                         if (e == null)
52                                 return null;
53                         
54                         if (e.Type != TypeManager.bool_type){
55                                 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type,
56                                                                 new Location (-1));
57                         }
58
59                         if (e == null){
60                                 Report.Error (
61                                         31, loc, "Can not convert the expression to a boolean");
62                         }
63
64                         ec.Mark (loc);
65
66                         return e;
67                 }
68                 
69                 /// <remarks>
70                 ///    Encapsulates the emission of a boolean test and jumping to a
71                 ///    destination.
72                 ///
73                 ///    This will emit the bool expression in `bool_expr' and if
74                 ///    `target_is_for_true' is true, then the code will generate a 
75                 ///    brtrue to the target.   Otherwise a brfalse. 
76                 /// </remarks>
77                 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
78                                                        Label target, bool target_is_for_true)
79                 {
80                         ILGenerator ig = ec.ig;
81                         
82                         bool invert = false;
83                         if (bool_expr is Unary){
84                                 Unary u = (Unary) bool_expr;
85                                 
86                                 if (u.Oper == Unary.Operator.LogicalNot){
87                                         invert = true;
88
89                                         u.EmitLogicalNot (ec);
90                                 }
91                         } else if (bool_expr is Binary){
92                                 Binary b = (Binary) bool_expr;
93
94                                 if (b.EmitBranchable (ec, target, target_is_for_true))
95                                         return;
96                         }
97
98                         if (!invert)
99                                 bool_expr.Emit (ec);
100
101                         if (target_is_for_true){
102                                 if (invert)
103                                         ig.Emit (OpCodes.Brfalse, target);
104                                 else
105                                         ig.Emit (OpCodes.Brtrue, target);
106                         } else {
107                                 if (invert)
108                                         ig.Emit (OpCodes.Brtrue, target);
109                                 else
110                                         ig.Emit (OpCodes.Brfalse, target);
111                         }
112                 }
113
114                 public static void Warning_DeadCodeFound (Location loc)
115                 {
116                         Report.Warning (162, loc, "Unreachable code detected");
117                 }
118         }
119
120         public class EmptyStatement : Statement {
121                 public override bool Resolve (EmitContext ec)
122                 {
123                         return true;
124                 }
125                 
126                 protected override bool DoEmit (EmitContext ec)
127                 {
128                         return false;
129                 }
130         }
131         
132         public class If : Statement {
133                 Expression expr;
134                 public Statement TrueStatement;
135                 public Statement FalseStatement;
136                 
137                 public If (Expression expr, Statement trueStatement, Location l)
138                 {
139                         this.expr = expr;
140                         TrueStatement = trueStatement;
141                         loc = l;
142                 }
143
144                 public If (Expression expr,
145                            Statement trueStatement,
146                            Statement falseStatement,
147                            Location l)
148                 {
149                         this.expr = expr;
150                         TrueStatement = trueStatement;
151                         FalseStatement = falseStatement;
152                         loc = l;
153                 }
154
155                 public override bool Resolve (EmitContext ec)
156                 {
157                         Report.Debug (1, "START IF BLOCK", loc);
158
159                         expr = ResolveBoolean (ec, expr, loc);
160                         if (expr == null){
161                                 return false;
162                         }
163                         
164                         ec.StartFlowBranching (FlowBranchingType.BLOCK, loc);
165                         
166                         if (!TrueStatement.Resolve (ec)) {
167                                 ec.KillFlowBranching ();
168                                 return false;
169                         }
170
171                         ec.CurrentBranching.CreateSibling ();
172
173                         if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
174                                 ec.KillFlowBranching ();
175                                 return false;
176                         }
177                                         
178                         ec.EndFlowBranching ();
179
180                         Report.Debug (1, "END IF BLOCK", loc);
181
182                         return true;
183                 }
184                 
185                 protected override bool DoEmit (EmitContext ec)
186                 {
187                         ILGenerator ig = ec.ig;
188                         Label false_target = ig.DefineLabel ();
189                         Label end;
190                         bool is_true_ret, is_false_ret;
191
192                         //
193                         // Dead code elimination
194                         //
195                         if (expr is BoolConstant){
196                                 bool take = ((BoolConstant) expr).Value;
197
198                                 if (take){
199                                         if (FalseStatement != null){
200                                                 Warning_DeadCodeFound (FalseStatement.loc);
201                                         }
202                                         return TrueStatement.Emit (ec);
203                                 } else {
204                                         Warning_DeadCodeFound (TrueStatement.loc);
205                                         if (FalseStatement != null)
206                                                 return FalseStatement.Emit (ec);
207                                 }
208                         }
209                         
210                         EmitBoolExpression (ec, expr, false_target, false);
211
212                         is_true_ret = TrueStatement.Emit (ec);
213                         is_false_ret = is_true_ret;
214
215                         if (FalseStatement != null){
216                                 bool branch_emitted = false;
217                                 
218                                 end = ig.DefineLabel ();
219                                 if (!is_true_ret){
220                                         ig.Emit (OpCodes.Br, end);
221                                         branch_emitted = true;
222                                 }
223
224                                 ig.MarkLabel (false_target);
225                                 is_false_ret = FalseStatement.Emit (ec);
226
227                                 if (branch_emitted)
228                                         ig.MarkLabel (end);
229                         } else {
230                                 ig.MarkLabel (false_target);
231                                 is_false_ret = false;
232                         }
233
234                         return is_true_ret && is_false_ret;
235                 }
236         }
237
238         public enum DoOptions {
239                 WHILE,
240                 UNTIL,
241                 TEST_BEFORE,
242                 TEST_AFTER
243         };
244
245         public class Do : Statement {
246                 public Expression expr;
247                 public readonly Statement  EmbeddedStatement;
248                 //public DoOptions type;
249                 public DoOptions test;
250                 bool infinite, may_return;
251
252                 
253                 public Do (Statement statement, Expression boolExpr, DoOptions do_test, Location l)
254                 {
255                         expr = boolExpr;
256                         EmbeddedStatement = statement;
257 //                      type = do_type;
258                         test = do_test;
259                         loc = l;
260                 }
261
262                 public override bool Resolve (EmitContext ec)
263                 {
264                         bool ok = true;
265
266                         ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
267
268                         if (!EmbeddedStatement.Resolve (ec))
269                                 ok = false;
270
271                         expr = ResolveBoolean (ec, expr, loc);
272                         if (expr == null)
273                                 ok = false;
274                         else if (expr is BoolConstant){
275                                 bool res = ((BoolConstant) expr).Value;
276
277                                 if (res)
278                                         infinite = true;
279                         }
280
281                         ec.CurrentBranching.Infinite = infinite;
282                         FlowReturns returns = ec.EndFlowBranching ();
283                         may_return = returns != FlowReturns.NEVER;
284
285                         return ok;
286                 }
287                 
288                 protected override bool DoEmit (EmitContext ec)
289                 {
290                         ILGenerator ig = ec.ig;
291                         Label loop = ig.DefineLabel ();
292                         Label old_begin = ec.LoopBegin;
293                         Label old_end = ec.LoopEnd;
294                         bool  old_inloop = ec.InLoop;
295                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
296                         
297                         ec.LoopBegin = ig.DefineLabel ();
298                         ec.LoopEnd = ig.DefineLabel ();
299                         ec.InLoop = true;
300                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
301
302                         if (test == DoOptions.TEST_AFTER) {
303                                 ig.MarkLabel (loop);
304                                 EmbeddedStatement.Emit (ec);
305                                 ig.MarkLabel (ec.LoopBegin);
306
307                                 //
308                                 // Dead code elimination
309                                 //
310                                 if (expr is BoolConstant){
311                                         bool res = ((BoolConstant) expr).Value;
312
313                                         if (res)
314                                                 ec.ig.Emit (OpCodes.Br, loop);
315                                 } else
316                                         EmitBoolExpression (ec, expr, loop, true);
317
318                                 ig.MarkLabel (ec.LoopEnd);
319                         }
320                         else
321                         {
322                                 ig.MarkLabel (loop);
323                                 ig.MarkLabel (ec.LoopBegin);
324
325                                 //
326                                 // Dead code elimination
327                                 //
328                                 if (expr is BoolConstant){
329                                         bool res = ((BoolConstant) expr).Value;
330
331                                         if (res)
332                                                 ec.ig.Emit (OpCodes.Br, ec.LoopEnd);
333                                 } else
334                                         EmitBoolExpression (ec, expr, ec.LoopEnd, true);
335
336                                 EmbeddedStatement.Emit (ec);
337                                 ec.ig.Emit (OpCodes.Br, loop);
338                                 ig.MarkLabel (ec.LoopEnd);
339                         }
340                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
341                         ec.LoopBegin = old_begin;
342                         ec.LoopEnd = old_end;
343                         ec.InLoop = old_inloop;
344
345                         if (infinite)
346                                 return may_return == false;
347                         else
348                                 return false;
349                 }
350         }
351
352         public class While : Statement {
353                 public Expression expr;
354                 public readonly Statement Statement;
355                 bool may_return, empty, infinite;
356                 
357                 public While (Expression boolExpr, Statement statement, Location l)
358                 {
359                         this.expr = boolExpr;
360                         Statement = statement;
361                         loc = l;
362                 }
363
364                 public override bool Resolve (EmitContext ec)
365                 {
366                         bool ok = true;
367
368                         expr = ResolveBoolean (ec, expr, loc);
369                         if (expr == null)
370                                 return false;
371
372                         ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
373
374                         //
375                         // Inform whether we are infinite or not
376                         //
377                         if (expr is BoolConstant){
378                                 BoolConstant bc = (BoolConstant) expr;
379
380                                 if (bc.Value == false){
381                                         Warning_DeadCodeFound (Statement.loc);
382                                         empty = true;
383                                 } else
384                                         infinite = true;
385                         } else {
386                                 //
387                                 // We are not infinite, so the loop may or may not be executed.
388                                 //
389                                 ec.CurrentBranching.CreateSibling ();
390                         }
391
392                         if (!Statement.Resolve (ec))
393                                 ok = false;
394
395                         if (empty)
396                                 ec.KillFlowBranching ();
397                         else {
398                                 ec.CurrentBranching.Infinite = infinite;
399                                 FlowReturns returns = ec.EndFlowBranching ();
400                                 may_return = returns != FlowReturns.NEVER;
401                         }
402
403                         return ok;
404                 }
405                 
406                 protected override bool DoEmit (EmitContext ec)
407                 {
408                         if (empty)
409                                 return false;
410
411                         ILGenerator ig = ec.ig;
412                         Label old_begin = ec.LoopBegin;
413                         Label old_end = ec.LoopEnd;
414                         bool old_inloop = ec.InLoop;
415                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
416                         bool ret;
417                         
418                         ec.LoopBegin = ig.DefineLabel ();
419                         ec.LoopEnd = ig.DefineLabel ();
420                         ec.InLoop = true;
421                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
422
423                         //
424                         // Inform whether we are infinite or not
425                         //
426                         if (expr is BoolConstant){
427                                 BoolConstant bc = (BoolConstant) expr;
428
429                                 ig.MarkLabel (ec.LoopBegin);
430                                 Statement.Emit (ec);
431                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
432                                         
433                                 //
434                                 // Inform that we are infinite (ie, `we return'), only
435                                 // if we do not `break' inside the code.
436                                 //
437                                 ret = may_return == false;
438                                 ig.MarkLabel (ec.LoopEnd);
439                         } else {
440                                 Label while_loop = ig.DefineLabel ();
441
442                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
443                                 ig.MarkLabel (while_loop);
444
445                                 Statement.Emit (ec);
446                         
447                                 ig.MarkLabel (ec.LoopBegin);
448
449                                 EmitBoolExpression (ec, expr, while_loop, true);
450                                 ig.MarkLabel (ec.LoopEnd);
451
452                                 ret = false;
453                         }       
454
455                         ec.LoopBegin = old_begin;
456                         ec.LoopEnd = old_end;
457                         ec.InLoop = old_inloop;
458                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
459
460                         return ret;
461                 }
462         }
463
464         public class For : Statement {
465                 Expression Test;
466                 readonly Statement InitStatement;
467                 readonly Statement Increment;
468                 readonly Statement Statement;
469                 bool may_return, infinite, empty;
470                 
471                 public For (Statement initStatement,
472                             Expression test,
473                             Statement increment,
474                             Statement statement,
475                             Location l)
476                 {
477                         InitStatement = initStatement;
478                         Test = test;
479                         Increment = increment;
480                         Statement = statement;
481                         loc = l;
482                 }
483                 
484
485                 public override bool Resolve (EmitContext ec)
486                 {
487                         bool ok = true;
488
489                         if (InitStatement != null){
490                                 if (!InitStatement.Resolve (ec))
491                                         ok = false;
492                         }
493
494                         if (Test != null){
495                                 Test = ResolveBoolean (ec, Test, loc);
496                                 if (Test == null)
497                                         ok = false;
498                                 else if (Test is BoolConstant){
499                                         BoolConstant bc = (BoolConstant) Test;
500
501                                         if (bc.Value == false){
502                                                 Warning_DeadCodeFound (Statement.loc);
503                                                 empty = true;
504                                         } else
505                                                 infinite = true;
506                                 }
507                         } else
508                                 infinite = true;
509
510                         if (Increment != null){
511                                 if (!Increment.Resolve (ec))
512                                         ok = false;
513                         }
514
515                         ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
516                         if (!infinite)
517                                 ec.CurrentBranching.CreateSibling ();
518
519                         if (!Statement.Resolve (ec))
520                                 ok = false;
521
522                         if (empty)
523                                 ec.KillFlowBranching ();
524                         else {
525                                 ec.CurrentBranching.Infinite = infinite;
526                                 FlowReturns returns = ec.EndFlowBranching ();
527                                 may_return = returns != FlowReturns.NEVER;
528                         }
529
530                         return ok;
531                 }
532                 
533                 protected override bool DoEmit (EmitContext ec)
534                 {
535                         if (empty)
536                                 return false;
537
538                         ILGenerator ig = ec.ig;
539                         Label old_begin = ec.LoopBegin;
540                         Label old_end = ec.LoopEnd;
541                         bool old_inloop = ec.InLoop;
542                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
543                         Label loop = ig.DefineLabel ();
544                         Label test = ig.DefineLabel ();
545                         
546                         if (InitStatement != null)
547                                 if (! (InitStatement is EmptyStatement))
548                                         InitStatement.Emit (ec);
549
550                         ec.LoopBegin = ig.DefineLabel ();
551                         ec.LoopEnd = ig.DefineLabel ();
552                         ec.InLoop = true;
553                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
554
555                         ig.Emit (OpCodes.Br, test);
556                         ig.MarkLabel (loop);
557                         Statement.Emit (ec);
558
559                         ig.MarkLabel (ec.LoopBegin);
560                         if (!(Increment is EmptyStatement))
561                                 Increment.Emit (ec);
562
563                         ig.MarkLabel (test);
564                         //
565                         // If test is null, there is no test, and we are just
566                         // an infinite loop
567                         //
568                         if (Test != null)
569                                 EmitBoolExpression (ec, Test, loop, true);
570                         else
571                                 ig.Emit (OpCodes.Br, loop);
572                         ig.MarkLabel (ec.LoopEnd);
573
574                         ec.LoopBegin = old_begin;
575                         ec.LoopEnd = old_end;
576                         ec.InLoop = old_inloop;
577                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
578                         
579                         //
580                         // Inform whether we are infinite or not
581                         //
582                         if (Test != null){
583                                 if (Test is BoolConstant){
584                                         BoolConstant bc = (BoolConstant) Test;
585
586                                         if (bc.Value)
587                                                 return may_return == false;
588                                 }
589                                 return false;
590                         } else
591                                 return may_return == false;
592                 }
593         }
594         
595         public class StatementExpression : Statement {
596                 Expression expr;
597                 
598                 public StatementExpression (ExpressionStatement expr, Location l)
599                 {
600                         this.expr = expr;
601                         loc = l;
602                 }
603
604                 public override bool Resolve (EmitContext ec)
605                 {
606                         expr = (Expression) expr.Resolve (ec);
607                         return expr != null;
608                 }
609                 
610                 protected override bool DoEmit (EmitContext ec)
611                 {
612                         ILGenerator ig = ec.ig;
613                         
614                         if (expr is ExpressionStatement)
615                                 ((ExpressionStatement) expr).EmitStatement (ec);
616                         else {
617                                 expr.Emit (ec);
618                                 ig.Emit (OpCodes.Pop);
619                         }
620
621                         return false;
622                 }
623
624                 public override string ToString ()
625                 {
626                         return "StatementExpression (" + expr + ")";
627                 }
628         }
629
630         /// <summary>
631         ///   Implements the return statement
632         /// </summary>
633         public class Return : Statement {
634                 public Expression Expr;
635                 
636                 public Return (Expression expr, Location l)
637                 {
638                         Expr = expr;
639                         loc = l;
640                 }
641
642                 public override bool Resolve (EmitContext ec)
643                 {
644                         if (Expr != null){
645                                 Expr = Expr.Resolve (ec);
646                                 if (Expr == null)
647                                         return false;
648                         }
649
650                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
651
652                         if (ec.CurrentBranching.InTryBlock ())
653                                 ec.CurrentBranching.AddFinallyVector (vector);
654                         else
655                                 vector.CheckOutParameters (ec.CurrentBranching);
656
657                         vector.Returns = FlowReturns.ALWAYS;
658                         vector.Breaks = FlowReturns.ALWAYS;
659                         return true;
660                 }
661                 
662                 protected override bool DoEmit (EmitContext ec)
663                 {
664                         if (ec.InFinally){
665                                 Report.Error (157,loc,"Control can not leave the body of the finally block");
666                                 return false;
667                         }
668                         
669                         if (ec.ReturnType == null){
670                                 if (Expr != null){
671                                         Report.Error (127, loc, "Return with a value not allowed here");
672                                         return true;
673                                 }
674                         } else {
675                                 if (Expr == null){
676                                         Report.Error (126, loc, "An object of type `" +
677                                                       TypeManager.CSharpName (ec.ReturnType) + "' is " +
678                                                       "expected for the return statement");
679                                         return true;
680                                 }
681
682                                 if (Expr.Type != ec.ReturnType)
683                                         Expr = Expression.ConvertImplicitRequired (
684                                                 ec, Expr, ec.ReturnType, loc);
685
686                                 if (Expr == null)
687                                         return true;
688
689                                 Expr.Emit (ec);
690
691                                 if (ec.InTry || ec.InCatch)
692                                         ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
693                         }
694
695                         if (ec.InTry || ec.InCatch) {
696                                 if (!ec.HasReturnLabel) {
697                                         ec.ReturnLabel = ec.ig.DefineLabel ();
698                                         ec.HasReturnLabel = true;
699                                 }
700                                 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
701                         } else
702                                 ec.ig.Emit (OpCodes.Ret);
703
704                         return true; 
705                 }
706         }
707
708         public class Goto : Statement {
709                 string target;
710                 Block block;
711                 LabeledStatement label;
712                 
713                 public override bool Resolve (EmitContext ec)
714                 {
715                         label = block.LookupLabel (target);
716                         if (label == null){
717                                 Report.Error (
718                                         159, loc,
719                                         "No such label `" + target + "' in this scope");
720                                 return false;
721                         }
722
723                         // If this is a forward goto.
724                         if (!label.IsDefined)
725                                 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
726
727                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
728
729                         return true;
730                 }
731                 
732                 public Goto (Block parent_block, string label, Location l)
733                 {
734                         block = parent_block;
735                         loc = l;
736                         target = label;
737                 }
738
739                 public string Target {
740                         get {
741                                 return target;
742                         }
743                 }
744
745                 protected override bool DoEmit (EmitContext ec)
746                 {
747                         Label l = label.LabelTarget (ec);
748                         ec.ig.Emit (OpCodes.Br, l);
749                         
750                         return false;
751                 }
752         }
753
754         public class LabeledStatement : Statement {
755                 public readonly Location Location;
756                 string label_name;
757                 bool defined;
758                 bool referenced;
759                 Label label;
760
761                 ArrayList vectors;
762                 
763                 public LabeledStatement (string label_name, Location l)
764                 {
765                         this.label_name = label_name;
766                         this.Location = l;
767                 }
768
769                 public Label LabelTarget (EmitContext ec)
770                 {
771                         if (defined)
772                                 return label;
773                         label = ec.ig.DefineLabel ();
774                         defined = true;
775
776                         return label;
777                 }
778
779                 public bool IsDefined {
780                         get {
781                                 return defined;
782                         }
783                 }
784
785                 public bool HasBeenReferenced {
786                         get {
787                                 return referenced;
788                         }
789                 }
790
791                 public void AddUsageVector (FlowBranching.UsageVector vector)
792                 {
793                         if (vectors == null)
794                                 vectors = new ArrayList ();
795
796                         vectors.Add (vector.Clone ());
797                 }
798
799                 public override bool Resolve (EmitContext ec)
800                 {
801                         if (vectors != null)
802                                 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
803                         else {
804                                 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.NEVER;
805                                 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.NEVER;
806                         }
807
808                         referenced = true;
809
810                         return true;
811                 }
812
813                 protected override bool DoEmit (EmitContext ec)
814                 {
815                         LabelTarget (ec);
816                         ec.ig.MarkLabel (label);
817
818                         return false;
819                 }
820         }
821         
822
823         /// <summary>
824         ///   `goto default' statement
825         /// </summary>
826         public class GotoDefault : Statement {
827                 
828                 public GotoDefault (Location l)
829                 {
830                         loc = l;
831                 }
832
833                 public override bool Resolve (EmitContext ec)
834                 {
835                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
836                         return true;
837                 }
838
839                 protected override bool DoEmit (EmitContext ec)
840                 {
841                         if (ec.Switch == null){
842                                 Report.Error (153, loc, "goto default is only valid in a switch statement");
843                                 return false;
844                         }
845
846                         if (!ec.Switch.GotDefault){
847                                 Report.Error (159, loc, "No default target on switch statement");
848                                 return false;
849                         }
850                         ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
851                         return false;
852                 }
853         }
854
855         /// <summary>
856         ///   `goto case' statement
857         /// </summary>
858         public class GotoCase : Statement {
859                 Expression expr;
860                 Label label;
861                 
862                 public GotoCase (Expression e, Location l)
863                 {
864                         expr = e;
865                         loc = l;
866                 }
867
868                 public override bool Resolve (EmitContext ec)
869                 {
870                         if (ec.Switch == null){
871                                 Report.Error (153, loc, "goto case is only valid in a switch statement");
872                                 return false;
873                         }
874
875                         expr = expr.Resolve (ec);
876                         if (expr == null)
877                                 return false;
878
879                         if (!(expr is Constant)){
880                                 Report.Error (159, loc, "Target expression for goto case is not constant");
881                                 return false;
882                         }
883
884                         object val = Expression.ConvertIntLiteral (
885                                 (Constant) expr, ec.Switch.SwitchType, loc);
886
887                         if (val == null)
888                                 return false;
889                                         
890                         SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
891
892                         if (sl == null){
893                                 Report.Error (
894                                         159, loc,
895                                         "No such label 'case " + val + "': for the goto case");
896                         }
897
898                         label = sl.ILLabelCode;
899
900                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
901                         return true;
902                 }
903
904                 protected override bool DoEmit (EmitContext ec)
905                 {
906                         ec.ig.Emit (OpCodes.Br, label);
907                         return true;
908                 }
909         }
910         
911         public class Throw : Statement {
912                 Expression expr;
913                 
914                 public Throw (Expression expr, Location l)
915                 {
916                         this.expr = expr;
917                         loc = l;
918                 }
919
920                 public override bool Resolve (EmitContext ec)
921                 {
922                         if (expr != null){
923                                 expr = expr.Resolve (ec);
924                                 if (expr == null)
925                                         return false;
926
927                                 ExprClass eclass = expr.eclass;
928
929                                 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
930                                       eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
931                                         expr.Error118 ("value, variable, property or indexer access ");
932                                         return false;
933                                 }
934
935                                 Type t = expr.Type;
936                                 
937                                 if ((t != TypeManager.exception_type) &&
938                                     !t.IsSubclassOf (TypeManager.exception_type) &&
939                                     !(expr is NullLiteral)) {
940                                         Report.Error (155, loc,
941                                                       "The type caught or thrown must be derived " +
942                                                       "from System.Exception");
943                                         return false;
944                                 }
945                         }
946
947                         ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
948                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
949                         return true;
950                 }
951                         
952                 protected override bool DoEmit (EmitContext ec)
953                 {
954                         if (expr == null){
955                                 if (ec.InCatch)
956                                         ec.ig.Emit (OpCodes.Rethrow);
957                                 else {
958                                         Report.Error (
959                                                 156, loc,
960                                                 "A throw statement with no argument is only " +
961                                                 "allowed in a catch clause");
962                                 }
963                                 return false;
964                         }
965
966                         expr.Emit (ec);
967
968                         ec.ig.Emit (OpCodes.Throw);
969
970                         return true;
971                 }
972         }
973
974         public class Break : Statement {
975                 
976                 public Break (Location l)
977                 {
978                         loc = l;
979                 }
980
981                 public override bool Resolve (EmitContext ec)
982                 {
983                         ec.CurrentBranching.MayLeaveLoop = true;
984                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
985                         return true;
986                 }
987
988                 protected override bool DoEmit (EmitContext ec)
989                 {
990                         ILGenerator ig = ec.ig;
991
992                         if (ec.InLoop == false && ec.Switch == null){
993                                 Report.Error (139, loc, "No enclosing loop or switch to continue to");
994                                 return false;
995                         }
996
997                         if (ec.InTry || ec.InCatch)
998                                 ig.Emit (OpCodes.Leave, ec.LoopEnd);
999                         else
1000                                 ig.Emit (OpCodes.Br, ec.LoopEnd);
1001
1002                         return false;
1003                 }
1004         }
1005         
1006         public enum ExitType {
1007                 DO, 
1008                 FOR, 
1009                 WHILE,
1010                 SELECT,
1011                 SUB,
1012                 FUNCTION,
1013                 PROPERTY,
1014                 TRY                     
1015         };
1016         
1017         public class Exit : Statement {
1018                 public readonly ExitType type;
1019                 public Exit (ExitType t, Location l)
1020                 {
1021                         loc = l;
1022                         type = t;
1023                 }
1024
1025                 public override bool Resolve (EmitContext ec)
1026                 {
1027                         ec.CurrentBranching.MayLeaveLoop = true;
1028                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1029                         return true;
1030                 }
1031
1032                 protected override bool DoEmit (EmitContext ec)
1033                 {
1034                         ILGenerator ig = ec.ig;
1035
1036                         if (ec.InLoop == false && ec.Switch == null){
1037                                 Report.Error (139, loc, "No enclosing loop or switch to continue to");
1038                                 return false;
1039                         }
1040
1041                         if (ec.InTry || ec.InCatch)
1042                                 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1043                         else
1044                                 ig.Emit (OpCodes.Br, ec.LoopEnd);
1045
1046                         return false;
1047                 }
1048         }       
1049
1050         public class Continue : Statement {
1051                 
1052                 public Continue (Location l)
1053                 {
1054                         loc = l;
1055                 }
1056
1057                 public override bool Resolve (EmitContext ec)
1058                 {
1059                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1060                         return true;
1061                 }
1062
1063                 protected override bool DoEmit (EmitContext ec)
1064                 {
1065                         Label begin = ec.LoopBegin;
1066                         
1067                         if (!ec.InLoop){
1068                                 Report.Error (139, loc, "No enclosing loop to continue to");
1069                                 return false;
1070                         } 
1071
1072                         //
1073                         // UGH: Non trivial.  This Br might cross a try/catch boundary
1074                         // How can we tell?
1075                         //
1076                         // while () {
1077                         //   try { ... } catch { continue; }
1078                         // }
1079                         //
1080                         // From:
1081                         // try {} catch { while () { continue; }}
1082                         //
1083                         if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
1084                                 ec.ig.Emit (OpCodes.Leave, begin);
1085                         else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
1086                                 throw new Exception ("Should never happen");
1087                         else
1088                                 ec.ig.Emit (OpCodes.Br, begin);
1089                         return false;
1090                 }
1091         }
1092
1093         // <summary>
1094         //   This is used in the control flow analysis code to specify whether the
1095         //   current code block may return to its enclosing block before reaching
1096         //   its end.
1097         // </summary>
1098         public enum FlowReturns {
1099                 // It can never return.
1100                 NEVER,
1101
1102                 // This means that the block contains a conditional return statement
1103                 // somewhere.
1104                 SOMETIMES,
1105
1106                 // The code always returns, ie. there's an unconditional return / break
1107                 // statement in it.
1108                 ALWAYS,
1109
1110                 // The code always throws an exception.
1111                 EXCEPTION,
1112
1113                 // The current code block is unreachable.  This happens if it's immediately
1114                 // following a FlowReturns.ALWAYS block.
1115                 UNREACHABLE
1116         }
1117
1118         // <summary>
1119         //   This is a special bit vector which can inherit from another bit vector doing a
1120         //   copy-on-write strategy.  The inherited vector may have a smaller size than the
1121         //   current one.
1122         // </summary>
1123         public class MyBitVector {
1124                 public readonly int Count;
1125                 public readonly MyBitVector InheritsFrom;
1126
1127                 bool is_dirty;
1128                 BitArray vector;
1129
1130                 public MyBitVector (int Count)
1131                         : this (null, Count)
1132                 { }
1133
1134                 public MyBitVector (MyBitVector InheritsFrom, int Count)
1135                 {
1136                         this.InheritsFrom = InheritsFrom;
1137                         this.Count = Count;
1138                 }
1139
1140                 // <summary>
1141                 //   Checks whether this bit vector has been modified.  After setting this to true,
1142                 //   we won't use the inherited vector anymore, but our own copy of it.
1143                 // </summary>
1144                 public bool IsDirty {
1145                         get {
1146                                 return is_dirty;
1147                         }
1148
1149                         set {
1150                                 if (!is_dirty)
1151                                         initialize_vector ();
1152                         }
1153                 }
1154
1155                 // <summary>
1156                 //   Get/set bit `index' in the bit vector.
1157                 // </summary>
1158                 public bool this [int index]
1159                 {
1160                         get {
1161                                 if (index > Count)
1162                                         throw new ArgumentOutOfRangeException ();
1163
1164                                 // We're doing a "copy-on-write" strategy here; as long
1165                                 // as nobody writes to the array, we can use our parent's
1166                                 // copy instead of duplicating the vector.
1167
1168                                 if (vector != null)
1169                                         return vector [index];
1170                                 else if (InheritsFrom != null) {
1171                                         BitArray inherited = InheritsFrom.Vector;
1172
1173                                         if (index < inherited.Count)
1174                                                 return inherited [index];
1175                                         else
1176                                                 return false;
1177                                 } else
1178                                         return false;
1179                         }
1180
1181                         set {
1182                                 if (index > Count)
1183                                         throw new ArgumentOutOfRangeException ();
1184
1185                                 // Only copy the vector if we're actually modifying it.
1186
1187                                 if (this [index] != value) {
1188                                         initialize_vector ();
1189
1190                                         vector [index] = value;
1191                                 }
1192                         }
1193                 }
1194
1195                 // <summary>
1196                 //   If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1197                 //   copy of the bit vector.
1198                 // </summary>
1199                 public static explicit operator BitArray (MyBitVector vector)
1200                 {
1201                         vector.initialize_vector ();
1202                         return vector.Vector;
1203                 }
1204
1205                 // <summary>
1206                 //   Performs an `or' operation on the bit vector.  The `new_vector' may have a
1207                 //   different size than the current one.
1208                 // </summary>
1209                 public void Or (MyBitVector new_vector)
1210                 {
1211                         BitArray new_array = new_vector.Vector;
1212
1213                         initialize_vector ();
1214
1215                         int upper;
1216                         if (vector.Count < new_array.Count)
1217                                 upper = vector.Count;
1218                         else
1219                                 upper = new_array.Count;
1220
1221                         for (int i = 0; i < upper; i++)
1222                                 vector [i] = vector [i] | new_array [i];
1223                 }
1224
1225                 // <summary>
1226                 //   Perfonrms an `and' operation on the bit vector.  The `new_vector' may have
1227                 //   a different size than the current one.
1228                 // </summary>
1229                 public void And (MyBitVector new_vector)
1230                 {
1231                         BitArray new_array = new_vector.Vector;
1232
1233                         initialize_vector ();
1234
1235                         int lower, upper;
1236                         if (vector.Count < new_array.Count)
1237                                 lower = upper = vector.Count;
1238                         else {
1239                                 lower = new_array.Count;
1240                                 upper = vector.Count;
1241                         }
1242
1243                         for (int i = 0; i < lower; i++)
1244                                 vector [i] = vector [i] & new_array [i];
1245
1246                         for (int i = lower; i < upper; i++)
1247                                 vector [i] = false;
1248                 }
1249
1250                 // <summary>
1251                 //   This does a deep copy of the bit vector.
1252                 // </summary>
1253                 public MyBitVector Clone ()
1254                 {
1255                         MyBitVector retval = new MyBitVector (Count);
1256
1257                         retval.Vector = Vector;
1258
1259                         return retval;
1260                 }
1261
1262                 BitArray Vector {
1263                         get {
1264                                 if (vector != null)
1265                                         return vector;
1266                                 else if (!is_dirty && (InheritsFrom != null))
1267                                         return InheritsFrom.Vector;
1268
1269                                 initialize_vector ();
1270
1271                                 return vector;
1272                         }
1273
1274                         set {
1275                                 initialize_vector ();
1276
1277                                 for (int i = 0; i < Math.Min (vector.Count, value.Count); i++)
1278                                         vector [i] = value [i];
1279                         }
1280                 }
1281
1282                 void initialize_vector ()
1283                 {
1284                         if (vector != null)
1285                                 return;
1286
1287                         vector = new BitArray (Count, false);
1288                         if (InheritsFrom != null)
1289                                 Vector = InheritsFrom.Vector;
1290
1291                         is_dirty = true;
1292                 }
1293
1294                 public override string ToString ()
1295                 {
1296                         StringBuilder sb = new StringBuilder ("MyBitVector (");
1297
1298                         BitArray vector = Vector;
1299                         sb.Append (Count);
1300                         sb.Append (",");
1301                         if (!IsDirty)
1302                                 sb.Append ("INHERITED - ");
1303                         for (int i = 0; i < vector.Count; i++) {
1304                                 if (i > 0)
1305                                         sb.Append (",");
1306                                 sb.Append (vector [i]);
1307                         }
1308                         
1309                         sb.Append (")");
1310                         return sb.ToString ();
1311                 }
1312         }
1313
1314         // <summary>
1315         //   The type of a FlowBranching.
1316         // </summary>
1317         public enum FlowBranchingType {
1318                 // Normal (conditional or toplevel) block.
1319                 BLOCK,
1320
1321                 // A loop block.
1322                 LOOP_BLOCK,
1323
1324                 // Try/Catch block.
1325                 EXCEPTION,
1326
1327                 // Switch block.
1328                 SWITCH,
1329
1330                 // Switch section.
1331                 SWITCH_SECTION
1332         }
1333
1334         // <summary>
1335         //   A new instance of this class is created every time a new block is resolved
1336         //   and if there's branching in the block's control flow.
1337         // </summary>
1338         public class FlowBranching {
1339                 // <summary>
1340                 //   The type of this flow branching.
1341                 // </summary>
1342                 public readonly FlowBranchingType Type;
1343
1344                 // <summary>
1345                 //   The block this branching is contained in.  This may be null if it's not
1346                 //   a top-level block and it doesn't declare any local variables.
1347                 // </summary>
1348                 public readonly Block Block;
1349
1350                 // <summary>
1351                 //   The parent of this branching or null if this is the top-block.
1352                 // </summary>
1353                 public readonly FlowBranching Parent;
1354
1355                 // <summary>
1356                 //   Start-Location of this flow branching.
1357                 // </summary>
1358                 public readonly Location Location;
1359
1360                 // <summary>
1361                 //   A list of UsageVectors.  A new vector is added each time control flow may
1362                 //   take a different path.
1363                 // </summary>
1364                 public ArrayList Siblings;
1365
1366                 // <summary>
1367                 //   If this is an infinite loop.
1368                 // </summary>
1369                 public bool Infinite;
1370
1371                 // <summary>
1372                 //   If we may leave the current loop.
1373                 // </summary>
1374                 public bool MayLeaveLoop;
1375
1376                 //
1377                 // Private
1378                 //
1379                 InternalParameters param_info;
1380                 int[] param_map;
1381                 MyStructInfo[] struct_params;
1382                 int num_params;
1383                 ArrayList finally_vectors;
1384
1385                 static int next_id = 0;
1386                 int id;
1387
1388                 // <summary>
1389                 //   Performs an `And' operation on the FlowReturns status
1390                 //   (for instance, a block only returns ALWAYS if all its siblings
1391                 //   always return).
1392                 // </summary>
1393                 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1394                 {
1395                         if (b == FlowReturns.UNREACHABLE)
1396                                 return a;
1397
1398                         switch (a) {
1399                         case FlowReturns.NEVER:
1400                                 if (b == FlowReturns.NEVER)
1401                                         return FlowReturns.NEVER;
1402                                 else
1403                                         return FlowReturns.SOMETIMES;
1404
1405                         case FlowReturns.SOMETIMES:
1406                                 return FlowReturns.SOMETIMES;
1407
1408                         case FlowReturns.ALWAYS:
1409                                 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1410                                         return FlowReturns.ALWAYS;
1411                                 else
1412                                         return FlowReturns.SOMETIMES;
1413
1414                         case FlowReturns.EXCEPTION:
1415                                 if (b == FlowReturns.EXCEPTION)
1416                                         return FlowReturns.EXCEPTION;
1417                                 else if (b == FlowReturns.ALWAYS)
1418                                         return FlowReturns.ALWAYS;
1419                                 else
1420                                         return FlowReturns.SOMETIMES;
1421                         }
1422
1423                         return b;
1424                 }
1425
1426                 // <summary>
1427                 //   The vector contains a BitArray with information about which local variables
1428                 //   and parameters are already initialized at the current code position.
1429                 // </summary>
1430                 public class UsageVector {
1431                         // <summary>
1432                         //   If this is true, then the usage vector has been modified and must be
1433                         //   merged when we're done with this branching.
1434                         // </summary>
1435                         public bool IsDirty;
1436
1437                         // <summary>
1438                         //   The number of parameters in this block.
1439                         // </summary>
1440                         public readonly int CountParameters;
1441
1442                         // <summary>
1443                         //   The number of locals in this block.
1444                         // </summary>
1445                         public readonly int CountLocals;
1446
1447                         // <summary>
1448                         //   If not null, then we inherit our state from this vector and do a
1449                         //   copy-on-write.  If null, then we're the first sibling in a top-level
1450                         //   block and inherit from the empty vector.
1451                         // </summary>
1452                         public readonly UsageVector InheritsFrom;
1453
1454                         //
1455                         // Private.
1456                         //
1457                         MyBitVector locals, parameters;
1458                         FlowReturns real_returns, real_breaks;
1459                         bool is_finally;
1460
1461                         static int next_id = 0;
1462                         int id;
1463
1464                         //
1465                         // Normally, you should not use any of these constructors.
1466                         //
1467                         public UsageVector (UsageVector parent, int num_params, int num_locals)
1468                         {
1469                                 this.InheritsFrom = parent;
1470                                 this.CountParameters = num_params;
1471                                 this.CountLocals = num_locals;
1472                                 this.real_returns = FlowReturns.NEVER;
1473                                 this.real_breaks = FlowReturns.NEVER;
1474
1475                                 if (parent != null) {
1476                                         locals = new MyBitVector (parent.locals, CountLocals);
1477                                         if (num_params > 0)
1478                                                 parameters = new MyBitVector (parent.parameters, num_params);
1479                                         real_returns = parent.Returns;
1480                                         real_breaks = parent.Breaks;
1481                                 } else {
1482                                         locals = new MyBitVector (null, CountLocals);
1483                                         if (num_params > 0)
1484                                                 parameters = new MyBitVector (null, num_params);
1485                                 }
1486
1487                                 id = ++next_id;
1488                         }
1489
1490                         public UsageVector (UsageVector parent)
1491                                 : this (parent, parent.CountParameters, parent.CountLocals)
1492                         { }
1493
1494                         // <summary>
1495                         //   This does a deep copy of the usage vector.
1496                         // </summary>
1497                         public UsageVector Clone ()
1498                         {
1499                                 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1500
1501                                 retval.locals = locals.Clone ();
1502                                 if (parameters != null)
1503                                         retval.parameters = parameters.Clone ();
1504                                 retval.real_returns = real_returns;
1505                                 retval.real_breaks = real_breaks;
1506
1507                                 return retval;
1508                         }
1509
1510                         // 
1511                         // State of parameter `number'.
1512                         //
1513                         public bool this [int number]
1514                         {
1515                                 get {
1516                                         if (number == -1)
1517                                                 return true;
1518                                         else if (number == 0)
1519                                                 throw new ArgumentException ();
1520
1521                                         return parameters [number - 1];
1522                                 }
1523
1524                                 set {
1525                                         if (number == -1)
1526                                                 return;
1527                                         else if (number == 0)
1528                                                 throw new ArgumentException ();
1529
1530                                         parameters [number - 1] = value;
1531                                 }
1532                         }
1533
1534                         //
1535                         // State of the local variable `vi'.
1536                         // If the local variable is a struct, use a non-zero `field_idx'
1537                         // to check an individual field in it.
1538                         //
1539                         public bool this [VariableInfo vi, int field_idx]
1540                         {
1541                                 get {
1542                                         if (vi.Number == -1)
1543                                                 return true;
1544                                         else if (vi.Number == 0)
1545                                                 throw new ArgumentException ();
1546
1547                                         return locals [vi.Number + field_idx - 1];
1548                                 }
1549
1550                                 set {
1551                                         if (vi.Number == -1)
1552                                                 return;
1553                                         else if (vi.Number == 0)
1554                                                 throw new ArgumentException ();
1555
1556                                         locals [vi.Number + field_idx - 1] = value;
1557                                 }
1558                         }
1559
1560                         // <summary>
1561                         //   Specifies when the current block returns.
1562                         //   If this is FlowReturns.UNREACHABLE, then control can never reach the
1563                         //   end of the method (so that we don't need to emit a return statement).
1564                         //   The same applies for FlowReturns.EXCEPTION, but in this case the return
1565                         //   value will never be used.
1566                         // </summary>
1567                         public FlowReturns Returns {
1568                                 get {
1569                                         return real_returns;
1570                                 }
1571
1572                                 set {
1573                                         real_returns = value;
1574                                 }
1575                         }
1576
1577                         // <summary>
1578                         //   Specifies whether control may return to our containing block
1579                         //   before reaching the end of this block.  This happens if there
1580                         //   is a break/continue/goto/return in it.
1581                         //   This can also be used to find out whether the statement immediately
1582                         //   following the current block may be reached or not.
1583                         // </summary>
1584                         public FlowReturns Breaks {
1585                                 get {
1586                                         return real_breaks;
1587                                 }
1588
1589                                 set {
1590                                         real_breaks = value;
1591                                 }
1592                         }
1593
1594                         public bool AlwaysBreaks {
1595                                 get {
1596                                         return (Breaks == FlowReturns.ALWAYS) ||
1597                                                 (Breaks == FlowReturns.EXCEPTION) ||
1598                                                 (Breaks == FlowReturns.UNREACHABLE);
1599                                 }
1600                         }
1601
1602                         public bool MayBreak {
1603                                 get {
1604                                         return Breaks != FlowReturns.NEVER;
1605                                 }
1606                         }
1607
1608                         public bool AlwaysReturns {
1609                                 get {
1610                                         return (Returns == FlowReturns.ALWAYS) ||
1611                                                 (Returns == FlowReturns.EXCEPTION);
1612                                 }
1613                         }
1614
1615                         public bool MayReturn {
1616                                 get {
1617                                         return (Returns == FlowReturns.SOMETIMES) ||
1618                                                 (Returns == FlowReturns.ALWAYS);
1619                                 }
1620                         }
1621
1622                         // <summary>
1623                         //   Merge a child branching.
1624                         // </summary>
1625                         public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1626                         {
1627                                 MyBitVector new_locals = null;
1628                                 MyBitVector new_params = null;
1629
1630                                 FlowReturns new_returns = FlowReturns.NEVER;
1631                                 FlowReturns new_breaks = FlowReturns.NEVER;
1632                                 bool new_returns_set = false, new_breaks_set = false;
1633
1634                                 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1635                                               this, children.Count);
1636
1637                                 foreach (UsageVector child in children) {
1638                                         Report.Debug (2, "  MERGING CHILD", child, child.is_finally);
1639                                         
1640                                         if (!child.is_finally) {
1641                                                 if (child.Breaks != FlowReturns.UNREACHABLE) {
1642                                                         // If Returns is already set, perform an
1643                                                         // `And' operation on it, otherwise just set just.
1644                                                         if (!new_returns_set) {
1645                                                                 new_returns = child.Returns;
1646                                                                 new_returns_set = true;
1647                                                         } else
1648                                                                 new_returns = AndFlowReturns (
1649                                                                         new_returns, child.Returns);
1650                                                 }
1651
1652                                                 // If Breaks is already set, perform an
1653                                                 // `And' operation on it, otherwise just set just.
1654                                                 if (!new_breaks_set) {
1655                                                         new_breaks = child.Breaks;
1656                                                         new_breaks_set = true;
1657                                                 } else
1658                                                         new_breaks = AndFlowReturns (
1659                                                                 new_breaks, child.Breaks);
1660                                         }
1661
1662                                         // Ignore unreachable children.
1663                                         if (child.Returns == FlowReturns.UNREACHABLE)
1664                                                 continue;
1665
1666                                         // A local variable is initialized after a flow branching if it
1667                                         // has been initialized in all its branches which do neither
1668                                         // always return or always throw an exception.
1669                                         //
1670                                         // If a branch may return, but does not always return, then we
1671                                         // can treat it like a never-returning branch here: control will
1672                                         // only reach the code position after the branching if we did not
1673                                         // return here.
1674                                         //
1675                                         // It's important to distinguish between always and sometimes
1676                                         // returning branches here:
1677                                         //
1678                                         //    1   int a;
1679                                         //    2   if (something) {
1680                                         //    3      return;
1681                                         //    4      a = 5;
1682                                         //    5   }
1683                                         //    6   Console.WriteLine (a);
1684                                         //
1685                                         // The if block in lines 3-4 always returns, so we must not look
1686                                         // at the initialization of `a' in line 4 - thus it'll still be
1687                                         // uninitialized in line 6.
1688                                         //
1689                                         // On the other hand, the following is allowed:
1690                                         //
1691                                         //    1   int a;
1692                                         //    2   if (something)
1693                                         //    3      a = 5;
1694                                         //    4   else
1695                                         //    5      return;
1696                                         //    6   Console.WriteLine (a);
1697                                         //
1698                                         // Here, `a' is initialized in line 3 and we must not look at
1699                                         // line 5 since it always returns.
1700                                         // 
1701                                         if (child.is_finally) {
1702                                                 if (new_locals == null)
1703                                                         new_locals = locals.Clone ();
1704                                                 new_locals.Or (child.locals);
1705
1706                                                 if (parameters != null) {
1707                                                         if (new_params == null)
1708                                                                 new_params = parameters.Clone ();
1709                                                         new_params.Or (child.parameters);
1710                                                 }
1711
1712                                         } else {
1713                                                 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1714                                                         if (new_locals != null)
1715                                                                 new_locals.And (child.locals);
1716                                                         else {
1717                                                                 new_locals = locals.Clone ();
1718                                                                 new_locals.Or (child.locals);
1719                                                         }
1720                                                 } else if (children.Count == 1) {
1721                                                         new_locals = locals.Clone ();
1722                                                         new_locals.Or (child.locals);
1723                                                 }
1724
1725                                                 // An `out' parameter must be assigned in all branches which do
1726                                                 // not always throw an exception.
1727                                                 if (parameters != null) {
1728                                                         if (child.Breaks != FlowReturns.EXCEPTION) {
1729                                                                 if (new_params != null)
1730                                                                         new_params.And (child.parameters);
1731                                                                 else {
1732                                                                         new_params = parameters.Clone ();
1733                                                                         new_params.Or (child.parameters);
1734                                                                 }
1735                                                         } else if (children.Count == 1) {
1736                                                                 new_params = parameters.Clone ();
1737                                                                 new_params.Or (child.parameters);
1738                                                         }
1739                                                 }
1740                                         }
1741                                 }
1742
1743                                 Returns = new_returns;
1744                                 if ((branching.Type == FlowBranchingType.BLOCK) ||
1745                                     (branching.Type == FlowBranchingType.EXCEPTION) ||
1746                                     (new_breaks == FlowReturns.UNREACHABLE) ||
1747                                     (new_breaks == FlowReturns.EXCEPTION))
1748                                         Breaks = new_breaks;
1749                                 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
1750                                         Breaks = new_returns;
1751                                 else if (branching.Type == FlowBranchingType.SWITCH){
1752                                         if (new_breaks == FlowReturns.ALWAYS)
1753                                                 Breaks = FlowReturns.ALWAYS;
1754                                 }
1755
1756                                 //
1757                                 // We've now either reached the point after the branching or we will
1758                                 // never get there since we always return or always throw an exception.
1759                                 //
1760                                 // If we can reach the point after the branching, mark all locals and
1761                                 // parameters as initialized which have been initialized in all branches
1762                                 // we need to look at (see above).
1763                                 //
1764
1765                                 if (((new_breaks != FlowReturns.ALWAYS) &&
1766                                      (new_breaks != FlowReturns.EXCEPTION) &&
1767                                      (new_breaks != FlowReturns.UNREACHABLE)) ||
1768                                     (children.Count == 1)) {
1769                                         if (new_locals != null)
1770                                                 locals.Or (new_locals);
1771
1772                                         if (new_params != null)
1773                                                 parameters.Or (new_params);
1774                                 }
1775
1776                                 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
1777                                               new_params, new_locals, new_returns, new_breaks,
1778                                               branching.Infinite, branching.MayLeaveLoop, this);
1779
1780                                 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
1781                                         if ((new_breaks != FlowReturns.ALWAYS) &&
1782                                             (new_breaks != FlowReturns.EXCEPTION) &&
1783                                             (new_breaks != FlowReturns.UNREACHABLE))
1784                                                 Report.Error (163, branching.Location,
1785                                                               "Control cannot fall through from one " +
1786                                                               "case label to another");
1787                                 }
1788
1789                                 if (branching.Infinite && !branching.MayLeaveLoop) {
1790                                         Report.Debug (1, "INFINITE", new_returns, new_breaks,
1791                                                       Returns, Breaks, this);
1792
1793                                         // We're actually infinite.
1794                                         if (new_returns == FlowReturns.NEVER) {
1795                                                 Breaks = FlowReturns.UNREACHABLE;
1796                                                 return FlowReturns.UNREACHABLE;
1797                                         }
1798
1799                                         // If we're an infinite loop and do not break, the code after
1800                                         // the loop can never be reached.  However, if we may return
1801                                         // from the loop, then we do always return (or stay in the loop
1802                                         // forever).
1803                                         if ((new_returns == FlowReturns.SOMETIMES) ||
1804                                             (new_returns == FlowReturns.ALWAYS)) {
1805                                                 Returns = FlowReturns.ALWAYS;
1806                                                 return FlowReturns.ALWAYS;
1807                                         }
1808                                 }
1809
1810                                 return new_returns;
1811                         }
1812
1813                         // <summary>
1814                         //   Tells control flow analysis that the current code position may be reached with
1815                         //   a forward jump from any of the origins listed in `origin_vectors' which is a
1816                         //   list of UsageVectors.
1817                         //
1818                         //   This is used when resolving forward gotos - in the following example, the
1819                         //   variable `a' is uninitialized in line 8 becase this line may be reached via
1820                         //   the goto in line 4:
1821                         //
1822                         //      1     int a;
1823                         //
1824                         //      3     if (something)
1825                         //      4        goto World;
1826                         //
1827                         //      6     a = 5;
1828                         //
1829                         //      7  World:
1830                         //      8     Console.WriteLine (a);
1831                         //
1832                         // </summary>
1833                         public void MergeJumpOrigins (ICollection origin_vectors)
1834                         {
1835                                 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1836
1837                                 real_breaks = FlowReturns.NEVER;
1838                                 real_returns = FlowReturns.NEVER;
1839
1840                                 foreach (UsageVector vector in origin_vectors) {
1841                                         Report.Debug (1, "  MERGING JUMP ORIGIN", vector);
1842
1843                                         locals.And (vector.locals);
1844                                         if (parameters != null)
1845                                                 parameters.And (vector.parameters);
1846                                         Breaks = AndFlowReturns (Breaks, vector.Breaks);
1847                                         Returns = AndFlowReturns (Returns, vector.Returns);
1848                                 }
1849
1850                                 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1851                         }
1852
1853                         // <summary>
1854                         //   This is used at the beginning of a finally block if there were
1855                         //   any return statements in the try block or one of the catch blocks.
1856                         // </summary>
1857                         public void MergeFinallyOrigins (ICollection finally_vectors)
1858                         {
1859                                 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1860
1861                                 real_breaks = FlowReturns.NEVER;
1862
1863                                 foreach (UsageVector vector in finally_vectors) {
1864                                         Report.Debug (1, "  MERGING FINALLY ORIGIN", vector);
1865
1866                                         if (parameters != null)
1867                                                 parameters.And (vector.parameters);
1868                                         Breaks = AndFlowReturns (Breaks, vector.Breaks);
1869                                 }
1870
1871                                 is_finally = true;
1872
1873                                 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1874                         }
1875
1876                         public void CheckOutParameters (FlowBranching branching)
1877                         {
1878                                 if (parameters != null)
1879                                         branching.CheckOutParameters (parameters, branching.Location);
1880                         }
1881
1882                         // <summary>
1883                         //   Performs an `or' operation on the locals and the parameters.
1884                         // </summary>
1885                         public void Or (UsageVector new_vector)
1886                         {
1887                                 locals.Or (new_vector.locals);
1888                                 if (parameters != null)
1889                                         parameters.Or (new_vector.parameters);
1890                         }
1891
1892                         // <summary>
1893                         //   Performs an `and' operation on the locals.
1894                         // </summary>
1895                         public void AndLocals (UsageVector new_vector)
1896                         {
1897                                 locals.And (new_vector.locals);
1898                         }
1899
1900                         // <summary>
1901                         //   Returns a deep copy of the parameters.
1902                         // </summary>
1903                         public MyBitVector Parameters {
1904                                 get {
1905                                         if (parameters != null)
1906                                                 return parameters.Clone ();
1907                                         else
1908                                                 return null;
1909                                 }
1910                         }
1911
1912                         // <summary>
1913                         //   Returns a deep copy of the locals.
1914                         // </summary>
1915                         public MyBitVector Locals {
1916                                 get {
1917                                         return locals.Clone ();
1918                                 }
1919                         }
1920
1921                         //
1922                         // Debugging stuff.
1923                         //
1924
1925                         public override string ToString ()
1926                         {
1927                                 StringBuilder sb = new StringBuilder ();
1928
1929                                 sb.Append ("Vector (");
1930                                 sb.Append (id);
1931                                 sb.Append (",");
1932                                 sb.Append (Returns);
1933                                 sb.Append (",");
1934                                 sb.Append (Breaks);
1935                                 if (parameters != null) {
1936                                         sb.Append (" - ");
1937                                         sb.Append (parameters);
1938                                 }
1939                                 sb.Append (" - ");
1940                                 sb.Append (locals);
1941                                 sb.Append (")");
1942
1943                                 return sb.ToString ();
1944                         }
1945                 }
1946
1947                 FlowBranching (FlowBranchingType type, Location loc)
1948                 {
1949                         this.Siblings = new ArrayList ();
1950                         this.Block = null;
1951                         this.Location = loc;
1952                         this.Type = type;
1953                         id = ++next_id;
1954                 }
1955
1956                 // <summary>
1957                 //   Creates a new flow branching for `block'.
1958                 //   This is used from Block.Resolve to create the top-level branching of
1959                 //   the block.
1960                 // </summary>
1961                 public FlowBranching (Block block, InternalParameters ip, Location loc)
1962                         : this (FlowBranchingType.BLOCK, loc)
1963                 {
1964                         Block = block;
1965                         Parent = null;
1966
1967                         int count = (ip != null) ? ip.Count : 0;
1968
1969                         param_info = ip;
1970                         param_map = new int [count];
1971                         struct_params = new MyStructInfo [count];
1972                         num_params = 0;
1973
1974                         for (int i = 0; i < count; i++) {
1975                                 Parameter.Modifier mod = param_info.ParameterModifier (i);
1976
1977                                 if ((mod & Parameter.Modifier.OUT) == 0)
1978                                         continue;
1979
1980                                 param_map [i] = ++num_params;
1981
1982                                 Type param_type = param_info.ParameterType (i);
1983
1984                                 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
1985                                 if (struct_params [i] != null)
1986                                         num_params += struct_params [i].Count;
1987                         }
1988
1989                         Siblings = new ArrayList ();
1990                         Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1991                 }
1992
1993                 // <summary>
1994                 //   Creates a new flow branching which is contained in `parent'.
1995                 //   You should only pass non-null for the `block' argument if this block
1996                 //   introduces any new variables - in this case, we need to create a new
1997                 //   usage vector with a different size than our parent's one.
1998                 // </summary>
1999                 public FlowBranching (FlowBranching parent, FlowBranchingType type,
2000                                       Block block, Location loc)
2001                         : this (type, loc)
2002                 {
2003                         Parent = parent;
2004                         Block = block;
2005
2006                         if (parent != null) {
2007                                 param_info = parent.param_info;
2008                                 param_map = parent.param_map;
2009                                 struct_params = parent.struct_params;
2010                                 num_params = parent.num_params;
2011                         }
2012
2013                         UsageVector vector;
2014                         if (Block != null)
2015                                 vector = new UsageVector (parent.CurrentUsageVector, num_params,
2016                                                           Block.CountVariables);
2017                         else
2018                                 vector = new UsageVector (Parent.CurrentUsageVector);
2019
2020                         Siblings.Add (vector);
2021
2022                         switch (Type) {
2023                         case FlowBranchingType.EXCEPTION:
2024                                 finally_vectors = new ArrayList ();
2025                                 break;
2026
2027                         default:
2028                                 break;
2029                         }
2030                 }
2031
2032                 // <summary>
2033                 //   Returns the branching's current usage vector.
2034                 // </summary>
2035                 public UsageVector CurrentUsageVector
2036                 {
2037                         get {
2038                                 return (UsageVector) Siblings [Siblings.Count - 1];
2039                         }
2040                 }
2041
2042                 // <summary>
2043                 //   Creates a sibling of the current usage vector.
2044                 // </summary>
2045                 public void CreateSibling ()
2046                 {
2047                         Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
2048
2049                         Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
2050                 }
2051
2052                 // <summary>
2053                 //   Creates a sibling for a `finally' block.
2054                 // </summary>
2055                 public void CreateSiblingForFinally ()
2056                 {
2057                         if (Type != FlowBranchingType.EXCEPTION)
2058                                 throw new NotSupportedException ();
2059
2060                         CreateSibling ();
2061
2062                         CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
2063                 }
2064
2065                 // <summary>
2066                 //   Check whether all `out' parameters have been assigned.
2067                 // </summary>
2068                 public void CheckOutParameters (MyBitVector parameters, Location loc)
2069                 {
2070                         if (InTryBlock ())
2071                                 return;
2072
2073                         for (int i = 0; i < param_map.Length; i++) {
2074                                 int index = param_map [i];
2075
2076                                 if (index == 0)
2077                                         continue;
2078
2079                                 if (parameters [index - 1])
2080                                         continue;
2081
2082                                 // If it's a struct, we must ensure that all its fields have
2083                                 // been assigned.  If the struct has any non-public fields, this
2084                                 // can only be done by assigning the whole struct.
2085
2086                                 MyStructInfo struct_info = struct_params [index - 1];
2087                                 if ((struct_info == null) || struct_info.HasNonPublicFields) {
2088                                         Report.Error (
2089                                                 177, loc, "The out parameter `" +
2090                                                 param_info.ParameterName (i) + "' must be " +
2091                                                 "assigned before control leave the current method.");
2092                                         param_map [i] = 0;
2093                                         continue;
2094                                 }
2095
2096
2097                                 for (int j = 0; j < struct_info.Count; j++) {
2098                                         if (!parameters [index + j]) {
2099                                                 Report.Error (
2100                                                         177, loc, "The out parameter `" +
2101                                                         param_info.ParameterName (i) + "' must be " +
2102                                                         "assigned before control leave the current method.");
2103                                                 param_map [i] = 0;
2104                                                 break;
2105                                         }
2106                                 }
2107                         }
2108                 }
2109
2110                 // <summary>
2111                 //   Merge a child branching.
2112                 // </summary>
2113                 public FlowReturns MergeChild (FlowBranching child)
2114                 {
2115                         FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2116
2117                         if (child.Type != FlowBranchingType.LOOP_BLOCK)
2118                                 MayLeaveLoop |= child.MayLeaveLoop;
2119                         else
2120                                 MayLeaveLoop = false;
2121
2122                         return returns;
2123                 }
2124  
2125                 // <summary>
2126                 //   Does the toplevel merging.
2127                 // </summary>
2128                 public FlowReturns MergeTopBlock ()
2129                 {
2130                         if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2131                                 throw new NotSupportedException ();
2132
2133                         UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2134
2135                         Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2136
2137                         vector.MergeChildren (this, Siblings);
2138
2139                         Siblings.Clear ();
2140                         Siblings.Add (vector);
2141
2142                         Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2143
2144                         if (vector.Breaks != FlowReturns.EXCEPTION) {
2145                                 if (!vector.AlwaysBreaks)
2146                                         CheckOutParameters (CurrentUsageVector.Parameters, Location);
2147                                 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2148                         } else
2149                                 return FlowReturns.EXCEPTION;
2150                 }
2151
2152                 public bool InTryBlock ()
2153                 {
2154                         if (finally_vectors != null)
2155                                 return true;
2156                         else if (Parent != null)
2157                                 return Parent.InTryBlock ();
2158                         else
2159                                 return false;
2160                 }
2161
2162                 public void AddFinallyVector (UsageVector vector)
2163                 {
2164                         if (finally_vectors != null) {
2165                                 finally_vectors.Add (vector.Clone ());
2166                                 return;
2167                         }
2168
2169                         if (Parent != null)
2170                                 Parent.AddFinallyVector (vector);
2171                         else
2172                                 throw new NotSupportedException ();
2173                 }
2174
2175                 public bool IsVariableAssigned (VariableInfo vi)
2176                 {
2177                         if (CurrentUsageVector.AlwaysBreaks)
2178                                 return true;
2179                         else
2180                                 return CurrentUsageVector [vi, 0];
2181                 }
2182
2183                 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2184                 {
2185                         if (CurrentUsageVector.AlwaysBreaks)
2186                                 return true;
2187                         else
2188                                 return CurrentUsageVector [vi, field_idx];
2189                 }
2190
2191                 public void SetVariableAssigned (VariableInfo vi)
2192                 {
2193                         if (CurrentUsageVector.AlwaysBreaks)
2194                                 return;
2195
2196                         CurrentUsageVector [vi, 0] = true;
2197                 }
2198
2199                 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2200                 {
2201                         if (CurrentUsageVector.AlwaysBreaks)
2202                                 return;
2203
2204                         CurrentUsageVector [vi, field_idx] = true;
2205                 }
2206
2207                 public bool IsParameterAssigned (int number)
2208                 {
2209                         int index = param_map [number];
2210
2211                         if (index == 0)
2212                                 return true;
2213
2214                         if (CurrentUsageVector [index])
2215                                 return true;
2216
2217                         // Parameter is not assigned, so check whether it's a struct.
2218                         // If it's either not a struct or a struct which non-public
2219                         // fields, return false.
2220                         MyStructInfo struct_info = struct_params [number];
2221                         if ((struct_info == null) || struct_info.HasNonPublicFields)
2222                                 return false;
2223
2224                         // Ok, so each field must be assigned.
2225                         for (int i = 0; i < struct_info.Count; i++)
2226                                 if (!CurrentUsageVector [index + i])
2227                                         return false;
2228
2229                         return true;
2230                 }
2231
2232                 public bool IsParameterAssigned (int number, string field_name)
2233                 {
2234                         int index = param_map [number];
2235
2236                         if (index == 0)
2237                                 return true;
2238
2239                         MyStructInfo info = (MyStructInfo) struct_params [number];
2240                         if (info == null)
2241                                 return true;
2242
2243                         int field_idx = info [field_name];
2244
2245                         return CurrentUsageVector [index + field_idx];
2246                 }
2247
2248                 public void SetParameterAssigned (int number)
2249                 {
2250                         if (param_map [number] == 0)
2251                                 return;
2252
2253                         if (!CurrentUsageVector.AlwaysBreaks)
2254                                 CurrentUsageVector [param_map [number]] = true;
2255                 }
2256
2257                 public void SetParameterAssigned (int number, string field_name)
2258                 {
2259                         int index = param_map [number];
2260
2261                         if (index == 0)
2262                                 return;
2263
2264                         MyStructInfo info = (MyStructInfo) struct_params [number];
2265                         if (info == null)
2266                                 return;
2267
2268                         int field_idx = info [field_name];
2269
2270                         if (!CurrentUsageVector.AlwaysBreaks)
2271                                 CurrentUsageVector [index + field_idx] = true;
2272                 }
2273
2274                 public bool IsReachable ()
2275                 {
2276                         bool reachable;
2277
2278                         switch (Type) {
2279                         case FlowBranchingType.SWITCH_SECTION:
2280                                 // The code following a switch block is reachable unless the switch
2281                                 // block always returns.
2282                                 reachable = !CurrentUsageVector.AlwaysReturns;
2283                                 break;
2284
2285                         case FlowBranchingType.LOOP_BLOCK:
2286                                 // The code following a loop is reachable unless the loop always
2287                                 // returns or it's an infinite loop without any `break's in it.
2288                                 reachable = !CurrentUsageVector.AlwaysReturns &&
2289                                         (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2290                                 break;
2291
2292                         default:
2293                                 // The code following a block or exception is reachable unless the
2294                                 // block either always returns or always breaks.
2295                                 reachable = !CurrentUsageVector.AlwaysBreaks &&
2296                                         !CurrentUsageVector.AlwaysReturns;
2297                                 break;
2298                         }
2299
2300                         Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2301                                       CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2302
2303                         return reachable;
2304                 }
2305
2306                 public override string ToString ()
2307                 {
2308                         StringBuilder sb = new StringBuilder ("FlowBranching (");
2309
2310                         sb.Append (id);
2311                         sb.Append (",");
2312                         sb.Append (Type);
2313                         if (Block != null) {
2314                                 sb.Append (" - ");
2315                                 sb.Append (Block.ID);
2316                                 sb.Append (" - ");
2317                                 sb.Append (Block.StartLocation);
2318                         }
2319                         sb.Append (" - ");
2320                         sb.Append (Siblings.Count);
2321                         sb.Append (" - ");
2322                         sb.Append (CurrentUsageVector);
2323                         sb.Append (")");
2324                         return sb.ToString ();
2325                 }
2326         }
2327
2328         public class MyStructInfo {
2329                 public readonly Type Type;
2330                 public readonly FieldInfo[] Fields;
2331                 public readonly FieldInfo[] NonPublicFields;
2332                 public readonly int Count;
2333                 public readonly int CountNonPublic;
2334                 public readonly bool HasNonPublicFields;
2335
2336                 private static Hashtable field_type_hash = new Hashtable ();
2337                 private Hashtable field_hash;
2338
2339                 // Private constructor.  To save memory usage, we only need to create one instance
2340                 // of this class per struct type.
2341                 private MyStructInfo (Type type)
2342                 {
2343                         this.Type = type;
2344
2345                         if (type is TypeBuilder) {
2346                                 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2347
2348                                 ArrayList fields = tc.Fields;
2349                                 if (fields != null) {
2350                                         foreach (Field field in fields) {
2351                                                 if ((field.ModFlags & Modifiers.STATIC) != 0)
2352                                                         continue;
2353                                                 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2354                                                         ++Count;
2355                                                 else
2356                                                         ++CountNonPublic;
2357                                         }
2358                                 }
2359
2360                                 Fields = new FieldInfo [Count];
2361                                 NonPublicFields = new FieldInfo [CountNonPublic];
2362
2363                                 Count = CountNonPublic = 0;
2364                                 if (fields != null) {
2365                                         foreach (Field field in fields) {
2366                                                 if ((field.ModFlags & Modifiers.STATIC) != 0)
2367                                                         continue;
2368                                                 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2369                                                         Fields [Count++] = field.FieldBuilder;
2370                                                 else
2371                                                         NonPublicFields [CountNonPublic++] =
2372                                                                 field.FieldBuilder;
2373                                         }
2374                                 }
2375                                 
2376                         } else {
2377                                 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2378                                 Count = Fields.Length;
2379
2380                                 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2381                                 CountNonPublic = NonPublicFields.Length;
2382                         }
2383
2384                         Count += NonPublicFields.Length;
2385
2386                         int number = 0;
2387                         field_hash = new Hashtable ();
2388                         foreach (FieldInfo field in Fields)
2389                                 field_hash.Add (field.Name, ++number);
2390
2391                         if (NonPublicFields.Length != 0)
2392                                 HasNonPublicFields = true;
2393
2394                         foreach (FieldInfo field in NonPublicFields)
2395                                 field_hash.Add (field.Name, ++number);
2396                 }
2397
2398                 public int this [string name] {
2399                         get {
2400                                 if (field_hash.Contains (name))
2401                                         return (int) field_hash [name];
2402                                 else
2403                                         return 0;
2404                         }
2405                 }
2406
2407                 public FieldInfo this [int index] {
2408                         get {
2409                                 if (index >= Fields.Length)
2410                                         return NonPublicFields [index - Fields.Length];
2411                                 else
2412                                         return Fields [index];
2413                         }
2414                 }                      
2415
2416                 public static MyStructInfo GetStructInfo (Type type)
2417                 {
2418                         if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2419                                 return null;
2420
2421                         if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2422                                 return null;
2423
2424                         MyStructInfo info = (MyStructInfo) field_type_hash [type];
2425                         if (info != null)
2426                                 return info;
2427
2428                         info = new MyStructInfo (type);
2429                         field_type_hash.Add (type, info);
2430                         return info;
2431                 }
2432
2433                 public static MyStructInfo GetStructInfo (TypeContainer tc)
2434                 {
2435                         MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2436                         if (info != null)
2437                                 return info;
2438
2439                         info = new MyStructInfo (tc.TypeBuilder);
2440                         field_type_hash.Add (tc.TypeBuilder, info);
2441                         return info;
2442                 }
2443         }
2444         
2445         public class VariableInfo : IVariable {
2446                 public Expression Type;
2447                 public LocalBuilder LocalBuilder;
2448                 public Type VariableType;
2449                 public readonly string Name;
2450                 public readonly Location Location;
2451                 public readonly int Block;
2452
2453                 public int Number;
2454                 
2455                 public bool Used;
2456                 public bool Assigned;
2457                 public bool ReadOnly;
2458                 
2459                 public VariableInfo (Expression type, string name, int block, Location l)
2460                 {
2461                         Type = type;
2462                         Name = name;
2463                         Block = block;
2464                         LocalBuilder = null;
2465                         Location = l;
2466                 }
2467
2468                 public VariableInfo (TypeContainer tc, int block, Location l)
2469                 {
2470                         VariableType = tc.TypeBuilder;
2471                         struct_info = MyStructInfo.GetStructInfo (tc);
2472                         Block = block;
2473                         LocalBuilder = null;
2474                         Location = l;
2475                 }
2476
2477                 MyStructInfo struct_info;
2478                 public MyStructInfo StructInfo {
2479                         get {
2480                                 return struct_info;
2481                         }
2482                 }
2483
2484                 public bool IsAssigned (EmitContext ec, Location loc)
2485                 {
2486                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2487                                 return true;
2488
2489                         MyStructInfo struct_info = StructInfo;
2490                         if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2491                                 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2492                                 ec.CurrentBranching.SetVariableAssigned (this);
2493                                 return false;
2494                         }
2495
2496                         int count = struct_info.Count;
2497
2498                         for (int i = 0; i < count; i++) {
2499                                 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2500                                         if (Name != null) {
2501                                                 Report.Error (165, loc,
2502                                                               "Use of unassigned local variable `" +
2503                                                               Name + "'");
2504                                                 ec.CurrentBranching.SetVariableAssigned (this);
2505                                                 return false;
2506                                         }
2507
2508                                         FieldInfo field = struct_info [i];
2509                                         Report.Error (171, loc,
2510                                                       "Field `" + TypeManager.CSharpName (VariableType) +
2511                                                       "." + field.Name + "' must be fully initialized " +
2512                                                       "before control leaves the constructor");
2513                                         return false;
2514                                 }
2515                         }
2516
2517                         return true;
2518                 }
2519
2520                 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2521                 {
2522                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2523                             (struct_info == null))
2524                                 return true;
2525
2526                         int field_idx = StructInfo [name];
2527                         if (field_idx == 0)
2528                                 return true;
2529
2530                         if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2531                                 Report.Error (170, loc,
2532                                               "Use of possibly unassigned field `" + name + "'");
2533                                 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2534                                 return false;
2535                         }
2536
2537                         return true;
2538                 }
2539
2540                 public void SetAssigned (EmitContext ec)
2541                 {
2542                         if (ec.DoFlowAnalysis)
2543                                 ec.CurrentBranching.SetVariableAssigned (this);
2544                 }
2545
2546                 public void SetFieldAssigned (EmitContext ec, string name)
2547                 {
2548                         if (ec.DoFlowAnalysis && (struct_info != null))
2549                                 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2550                 }
2551
2552                 public bool Resolve (DeclSpace decl)
2553                 {
2554                         if (struct_info != null)
2555                                 return true;
2556
2557                         if (VariableType == null)
2558                                 VariableType = decl.ResolveType (Type, false, Location);
2559
2560                         if (VariableType == null)
2561                                 return false;
2562
2563                         struct_info = MyStructInfo.GetStructInfo (VariableType);
2564
2565                         return true;
2566                 }
2567
2568                 public void MakePinned ()
2569                 {
2570                         TypeManager.MakePinned (LocalBuilder);
2571                 }
2572
2573                 public override string ToString ()
2574                 {
2575                         return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2576                 }
2577         }
2578                 
2579         /// <summary>
2580         ///   Block represents a C# block.
2581         /// </summary>
2582         ///
2583         /// <remarks>
2584         ///   This class is used in a number of places: either to represent
2585         ///   explicit blocks that the programmer places or implicit blocks.
2586         ///
2587         ///   Implicit blocks are used as labels or to introduce variable
2588         ///   declarations.
2589         /// </remarks>
2590         public class Block : Statement {
2591                 public readonly Block     Parent;
2592                 public readonly bool      Implicit;
2593                 public readonly Location  StartLocation;
2594                 public Location           EndLocation;
2595
2596                 //
2597                 // The statements in this block
2598                 //
2599                 public ArrayList statements;
2600
2601                 //
2602                 // An array of Blocks.  We keep track of children just
2603                 // to generate the local variable declarations.
2604                 //
2605                 // Statements and child statements are handled through the
2606                 // statements.
2607                 //
2608                 ArrayList children;
2609                 
2610                 //
2611                 // Labels.  (label, block) pairs.
2612                 //
2613                 Hashtable labels;
2614
2615                 //
2616                 // Keeps track of (name, type) pairs
2617                 //
2618                 Hashtable variables;
2619
2620                 //
2621                 // Keeps track of constants
2622                 Hashtable constants;
2623
2624                 //
2625                 // Maps variable names to ILGenerator.LocalBuilders
2626                 //
2627                 Hashtable local_builders;
2628
2629                 bool used = false;
2630
2631                 static int id;
2632
2633                 int this_id;
2634                 
2635                 public Block (Block parent)
2636                         : this (parent, false, Location.Null, Location.Null)
2637                 { }
2638
2639                 public Block (Block parent, bool implicit_block)
2640                         : this (parent, implicit_block, Location.Null, Location.Null)
2641                 { }
2642
2643                 public Block (Block parent, bool implicit_block, Parameters parameters)
2644                         : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2645                 { }
2646
2647                 public Block (Block parent, Location start, Location end)
2648                         : this (parent, false, start, end)
2649                 { }
2650
2651                 public Block (Block parent, Parameters parameters, Location start, Location end)
2652                         : this (parent, false, parameters, start, end)
2653                 { }
2654
2655                 public Block (Block parent, bool implicit_block, Location start, Location end)
2656                         : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2657                                 start, end)
2658                 { }
2659
2660                 public Block (Block parent, bool implicit_block, Parameters parameters,
2661                               Location start, Location end)
2662                 {
2663                         if (parent != null)
2664                                 parent.AddChild (this);
2665                         
2666                         this.Parent = parent;
2667                         this.Implicit = implicit_block;
2668                         this.parameters = parameters;
2669                         this.StartLocation = start;
2670                         this.EndLocation = end;
2671                         this.loc = start;
2672                         this_id = id++;
2673                         statements = new ArrayList ();
2674                 }
2675
2676                 public int ID {
2677                         get {
2678                                 return this_id;
2679                         }
2680                 }
2681
2682                 void AddChild (Block b)
2683                 {
2684                         if (children == null)
2685                                 children = new ArrayList ();
2686                         
2687                         children.Add (b);
2688                 }
2689
2690                 public void SetEndLocation (Location loc)
2691                 {
2692                         EndLocation = loc;
2693                 }
2694
2695                 /// <summary>
2696                 ///   Adds a label to the current block. 
2697                 /// </summary>
2698                 ///
2699                 /// <returns>
2700                 ///   false if the name already exists in this block. true
2701                 ///   otherwise.
2702                 /// </returns>
2703                 ///
2704                 public bool AddLabel (string name, LabeledStatement target)
2705                 {
2706                         if (labels == null)
2707                                 labels = new Hashtable ();
2708                         if (labels.Contains (name))
2709                                 return false;
2710                         
2711                         labels.Add (name, target);
2712                         return true;
2713                 }
2714
2715                 public LabeledStatement LookupLabel (string name)
2716                 {
2717                         if (labels != null){
2718                                 if (labels.Contains (name))
2719                                         return ((LabeledStatement) labels [name]);
2720                         }
2721
2722                         if (Parent != null)
2723                                 return Parent.LookupLabel (name);
2724
2725                         return null;
2726                 }
2727
2728                 VariableInfo this_variable = null;
2729
2730                 // <summary>
2731                 //   Returns the "this" instance variable of this block.
2732                 //   See AddThisVariable() for more information.
2733                 // </summary>
2734                 public VariableInfo ThisVariable {
2735                         get {
2736                                 if (this_variable != null)
2737                                         return this_variable;
2738                                 else if (Parent != null)
2739                                         return Parent.ThisVariable;
2740                                 else
2741                                         return null;
2742                         }
2743                 }
2744
2745                 Hashtable child_variable_names;
2746
2747                 // <summary>
2748                 //   Marks a variable with name @name as being used in a child block.
2749                 //   If a variable name has been used in a child block, it's illegal to
2750                 //   declare a variable with the same name in the current block.
2751                 // </summary>
2752                 public void AddChildVariableName (string name)
2753                 {
2754                         if (child_variable_names == null)
2755                                 child_variable_names = new Hashtable ();
2756
2757                         if (!child_variable_names.Contains (name))
2758                                 child_variable_names.Add (name, true);
2759                 }
2760
2761                 // <summary>
2762                 //   Marks all variables from block @block and all its children as being
2763                 //   used in a child block.
2764                 // </summary>
2765                 public void AddChildVariableNames (Block block)
2766                 {
2767                         if (block.Variables != null) {
2768                                 foreach (string name in block.Variables.Keys)
2769                                         AddChildVariableName (name);
2770                         }
2771
2772                         foreach (Block child in block.children) {
2773                                 if (child.Variables != null) {
2774                                         foreach (string name in child.Variables.Keys)
2775                                                 AddChildVariableName (name);
2776                                 }
2777                         }
2778                 }
2779
2780                 // <summary>
2781                 //   Checks whether a variable name has already been used in a child block.
2782                 // </summary>
2783                 public bool IsVariableNameUsedInChildBlock (string name)
2784                 {
2785                         if (child_variable_names == null)
2786                                 return false;
2787
2788                         return child_variable_names.Contains (name);
2789                 }
2790
2791                 // <summary>
2792                 //   This is used by non-static `struct' constructors which do not have an
2793                 //   initializer - in this case, the constructor must initialize all of the
2794                 //   struct's fields.  To do this, we add a "this" variable and use the flow
2795                 //   analysis code to ensure that it's been fully initialized before control
2796                 //   leaves the constructor.
2797                 // </summary>
2798                 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2799                 {
2800                         if (this_variable != null)
2801                                 return this_variable;
2802
2803                         this_variable = new VariableInfo (tc, ID, l);
2804
2805                         if (variables == null)
2806                                 variables = new Hashtable ();
2807                         variables.Add ("this", this_variable);
2808
2809                         return this_variable;
2810                 }
2811
2812                 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2813                 {
2814                         if (variables == null)
2815                                 variables = new Hashtable ();
2816
2817                         VariableInfo vi = GetVariableInfo (name);
2818                         if (vi != null) {
2819                                 if (vi.Block != ID)
2820                                         Report.Error (136, l, "A local variable named `" + name + "' " +
2821                                                       "cannot be declared in this scope since it would " +
2822                                                       "give a different meaning to `" + name + "', which " +
2823                                                       "is already used in a `parent or current' scope to " +
2824                                                       "denote something else");
2825                                 else
2826                                         Report.Error (128, l, "A local variable `" + name + "' is already " +
2827                                                       "defined in this scope");
2828                                 return null;
2829                         }
2830
2831                         if (IsVariableNameUsedInChildBlock (name)) {
2832                                 Report.Error (136, l, "A local variable named `" + name + "' " +
2833                                               "cannot be declared in this scope since it would " +
2834                                               "give a different meaning to `" + name + "', which " +
2835                                               "is already used in a `child' scope to denote something " +
2836                                               "else");
2837                                 return null;
2838                         }
2839
2840                         if (pars != null) {
2841                                 int idx = 0;
2842                                 Parameter p = pars.GetParameterByName (name, out idx);
2843                                 if (p != null) {
2844                                         Report.Error (136, l, "A local variable named `" + name + "' " +
2845                                                       "cannot be declared in this scope since it would " +
2846                                                       "give a different meaning to `" + name + "', which " +
2847                                                       "is already used in a `parent or current' scope to " +
2848                                                       "denote something else");
2849                                         return null;
2850                                 }
2851                         }
2852                         
2853                         vi = new VariableInfo (type, name, ID, l);
2854
2855                         variables.Add (name, vi);
2856
2857                         if (variables_initialized)
2858                                 throw new Exception ();
2859
2860                         // Console.WriteLine ("Adding {0} to {1}", name, ID);
2861                         return vi;
2862                 }
2863
2864                 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2865                 {
2866                         if (AddVariable (type, name, pars, l) == null)
2867                                 return false;
2868                         
2869                         if (constants == null)
2870                                 constants = new Hashtable ();
2871
2872                         constants.Add (name, value);
2873                         return true;
2874                 }
2875
2876                 public Hashtable Variables {
2877                         get {
2878                                 return variables;
2879                         }
2880                 }
2881
2882                 public VariableInfo GetVariableInfo (string name)
2883                 {
2884                         if (variables != null) {
2885                                 object temp;
2886                                 temp = variables [name];
2887
2888                                 if (temp != null){
2889                                         return (VariableInfo) temp;
2890                                 }
2891                         }
2892
2893                         if (Parent != null)
2894                                 return Parent.GetVariableInfo (name);
2895
2896                         return null;
2897                 }
2898                 
2899                 public Expression GetVariableType (string name)
2900                 {
2901                         VariableInfo vi = GetVariableInfo (name);
2902
2903                         if (vi != null)
2904                                 return vi.Type;
2905
2906                         return null;
2907                 }
2908
2909                 public Expression GetConstantExpression (string name)
2910                 {
2911                         if (constants != null) {
2912                                 object temp;
2913                                 temp = constants [name];
2914                                 
2915                                 if (temp != null)
2916                                         return (Expression) temp;
2917                         }
2918                         
2919                         if (Parent != null)
2920                                 return Parent.GetConstantExpression (name);
2921
2922                         return null;
2923                 }
2924                 
2925                 /// <summary>
2926                 ///   True if the variable named @name has been defined
2927                 ///   in this block
2928                 /// </summary>
2929                 public bool IsVariableDefined (string name)
2930                 {
2931                         // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2932                         if (variables != null) {
2933                                 if (variables.Contains (name))
2934                                         return true;
2935                         }
2936                         
2937                         if (Parent != null)
2938                                 return Parent.IsVariableDefined (name);
2939
2940                         return false;
2941                 }
2942
2943                 /// <summary>
2944                 ///   True if the variable named @name is a constant
2945                 ///  </summary>
2946                 public bool IsConstant (string name)
2947                 {
2948                         Expression e = null;
2949                         
2950                         e = GetConstantExpression (name);
2951                         
2952                         return e != null;
2953                 }
2954                 
2955                 /// <summary>
2956                 ///   Use to fetch the statement associated with this label
2957                 /// </summary>
2958                 public Statement this [string name] {
2959                         get {
2960                                 return (Statement) labels [name];
2961                         }
2962                 }
2963
2964                 Parameters parameters = null;
2965                 public Parameters Parameters {
2966                         get {
2967                                 if (Parent != null)
2968                                         return Parent.Parameters;
2969
2970                                 return parameters;
2971                         }
2972                 }
2973
2974                 /// <returns>
2975                 ///   A list of labels that were not used within this block
2976                 /// </returns>
2977                 public string [] GetUnreferenced ()
2978                 {
2979                         // FIXME: Implement me
2980                         return null;
2981                 }
2982
2983                 public void AddStatement (Statement s)
2984                 {
2985                         statements.Add (s);
2986                         used = true;
2987                 }
2988
2989                 public bool Used {
2990                         get {
2991                                 return used;
2992                         }
2993                 }
2994
2995                 public void Use ()
2996                 {
2997                         used = true;
2998                 }
2999
3000                 bool variables_initialized = false;
3001                 int count_variables = 0, first_variable = 0;
3002
3003                 void UpdateVariableInfo (EmitContext ec)
3004                 {
3005                         DeclSpace ds = ec.DeclSpace;
3006
3007                         first_variable = 0;
3008
3009                         if (Parent != null)
3010                                 first_variable += Parent.CountVariables;
3011
3012                         count_variables = first_variable;
3013                         if (variables != null) {
3014                                 foreach (VariableInfo vi in variables.Values) {
3015                                         if (!vi.Resolve (ds)) {
3016                                                 vi.Number = -1;
3017                                                 continue;
3018                                         }
3019
3020                                         vi.Number = ++count_variables;
3021
3022                                         if (vi.StructInfo != null)
3023                                                 count_variables += vi.StructInfo.Count;
3024                                 }
3025                         }
3026
3027                         variables_initialized = true;
3028                 }
3029
3030                 //
3031                 // <returns>
3032                 //   The number of local variables in this block
3033                 // </returns>
3034                 public int CountVariables
3035                 {
3036                         get {
3037                                 if (!variables_initialized)
3038                                         throw new Exception ();
3039
3040                                 return count_variables;
3041                         }
3042                 }
3043
3044                 /// <summary>
3045                 ///   Emits the variable declarations and labels.
3046                 /// </summary>
3047                 /// <remarks>
3048                 ///   tc: is our typecontainer (to resolve type references)
3049                 ///   ig: is the code generator:
3050                 ///   toplevel: the toplevel block.  This is used for checking 
3051                 ///             that no two labels with the same name are used.
3052                 /// </remarks>
3053                 public void EmitMeta (EmitContext ec, Block toplevel)
3054                 {
3055                         DeclSpace ds = ec.DeclSpace;
3056                         ILGenerator ig = ec.ig;
3057
3058                         if (!variables_initialized)
3059                                 UpdateVariableInfo (ec);
3060
3061                         //
3062                         // Process this block variables
3063                         //
3064                         if (variables != null){
3065                                 local_builders = new Hashtable ();
3066                                 
3067                                 foreach (DictionaryEntry de in variables){
3068                                         string name = (string) de.Key;
3069                                         VariableInfo vi = (VariableInfo) de.Value;
3070
3071                                         if (vi.VariableType == null)
3072                                                 continue;
3073
3074                                         vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
3075
3076                                         if (CodeGen.SymbolWriter != null)
3077                                                 vi.LocalBuilder.SetLocalSymInfo (name);
3078
3079                                         if (constants == null)
3080                                                 continue;
3081
3082                                         Expression cv = (Expression) constants [name];
3083                                         if (cv == null)
3084                                                 continue;
3085
3086                                         Expression e = cv.Resolve (ec);
3087                                         if (e == null)
3088                                                 continue;
3089
3090                                         if (!(e is Constant)){
3091                                                 Report.Error (133, vi.Location,
3092                                                               "The expression being assigned to `" +
3093                                                               name + "' must be constant (" + e + ")");
3094                                                 continue;
3095                                         }
3096
3097                                         constants.Remove (name);
3098                                         constants.Add (name, e);
3099                                 }
3100                         }
3101
3102                         //
3103                         // Now, handle the children
3104                         //
3105                         if (children != null){
3106                                 foreach (Block b in children)
3107                                         b.EmitMeta (ec, toplevel);
3108                         }
3109                 }
3110
3111                 public void UsageWarning ()
3112                 {
3113                         string name;
3114                         
3115                         if (variables != null){
3116                                 foreach (DictionaryEntry de in variables){
3117                                         VariableInfo vi = (VariableInfo) de.Value;
3118                                         
3119                                         if (vi.Used)
3120                                                 continue;
3121                                         
3122                                         name = (string) de.Key;
3123                                                 
3124                                         if (vi.Assigned){
3125                                                 Report.Warning (
3126                                                         219, vi.Location, "The variable `" + name +
3127                                                         "' is assigned but its value is never used");
3128                                         } else {
3129                                                 Report.Warning (
3130                                                         168, vi.Location, "The variable `" +
3131                                                         name +
3132                                                         "' is declared but never used");
3133                                         } 
3134                                 }
3135                         }
3136
3137                         if (children != null)
3138                                 foreach (Block b in children)
3139                                         b.UsageWarning ();
3140                 }
3141
3142                 bool has_ret = false;
3143
3144                 public override bool Resolve (EmitContext ec)
3145                 {
3146                         Block prev_block = ec.CurrentBlock;
3147                         bool ok = true;
3148
3149                         ec.CurrentBlock = this;
3150                         ec.StartFlowBranching (this);
3151
3152                         Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
3153
3154                         if (!variables_initialized)
3155                                 UpdateVariableInfo (ec);
3156
3157                         ArrayList new_statements = new ArrayList ();
3158                         bool unreachable = false, warning_shown = false;
3159
3160                         foreach (Statement s in statements){
3161                                 if (unreachable && !(s is LabeledStatement)) {
3162                                         if (!warning_shown && !(s is EmptyStatement)) {
3163                                                 warning_shown = true;
3164                                                 Warning_DeadCodeFound (s.loc);
3165                                         }
3166
3167                                         continue;
3168                                 }
3169
3170                                 if (s.Resolve (ec) == false) {
3171                                         ok = false;
3172                                         continue;
3173                                 }
3174
3175                                 if (s is LabeledStatement)
3176                                         unreachable = false;
3177                                 else
3178                                         unreachable = ! ec.CurrentBranching.IsReachable ();
3179
3180                                 new_statements.Add (s);
3181                         }
3182
3183                         statements = new_statements;
3184
3185                         Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
3186
3187                         FlowReturns returns = ec.EndFlowBranching ();
3188                         ec.CurrentBlock = prev_block;
3189
3190                         // If we're a non-static `struct' constructor which doesn't have an
3191                         // initializer, then we must initialize all of the struct's fields.
3192                         if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
3193                             !this_variable.IsAssigned (ec, loc))
3194                                 ok = false;
3195
3196                         if ((labels != null) && (RootContext.WarningLevel >= 2)) {
3197                                 foreach (LabeledStatement label in labels.Values)
3198                                         if (!label.HasBeenReferenced)
3199                                                 Report.Warning (164, label.Location,
3200                                                                 "This label has not been referenced");
3201                         }
3202
3203                         if ((returns == FlowReturns.ALWAYS) ||
3204                             (returns == FlowReturns.EXCEPTION) ||
3205                             (returns == FlowReturns.UNREACHABLE))
3206                                 has_ret = true;
3207
3208                         return ok;
3209                 }
3210                 
3211                 protected override bool DoEmit (EmitContext ec)
3212                 {
3213                         Block prev_block = ec.CurrentBlock;
3214
3215                         ec.CurrentBlock = this;
3216
3217                         ec.Mark (StartLocation);
3218                         foreach (Statement s in statements)
3219                                 s.Emit (ec);
3220                                 
3221                         ec.Mark (EndLocation); 
3222                         
3223                         ec.CurrentBlock = prev_block;
3224                         return has_ret;
3225                 }
3226         }
3227
3228         public class SwitchLabel {
3229                 Expression label;
3230                 object converted;
3231                 public Location loc;
3232                 public Label ILLabel;
3233                 public Label ILLabelCode;
3234
3235                 //
3236                 // if expr == null, then it is the default case.
3237                 //
3238                 public SwitchLabel (Expression expr, Location l)
3239                 {
3240                         label = expr;
3241                         loc = l;
3242                 }
3243
3244                 public Expression Label {
3245                         get {
3246                                 return label;
3247                         }
3248                 }
3249
3250                 public object Converted {
3251                         get {
3252                                 return converted;
3253                         }
3254                 }
3255
3256                 //
3257                 // Resolves the expression, reduces it to a literal if possible
3258                 // and then converts it to the requested type.
3259                 //
3260                 public bool ResolveAndReduce (EmitContext ec, Type required_type)
3261                 {
3262                         ILLabel = ec.ig.DefineLabel ();
3263                         ILLabelCode = ec.ig.DefineLabel ();
3264
3265                         if (label == null)
3266                                 return true;
3267                         
3268                         Expression e = label.Resolve (ec);
3269
3270                         if (e == null)
3271                                 return false;
3272
3273                         if (!(e is Constant)){
3274                                 Console.WriteLine ("Value is: " + label);
3275                                 Report.Error (150, loc, "A constant value is expected");
3276                                 return false;
3277                         }
3278
3279                         if (e is StringConstant || e is NullLiteral){
3280                                 if (required_type == TypeManager.string_type){
3281                                         converted = e;
3282                                         ILLabel = ec.ig.DefineLabel ();
3283                                         return true;
3284                                 }
3285                         }
3286
3287                         converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
3288                         if (converted == null)
3289                                 return false;
3290
3291                         return true;
3292                 }
3293         }
3294
3295         public class SwitchSection {
3296                 // An array of SwitchLabels.
3297                 public readonly ArrayList Labels;
3298                 public readonly Block Block;
3299                 
3300                 public SwitchSection (ArrayList labels, Block block)
3301                 {
3302                         Labels = labels;
3303                         Block = block;
3304                 }
3305         }
3306         
3307         public class Switch : Statement {
3308                 public readonly ArrayList Sections;
3309                 public Expression Expr;
3310
3311                 /// <summary>
3312                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
3313                 /// </summary>
3314                 public Hashtable Elements;
3315
3316                 /// <summary>
3317                 ///   The governing switch type
3318                 /// </summary>
3319                 public Type SwitchType;
3320
3321                 //
3322                 // Computed
3323                 //
3324                 bool got_default;
3325                 Label default_target;
3326                 Expression new_expr;
3327
3328                 //
3329                 // The types allowed to be implicitly cast from
3330                 // on the governing type
3331                 //
3332                 static Type [] allowed_types;
3333                 
3334                 public Switch (Expression e, ArrayList sects, Location l)
3335                 {
3336                         Expr = e;
3337                         Sections = sects;
3338                         loc = l;
3339                 }
3340
3341                 public bool GotDefault {
3342                         get {
3343                                 return got_default;
3344                         }
3345                 }
3346
3347                 public Label DefaultTarget {
3348                         get {
3349                                 return default_target;
3350                         }
3351                 }
3352
3353                 //
3354                 // Determines the governing type for a switch.  The returned
3355                 // expression might be the expression from the switch, or an
3356                 // expression that includes any potential conversions to the
3357                 // integral types or to string.
3358                 //
3359                 Expression SwitchGoverningType (EmitContext ec, Type t)
3360                 {
3361                         if (t == TypeManager.int32_type ||
3362                             t == TypeManager.uint32_type ||
3363                             t == TypeManager.char_type ||
3364                             t == TypeManager.byte_type ||
3365                             t == TypeManager.sbyte_type ||
3366                             t == TypeManager.ushort_type ||
3367                             t == TypeManager.short_type ||
3368                             t == TypeManager.uint64_type ||
3369                             t == TypeManager.int64_type ||
3370                             t == TypeManager.string_type ||
3371                                 t == TypeManager.bool_type ||
3372                                 t.IsSubclassOf (TypeManager.enum_type))
3373                                 return Expr;
3374
3375                         if (allowed_types == null){
3376                                 allowed_types = new Type [] {
3377                                         TypeManager.sbyte_type,
3378                                         TypeManager.byte_type,
3379                                         TypeManager.short_type,
3380                                         TypeManager.ushort_type,
3381                                         TypeManager.int32_type,
3382                                         TypeManager.uint32_type,
3383                                         TypeManager.int64_type,
3384                                         TypeManager.uint64_type,
3385                                         TypeManager.char_type,
3386                                         TypeManager.bool_type,
3387                                         TypeManager.string_type
3388                                 };
3389                         }
3390
3391                         //
3392                         // Try to find a *user* defined implicit conversion.
3393                         //
3394                         // If there is no implicit conversion, or if there are multiple
3395                         // conversions, we have to report an error
3396                         //
3397                         Expression converted = null;
3398                         foreach (Type tt in allowed_types){
3399                                 Expression e;
3400                                 
3401                                 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3402                                 if (e == null)
3403                                         continue;
3404
3405                                 if (converted != null){
3406                                         Report.Error (-12, loc, "More than one conversion to an integral " +
3407                                                       " type exists for type `" +
3408                                                       TypeManager.CSharpName (Expr.Type)+"'");
3409                                         return null;
3410                                 } else
3411                                         converted = e;
3412                         }
3413                         return converted;
3414                 }
3415
3416                 void error152 (string n)
3417                 {
3418                         Report.Error (
3419                                 152, "The label `" + n + ":' " +
3420                                 "is already present on this switch statement");
3421                 }
3422                 
3423                 //
3424                 // Performs the basic sanity checks on the switch statement
3425                 // (looks for duplicate keys and non-constant expressions).
3426                 //
3427                 // It also returns a hashtable with the keys that we will later
3428                 // use to compute the switch tables
3429                 //
3430                 bool CheckSwitch (EmitContext ec)
3431                 {
3432                         Type compare_type;
3433                         bool error = false;
3434                         Elements = new Hashtable ();
3435                                 
3436                         got_default = false;
3437
3438                         if (TypeManager.IsEnumType (SwitchType)){
3439                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3440                         } else
3441                                 compare_type = SwitchType;
3442                         
3443                         foreach (SwitchSection ss in Sections){
3444                                 foreach (SwitchLabel sl in ss.Labels){
3445                                         if (!sl.ResolveAndReduce (ec, SwitchType)){
3446                                                 error = true;
3447                                                 continue;
3448                                         }
3449
3450                                         if (sl.Label == null){
3451                                                 if (got_default){
3452                                                         error152 ("default");
3453                                                         error = true;
3454                                                 }
3455                                                 got_default = true;
3456                                                 continue;
3457                                         }
3458                                         
3459                                         object key = sl.Converted;
3460
3461                                         if (key is Constant)
3462                                                 key = ((Constant) key).GetValue ();
3463
3464                                         if (key == null)
3465                                                 key = NullLiteral.Null;
3466                                         
3467                                         string lname = null;
3468                                         if (compare_type == TypeManager.uint64_type){
3469                                                 ulong v = (ulong) key;
3470
3471                                                 if (Elements.Contains (v))
3472                                                         lname = v.ToString ();
3473                                                 else
3474                                                         Elements.Add (v, sl);
3475                                         } else if (compare_type == TypeManager.int64_type){
3476                                                 long v = (long) key;
3477
3478                                                 if (Elements.Contains (v))
3479                                                         lname = v.ToString ();
3480                                                 else
3481                                                         Elements.Add (v, sl);
3482                                         } else if (compare_type == TypeManager.uint32_type){
3483                                                 uint v = (uint) key;
3484
3485                                                 if (Elements.Contains (v))
3486                                                         lname = v.ToString ();
3487                                                 else
3488                                                         Elements.Add (v, sl);
3489                                         } else if (compare_type == TypeManager.char_type){
3490                                                 char v = (char) key;
3491                                                 
3492                                                 if (Elements.Contains (v))
3493                                                         lname = v.ToString ();
3494                                                 else
3495                                                         Elements.Add (v, sl);
3496                                         } else if (compare_type == TypeManager.byte_type){
3497                                                 byte v = (byte) key;
3498                                                 
3499                                                 if (Elements.Contains (v))
3500                                                         lname = v.ToString ();
3501                                                 else
3502                                                         Elements.Add (v, sl);
3503                                         } else if (compare_type == TypeManager.sbyte_type){
3504                                                 sbyte v = (sbyte) key;
3505                                                 
3506                                                 if (Elements.Contains (v))
3507                                                         lname = v.ToString ();
3508                                                 else
3509                                                         Elements.Add (v, sl);
3510                                         } else if (compare_type == TypeManager.short_type){
3511                                                 short v = (short) key;
3512                                                 
3513                                                 if (Elements.Contains (v))
3514                                                         lname = v.ToString ();
3515                                                 else
3516                                                         Elements.Add (v, sl);
3517                                         } else if (compare_type == TypeManager.ushort_type){
3518                                                 ushort v = (ushort) key;
3519                                                 
3520                                                 if (Elements.Contains (v))
3521                                                         lname = v.ToString ();
3522                                                 else
3523                                                         Elements.Add (v, sl);
3524                                         } else if (compare_type == TypeManager.string_type){
3525                                                 if (key is NullLiteral){
3526                                                         if (Elements.Contains (NullLiteral.Null))
3527                                                                 lname = "null";
3528                                                         else
3529                                                                 Elements.Add (NullLiteral.Null, null);
3530                                                 } else {
3531                                                         string s = (string) key;
3532
3533                                                         if (Elements.Contains (s))
3534                                                                 lname = s;
3535                                                         else
3536                                                                 Elements.Add (s, sl);
3537                                                 }
3538                                         } else if (compare_type == TypeManager.int32_type) {
3539                                                 int v = (int) key;
3540
3541                                                 if (Elements.Contains (v))
3542                                                         lname = v.ToString ();
3543                                                 else
3544                                                         Elements.Add (v, sl);
3545                                         } else if (compare_type == TypeManager.bool_type) {
3546                                                 bool v = (bool) key;
3547
3548                                                 if (Elements.Contains (v))
3549                                                         lname = v.ToString ();
3550                                                 else
3551                                                         Elements.Add (v, sl);
3552                                         }
3553                                         else
3554                                         {
3555                                                 throw new Exception ("Unknown switch type!" +
3556                                                                      SwitchType + " " + compare_type);
3557                                         }
3558
3559                                         if (lname != null){
3560                                                 error152 ("case + " + lname);
3561                                                 error = true;
3562                                         }
3563                                 }
3564                         }
3565                         if (error)
3566                                 return false;
3567                         
3568                         return true;
3569                 }
3570
3571                 void EmitObjectInteger (ILGenerator ig, object k)
3572                 {
3573                         if (k is int)
3574                                 IntConstant.EmitInt (ig, (int) k);
3575                         else if (k is Constant) {
3576                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3577                         } 
3578                         else if (k is uint)
3579                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3580                         else if (k is long)
3581                         {
3582                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3583                                 {
3584                                         IntConstant.EmitInt (ig, (int) (long) k);
3585                                         ig.Emit (OpCodes.Conv_I8);
3586                                 }
3587                                 else
3588                                         LongConstant.EmitLong (ig, (long) k);
3589                         }
3590                         else if (k is ulong)
3591                         {
3592                                 if ((ulong) k < (1L<<32))
3593                                 {
3594                                         IntConstant.EmitInt (ig, (int) (long) k);
3595                                         ig.Emit (OpCodes.Conv_U8);
3596                                 }
3597                                 else
3598                                 {
3599                                         LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3600                                 }
3601                         }
3602                         else if (k is char)
3603                                 IntConstant.EmitInt (ig, (int) ((char) k));
3604                         else if (k is sbyte)
3605                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3606                         else if (k is byte)
3607                                 IntConstant.EmitInt (ig, (int) ((byte) k));
3608                         else if (k is short)
3609                                 IntConstant.EmitInt (ig, (int) ((short) k));
3610                         else if (k is ushort)
3611                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
3612                         else if (k is bool)
3613                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3614                         else
3615                                 throw new Exception ("Unhandled case");
3616                 }
3617                 
3618                 // structure used to hold blocks of keys while calculating table switch
3619                 class KeyBlock : IComparable
3620                 {
3621                         public KeyBlock (long _nFirst)
3622                         {
3623                                 nFirst = nLast = _nFirst;
3624                         }
3625                         public long nFirst;
3626                         public long nLast;
3627                         public ArrayList rgKeys = null;
3628                         public int Length
3629                         {
3630                                 get { return (int) (nLast - nFirst + 1); }
3631                         }
3632                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3633                         {
3634                                 return kbLast.nLast - kbFirst.nFirst + 1;
3635                         }
3636                         public int CompareTo (object obj)
3637                         {
3638                                 KeyBlock kb = (KeyBlock) obj;
3639                                 int nLength = Length;
3640                                 int nLengthOther = kb.Length;
3641                                 if (nLengthOther == nLength)
3642                                         return (int) (kb.nFirst - nFirst);
3643                                 return nLength - nLengthOther;
3644                         }
3645                 }
3646
3647                 /// <summary>
3648                 /// This method emits code for a lookup-based switch statement (non-string)
3649                 /// Basically it groups the cases into blocks that are at least half full,
3650                 /// and then spits out individual lookup opcodes for each block.
3651                 /// It emits the longest blocks first, and short blocks are just
3652                 /// handled with direct compares.
3653                 /// </summary>
3654                 /// <param name="ec"></param>
3655                 /// <param name="val"></param>
3656                 /// <returns></returns>
3657                 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3658                 {
3659                         int cElements = Elements.Count;
3660                         object [] rgKeys = new object [cElements];
3661                         Elements.Keys.CopyTo (rgKeys, 0);
3662                         Array.Sort (rgKeys);
3663
3664                         // initialize the block list with one element per key
3665                         ArrayList rgKeyBlocks = new ArrayList ();
3666                         foreach (object key in rgKeys)
3667                                 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3668
3669                         KeyBlock kbCurr;
3670                         // iteratively merge the blocks while they are at least half full
3671                         // there's probably a really cool way to do this with a tree...
3672                         while (rgKeyBlocks.Count > 1)
3673                         {
3674                                 ArrayList rgKeyBlocksNew = new ArrayList ();
3675                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
3676                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3677                                 {
3678                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3679                                         if ((kbCurr.Length + kb.Length) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
3680                                         {
3681                                                 // merge blocks
3682                                                 kbCurr.nLast = kb.nLast;
3683                                         }
3684                                         else
3685                                         {
3686                                                 // start a new block
3687                                                 rgKeyBlocksNew.Add (kbCurr);
3688                                                 kbCurr = kb;
3689                                         }
3690                                 }
3691                                 rgKeyBlocksNew.Add (kbCurr);
3692                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3693                                         break;
3694                                 rgKeyBlocks = rgKeyBlocksNew;
3695                         }
3696
3697                         // initialize the key lists
3698                         foreach (KeyBlock kb in rgKeyBlocks)
3699                                 kb.rgKeys = new ArrayList ();
3700
3701                         // fill the key lists
3702                         int iBlockCurr = 0;
3703                         if (rgKeyBlocks.Count > 0) {
3704                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
3705                                 foreach (object key in rgKeys)
3706                                 {
3707                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3708                                         if (fNextBlock)
3709                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3710                                         kbCurr.rgKeys.Add (key);
3711                                 }
3712                         }
3713
3714                         // sort the blocks so we can tackle the largest ones first
3715                         rgKeyBlocks.Sort ();
3716
3717                         // okay now we can start...
3718                         ILGenerator ig = ec.ig;
3719                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
3720                         Label lblDefault = ig.DefineLabel ();
3721
3722                         Type typeKeys = null;
3723                         if (rgKeys.Length > 0)
3724                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
3725
3726                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3727                         {
3728                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3729                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3730                                 if (kb.Length <= 2)
3731                                 {
3732                                         foreach (object key in kb.rgKeys)
3733                                         {
3734                                                 ig.Emit (OpCodes.Ldloc, val);
3735                                                 EmitObjectInteger (ig, key);
3736                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
3737                                                 ig.Emit (OpCodes.Beq, sl.ILLabel);
3738                                         }
3739                                 }
3740                                 else
3741                                 {
3742                                         // TODO: if all the keys in the block are the same and there are
3743                                         //       no gaps/defaults then just use a range-check.
3744                                         if (SwitchType == TypeManager.int64_type ||
3745                                                 SwitchType == TypeManager.uint64_type)
3746                                         {
3747                                                 // TODO: optimize constant/I4 cases
3748
3749                                                 // check block range (could be > 2^31)
3750                                                 ig.Emit (OpCodes.Ldloc, val);
3751                                                 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3752                                                 ig.Emit (OpCodes.Blt, lblDefault);
3753                                                 ig.Emit (OpCodes.Ldloc, val);
3754                                                 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3755                                                 ig.Emit (OpCodes.Bgt, lblDefault);
3756
3757                                                 // normalize range
3758                                                 ig.Emit (OpCodes.Ldloc, val);
3759                                                 if (kb.nFirst != 0)
3760                                                 {
3761                                                         EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3762                                                         ig.Emit (OpCodes.Sub);
3763                                                 }
3764                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
3765                                         }
3766                                         else
3767                                         {
3768                                                 // normalize range
3769                                                 ig.Emit (OpCodes.Ldloc, val);
3770                                                 int nFirst = (int) kb.nFirst;
3771                                                 if (nFirst > 0)
3772                                                 {
3773                                                         IntConstant.EmitInt (ig, nFirst);
3774                                                         ig.Emit (OpCodes.Sub);
3775                                                 }
3776                                                 else if (nFirst < 0)
3777                                                 {
3778                                                         IntConstant.EmitInt (ig, -nFirst);
3779                                                         ig.Emit (OpCodes.Add);
3780                                                 }
3781                                         }
3782
3783                                         // first, build the list of labels for the switch
3784                                         int iKey = 0;
3785                                         int cJumps = kb.Length;
3786                                         Label [] rgLabels = new Label [cJumps];
3787                                         for (int iJump = 0; iJump < cJumps; iJump++)
3788                                         {
3789                                                 object key = kb.rgKeys [iKey];
3790                                                 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3791                                                 {
3792                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
3793                                                         rgLabels [iJump] = sl.ILLabel;
3794                                                         iKey++;
3795                                                 }
3796                                                 else
3797                                                         rgLabels [iJump] = lblDefault;
3798                                         }
3799                                         // emit the switch opcode
3800                                         ig.Emit (OpCodes.Switch, rgLabels);
3801                                 }
3802
3803                                 // mark the default for this block
3804                                 if (iBlock != 0)
3805                                         ig.MarkLabel (lblDefault);
3806                         }
3807
3808                         // TODO: find the default case and emit it here,
3809                         //       to prevent having to do the following jump.
3810                         //       make sure to mark other labels in the default section
3811
3812                         // the last default just goes to the end
3813                         ig.Emit (OpCodes.Br, lblDefault);
3814
3815                         // now emit the code for the sections
3816                         bool fFoundDefault = false;
3817                         bool fAllReturn = true;
3818                         foreach (SwitchSection ss in Sections)
3819                         {
3820                                 foreach (SwitchLabel sl in ss.Labels)
3821                                 {
3822                                         ig.MarkLabel (sl.ILLabel);
3823                                         ig.MarkLabel (sl.ILLabelCode);
3824                                         if (sl.Label == null)
3825                                         {
3826                                                 ig.MarkLabel (lblDefault);
3827                                                 fFoundDefault = true;
3828                                         }
3829                                 }
3830                                 bool returns = ss.Block.Emit (ec);
3831                                 fAllReturn &= returns;
3832                                 //ig.Emit (OpCodes.Br, lblEnd);
3833                         }
3834                         
3835                         if (!fFoundDefault) {
3836                                 ig.MarkLabel (lblDefault);
3837                                 fAllReturn = false;
3838                         }
3839                         ig.MarkLabel (lblEnd);
3840
3841                         return fAllReturn;
3842                 }
3843                 //
3844                 // This simple emit switch works, but does not take advantage of the
3845                 // `switch' opcode. 
3846                 // TODO: remove non-string logic from here
3847                 // TODO: binary search strings?
3848                 //
3849                 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3850                 {
3851                         ILGenerator ig = ec.ig;
3852                         Label end_of_switch = ig.DefineLabel ();
3853                         Label next_test = ig.DefineLabel ();
3854                         Label null_target = ig.DefineLabel ();
3855                         bool default_found = false;
3856                         bool first_test = true;
3857                         bool pending_goto_end = false;
3858                         bool all_return = true;
3859                         bool is_string = false;
3860                         bool null_found;
3861                         
3862                         //
3863                         // Special processing for strings: we cant compare
3864                         // against null.
3865                         //
3866                         if (SwitchType == TypeManager.string_type){
3867                                 ig.Emit (OpCodes.Ldloc, val);
3868                                 is_string = true;
3869                                 
3870                                 if (Elements.Contains (NullLiteral.Null)){
3871                                         ig.Emit (OpCodes.Brfalse, null_target);
3872                                 } else
3873                                         ig.Emit (OpCodes.Brfalse, default_target);
3874
3875                                 ig.Emit (OpCodes.Ldloc, val);
3876                                 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3877                                 ig.Emit (OpCodes.Stloc, val);
3878                         }
3879                         
3880                         foreach (SwitchSection ss in Sections){
3881                                 Label sec_begin = ig.DefineLabel ();
3882
3883                                 if (pending_goto_end)
3884                                         ig.Emit (OpCodes.Br, end_of_switch);
3885
3886                                 int label_count = ss.Labels.Count;
3887                                 null_found = false;
3888                                 foreach (SwitchLabel sl in ss.Labels){
3889                                         ig.MarkLabel (sl.ILLabel);
3890                                         
3891                                         if (!first_test){
3892                                                 ig.MarkLabel (next_test);
3893                                                 next_test = ig.DefineLabel ();
3894                                         }
3895                                         //
3896                                         // If we are the default target
3897                                         //
3898                                         if (sl.Label == null){
3899                                                 ig.MarkLabel (default_target);
3900                                                 default_found = true;
3901                                         } else {
3902                                                 object lit = sl.Converted;
3903
3904                                                 if (lit is NullLiteral){
3905                                                         null_found = true;
3906                                                         if (label_count == 1)
3907                                                                 ig.Emit (OpCodes.Br, next_test);
3908                                                         continue;
3909                                                                               
3910                                                 }
3911                                                 if (is_string){
3912                                                         StringConstant str = (StringConstant) lit;
3913
3914                                                         ig.Emit (OpCodes.Ldloc, val);
3915                                                         ig.Emit (OpCodes.Ldstr, str.Value);
3916                                                         if (label_count == 1)
3917                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
3918                                                         else
3919                                                                 ig.Emit (OpCodes.Beq, sec_begin);
3920                                                 } else {
3921                                                         ig.Emit (OpCodes.Ldloc, val);
3922                                                         EmitObjectInteger (ig, lit);
3923                                                         ig.Emit (OpCodes.Ceq);
3924                                                         if (label_count == 1)
3925                                                                 ig.Emit (OpCodes.Brfalse, next_test);
3926                                                         else
3927                                                                 ig.Emit (OpCodes.Brtrue, sec_begin);
3928                                                 }
3929                                         }
3930                                 }
3931                                 if (label_count != 1)
3932                                         ig.Emit (OpCodes.Br, next_test);
3933                                 
3934                                 if (null_found)
3935                                         ig.MarkLabel (null_target);
3936                                 ig.MarkLabel (sec_begin);
3937                                 foreach (SwitchLabel sl in ss.Labels)
3938                                         ig.MarkLabel (sl.ILLabelCode);
3939
3940                                 bool returns = ss.Block.Emit (ec);
3941                                 if (returns)
3942                                         pending_goto_end = false;
3943                                 else {
3944                                         all_return = false;
3945                                         pending_goto_end = true;
3946                                 }
3947                                 first_test = false;
3948                         }
3949                         if (!default_found){
3950                                 ig.MarkLabel (default_target);
3951                                 all_return = false;
3952                         }
3953                         ig.MarkLabel (next_test);
3954                         ig.MarkLabel (end_of_switch);
3955                         
3956                         return all_return;
3957                 }
3958
3959                 public override bool Resolve (EmitContext ec)
3960                 {
3961                         Expr = Expr.Resolve (ec);
3962                         if (Expr == null)
3963                                 return false;
3964
3965                         new_expr = SwitchGoverningType (ec, Expr.Type);
3966                         if (new_expr == null){
3967                                 Report.Error (151, loc, "An integer type or string was expected for switch");
3968                                 return false;
3969                         }
3970
3971                         // Validate switch.
3972                         SwitchType = new_expr.Type;
3973
3974                         if (!CheckSwitch (ec))
3975                                 return false;
3976
3977                         Switch old_switch = ec.Switch;
3978                         ec.Switch = this;
3979                         ec.Switch.SwitchType = SwitchType;
3980
3981                         ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3982
3983                         bool first = true;
3984                         foreach (SwitchSection ss in Sections){
3985                                 if (!first)
3986                                         ec.CurrentBranching.CreateSibling ();
3987                                 else
3988                                         first = false;
3989
3990                                 if (ss.Block.Resolve (ec) != true)
3991                                         return false;
3992                         }
3993
3994
3995                         if (!got_default)
3996                                 ec.CurrentBranching.CreateSibling ();
3997
3998                         ec.EndFlowBranching ();
3999                         ec.Switch = old_switch;
4000
4001                         return true;
4002                 }
4003                 
4004                 protected override bool DoEmit (EmitContext ec)
4005                 {
4006                         // Store variable for comparission purposes
4007                         LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
4008                         new_expr.Emit (ec);
4009                         ec.ig.Emit (OpCodes.Stloc, value);
4010
4011                         ILGenerator ig = ec.ig;
4012
4013                         default_target = ig.DefineLabel ();
4014
4015                         //
4016                         // Setup the codegen context
4017                         //
4018                         Label old_end = ec.LoopEnd;
4019                         Switch old_switch = ec.Switch;
4020                         
4021                         ec.LoopEnd = ig.DefineLabel ();
4022                         ec.Switch = this;
4023
4024                         // Emit Code.
4025                         bool all_return;
4026                         if (SwitchType == TypeManager.string_type)
4027                                 all_return = SimpleSwitchEmit (ec, value);
4028                         else
4029                                 all_return = TableSwitchEmit (ec, value);
4030
4031                         // Restore context state. 
4032                         ig.MarkLabel (ec.LoopEnd);
4033
4034                         //
4035                         // Restore the previous context
4036                         //
4037                         ec.LoopEnd = old_end;
4038                         ec.Switch = old_switch;
4039                         
4040                         return all_return;
4041                 }
4042         }
4043
4044         public class Lock : Statement {
4045                 Expression expr;
4046                 Statement Statement;
4047                         
4048                 public Lock (Expression expr, Statement stmt, Location l)
4049                 {
4050                         this.expr = expr;
4051                         Statement = stmt;
4052                         loc = l;
4053                 }
4054
4055                 public override bool Resolve (EmitContext ec)
4056                 {
4057                         expr = expr.Resolve (ec);
4058                         return Statement.Resolve (ec) && expr != null;
4059                 }
4060                 
4061                 protected override bool DoEmit (EmitContext ec)
4062                 {
4063                         Type type = expr.Type;
4064                         bool val;
4065                         
4066                         if (type.IsValueType){
4067                                 Report.Error (185, loc, "lock statement requires the expression to be " +
4068                                               " a reference type (type is: `" +
4069                                               TypeManager.CSharpName (type) + "'");
4070                                 return false;
4071                         }
4072
4073                         ILGenerator ig = ec.ig;
4074                         LocalBuilder temp = ig.DeclareLocal (type);
4075                                 
4076                         expr.Emit (ec);
4077                         ig.Emit (OpCodes.Dup);
4078                         ig.Emit (OpCodes.Stloc, temp);
4079                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
4080
4081                         // try
4082                         Label end = ig.BeginExceptionBlock ();
4083                         bool old_in_try = ec.InTry;
4084                         ec.InTry = true;
4085                         Label finish = ig.DefineLabel ();
4086                         val = Statement.Emit (ec);
4087                         ec.InTry = old_in_try;
4088                         // ig.Emit (OpCodes.Leave, finish);
4089
4090                         ig.MarkLabel (finish);
4091                         
4092                         // finally
4093                         ig.BeginFinallyBlock ();
4094                         ig.Emit (OpCodes.Ldloc, temp);
4095                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
4096                         ig.EndExceptionBlock ();
4097                         
4098                         return val;
4099                 }
4100         }
4101
4102         public class Unchecked : Statement {
4103                 public readonly Block Block;
4104                 
4105                 public Unchecked (Block b)
4106                 {
4107                         Block = b;
4108                 }
4109
4110                 public override bool Resolve (EmitContext ec)
4111                 {
4112                         return Block.Resolve (ec);
4113                 }
4114                 
4115                 protected override bool DoEmit (EmitContext ec)
4116                 {
4117                         bool previous_state = ec.CheckState;
4118                         bool previous_state_const = ec.ConstantCheckState;
4119                         bool val;
4120                         
4121                         ec.CheckState = false;
4122                         ec.ConstantCheckState = false;
4123                         val = Block.Emit (ec);
4124                         ec.CheckState = previous_state;
4125                         ec.ConstantCheckState = previous_state_const;
4126
4127                         return val;
4128                 }
4129         }
4130
4131         public class Checked : Statement {
4132                 public readonly Block Block;
4133                 
4134                 public Checked (Block b)
4135                 {
4136                         Block = b;
4137                 }
4138
4139                 public override bool Resolve (EmitContext ec)
4140                 {
4141                         bool previous_state = ec.CheckState;
4142                         bool previous_state_const = ec.ConstantCheckState;
4143                         
4144                         ec.CheckState = true;
4145                         ec.ConstantCheckState = true;
4146                         bool ret = Block.Resolve (ec);
4147                         ec.CheckState = previous_state;
4148                         ec.ConstantCheckState = previous_state_const;
4149
4150                         return ret;
4151                 }
4152
4153                 protected override bool DoEmit (EmitContext ec)
4154                 {
4155                         bool previous_state = ec.CheckState;
4156                         bool previous_state_const = ec.ConstantCheckState;
4157                         bool val;
4158                         
4159                         ec.CheckState = true;
4160                         ec.ConstantCheckState = true;
4161                         val = Block.Emit (ec);
4162                         ec.CheckState = previous_state;
4163                         ec.ConstantCheckState = previous_state_const;
4164
4165                         return val;
4166                 }
4167         }
4168
4169         public class Unsafe : Statement {
4170                 public readonly Block Block;
4171
4172                 public Unsafe (Block b)
4173                 {
4174                         Block = b;
4175                 }
4176
4177                 public override bool Resolve (EmitContext ec)
4178                 {
4179                         bool previous_state = ec.InUnsafe;
4180                         bool val;
4181                         
4182                         ec.InUnsafe = true;
4183                         val = Block.Resolve (ec);
4184                         ec.InUnsafe = previous_state;
4185
4186                         return val;
4187                 }
4188                 
4189                 protected override bool DoEmit (EmitContext ec)
4190                 {
4191                         bool previous_state = ec.InUnsafe;
4192                         bool val;
4193                         
4194                         ec.InUnsafe = true;
4195                         val = Block.Emit (ec);
4196                         ec.InUnsafe = previous_state;
4197
4198                         return val;
4199                 }
4200         }
4201
4202         // 
4203         // Fixed statement
4204         //
4205         public class Fixed : Statement {
4206                 Expression type;
4207                 ArrayList declarators;
4208                 Statement statement;
4209                 Type expr_type;
4210                 FixedData[] data;
4211
4212                 struct FixedData {
4213                         public bool is_object;
4214                         public VariableInfo vi;
4215                         public Expression expr;
4216                         public Expression converted;
4217                 }                       
4218
4219                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4220                 {
4221                         this.type = type;
4222                         declarators = decls;
4223                         statement = stmt;
4224                         loc = l;
4225                 }
4226
4227                 public override bool Resolve (EmitContext ec)
4228                 {
4229                         expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4230                         if (expr_type == null)
4231                                 return false;
4232
4233                         data = new FixedData [declarators.Count];
4234
4235                         int i = 0;
4236                         foreach (Pair p in declarators){
4237                                 VariableInfo vi = (VariableInfo) p.First;
4238                                 Expression e = (Expression) p.Second;
4239
4240                                 vi.Number = -1;
4241
4242                                 //
4243                                 // The rules for the possible declarators are pretty wise,
4244                                 // but the production on the grammar is more concise.
4245                                 //
4246                                 // So we have to enforce these rules here.
4247                                 //
4248                                 // We do not resolve before doing the case 1 test,
4249                                 // because the grammar is explicit in that the token &
4250                                 // is present, so we need to test for this particular case.
4251                                 //
4252
4253                                 //
4254                                 // Case 1: & object.
4255                                 //
4256                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4257                                         Expression child = ((Unary) e).Expr;
4258
4259                                         vi.MakePinned ();
4260                                         if (child is ParameterReference || child is LocalVariableReference){
4261                                                 Report.Error (
4262                                                         213, loc, 
4263                                                         "No need to use fixed statement for parameters or " +
4264                                                         "local variable declarations (address is already " +
4265                                                         "fixed)");
4266                                                 return false;
4267                                         }
4268                                         
4269                                         e = e.Resolve (ec);
4270                                         if (e == null)
4271                                                 return false;
4272
4273                                         child = ((Unary) e).Expr;
4274                                         
4275                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
4276                                                 return false;
4277
4278                                         data [i].is_object = true;
4279                                         data [i].expr = e;
4280                                         data [i].converted = null;
4281                                         data [i].vi = vi;
4282                                         i++;
4283
4284                                         continue;
4285                                 }
4286
4287                                 e = e.Resolve (ec);
4288                                 if (e == null)
4289                                         return false;
4290
4291                                 //
4292                                 // Case 2: Array
4293                                 //
4294                                 if (e.Type.IsArray){
4295                                         Type array_type = e.Type.GetElementType ();
4296                                         
4297                                         vi.MakePinned ();
4298                                         //
4299                                         // Provided that array_type is unmanaged,
4300                                         //
4301                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
4302                                                 return false;
4303
4304                                         //
4305                                         // and T* is implicitly convertible to the
4306                                         // pointer type given in the fixed statement.
4307                                         //
4308                                         ArrayPtr array_ptr = new ArrayPtr (e, loc);
4309                                         
4310                                         Expression converted = Expression.ConvertImplicitRequired (
4311                                                 ec, array_ptr, vi.VariableType, loc);
4312                                         if (converted == null)
4313                                                 return false;
4314
4315                                         data [i].is_object = false;
4316                                         data [i].expr = e;
4317                                         data [i].converted = converted;
4318                                         data [i].vi = vi;
4319                                         i++;
4320
4321                                         continue;
4322                                 }
4323
4324                                 //
4325                                 // Case 3: string
4326                                 //
4327                                 if (e.Type == TypeManager.string_type){
4328                                         data [i].is_object = false;
4329                                         data [i].expr = e;
4330                                         data [i].converted = null;
4331                                         data [i].vi = vi;
4332                                         i++;
4333                                 }
4334                         }
4335
4336                         return statement.Resolve (ec);
4337                 }
4338                 
4339                 protected override bool DoEmit (EmitContext ec)
4340                 {
4341                         ILGenerator ig = ec.ig;
4342
4343                         bool is_ret = false;
4344
4345                         for (int i = 0; i < data.Length; i++) {
4346                                 VariableInfo vi = data [i].vi;
4347
4348                                 //
4349                                 // Case 1: & object.
4350                                 //
4351                                 if (data [i].is_object) {
4352                                         //
4353                                         // Store pointer in pinned location
4354                                         //
4355                                         data [i].expr.Emit (ec);
4356                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4357
4358                                         is_ret = statement.Emit (ec);
4359
4360                                         // Clear the pinned variable.
4361                                         ig.Emit (OpCodes.Ldc_I4_0);
4362                                         ig.Emit (OpCodes.Conv_U);
4363                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4364
4365                                         continue;
4366                                 }
4367
4368                                 //
4369                                 // Case 2: Array
4370                                 //
4371                                 if (data [i].expr.Type.IsArray){
4372                                         //
4373                                         // Store pointer in pinned location
4374                                         //
4375                                         data [i].converted.Emit (ec);
4376                                         
4377                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4378
4379                                         is_ret = statement.Emit (ec);
4380                                         
4381                                         // Clear the pinned variable.
4382                                         ig.Emit (OpCodes.Ldc_I4_0);
4383                                         ig.Emit (OpCodes.Conv_U);
4384                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4385
4386                                         continue;
4387                                 }
4388
4389                                 //
4390                                 // Case 3: string
4391                                 //
4392                                 if (data [i].expr.Type == TypeManager.string_type){
4393                                         LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4394                                         TypeManager.MakePinned (pinned_string);
4395                                         
4396                                         data [i].expr.Emit (ec);
4397                                         ig.Emit (OpCodes.Stloc, pinned_string);
4398
4399                                         Expression sptr = new StringPtr (pinned_string, loc);
4400                                         Expression converted = Expression.ConvertImplicitRequired (
4401                                                 ec, sptr, vi.VariableType, loc);
4402                                         
4403                                         if (converted == null)
4404                                                 continue;
4405
4406                                         converted.Emit (ec);
4407                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4408                                         
4409                                         is_ret = statement.Emit (ec);
4410
4411                                         // Clear the pinned variable
4412                                         ig.Emit (OpCodes.Ldnull);
4413                                         ig.Emit (OpCodes.Stloc, pinned_string);
4414                                 }
4415                         }
4416
4417                         return is_ret;
4418                 }
4419         }
4420         
4421         public class Catch {
4422                 public readonly string Name;
4423                 public readonly Block  Block;
4424                 public readonly Location Location;
4425
4426                 Expression type_expr;
4427                 Type type;
4428                 
4429                 public Catch (Expression type, string name, Block block, Location l)
4430                 {
4431                         type_expr = type;
4432                         Name = name;
4433                         Block = block;
4434                         Location = l;
4435                 }
4436
4437                 public Type CatchType {
4438                         get {
4439                                 return type;
4440                         }
4441                 }
4442
4443                 public bool IsGeneral {
4444                         get {
4445                                 return type_expr == null;
4446                         }
4447                 }
4448
4449                 public bool Resolve (EmitContext ec)
4450                 {
4451                         if (type_expr != null) {
4452                                 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4453                                 if (type == null)
4454                                         return false;
4455
4456                                 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4457                                         Report.Error (155, Location,
4458                                                       "The type caught or thrown must be derived " +
4459                                                       "from System.Exception");
4460                                         return false;
4461                                 }
4462                         } else
4463                                 type = null;
4464
4465                         if (!Block.Resolve (ec))
4466                                 return false;
4467
4468                         return true;
4469                 }
4470         }
4471
4472         public class Try : Statement {
4473                 public readonly Block Fini, Block;
4474                 public readonly ArrayList Specific;
4475                 public readonly Catch General;
4476                 
4477                 //
4478                 // specific, general and fini might all be null.
4479                 //
4480                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4481                 {
4482                         if (specific == null && general == null){
4483                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4484                         }
4485                         
4486                         this.Block = block;
4487                         this.Specific = specific;
4488                         this.General = general;
4489                         this.Fini = fini;
4490                         loc = l;
4491                 }
4492
4493                 public override bool Resolve (EmitContext ec)
4494                 {
4495                         bool ok = true;
4496                         
4497                         ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4498
4499                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4500
4501                         bool old_in_try = ec.InTry;
4502                         ec.InTry = true;
4503
4504                         if (!Block.Resolve (ec))
4505                                 ok = false;
4506
4507                         ec.InTry = old_in_try;
4508
4509                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4510
4511                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
4512
4513                         foreach (Catch c in Specific){
4514                                 ec.CurrentBranching.CreateSibling ();
4515                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4516
4517                                 if (c.Name != null) {
4518                                         VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4519                                         if (vi == null)
4520                                                 throw new Exception ();
4521
4522                                         vi.Number = -1;
4523                                 }
4524
4525                                 bool old_in_catch = ec.InCatch;
4526                                 ec.InCatch = true;
4527
4528                                 if (!c.Resolve (ec))
4529                                         ok = false;
4530
4531                                 ec.InCatch = old_in_catch;
4532
4533                                 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4534
4535                                 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4536                                         vector.AndLocals (current);
4537                         }
4538
4539                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4540
4541                         if (General != null){
4542                                 ec.CurrentBranching.CreateSibling ();
4543                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4544
4545                                 bool old_in_catch = ec.InCatch;
4546                                 ec.InCatch = true;
4547
4548                                 if (!General.Resolve (ec))
4549                                         ok = false;
4550
4551                                 ec.InCatch = old_in_catch;
4552
4553                                 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4554
4555                                 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4556                                         vector.AndLocals (current);
4557                         }
4558
4559                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4560
4561                         if (Fini != null) {
4562                                 ec.CurrentBranching.CreateSiblingForFinally ();
4563                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4564
4565                                 bool old_in_finally = ec.InFinally;
4566                                 ec.InFinally = true;
4567
4568                                 if (!Fini.Resolve (ec))
4569                                         ok = false;
4570
4571                                 ec.InFinally = old_in_finally;
4572                         }
4573
4574                         FlowReturns returns = ec.EndFlowBranching ();
4575
4576                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4577
4578                         Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4579
4580                         if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4581                                 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4582                         }
4583
4584                         ec.CurrentBranching.CurrentUsageVector.Or (vector);
4585
4586                         Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4587
4588                         return ok;
4589                 }
4590                 
4591                 protected override bool DoEmit (EmitContext ec)
4592                 {
4593                         ILGenerator ig = ec.ig;
4594                         Label end;
4595                         Label finish = ig.DefineLabel ();;
4596                         bool returns;
4597
4598                         ec.TryCatchLevel++;
4599                         end = ig.BeginExceptionBlock ();
4600                         bool old_in_try = ec.InTry;
4601                         ec.InTry = true;
4602                         returns = Block.Emit (ec);
4603                         ec.InTry = old_in_try;
4604
4605                         //
4606                         // System.Reflection.Emit provides this automatically:
4607                         // ig.Emit (OpCodes.Leave, finish);
4608
4609                         bool old_in_catch = ec.InCatch;
4610                         ec.InCatch = true;
4611                         DeclSpace ds = ec.DeclSpace;
4612
4613                         foreach (Catch c in Specific){
4614                                 VariableInfo vi;
4615                                 
4616                                 ig.BeginCatchBlock (c.CatchType);
4617
4618                                 if (c.Name != null){
4619                                         vi = c.Block.GetVariableInfo (c.Name);
4620                                         if (vi == null)
4621                                                 throw new Exception ("Variable does not exist in this block");
4622
4623                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4624                                 } else
4625                                         ig.Emit (OpCodes.Pop);
4626                                 
4627                                 if (!c.Block.Emit (ec))
4628                                         returns = false;
4629                         }
4630
4631                         if (General != null){
4632                                 ig.BeginCatchBlock (TypeManager.object_type);
4633                                 ig.Emit (OpCodes.Pop);
4634                                 if (!General.Block.Emit (ec))
4635                                         returns = false;
4636                         }
4637                         ec.InCatch = old_in_catch;
4638
4639                         ig.MarkLabel (finish);
4640                         if (Fini != null){
4641                                 ig.BeginFinallyBlock ();
4642                                 bool old_in_finally = ec.InFinally;
4643                                 ec.InFinally = true;
4644                                 Fini.Emit (ec);
4645                                 ec.InFinally = old_in_finally;
4646                         }
4647                         
4648                         ig.EndExceptionBlock ();
4649                         ec.TryCatchLevel--;
4650
4651                         if (!returns || ec.InTry || ec.InCatch)
4652                                 return returns;
4653
4654                         // Unfortunately, System.Reflection.Emit automatically emits a leave
4655                         // to the end of the finally block.  This is a problem if `returns'
4656                         // is true since we may jump to a point after the end of the method.
4657                         // As a workaround, emit an explicit ret here.
4658
4659                         if (ec.ReturnType != null)
4660                                 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4661                         ec.ig.Emit (OpCodes.Ret);
4662
4663                         return true;
4664                 }
4665         }
4666
4667         public class Using : Statement {
4668                 object expression_or_block;
4669                 Statement Statement;
4670                 ArrayList var_list;
4671                 Expression expr;
4672                 Type expr_type;
4673                 Expression conv;
4674                 Expression [] converted_vars;
4675                 ExpressionStatement [] assign;
4676                 
4677                 public Using (object expression_or_block, Statement stmt, Location l)
4678                 {
4679                         this.expression_or_block = expression_or_block;
4680                         Statement = stmt;
4681                         loc = l;
4682                 }
4683
4684                 //
4685                 // Resolves for the case of using using a local variable declaration.
4686                 //
4687                 bool ResolveLocalVariableDecls (EmitContext ec)
4688                 {
4689                         bool need_conv = false;
4690                         expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4691                         int i = 0;
4692
4693                         if (expr_type == null)
4694                                 return false;
4695
4696                         //
4697                         // The type must be an IDisposable or an implicit conversion
4698                         // must exist.
4699                         //
4700                         converted_vars = new Expression [var_list.Count];
4701                         assign = new ExpressionStatement [var_list.Count];
4702                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4703                                 foreach (DictionaryEntry e in var_list){
4704                                         Expression var = (Expression) e.Key;
4705
4706                                         var = var.ResolveLValue (ec, new EmptyExpression ());
4707                                         if (var == null)
4708                                                 return false;
4709                                         
4710                                         converted_vars [i] = Expression.ConvertImplicitRequired (
4711                                                 ec, var, TypeManager.idisposable_type, loc);
4712
4713                                         if (converted_vars [i] == null)
4714                                                 return false;
4715                                         i++;
4716                                 }
4717                                 need_conv = true;
4718                         }
4719
4720                         i = 0;
4721                         foreach (DictionaryEntry e in var_list){
4722                                 LocalVariableReference var = (LocalVariableReference) e.Key;
4723                                 Expression new_expr = (Expression) e.Value;
4724                                 Expression a;
4725
4726                                 a = new Assign (var, new_expr, loc);
4727                                 a = a.Resolve (ec);
4728                                 if (a == null)
4729                                         return false;
4730
4731                                 if (!need_conv)
4732                                         converted_vars [i] = var;
4733                                 assign [i] = (ExpressionStatement) a;
4734                                 i++;
4735                         }
4736
4737                         return true;
4738                 }
4739
4740                 bool ResolveExpression (EmitContext ec)
4741                 {
4742                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4743                                 conv = Expression.ConvertImplicitRequired (
4744                                         ec, expr, TypeManager.idisposable_type, loc);
4745
4746                                 if (conv == null)
4747                                         return false;
4748                         }
4749
4750                         return true;
4751                 }
4752                 
4753                 //
4754                 // Emits the code for the case of using using a local variable declaration.
4755                 //
4756                 bool EmitLocalVariableDecls (EmitContext ec)
4757                 {
4758                         ILGenerator ig = ec.ig;
4759                         int i = 0;
4760
4761                         bool old_in_try = ec.InTry;
4762                         ec.InTry = true;
4763                         for (i = 0; i < assign.Length; i++) {
4764                                 assign [i].EmitStatement (ec);
4765                                 
4766                                 ig.BeginExceptionBlock ();
4767                         }
4768                         Statement.Emit (ec);
4769                         ec.InTry = old_in_try;
4770
4771                         bool old_in_finally = ec.InFinally;
4772                         ec.InFinally = true;
4773                         var_list.Reverse ();
4774                         foreach (DictionaryEntry e in var_list){
4775                                 LocalVariableReference var = (LocalVariableReference) e.Key;
4776                                 Label skip = ig.DefineLabel ();
4777                                 i--;
4778                                 
4779                                 ig.BeginFinallyBlock ();
4780                                 
4781                                 var.Emit (ec);
4782                                 ig.Emit (OpCodes.Brfalse, skip);
4783                                 converted_vars [i].Emit (ec);
4784                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4785                                 ig.MarkLabel (skip);
4786                                 ig.EndExceptionBlock ();
4787                         }
4788                         ec.InFinally = old_in_finally;
4789
4790                         return false;
4791                 }
4792
4793                 bool EmitExpression (EmitContext ec)
4794                 {
4795                         //
4796                         // Make a copy of the expression and operate on that.
4797                         //
4798                         ILGenerator ig = ec.ig;
4799                         LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4800                         if (conv != null)
4801                                 conv.Emit (ec);
4802                         else
4803                                 expr.Emit (ec);
4804                         ig.Emit (OpCodes.Stloc, local_copy);
4805
4806                         bool old_in_try = ec.InTry;
4807                         ec.InTry = true;
4808                         ig.BeginExceptionBlock ();
4809                         Statement.Emit (ec);
4810                         ec.InTry = old_in_try;
4811                         
4812                         Label skip = ig.DefineLabel ();
4813                         bool old_in_finally = ec.InFinally;
4814                         ig.BeginFinallyBlock ();
4815                         ig.Emit (OpCodes.Ldloc, local_copy);
4816                         ig.Emit (OpCodes.Brfalse, skip);
4817                         ig.Emit (OpCodes.Ldloc, local_copy);
4818                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4819                         ig.MarkLabel (skip);
4820                         ec.InFinally = old_in_finally;
4821                         ig.EndExceptionBlock ();
4822
4823                         return false;
4824                 }
4825                 
4826                 public override bool Resolve (EmitContext ec)
4827                 {
4828                         if (expression_or_block is DictionaryEntry){
4829                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4830                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4831
4832                                 if (!ResolveLocalVariableDecls (ec))
4833                                         return false;
4834
4835                         } else if (expression_or_block is Expression){
4836                                 expr = (Expression) expression_or_block;
4837
4838                                 expr = expr.Resolve (ec);
4839                                 if (expr == null)
4840                                         return false;
4841
4842                                 expr_type = expr.Type;
4843
4844                                 if (!ResolveExpression (ec))
4845                                         return false;
4846                         }                       
4847
4848                         return Statement.Resolve (ec);
4849                 }
4850                 
4851                 protected override bool DoEmit (EmitContext ec)
4852                 {
4853                         if (expression_or_block is DictionaryEntry)
4854                                 return EmitLocalVariableDecls (ec);
4855                         else if (expression_or_block is Expression)
4856                                 return EmitExpression (ec);
4857
4858                         return false;
4859                 }
4860         }
4861
4862         /// <summary>
4863         ///   Implementation of the foreach C# statement
4864         /// </summary>
4865         public class Foreach : Statement {
4866                 Expression type;
4867                 LocalVariableReference variable;
4868                 Expression expr;
4869                 Statement statement;
4870                 ForeachHelperMethods hm;
4871                 Expression empty, conv;
4872                 Type array_type, element_type;
4873                 Type var_type;
4874                 
4875                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4876                                 Statement stmt, Location l)
4877                 {
4878                         if (type != null) {
4879                                 this.type = type;
4880                         }
4881                         else
4882                         {
4883                                 VariableInfo vi = var.VariableInfo;
4884                                 this.type = vi.Type;
4885                         }
4886                         this.variable = var;
4887                         this.expr = expr;
4888                         statement = stmt;
4889                         loc = l;
4890                 }
4891                 
4892                 public override bool Resolve (EmitContext ec)
4893                 {
4894                         expr = expr.Resolve (ec);
4895                         if (expr == null)
4896                                 return false;
4897
4898                         var_type = ec.DeclSpace.ResolveType (type, false, loc);
4899                         if (var_type == null)
4900                                 return false;
4901                         
4902                         //
4903                         // We need an instance variable.  Not sure this is the best
4904                         // way of doing this.
4905                         //
4906                         // FIXME: When we implement propertyaccess, will those turn
4907                         // out to return values in ExprClass?  I think they should.
4908                         //
4909                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4910                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4911                                 error1579 (expr.Type);
4912                                 return false;
4913                         }
4914
4915                         if (expr.Type.IsArray) {
4916                                 array_type = expr.Type;
4917                                 element_type = array_type.GetElementType ();
4918
4919                                 empty = new EmptyExpression (element_type);
4920                         } else {
4921                                 hm = ProbeCollectionType (ec, expr.Type);
4922                                 if (hm == null){
4923                                         error1579 (expr.Type);
4924                                         return false;
4925                                 }
4926
4927                                 array_type = expr.Type;
4928                                 element_type = hm.element_type;
4929
4930                                 empty = new EmptyExpression (hm.element_type);
4931                         }
4932
4933                         ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
4934                         ec.CurrentBranching.CreateSibling ();
4935
4936                         //
4937                         //
4938                         // FIXME: maybe we can apply the same trick we do in the
4939                         // array handling to avoid creating empty and conv in some cases.
4940                         //
4941                         // Although it is not as important in this case, as the type
4942                         // will not likely be object (what the enumerator will return).
4943                         //
4944                         conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4945                         if (conv == null)
4946                                 return false;
4947
4948                         if (variable.ResolveLValue (ec, empty) == null)
4949                                 return false;
4950
4951                         if (!statement.Resolve (ec))
4952                                 return false;
4953
4954                         FlowReturns returns = ec.EndFlowBranching ();
4955
4956                         return true;
4957                 }
4958                 
4959                 //
4960                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4961                 //
4962                 static MethodInfo FetchMethodMoveNext (Type t)
4963                 {
4964                         MemberList move_next_list;
4965                         
4966                         move_next_list = TypeContainer.FindMembers (
4967                                 t, MemberTypes.Method,
4968                                 BindingFlags.Public | BindingFlags.Instance,
4969                                 Type.FilterName, "MoveNext");
4970                         if (move_next_list.Count == 0)
4971                                 return null;
4972
4973                         foreach (MemberInfo m in move_next_list){
4974                                 MethodInfo mi = (MethodInfo) m;
4975                                 Type [] args;
4976                                 
4977                                 args = TypeManager.GetArgumentTypes (mi);
4978                                 if (args != null && args.Length == 0){
4979                                         if (mi.ReturnType == TypeManager.bool_type)
4980                                                 return mi;
4981                                 }
4982                         }
4983                         return null;
4984                 }
4985                 
4986                 //
4987                 // Retrieves a `public T get_Current ()' method from the Type `t'
4988                 //
4989                 static MethodInfo FetchMethodGetCurrent (Type t)
4990                 {
4991                         MemberList move_next_list;
4992                         
4993                         move_next_list = TypeContainer.FindMembers (
4994                                 t, MemberTypes.Method,
4995                                 BindingFlags.Public | BindingFlags.Instance,
4996                                 Type.FilterName, "get_Current");
4997                         if (move_next_list.Count == 0)
4998                                 return null;
4999
5000                         foreach (MemberInfo m in move_next_list){
5001                                 MethodInfo mi = (MethodInfo) m;
5002                                 Type [] args;
5003
5004                                 args = TypeManager.GetArgumentTypes (mi);
5005                                 if (args != null && args.Length == 0)
5006                                         return mi;
5007                         }
5008                         return null;
5009                 }
5010
5011                 // 
5012                 // This struct records the helper methods used by the Foreach construct
5013                 //
5014                 class ForeachHelperMethods {
5015                         public EmitContext ec;
5016                         public MethodInfo get_enumerator;
5017                         public MethodInfo move_next;
5018                         public MethodInfo get_current;
5019                         public Type element_type;
5020                         public Type enumerator_type;
5021                         public bool is_disposable;
5022
5023                         public ForeachHelperMethods (EmitContext ec)
5024                         {
5025                                 this.ec = ec;
5026                                 this.element_type = TypeManager.object_type;
5027                                 this.enumerator_type = TypeManager.ienumerator_type;
5028                                 this.is_disposable = true;
5029                         }
5030                 }
5031                 
5032                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
5033                 {
5034                         if (m == null)
5035                                 return false;
5036                         
5037                         if (!(m is MethodInfo))
5038                                 return false;
5039                         
5040                         if (m.Name != "GetEnumerator")
5041                                 return false;
5042
5043                         MethodInfo mi = (MethodInfo) m;
5044                         Type [] args = TypeManager.GetArgumentTypes (mi);
5045                         if (args != null){
5046                                 if (args.Length != 0)
5047                                         return false;
5048                         }
5049                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
5050                         EmitContext ec = hm.ec;
5051
5052                         //
5053                         // Check whether GetEnumerator is accessible to us
5054                         //
5055                         MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5056
5057                         Type declaring = mi.DeclaringType;
5058                         if (prot == MethodAttributes.Private){
5059                                 if (declaring != ec.ContainerType)
5060                                         return false;
5061                         } else if (prot == MethodAttributes.FamANDAssem){
5062                                 // If from a different assembly, false
5063                                 if (!(mi is MethodBuilder))
5064                                         return false;
5065                                 //
5066                                 // Are we being invoked from the same class, or from a derived method?
5067                                 //
5068                                 if (ec.ContainerType != declaring){
5069                                         if (!ec.ContainerType.IsSubclassOf (declaring))
5070                                                 return false;
5071                                 }
5072                         } else if (prot == MethodAttributes.FamORAssem){
5073                                 if (!(mi is MethodBuilder ||
5074                                       ec.ContainerType == declaring ||
5075                                       ec.ContainerType.IsSubclassOf (declaring)))
5076                                         return false;
5077                         } if (prot == MethodAttributes.Family){
5078                                 if (!(ec.ContainerType == declaring ||
5079                                       ec.ContainerType.IsSubclassOf (declaring)))
5080                                         return false;
5081                         }
5082
5083                         //
5084                         // Ok, we can access it, now make sure that we can do something
5085                         // with this `GetEnumerator'
5086                         //
5087
5088                         if (mi.ReturnType == TypeManager.ienumerator_type ||
5089                             TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
5090                             (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
5091                                 hm.move_next = TypeManager.bool_movenext_void;
5092                                 hm.get_current = TypeManager.object_getcurrent_void;
5093                                 return true;
5094                         }
5095
5096                         //
5097                         // Ok, so they dont return an IEnumerable, we will have to
5098                         // find if they support the GetEnumerator pattern.
5099                         //
5100                         Type return_type = mi.ReturnType;
5101
5102                         hm.move_next = FetchMethodMoveNext (return_type);
5103                         if (hm.move_next == null)
5104                                 return false;
5105                         hm.get_current = FetchMethodGetCurrent (return_type);
5106                         if (hm.get_current == null)
5107                                 return false;
5108
5109                         hm.element_type = hm.get_current.ReturnType;
5110                         hm.enumerator_type = return_type;
5111                         hm.is_disposable = TypeManager.ImplementsInterface (
5112                                 hm.enumerator_type, TypeManager.idisposable_type);
5113
5114                         return true;
5115                 }
5116                 
5117                 /// <summary>
5118                 ///   This filter is used to find the GetEnumerator method
5119                 ///   on which IEnumerator operates
5120                 /// </summary>
5121                 static MemberFilter FilterEnumerator;
5122                 
5123                 static Foreach ()
5124                 {
5125                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5126                 }
5127
5128                 void error1579 (Type t)
5129                 {
5130                         Report.Error (1579, loc,
5131                                       "foreach statement cannot operate on variables of type `" +
5132                                       t.FullName + "' because that class does not provide a " +
5133                                       " GetEnumerator method or it is inaccessible");
5134                 }
5135
5136                 static bool TryType (Type t, ForeachHelperMethods hm)
5137                 {
5138                         MemberList mi;
5139                         
5140                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5141                                                         BindingFlags.Public | BindingFlags.NonPublic |
5142                                                         BindingFlags.Instance,
5143                                                         FilterEnumerator, hm);
5144
5145                         if (mi.Count == 0)
5146                                 return false;
5147
5148                         hm.get_enumerator = (MethodInfo) mi [0];
5149                         return true;    
5150                 }
5151                 
5152                 //
5153                 // Looks for a usable GetEnumerator in the Type, and if found returns
5154                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5155                 //
5156                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5157                 {
5158                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5159
5160                         if (TryType (t, hm))
5161                                 return hm;
5162
5163                         //
5164                         // Now try to find the method in the interfaces
5165                         //
5166                         while (t != null){
5167                                 Type [] ifaces = t.GetInterfaces ();
5168
5169                                 foreach (Type i in ifaces){
5170                                         if (TryType (i, hm))
5171                                                 return hm;
5172                                 }
5173                                 
5174                                 //
5175                                 // Since TypeBuilder.GetInterfaces only returns the interface
5176                                 // types for this type, we have to keep looping, but once
5177                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5178                                 // done, because it returns all the types
5179                                 //
5180                                 if ((t is TypeBuilder))
5181                                         t = t.BaseType;
5182                                 else
5183                                         break;
5184                         } 
5185
5186                         return null;
5187                 }
5188
5189                 //
5190                 // FIXME: possible optimization.
5191                 // We might be able to avoid creating `empty' if the type is the sam
5192                 //
5193                 bool EmitCollectionForeach (EmitContext ec)
5194                 {
5195                         ILGenerator ig = ec.ig;
5196                         LocalBuilder enumerator, disposable;
5197
5198                         enumerator = ig.DeclareLocal (hm.enumerator_type);
5199                         if (hm.is_disposable)
5200                                 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5201                         else
5202                                 disposable = null;
5203                         
5204                         //
5205                         // Instantiate the enumerator
5206                         //
5207                         if (expr.Type.IsValueType){
5208                                 if (expr is IMemoryLocation){
5209                                         IMemoryLocation ml = (IMemoryLocation) expr;
5210
5211                                         ml.AddressOf (ec, AddressOp.Load);
5212                                 } else
5213                                         throw new Exception ("Expr " + expr + " of type " + expr.Type +
5214                                                              " does not implement IMemoryLocation");
5215                                 ig.Emit (OpCodes.Call, hm.get_enumerator);
5216                         } else {
5217                                 expr.Emit (ec);
5218                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5219                         }
5220                         ig.Emit (OpCodes.Stloc, enumerator);
5221
5222                         //
5223                         // Protect the code in a try/finalize block, so that
5224                         // if the beast implement IDisposable, we get rid of it
5225                         //
5226                         Label l;
5227                         bool old_in_try = ec.InTry;
5228
5229                         if (hm.is_disposable) {
5230                                 l = ig.BeginExceptionBlock ();
5231                                 ec.InTry = true;
5232                         }
5233                         
5234                         Label end_try = ig.DefineLabel ();
5235                         
5236                         ig.MarkLabel (ec.LoopBegin);
5237                         ig.Emit (OpCodes.Ldloc, enumerator);
5238                         ig.Emit (OpCodes.Callvirt, hm.move_next);
5239                         ig.Emit (OpCodes.Brfalse, end_try);
5240                         ig.Emit (OpCodes.Ldloc, enumerator);
5241                         ig.Emit (OpCodes.Callvirt, hm.get_current);
5242                         variable.EmitAssign (ec, conv);
5243                         statement.Emit (ec);
5244                         ig.Emit (OpCodes.Br, ec.LoopBegin);
5245                         ig.MarkLabel (end_try);
5246                         ec.InTry = old_in_try;
5247                         
5248                         // The runtime provides this for us.
5249                         // ig.Emit (OpCodes.Leave, end);
5250
5251                         //
5252                         // Now the finally block
5253                         //
5254                         if (hm.is_disposable) {
5255                                 Label end_finally = ig.DefineLabel ();
5256                                 bool old_in_finally = ec.InFinally;
5257                                 ec.InFinally = true;
5258                                 ig.BeginFinallyBlock ();
5259                         
5260                                 ig.Emit (OpCodes.Ldloc, enumerator);
5261                                 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5262                                 ig.Emit (OpCodes.Stloc, disposable);
5263                                 ig.Emit (OpCodes.Ldloc, disposable);
5264                                 ig.Emit (OpCodes.Brfalse, end_finally);
5265                                 ig.Emit (OpCodes.Ldloc, disposable);
5266                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5267                                 ig.MarkLabel (end_finally);
5268                                 ec.InFinally = old_in_finally;
5269
5270                                 // The runtime generates this anyways.
5271                                 // ig.Emit (OpCodes.Endfinally);
5272
5273                                 ig.EndExceptionBlock ();
5274                         }
5275
5276                         ig.MarkLabel (ec.LoopEnd);
5277                         return false;
5278                 }
5279
5280                 //
5281                 // FIXME: possible optimization.
5282                 // We might be able to avoid creating `empty' if the type is the sam
5283                 //
5284                 bool EmitArrayForeach (EmitContext ec)
5285                 {
5286                         int rank = array_type.GetArrayRank ();
5287                         ILGenerator ig = ec.ig;
5288
5289                         LocalBuilder copy = ig.DeclareLocal (array_type);
5290                         
5291                         //
5292                         // Make our copy of the array
5293                         //
5294                         expr.Emit (ec);
5295                         ig.Emit (OpCodes.Stloc, copy);
5296                         
5297                         if (rank == 1){
5298                                 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5299
5300                                 Label loop, test;
5301                                 
5302                                 ig.Emit (OpCodes.Ldc_I4_0);
5303                                 ig.Emit (OpCodes.Stloc, counter);
5304                                 test = ig.DefineLabel ();
5305                                 ig.Emit (OpCodes.Br, test);
5306
5307                                 loop = ig.DefineLabel ();
5308                                 ig.MarkLabel (loop);
5309
5310                                 ig.Emit (OpCodes.Ldloc, copy);
5311                                 ig.Emit (OpCodes.Ldloc, counter);
5312                                 ArrayAccess.EmitLoadOpcode (ig, var_type);
5313
5314                                 variable.EmitAssign (ec, conv);
5315
5316                                 statement.Emit (ec);
5317
5318                                 ig.MarkLabel (ec.LoopBegin);
5319                                 ig.Emit (OpCodes.Ldloc, counter);
5320                                 ig.Emit (OpCodes.Ldc_I4_1);
5321                                 ig.Emit (OpCodes.Add);
5322                                 ig.Emit (OpCodes.Stloc, counter);
5323
5324                                 ig.MarkLabel (test);
5325                                 ig.Emit (OpCodes.Ldloc, counter);
5326                                 ig.Emit (OpCodes.Ldloc, copy);
5327                                 ig.Emit (OpCodes.Ldlen);
5328                                 ig.Emit (OpCodes.Conv_I4);
5329                                 ig.Emit (OpCodes.Blt, loop);
5330                         } else {
5331                                 LocalBuilder [] dim_len   = new LocalBuilder [rank];
5332                                 LocalBuilder [] dim_count = new LocalBuilder [rank];
5333                                 Label [] loop = new Label [rank];
5334                                 Label [] test = new Label [rank];
5335                                 int dim;
5336                                 
5337                                 for (dim = 0; dim < rank; dim++){
5338                                         dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5339                                         dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5340                                         test [dim] = ig.DefineLabel ();
5341                                         loop [dim] = ig.DefineLabel ();
5342                                 }
5343                                         
5344                                 for (dim = 0; dim < rank; dim++){
5345                                         ig.Emit (OpCodes.Ldloc, copy);
5346                                         IntLiteral.EmitInt (ig, dim);
5347                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5348                                         ig.Emit (OpCodes.Stloc, dim_len [dim]);
5349                                 }
5350
5351                                 for (dim = 0; dim < rank; dim++){
5352                                         ig.Emit (OpCodes.Ldc_I4_0);
5353                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
5354                                         ig.Emit (OpCodes.Br, test [dim]);
5355                                         ig.MarkLabel (loop [dim]);
5356                                 }
5357
5358                                 ig.Emit (OpCodes.Ldloc, copy);
5359                                 for (dim = 0; dim < rank; dim++)
5360                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5361
5362                                 //
5363                                 // FIXME: Maybe we can cache the computation of `get'?
5364                                 //
5365                                 Type [] args = new Type [rank];
5366                                 MethodInfo get;
5367
5368                                 for (int i = 0; i < rank; i++)
5369                                         args [i] = TypeManager.int32_type;
5370
5371                                 ModuleBuilder mb = CodeGen.ModuleBuilder;
5372                                 get = mb.GetArrayMethod (
5373                                         array_type, "Get",
5374                                         CallingConventions.HasThis| CallingConventions.Standard,
5375                                         var_type, args);
5376                                 ig.Emit (OpCodes.Call, get);
5377                                 variable.EmitAssign (ec, conv);
5378                                 statement.Emit (ec);
5379                                 ig.MarkLabel (ec.LoopBegin);
5380                                 for (dim = rank - 1; dim >= 0; dim--){
5381                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5382                                         ig.Emit (OpCodes.Ldc_I4_1);
5383                                         ig.Emit (OpCodes.Add);
5384                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
5385
5386                                         ig.MarkLabel (test [dim]);
5387                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5388                                         ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5389                                         ig.Emit (OpCodes.Blt, loop [dim]);
5390                                 }
5391                         }
5392                         ig.MarkLabel (ec.LoopEnd);
5393                         
5394                         return false;
5395                 }
5396                 
5397                 protected override bool DoEmit (EmitContext ec)
5398                 {
5399                         bool ret_val;
5400                         
5401                         ILGenerator ig = ec.ig;
5402                         
5403                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5404                         bool old_inloop = ec.InLoop;
5405                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5406                         ec.LoopBegin = ig.DefineLabel ();
5407                         ec.LoopEnd = ig.DefineLabel ();
5408                         ec.InLoop = true;
5409                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5410                         
5411                         if (hm != null)
5412                                 ret_val = EmitCollectionForeach (ec);
5413                         else
5414                                 ret_val = EmitArrayForeach (ec);
5415                         
5416                         ec.LoopBegin = old_begin;
5417                         ec.LoopEnd = old_end;
5418                         ec.InLoop = old_inloop;
5419                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5420
5421                         return ret_val;
5422                 }
5423         }
5424         
5425         /// <summary>
5426         ///   AddHandler statement
5427         /// </summary>
5428         public class AddHandler : Statement {
5429                 Expression EvtId;
5430                 Expression EvtHandler;
5431                 Expression EvtTarget;
5432
5433                 public AddHandler (Expression evt_id, Expression evt_handler, 
5434                                                         Expression evt_target, Location l)
5435                 {
5436                         EvtId = evt_id;
5437                         EvtHandler = evt_handler;
5438                         EvtTarget = evt_target;
5439                         loc = l;
5440                         Console.WriteLine ("Adding handler '" + evt_handler + "' for Event '" + evt_id +"'");
5441                 }
5442
5443                 public override bool Resolve (EmitContext ec)
5444                 {
5445                         EvtId = EvtId.Resolve(ec);
5446                         EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5447                         EvtTarget = EvtTarget.Resolve (ec,ResolveFlags.VariableOrValue);
5448                         if (EvtId == null || (!(EvtId is EventExpr))) {
5449                                 Report.Error (999, "'AddHandler' statement needs an event designator.");
5450                                 return false;
5451                         }
5452
5453                         if (EvtHandler == null) 
5454                         {
5455                                 Report.Error (999, "'AddHandler' statement needs an event handler.");
5456                                 return false;
5457                         }
5458                         //EventExpr ee = (EventExpr) EvtId;
5459                         //MethodGroupExpr me = (MethodGroupExpr) EvtHandler;
5460                         //bool b = EvtId.Type.IsSubclassOf (TypeManager.delegate_type);
5461                         //ee.EventInfo.AddEventHandler(EvtTarget, new System.Delegate())
5462                         return true;
5463                 }
5464
5465                 protected override bool DoEmit (EmitContext ec)
5466                 {
5467                         Expression e, d;
5468                         ArrayList args = new ArrayList();
5469                         Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5470                         args.Add (arg);
5471                         
5472                         // The even type was already resolved to a delegate, so
5473                         // we must un-resolve its name to generate a type expression
5474                         string ts = (EvtId.Type.ToString()).Replace ('+','.');
5475                         Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5476
5477                         // which we can use to declare a new event handler
5478                         // of the same type
5479                         d = new New (dtype, args, Location.Null);
5480                         d = d.Resolve(ec);
5481                         e = new CompoundAssign(Binary.Operator.Addition, EvtId, d, Location.Null);
5482
5483                         // we resolve it all and emit the code
5484                         e = e.Resolve(ec);
5485                         if (e != null) 
5486                         {
5487                                 e.Emit(ec);
5488                                 return true;
5489                         }
5490
5491                         return false;
5492                 }
5493         }       
5494 }