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