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