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