2006-08-30 Lluis Sanchez Gual <lluis@novell.com>
[mono.git] / mcs / gmcs / 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@ximian.com)
7 //
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 // (C) 2003, 2004 Novell, Inc.
10 //
11
12 using System;
13 using System.Text;
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Diagnostics;
17 using System.Collections;
18 using System.Collections.Specialized;
19
20 namespace Mono.CSharp {
21         
22         public abstract class Statement {
23                 public Location loc;
24                 
25                 /// <summary>
26                 /// Resolves the statement, true means that all sub-statements
27                 /// did resolve ok.
28                 //  </summary>
29                 public virtual bool Resolve (EmitContext ec)
30                 {
31                         return true;
32                 }
33                 
34                 /// <summary>
35                 ///   We already know that the statement is unreachable, but we still
36                 ///   need to resolve it to catch errors.
37                 /// </summary>
38                 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
39                 {
40                         //
41                         // This conflicts with csc's way of doing this, but IMHO it's
42                         // the right thing to do.
43                         //
44                         // If something is unreachable, we still check whether it's
45                         // correct.  This means that you cannot use unassigned variables
46                         // in unreachable code, for instance.
47                         //
48
49                         if (warn)
50                                 Report.Warning (162, 2, loc, "Unreachable code detected");
51
52                         ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
53                         bool ok = Resolve (ec);
54                         ec.KillFlowBranching ();
55
56                         return ok;
57                 }
58                                 
59                 /// <summary>
60                 ///   Return value indicates whether all code paths emitted return.
61                 /// </summary>
62                 protected abstract void DoEmit (EmitContext ec);
63
64                 /// <summary>
65                 ///   Utility wrapper routine for Error, just to beautify the code
66                 /// </summary>
67                 public void Error (int error, string format, params object[] args)
68                 {
69                         Error (error, String.Format (format, args));
70                 }
71                 
72                 public void Error (int error, string s)
73                 {
74                         if (!loc.IsNull)
75                                 Report.Error (error, loc, s);
76                                 else
77                                 Report.Error (error, s);
78                 }
79
80                 /// <summary>
81                 ///   Return value indicates whether all code paths emitted return.
82                 /// </summary>
83                 public virtual void Emit (EmitContext ec)
84                 {
85                         ec.Mark (loc, true);
86                         DoEmit (ec);
87                 }
88         }
89
90         public sealed class EmptyStatement : Statement {
91                 
92                 private EmptyStatement () {}
93                 
94                 public static readonly EmptyStatement Value = new EmptyStatement ();
95                 
96                 public override bool Resolve (EmitContext ec)
97                 {
98                         return true;
99                 }
100
101                 public override bool ResolveUnreachable (EmitContext ec, bool warn)
102                 {
103                         return true;
104                 }
105
106                 protected override void DoEmit (EmitContext ec)
107                 {
108                 }
109         }
110         
111         public class If : Statement {
112                 Expression expr;
113                 public Statement TrueStatement;
114                 public Statement FalseStatement;
115                 
116                 bool is_true_ret;
117                 
118                 public If (Expression expr, Statement trueStatement, Location l)
119                 {
120                         this.expr = expr;
121                         TrueStatement = trueStatement;
122                         loc = l;
123                 }
124
125                 public If (Expression expr,
126                            Statement trueStatement,
127                            Statement falseStatement,
128                            Location l)
129                 {
130                         this.expr = expr;
131                         TrueStatement = trueStatement;
132                         FalseStatement = falseStatement;
133                         loc = l;
134                 }
135
136                 public override bool Resolve (EmitContext ec)
137                 {
138                         bool ok = true;
139
140                         Report.Debug (1, "START IF BLOCK", loc);
141
142                         expr = Expression.ResolveBoolean (ec, expr, loc);
143                         if (expr == null){
144                                 ok = false;
145                                 goto skip;
146                         }
147                         
148                         Assign ass = expr as Assign;
149                         if (ass != null && ass.Source is Constant) {
150                                 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
151                         }
152
153                         //
154                         // Dead code elimination
155                         //
156                         if (expr is BoolConstant){
157                                 bool take = ((BoolConstant) expr).Value;
158
159                                 if (take){
160                                         if (!TrueStatement.Resolve (ec))
161                                                 return false;
162
163                                         if ((FalseStatement != null) &&
164                                             !FalseStatement.ResolveUnreachable (ec, true))
165                                                 return false;
166                                         FalseStatement = null;
167                                 } else {
168                                         if (!TrueStatement.ResolveUnreachable (ec, true))
169                                                 return false;
170                                         TrueStatement = null;
171                         
172                                         if ((FalseStatement != null) &&
173                                             !FalseStatement.Resolve (ec))
174                                                 return false;
175                                 }
176
177                                 return true;
178                         }
179                 skip:
180                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
181                         
182                         ok &= TrueStatement.Resolve (ec);
183
184                         is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
185
186                         ec.CurrentBranching.CreateSibling ();
187
188                         if (FalseStatement != null)
189                                 ok &= FalseStatement.Resolve (ec);
190                                         
191                         ec.EndFlowBranching ();
192
193                         Report.Debug (1, "END IF BLOCK", loc);
194
195                         return ok;
196                 }
197                 
198                 protected override void DoEmit (EmitContext ec)
199                 {
200                         ILGenerator ig = ec.ig;
201                         Label false_target = ig.DefineLabel ();
202                         Label end;
203
204                         //
205                         // If we're a boolean expression, Resolve() already
206                         // eliminated dead code for us.
207                         //
208                         if (expr is BoolConstant){
209                                 bool take = ((BoolConstant) expr).Value;
210
211                                 if (take)
212                                         TrueStatement.Emit (ec);
213                                 else if (FalseStatement != null)
214                                                 FalseStatement.Emit (ec);
215
216                                                 return;
217                                         }
218                         
219                         expr.EmitBranchable (ec, false_target, false);
220
221                         TrueStatement.Emit (ec);
222
223                         if (FalseStatement != null){
224                                 bool branch_emitted = false;
225                                 
226                                 end = ig.DefineLabel ();
227                                 if (!is_true_ret){
228                                         ig.Emit (OpCodes.Br, end);
229                                         branch_emitted = true;
230                                 }
231
232                                 ig.MarkLabel (false_target);
233                                 FalseStatement.Emit (ec);
234
235                                 if (branch_emitted)
236                                         ig.MarkLabel (end);
237                         } else {
238                                 ig.MarkLabel (false_target);
239                         }
240                 }
241         }
242
243         public class Do : Statement {
244                 public Expression expr;
245                 public readonly Statement  EmbeddedStatement;
246                 bool infinite;
247                 
248                 public Do (Statement statement, Expression boolExpr, Location l)
249                 {
250                         expr = boolExpr;
251                         EmbeddedStatement = statement;
252                         loc = l;
253                 }
254
255                 public override bool Resolve (EmitContext ec)
256                 {
257                         bool ok = true;
258
259                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
260
261                         bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
262
263                         ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
264                         if (!EmbeddedStatement.Resolve (ec))
265                                 ok = false;
266                         ec.EndFlowBranching ();
267
268                         if (ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable && !was_unreachable)
269                                 Report.Warning (162, 2, expr.Location, "Unreachable code detected");
270
271                         expr = Expression.ResolveBoolean (ec, expr, loc);
272                         if (expr == null)
273                                 ok = false;
274                         else if (expr is BoolConstant){
275                                 bool res = ((BoolConstant) expr).Value;
276
277                                 if (res)
278                                         infinite = true;
279                         }
280                         if (infinite)
281                                 ec.CurrentBranching.CurrentUsageVector.Goto ();
282
283                         ec.EndFlowBranching ();
284
285                         return ok;
286                 }
287                 
288                 protected override void DoEmit (EmitContext ec)
289                 {
290                         ILGenerator ig = ec.ig;
291                         Label loop = ig.DefineLabel ();
292                         Label old_begin = ec.LoopBegin;
293                         Label old_end = ec.LoopEnd;
294                         
295                         ec.LoopBegin = ig.DefineLabel ();
296                         ec.LoopEnd = ig.DefineLabel ();
297                                 
298                         ig.MarkLabel (loop);
299                         EmbeddedStatement.Emit (ec);
300                         ig.MarkLabel (ec.LoopBegin);
301
302                         //
303                         // Dead code elimination
304                         //
305                         if (expr is BoolConstant){
306                                 bool res = ((BoolConstant) expr).Value;
307
308                                 if (res)
309                                         ec.ig.Emit (OpCodes.Br, loop); 
310                         } else
311                                 expr.EmitBranchable (ec, loop, true);
312                         
313                         ig.MarkLabel (ec.LoopEnd);
314
315                         ec.LoopBegin = old_begin;
316                         ec.LoopEnd = old_end;
317                 }
318         }
319
320         public class While : Statement {
321                 public Expression expr;
322                 public readonly Statement Statement;
323                 bool infinite, empty;
324                 
325                 public While (Expression boolExpr, Statement statement, Location l)
326                 {
327                         this.expr = boolExpr;
328                         Statement = statement;
329                         loc = l;
330                 }
331
332                 public override bool Resolve (EmitContext ec)
333                 {
334                         bool ok = true;
335
336                         expr = Expression.ResolveBoolean (ec, expr, loc);
337                         if (expr == null)
338                                 return false;
339
340                         //
341                         // Inform whether we are infinite or not
342                         //
343                         if (expr is BoolConstant){
344                                 BoolConstant bc = (BoolConstant) expr;
345
346                                 if (bc.Value == false){
347                                         if (!Statement.ResolveUnreachable (ec, true))
348                                                 return false;
349                                         empty = true;
350                                         return true;
351                                 } else
352                                         infinite = true;
353                         }
354
355                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
356                         if (!infinite)
357                                 ec.CurrentBranching.CreateSibling ();
358
359                         ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
360                         if (!Statement.Resolve (ec))
361                                 ok = false;
362                         ec.EndFlowBranching ();
363
364                         // There's no direct control flow from the end of the embedded statement to the end of the loop
365                         ec.CurrentBranching.CurrentUsageVector.Goto ();
366
367                         ec.EndFlowBranching ();
368
369                         return ok;
370                 }
371                 
372                 protected override void DoEmit (EmitContext ec)
373                 {
374                         if (empty)
375                                 return;
376
377                         ILGenerator ig = ec.ig;
378                         Label old_begin = ec.LoopBegin;
379                         Label old_end = ec.LoopEnd;
380                         
381                         ec.LoopBegin = ig.DefineLabel ();
382                         ec.LoopEnd = ig.DefineLabel ();
383
384                         //
385                         // Inform whether we are infinite or not
386                         //
387                         if (expr is BoolConstant){
388                                 ig.MarkLabel (ec.LoopBegin);
389                                 Statement.Emit (ec);
390                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
391                                         
392                                 //
393                                 // Inform that we are infinite (ie, `we return'), only
394                                 // if we do not `break' inside the code.
395                                 //
396                                 ig.MarkLabel (ec.LoopEnd);
397                         } else {
398                                 Label while_loop = ig.DefineLabel ();
399
400                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
401                                 ig.MarkLabel (while_loop);
402
403                                 Statement.Emit (ec);
404                         
405                                 ig.MarkLabel (ec.LoopBegin);
406
407                                 expr.EmitBranchable (ec, while_loop, true);
408                                 
409                                 ig.MarkLabel (ec.LoopEnd);
410                         }       
411
412                         ec.LoopBegin = old_begin;
413                         ec.LoopEnd = old_end;
414                 }
415         }
416
417         public class For : Statement {
418                 Expression Test;
419                 readonly Statement InitStatement;
420                 readonly Statement Increment;
421                 public readonly Statement Statement;
422                 bool infinite, empty;
423                 
424                 public For (Statement initStatement,
425                             Expression test,
426                             Statement increment,
427                             Statement statement,
428                             Location l)
429                 {
430                         InitStatement = initStatement;
431                         Test = test;
432                         Increment = increment;
433                         Statement = statement;
434                         loc = l;
435                 }
436
437                 public override bool Resolve (EmitContext ec)
438                 {
439                         bool ok = true;
440
441                         if (InitStatement != null){
442                                 if (!InitStatement.Resolve (ec))
443                                         ok = false;
444                         }
445
446                         if (Test != null){
447                                 Test = Expression.ResolveBoolean (ec, Test, loc);
448                                 if (Test == null)
449                                         ok = false;
450                                 else if (Test is BoolConstant){
451                                         BoolConstant bc = (BoolConstant) Test;
452
453                                         if (bc.Value == false){
454                                                 if (!Statement.ResolveUnreachable (ec, true))
455                                                         return false;
456                                                 if ((Increment != null) &&
457                                                     !Increment.ResolveUnreachable (ec, false))
458                                                         return false;
459                                                 empty = true;
460                                                 return true;
461                                         } else
462                                                 infinite = true;
463                                 }
464                         } else
465                                 infinite = true;
466
467                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
468                         if (!infinite)
469                                 ec.CurrentBranching.CreateSibling ();
470
471                         bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
472
473                         ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
474                         if (!Statement.Resolve (ec))
475                                 ok = false;
476                         ec.EndFlowBranching ();
477
478                         if (Increment != null){
479                                 if (ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable) {
480                                         if (!Increment.ResolveUnreachable (ec, !was_unreachable))
481                                                 ok = false;
482                                 } else {
483                                         if (!Increment.Resolve (ec))
484                                                 ok = false;
485                                 }
486                         }
487
488                         // There's no direct control flow from the end of the embedded statement to the end of the loop
489                         ec.CurrentBranching.CurrentUsageVector.Goto ();
490
491                         ec.EndFlowBranching ();
492
493                         return ok;
494                 }
495                 
496                 protected override void DoEmit (EmitContext ec)
497                 {
498                         if (empty)
499                                 return;
500
501                         ILGenerator ig = ec.ig;
502                         Label old_begin = ec.LoopBegin;
503                         Label old_end = ec.LoopEnd;
504                         Label loop = ig.DefineLabel ();
505                         Label test = ig.DefineLabel ();
506                         
507                         if (InitStatement != null && InitStatement != EmptyStatement.Value)
508                                         InitStatement.Emit (ec);
509
510                         ec.LoopBegin = ig.DefineLabel ();
511                         ec.LoopEnd = ig.DefineLabel ();
512
513                         ig.Emit (OpCodes.Br, test);
514                         ig.MarkLabel (loop);
515                         Statement.Emit (ec);
516
517                         ig.MarkLabel (ec.LoopBegin);
518                         if (Increment != EmptyStatement.Value)
519                                 Increment.Emit (ec);
520
521                         ig.MarkLabel (test);
522                         //
523                         // If test is null, there is no test, and we are just
524                         // an infinite loop
525                         //
526                         if (Test != null){
527                                 //
528                                 // The Resolve code already catches the case for
529                                 // Test == BoolConstant (false) so we know that
530                                 // this is true
531                                 //
532                                 if (Test is BoolConstant)
533                                         ig.Emit (OpCodes.Br, loop);
534                                 else
535                                         Test.EmitBranchable (ec, loop, true);
536                                 
537                         } else
538                                 ig.Emit (OpCodes.Br, loop);
539                         ig.MarkLabel (ec.LoopEnd);
540
541                         ec.LoopBegin = old_begin;
542                         ec.LoopEnd = old_end;
543                 }
544         }
545         
546         public class StatementExpression : Statement {
547                 ExpressionStatement expr;
548                 
549                 public StatementExpression (ExpressionStatement expr)
550                 {
551                         this.expr = expr;
552                         loc = expr.Location;
553                 }
554
555                 public override bool Resolve (EmitContext ec)
556                 {
557                         if (expr != null)
558                                 expr = expr.ResolveStatement (ec);
559                         return expr != null;
560                 }
561                 
562                 protected override void DoEmit (EmitContext ec)
563                 {
564                         expr.EmitStatement (ec);
565                 }
566
567                 public override string ToString ()
568                 {
569                         return "StatementExpression (" + expr + ")";
570                 }
571         }
572
573         /// <summary>
574         ///   Implements the return statement
575         /// </summary>
576         public class Return : Statement {
577                 public Expression Expr;
578                 
579                 public Return (Expression expr, Location l)
580                 {
581                         Expr = expr;
582                         loc = l;
583                 }
584
585                 bool unwind_protect;
586
587                 public override bool Resolve (EmitContext ec)
588                 {
589                         AnonymousContainer am = ec.CurrentAnonymousMethod;
590                         if ((am != null) && am.IsIterator && ec.InIterator) {
591                                 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
592                                               "statement to return a value, or yield break to end the iteration");
593                                 return false;
594                         }
595
596                         if (ec.ReturnType == null){
597                                 if (Expr != null){
598                                         if (ec.CurrentAnonymousMethod != null){
599                                                 Report.Error (1662, loc,
600                                                         "Cannot convert anonymous method block to delegate type `{0}' because some of the return types in the block are not implicitly convertible to the delegate return type",
601                                                         ec.CurrentAnonymousMethod.GetSignatureForError ());
602                                         }
603                                         Error (127, "A return keyword must not be followed by any expression when method returns void");
604                                         return false;
605                                 }
606                         } else {
607                                 if (Expr == null){
608                                         Error (126, "An object of a type convertible to `{0}' is required " +
609                                                "for the return statement",
610                                                TypeManager.CSharpName (ec.ReturnType));
611                                         return false;
612                                 }
613
614                                 Expr = Expr.Resolve (ec);
615                                 if (Expr == null)
616                                         return false;
617
618                                 if (Expr.Type != ec.ReturnType) {
619                                         Expr = Convert.ImplicitConversionRequired (
620                                                 ec, Expr, ec.ReturnType, loc);
621                                         if (Expr == null)
622                                                 return false;
623                                 }
624                         }
625
626                         int errors = Report.Errors;
627                         unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
628                         if (unwind_protect)
629                                 ec.NeedReturnLabel ();
630                         ec.CurrentBranching.CurrentUsageVector.Return ();
631                         return errors == Report.Errors;
632                 }
633                 
634                 protected override void DoEmit (EmitContext ec)
635                 {
636                         if (Expr != null) {
637                                 Expr.Emit (ec);
638
639                                 if (unwind_protect)
640                                         ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
641                         }
642
643                         if (unwind_protect)
644                                 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
645                         else
646                                 ec.ig.Emit (OpCodes.Ret);
647                         }
648                 }
649
650         public class Goto : Statement {
651                 string target;
652                 LabeledStatement label;
653                 bool unwind_protect;
654                 
655                 public override bool Resolve (EmitContext ec)
656                 {
657                         int errors = Report.Errors;
658                         unwind_protect = ec.CurrentBranching.AddGotoOrigin (ec.CurrentBranching.CurrentUsageVector, this);
659                         ec.CurrentBranching.CurrentUsageVector.Goto ();
660                         return errors == Report.Errors;
661                 }
662                 
663                 public Goto (string label, Location l)
664                 {
665                         loc = l;
666                         target = label;
667                 }
668
669                 public string Target {
670                         get { return target; }
671                 }
672
673                 public void SetResolvedTarget (LabeledStatement label)
674                 {
675                         this.label = label;
676                         label.AddReference ();
677                 }
678
679                 protected override void DoEmit (EmitContext ec)
680                 {
681                         if (label == null)
682                                 throw new InternalErrorException ("goto emitted before target resolved");
683                         Label l = label.LabelTarget (ec);
684                         ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
685                 }
686         }
687
688         public class LabeledStatement : Statement {
689                 string name;
690                 bool defined;
691                 bool referenced;
692                 Label label;
693                 ILGenerator ig;
694
695                 FlowBranching.UsageVector vectors;
696                 
697                 public LabeledStatement (string name, Location l)
698                 {
699                         this.name = name;
700                         this.loc = l;
701                 }
702
703                 public Label LabelTarget (EmitContext ec)
704                 {
705                         if (defined)
706                                 return label;
707                         ig = ec.ig;
708                         label = ec.ig.DefineLabel ();
709                         defined = true;
710
711                         return label;
712                 }
713
714                 public string Name {
715                         get { return name; }
716                 }
717
718                 public bool IsDefined {
719                         get { return defined; }
720                 }
721
722                 public bool HasBeenReferenced {
723                         get { return referenced; }
724                 }
725
726                 public FlowBranching.UsageVector JumpOrigins {
727                         get { return vectors; }
728                 }
729
730                 public void AddUsageVector (FlowBranching.UsageVector vector)
731                 {
732                         vector = vector.Clone ();
733                         vector.Next = vectors;
734                         vectors = vector;
735                 }
736
737                 public override bool Resolve (EmitContext ec)
738                 {
739                         // this flow-branching will be terminated when the surrounding block ends
740                         ec.StartFlowBranching (this);
741                         return true;
742                 }
743
744                 protected override void DoEmit (EmitContext ec)
745                 {
746                         if (ig != null && ig != ec.ig)
747                                 throw new InternalErrorException ("cannot happen");
748                         LabelTarget (ec);
749                         ec.ig.MarkLabel (label);
750                 }
751
752                 public void AddReference ()
753                 {
754                         referenced = true;
755                 }
756         }
757         
758
759         /// <summary>
760         ///   `goto default' statement
761         /// </summary>
762         public class GotoDefault : Statement {
763                 
764                 public GotoDefault (Location l)
765                 {
766                         loc = l;
767                 }
768
769                 public override bool Resolve (EmitContext ec)
770                 {
771                         ec.CurrentBranching.CurrentUsageVector.Goto ();
772                         return true;
773                 }
774
775                 protected override void DoEmit (EmitContext ec)
776                 {
777                         if (ec.Switch == null){
778                                 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
779                                 return;
780                         }
781
782                         if (!ec.Switch.GotDefault){
783                                 Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
784                                 return;
785                         }
786                         ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
787                 }
788         }
789
790         /// <summary>
791         ///   `goto case' statement
792         /// </summary>
793         public class GotoCase : Statement {
794                 Expression expr;
795                 SwitchLabel sl;
796                 
797                 public GotoCase (Expression e, Location l)
798                 {
799                         expr = e;
800                         loc = l;
801                 }
802
803                 public override bool Resolve (EmitContext ec)
804                 {
805                         if (ec.Switch == null){
806                                 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
807                                 return false;
808                         }
809
810                         expr = expr.Resolve (ec);
811                         if (expr == null)
812                                 return false;
813
814                         Constant c = expr as Constant;
815                         if (c == null) {
816                                 Error (150, "A constant value is expected");
817                                 return false;
818                         }
819
820                         Type type = ec.Switch.SwitchType;
821                         if (!Convert.ImplicitStandardConversionExists (c, type))
822                                 Report.Warning (469, 2, loc, "The `goto case' value is not implicitly " +
823                                                 "convertible to type `{0}'", TypeManager.CSharpName (type));
824
825                         bool fail = false;
826                         object val = c.GetValue ();
827                         if ((val != null) && (c.Type != type) && (c.Type != TypeManager.object_type))
828                                 val = TypeManager.ChangeType (val, type, out fail);
829
830                         if (fail) {
831                                 Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
832                                               c.GetSignatureForError (), TypeManager.CSharpName (type));
833                                 return false;
834                         }
835
836                         if (val == null)
837                                 val = SwitchLabel.NullStringCase;
838                                         
839                         sl = (SwitchLabel) ec.Switch.Elements [val];
840
841                         if (sl == null){
842                                 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", c.GetValue () == null ? "null" : val.ToString ());
843                                 return false;
844                         }
845
846                         ec.CurrentBranching.CurrentUsageVector.Goto ();
847                         return true;
848                 }
849
850                 protected override void DoEmit (EmitContext ec)
851                 {
852                         ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
853                 }
854         }
855         
856         public class Throw : Statement {
857                 Expression expr;
858                 
859                 public Throw (Expression expr, Location l)
860                 {
861                         this.expr = expr;
862                         loc = l;
863                 }
864
865                 public override bool Resolve (EmitContext ec)
866                 {
867                         ec.CurrentBranching.CurrentUsageVector.Throw ();
868
869                         if (expr != null){
870                                 expr = expr.Resolve (ec);
871                                 if (expr == null)
872                                         return false;
873
874                                 ExprClass eclass = expr.eclass;
875
876                                 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
877                                         eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
878                                         expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
879                                         return false;
880                                 }
881
882                                 Type t = expr.Type;
883
884                                 if ((t != TypeManager.exception_type) &&
885                                     !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
886                                     !(expr is NullLiteral)) {
887                                         Error (155,
888                                                 "The type caught or thrown must be derived " +
889                                                 "from System.Exception");
890                                         return false;
891                                 }
892                                 return true;
893                         }
894
895                         if (!ec.InCatch) {
896                                 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
897                                 return false;
898                         }
899
900                         if (ec.InFinally) {
901                                 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
902                                 return false;
903                         }
904                         return true;
905                 }
906                         
907                 protected override void DoEmit (EmitContext ec)
908                 {
909                         if (expr == null)
910                                         ec.ig.Emit (OpCodes.Rethrow);
911                                 else {
912                         expr.Emit (ec);
913
914                         ec.ig.Emit (OpCodes.Throw);
915                 }
916         }
917         }
918
919         public class Break : Statement {
920                 
921                 public Break (Location l)
922                 {
923                         loc = l;
924                 }
925
926                 bool unwind_protect;
927
928                 public override bool Resolve (EmitContext ec)
929                 {
930                         int errors = Report.Errors;
931                         unwind_protect = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
932                         ec.CurrentBranching.CurrentUsageVector.Goto ();
933                         return errors == Report.Errors;
934                 }
935
936                 protected override void DoEmit (EmitContext ec)
937                 {
938                         ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
939                 }
940         }
941
942         public class Continue : Statement {
943                 
944                 public Continue (Location l)
945                 {
946                         loc = l;
947                 }
948
949                 bool unwind_protect;
950
951                 public override bool Resolve (EmitContext ec)
952                 {
953                         int errors = Report.Errors;
954                         unwind_protect = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
955                         ec.CurrentBranching.CurrentUsageVector.Goto ();
956                         return errors == Report.Errors;
957                 }
958
959                 protected override void DoEmit (EmitContext ec)
960                 {
961                         ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
962                 }
963         }
964
965         //
966         // The information about a user-perceived local variable
967         //
968         public class LocalInfo {
969                 public Expression Type;
970
971                 //
972                 // Most of the time a variable will be stored in a LocalBuilder
973                 //
974                 // But sometimes, it will be stored in a field (variables that have been
975                 // hoisted by iterators or by anonymous methods).  The context of the field will
976                 // be stored in the EmitContext
977                 //
978                 //
979                 public LocalBuilder LocalBuilder;
980                 public FieldBuilder FieldBuilder;
981
982                 public Type VariableType;
983                 public readonly string Name;
984                 public readonly Location Location;
985                 public readonly Block Block;
986
987                 public VariableInfo VariableInfo;
988
989                 [Flags]
990                 enum Flags : byte {
991                         Used = 1,
992                         ReadOnly = 2,
993                         Pinned = 4,
994                         IsThis = 8,
995                         Captured = 16,
996                         AddressTaken = 32,
997                         CompilerGenerated = 64,
998                         IsConstant = 128
999                 }
1000
1001                 public enum ReadOnlyContext: byte {
1002                         Using,
1003                         Foreach,
1004                         Fixed
1005                 }
1006
1007                 Flags flags;
1008                 ReadOnlyContext ro_context;
1009                 
1010                 public LocalInfo (Expression type, string name, Block block, Location l)
1011                 {
1012                         Type = type;
1013                         Name = name;
1014                         Block = block;
1015                         Location = l;
1016                 }
1017
1018                 public LocalInfo (DeclSpace ds, Block block, Location l)
1019                 {
1020                         VariableType = ds.TypeBuilder;
1021                         Block = block;
1022                         Location = l;
1023                 }
1024
1025                 public void DeclareLocal (ILGenerator ig)
1026                 {
1027                         if (Pinned) {
1028                                 //
1029                                 // This is needed to compile on both .NET 1.x and .NET 2.x
1030                                 // the later introduced `DeclareLocal (Type t, bool pinned)'
1031                                 //
1032                                 LocalBuilder = TypeManager.DeclareLocalPinned (ig, VariableType);
1033                                 return;
1034                         }
1035                         if (!IsThis && !IsConstant)
1036                                 LocalBuilder = ig.DeclareLocal (VariableType);
1037                 }
1038
1039                 public bool IsThisAssigned (EmitContext ec, Location loc)
1040                 {
1041                         if (VariableInfo == null)
1042                                 throw new Exception ();
1043
1044                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1045                                 return true;
1046
1047                         return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1048                 }
1049
1050                 public bool IsAssigned (EmitContext ec)
1051                 {
1052                         if (VariableInfo == null)
1053                                 throw new Exception ();
1054
1055                         return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1056                 }
1057
1058                 public bool Resolve (EmitContext ec)
1059                 {
1060                         if (VariableType == null) {
1061                                 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1062                                 if (texpr == null)
1063                                         return false;
1064                                 
1065                                 VariableType = texpr.Type;
1066                         }
1067
1068                         if (VariableType == TypeManager.void_type) {
1069                                 Expression.Error_VoidInvalidInTheContext (Location);
1070                                 return false;
1071                         }
1072
1073                         if (VariableType.IsAbstract && VariableType.IsSealed) {
1074                                 Report.Error (723, Location, "Cannot declare variable of static type `{0}'", TypeManager.CSharpName (VariableType));
1075                                 return false;
1076                         }
1077
1078                         if (VariableType.IsPointer && !ec.InUnsafe)
1079                                 Expression.UnsafeError (Location);
1080
1081                         return true;
1082                 }
1083
1084                 public bool IsCaptured {
1085                         get {
1086                                 return (flags & Flags.Captured) != 0;
1087                         }
1088
1089                         set {
1090                                 flags |= Flags.Captured;
1091                         }
1092                 }
1093
1094                 public bool IsConstant {
1095                         get {
1096                                 return (flags & Flags.IsConstant) != 0;
1097                         }
1098                         set {
1099                                 flags |= Flags.IsConstant;
1100                         }
1101                 }
1102
1103                 public bool AddressTaken {
1104                         get {
1105                                 return (flags & Flags.AddressTaken) != 0;
1106                         }
1107
1108                         set {
1109                                 flags |= Flags.AddressTaken;
1110                         }
1111                 }
1112
1113                 public bool CompilerGenerated {
1114                         get {
1115                                 return (flags & Flags.CompilerGenerated) != 0;
1116                         }
1117
1118                         set {
1119                                 flags |= Flags.CompilerGenerated;
1120                         }
1121                 }
1122
1123                 public override string ToString ()
1124                 {
1125                         return String.Format ("LocalInfo ({0},{1},{2},{3})",
1126                                               Name, Type, VariableInfo, Location);
1127                 }
1128
1129                 public bool Used {
1130                         get {
1131                                 return (flags & Flags.Used) != 0;
1132                         }
1133                         set {
1134                                 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1135                         }
1136                 }
1137
1138                 public bool ReadOnly {
1139                         get {
1140                                 return (flags & Flags.ReadOnly) != 0;
1141                         }
1142                 }
1143
1144                 public void SetReadOnlyContext (ReadOnlyContext context)
1145                 {
1146                         flags |= Flags.ReadOnly;
1147                         ro_context = context;
1148                 }
1149
1150                 public string GetReadOnlyContext ()
1151                 {
1152                         if (!ReadOnly)
1153                                 throw new InternalErrorException ("Variable is not readonly");
1154
1155                         switch (ro_context) {
1156                                 case ReadOnlyContext.Fixed:
1157                                         return "fixed variable";
1158                                 case ReadOnlyContext.Foreach:
1159                                         return "foreach iteration variable";
1160                                 case ReadOnlyContext.Using:
1161                                         return "using variable";
1162                         }
1163                         throw new NotImplementedException ();
1164                 }
1165
1166                 //
1167                 // Whether the variable is pinned, if Pinned the variable has been 
1168                 // allocated in a pinned slot with DeclareLocal.
1169                 //
1170                 public bool Pinned {
1171                         get {
1172                                 return (flags & Flags.Pinned) != 0;
1173                         }
1174                         set {
1175                                 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1176                         }
1177                 }
1178
1179                 public bool IsThis {
1180                         get {
1181                                 return (flags & Flags.IsThis) != 0;
1182                         }
1183                         set {
1184                                 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1185                         }
1186                 }
1187         }
1188                 
1189         /// <summary>
1190         ///   Block represents a C# block.
1191         /// </summary>
1192         ///
1193         /// <remarks>
1194         ///   This class is used in a number of places: either to represent
1195         ///   explicit blocks that the programmer places or implicit blocks.
1196         ///
1197         ///   Implicit blocks are used as labels or to introduce variable
1198         ///   declarations.
1199         ///
1200         ///   Top-level blocks derive from Block, and they are called ToplevelBlock
1201         ///   they contain extra information that is not necessary on normal blocks.
1202         /// </remarks>
1203         public class Block : Statement {
1204                 public Block    Parent;
1205                 public readonly Location  StartLocation;
1206                 public Location           EndLocation = Location.Null;
1207
1208                 public readonly ToplevelBlock Toplevel;
1209
1210                 [Flags]
1211                 public enum Flags : ushort {
1212                         Implicit  = 1,
1213                         Unchecked = 2,
1214                         BlockUsed = 4,
1215                         VariablesInitialized = 8,
1216                         HasRet = 16,
1217                         IsDestructor = 32,
1218                         IsToplevel = 64,
1219                         Unsafe = 128,
1220                         HasVarargs = 256 // Used in ToplevelBlock
1221                 }
1222                 protected Flags flags;
1223
1224                 public bool Implicit {
1225                         get { return (flags & Flags.Implicit) != 0; }
1226                 }
1227
1228                 public bool Unchecked {
1229                         get { return (flags & Flags.Unchecked) != 0; }
1230                         set { flags |= Flags.Unchecked; }
1231                 }
1232
1233                 public bool Unsafe {
1234                         get { return (flags & Flags.Unsafe) != 0; }
1235                         set { flags |= Flags.Unsafe; }
1236                 }
1237
1238                 //
1239                 // The statements in this block
1240                 //
1241                 ArrayList statements;
1242                 int num_statements;
1243
1244                 //
1245                 // An array of Blocks.  We keep track of children just
1246                 // to generate the local variable declarations.
1247                 //
1248                 // Statements and child statements are handled through the
1249                 // statements.
1250                 //
1251                 ArrayList children;
1252
1253                 //
1254                 // Labels.  (label, block) pairs.
1255                 //
1256                 Hashtable labels;
1257
1258                 //
1259                 // Keeps track of (name, type) pairs
1260                 //
1261                 IDictionary variables;
1262
1263                 //
1264                 // Keeps track of constants
1265                 Hashtable constants;
1266
1267                 //
1268                 // Temporary variables.
1269                 //
1270                 ArrayList temporary_variables;
1271                 
1272                 //
1273                 // If this is a switch section, the enclosing switch block.
1274                 //
1275                 Block switch_block;
1276
1277                 protected static int id;
1278
1279                 int this_id;
1280                 
1281                 public Block (Block parent)
1282                         : this (parent, (Flags) 0, Location.Null, Location.Null)
1283                 { }
1284
1285                 public Block (Block parent, Flags flags)
1286                         : this (parent, flags, Location.Null, Location.Null)
1287                 { }
1288
1289                 public Block (Block parent, Location start, Location end)
1290                         : this (parent, (Flags) 0, start, end)
1291                 { }
1292
1293                 public Block (Block parent, Flags flags, Location start, Location end)
1294                 {
1295                         if (parent != null)
1296                                 parent.AddChild (this);
1297                         
1298                         this.Parent = parent;
1299                         this.flags = flags;
1300                         this.StartLocation = start;
1301                         this.EndLocation = end;
1302                         this.loc = start;
1303                         this_id = id++;
1304                         statements = new ArrayList ();
1305
1306                         if ((flags & Flags.IsToplevel) != 0)
1307                                 Toplevel = (ToplevelBlock) this;
1308                         else
1309                                 Toplevel = parent.Toplevel;
1310
1311                         if (parent != null && Implicit) {
1312                                 if (parent.known_variables == null)
1313                                         parent.known_variables = new Hashtable ();
1314                                 // share with parent
1315                                 known_variables = parent.known_variables;
1316                         }
1317                 }
1318
1319                 public Block CreateSwitchBlock (Location start)
1320                 {
1321                         Block new_block = new Block (this, start, start);
1322                         new_block.switch_block = this;
1323                         return new_block;
1324                 }
1325
1326                 public int ID {
1327                         get { return this_id; }
1328                 }
1329
1330                 protected IDictionary Variables {
1331                         get {
1332                                 if (variables == null)
1333                                         variables = new ListDictionary ();
1334                                 return variables;
1335                         }
1336                 }
1337
1338                 void AddChild (Block b)
1339                 {
1340                         if (children == null)
1341                                 children = new ArrayList ();
1342                         
1343                         children.Add (b);
1344                 }
1345
1346                 public void SetEndLocation (Location loc)
1347                 {
1348                         EndLocation = loc;
1349                 }
1350
1351                 /// <summary>
1352                 ///   Adds a label to the current block. 
1353                 /// </summary>
1354                 ///
1355                 /// <returns>
1356                 ///   false if the name already exists in this block. true
1357                 ///   otherwise.
1358                 /// </returns>
1359                 ///
1360                 public bool AddLabel (LabeledStatement target)
1361                 {
1362                         if (switch_block != null)
1363                                 return switch_block.AddLabel (target);
1364
1365                         string name = target.Name;
1366
1367                         Block cur = this;
1368                         while (cur != null) {
1369                                 if (cur.DoLookupLabel (name) != null) {
1370                                         Report.Error (140, target.loc, "The label `{0}' is a duplicate", name);
1371                                         return false;
1372                                 }
1373
1374                                 if (!Implicit)
1375                                         break;
1376
1377                                 cur = cur.Parent;
1378                         }
1379
1380                         while (cur != null) {
1381                                 if (cur.DoLookupLabel (name) != null) {
1382                                         Report.Error (
1383                                                 158, target.loc,
1384                                                 "The label `{0}' shadows another label by the same name in a contained scope.",
1385                                                 name);
1386                                         return false;
1387                                 }
1388
1389                                 if (children != null) {
1390                                         foreach (Block b in children) {
1391                                                 LabeledStatement s = b.DoLookupLabel (name);
1392                                                 if (s == null)
1393                                                         continue;
1394
1395                                                 Report.Error (
1396                                                         158, s.loc,
1397                                                         "The label `{0}' shadows another label by the same name in a contained scope.",
1398                                                         name);
1399                                                 return false;
1400                                         }
1401                                 }
1402
1403
1404                                 cur = cur.Parent;
1405                         }
1406
1407                         if (labels == null)
1408                                 labels = new Hashtable ();
1409
1410                         labels.Add (name, target);
1411                         return true;
1412                 }
1413
1414                 public LabeledStatement LookupLabel (string name)
1415                 {
1416                         LabeledStatement s = DoLookupLabel (name);
1417                         if (s != null)
1418                                 return s;
1419
1420                         if (children == null)
1421                                 return null;
1422
1423                         foreach (Block child in children) {
1424                                 if (!child.Implicit)
1425                                         continue;
1426
1427                                 s = child.LookupLabel (name);
1428                                 if (s != null)
1429                                         return s;
1430                         }
1431
1432                         return null;
1433                 }
1434
1435                 LabeledStatement DoLookupLabel (string name)
1436                 {
1437                         if (switch_block != null)
1438                                 return switch_block.LookupLabel (name);
1439
1440                         if (labels != null)
1441                                 if (labels.Contains (name))
1442                                         return ((LabeledStatement) labels [name]);
1443
1444                         return null;
1445                 }
1446
1447                 Hashtable known_variables;
1448
1449                 // <summary>
1450                 //   Marks a variable with name @name as being used in this or a child block.
1451                 //   If a variable name has been used in a child block, it's illegal to
1452                 //   declare a variable with the same name in the current block.
1453                 // </summary>
1454                 void AddKnownVariable (string name, LocalInfo info)
1455                 {
1456                         if (known_variables == null)
1457                                 known_variables = new Hashtable ();
1458
1459                         known_variables [name] = info;
1460                 }
1461
1462                 LocalInfo GetKnownVariableInfo (string name)
1463                 {
1464                         if (known_variables == null)
1465                                 return null;
1466                         return (LocalInfo) known_variables [name];
1467                 }
1468
1469                 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1470                 {
1471                         Block b = this;
1472                         LocalInfo kvi = b.GetKnownVariableInfo (name);
1473                         while (kvi == null) {
1474                                 while (b.Implicit)
1475                                         b = b.Parent;
1476                                 b = b.Parent;
1477                                 if (b == null)
1478                                         return true;
1479                                 kvi = b.GetKnownVariableInfo (name);
1480                         }
1481
1482                         if (kvi.Block == b)
1483                                 return true;
1484
1485                         // Is kvi.Block nested inside 'b'
1486                         if (b.known_variables != kvi.Block.known_variables) {
1487                                 //
1488                                 // If a variable by the same name it defined in a nested block of this
1489                                 // block, we violate the invariant meaning in a block.
1490                                 //
1491                                 if (b == this) {
1492                                         Report.SymbolRelatedToPreviousError (kvi.Location, name);
1493                                         Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1494                                         return false;
1495                                 }
1496
1497                                 //
1498                                 // It's ok if the definition is in a nested subblock of b, but not
1499                                 // nested inside this block -- a definition in a sibling block
1500                                 // should not affect us.
1501                                 //
1502                                 return true;
1503                         }
1504
1505                         //
1506                         // Block 'b' and kvi.Block are the same textual block.
1507                         // However, different variables are extant.
1508                         //
1509                         // Check if the variable is in scope in both blocks.  We use
1510                         // an indirect check that depends on AddVariable doing its
1511                         // part in maintaining the invariant-meaning-in-block property.
1512                         //
1513                         if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1514                                 return true;
1515
1516                         //
1517                         // Even though we detected the error when the name is used, we
1518                         // treat it as if the variable declaration was in error.
1519                         //
1520                         Report.SymbolRelatedToPreviousError (loc, name);
1521                         Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1522                         return false;
1523                 }
1524
1525                 public LocalInfo AddVariable (Expression type, string name, Location l)
1526                 {
1527                         LocalInfo vi = GetLocalInfo (name);
1528                         if (vi != null) {
1529                                 Report.SymbolRelatedToPreviousError (vi.Location, name);
1530                                 if (known_variables == vi.Block.known_variables)
1531                                         Report.Error (128, l,
1532                                                 "A local variable named `{0}' is already defined in this scope", name);
1533                                 else
1534                                         Error_AlreadyDeclared (l, name, "parent");
1535                                 return null;
1536                         }
1537
1538                         vi = GetKnownVariableInfo (name);
1539                         if (vi != null) {
1540                                 Report.SymbolRelatedToPreviousError (vi.Location, name);
1541                                 Error_AlreadyDeclared (l, name, "child");
1542                                 return null;
1543                         }
1544
1545                         int idx;
1546                         Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1547                         if (p != null) {
1548                                 Report.SymbolRelatedToPreviousError (p.Location, name);
1549                                 Error_AlreadyDeclared (l, name, "method argument");
1550                                 return null;
1551                         }
1552
1553                         vi = new LocalInfo (type, name, this, l);
1554
1555                         Variables.Add (name, vi);
1556
1557                         for (Block b = this; b != null; b = b.Parent)
1558                                 b.AddKnownVariable (name, vi);
1559
1560                         if ((flags & Flags.VariablesInitialized) != 0)
1561                                 throw new Exception ();
1562
1563                         return vi;
1564                 }
1565
1566                 void Error_AlreadyDeclared (Location loc, string var, string reason)
1567                 {
1568                         Report.Error (136, loc, "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning to `{0}', " +
1569                                 "which is already used in a `{1}' scope", var, reason);
1570                 }
1571
1572                 public bool AddConstant (Expression type, string name, Expression value, Location l)
1573                 {
1574                         if (AddVariable (type, name, l) == null)
1575                                 return false;
1576                         
1577                         if (constants == null)
1578                                 constants = new Hashtable ();
1579
1580                         constants.Add (name, value);
1581
1582                         // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1583                         Use ();
1584                         return true;
1585                 }
1586
1587                 static int next_temp_id = 0;
1588
1589                 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1590                 {
1591                         if (temporary_variables == null)
1592                                 temporary_variables = new ArrayList ();
1593
1594                         int id = ++next_temp_id;
1595                         string name = "$s_" + id.ToString ();
1596
1597                         LocalInfo li = new LocalInfo (te, name, this, loc);
1598                         li.CompilerGenerated = true;
1599                         temporary_variables.Add (li);
1600                         return li;
1601                 }
1602
1603                 public LocalInfo GetLocalInfo (string name)
1604                 {
1605                         for (Block b = this; b != null; b = b.Parent) {
1606                                 if (b.variables != null) {
1607                                         LocalInfo ret = b.variables [name] as LocalInfo;
1608                                         if (ret != null)
1609                                                 return ret;
1610                                 }
1611                         }
1612                         return null;
1613                 }
1614
1615                 public Expression GetVariableType (string name)
1616                 {
1617                         LocalInfo vi = GetLocalInfo (name);
1618                         return vi == null ? null : vi.Type;
1619                 }
1620
1621                 public Expression GetConstantExpression (string name)
1622                 {
1623                         for (Block b = this; b != null; b = b.Parent) {
1624                                 if (b.constants != null) {
1625                                         Expression ret = b.constants [name] as Expression;
1626                                         if (ret != null)
1627                                                 return ret;
1628                                 }
1629                         }
1630                         return null;
1631                 }
1632                 
1633                 public void AddStatement (Statement s)
1634                 {
1635                         statements.Add (s);
1636                         flags |= Flags.BlockUsed;
1637                 }
1638
1639                 public bool Used {
1640                         get { return (flags & Flags.BlockUsed) != 0; }
1641                 }
1642
1643                 public void Use ()
1644                 {
1645                         flags |= Flags.BlockUsed;
1646                 }
1647
1648                 public bool HasRet {
1649                         get { return (flags & Flags.HasRet) != 0; }
1650                 }
1651
1652                 public bool IsDestructor {
1653                         get { return (flags & Flags.IsDestructor) != 0; }
1654                 }
1655
1656                 public void SetDestructor ()
1657                 {
1658                         flags |= Flags.IsDestructor;
1659                 }
1660
1661                 VariableMap param_map, local_map;
1662
1663                 public VariableMap ParameterMap {
1664                         get {
1665                                 if ((flags & Flags.VariablesInitialized) == 0)
1666                                         throw new Exception ("Variables have not been initialized yet");
1667
1668                                 return param_map;
1669                         }
1670                 }
1671
1672                 public VariableMap LocalMap {
1673                         get {
1674                                 if ((flags & Flags.VariablesInitialized) == 0)
1675                                         throw new Exception ("Variables have not been initialized yet");
1676
1677                                 return local_map;
1678                         }
1679                 }
1680
1681                 /// <summary>
1682                 ///   Emits the variable declarations and labels.
1683                 /// </summary>
1684                 /// <remarks>
1685                 ///   tc: is our typecontainer (to resolve type references)
1686                 ///   ig: is the code generator:
1687                 /// </remarks>
1688                 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
1689                 {
1690                         // If some parent block was unsafe, we remain unsafe even if this block
1691                         // isn't explicitly marked as such.
1692                         using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
1693                                 //
1694                                 // Compute the VariableMap's.
1695                                 //
1696                                 // Unfortunately, we don't know the type when adding variables with
1697                                 // AddVariable(), so we need to compute this info here.
1698                                 //
1699
1700                                 LocalInfo[] locals;
1701                                 if (variables != null) {
1702                                         foreach (LocalInfo li in variables.Values)
1703                                                 li.Resolve (ec);
1704
1705                                         locals = new LocalInfo [variables.Count];
1706                                         variables.Values.CopyTo (locals, 0);
1707                                 } else
1708                                         locals = new LocalInfo [0];
1709
1710                                 if (Parent != null)
1711                                         local_map = new VariableMap (Parent.LocalMap, locals);
1712                                 else
1713                                         local_map = new VariableMap (locals);
1714
1715                                 param_map = new VariableMap (ip);
1716                                 flags |= Flags.VariablesInitialized;
1717
1718                                 //
1719                                 // Process this block variables
1720                                 //
1721                                 if (variables != null) {
1722                                         foreach (DictionaryEntry de in variables) {
1723                                                 string name = (string) de.Key;
1724                                                 LocalInfo vi = (LocalInfo) de.Value;
1725                                                 Type variable_type = vi.VariableType;
1726
1727                                                 if (variable_type == null)
1728                                                         continue;
1729
1730                                                 if (variable_type.IsPointer) {
1731                                                         //
1732                                                         // Am not really convinced that this test is required (Microsoft does it)
1733                                                         // but the fact is that you would not be able to use the pointer variable
1734                                                         // *anyways*
1735                                                         //
1736                                                         if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1737                                                                                           vi.Location))
1738                                                                 continue;
1739                                                 }
1740
1741                                                 if (constants == null)
1742                                                         continue;
1743
1744                                                 Expression cv = (Expression) constants [name];
1745                                                 if (cv == null)
1746                                                         continue;
1747
1748                                                 // Don't let 'const int Foo = Foo;' succeed.
1749                                                 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
1750                                                 // which in turn causes the 'must be constant' error to be triggered.
1751                                                 constants.Remove (name);
1752
1753                                                 using (ec.With (EmitContext.Flags.ConstantCheckState, (flags & Flags.Unchecked) == 0)) {
1754                                                         ec.CurrentBlock = this;
1755                                                         Expression e = cv.Resolve (ec);
1756                                                         if (e == null)
1757                                                                 continue;
1758
1759                                                         Constant ce = e as Constant;
1760                                                         if (ce == null) {
1761                                                                 Const.Error_ExpressionMustBeConstant (variable_type, vi.Location, name);
1762                                                                 continue;
1763                                                         }
1764
1765                                                         e = ce.ToType (variable_type, vi.Location);
1766                                                         if (e == null)
1767                                                                 continue;
1768
1769                                                         if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue) {
1770                                                                 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
1771                                                                 continue;
1772                                                         }
1773
1774                                                         constants.Add (name, e);
1775                                                         vi.IsConstant = true;
1776                                                 }
1777                                         }
1778                                 }
1779
1780                                 //
1781                                 // Now, handle the children
1782                                 //
1783                                 if (children != null) {
1784                                         foreach (Block b in children)
1785                                                 b.ResolveMeta (toplevel, ec, ip);
1786                                 }
1787                         }
1788                 }
1789
1790                 //
1791                 // Emits the local variable declarations for a block
1792                 //
1793                 public void EmitMeta (EmitContext ec)
1794                 {
1795                         ILGenerator ig = ec.ig;
1796                         
1797                         if (variables != null){
1798                                 bool have_captured_vars = ec.HaveCapturedVariables ();
1799                                 
1800                                 foreach (DictionaryEntry de in variables){
1801                                         LocalInfo vi = (LocalInfo) de.Value;
1802
1803                                         if (have_captured_vars && ec.IsCaptured (vi))
1804                                                 continue;
1805
1806                                         vi.DeclareLocal (ig);
1807                                 }
1808                         }
1809
1810                         if (temporary_variables != null) {
1811                                 AnonymousContainer am = ec.CurrentAnonymousMethod;
1812                                 TypeBuilder scope = null;
1813                                 if ((am != null) && am.IsIterator) {
1814                                         scope = am.Scope.ScopeTypeBuilder;
1815                                         if (scope == null)
1816                                                 throw new InternalErrorException ();
1817                                 }
1818                                 foreach (LocalInfo vi in temporary_variables) {
1819                                         if (scope != null) {
1820                                                 if (vi.FieldBuilder == null)
1821                                                         vi.FieldBuilder = scope.DefineField (
1822                                                                 vi.Name, vi.VariableType, FieldAttributes.Assembly);
1823                                         } else
1824                                                 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1825                                 }
1826                         }
1827
1828                         if (children != null){
1829                                 foreach (Block b in children)
1830                                         b.EmitMeta (ec);
1831                         }
1832                 }
1833
1834                 void UsageWarning (FlowBranching.UsageVector vector)
1835                 {
1836                         string name;
1837                         
1838                         if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1839                                 foreach (DictionaryEntry de in variables){
1840                                         LocalInfo vi = (LocalInfo) de.Value;
1841
1842                                         if (vi.Used)
1843                                                 continue;
1844
1845                                         name = (string) de.Key;
1846
1847                                         // vi.VariableInfo can be null for 'catch' variables
1848                                         if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
1849                                                 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
1850                                         } else {
1851                                                 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
1852                                         }
1853                                 }
1854                         }
1855                 }
1856
1857                 bool unreachable_shown;
1858                 bool unreachable;
1859
1860                 private void CheckPossibleMistakenEmptyStatement (Statement s)
1861                 {
1862                         Statement body;
1863
1864                         // Some statements are wrapped by a Block. Since
1865                         // others' internal could be changed, here I treat
1866                         // them as possibly wrapped by Block equally.
1867                         Block b = s as Block;
1868                         if (b != null && b.statements.Count == 1)
1869                                 s = (Statement) b.statements [0];
1870
1871                         if (s is Lock)
1872                                 body = ((Lock) s).Statement;
1873                         else if (s is For)
1874                                 body = ((For) s).Statement;
1875                         else if (s is Foreach)
1876                                 body = ((Foreach) s).Statement;
1877                         else if (s is While)
1878                                 body = ((While) s).Statement;
1879                         else if (s is Using)
1880                                 body = ((Using) s).Statement;
1881                         else if (s is Fixed)
1882                                 body = ((Fixed) s).Statement;
1883                         else
1884                                 return;
1885
1886                         if (body == null || body is EmptyStatement)
1887                                 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
1888                 }
1889
1890                 public override bool Resolve (EmitContext ec)
1891                 {
1892                         Block prev_block = ec.CurrentBlock;
1893                         bool ok = true;
1894
1895                         int errors = Report.Errors;
1896
1897                         ec.CurrentBlock = this;
1898                         ec.StartFlowBranching (this);
1899
1900                         Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1901
1902                         //
1903                         // This flag is used to notate nested statements as unreachable from the beginning of this block.
1904                         // For the purposes of this resolution, it doesn't matter that the whole block is unreachable 
1905                         // from the beginning of the function.  The outer Resolve() that detected the unreachability is
1906                         // responsible for handling the situation.
1907                         //
1908                         int statement_count = statements.Count;
1909                         for (int ix = 0; ix < statement_count; ix++){
1910                                 Statement s = (Statement) statements [ix];
1911                                 // Check possible empty statement (CS0642)
1912                                 if (RootContext.WarningLevel >= 3 &&
1913                                         ix + 1 < statement_count &&
1914                                                 statements [ix + 1] is Block)
1915                                         CheckPossibleMistakenEmptyStatement (s);
1916
1917                                 if (unreachable) {
1918                                         if (s is EmptyStatement)
1919                                                 continue;
1920
1921                                         if (s is Block)
1922                                                 ((Block) s).unreachable = true;
1923
1924                                         if (!unreachable_shown && !(s is LabeledStatement)) {
1925                                                 Report.Warning (162, 2, s.loc, "Unreachable code detected");
1926                                                 unreachable_shown = true;
1927                                         }
1928                                 }
1929
1930                                 if (!s.Resolve (ec)) {
1931                                         ok = false;
1932                                         statements [ix] = EmptyStatement.Value;
1933                                         continue;
1934                                 }
1935
1936                                 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1937                                         statements [ix] = EmptyStatement.Value;
1938
1939                                 num_statements = ix + 1;
1940
1941                                 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1942                                 if (unreachable && s is LabeledStatement)
1943                                         throw new InternalErrorException ("should not happen");
1944                         }
1945
1946                         Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1947                                       ec.CurrentBranching, statement_count, num_statements);
1948
1949                         while (ec.CurrentBranching is FlowBranchingLabeled)
1950                                 ec.EndFlowBranching ();
1951
1952                         FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1953
1954                         ec.CurrentBlock = prev_block;
1955
1956                         // If we're a non-static `struct' constructor which doesn't have an
1957                         // initializer, then we must initialize all of the struct's fields.
1958                         if ((flags & Flags.IsToplevel) != 0 && 
1959                             !Toplevel.IsThisAssigned (ec) &&
1960                             !vector.Reachability.AlwaysThrows)
1961                                 ok = false;
1962
1963                         if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1964                                 foreach (LabeledStatement label in labels.Values)
1965                                         if (!label.HasBeenReferenced)
1966                                                 Report.Warning (164, 2, label.loc,
1967                                                                 "This label has not been referenced");
1968                         }
1969
1970                         Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1971
1972                         if (vector.Reachability.IsUnreachable)
1973                                 flags |= Flags.HasRet;
1974
1975                         if (ok && (errors == Report.Errors)) {
1976                                 if (RootContext.WarningLevel >= 3)
1977                                         UsageWarning (vector);
1978                         }
1979
1980                         return ok;
1981                 }
1982                 
1983                 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1984                 {
1985                         unreachable_shown = true;
1986                         unreachable = true;
1987
1988                         if (warn)
1989                                 Report.Warning (162, 2, loc, "Unreachable code detected");
1990
1991                         ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1992                         bool ok = Resolve (ec);
1993                         ec.KillFlowBranching ();
1994
1995                         return ok;
1996                 }
1997                 
1998                 protected override void DoEmit (EmitContext ec)
1999                 {
2000                         for (int ix = 0; ix < num_statements; ix++){
2001                                 Statement s = (Statement) statements [ix];
2002
2003                                 // Check whether we are the last statement in a
2004                                 // top-level block.
2005
2006                                 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2007                                         ec.IsLastStatement = true;
2008                                 else
2009                                         ec.IsLastStatement = false;
2010
2011                                 s.Emit (ec);
2012                         }
2013                 }
2014
2015                 public override void Emit (EmitContext ec)
2016                 {
2017                         Block prev_block = ec.CurrentBlock;
2018
2019                         ec.CurrentBlock = this;
2020
2021                         bool emit_debug_info = (CodeGen.SymbolWriter != null);
2022                         bool is_lexical_block = !Implicit && (Parent != null);
2023
2024                         if (emit_debug_info) {
2025                                 if (is_lexical_block)
2026                                         ec.BeginScope ();
2027
2028                                 if (variables != null) {
2029                                         foreach (DictionaryEntry de in variables) {
2030                                                 string name = (string) de.Key;
2031                                                 LocalInfo vi = (LocalInfo) de.Value;
2032
2033                                                 if (vi.LocalBuilder == null)
2034                                                         continue;
2035
2036                                                 ec.DefineLocalVariable (name, vi.LocalBuilder);
2037                                         }
2038                                 }
2039                         }
2040                         ec.Mark (StartLocation, true);
2041                         ec.EmitScopeInitFromBlock (this);
2042                         DoEmit (ec);
2043                         ec.Mark (EndLocation, true); 
2044
2045                         if (emit_debug_info && is_lexical_block)
2046                                 ec.EndScope ();
2047
2048                         ec.CurrentBlock = prev_block;
2049                 }
2050
2051                 //
2052                 // Returns true if we ar ea child of `b'.
2053                 //
2054                 public bool IsChildOf (Block b)
2055                 {
2056                         Block current = this;
2057                         
2058                         do {
2059                                 if (current.Parent == b)
2060                                         return true;
2061                                 current = current.Parent;
2062                         } while (current != null);
2063                         return false;
2064                 }
2065
2066                 public override string ToString ()
2067                 {
2068                         return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2069                 }
2070         }
2071
2072         //
2073         // A toplevel block contains extra information, the split is done
2074         // only to separate information that would otherwise bloat the more
2075         // lightweight Block.
2076         //
2077         // In particular, this was introduced when the support for Anonymous
2078         // Methods was implemented. 
2079         // 
2080         public class ToplevelBlock : Block {
2081                 //
2082                 // Pointer to the host of this anonymous method, or null
2083                 // if we are the topmost block
2084                 //
2085                 ToplevelBlock container;
2086                 CaptureContext capture_context;
2087                 FlowBranchingToplevel top_level_branching;
2088
2089                 Hashtable capture_contexts;
2090                 ArrayList children;
2091
2092                 public bool HasVarargs {
2093                         get { return (flags & Flags.HasVarargs) != 0; }
2094                         set { flags |= Flags.HasVarargs; }
2095                 }
2096
2097                 //
2098                 // The parameters for the block.
2099                 //
2100                 Parameters parameters;
2101                 public Parameters Parameters {
2102                         get { return parameters; }
2103                 }
2104
2105                 public void RegisterCaptureContext (CaptureContext cc)
2106                 {
2107                         if (capture_contexts == null)
2108                                 capture_contexts = new Hashtable ();
2109                         capture_contexts [cc] = cc;
2110                 }
2111
2112                 public void CompleteContexts ()
2113                 {
2114                         if (capture_contexts == null)
2115                                 return;
2116
2117                         foreach (CaptureContext cc in capture_contexts.Keys){
2118                                 cc.LinkScopes ();
2119                         }
2120                 }
2121
2122                 public CaptureContext ToplevelBlockCaptureContext {
2123                         get { return capture_context; }
2124                 }
2125
2126                 public ToplevelBlock Container {
2127                         get { return container; }
2128                 }
2129
2130                 protected void AddChild (ToplevelBlock block)
2131                 {
2132                         if (children == null)
2133                                 children = new ArrayList ();
2134
2135                         children.Add (block);
2136                 }
2137
2138                 //
2139                 // Parent is only used by anonymous blocks to link back to their
2140                 // parents
2141                 //
2142                 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2143                         this (container, (Flags) 0, parameters, start)
2144                 {
2145                 }
2146                 
2147                 public ToplevelBlock (Parameters parameters, Location start) :
2148                         this (null, (Flags) 0, parameters, start)
2149                 {
2150                 }
2151
2152                 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2153                         this (null, flags, parameters, start)
2154                 {
2155                 }
2156
2157                 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2158                         base (null, flags | Flags.IsToplevel, start, Location.Null)
2159                 {
2160                         this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2161                         this.container = container;
2162
2163                         if (container != null)
2164                                 container.AddChild (this);
2165                 }
2166
2167                 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2168                 {
2169                 }
2170
2171                 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2172                 {
2173                         if (capture_context == null)
2174                                 capture_context = new CaptureContext (this, loc, host);
2175                 }
2176
2177                 public CaptureContext CaptureContext {
2178                         get { return capture_context; }
2179                 }
2180
2181                 public FlowBranchingToplevel TopLevelBranching {
2182                         get { return top_level_branching; }
2183                 }
2184
2185                 //
2186                 // This is used if anonymous methods are used inside an iterator
2187                 // (see 2test-22.cs for an example).
2188                 //
2189                 // The AnonymousMethod is created while parsing - at a time when we don't
2190                 // know yet that we're inside an iterator, so it's `Container' is initially
2191                 // null.  Later on, when resolving the iterator, we need to move the
2192                 // anonymous method into that iterator.
2193                 //
2194                 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2195                 {
2196                         foreach (ToplevelBlock block in children) {
2197                                 if (block.CaptureContext == null)
2198                                         continue;
2199
2200                                 block.container = new_parent;
2201                                 block.CaptureContext.ReParent (new_parent, new_host);
2202                         }
2203                 }
2204
2205                 //
2206                 // Returns a `ParameterReference' for the given name, or null if there
2207                 // is no such parameter
2208                 //
2209                 public ParameterReference GetParameterReference (string name, Location loc)
2210                 {
2211                         Parameter par;
2212                         int idx;
2213
2214                         for (ToplevelBlock t = this; t != null; t = t.Container) {
2215                                 Parameters pars = t.Parameters;
2216                                 par = pars.GetParameterByName (name, out idx);
2217                                 if (par != null)
2218                                         return new ParameterReference (par, this, idx, loc);
2219                         }
2220                         return null;
2221                 }
2222
2223                 //
2224                 // Whether the parameter named `name' is local to this block, 
2225                 // or false, if the parameter belongs to an encompassing block.
2226                 //
2227                 public bool IsLocalParameter (string name)
2228                 {
2229                         return Parameters.GetParameterByName (name) != null;
2230                 }
2231                 
2232                 //
2233                 // Whether the `name' is a parameter reference
2234                 //
2235                 public bool IsParameterReference (string name)
2236                 {
2237                         for (ToplevelBlock t = this; t != null; t = t.Container) {
2238                                 if (t.IsLocalParameter (name))
2239                                         return true;
2240                         }
2241                         return false;
2242                 }
2243
2244                 LocalInfo this_variable = null;
2245
2246                 // <summary>
2247                 //   Returns the "this" instance variable of this block.
2248                 //   See AddThisVariable() for more information.
2249                 // </summary>
2250                 public LocalInfo ThisVariable {
2251                         get { return this_variable; }
2252                 }
2253
2254
2255                 // <summary>
2256                 //   This is used by non-static `struct' constructors which do not have an
2257                 //   initializer - in this case, the constructor must initialize all of the
2258                 //   struct's fields.  To do this, we add a "this" variable and use the flow
2259                 //   analysis code to ensure that it's been fully initialized before control
2260                 //   leaves the constructor.
2261                 // </summary>
2262                 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2263                 {
2264                         if (this_variable == null) {
2265                                 this_variable = new LocalInfo (ds, this, l);
2266                                 this_variable.Used = true;
2267                                 this_variable.IsThis = true;
2268
2269                                 Variables.Add ("this", this_variable);
2270                         }
2271
2272                         return this_variable;
2273                 }
2274
2275                 public bool IsThisAssigned (EmitContext ec)
2276                 {
2277                         return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2278                 }
2279
2280                 public bool ResolveMeta (EmitContext ec, Parameters ip)
2281                 {
2282                         int errors = Report.Errors;
2283
2284                         if (top_level_branching != null)
2285                                 return true;
2286
2287                         if (ip != null)
2288                                 parameters = ip;
2289
2290                         ResolveMeta (this, ec, ip);
2291
2292                         top_level_branching = ec.StartFlowBranching (this);
2293
2294                         return Report.Errors == errors;
2295                 }
2296         }
2297         
2298         public class SwitchLabel {
2299                 Expression label;
2300                 object converted;
2301                 Location loc;
2302
2303                 Label il_label;
2304                 bool  il_label_set;
2305                 Label il_label_code;
2306                 bool  il_label_code_set;
2307
2308                 public static readonly object NullStringCase = new object ();
2309
2310                 //
2311                 // if expr == null, then it is the default case.
2312                 //
2313                 public SwitchLabel (Expression expr, Location l)
2314                 {
2315                         label = expr;
2316                         loc = l;
2317                 }
2318
2319                 public Expression Label {
2320                         get {
2321                                 return label;
2322                         }
2323                 }
2324
2325                 public object Converted {
2326                         get {
2327                                 return converted;
2328                         }
2329                 }
2330
2331                 public Label GetILLabel (EmitContext ec)
2332                 {
2333                         if (!il_label_set){
2334                                 il_label = ec.ig.DefineLabel ();
2335                                 il_label_set = true;
2336                         }
2337                         return il_label;
2338                 }
2339
2340                 public Label GetILLabelCode (EmitContext ec)
2341                 {
2342                         if (!il_label_code_set){
2343                                 il_label_code = ec.ig.DefineLabel ();
2344                                 il_label_code_set = true;
2345                         }
2346                         return il_label_code;
2347                 }                               
2348                 
2349                 //
2350                 // Resolves the expression, reduces it to a literal if possible
2351                 // and then converts it to the requested type.
2352                 //
2353                 public bool ResolveAndReduce (EmitContext ec, Type required_type, bool allow_nullable)
2354                 {       
2355                         Expression e = label.Resolve (ec);
2356
2357                         if (e == null)
2358                                 return false;
2359
2360                         Constant c = e as Constant;
2361                         if (c == null){
2362                                 Report.Error (150, loc, "A constant value is expected");
2363                                 return false;
2364                         }
2365
2366                         if (required_type == TypeManager.string_type && c.GetValue () == null) {
2367                                 converted = NullStringCase;
2368                                 return true;
2369                         }
2370
2371                         if (allow_nullable && c.GetValue () == null) {
2372                                 converted = NullStringCase;
2373                                 return true;
2374                         }
2375
2376                         c = c.ToType (required_type, loc);
2377                         if (c == null)
2378                                 return false;
2379
2380                         converted = c.GetValue ();
2381                         return true;
2382                 }
2383
2384                 public void Erorr_AlreadyOccurs ()
2385                 {
2386                         string label;
2387                         if (converted == null)
2388                                 label = "default";
2389                         else if (converted == NullStringCase)
2390                                 label = "null";
2391                         else
2392                                 label = converted.ToString ();
2393
2394                         Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2395                 }
2396         }
2397
2398         public class SwitchSection {
2399                 // An array of SwitchLabels.
2400                 public readonly ArrayList Labels;
2401                 public readonly Block Block;
2402                 
2403                 public SwitchSection (ArrayList labels, Block block)
2404                 {
2405                         Labels = labels;
2406                         Block = block;
2407                 }
2408         }
2409         
2410         public class Switch : Statement {
2411                 public readonly ArrayList Sections;
2412                 public Expression Expr;
2413
2414                 /// <summary>
2415                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
2416                 /// </summary>
2417                 public IDictionary Elements;
2418
2419                 /// <summary>
2420                 ///   The governing switch type
2421                 /// </summary>
2422                 public Type SwitchType;
2423
2424                 //
2425                 // Computed
2426                 //
2427                 Label default_target;
2428                 Label null_target;
2429                 Expression new_expr;
2430                 Nullable.Unwrap unwrap;
2431                 bool is_constant;
2432                 SwitchSection constant_section;
2433                 SwitchSection default_section;
2434
2435                 //
2436                 // The types allowed to be implicitly cast from
2437                 // on the governing type
2438                 //
2439                 static Type [] allowed_types;
2440                 
2441                 public Switch (Expression e, ArrayList sects, Location l)
2442                 {
2443                         Expr = e;
2444                         Sections = sects;
2445                         loc = l;
2446                 }
2447
2448                 public bool GotDefault {
2449                         get {
2450                                 return default_section != null;
2451                         }
2452                 }
2453
2454                 public Label DefaultTarget {
2455                         get {
2456                                 return default_target;
2457                         }
2458                 }
2459
2460                 //
2461                 // Determines the governing type for a switch.  The returned
2462                 // expression might be the expression from the switch, or an
2463                 // expression that includes any potential conversions to the
2464                 // integral types or to string.
2465                 //
2466                 Expression SwitchGoverningType (EmitContext ec, Expression expr)
2467                 {
2468                         Type t = expr.Type;
2469
2470                         if (t == TypeManager.byte_type ||
2471                             t == TypeManager.sbyte_type ||
2472                             t == TypeManager.ushort_type ||
2473                             t == TypeManager.short_type ||
2474                             t == TypeManager.uint32_type ||
2475                             t == TypeManager.int32_type ||
2476                             t == TypeManager.uint64_type ||
2477                             t == TypeManager.int64_type ||
2478                             t == TypeManager.char_type ||
2479                             t == TypeManager.string_type ||
2480                             t == TypeManager.bool_type ||
2481                             t.IsSubclassOf (TypeManager.enum_type))
2482                                 return expr;
2483
2484                         if (allowed_types == null){
2485                                 allowed_types = new Type [] {
2486                                         TypeManager.sbyte_type,
2487                                         TypeManager.byte_type,
2488                                         TypeManager.short_type,
2489                                         TypeManager.ushort_type,
2490                                         TypeManager.int32_type,
2491                                         TypeManager.uint32_type,
2492                                         TypeManager.int64_type,
2493                                         TypeManager.uint64_type,
2494                                         TypeManager.char_type,
2495                                         TypeManager.string_type,
2496                                         TypeManager.bool_type
2497                                 };
2498                         }
2499
2500                         //
2501                         // Try to find a *user* defined implicit conversion.
2502                         //
2503                         // If there is no implicit conversion, or if there are multiple
2504                         // conversions, we have to report an error
2505                         //
2506                         Expression converted = null;
2507                         foreach (Type tt in allowed_types){
2508                                 Expression e;
2509                                 
2510                                 e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
2511                                 if (e == null)
2512                                         continue;
2513
2514                                 //
2515                                 // Ignore over-worked ImplicitUserConversions that do
2516                                 // an implicit conversion in addition to the user conversion.
2517                                 // 
2518                                 if (!(e is UserCast))
2519                                         continue;
2520
2521                                 if (converted != null){
2522                                         Report.ExtraInformation (
2523                                                 loc,
2524                                                 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2525                                                                TypeManager.CSharpName (expr.Type)));
2526                                         return null;
2527                                 }
2528
2529                                 converted = e;
2530                         }
2531                         return converted;
2532                 }
2533
2534                 //
2535                 // Performs the basic sanity checks on the switch statement
2536                 // (looks for duplicate keys and non-constant expressions).
2537                 //
2538                 // It also returns a hashtable with the keys that we will later
2539                 // use to compute the switch tables
2540                 //
2541                 bool CheckSwitch (EmitContext ec)
2542                 {
2543                         bool error = false;
2544                         Elements = Sections.Count > 10 ? 
2545                                 (IDictionary)new Hashtable () : 
2546                                 (IDictionary)new ListDictionary ();
2547                                 
2548                         foreach (SwitchSection ss in Sections){
2549                                 foreach (SwitchLabel sl in ss.Labels){
2550                                         if (sl.Label == null){
2551                                                 if (default_section != null){
2552                                                         sl.Erorr_AlreadyOccurs ();
2553                                                         error = true;
2554                                                 }
2555                                                 default_section = ss;
2556                                                 continue;
2557                                         }
2558
2559                                         if (!sl.ResolveAndReduce (ec, SwitchType, unwrap != null)){
2560                                                 error = true;
2561                                                 continue;
2562                                         }
2563                                         
2564                                         object key = sl.Converted;
2565                                         try {
2566                                                 Elements.Add (key, sl);
2567                                         } catch (ArgumentException) {
2568                                                 sl.Erorr_AlreadyOccurs ();
2569                                                 error = true;
2570                                         }
2571                                 }
2572                         }
2573                         return !error;
2574                 }
2575
2576                 void EmitObjectInteger (ILGenerator ig, object k)
2577                 {
2578                         if (k is int)
2579                                 IntConstant.EmitInt (ig, (int) k);
2580                         else if (k is Constant) {
2581                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2582                         } 
2583                         else if (k is uint)
2584                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2585                         else if (k is long)
2586                         {
2587                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2588                                 {
2589                                         IntConstant.EmitInt (ig, (int) (long) k);
2590                                         ig.Emit (OpCodes.Conv_I8);
2591                                 }
2592                                 else
2593                                         LongConstant.EmitLong (ig, (long) k);
2594                         }
2595                         else if (k is ulong)
2596                         {
2597                                 ulong ul = (ulong) k;
2598                                 if (ul < (1L<<32))
2599                                 {
2600                                         IntConstant.EmitInt (ig, unchecked ((int) ul));
2601                                         ig.Emit (OpCodes.Conv_U8);
2602                                 }
2603                                 else
2604                                 {
2605                                         LongConstant.EmitLong (ig, unchecked ((long) ul));
2606                                 }
2607                         }
2608                         else if (k is char)
2609                                 IntConstant.EmitInt (ig, (int) ((char) k));
2610                         else if (k is sbyte)
2611                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2612                         else if (k is byte)
2613                                 IntConstant.EmitInt (ig, (int) ((byte) k));
2614                         else if (k is short)
2615                                 IntConstant.EmitInt (ig, (int) ((short) k));
2616                         else if (k is ushort)
2617                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
2618                         else if (k is bool)
2619                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2620                         else
2621                                 throw new Exception ("Unhandled case");
2622                 }
2623                 
2624                 // structure used to hold blocks of keys while calculating table switch
2625                 class KeyBlock : IComparable
2626                 {
2627                         public KeyBlock (long _nFirst)
2628                         {
2629                                 nFirst = nLast = _nFirst;
2630                         }
2631                         public long nFirst;
2632                         public long nLast;
2633                         public ArrayList rgKeys = null;
2634                         // how many items are in the bucket
2635                         public int Size = 1;
2636                         public int Length
2637                         {
2638                                 get { return (int) (nLast - nFirst + 1); }
2639                         }
2640                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2641                         {
2642                                 return kbLast.nLast - kbFirst.nFirst + 1;
2643                         }
2644                         public int CompareTo (object obj)
2645                         {
2646                                 KeyBlock kb = (KeyBlock) obj;
2647                                 int nLength = Length;
2648                                 int nLengthOther = kb.Length;
2649                                 if (nLengthOther == nLength)
2650                                         return (int) (kb.nFirst - nFirst);
2651                                 return nLength - nLengthOther;
2652                         }
2653                 }
2654
2655                 /// <summary>
2656                 /// This method emits code for a lookup-based switch statement (non-string)
2657                 /// Basically it groups the cases into blocks that are at least half full,
2658                 /// and then spits out individual lookup opcodes for each block.
2659                 /// It emits the longest blocks first, and short blocks are just
2660                 /// handled with direct compares.
2661                 /// </summary>
2662                 /// <param name="ec"></param>
2663                 /// <param name="val"></param>
2664                 /// <returns></returns>
2665                 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2666                 {
2667                         int cElements = Elements.Count;
2668                         object [] rgKeys = new object [cElements];
2669                         Elements.Keys.CopyTo (rgKeys, 0);
2670                         Array.Sort (rgKeys);
2671
2672                         // initialize the block list with one element per key
2673                         ArrayList rgKeyBlocks = new ArrayList ();
2674                         foreach (object key in rgKeys)
2675                                 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2676
2677                         KeyBlock kbCurr;
2678                         // iteratively merge the blocks while they are at least half full
2679                         // there's probably a really cool way to do this with a tree...
2680                         while (rgKeyBlocks.Count > 1)
2681                         {
2682                                 ArrayList rgKeyBlocksNew = new ArrayList ();
2683                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2684                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2685                                 {
2686                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2687                                         if ((kbCurr.Size + kb.Size) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
2688                                         {
2689                                                 // merge blocks
2690                                                 kbCurr.nLast = kb.nLast;
2691                                                 kbCurr.Size += kb.Size;
2692                                         }
2693                                         else
2694                                         {
2695                                                 // start a new block
2696                                                 rgKeyBlocksNew.Add (kbCurr);
2697                                                 kbCurr = kb;
2698                                         }
2699                                 }
2700                                 rgKeyBlocksNew.Add (kbCurr);
2701                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2702                                         break;
2703                                 rgKeyBlocks = rgKeyBlocksNew;
2704                         }
2705
2706                         // initialize the key lists
2707                         foreach (KeyBlock kb in rgKeyBlocks)
2708                                 kb.rgKeys = new ArrayList ();
2709
2710                         // fill the key lists
2711                         int iBlockCurr = 0;
2712                         if (rgKeyBlocks.Count > 0) {
2713                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2714                                 foreach (object key in rgKeys)
2715                                 {
2716                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2717                                                 System.Convert.ToInt64 (key) > kbCurr.nLast;
2718                                         if (fNextBlock)
2719                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2720                                         kbCurr.rgKeys.Add (key);
2721                                 }
2722                         }
2723
2724                         // sort the blocks so we can tackle the largest ones first
2725                         rgKeyBlocks.Sort ();
2726
2727                         // okay now we can start...
2728                         ILGenerator ig = ec.ig;
2729                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
2730                         Label lblDefault = ig.DefineLabel ();
2731
2732                         Type typeKeys = null;
2733                         if (rgKeys.Length > 0)
2734                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
2735
2736                         Type compare_type;
2737                         
2738                         if (TypeManager.IsEnumType (SwitchType))
2739                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2740                         else
2741                                 compare_type = SwitchType;
2742                         
2743                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2744                         {
2745                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2746                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2747                                 if (kb.Length <= 2)
2748                                 {
2749                                         foreach (object key in kb.rgKeys)
2750                                         {
2751                                                 ig.Emit (OpCodes.Ldloc, val);
2752                                                 EmitObjectInteger (ig, key);
2753                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
2754                                                 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2755                                         }
2756                                 }
2757                                 else
2758                                 {
2759                                         // TODO: if all the keys in the block are the same and there are
2760                                         //       no gaps/defaults then just use a range-check.
2761                                         if (compare_type == TypeManager.int64_type ||
2762                                                 compare_type == TypeManager.uint64_type)
2763                                         {
2764                                                 // TODO: optimize constant/I4 cases
2765
2766                                                 // check block range (could be > 2^31)
2767                                                 ig.Emit (OpCodes.Ldloc, val);
2768                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2769                                                 ig.Emit (OpCodes.Blt, lblDefault);
2770                                                 ig.Emit (OpCodes.Ldloc, val);
2771                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2772                                                 ig.Emit (OpCodes.Bgt, lblDefault);
2773
2774                                                 // normalize range
2775                                                 ig.Emit (OpCodes.Ldloc, val);
2776                                                 if (kb.nFirst != 0)
2777                                                 {
2778                                                         EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2779                                                         ig.Emit (OpCodes.Sub);
2780                                                 }
2781                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
2782                                         }
2783                                         else
2784                                         {
2785                                                 // normalize range
2786                                                 ig.Emit (OpCodes.Ldloc, val);
2787                                                 int nFirst = (int) kb.nFirst;
2788                                                 if (nFirst > 0)
2789                                                 {
2790                                                         IntConstant.EmitInt (ig, nFirst);
2791                                                         ig.Emit (OpCodes.Sub);
2792                                                 }
2793                                                 else if (nFirst < 0)
2794                                                 {
2795                                                         IntConstant.EmitInt (ig, -nFirst);
2796                                                         ig.Emit (OpCodes.Add);
2797                                                 }
2798                                         }
2799
2800                                         // first, build the list of labels for the switch
2801                                         int iKey = 0;
2802                                         int cJumps = kb.Length;
2803                                         Label [] rgLabels = new Label [cJumps];
2804                                         for (int iJump = 0; iJump < cJumps; iJump++)
2805                                         {
2806                                                 object key = kb.rgKeys [iKey];
2807                                                 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2808                                                 {
2809                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
2810                                                         rgLabels [iJump] = sl.GetILLabel (ec);
2811                                                         iKey++;
2812                                                 }
2813                                                 else
2814                                                         rgLabels [iJump] = lblDefault;
2815                                         }
2816                                         // emit the switch opcode
2817                                         ig.Emit (OpCodes.Switch, rgLabels);
2818                                 }
2819
2820                                 // mark the default for this block
2821                                 if (iBlock != 0)
2822                                         ig.MarkLabel (lblDefault);
2823                         }
2824
2825                         // TODO: find the default case and emit it here,
2826                         //       to prevent having to do the following jump.
2827                         //       make sure to mark other labels in the default section
2828
2829                         // the last default just goes to the end
2830                         ig.Emit (OpCodes.Br, lblDefault);
2831
2832                         // now emit the code for the sections
2833                         bool fFoundDefault = false;
2834                         bool fFoundNull = false;
2835                         foreach (SwitchSection ss in Sections)
2836                         {
2837                                 foreach (SwitchLabel sl in ss.Labels)
2838                                         if (sl.Converted == SwitchLabel.NullStringCase)
2839                                                 fFoundNull = true;
2840                         }
2841
2842                         foreach (SwitchSection ss in Sections)
2843                         {
2844                                 foreach (SwitchLabel sl in ss.Labels)
2845                                 {
2846                                         ig.MarkLabel (sl.GetILLabel (ec));
2847                                         ig.MarkLabel (sl.GetILLabelCode (ec));
2848                                         if (sl.Converted == SwitchLabel.NullStringCase)
2849                                                 ig.MarkLabel (null_target);
2850                                         else if (sl.Label == null) {
2851                                                 ig.MarkLabel (lblDefault);
2852                                                 fFoundDefault = true;
2853                                                 if (!fFoundNull)
2854                                                         ig.MarkLabel (null_target);
2855                                         }
2856                                 }
2857                                 ss.Block.Emit (ec);
2858                                 //ig.Emit (OpCodes.Br, lblEnd);
2859                         }
2860                         
2861                         if (!fFoundDefault) {
2862                                 ig.MarkLabel (lblDefault);
2863                         }
2864                         ig.MarkLabel (lblEnd);
2865                 }
2866                 //
2867                 // This simple emit switch works, but does not take advantage of the
2868                 // `switch' opcode. 
2869                 // TODO: remove non-string logic from here
2870                 // TODO: binary search strings?
2871                 //
2872                 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2873                 {
2874                         ILGenerator ig = ec.ig;
2875                         Label end_of_switch = ig.DefineLabel ();
2876                         Label next_test = ig.DefineLabel ();
2877                         bool first_test = true;
2878                         bool pending_goto_end = false;
2879                         bool null_marked = false;
2880                         bool null_found;
2881
2882                         ig.Emit (OpCodes.Ldloc, val);
2883                         
2884                         if (Elements.Contains (SwitchLabel.NullStringCase)){
2885                                 ig.Emit (OpCodes.Brfalse, null_target);
2886                         } else
2887                                 ig.Emit (OpCodes.Brfalse, default_target);
2888                         
2889                         ig.Emit (OpCodes.Ldloc, val);
2890                         ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2891                         ig.Emit (OpCodes.Stloc, val);
2892
2893                         int section_count = Sections.Count;
2894                         for (int section = 0; section < section_count; section++){
2895                                 SwitchSection ss = (SwitchSection) Sections [section];
2896
2897                                 if (ss == default_section)
2898                                         continue;
2899
2900                                 Label sec_begin = ig.DefineLabel ();
2901
2902                                 ig.Emit (OpCodes.Nop);
2903
2904                                 if (pending_goto_end)
2905                                         ig.Emit (OpCodes.Br, end_of_switch);
2906
2907                                 int label_count = ss.Labels.Count;
2908                                 null_found = false;
2909                                 for (int label = 0; label < label_count; label++){
2910                                         SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2911                                         ig.MarkLabel (sl.GetILLabel (ec));
2912                                         
2913                                         if (!first_test){
2914                                                 ig.MarkLabel (next_test);
2915                                                 next_test = ig.DefineLabel ();
2916                                         }
2917                                         //
2918                                         // If we are the default target
2919                                         //
2920                                         if (sl.Label != null){
2921                                                 object lit = sl.Converted;
2922
2923                                                 if (lit == SwitchLabel.NullStringCase){
2924                                                         null_found = true;
2925                                                         if (label + 1 == label_count)
2926                                                                 ig.Emit (OpCodes.Br, next_test);
2927                                                         continue;
2928                                                 }
2929                                                 
2930                                                 ig.Emit (OpCodes.Ldloc, val);
2931                                                 ig.Emit (OpCodes.Ldstr, (string)lit);
2932                                                 if (label_count == 1)
2933                                                         ig.Emit (OpCodes.Bne_Un, next_test);
2934                                                 else {
2935                                                         if (label+1 == label_count)
2936                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
2937                                                         else
2938                                                                 ig.Emit (OpCodes.Beq, sec_begin);
2939                                                 }
2940                                         }
2941                                 }
2942                                 if (null_found) {
2943                                         ig.MarkLabel (null_target);
2944                                         null_marked = true;
2945                                 }
2946                                 ig.MarkLabel (sec_begin);
2947                                 foreach (SwitchLabel sl in ss.Labels)
2948                                         ig.MarkLabel (sl.GetILLabelCode (ec));
2949
2950                                 ss.Block.Emit (ec);
2951                                 pending_goto_end = !ss.Block.HasRet;
2952                                 first_test = false;
2953                         }
2954                         ig.MarkLabel (next_test);
2955                         ig.MarkLabel (default_target);
2956                         if (!null_marked)
2957                                 ig.MarkLabel (null_target);
2958                         if (default_section != null)
2959                                 default_section.Block.Emit (ec);
2960                         ig.MarkLabel (end_of_switch);
2961                 }
2962
2963                 SwitchSection FindSection (SwitchLabel label)
2964                 {
2965                         foreach (SwitchSection ss in Sections){
2966                                 foreach (SwitchLabel sl in ss.Labels){
2967                                         if (label == sl)
2968                                                 return ss;
2969                                 }
2970                         }
2971
2972                         return null;
2973                 }
2974
2975                 public override bool Resolve (EmitContext ec)
2976                 {
2977                         Expr = Expr.Resolve (ec);
2978                         if (Expr == null)
2979                                 return false;
2980
2981                         new_expr = SwitchGoverningType (ec, Expr);
2982
2983                         if ((new_expr == null) && TypeManager.IsNullableType (Expr.Type)) {
2984                                 unwrap = Nullable.Unwrap.Create (Expr, ec);
2985                                 if (unwrap == null)
2986                                         return false;
2987
2988                                 new_expr = SwitchGoverningType (ec, unwrap);
2989                         }
2990
2991                         if (new_expr == null){
2992                                 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2993                                 return false;
2994                         }
2995
2996                         // Validate switch.
2997                         SwitchType = new_expr.Type;
2998
2999                         if (!CheckSwitch (ec))
3000                                 return false;
3001
3002                         if (unwrap != null) {
3003                                 Elements.Remove (SwitchLabel.NullStringCase);
3004                         }
3005
3006                         Switch old_switch = ec.Switch;
3007                         ec.Switch = this;
3008                         ec.Switch.SwitchType = SwitchType;
3009
3010                         Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3011                         ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3012
3013                         is_constant = new_expr is Constant;
3014                         if (is_constant) {
3015                                 object key = ((Constant) new_expr).GetValue ();
3016                                 SwitchLabel label = (SwitchLabel) Elements [key];
3017
3018                                 constant_section = FindSection (label);
3019                                 if (constant_section == null)
3020                                         constant_section = default_section;
3021                         }
3022
3023                         bool first = true;
3024                         foreach (SwitchSection ss in Sections){
3025                                 if (!first)
3026                                         ec.CurrentBranching.CreateSibling (
3027                                                 null, FlowBranching.SiblingType.SwitchSection);
3028                                 else
3029                                         first = false;
3030
3031                                 if (is_constant && (ss != constant_section)) {
3032                                         // If we're a constant switch, we're only emitting
3033                                         // one single section - mark all the others as
3034                                         // unreachable.
3035                                         ec.CurrentBranching.CurrentUsageVector.Goto ();
3036                                         if (!ss.Block.ResolveUnreachable (ec, true))
3037                                                 return false;
3038                                 } else {
3039                                         if (!ss.Block.Resolve (ec))
3040                                                 return false;
3041                         }
3042                         }
3043
3044                         if (default_section == null)
3045                                 ec.CurrentBranching.CreateSibling (
3046                                         null, FlowBranching.SiblingType.SwitchSection);
3047
3048                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3049                         ec.Switch = old_switch;
3050
3051                         Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3052                                       reachability);
3053
3054                         return true;
3055                 }
3056                 
3057                 protected override void DoEmit (EmitContext ec)
3058                 {
3059                         ILGenerator ig = ec.ig;
3060
3061                         default_target = ig.DefineLabel ();
3062                         null_target = ig.DefineLabel ();
3063
3064                         // Store variable for comparission purposes
3065                         LocalBuilder value;
3066                         if (unwrap != null) {
3067                                 value = ig.DeclareLocal (SwitchType);
3068                                 unwrap.EmitCheck (ec);
3069                                 ig.Emit (OpCodes.Brfalse, null_target);
3070                                 new_expr.Emit (ec);
3071                                 ig.Emit (OpCodes.Stloc, value);
3072                         } else if (!is_constant) {
3073                                 value = ig.DeclareLocal (SwitchType);
3074                                 new_expr.Emit (ec);
3075                                 ig.Emit (OpCodes.Stloc, value);
3076                         } else
3077                                 value = null;
3078
3079                         //
3080                         // Setup the codegen context
3081                         //
3082                         Label old_end = ec.LoopEnd;
3083                         Switch old_switch = ec.Switch;
3084                         
3085                         ec.LoopEnd = ig.DefineLabel ();
3086                         ec.Switch = this;
3087
3088                         // Emit Code.
3089                         if (is_constant) {
3090                                 if (constant_section != null)
3091                                         constant_section.Block.Emit (ec);
3092                         } else if (SwitchType == TypeManager.string_type)
3093                                 SimpleSwitchEmit (ec, value);
3094                         else
3095                                 TableSwitchEmit (ec, value);
3096
3097                         // Restore context state. 
3098                         ig.MarkLabel (ec.LoopEnd);
3099
3100                         //
3101                         // Restore the previous context
3102                         //
3103                         ec.LoopEnd = old_end;
3104                         ec.Switch = old_switch;
3105                 }
3106         }
3107
3108         public abstract class ExceptionStatement : Statement
3109         {
3110                 public abstract void EmitFinally (EmitContext ec);
3111
3112                 protected bool emit_finally = true;
3113                 ArrayList parent_vectors;
3114
3115                 protected void DoEmitFinally (EmitContext ec)
3116                 {
3117                         if (emit_finally)
3118                                 ec.ig.BeginFinallyBlock ();
3119                         else if (ec.InIterator)
3120                                 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3121                         EmitFinally (ec);
3122                 }
3123
3124                 protected void ResolveFinally (FlowBranchingException branching)
3125                 {
3126                         emit_finally = branching.EmitFinally;
3127                         if (!emit_finally)
3128                                 branching.Parent.StealFinallyClauses (ref parent_vectors);
3129                 }
3130         }
3131
3132         public class Lock : ExceptionStatement {
3133                 Expression expr;
3134                 public Statement Statement;
3135                 TemporaryVariable temp;
3136                         
3137                 public Lock (Expression expr, Statement stmt, Location l)
3138                 {
3139                         this.expr = expr;
3140                         Statement = stmt;
3141                         loc = l;
3142                 }
3143
3144                 public override bool Resolve (EmitContext ec)
3145                 {
3146                         expr = expr.Resolve (ec);
3147                         if (expr == null)
3148                                 return false;
3149
3150                         if (expr.Type.IsValueType){
3151                                 Report.Error (185, loc,
3152                                               "`{0}' is not a reference type as required by the lock statement",
3153                                               TypeManager.CSharpName (expr.Type));
3154                                 return false;
3155                         }
3156
3157                         FlowBranchingException branching = ec.StartFlowBranching (this);
3158                         bool ok = Statement.Resolve (ec);
3159                         if (!ok) {
3160                                 ec.KillFlowBranching ();
3161                                 return false;
3162                         }
3163
3164                         ResolveFinally (branching);
3165
3166                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3167                         if (!reachability.AlwaysReturns) {
3168                                 // Unfortunately, System.Reflection.Emit automatically emits
3169                                 // a leave to the end of the finally block.
3170                                 // This is a problem if `returns' is true since we may jump
3171                                 // to a point after the end of the method.
3172                                 // As a workaround, emit an explicit ret here.
3173                                 ec.NeedReturnLabel ();
3174                         }
3175
3176                         Type t = expr.Type;
3177                         if (t == TypeManager.null_type)
3178                                 t = TypeManager.object_type;
3179                         
3180                         temp = new TemporaryVariable (t, loc);
3181                         temp.Resolve (ec);
3182                         
3183                         return true;
3184                 }
3185                 
3186                 protected override void DoEmit (EmitContext ec)
3187                 {
3188                         ILGenerator ig = ec.ig;
3189
3190                         temp.Store (ec, expr);
3191                         temp.Emit (ec);
3192                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3193
3194                         // try
3195                         if (emit_finally)
3196                                 ig.BeginExceptionBlock ();
3197                         Statement.Emit (ec);
3198                         
3199                         // finally
3200                         DoEmitFinally (ec);
3201                         if (emit_finally)
3202                                 ig.EndExceptionBlock ();
3203                 }
3204
3205                 public override void EmitFinally (EmitContext ec)
3206                 {
3207                         temp.Emit (ec);
3208                         ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3209                 }
3210         }
3211
3212         public class Unchecked : Statement {
3213                 public readonly Block Block;
3214                 
3215                 public Unchecked (Block b)
3216                 {
3217                         Block = b;
3218                         b.Unchecked = true;
3219                 }
3220
3221                 public override bool Resolve (EmitContext ec)
3222                 {
3223                         using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3224                                 return Block.Resolve (ec);
3225                 }
3226                 
3227                 protected override void DoEmit (EmitContext ec)
3228                 {
3229                         using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3230                                 Block.Emit (ec);
3231                 }
3232         }
3233
3234         public class Checked : Statement {
3235                 public readonly Block Block;
3236                 
3237                 public Checked (Block b)
3238                 {
3239                         Block = b;
3240                         b.Unchecked = false;
3241                 }
3242
3243                 public override bool Resolve (EmitContext ec)
3244                 {
3245                         using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3246                                 return Block.Resolve (ec);
3247                 }
3248
3249                 protected override void DoEmit (EmitContext ec)
3250                 {
3251                         using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3252                                 Block.Emit (ec);
3253                 }
3254         }
3255
3256         public class Unsafe : Statement {
3257                 public readonly Block Block;
3258
3259                 public Unsafe (Block b)
3260                 {
3261                         Block = b;
3262                         Block.Unsafe = true;
3263                 }
3264
3265                 public override bool Resolve (EmitContext ec)
3266                 {
3267                         using (ec.With (EmitContext.Flags.InUnsafe, true))
3268                                 return Block.Resolve (ec);
3269                 }
3270                 
3271                 protected override void DoEmit (EmitContext ec)
3272                 {
3273                         using (ec.With (EmitContext.Flags.InUnsafe, true))
3274                                 Block.Emit (ec);
3275                 }
3276         }
3277
3278         // 
3279         // Fixed statement
3280         //
3281         public class Fixed : Statement {
3282                 Expression type;
3283                 ArrayList declarators;
3284                 Statement statement;
3285                 Type expr_type;
3286                 Emitter[] data;
3287                 bool has_ret;
3288
3289                 abstract class Emitter
3290                 {
3291                         protected LocalInfo vi;
3292                         protected Expression converted;
3293
3294                         protected Emitter (Expression expr, LocalInfo li)
3295                         {
3296                                 converted = expr;
3297                                 vi = li;
3298                         }
3299
3300                         public abstract void Emit (EmitContext ec);
3301                         public abstract void EmitExit (ILGenerator ig);
3302                 }
3303
3304                 class ExpressionEmitter : Emitter {
3305                         public ExpressionEmitter (Expression converted, LocalInfo li) :
3306                                 base (converted, li)
3307                         {
3308                         }
3309
3310                         public override void Emit (EmitContext ec) {
3311                                 //
3312                                 // Store pointer in pinned location
3313                                 //
3314                                 converted.Emit (ec);
3315                                 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3316                         }
3317
3318                         public override void EmitExit (ILGenerator ig)
3319                         {
3320                                 ig.Emit (OpCodes.Ldc_I4_0);
3321                                 ig.Emit (OpCodes.Conv_U);
3322                                 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3323                         }
3324                 }
3325
3326                 class StringEmitter : Emitter {
3327                         LocalBuilder pinned_string;
3328                         Location loc;
3329
3330                         public StringEmitter (Expression expr, LocalInfo li, Location loc):
3331                                 base (expr, li)
3332                         {
3333                                 this.loc = loc;
3334                         }
3335
3336                         public override void Emit (EmitContext ec)
3337                         {
3338                                 ILGenerator ig = ec.ig;
3339                                 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3340                                         
3341                                 converted.Emit (ec);
3342                                 ig.Emit (OpCodes.Stloc, pinned_string);
3343
3344                                 Expression sptr = new StringPtr (pinned_string, loc);
3345                                 converted = Convert.ImplicitConversionRequired (
3346                                         ec, sptr, vi.VariableType, loc);
3347                                         
3348                                 if (converted == null)
3349                                         return;
3350
3351                                 converted.Emit (ec);
3352                                 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3353                         }
3354
3355                         public override void EmitExit(ILGenerator ig)
3356                         {
3357                                 ig.Emit (OpCodes.Ldnull);
3358                                 ig.Emit (OpCodes.Stloc, pinned_string);
3359                         }
3360                 }
3361
3362                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3363                 {
3364                         this.type = type;
3365                         declarators = decls;
3366                         statement = stmt;
3367                         loc = l;
3368                 }
3369
3370                 public Statement Statement {
3371                         get { return statement; }
3372                 }
3373
3374                 public override bool Resolve (EmitContext ec)
3375                 {
3376                         if (!ec.InUnsafe){
3377                                 Expression.UnsafeError (loc);
3378                                 return false;
3379                         }
3380                         
3381                         TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3382                         if (texpr == null)
3383                                 return false;
3384
3385                         expr_type = texpr.Type;
3386
3387                         data = new Emitter [declarators.Count];
3388
3389                         if (!expr_type.IsPointer){
3390                                 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3391                                 return false;
3392                         }
3393                         
3394                         int i = 0;
3395                         foreach (Pair p in declarators){
3396                                 LocalInfo vi = (LocalInfo) p.First;
3397                                 Expression e = (Expression) p.Second;
3398
3399                                 vi.VariableInfo.SetAssigned (ec);
3400                                 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3401
3402                                 //
3403                                 // The rules for the possible declarators are pretty wise,
3404                                 // but the production on the grammar is more concise.
3405                                 //
3406                                 // So we have to enforce these rules here.
3407                                 //
3408                                 // We do not resolve before doing the case 1 test,
3409                                 // because the grammar is explicit in that the token &
3410                                 // is present, so we need to test for this particular case.
3411                                 //
3412
3413                                 if (e is Cast){
3414                                         Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3415                                         return false;
3416                                 }
3417                                 
3418                                 //
3419                                 // Case 1: & object.
3420                                 //
3421                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3422                                         Expression child = ((Unary) e).Expr;
3423
3424                                         if (child is ParameterReference || child is LocalVariableReference){
3425                                                 Report.Error (
3426                                                         213, loc, 
3427                                                         "No need to use fixed statement for parameters or " +
3428                                                         "local variable declarations (address is already " +
3429                                                         "fixed)");
3430                                                 return false;
3431                                         }
3432
3433                                         ec.InFixedInitializer = true;
3434                                         e = e.Resolve (ec);
3435                                         ec.InFixedInitializer = false;
3436                                         if (e == null)
3437                                                 return false;
3438
3439                                         child = ((Unary) e).Expr;
3440                                         
3441                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
3442                                                 return false;
3443
3444                                         if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
3445                                                 e.Error_ValueCannotBeConverted (e.Location, expr_type, false);
3446                                                 return false;
3447                                         }
3448
3449                                         data [i] = new ExpressionEmitter (e, vi);
3450                                         i++;
3451
3452                                         continue;
3453                                 }
3454
3455                                 ec.InFixedInitializer = true;
3456                                 e = e.Resolve (ec);
3457                                 ec.InFixedInitializer = false;
3458                                 if (e == null)
3459                                         return false;
3460
3461                                 //
3462                                 // Case 2: Array
3463                                 //
3464                                 if (e.Type.IsArray){
3465                                         Type array_type = TypeManager.GetElementType (e.Type);
3466                                         
3467                                         //
3468                                         // Provided that array_type is unmanaged,
3469                                         //
3470                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
3471                                                 return false;
3472
3473                                         //
3474                                         // and T* is implicitly convertible to the
3475                                         // pointer type given in the fixed statement.
3476                                         //
3477                                         ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3478                                         
3479                                         Expression converted = Convert.ImplicitConversionRequired (
3480                                                 ec, array_ptr, vi.VariableType, loc);
3481                                         if (converted == null)
3482                                                 return false;
3483
3484                                         data [i] = new ExpressionEmitter (converted, vi);
3485                                         i++;
3486
3487                                         continue;
3488                                 }
3489
3490                                 //
3491                                 // Case 3: string
3492                                 //
3493                                 if (e.Type == TypeManager.string_type){
3494                                         data [i] = new StringEmitter (e, vi, loc);
3495                                         i++;
3496                                         continue;
3497                                 }
3498
3499                                 // Case 4: fixed buffer
3500                                 FieldExpr fe = e as FieldExpr;
3501                                 if (fe != null) {
3502                                         IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3503                                         if (ff != null) {
3504                                                 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3505                                         
3506                                                 Expression converted = Convert.ImplicitConversionRequired (
3507                                                         ec, fixed_buffer_ptr, vi.VariableType, loc);
3508                                                 if (converted == null)
3509                                                         return false;
3510
3511                                                 data [i] = new ExpressionEmitter (converted, vi);
3512                                                 i++;
3513
3514                                                 continue;
3515                                         }
3516                                 }
3517
3518                                 //
3519                                 // For other cases, flag a `this is already fixed expression'
3520                                 //
3521                                 if (e is LocalVariableReference || e is ParameterReference ||
3522                                     Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3523                                     
3524                                         Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3525                                         return false;
3526                                 }
3527
3528                                 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3529                                 return false;
3530                         }
3531
3532                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3533
3534                         if (!statement.Resolve (ec)) {
3535                                 ec.KillFlowBranching ();
3536                                 return false;
3537                         }
3538
3539                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3540                         has_ret = reachability.IsUnreachable;
3541
3542                         return true;
3543                 }
3544                 
3545                 protected override void DoEmit (EmitContext ec)
3546                 {
3547                         for (int i = 0; i < data.Length; i++) {
3548                                 data [i].Emit (ec);
3549                         }
3550
3551                         statement.Emit (ec);
3552
3553                         if (has_ret)
3554                                 return;
3555
3556                         ILGenerator ig = ec.ig;
3557
3558                         //
3559                         // Clear the pinned variable
3560                         //
3561                         for (int i = 0; i < data.Length; i++) {
3562                                 data [i].EmitExit (ig);
3563                         }
3564                 }
3565         }
3566         
3567         public class Catch : Statement {
3568                 public readonly string Name;
3569                 public readonly Block  Block;
3570                 public readonly Block  VarBlock;
3571
3572                 Expression type_expr;
3573                 Type type;
3574                 
3575                 public Catch (Expression type, string name, Block block, Block var_block, Location l)
3576                 {
3577                         type_expr = type;
3578                         Name = name;
3579                         Block = block;
3580                         VarBlock = var_block;
3581                         loc = l;
3582                 }
3583
3584                 public Type CatchType {
3585                         get {
3586                                 return type;
3587                         }
3588                 }
3589
3590                 public bool IsGeneral {
3591                         get {
3592                                 return type_expr == null;
3593                         }
3594                 }
3595
3596                 protected override void DoEmit(EmitContext ec)
3597                 {
3598                 }
3599
3600                 public override bool Resolve (EmitContext ec)
3601                 {
3602                         using (ec.With (EmitContext.Flags.InCatch, true)) {
3603                                 if (type_expr != null) {
3604                                         TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3605                                         if (te == null)
3606                                                 return false;
3607
3608                                         type = te.Type;
3609
3610                                         if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3611                                                 Error (155, "The type caught or thrown must be derived from System.Exception");
3612                                                 return false;
3613                                         }
3614                                 } else
3615                                         type = null;
3616
3617                                 if (!Block.Resolve (ec))
3618                                         return false;
3619
3620                                 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
3621                                 // emit the "unused variable" warnings.
3622                                 if (VarBlock != null)
3623                                         return VarBlock.Resolve (ec);
3624
3625                                 return true;
3626                         }
3627                 }
3628         }
3629
3630         public class Try : ExceptionStatement {
3631                 public readonly Block Fini, Block;
3632                 public readonly ArrayList Specific;
3633                 public readonly Catch General;
3634
3635                 bool need_exc_block;
3636                 
3637                 //
3638                 // specific, general and fini might all be null.
3639                 //
3640                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3641                 {
3642                         if (specific == null && general == null){
3643                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3644                         }
3645                         
3646                         this.Block = block;
3647                         this.Specific = specific;
3648                         this.General = general;
3649                         this.Fini = fini;
3650                         loc = l;
3651                 }
3652
3653                 public override bool Resolve (EmitContext ec)
3654                 {
3655                         bool ok = true;
3656                         
3657                         FlowBranchingException branching = ec.StartFlowBranching (this);
3658
3659                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3660
3661                         if (!Block.Resolve (ec))
3662                                 ok = false;
3663
3664                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3665
3666                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
3667
3668                         Type[] prevCatches = new Type [Specific.Count];
3669                         int last_index = 0;
3670                         foreach (Catch c in Specific){
3671                                 ec.CurrentBranching.CreateSibling (
3672                                         c.Block, FlowBranching.SiblingType.Catch);
3673
3674                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3675
3676                                 if (c.Name != null) {
3677                                         LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3678                                         if (vi == null)
3679                                                 throw new Exception ();
3680
3681                                         vi.VariableInfo = null;
3682                                 }
3683
3684                                 if (!c.Resolve (ec))
3685                                         return false;
3686
3687                                 Type resolvedType = c.CatchType;
3688                                 for (int ii = 0; ii < last_index; ++ii) {
3689                                         if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3690                                                 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3691                                                 return false;
3692                                         }
3693                                 }
3694
3695                                 prevCatches [last_index++] = resolvedType;
3696                                 need_exc_block = true;
3697                         }
3698
3699                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3700
3701                         if (General != null){
3702                                 if (CodeGen.Assembly.WrapNonExceptionThrows) {
3703                                         foreach (Catch c in Specific){
3704                                                 if (c.CatchType == TypeManager.exception_type) {
3705                                                         Report.Warning (1058, 1, c.loc, "A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a `System.Runtime.CompilerServices.RuntimeWrappedException'");
3706                                                 }
3707                                         }
3708                                 }
3709
3710                                 ec.CurrentBranching.CreateSibling (
3711                                         General.Block, FlowBranching.SiblingType.Catch);
3712
3713                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3714
3715                                 if (!General.Resolve (ec))
3716                                         ok = false;
3717
3718                                 need_exc_block = true;
3719                         }
3720
3721                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3722
3723                         if (Fini != null) {
3724                                 if (ok)
3725                                         ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
3726
3727                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3728                                 using (ec.With (EmitContext.Flags.InFinally, true)) {
3729                                         if (!Fini.Resolve (ec))
3730                                                 ok = false;
3731                                 }
3732
3733                                 if (!ec.InIterator)
3734                                         need_exc_block = true;
3735                         }
3736
3737                         if (ec.InIterator) {
3738                                 ResolveFinally (branching);
3739                                 need_exc_block |= emit_finally;
3740                         } else
3741                                 emit_finally = Fini != null;
3742
3743                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3744
3745                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3746
3747                         Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3748
3749                         if (!reachability.AlwaysReturns) {
3750                                 // Unfortunately, System.Reflection.Emit automatically emits
3751                                 // a leave to the end of the finally block.  This is a problem
3752                                 // if `returns' is true since we may jump to a point after the
3753                                 // end of the method.
3754                                 // As a workaround, emit an explicit ret here.
3755                                 ec.NeedReturnLabel ();
3756                         }
3757
3758                         return ok;
3759                 }
3760                 
3761                 protected override void DoEmit (EmitContext ec)
3762                 {
3763                         ILGenerator ig = ec.ig;
3764
3765                         if (need_exc_block)
3766                                 ig.BeginExceptionBlock ();
3767                         Block.Emit (ec);
3768
3769                         foreach (Catch c in Specific){
3770                                 LocalInfo vi;
3771                                 
3772                                 ig.BeginCatchBlock (c.CatchType);
3773
3774                                 if (c.VarBlock != null)
3775                                         ec.EmitScopeInitFromBlock (c.VarBlock);
3776                                 if (c.Name != null){
3777                                         vi = c.Block.GetLocalInfo (c.Name);
3778                                         if (vi == null)
3779                                                 throw new Exception ("Variable does not exist in this block");
3780
3781                                         if (vi.IsCaptured){
3782                                                 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
3783                                                 ig.Emit (OpCodes.Stloc, e);
3784                                                 
3785                                                 ec.EmitCapturedVariableInstance (vi);
3786                                                 ig.Emit (OpCodes.Ldloc, e);
3787                                                 ig.Emit (OpCodes.Stfld, vi.FieldBuilder);
3788                                         } else
3789                                                 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3790                                 } else
3791                                         ig.Emit (OpCodes.Pop);
3792
3793                                 c.Block.Emit (ec);
3794                         }
3795
3796                         if (General != null){
3797                                 ig.BeginCatchBlock (TypeManager.object_type);
3798                                 ig.Emit (OpCodes.Pop);
3799                                 General.Block.Emit (ec);
3800                         }
3801
3802                         DoEmitFinally (ec);
3803                         if (need_exc_block)
3804                                 ig.EndExceptionBlock ();
3805                 }
3806
3807                 public override void EmitFinally (EmitContext ec)
3808                 {
3809                         if (Fini != null)
3810                                 Fini.Emit (ec);
3811                 }
3812
3813                 public bool HasCatch
3814                 {
3815                         get {
3816                                 return General != null || Specific.Count > 0;
3817                         }
3818                 }
3819         }
3820
3821         public class Using : ExceptionStatement {
3822                 object expression_or_block;
3823                 public Statement Statement;
3824                 ArrayList var_list;
3825                 Expression expr;
3826                 Type expr_type;
3827                 Expression [] resolved_vars;
3828                 Expression [] converted_vars;
3829                 ExpressionStatement [] assign;
3830                 LocalBuilder local_copy;
3831                 
3832                 public Using (object expression_or_block, Statement stmt, Location l)
3833                 {
3834                         this.expression_or_block = expression_or_block;
3835                         Statement = stmt;
3836                         loc = l;
3837                 }
3838
3839                 //
3840                 // Resolves for the case of using using a local variable declaration.
3841                 //
3842                 bool ResolveLocalVariableDecls (EmitContext ec)
3843                 {
3844                         int i = 0;
3845
3846                         TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3847                         if (texpr == null)
3848                                 return false;
3849
3850                         expr_type = texpr.Type;
3851
3852                         //
3853                         // The type must be an IDisposable or an implicit conversion
3854                         // must exist.
3855                         //
3856                         converted_vars = new Expression [var_list.Count];
3857                         resolved_vars = new Expression [var_list.Count];
3858                         assign = new ExpressionStatement [var_list.Count];
3859
3860                         bool need_conv = !TypeManager.ImplementsInterface (
3861                                 expr_type, TypeManager.idisposable_type);
3862
3863                         foreach (DictionaryEntry e in var_list){
3864                                 Expression var = (Expression) e.Key;
3865
3866                                 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3867                                 if (var == null)
3868                                         return false;
3869
3870                                 resolved_vars [i] = var;
3871
3872                                 if (!need_conv) {
3873                                         i++;
3874                                         continue;
3875                                 }
3876
3877                                 converted_vars [i] = Convert.ImplicitConversion (
3878                                         ec, var, TypeManager.idisposable_type, loc);
3879
3880                                 if (converted_vars [i] == null) {
3881                                         Error_IsNotConvertibleToIDisposable ();
3882                                         return false;
3883                                 }
3884
3885                                 i++;
3886                         }
3887
3888                         i = 0;
3889                         foreach (DictionaryEntry e in var_list){
3890                                 Expression var = resolved_vars [i];
3891                                 Expression new_expr = (Expression) e.Value;
3892                                 Expression a;
3893
3894                                 a = new Assign (var, new_expr, loc);
3895                                 a = a.Resolve (ec);
3896                                 if (a == null)
3897                                         return false;
3898
3899                                 if (!need_conv)
3900                                         converted_vars [i] = var;
3901                                 assign [i] = (ExpressionStatement) a;
3902                                 i++;
3903                         }
3904
3905                         return true;
3906                 }
3907
3908                 void Error_IsNotConvertibleToIDisposable ()
3909                 {
3910                         Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
3911                                 TypeManager.CSharpName (expr_type));
3912                 }
3913
3914                 bool ResolveExpression (EmitContext ec)
3915                 {
3916                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3917                                 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3918                                         Error_IsNotConvertibleToIDisposable ();
3919                                         return false;
3920                                 }
3921                         }
3922
3923                         return true;
3924                 }
3925                 
3926                 //
3927                 // Emits the code for the case of using using a local variable declaration.
3928                 //
3929                 void EmitLocalVariableDecls (EmitContext ec)
3930                 {
3931                         ILGenerator ig = ec.ig;
3932                         int i = 0;
3933
3934                         for (i = 0; i < assign.Length; i++) {
3935                                 assign [i].EmitStatement (ec);
3936
3937                                 if (emit_finally)
3938                                         ig.BeginExceptionBlock ();
3939                         }
3940                         Statement.Emit (ec);
3941
3942                         var_list.Reverse ();
3943
3944                         DoEmitFinally (ec);
3945                 }
3946
3947                 void EmitLocalVariableDeclFinally (EmitContext ec)
3948                 {
3949                         ILGenerator ig = ec.ig;
3950
3951                         int i = assign.Length;
3952                         for (int ii = 0; ii < var_list.Count; ++ii){
3953                                 Expression var = resolved_vars [--i];
3954                                 Label skip = ig.DefineLabel ();
3955                                 
3956                                 ig.BeginFinallyBlock ();
3957                                 
3958                                 if (!var.Type.IsValueType) {
3959                                         var.Emit (ec);
3960                                         ig.Emit (OpCodes.Brfalse, skip);
3961                                         converted_vars [i].Emit (ec);
3962                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3963                                 } else {
3964                                         Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3965
3966                                         if (!(ml is MethodGroupExpr)) {
3967                                                 var.Emit (ec);
3968                                                 ig.Emit (OpCodes.Box, var.Type);
3969                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3970                                         } else {
3971                                                 MethodInfo mi = null;
3972
3973                                                 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3974                                                         if (TypeManager.GetParameterData (mk).Count == 0) {
3975                                                                 mi = mk;
3976                                                                 break;
3977                                                         }
3978                                                 }
3979
3980                                                 if (mi == null) {
3981                                                         Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3982                                                         return;
3983                                                 }
3984
3985                                                 IMemoryLocation mloc = (IMemoryLocation) var;
3986
3987                                                 mloc.AddressOf (ec, AddressOp.Load);
3988                                                 ig.Emit (OpCodes.Call, mi);
3989                                         }
3990                                 }
3991
3992                                 ig.MarkLabel (skip);
3993
3994                                 if (emit_finally) {
3995                                         ig.EndExceptionBlock ();
3996                                         if (i > 0)
3997                                                 ig.BeginFinallyBlock ();
3998                                 }
3999                         }
4000                 }
4001
4002                 void EmitExpression (EmitContext ec)
4003                 {
4004                         //
4005                         // Make a copy of the expression and operate on that.
4006                         //
4007                         ILGenerator ig = ec.ig;
4008                         local_copy = ig.DeclareLocal (expr_type);
4009
4010                         expr.Emit (ec);
4011                         ig.Emit (OpCodes.Stloc, local_copy);
4012
4013                         if (emit_finally)
4014                                 ig.BeginExceptionBlock ();
4015
4016                         Statement.Emit (ec);
4017                         
4018                         DoEmitFinally (ec);
4019                         if (emit_finally)
4020                                 ig.EndExceptionBlock ();
4021                 }
4022
4023                 void EmitExpressionFinally (EmitContext ec)
4024                 {
4025                         ILGenerator ig = ec.ig;
4026                         if (!local_copy.LocalType.IsValueType) {
4027                                 Label skip = ig.DefineLabel ();
4028                                 ig.Emit (OpCodes.Ldloc, local_copy);
4029                                 ig.Emit (OpCodes.Brfalse, skip);
4030                                 ig.Emit (OpCodes.Ldloc, local_copy);
4031                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4032                                 ig.MarkLabel (skip);
4033                         } else {
4034                                 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4035
4036                                 if (!(ml is MethodGroupExpr)) {
4037                                         ig.Emit (OpCodes.Ldloc, local_copy);
4038                                         ig.Emit (OpCodes.Box, local_copy.LocalType);
4039                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4040                                 } else {
4041                                         MethodInfo mi = null;
4042
4043                                         foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4044                                                 if (TypeManager.GetParameterData (mk).Count == 0) {
4045                                                         mi = mk;
4046                                                         break;
4047                                                 }
4048                                         }
4049
4050                                         if (mi == null) {
4051                                                 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4052                                                 return;
4053                                         }
4054
4055                                         ig.Emit (OpCodes.Ldloca, local_copy);
4056                                         ig.Emit (OpCodes.Call, mi);
4057                                 }
4058                         }
4059                 }
4060                 
4061                 public override bool Resolve (EmitContext ec)
4062                 {
4063                         if (expression_or_block is DictionaryEntry){
4064                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4065                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4066
4067                                 if (!ResolveLocalVariableDecls (ec))
4068                                         return false;
4069
4070                         } else if (expression_or_block is Expression){
4071                                 expr = (Expression) expression_or_block;
4072
4073                                 expr = expr.Resolve (ec);
4074                                 if (expr == null)
4075                                         return false;
4076
4077                                 expr_type = expr.Type;
4078
4079                                 if (!ResolveExpression (ec))
4080                                         return false;
4081                         }
4082
4083                         FlowBranchingException branching = ec.StartFlowBranching (this);
4084
4085                         bool ok = Statement.Resolve (ec);
4086
4087                         if (!ok) {
4088                                 ec.KillFlowBranching ();
4089                                 return false;
4090                         }
4091
4092                         ResolveFinally (branching);                                     
4093                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4094
4095                         if (!reachability.AlwaysReturns) {
4096                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
4097                                 // to the end of the finally block.  This is a problem if `returns'
4098                                 // is true since we may jump to a point after the end of the method.
4099                                 // As a workaround, emit an explicit ret here.
4100                                 ec.NeedReturnLabel ();
4101                         }
4102
4103                         return true;
4104                 }
4105                 
4106                 protected override void DoEmit (EmitContext ec)
4107                 {
4108                         if (expression_or_block is DictionaryEntry)
4109                                 EmitLocalVariableDecls (ec);
4110                         else if (expression_or_block is Expression)
4111                                 EmitExpression (ec);
4112                 }
4113
4114                 public override void EmitFinally (EmitContext ec)
4115                 {
4116                         if (expression_or_block is DictionaryEntry)
4117                                 EmitLocalVariableDeclFinally (ec);
4118                         else if (expression_or_block is Expression)
4119                                 EmitExpressionFinally (ec);
4120                 }
4121         }
4122
4123         /// <summary>
4124         ///   Implementation of the foreach C# statement
4125         /// </summary>
4126         public class Foreach : Statement {
4127                 Expression type;
4128                 Expression variable;
4129                 Expression expr;
4130                 Statement statement;
4131                 ArrayForeach array;
4132                 CollectionForeach collection;
4133                 
4134                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4135                                 Statement stmt, Location l)
4136                 {
4137                         this.type = type;
4138                         this.variable = var;
4139                         this.expr = expr;
4140                         statement = stmt;
4141                         loc = l;
4142                 }
4143
4144                 public Statement Statement {
4145                         get { return statement; }
4146                 }
4147
4148                 public override bool Resolve (EmitContext ec)
4149                 {
4150                         expr = expr.Resolve (ec);
4151                         if (expr == null)
4152                                 return false;
4153
4154                         Constant c = expr as Constant;
4155                         if (c != null && c.GetValue () == null) {
4156                                 Report.Error (186, loc, "Use of null is not valid in this context");
4157                                 return false;
4158                         }
4159
4160                         TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4161                         if (texpr == null)
4162                                 return false;
4163
4164                         Type var_type = texpr.Type;
4165
4166                         if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethod) {
4167                                 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4168                                         expr.ExprClassName);
4169                                 return false;
4170                         }
4171
4172                         //
4173                         // We need an instance variable.  Not sure this is the best
4174                         // way of doing this.
4175                         //
4176                         // FIXME: When we implement propertyaccess, will those turn
4177                         // out to return values in ExprClass?  I think they should.
4178                         //
4179                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4180                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4181                                 collection.Error_Enumerator ();
4182                                 return false;
4183                         }
4184
4185                         if (expr.Type.IsArray) {
4186                                 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4187                                 return array.Resolve (ec);
4188                         } else {
4189                                 collection = new CollectionForeach (
4190                                         var_type, variable, expr, statement, loc);
4191                                 return collection.Resolve (ec);
4192                         }
4193                 }
4194
4195                 protected override void DoEmit (EmitContext ec)
4196                 {
4197                         ILGenerator ig = ec.ig;
4198                         
4199                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4200                         ec.LoopBegin = ig.DefineLabel ();
4201                         ec.LoopEnd = ig.DefineLabel ();
4202
4203                         if (collection != null)
4204                                 collection.Emit (ec);
4205                         else
4206                                 array.Emit (ec);
4207                         
4208                         ec.LoopBegin = old_begin;
4209                         ec.LoopEnd = old_end;
4210                 }
4211
4212                 protected class ArrayCounter : TemporaryVariable
4213                 {
4214                         public ArrayCounter (Location loc)
4215                                 : base (TypeManager.int32_type, loc)
4216                         { }
4217
4218                         public void Initialize (EmitContext ec)
4219                         {
4220                                 EmitThis (ec);
4221                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
4222                                 EmitStore (ec.ig);
4223                         }
4224
4225                         public void Increment (EmitContext ec)
4226                         {
4227                                 EmitThis (ec);
4228                                 Emit (ec);
4229                                 ec.ig.Emit (OpCodes.Ldc_I4_1);
4230                                 ec.ig.Emit (OpCodes.Add);
4231                                 EmitStore (ec.ig);
4232                         }
4233                 }
4234
4235                 protected class ArrayForeach : Statement
4236                 {
4237                         Expression variable, expr, conv;
4238                         Statement statement;
4239                         Type array_type;
4240                         Type var_type;
4241                         TemporaryVariable[] lengths;
4242                         ArrayCounter[] counter;
4243                         int rank;
4244
4245                         TemporaryVariable copy;
4246                         Expression access;
4247
4248                         public ArrayForeach (Type var_type, Expression var,
4249                                              Expression expr, Statement stmt, Location l)
4250                         {
4251                                 this.var_type = var_type;
4252                                 this.variable = var;
4253                                 this.expr = expr;
4254                                 statement = stmt;
4255                                 loc = l;
4256                         }
4257
4258                         public override bool Resolve (EmitContext ec)
4259                         {
4260                                 array_type = expr.Type;
4261                                 rank = array_type.GetArrayRank ();
4262
4263                                 copy = new TemporaryVariable (array_type, loc);
4264                                 copy.Resolve (ec);
4265
4266                                 counter = new ArrayCounter [rank];
4267                                 lengths = new TemporaryVariable [rank];
4268
4269                                 ArrayList list = new ArrayList ();
4270                                 for (int i = 0; i < rank; i++) {
4271                                         counter [i] = new ArrayCounter (loc);
4272                                         counter [i].Resolve (ec);
4273
4274                                         lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4275                                         lengths [i].Resolve (ec);
4276
4277                                         list.Add (counter [i]);
4278                                 }
4279
4280                                 access = new ElementAccess (copy, list).Resolve (ec);
4281                                 if (access == null)
4282                                         return false;
4283
4284                                 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4285                                 if (conv == null)
4286                                         return false;
4287
4288                                 bool ok = true;
4289
4290                                 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4291                                 ec.CurrentBranching.CreateSibling ();
4292
4293                                 variable = variable.ResolveLValue (ec, conv, loc);
4294                                 if (variable == null)
4295                                         ok = false;
4296
4297                                 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4298                                 if (!statement.Resolve (ec))
4299                                         ok = false;
4300                                 ec.EndFlowBranching ();
4301
4302                                 // There's no direct control flow from the end of the embedded statement to the end of the loop
4303                                 ec.CurrentBranching.CurrentUsageVector.Goto ();
4304
4305                                 ec.EndFlowBranching ();
4306
4307                                 return ok;
4308                         }
4309
4310                         protected override void DoEmit (EmitContext ec)
4311                         {
4312                                 ILGenerator ig = ec.ig;
4313
4314                                 copy.Store (ec, expr);
4315
4316                                 Label[] test = new Label [rank];
4317                                 Label[] loop = new Label [rank];
4318
4319                                 for (int i = 0; i < rank; i++) {
4320                                         test [i] = ig.DefineLabel ();
4321                                         loop [i] = ig.DefineLabel ();
4322
4323                                         lengths [i].EmitThis (ec);
4324                                         ((ArrayAccess) access).EmitGetLength (ec, i);
4325                                         lengths [i].EmitStore (ig);
4326                                 }
4327
4328                                 for (int i = 0; i < rank; i++) {
4329                                         counter [i].Initialize (ec);
4330
4331                                         ig.Emit (OpCodes.Br, test [i]);
4332                                         ig.MarkLabel (loop [i]);
4333                                 }
4334
4335                                 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4336
4337                                 statement.Emit (ec);
4338
4339                                 ig.MarkLabel (ec.LoopBegin);
4340
4341                                 for (int i = rank - 1; i >= 0; i--){
4342                                         counter [i].Increment (ec);
4343
4344                                         ig.MarkLabel (test [i]);
4345                                         counter [i].Emit (ec);
4346                                         lengths [i].Emit (ec);
4347                                         ig.Emit (OpCodes.Blt, loop [i]);
4348                                 }
4349
4350                                 ig.MarkLabel (ec.LoopEnd);
4351                         }
4352                 }
4353
4354                 protected class CollectionForeach : ExceptionStatement
4355                 {
4356                         Expression variable, expr;
4357                         Statement statement;
4358
4359                         TemporaryVariable enumerator;
4360                         Expression init;
4361                         Statement loop;
4362
4363                         MethodGroupExpr get_enumerator;
4364                         PropertyExpr get_current;
4365                         MethodInfo move_next;
4366                         Type var_type, enumerator_type;
4367                         bool is_disposable;
4368                         bool enumerator_found;
4369
4370                         public CollectionForeach (Type var_type, Expression var,
4371                                                   Expression expr, Statement stmt, Location l)
4372                         {
4373                                 this.var_type = var_type;
4374                                 this.variable = var;
4375                                 this.expr = expr;
4376                                 statement = stmt;
4377                                 loc = l;
4378                         }
4379
4380                         bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4381                         {
4382                                 Type return_type = mi.ReturnType;
4383
4384                                 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4385                                         //
4386                                         // Apply the same optimization as MS: skip the GetEnumerator
4387                                         // returning an IEnumerator, and use the one returning a 
4388                                         // CharEnumerator instead. This allows us to avoid the 
4389                                         // try-finally block and the boxing.
4390                                         //
4391                                         return false;
4392
4393                                 //
4394                                 // Ok, we can access it, now make sure that we can do something
4395                                 // with this `GetEnumerator'
4396                                 //
4397
4398                                 if (return_type == TypeManager.ienumerator_type ||
4399                                     TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4400                                     (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4401                                         //
4402                                         // If it is not an interface, lets try to find the methods ourselves.
4403                                         // For example, if we have:
4404                                         // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4405                                         // We can avoid the iface call. This is a runtime perf boost.
4406                                         // even bigger if we have a ValueType, because we avoid the cost
4407                                         // of boxing.
4408                                         //
4409                                         // We have to make sure that both methods exist for us to take
4410                                         // this path. If one of the methods does not exist, we will just
4411                                         // use the interface. Sadly, this complex if statement is the only
4412                                         // way I could do this without a goto
4413                                         //
4414
4415                                         if (return_type.IsInterface && return_type.IsGenericType) {
4416                                                 enumerator_type = return_type;
4417                                                 if (!FetchGetCurrent (ec, return_type))
4418                                                         get_current = new PropertyExpr (
4419                                                                 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4420                                                 if (!FetchMoveNext (return_type))
4421                                                         move_next = TypeManager.bool_movenext_void;
4422                                                 return true;
4423                                         }
4424
4425                                         if (return_type.IsInterface ||
4426                                             !FetchMoveNext (return_type) ||
4427                                             !FetchGetCurrent (ec, return_type)) {
4428                                                 enumerator_type = return_type;
4429                                                 move_next = TypeManager.bool_movenext_void;
4430                                                 get_current = new PropertyExpr (
4431                                                         ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4432                                                 return true;
4433                                         }
4434                                 } else {
4435                                         //
4436                                         // Ok, so they dont return an IEnumerable, we will have to
4437                                         // find if they support the GetEnumerator pattern.
4438                                         //
4439
4440                                         if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
4441                                                 Report.Error (202, loc, "foreach statement requires that the return type `{0}' of `{1}' must have a suitable public MoveNext method and public Current property",
4442                                                         TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
4443                                                 return false;
4444                                         }
4445                                 }
4446
4447                                 enumerator_type = return_type;
4448                                 is_disposable = !enumerator_type.IsSealed ||
4449                                         TypeManager.ImplementsInterface (
4450                                                 enumerator_type, TypeManager.idisposable_type);
4451
4452                                 return true;
4453                         }
4454
4455                         //
4456                         // Retrieves a `public bool MoveNext ()' method from the Type `t'
4457                         //
4458                         bool FetchMoveNext (Type t)
4459                         {
4460                                 MemberList move_next_list;
4461
4462                                 move_next_list = TypeContainer.FindMembers (
4463                                         t, MemberTypes.Method,
4464                                         Expression.AllBindingFlags,
4465                                         Type.FilterName, "MoveNext");
4466                                 if (move_next_list.Count == 0)
4467                                         return false;
4468
4469                                 bool found = false;
4470                                 foreach (MemberInfo m in move_next_list){
4471                                         MethodInfo mi = (MethodInfo) m;
4472                                 
4473                                         if ((TypeManager.GetParameterData (mi).Count == 0) &&
4474                                             TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4475                                                 move_next = mi;
4476                                                 if (mi.IsPublic)
4477                                                         return true;
4478                                                 found = true;
4479                                         }
4480                                 }
4481
4482                                 return found;
4483                         }
4484                 
4485                         //
4486                         // Retrieves a `public T get_Current ()' method from the Type `t'
4487                         //
4488                         bool FetchGetCurrent (EmitContext ec, Type t)
4489                         {
4490                                 PropertyExpr pe = Expression.MemberLookup (
4491                                         ec.ContainerType, t, "Current", MemberTypes.Property,
4492                                         Expression.AllBindingFlags, loc) as PropertyExpr;
4493                                 if (pe == null)
4494                                         return false;
4495
4496                                 get_current = pe;
4497                                 return true;
4498                         }
4499
4500                         // 
4501                         // Retrieves a `public void Dispose ()' method from the Type `t'
4502                         //
4503                         static MethodInfo FetchMethodDispose (Type t)
4504                         {
4505                                 MemberList dispose_list;
4506
4507                                 dispose_list = TypeContainer.FindMembers (
4508                                         t, MemberTypes.Method,
4509                                         BindingFlags.Public | BindingFlags.Instance,
4510                                         Type.FilterName, "Dispose");
4511                                 if (dispose_list.Count == 0)
4512                                         return null;
4513
4514                                 foreach (MemberInfo m in dispose_list){
4515                                         MethodInfo mi = (MethodInfo) m;
4516
4517                                         if (TypeManager.GetParameterData (mi).Count == 0){
4518                                                 if (mi.ReturnType == TypeManager.void_type)
4519                                                         return mi;
4520                                         }
4521                                 }
4522                                 return null;
4523                         }
4524
4525                         public void Error_Enumerator ()
4526                         {
4527                                 if (enumerator_found) {
4528                                         return;
4529                                 }
4530
4531                             Report.Error (1579, loc,
4532                                         "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4533                                         TypeManager.CSharpName (expr.Type));
4534                         }
4535
4536                         bool TryType (EmitContext ec, Type t)
4537                         {
4538                                 MethodGroupExpr mg = Expression.MemberLookup (
4539                                         ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
4540                                         Expression.AllBindingFlags, loc) as MethodGroupExpr;
4541                                 if (mg == null)
4542                                         return false;
4543
4544                                 MethodBase result = null;
4545                                 MethodInfo tmp_move_next = null;
4546                                 PropertyExpr tmp_get_cur = null;
4547                                 Type tmp_enumerator_type = enumerator_type;
4548                                 foreach (MethodInfo mi in mg.Methods) {
4549                                         if (TypeManager.GetParameterData (mi).Count != 0)
4550                                                 continue;
4551                         
4552                                         // Check whether GetEnumerator is public
4553                                         if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4554                                                 continue;
4555
4556                                         if (TypeManager.IsOverride (mi))
4557                                                 continue;
4558
4559                                         enumerator_found = true;
4560
4561                                         if (!GetEnumeratorFilter (ec, mi)) {
4562                                                 continue;
4563                                         }
4564
4565                                         result = mi;
4566                                         tmp_move_next = move_next;
4567                                         tmp_get_cur = get_current;
4568                                         tmp_enumerator_type = enumerator_type;
4569                                         if (mi.DeclaringType == t)
4570                                                 break;
4571                                 }
4572
4573                                 if (result != null) {
4574                                         move_next = tmp_move_next;
4575                                         get_current = tmp_get_cur;
4576                                         enumerator_type = tmp_enumerator_type;
4577                                         MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
4578                                         get_enumerator = new MethodGroupExpr (mi, loc);
4579
4580                                         if (t != expr.Type) {
4581                                                 expr = Convert.ExplicitConversion (
4582                                                         ec, expr, t, loc);
4583                                                 if (expr == null)
4584                                                         throw new InternalErrorException ();
4585                                         }
4586
4587                                         get_enumerator.InstanceExpression = expr;
4588                                         get_enumerator.IsBase = t != expr.Type;
4589
4590                                         return true;
4591                                 }
4592
4593                                 return false;
4594                         }               
4595
4596                         bool ProbeCollectionType (EmitContext ec, Type t)
4597                         {
4598                                 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4599                                         if (TryType (ec, tt))
4600                                                 return true;
4601                                         tt = tt.BaseType;
4602                                 }
4603
4604                                 //
4605                                 // Now try to find the method in the interfaces
4606                                 //
4607                                 while (t != null){
4608                                         Type [] ifaces = t.GetInterfaces ();
4609
4610                                         foreach (Type i in ifaces){
4611                                                 if (TryType (ec, i))
4612                                                         return true;
4613                                         }
4614                                 
4615                                         //
4616                                         // Since TypeBuilder.GetInterfaces only returns the interface
4617                                         // types for this type, we have to keep looping, but once
4618                                         // we hit a non-TypeBuilder (ie, a Type), then we know we are
4619                                         // done, because it returns all the types
4620                                         //
4621                                         if ((t is TypeBuilder))
4622                                                 t = t.BaseType;
4623                                         else
4624                                                 break;
4625                                 }
4626
4627                                 return false;
4628                         }
4629
4630                         public override bool Resolve (EmitContext ec)
4631                         {
4632                                 enumerator_type = TypeManager.ienumerator_type;
4633                                 is_disposable = true;
4634
4635                                 if (!ProbeCollectionType (ec, expr.Type)) {
4636                                         Error_Enumerator ();
4637                                         return false;
4638                                 }
4639
4640                                 enumerator = new TemporaryVariable (enumerator_type, loc);
4641                                 enumerator.Resolve (ec);
4642
4643                                 init = new Invocation (get_enumerator, new ArrayList ());
4644                                 init = init.Resolve (ec);
4645                                 if (init == null)
4646                                         return false;
4647
4648                                 Expression move_next_expr;
4649                                 {
4650                                         MemberInfo[] mi = new MemberInfo[] { move_next };
4651                                         MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4652                                         mg.InstanceExpression = enumerator;
4653
4654                                         move_next_expr = new Invocation (mg, new ArrayList ());
4655                                 }
4656
4657                                 get_current.InstanceExpression = enumerator;
4658
4659                                 Statement block = new CollectionForeachStatement (
4660                                         var_type, variable, get_current, statement, loc);
4661
4662                                 loop = new While (move_next_expr, block, loc);
4663
4664                                 bool ok = true;
4665
4666                                 FlowBranchingException branching = null;
4667                                 if (is_disposable)
4668                                         branching = ec.StartFlowBranching (this);
4669
4670                                 if (!loop.Resolve (ec))
4671                                         ok = false;
4672
4673                                 if (is_disposable) {
4674                                         ResolveFinally (branching);
4675                                         ec.EndFlowBranching ();
4676                                 } else
4677                                         emit_finally = true;
4678
4679                                 return ok;
4680                         }
4681
4682                         protected override void DoEmit (EmitContext ec)
4683                         {
4684                                 ILGenerator ig = ec.ig;
4685
4686                                 enumerator.Store (ec, init);
4687
4688                                 //
4689                                 // Protect the code in a try/finalize block, so that
4690                                 // if the beast implement IDisposable, we get rid of it
4691                                 //
4692                                 if (is_disposable && emit_finally)
4693                                         ig.BeginExceptionBlock ();
4694                         
4695                                 loop.Emit (ec);
4696
4697                                 //
4698                                 // Now the finally block
4699                                 //
4700                                 if (is_disposable) {
4701                                         DoEmitFinally (ec);
4702                                         if (emit_finally)
4703                                                 ig.EndExceptionBlock ();
4704                                 }
4705                         }
4706
4707
4708                         public override void EmitFinally (EmitContext ec)
4709                         {
4710                                 ILGenerator ig = ec.ig;
4711
4712                                 if (enumerator_type.IsValueType) {
4713                                         MethodInfo mi = FetchMethodDispose (enumerator_type);
4714                                         if (mi != null) {
4715                                                 enumerator.EmitLoadAddress (ec);
4716                                                 ig.Emit (OpCodes.Call, mi);
4717                                         } else {
4718                                                 enumerator.Emit (ec);
4719                                                 ig.Emit (OpCodes.Box, enumerator_type);
4720                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4721                                         }
4722                                 } else {
4723                                         Label call_dispose = ig.DefineLabel ();
4724
4725                                         enumerator.Emit (ec);
4726                                         ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4727                                         ig.Emit (OpCodes.Dup);
4728                                         ig.Emit (OpCodes.Brtrue_S, call_dispose);
4729                                         ig.Emit (OpCodes.Pop);
4730
4731                                         Label end_finally = ig.DefineLabel ();
4732                                         ig.Emit (OpCodes.Br, end_finally);
4733
4734                                         ig.MarkLabel (call_dispose);
4735                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4736                                         ig.MarkLabel (end_finally);
4737                                 }
4738                         }
4739                 }
4740
4741                 protected class CollectionForeachStatement : Statement
4742                 {
4743                         Type type;
4744                         Expression variable, current, conv;
4745                         Statement statement;
4746                         Assign assign;
4747
4748                         public CollectionForeachStatement (Type type, Expression variable,
4749                                                            Expression current, Statement statement,
4750                                                            Location loc)
4751                         {
4752                                 this.type = type;
4753                                 this.variable = variable;
4754                                 this.current = current;
4755                                 this.statement = statement;
4756                                 this.loc = loc;
4757                         }
4758
4759                         public override bool Resolve (EmitContext ec)
4760                         {
4761                                 current = current.Resolve (ec);
4762                                 if (current == null)
4763                                         return false;
4764
4765                                 conv = Convert.ExplicitConversion (ec, current, type, loc);
4766                                 if (conv == null)
4767                                         return false;
4768
4769                                 assign = new Assign (variable, conv, loc);
4770                                 if (assign.Resolve (ec) == null)
4771                                         return false;
4772
4773                                 if (!statement.Resolve (ec))
4774                                         return false;
4775
4776                                 return true;
4777                         }
4778
4779                         protected override void DoEmit (EmitContext ec)
4780                         {
4781                                 assign.EmitStatement (ec);
4782                                 statement.Emit (ec);
4783                         }
4784                 }
4785         }
4786 }