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