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