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