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