The logic was wrong here, it worked because of a codepath not covered, fixes #57895
[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 ();
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 ();
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)
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 {
609                                 ec.ig.Emit (OpCodes.Ret);
610                         }
611                 }
612         }
613
614         public class Goto : Statement {
615                 string target;
616                 Block block;
617                 LabeledStatement label;
618                 
619                 public override bool Resolve (EmitContext ec)
620                 {
621                         label = ec.CurrentBranching.LookupLabel (target, loc);
622                         if (label == null)
623                                 return false;
624
625                         // If this is a forward goto.
626                         if (!label.IsDefined)
627                                 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
628
629                         ec.CurrentBranching.CurrentUsageVector.Goto ();
630
631                         return true;
632                 }
633                 
634                 public Goto (Block parent_block, string label, Location l)
635                 {
636                         block = parent_block;
637                         loc = l;
638                         target = label;
639                 }
640
641                 public string Target {
642                         get {
643                                 return target;
644                         }
645                 }
646
647                 protected override void DoEmit (EmitContext ec)
648                 {
649                         Label l = label.LabelTarget (ec);
650                         ec.ig.Emit (OpCodes.Br, l);
651                 }
652         }
653
654         public class LabeledStatement : Statement {
655                 public readonly Location Location;
656                 bool defined;
657                 bool referenced;
658                 Label label;
659
660                 FlowBranching.UsageVector vectors;
661                 
662                 public LabeledStatement (string label_name, Location l)
663                 {
664                         this.Location = l;
665                 }
666
667                 public Label LabelTarget (EmitContext ec)
668                 {
669                         if (defined)
670                                 return label;
671                         label = ec.ig.DefineLabel ();
672                         defined = true;
673
674                         return label;
675                 }
676
677                 public bool IsDefined {
678                         get {
679                                 return defined;
680                         }
681                 }
682
683                 public bool HasBeenReferenced {
684                         get {
685                                 return referenced;
686                         }
687                 }
688
689                 public void AddUsageVector (FlowBranching.UsageVector vector)
690                 {
691                         vector = vector.Clone ();
692                         vector.Next = vectors;
693                         vectors = vector;
694                 }
695
696                 public override bool Resolve (EmitContext ec)
697                 {
698                         ec.CurrentBranching.Label (vectors);
699
700                         referenced = true;
701
702                         return true;
703                 }
704
705                 protected override void DoEmit (EmitContext ec)
706                 {
707                         LabelTarget (ec);
708                         ec.ig.MarkLabel (label);
709                 }
710         }
711         
712
713         /// <summary>
714         ///   `goto default' statement
715         /// </summary>
716         public class GotoDefault : Statement {
717                 
718                 public GotoDefault (Location l)
719                 {
720                         loc = l;
721                 }
722
723                 public override bool Resolve (EmitContext ec)
724                 {
725                         ec.CurrentBranching.CurrentUsageVector.Goto ();
726                         return true;
727                 }
728
729                 protected override void DoEmit (EmitContext ec)
730                 {
731                         if (ec.Switch == null){
732                                 Report.Error (153, loc, "goto default is only valid in a switch statement");
733                                 return;
734                         }
735
736                         if (!ec.Switch.GotDefault){
737                                 Report.Error (159, loc, "No default target on switch statement");
738                                 return;
739                         }
740                         ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
741                 }
742         }
743
744         /// <summary>
745         ///   `goto case' statement
746         /// </summary>
747         public class GotoCase : Statement {
748                 Expression expr;
749                 Label label;
750                 
751                 public GotoCase (Expression e, Location l)
752                 {
753                         expr = e;
754                         loc = l;
755                 }
756
757                 public override bool Resolve (EmitContext ec)
758                 {
759                         if (ec.Switch == null){
760                                 Report.Error (153, loc, "goto case is only valid in a switch statement");
761                                 return false;
762                         }
763
764                         expr = expr.Resolve (ec);
765                         if (expr == null)
766                                 return false;
767
768                         if (!(expr is Constant)){
769                                 Report.Error (159, loc, "Target expression for goto case is not constant");
770                                 return false;
771                         }
772
773                         object val = Expression.ConvertIntLiteral (
774                                 (Constant) expr, ec.Switch.SwitchType, loc);
775
776                         if (val == null)
777                                 return false;
778                                         
779                         SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
780
781                         if (sl == null){
782                                 Report.Error (
783                                         159, loc,
784                                         "No such label 'case " + val + "': for the goto case");
785                                 return false;
786                         }
787
788                         label = sl.ILLabelCode;
789
790                         ec.CurrentBranching.CurrentUsageVector.Goto ();
791                         return true;
792                 }
793
794                 protected override void DoEmit (EmitContext ec)
795                 {
796                         ec.ig.Emit (OpCodes.Br, label);
797                 }
798         }
799         
800         public class Throw : Statement {
801                 Expression expr;
802                 
803                 public Throw (Expression expr, Location l)
804                 {
805                         this.expr = expr;
806                         loc = l;
807                 }
808
809                 public override bool Resolve (EmitContext ec)
810                 {
811                         bool in_catch = ec.CurrentBranching.InCatch ();
812                         ec.CurrentBranching.CurrentUsageVector.Throw ();
813
814                         if (expr != null){
815                                 expr = expr.Resolve (ec);
816                                 if (expr == null)
817                                         return false;
818
819                                 ExprClass eclass = expr.eclass;
820
821                                 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
822                                       eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
823                                         expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
824                                         return false;
825                                 }
826
827                                 Type t = expr.Type;
828                                 
829                                 if ((t != TypeManager.exception_type) &&
830                                     !t.IsSubclassOf (TypeManager.exception_type) &&
831                                     !(expr is NullLiteral)) {
832                                         Error (155,
833                                                "The type caught or thrown must be derived " +
834                                                "from System.Exception");
835                                         return false;
836                                 }
837                         } else if (!in_catch) {
838                                 Error (156,
839                                        "A throw statement with no argument is only " +
840                                        "allowed in a catch clause");
841                                 return false;
842                         }
843
844                         return true;
845                 }
846                         
847                 protected override void DoEmit (EmitContext ec)
848                 {
849                         if (expr == null)
850                                 ec.ig.Emit (OpCodes.Rethrow);
851                         else {
852                                 expr.Emit (ec);
853
854                                 ec.ig.Emit (OpCodes.Throw);
855                         }
856                 }
857         }
858
859         public class Break : Statement {
860                 
861                 public Break (Location l)
862                 {
863                         loc = l;
864                 }
865
866                 bool crossing_exc;
867
868                 public override bool Resolve (EmitContext ec)
869                 {
870                         if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
871                                 Error (139, "No enclosing loop or switch to continue to");
872                                 return false;
873                         } else if (ec.CurrentBranching.InFinally (false)) {
874                                 Error (157, "Control can not leave the body of the finally block");
875                                 return false;
876                         } else if (ec.CurrentBranching.InTryOrCatch (false))
877                                 ec.CurrentBranching.AddFinallyVector (
878                                         ec.CurrentBranching.CurrentUsageVector);
879                         else if (ec.CurrentBranching.InLoop ())
880                                 ec.CurrentBranching.AddBreakVector (
881                                         ec.CurrentBranching.CurrentUsageVector);
882
883                         crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
884
885                         ec.CurrentBranching.CurrentUsageVector.Break ();
886                         return true;
887                 }
888
889                 protected override void DoEmit (EmitContext ec)
890                 {
891                         ILGenerator ig = ec.ig;
892
893                         if (crossing_exc)
894                                 ig.Emit (OpCodes.Leave, ec.LoopEnd);
895                         else {
896                                 ec.NeedReturnLabel ();
897                                 ig.Emit (OpCodes.Br, ec.LoopEnd);
898                         }
899                 }
900         }
901
902         public class Continue : Statement {
903                 
904                 public Continue (Location l)
905                 {
906                         loc = l;
907                 }
908
909                 bool crossing_exc;
910
911                 public override bool Resolve (EmitContext ec)
912                 {
913                         if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
914                                 Error (139, "No enclosing loop to continue to");
915                                 return false;
916                         } else if (ec.CurrentBranching.InFinally (false)) {
917                                 Error (157, "Control can not leave the body of the finally block");
918                                 return false;
919                         } else if (ec.CurrentBranching.InTryOrCatch (false))
920                                 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
921
922                         crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
923
924                         ec.CurrentBranching.CurrentUsageVector.Goto ();
925                         return true;
926                 }
927
928                 protected override void DoEmit (EmitContext ec)
929                 {
930                         Label begin = ec.LoopBegin;
931                         
932                         if (crossing_exc)
933                                 ec.ig.Emit (OpCodes.Leave, begin);
934                         else
935                                 ec.ig.Emit (OpCodes.Br, begin);
936                 }
937         }
938
939         public class LocalInfo {
940                 public Expression Type;
941
942                 //
943                 // Most of the time a variable will be stored in a LocalBuilder
944                 //
945                 // But sometimes, it will be stored in a field.  The context of the field will
946                 // be stored in the EmitContext
947                 //
948                 //
949                 public LocalBuilder LocalBuilder;
950                 public FieldBuilder FieldBuilder;
951
952                 public Type VariableType;
953                 public readonly string Name;
954                 public readonly Location Location;
955                 public readonly Block Block;
956
957                 public VariableInfo VariableInfo;
958
959                 enum Flags : byte {
960                         Used = 1,
961                         ReadOnly = 2,
962                         Fixed = 4
963                 }
964
965                 Flags flags;
966                 
967                 public LocalInfo (Expression type, string name, Block block, Location l)
968                 {
969                         Type = type;
970                         Name = name;
971                         Block = block;
972                         Location = l;
973                 }
974
975                 public LocalInfo (TypeContainer tc, Block block, Location l)
976                 {
977                         VariableType = tc.TypeBuilder;
978                         Block = block;
979                         Location = l;
980                 }
981
982                 public bool IsThisAssigned (EmitContext ec, Location loc)
983                 {
984                         if (VariableInfo == null)
985                                 throw new Exception ();
986
987                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
988                                 return true;
989
990                         return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
991                 }
992
993                 public bool IsAssigned (EmitContext ec)
994                 {
995                         if (VariableInfo == null)
996                                 throw new Exception ();
997
998                         return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
999                 }
1000
1001                 public bool Resolve (DeclSpace decl)
1002                 {
1003                         if (VariableType == null)
1004                                 VariableType = decl.ResolveType (Type, false, Location);
1005
1006                         if (VariableType == TypeManager.void_type) {
1007                                 Report.Error (1547, Location,
1008                                               "Keyword 'void' cannot be used in this context");
1009                                 return false;
1010                         }
1011
1012                         if (VariableType == null)
1013                                 return false;
1014
1015                         return true;
1016                 }
1017
1018                 public void MakePinned ()
1019                 {
1020                         TypeManager.MakePinned (LocalBuilder);
1021                         flags |= Flags.Fixed;
1022                 }
1023
1024                 public bool IsFixed {
1025                         get {
1026                                 if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
1027                                         return true;
1028
1029                                 return false;
1030                         }
1031                 }
1032
1033                 public override string ToString ()
1034                 {
1035                         return String.Format ("LocalInfo ({0},{1},{2},{3})",
1036                                               Name, Type, VariableInfo, Location);
1037                 }
1038
1039                 public bool Used {
1040                         get {
1041                                 return (flags & Flags.Used) != 0;
1042                         }
1043                         set {
1044                                 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1045                         }
1046                 }
1047
1048                 public bool ReadOnly {
1049                         get {
1050                                 return (flags & Flags.ReadOnly) != 0;
1051                         }
1052                         set {
1053                                 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1054                         }
1055                 }
1056
1057                 
1058                 
1059         }
1060                 
1061         /// <summary>
1062         ///   Block represents a C# block.
1063         /// </summary>
1064         ///
1065         /// <remarks>
1066         ///   This class is used in a number of places: either to represent
1067         ///   explicit blocks that the programmer places or implicit blocks.
1068         ///
1069         ///   Implicit blocks are used as labels or to introduce variable
1070         ///   declarations.
1071         ///
1072         ///   Top-level blocks derive from Block, and they are called ToplevelBlock
1073         ///   they contain extra information that is not necessary on normal blocks.
1074         /// </remarks>
1075         public class Block : Statement {
1076                 public readonly Block     Parent;
1077                 public readonly Location  StartLocation;
1078                 public Location           EndLocation = Location.Null;
1079
1080                 [Flags]
1081                 public enum Flags : byte {
1082                         Implicit  = 1,
1083                         Unchecked = 2,
1084                         BlockUsed = 4,
1085                         VariablesInitialized = 8,
1086                         HasRet = 16,
1087                         IsDestructor = 32       
1088                 }
1089                 Flags flags;
1090
1091                 public bool Implicit {
1092                         get {
1093                                 return (flags & Flags.Implicit) != 0;
1094                         }
1095                 }
1096
1097                 public bool Unchecked {
1098                         get {
1099                                 return (flags & Flags.Unchecked) != 0;
1100                         }
1101                         set {
1102                                 flags |= Flags.Unchecked;
1103                         }
1104                 }
1105
1106                 //
1107                 // The statements in this block
1108                 //
1109                 ArrayList statements;
1110                 int num_statements;
1111
1112                 //
1113                 // An array of Blocks.  We keep track of children just
1114                 // to generate the local variable declarations.
1115                 //
1116                 // Statements and child statements are handled through the
1117                 // statements.
1118                 //
1119                 ArrayList children;
1120                 
1121                 //
1122                 // Labels.  (label, block) pairs.
1123                 //
1124                 Hashtable labels;
1125
1126                 //
1127                 // Keeps track of (name, type) pairs
1128                 //
1129                 Hashtable variables;
1130
1131                 //
1132                 // Keeps track of constants
1133                 Hashtable constants;
1134
1135                 //
1136                 // If this is a switch section, the enclosing switch block.
1137                 //
1138                 Block switch_block;
1139
1140                 static int id;
1141
1142                 int this_id;
1143                 
1144                 public Block (Block parent)
1145                         : this (parent, (Flags) 0, Location.Null, Location.Null)
1146                 { }
1147
1148                 public Block (Block parent, Flags flags)
1149                         : this (parent, flags, Location.Null, Location.Null)
1150                 { }
1151
1152                 public Block (Block parent, Flags flags, Parameters parameters)
1153                         : this (parent, flags, parameters, Location.Null, Location.Null)
1154                 { }
1155
1156                 public Block (Block parent, Location start, Location end)
1157                         : this (parent, (Flags) 0, start, end)
1158                 { }
1159
1160                 public Block (Block parent, Parameters parameters, Location start, Location end)
1161                         : this (parent, (Flags) 0, parameters, start, end)
1162                 { }
1163
1164                 public Block (Block parent, Flags flags, Location start, Location end)
1165                         : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1166                 { }
1167
1168                 public Block (Block parent, Flags flags, Parameters parameters,
1169                               Location start, Location end)
1170                 {
1171                         if (parent != null)
1172                                 parent.AddChild (this);
1173                         
1174                         this.Parent = parent;
1175                         this.flags = flags;
1176                         this.parameters = parameters;
1177                         this.StartLocation = start;
1178                         this.EndLocation = end;
1179                         this.loc = start;
1180                         this_id = id++;
1181                         statements = new ArrayList ();
1182
1183                         if (parent != null && Implicit) {
1184                                 if (parent.child_variable_names == null)
1185                                         parent.child_variable_names = new Hashtable();
1186                                 // share with parent
1187                                 child_variable_names = parent.child_variable_names;
1188                         }
1189                                 
1190                 }
1191
1192                 public Block CreateSwitchBlock (Location start)
1193                 {
1194                         Block new_block = new Block (this, start, start);
1195                         new_block.switch_block = this;
1196                         return new_block;
1197                 }
1198
1199                 public int ID {
1200                         get {
1201                                 return this_id;
1202                         }
1203                 }
1204
1205                 void AddChild (Block b)
1206                 {
1207                         if (children == null)
1208                                 children = new ArrayList ();
1209                         
1210                         children.Add (b);
1211                 }
1212
1213                 public void SetEndLocation (Location loc)
1214                 {
1215                         EndLocation = loc;
1216                 }
1217
1218                 /// <summary>
1219                 ///   Adds a label to the current block. 
1220                 /// </summary>
1221                 ///
1222                 /// <returns>
1223                 ///   false if the name already exists in this block. true
1224                 ///   otherwise.
1225                 /// </returns>
1226                 ///
1227                 public bool AddLabel (string name, LabeledStatement target, Location loc)
1228                 {
1229                         if (switch_block != null)
1230                                 return switch_block.AddLabel (name, target, loc);
1231
1232                         Block cur = this;
1233                         while (cur != null) {
1234                                 if (cur.DoLookupLabel (name) != null) {
1235                                         Report.Error (
1236                                                 140, loc, "The label '{0}' is a duplicate",
1237                                                 name);
1238                                         return false;
1239                                 }
1240
1241                                 if (!Implicit)
1242                                         break;
1243
1244                                 cur = cur.Parent;
1245                         }
1246
1247                         while (cur != null) {
1248                                 if (cur.DoLookupLabel (name) != null) {
1249                                         Report.Error (
1250                                                 158, loc,
1251                                                 "The label '{0}' shadows another label " +
1252                                                 "by the same name in a containing scope.",
1253                                                 name);
1254                                         return false;
1255                                 }
1256
1257                                 if (children != null) {
1258                                         foreach (Block b in children) {
1259                                                 LabeledStatement s = b.DoLookupLabel (name);
1260                                                 if (s == null)
1261                                                         continue;
1262
1263                                                 Report.Error (
1264                                                         158, s.Location,
1265                                                         "The label '{0}' shadows another " +
1266                                                         "label by the same name in a " +
1267                                                         "containing scope.",
1268                                                         name);
1269                                                 return false;
1270                                         }
1271                                 }
1272
1273
1274                                 cur = cur.Parent;
1275                         }
1276
1277                         if (labels == null)
1278                                 labels = new Hashtable ();
1279
1280                         labels.Add (name, target);
1281                         return true;
1282                 }
1283
1284                 public LabeledStatement LookupLabel (string name)
1285                 {
1286                         LabeledStatement s = DoLookupLabel (name);
1287                         if (s != null)
1288                                 return s;
1289
1290                         if (children == null)
1291                                 return null;
1292
1293                         foreach (Block child in children) {
1294                                 if (!child.Implicit)
1295                                         continue;
1296
1297                                 s = child.LookupLabel (name);
1298                                 if (s != null)
1299                                         return s;
1300                         }
1301
1302                         return null;
1303                 }
1304
1305                 LabeledStatement DoLookupLabel (string name)
1306                 {
1307                         if (switch_block != null)
1308                                 return switch_block.LookupLabel (name);
1309
1310                         if (labels != null)
1311                                 if (labels.Contains (name))
1312                                         return ((LabeledStatement) labels [name]);
1313
1314                         return null;
1315                 }
1316
1317                 LocalInfo this_variable = null;
1318
1319                 // <summary>
1320                 //   Returns the "this" instance variable of this block.
1321                 //   See AddThisVariable() for more information.
1322                 // </summary>
1323                 public LocalInfo ThisVariable {
1324                         get {
1325                                 if (this_variable != null)
1326                                         return this_variable;
1327                                 else if (Parent != null)
1328                                         return Parent.ThisVariable;
1329                                 else
1330                                         return null;
1331                         }
1332                 }
1333
1334                 Hashtable child_variable_names;
1335
1336                 // <summary>
1337                 //   Marks a variable with name @name as being used in a child block.
1338                 //   If a variable name has been used in a child block, it's illegal to
1339                 //   declare a variable with the same name in the current block.
1340                 // </summary>
1341                 public void AddChildVariableName (string name)
1342                 {
1343                         if (child_variable_names == null)
1344                                 child_variable_names = new Hashtable ();
1345
1346                         if (!child_variable_names.Contains (name))
1347                                 child_variable_names.Add (name, true);
1348                 }
1349
1350                 // <summary>
1351                 //   Checks whether a variable name has already been used in a child block.
1352                 // </summary>
1353                 public bool IsVariableNameUsedInChildBlock (string name)
1354                 {
1355                         if (child_variable_names == null)
1356                                 return false;
1357
1358                         return child_variable_names.Contains (name);
1359                 }
1360
1361                 // <summary>
1362                 //   This is used by non-static `struct' constructors which do not have an
1363                 //   initializer - in this case, the constructor must initialize all of the
1364                 //   struct's fields.  To do this, we add a "this" variable and use the flow
1365                 //   analysis code to ensure that it's been fully initialized before control
1366                 //   leaves the constructor.
1367                 // </summary>
1368                 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1369                 {
1370                         if (this_variable != null)
1371                                 return this_variable;
1372
1373                         if (variables == null)
1374                                 variables = new Hashtable ();
1375
1376                         this_variable = new LocalInfo (tc, this, l);
1377                         this_variable.Used = true;
1378
1379                         variables.Add ("this", this_variable);
1380
1381                         return this_variable;
1382                 }
1383
1384                 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1385                 {
1386                         if (variables == null)
1387                                 variables = new Hashtable ();
1388
1389                         LocalInfo vi = GetLocalInfo (name);
1390                         if (vi != null) {
1391                                 if (vi.Block != this)
1392                                         Report.Error (136, l, "A local variable named `" + name + "' " +
1393                                                       "cannot be declared in this scope since it would " +
1394                                                       "give a different meaning to `" + name + "', which " +
1395                                                       "is already used in a `parent or current' scope to " +
1396                                                       "denote something else");
1397                                 else
1398                                         Report.Error (128, l, "A local variable `" + name + "' is already " +
1399                                                       "defined in this scope");
1400                                 return null;
1401                         }
1402
1403                         if (IsVariableNameUsedInChildBlock (name)) {
1404                                 Report.Error (136, l, "A local variable named `" + name + "' " +
1405                                               "cannot be declared in this scope since it would " +
1406                                               "give a different meaning to `" + name + "', which " +
1407                                               "is already used in a `child' scope to denote something " +
1408                                               "else");
1409                                 return null;
1410                         }
1411
1412                         if (pars != null) {
1413                                 int idx;
1414                                 Parameter p = pars.GetParameterByName (name, out idx);
1415                                 if (p != null) {
1416                                         Report.Error (136, l, "A local variable named `" + name + "' " +
1417                                                       "cannot be declared in this scope since it would " +
1418                                                       "give a different meaning to `" + name + "', which " +
1419                                                       "is already used in a `parent or current' scope to " +
1420                                                       "denote something else");
1421                                         return null;
1422                                 }
1423                         }
1424
1425                         vi = new LocalInfo (type, name, this, l);
1426
1427                         variables.Add (name, vi);
1428
1429                         // Mark 'name' as "used by a child block" in every surrounding block
1430                         Block cur = this;
1431                         while (cur != null && cur.Implicit) 
1432                                 cur = cur.Parent;
1433                         if (cur != null)
1434                                 for (Block par = cur.Parent; par != null; par = par.Parent)
1435                                         par.AddChildVariableName (name);
1436
1437                         if ((flags & Flags.VariablesInitialized) != 0)
1438                                 throw new Exception ();
1439
1440                         // Console.WriteLine ("Adding {0} to {1}", name, ID);
1441                         return vi;
1442                 }
1443
1444                 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1445                 {
1446                         if (AddVariable (type, name, pars, l) == null)
1447                                 return false;
1448                         
1449                         if (constants == null)
1450                                 constants = new Hashtable ();
1451
1452                         constants.Add (name, value);
1453                         return true;
1454                 }
1455
1456                 public Hashtable Variables {
1457                         get {
1458                                 return variables;
1459                         }
1460                 }
1461
1462                 public LocalInfo GetLocalInfo (string name)
1463                 {
1464                         for (Block b = this; b != null; b = b.Parent) {
1465                                 if (b.variables != null) {
1466                                         LocalInfo ret = b.variables [name] as LocalInfo;
1467                                         if (ret != null)
1468                                                 return ret;
1469                                 }
1470                         }
1471                         return null;
1472                 }
1473
1474                 public Expression GetVariableType (string name)
1475                 {
1476                         LocalInfo vi = GetLocalInfo (name);
1477
1478                         if (vi != null)
1479                                 return vi.Type;
1480
1481                         return null;
1482                 }
1483
1484                 public Expression GetConstantExpression (string name)
1485                 {
1486                         for (Block b = this; b != null; b = b.Parent) {
1487                                 if (b.constants != null) {
1488                                         Expression ret = b.constants [name] as Expression;
1489                                         if (ret != null)
1490                                                 return ret;
1491                                 }
1492                         }
1493                         return null;
1494                 }
1495                 
1496                 /// <summary>
1497                 ///   True if the variable named @name is a constant
1498                 ///  </summary>
1499                 public bool IsConstant (string name)
1500                 {
1501                         Expression e = null;
1502                         
1503                         e = GetConstantExpression (name);
1504                         
1505                         return e != null;
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 (
2621                                                 null, FlowBranching.SiblingType.SwitchSection);
2622                                 else
2623                                         first = false;
2624
2625                                 if (ss.Block.Resolve (ec) != true)
2626                                         return false;
2627                         }
2628
2629
2630                         if (!got_default)
2631                                 ec.CurrentBranching.CreateSibling (
2632                                         null, FlowBranching.SiblingType.SwitchSection);
2633
2634                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2635                         ec.Switch = old_switch;
2636
2637                         Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2638                                       reachability);
2639
2640                         return true;
2641                 }
2642                 
2643                 protected override void DoEmit (EmitContext ec)
2644                 {
2645                         // Store variable for comparission purposes
2646                         LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2647                         new_expr.Emit (ec);
2648                         ec.ig.Emit (OpCodes.Stloc, value);
2649
2650                         ILGenerator ig = ec.ig;
2651
2652                         default_target = ig.DefineLabel ();
2653
2654                         //
2655                         // Setup the codegen context
2656                         //
2657                         Label old_end = ec.LoopEnd;
2658                         Switch old_switch = ec.Switch;
2659                         
2660                         ec.LoopEnd = ig.DefineLabel ();
2661                         ec.Switch = this;
2662
2663                         // Emit Code.
2664                         if (SwitchType == TypeManager.string_type)
2665                                 SimpleSwitchEmit (ec, value);
2666                         else
2667                                 TableSwitchEmit (ec, value);
2668
2669                         // Restore context state. 
2670                         ig.MarkLabel (ec.LoopEnd);
2671
2672                         //
2673                         // Restore the previous context
2674                         //
2675                         ec.LoopEnd = old_end;
2676                         ec.Switch = old_switch;
2677                 }
2678         }
2679
2680         public class Lock : Statement {
2681                 Expression expr;
2682                 Statement Statement;
2683                         
2684                 public Lock (Expression expr, Statement stmt, Location l)
2685                 {
2686                         this.expr = expr;
2687                         Statement = stmt;
2688                         loc = l;
2689                 }
2690
2691                 public override bool Resolve (EmitContext ec)
2692                 {
2693                         expr = expr.Resolve (ec);
2694                         if (expr == null)
2695                                 return false;
2696
2697                         if (expr.Type.IsValueType){
2698                                 Error (185, "lock statement requires the expression to be " +
2699                                        " a reference type (type is: `{0}'",
2700                                        TypeManager.CSharpName (expr.Type));
2701                                 return false;
2702                         }
2703
2704                         ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
2705                         bool ok = Statement.Resolve (ec);
2706                         ec.EndFlowBranching ();
2707
2708                         return ok;
2709                 }
2710                 
2711                 protected override void DoEmit (EmitContext ec)
2712                 {
2713                         Type type = expr.Type;
2714                         
2715                         ILGenerator ig = ec.ig;
2716                         LocalBuilder temp = ig.DeclareLocal (type);
2717                                 
2718                         expr.Emit (ec);
2719                         ig.Emit (OpCodes.Dup);
2720                         ig.Emit (OpCodes.Stloc, temp);
2721                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2722
2723                         // try
2724                         ig.BeginExceptionBlock ();
2725                         Label finish = ig.DefineLabel ();
2726                         Statement.Emit (ec);
2727                         // ig.Emit (OpCodes.Leave, finish);
2728
2729                         ig.MarkLabel (finish);
2730                         
2731                         // finally
2732                         ig.BeginFinallyBlock ();
2733                         ig.Emit (OpCodes.Ldloc, temp);
2734                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2735                         ig.EndExceptionBlock ();
2736                 }
2737         }
2738
2739         public class Unchecked : Statement {
2740                 public readonly Block Block;
2741                 
2742                 public Unchecked (Block b)
2743                 {
2744                         Block = b;
2745                         b.Unchecked = true;
2746                 }
2747
2748                 public override bool Resolve (EmitContext ec)
2749                 {
2750                         bool previous_state = ec.CheckState;
2751                         bool previous_state_const = ec.ConstantCheckState;
2752
2753                         ec.CheckState = false;
2754                         ec.ConstantCheckState = false;
2755                         bool ret = Block.Resolve (ec);
2756                         ec.CheckState = previous_state;
2757                         ec.ConstantCheckState = previous_state_const;
2758
2759                         return ret;
2760                 }
2761                 
2762                 protected override void DoEmit (EmitContext ec)
2763                 {
2764                         bool previous_state = ec.CheckState;
2765                         bool previous_state_const = ec.ConstantCheckState;
2766                         
2767                         ec.CheckState = false;
2768                         ec.ConstantCheckState = false;
2769                         Block.Emit (ec);
2770                         ec.CheckState = previous_state;
2771                         ec.ConstantCheckState = previous_state_const;
2772                 }
2773         }
2774
2775         public class Checked : Statement {
2776                 public readonly Block Block;
2777                 
2778                 public Checked (Block b)
2779                 {
2780                         Block = b;
2781                         b.Unchecked = false;
2782                 }
2783
2784                 public override bool Resolve (EmitContext ec)
2785                 {
2786                         bool previous_state = ec.CheckState;
2787                         bool previous_state_const = ec.ConstantCheckState;
2788                         
2789                         ec.CheckState = true;
2790                         ec.ConstantCheckState = true;
2791                         bool ret = Block.Resolve (ec);
2792                         ec.CheckState = previous_state;
2793                         ec.ConstantCheckState = previous_state_const;
2794
2795                         return ret;
2796                 }
2797
2798                 protected override void DoEmit (EmitContext ec)
2799                 {
2800                         bool previous_state = ec.CheckState;
2801                         bool previous_state_const = ec.ConstantCheckState;
2802                         
2803                         ec.CheckState = true;
2804                         ec.ConstantCheckState = true;
2805                         Block.Emit (ec);
2806                         ec.CheckState = previous_state;
2807                         ec.ConstantCheckState = previous_state_const;
2808                 }
2809         }
2810
2811         public class Unsafe : Statement {
2812                 public readonly Block Block;
2813
2814                 public Unsafe (Block b)
2815                 {
2816                         Block = b;
2817                 }
2818
2819                 public override bool Resolve (EmitContext ec)
2820                 {
2821                         bool previous_state = ec.InUnsafe;
2822                         bool val;
2823                         
2824                         ec.InUnsafe = true;
2825                         val = Block.Resolve (ec);
2826                         ec.InUnsafe = previous_state;
2827
2828                         return val;
2829                 }
2830                 
2831                 protected override void DoEmit (EmitContext ec)
2832                 {
2833                         bool previous_state = ec.InUnsafe;
2834                         
2835                         ec.InUnsafe = true;
2836                         Block.Emit (ec);
2837                         ec.InUnsafe = previous_state;
2838                 }
2839         }
2840
2841         // 
2842         // Fixed statement
2843         //
2844         public class Fixed : Statement {
2845                 Expression type;
2846                 ArrayList declarators;
2847                 Statement statement;
2848                 Type expr_type;
2849                 FixedData[] data;
2850                 bool has_ret;
2851
2852                 struct FixedData {
2853                         public bool is_object;
2854                         public LocalInfo vi;
2855                         public Expression expr;
2856                         public Expression converted;
2857                 }                       
2858
2859                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2860                 {
2861                         this.type = type;
2862                         declarators = decls;
2863                         statement = stmt;
2864                         loc = l;
2865                 }
2866
2867                 public override bool Resolve (EmitContext ec)
2868                 {
2869                         if (!ec.InUnsafe){
2870                                 Expression.UnsafeError (loc);
2871                                 return false;
2872                         }
2873                         
2874                         expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2875                         if (expr_type == null)
2876                                 return false;
2877
2878                         if (ec.RemapToProxy){
2879                                 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2880                                 return false;
2881                         }
2882                         
2883                         data = new FixedData [declarators.Count];
2884
2885                         if (!expr_type.IsPointer){
2886                                 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2887                                 return false;
2888                         }
2889                         
2890                         int i = 0;
2891                         foreach (Pair p in declarators){
2892                                 LocalInfo vi = (LocalInfo) p.First;
2893                                 Expression e = (Expression) p.Second;
2894
2895                                 vi.VariableInfo = null;
2896                                 vi.ReadOnly = true;
2897
2898                                 //
2899                                 // The rules for the possible declarators are pretty wise,
2900                                 // but the production on the grammar is more concise.
2901                                 //
2902                                 // So we have to enforce these rules here.
2903                                 //
2904                                 // We do not resolve before doing the case 1 test,
2905                                 // because the grammar is explicit in that the token &
2906                                 // is present, so we need to test for this particular case.
2907                                 //
2908
2909                                 if (e is Cast){
2910                                         Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2911                                         return false;
2912                                 }
2913                                 
2914                                 //
2915                                 // Case 1: & object.
2916                                 //
2917                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2918                                         Expression child = ((Unary) e).Expr;
2919
2920                                         vi.MakePinned ();
2921                                         if (child is ParameterReference || child is LocalVariableReference){
2922                                                 Report.Error (
2923                                                         213, loc, 
2924                                                         "No need to use fixed statement for parameters or " +
2925                                                         "local variable declarations (address is already " +
2926                                                         "fixed)");
2927                                                 return false;
2928                                         }
2929
2930                                         ec.InFixedInitializer = true;
2931                                         e = e.Resolve (ec);
2932                                         ec.InFixedInitializer = false;
2933                                         if (e == null)
2934                                                 return false;
2935
2936                                         child = ((Unary) e).Expr;
2937                                         
2938                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
2939                                                 return false;
2940
2941                                         data [i].is_object = true;
2942                                         data [i].expr = e;
2943                                         data [i].converted = null;
2944                                         data [i].vi = vi;
2945                                         i++;
2946
2947                                         continue;
2948                                 }
2949
2950                                 ec.InFixedInitializer = true;
2951                                 e = e.Resolve (ec);
2952                                 ec.InFixedInitializer = false;
2953                                 if (e == null)
2954                                         return false;
2955
2956                                 //
2957                                 // Case 2: Array
2958                                 //
2959                                 if (e.Type.IsArray){
2960                                         Type array_type = TypeManager.GetElementType (e.Type);
2961                                         
2962                                         vi.MakePinned ();
2963                                         //
2964                                         // Provided that array_type is unmanaged,
2965                                         //
2966                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
2967                                                 return false;
2968
2969                                         //
2970                                         // and T* is implicitly convertible to the
2971                                         // pointer type given in the fixed statement.
2972                                         //
2973                                         ArrayPtr array_ptr = new ArrayPtr (e, loc);
2974                                         
2975                                         Expression converted = Convert.ImplicitConversionRequired (
2976                                                 ec, array_ptr, vi.VariableType, loc);
2977                                         if (converted == null)
2978                                                 return false;
2979
2980                                         data [i].is_object = false;
2981                                         data [i].expr = e;
2982                                         data [i].converted = converted;
2983                                         data [i].vi = vi;
2984                                         i++;
2985
2986                                         continue;
2987                                 }
2988
2989                                 //
2990                                 // Case 3: string
2991                                 //
2992                                 if (e.Type == TypeManager.string_type){
2993                                         data [i].is_object = false;
2994                                         data [i].expr = e;
2995                                         data [i].converted = null;
2996                                         data [i].vi = vi;
2997                                         i++;
2998                                         continue;
2999                                 }
3000
3001                                 //
3002                                 // For other cases, flag a `this is already fixed expression'
3003                                 //
3004                                 if (e is LocalVariableReference || e is ParameterReference ||
3005                                     Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3006                                     
3007                                         Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3008                                         return false;
3009                                 }
3010
3011                                 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3012                                 return false;
3013                         }
3014
3015                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3016
3017                         if (!statement.Resolve (ec)) {
3018                                 ec.KillFlowBranching ();
3019                                 return false;
3020                         }
3021
3022                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3023                         has_ret = reachability.IsUnreachable;
3024
3025                         return true;
3026                 }
3027                 
3028                 protected override void DoEmit (EmitContext ec)
3029                 {
3030                         ILGenerator ig = ec.ig;
3031
3032                         LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3033                         
3034                         for (int i = 0; i < data.Length; i++) {
3035                                 LocalInfo vi = data [i].vi;
3036
3037                                 //
3038                                 // Case 1: & object.
3039                                 //
3040                                 if (data [i].is_object) {
3041                                         //
3042                                         // Store pointer in pinned location
3043                                         //
3044                                         data [i].expr.Emit (ec);
3045                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3046                                         clear_list [i] = vi.LocalBuilder;
3047                                         continue;
3048                                 }
3049
3050                                 //
3051                                 // Case 2: Array
3052                                 //
3053                                 if (data [i].expr.Type.IsArray){
3054                                         //
3055                                         // Store pointer in pinned location
3056                                         //
3057                                         data [i].converted.Emit (ec);
3058                                         
3059                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3060                                         clear_list [i] = vi.LocalBuilder;
3061                                         continue;
3062                                 }
3063
3064                                 //
3065                                 // Case 3: string
3066                                 //
3067                                 if (data [i].expr.Type == TypeManager.string_type){
3068                                         LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3069                                         TypeManager.MakePinned (pinned_string);
3070                                         clear_list [i] = pinned_string;
3071                                         
3072                                         data [i].expr.Emit (ec);
3073                                         ig.Emit (OpCodes.Stloc, pinned_string);
3074
3075                                         Expression sptr = new StringPtr (pinned_string, loc);
3076                                         Expression converted = Convert.ImplicitConversionRequired (
3077                                                 ec, sptr, vi.VariableType, loc);
3078                                         
3079                                         if (converted == null)
3080                                                 continue;
3081
3082                                         converted.Emit (ec);
3083                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3084                                 }
3085                         }
3086
3087                         statement.Emit (ec);
3088
3089                         if (has_ret)
3090                                 return;
3091
3092                         //
3093                         // Clear the pinned variable
3094                         //
3095                         for (int i = 0; i < data.Length; i++) {
3096                                 if (data [i].is_object || data [i].expr.Type.IsArray) {
3097                                         ig.Emit (OpCodes.Ldc_I4_0);
3098                                         ig.Emit (OpCodes.Conv_U);
3099                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3100                                 } else if (data [i].expr.Type == TypeManager.string_type){
3101                                         ig.Emit (OpCodes.Ldnull);
3102                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3103                                 }
3104                         }
3105                 }
3106         }
3107         
3108         public class Catch {
3109                 public readonly string Name;
3110                 public readonly Block  Block;
3111                 public readonly Location Location;
3112
3113                 Expression type_expr;
3114                 Type type;
3115                 
3116                 public Catch (Expression type, string name, Block block, Location l)
3117                 {
3118                         type_expr = type;
3119                         Name = name;
3120                         Block = block;
3121                         Location = l;
3122                 }
3123
3124                 public Type CatchType {
3125                         get {
3126                                 return type;
3127                         }
3128                 }
3129
3130                 public bool IsGeneral {
3131                         get {
3132                                 return type_expr == null;
3133                         }
3134                 }
3135
3136                 public bool Resolve (EmitContext ec)
3137                 {
3138                         if (type_expr != null) {
3139                                 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3140                                 if (type == null)
3141                                         return false;
3142
3143                                 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3144                                         Report.Error (155, Location,
3145                                                       "The type caught or thrown must be derived " +
3146                                                       "from System.Exception");
3147                                         return false;
3148                                 }
3149                         } else
3150                                 type = null;
3151
3152                         if (!Block.Resolve (ec))
3153                                 return false;
3154
3155                         return true;
3156                 }
3157         }
3158
3159         public class Try : Statement {
3160                 public readonly Block Fini, Block;
3161                 public readonly ArrayList Specific;
3162                 public readonly Catch General;
3163                 
3164                 //
3165                 // specific, general and fini might all be null.
3166                 //
3167                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3168                 {
3169                         if (specific == null && general == null){
3170                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3171                         }
3172                         
3173                         this.Block = block;
3174                         this.Specific = specific;
3175                         this.General = general;
3176                         this.Fini = fini;
3177                         loc = l;
3178                 }
3179
3180                 public override bool Resolve (EmitContext ec)
3181                 {
3182                         bool ok = true;
3183                         
3184                         ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3185
3186                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3187
3188                         if (!Block.Resolve (ec))
3189                                 ok = false;
3190
3191                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3192
3193                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
3194
3195                         foreach (Catch c in Specific){
3196                                 ec.CurrentBranching.CreateSibling (
3197                                         c.Block, FlowBranching.SiblingType.Catch);
3198
3199                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3200
3201                                 if (c.Name != null) {
3202                                         LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3203                                         if (vi == null)
3204                                                 throw new Exception ();
3205
3206                                         vi.VariableInfo = null;
3207                                 }
3208
3209                                 if (!c.Resolve (ec))
3210                                         ok = false;
3211                         }
3212
3213                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3214
3215                         if (General != null){
3216                                 ec.CurrentBranching.CreateSibling (
3217                                         General.Block, FlowBranching.SiblingType.Catch);
3218
3219                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3220
3221                                 if (!General.Resolve (ec))
3222                                         ok = false;
3223                         }
3224
3225                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3226
3227                         if (Fini != null) {
3228                                 if (ok)
3229                                         ec.CurrentBranching.CreateSibling (
3230                                                 Fini, FlowBranching.SiblingType.Finally);
3231
3232                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3233
3234                                 if (!Fini.Resolve (ec))
3235                                         ok = false;
3236                         }
3237
3238                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3239
3240                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3241
3242                         Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3243
3244                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3245                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
3246                                 // to the end of the finally block.  This is a problem if `returns'
3247                                 // is true since we may jump to a point after the end of the method.
3248                                 // As a workaround, emit an explicit ret here.
3249                                 ec.NeedReturnLabel ();
3250                         }
3251
3252                         return ok;
3253                 }
3254                 
3255                 protected override void DoEmit (EmitContext ec)
3256                 {
3257                         ILGenerator ig = ec.ig;
3258                         Label finish = ig.DefineLabel ();;
3259
3260                         ig.BeginExceptionBlock ();
3261                         Block.Emit (ec);
3262
3263                         //
3264                         // System.Reflection.Emit provides this automatically:
3265                         // ig.Emit (OpCodes.Leave, finish);
3266
3267                         foreach (Catch c in Specific){
3268                                 LocalInfo vi;
3269                                 
3270                                 ig.BeginCatchBlock (c.CatchType);
3271
3272                                 if (c.Name != null){
3273                                         vi = c.Block.GetLocalInfo (c.Name);
3274                                         if (vi == null)
3275                                                 throw new Exception ("Variable does not exist in this block");
3276
3277                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3278                                 } else
3279                                         ig.Emit (OpCodes.Pop);
3280                                 
3281                                 c.Block.Emit (ec);
3282                         }
3283
3284                         if (General != null){
3285                                 ig.BeginCatchBlock (TypeManager.object_type);
3286                                 ig.Emit (OpCodes.Pop);
3287                                 General.Block.Emit (ec);
3288                         }
3289
3290                         ig.MarkLabel (finish);
3291                         if (Fini != null){
3292                                 ig.BeginFinallyBlock ();
3293                                 Fini.Emit (ec);
3294                         }
3295                         
3296                         ig.EndExceptionBlock ();
3297                 }
3298         }
3299
3300         public class Using : Statement {
3301                 object expression_or_block;
3302                 Statement Statement;
3303                 ArrayList var_list;
3304                 Expression expr;
3305                 Type expr_type;
3306                 Expression conv;
3307                 Expression [] converted_vars;
3308                 ExpressionStatement [] assign;
3309                 
3310                 public Using (object expression_or_block, Statement stmt, Location l)
3311                 {
3312                         this.expression_or_block = expression_or_block;
3313                         Statement = stmt;
3314                         loc = l;
3315                 }
3316
3317                 //
3318                 // Resolves for the case of using using a local variable declaration.
3319                 //
3320                 bool ResolveLocalVariableDecls (EmitContext ec)
3321                 {
3322                         bool need_conv = false;
3323                         expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3324                         int i = 0;
3325
3326                         if (expr_type == null)
3327                                 return false;
3328
3329                         //
3330                         // The type must be an IDisposable or an implicit conversion
3331                         // must exist.
3332                         //
3333                         converted_vars = new Expression [var_list.Count];
3334                         assign = new ExpressionStatement [var_list.Count];
3335                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3336                                 foreach (DictionaryEntry e in var_list){
3337                                         Expression var = (Expression) e.Key;
3338
3339                                         var = var.ResolveLValue (ec, new EmptyExpression ());
3340                                         if (var == null)
3341                                                 return false;
3342                                         
3343                                         converted_vars [i] = Convert.ImplicitConversionRequired (
3344                                                 ec, var, TypeManager.idisposable_type, loc);
3345
3346                                         if (converted_vars [i] == null)
3347                                                 return false;
3348                                         i++;
3349                                 }
3350                                 need_conv = true;
3351                         }
3352
3353                         i = 0;
3354                         foreach (DictionaryEntry e in var_list){
3355                                 LocalVariableReference var = (LocalVariableReference) e.Key;
3356                                 Expression new_expr = (Expression) e.Value;
3357                                 Expression a;
3358
3359                                 a = new Assign (var, new_expr, loc);
3360                                 a = a.Resolve (ec);
3361                                 if (a == null)
3362                                         return false;
3363
3364                                 if (!need_conv)
3365                                         converted_vars [i] = var;
3366                                 assign [i] = (ExpressionStatement) a;
3367                                 i++;
3368                         }
3369
3370                         return true;
3371                 }
3372
3373                 bool ResolveExpression (EmitContext ec)
3374                 {
3375                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3376                                 conv = Convert.ImplicitConversionRequired (
3377                                         ec, expr, TypeManager.idisposable_type, loc);
3378
3379                                 if (conv == null)
3380                                         return false;
3381                         }
3382
3383                         return true;
3384                 }
3385                 
3386                 //
3387                 // Emits the code for the case of using using a local variable declaration.
3388                 //
3389                 bool EmitLocalVariableDecls (EmitContext ec)
3390                 {
3391                         ILGenerator ig = ec.ig;
3392                         int i = 0;
3393
3394                         for (i = 0; i < assign.Length; i++) {
3395                                 assign [i].EmitStatement (ec);
3396                                 
3397                                 ig.BeginExceptionBlock ();
3398                         }
3399                         Statement.Emit (ec);
3400
3401                         var_list.Reverse ();
3402                         foreach (DictionaryEntry e in var_list){
3403                                 LocalVariableReference var = (LocalVariableReference) e.Key;
3404                                 Label skip = ig.DefineLabel ();
3405                                 i--;
3406                                 
3407                                 ig.BeginFinallyBlock ();
3408
3409                                 if (!var.Type.IsValueType) {
3410                                         var.Emit (ec);
3411                                         ig.Emit (OpCodes.Brfalse, skip);
3412                                         converted_vars [i].Emit (ec);
3413                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3414                                 } else {
3415                                         Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3416
3417                                         if (!(ml is MethodGroupExpr)) {
3418                                                 var.Emit (ec);
3419                                                 ig.Emit (OpCodes.Box, var.Type);
3420                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3421                                         } else {
3422                                                 MethodInfo mi = null;
3423
3424                                                 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3425                                                         if (mk.GetParameters().Length == 0) {
3426                                                                 mi = mk;
3427                                                                 break;
3428                                                         }
3429                                                 }
3430
3431                                                 if (mi == null) {
3432                                                         Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3433                                                         return false;
3434                                                 }
3435
3436                                                 var.AddressOf (ec, AddressOp.Load);
3437                                                 ig.Emit (OpCodes.Call, mi);
3438                                         }
3439                                 }
3440
3441                                 ig.MarkLabel (skip);
3442                                 ig.EndExceptionBlock ();
3443                         }
3444
3445                         return false;
3446                 }
3447
3448                 bool EmitExpression (EmitContext ec)
3449                 {
3450                         //
3451                         // Make a copy of the expression and operate on that.
3452                         //
3453                         ILGenerator ig = ec.ig;
3454                         LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3455                         if (conv != null)
3456                                 conv.Emit (ec);
3457                         else
3458                                 expr.Emit (ec);
3459                         ig.Emit (OpCodes.Stloc, local_copy);
3460
3461                         ig.BeginExceptionBlock ();
3462                         Statement.Emit (ec);
3463                         
3464                         Label skip = ig.DefineLabel ();
3465                         ig.BeginFinallyBlock ();
3466                         ig.Emit (OpCodes.Ldloc, local_copy);
3467                         ig.Emit (OpCodes.Brfalse, skip);
3468                         ig.Emit (OpCodes.Ldloc, local_copy);
3469                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3470                         ig.MarkLabel (skip);
3471                         ig.EndExceptionBlock ();
3472
3473                         return false;
3474                 }
3475                 
3476                 public override bool Resolve (EmitContext ec)
3477                 {
3478                         if (expression_or_block is DictionaryEntry){
3479                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3480                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3481
3482                                 if (!ResolveLocalVariableDecls (ec))
3483                                         return false;
3484
3485                         } else if (expression_or_block is Expression){
3486                                 expr = (Expression) expression_or_block;
3487
3488                                 expr = expr.Resolve (ec);
3489                                 if (expr == null)
3490                                         return false;
3491
3492                                 expr_type = expr.Type;
3493
3494                                 if (!ResolveExpression (ec))
3495                                         return false;
3496                         }
3497
3498                         ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3499
3500                         bool ok = Statement.Resolve (ec);
3501
3502                         if (!ok) {
3503                                 ec.KillFlowBranching ();
3504                                 return false;
3505                         }
3506                                         
3507                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3508
3509                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3510                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
3511                                 // to the end of the finally block.  This is a problem if `returns'
3512                                 // is true since we may jump to a point after the end of the method.
3513                                 // As a workaround, emit an explicit ret here.
3514                                 ec.NeedReturnLabel ();
3515                         }
3516
3517                         return true;
3518                 }
3519                 
3520                 protected override void DoEmit (EmitContext ec)
3521                 {
3522                         if (expression_or_block is DictionaryEntry)
3523                                 EmitLocalVariableDecls (ec);
3524                         else if (expression_or_block is Expression)
3525                                 EmitExpression (ec);
3526                 }
3527         }
3528
3529         /// <summary>
3530         ///   Implementation of the foreach C# statement
3531         /// </summary>
3532         public class Foreach : Statement {
3533                 Expression type;
3534                 Expression variable;
3535                 Expression expr;
3536                 Statement statement;
3537                 ForeachHelperMethods hm;
3538                 Expression empty, conv;
3539                 Type array_type, element_type;
3540                 Type var_type;
3541                 
3542                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3543                                 Statement stmt, Location l)
3544                 {
3545                         this.type = type;
3546                         this.variable = var;
3547                         this.expr = expr;
3548                         statement = stmt;
3549                         loc = l;
3550                 }
3551                 
3552                 public override bool Resolve (EmitContext ec)
3553                 {
3554                         expr = expr.Resolve (ec);
3555                         if (expr == null)
3556                                 return false;
3557
3558                         var_type = ec.DeclSpace.ResolveType (type, false, loc);
3559                         if (var_type == null)
3560                                 return false;
3561                         
3562                         //
3563                         // We need an instance variable.  Not sure this is the best
3564                         // way of doing this.
3565                         //
3566                         // FIXME: When we implement propertyaccess, will those turn
3567                         // out to return values in ExprClass?  I think they should.
3568                         //
3569                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3570                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3571                                 error1579 (expr.Type);
3572                                 return false;
3573                         }
3574
3575                         if (expr.Type.IsArray) {
3576                                 array_type = expr.Type;
3577                                 element_type = TypeManager.GetElementType (array_type);
3578
3579                                 empty = new EmptyExpression (element_type);
3580                         } else {
3581                                 hm = ProbeCollectionType (ec, expr.Type);
3582                                 if (hm == null){
3583                                         error1579 (expr.Type);
3584                                         return false;
3585                                 }                       
3586
3587                                 array_type = expr.Type;
3588                                 element_type = hm.element_type;
3589
3590                                 empty = new EmptyExpression (hm.element_type);
3591                         }
3592
3593                         bool ok = true;
3594
3595                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3596                         ec.CurrentBranching.CreateSibling ();
3597
3598                         //
3599                         //
3600                         // FIXME: maybe we can apply the same trick we do in the
3601                         // array handling to avoid creating empty and conv in some cases.
3602                         //
3603                         // Although it is not as important in this case, as the type
3604                         // will not likely be object (what the enumerator will return).
3605                         //
3606                         conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3607                         if (conv == null)
3608                                 ok = false;
3609
3610                         variable = variable.ResolveLValue (ec, empty);
3611                         if (variable == null)
3612                                 ok = false;
3613
3614                         bool disposable = (hm != null) && hm.is_disposable;
3615                         if (disposable)
3616                                 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3617
3618                         if (!statement.Resolve (ec))
3619                                 ok = false;
3620
3621                         if (disposable)
3622                                 ec.EndFlowBranching ();
3623
3624                         ec.EndFlowBranching ();
3625
3626                         return ok;
3627                 }
3628                 
3629                 //
3630                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3631                 //
3632                 static MethodInfo FetchMethodMoveNext (Type t)
3633                 {
3634                         MemberList move_next_list;
3635                         
3636                         move_next_list = TypeContainer.FindMembers (
3637                                 t, MemberTypes.Method,
3638                                 BindingFlags.Public | BindingFlags.Instance,
3639                                 Type.FilterName, "MoveNext");
3640                         if (move_next_list.Count == 0)
3641                                 return null;
3642
3643                         foreach (MemberInfo m in move_next_list){
3644                                 MethodInfo mi = (MethodInfo) m;
3645                                 Type [] args;
3646                                 
3647                                 args = TypeManager.GetArgumentTypes (mi);
3648                                 if (args != null && args.Length == 0){
3649                                         if (mi.ReturnType == TypeManager.bool_type)
3650                                                 return mi;
3651                                 }
3652                         }
3653                         return null;
3654                 }
3655                 
3656                 //
3657                 // Retrieves a `public T get_Current ()' method from the Type `t'
3658                 //
3659                 static MethodInfo FetchMethodGetCurrent (Type t)
3660                 {
3661                         MemberList get_current_list;
3662
3663                         get_current_list = TypeContainer.FindMembers (
3664                                 t, MemberTypes.Method,
3665                                 BindingFlags.Public | BindingFlags.Instance,
3666                                 Type.FilterName, "get_Current");
3667                         if (get_current_list.Count == 0)
3668                                 return null;
3669
3670                         foreach (MemberInfo m in get_current_list){
3671                                 MethodInfo mi = (MethodInfo) m;
3672                                 Type [] args;
3673
3674                                 args = TypeManager.GetArgumentTypes (mi);
3675                                 if (args != null && args.Length == 0)
3676                                         return mi;
3677                         }
3678                         return null;
3679                 }
3680
3681                 // 
3682                 // This struct records the helper methods used by the Foreach construct
3683                 //
3684                 class ForeachHelperMethods {
3685                         public EmitContext ec;
3686                         public MethodInfo get_enumerator;
3687                         public MethodInfo move_next;
3688                         public MethodInfo get_current;
3689                         public Type element_type;
3690                         public Type enumerator_type;
3691                         public bool is_disposable;
3692
3693                         public ForeachHelperMethods (EmitContext ec)
3694                         {
3695                                 this.ec = ec;
3696                                 this.element_type = TypeManager.object_type;
3697                                 this.enumerator_type = TypeManager.ienumerator_type;
3698                                 this.is_disposable = true;
3699                         }
3700                 }
3701                 
3702                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3703                 {
3704                         if (m == null)
3705                                 return false;
3706                         
3707                         if (!(m is MethodInfo))
3708                                 return false;
3709                         
3710                         if (m.Name != "GetEnumerator")
3711                                 return false;
3712
3713                         MethodInfo mi = (MethodInfo) m;
3714                         Type [] args = TypeManager.GetArgumentTypes (mi);
3715                         if (args != null){
3716                                 if (args.Length != 0)
3717                                         return false;
3718                         }
3719                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3720                         EmitContext ec = hm.ec;
3721
3722                         //
3723                         // Check whether GetEnumerator is accessible to us
3724                         //
3725                         MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3726
3727                         Type declaring = mi.DeclaringType;
3728                         if (prot == MethodAttributes.Private){
3729                                 if (declaring != ec.ContainerType)
3730                                         return false;
3731                         } else if (prot == MethodAttributes.FamANDAssem){
3732                                 // If from a different assembly, false
3733                                 if (!(mi is MethodBuilder))
3734                                         return false;
3735                                 //
3736                                 // Are we being invoked from the same class, or from a derived method?
3737                                 //
3738                                 if (ec.ContainerType != declaring){
3739                                         if (!ec.ContainerType.IsSubclassOf (declaring))
3740                                                 return false;
3741                                 }
3742                         } else if (prot == MethodAttributes.FamORAssem){
3743                                 if (!(mi is MethodBuilder ||
3744                                       ec.ContainerType == declaring ||
3745                                       ec.ContainerType.IsSubclassOf (declaring)))
3746                                         return false;
3747                         } if (prot == MethodAttributes.Family){
3748                                 if (!(ec.ContainerType == declaring ||
3749                                       ec.ContainerType.IsSubclassOf (declaring)))
3750                                         return false;
3751                         }
3752
3753                         if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3754                                 //
3755                                 // Apply the same optimization as MS: skip the GetEnumerator
3756                                 // returning an IEnumerator, and use the one returning a 
3757                                 // CharEnumerator instead. This allows us to avoid the 
3758                                 // try-finally block and the boxing.
3759                                 //
3760                                 return false;
3761
3762                         //
3763                         // Ok, we can access it, now make sure that we can do something
3764                         // with this `GetEnumerator'
3765                         //
3766                         
3767                         Type return_type = mi.ReturnType;
3768                         if (mi.ReturnType == TypeManager.ienumerator_type ||
3769                             TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3770                             (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3771                                 
3772                                 //
3773                                 // If it is not an interface, lets try to find the methods ourselves.
3774                                 // For example, if we have:
3775                                 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
3776                                 // We can avoid the iface call. This is a runtime perf boost.
3777                                 // even bigger if we have a ValueType, because we avoid the cost
3778                                 // of boxing.
3779                                 //
3780                                 // We have to make sure that both methods exist for us to take
3781                                 // this path. If one of the methods does not exist, we will just
3782                                 // use the interface. Sadly, this complex if statement is the only
3783                                 // way I could do this without a goto
3784                                 //
3785                                 
3786                                 if (return_type.IsInterface ||
3787                                     (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
3788                                     (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
3789                                         
3790                                         hm.move_next = TypeManager.bool_movenext_void;
3791                                         hm.get_current = TypeManager.object_getcurrent_void;
3792                                         return true;    
3793                                 }
3794
3795                         } else {
3796
3797                                 //
3798                                 // Ok, so they dont return an IEnumerable, we will have to
3799                                 // find if they support the GetEnumerator pattern.
3800                                 //
3801                                 
3802                                 hm.move_next = FetchMethodMoveNext (return_type);
3803                                 if (hm.move_next == null)
3804                                         return false;
3805                                 
3806                                 hm.get_current = FetchMethodGetCurrent (return_type);
3807                                 if (hm.get_current == null)
3808                                         return false;
3809                         }
3810                         
3811                         hm.element_type = hm.get_current.ReturnType;
3812                         hm.enumerator_type = return_type;
3813                         hm.is_disposable = !hm.enumerator_type.IsSealed ||
3814                                 TypeManager.ImplementsInterface (
3815                                         hm.enumerator_type, TypeManager.idisposable_type);
3816
3817                         return true;
3818                 }
3819                 
3820                 /// <summary>
3821                 ///   This filter is used to find the GetEnumerator method
3822                 ///   on which IEnumerator operates
3823                 /// </summary>
3824                 static MemberFilter FilterEnumerator;
3825                 
3826                 static Foreach ()
3827                 {
3828                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3829                 }
3830
3831                 void error1579 (Type t)
3832                 {
3833                         Report.Error (1579, loc,
3834                                       "foreach statement cannot operate on variables of type `" +
3835                                       t.FullName + "' because that class does not provide a " +
3836                                       " GetEnumerator method or it is inaccessible");
3837                 }
3838
3839                 static bool TryType (Type t, ForeachHelperMethods hm)
3840                 {
3841                         MemberList mi;
3842                         
3843                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3844                                                         BindingFlags.Public | BindingFlags.NonPublic |
3845                                                         BindingFlags.Instance | BindingFlags.DeclaredOnly,
3846                                                         FilterEnumerator, hm);
3847
3848                         if (mi.Count == 0)
3849                                 return false;
3850
3851                         hm.get_enumerator = (MethodInfo) mi [0];
3852                         return true;    
3853                 }
3854                 
3855                 //
3856                 // Looks for a usable GetEnumerator in the Type, and if found returns
3857                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3858                 //
3859                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3860                 {
3861                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3862
3863                         for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3864                                 if (TryType (tt, hm))
3865                                         return hm;
3866                                 tt = tt.BaseType;
3867                         }
3868
3869                         //
3870                         // Now try to find the method in the interfaces
3871                         //
3872                         while (t != null){
3873                                 Type [] ifaces = t.GetInterfaces ();
3874
3875                                 foreach (Type i in ifaces){
3876                                         if (TryType (i, hm))
3877                                                 return hm;
3878                                 }
3879                                 
3880                                 //
3881                                 // Since TypeBuilder.GetInterfaces only returns the interface
3882                                 // types for this type, we have to keep looping, but once
3883                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3884                                 // done, because it returns all the types
3885                                 //
3886                                 if ((t is TypeBuilder))
3887                                         t = t.BaseType;
3888                                 else
3889                                         break;
3890                         } 
3891
3892                         return null;
3893                 }
3894
3895                 //
3896                 // FIXME: possible optimization.
3897                 // We might be able to avoid creating `empty' if the type is the sam
3898                 //
3899                 bool EmitCollectionForeach (EmitContext ec)
3900                 {
3901                         ILGenerator ig = ec.ig;
3902                         VariableStorage enumerator;
3903
3904                         enumerator = new VariableStorage (ec, hm.enumerator_type);
3905                         enumerator.EmitThis ();
3906                         //
3907                         // Instantiate the enumerator
3908                         //
3909                         if (expr.Type.IsValueType){
3910                                 if (expr is IMemoryLocation){
3911                                         IMemoryLocation ml = (IMemoryLocation) expr;
3912
3913                                         Expression ml1 = Expression.MemberLookup(ec, TypeManager.ienumerator_type, expr.Type, "GetEnumerator", Mono.CSharp.Location.Null);
3914
3915                                         if (!(ml1 is MethodGroupExpr)) {
3916                                                 expr.Emit(ec);
3917                                                 ec.ig.Emit(OpCodes.Box, expr.Type);
3918                                         } else {
3919                                                 ml.AddressOf (ec, AddressOp.Load);
3920                                         }
3921                                 } else
3922                                         throw new Exception ("Expr " + expr + " of type " + expr.Type +
3923                                                              " does not implement IMemoryLocation");
3924                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3925                         } else {
3926                                 expr.Emit (ec);
3927                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3928                         }
3929                         enumerator.EmitStore ();
3930
3931                         //
3932                         // Protect the code in a try/finalize block, so that
3933                         // if the beast implement IDisposable, we get rid of it
3934                         //
3935                         if (hm.is_disposable)
3936                                 ig.BeginExceptionBlock ();
3937                         
3938                         Label end_try = ig.DefineLabel ();
3939                         
3940                         ig.MarkLabel (ec.LoopBegin);
3941                         
3942                         enumerator.EmitCall (hm.move_next);
3943                         
3944                         ig.Emit (OpCodes.Brfalse, end_try);
3945                         if (ec.InIterator)
3946                                 ec.EmitThis ();
3947                         
3948                         enumerator.EmitCall (hm.get_current);
3949
3950                         if (ec.InIterator){
3951                                 conv.Emit (ec);
3952                                 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3953                         } else 
3954                                 ((IAssignMethod)variable).EmitAssign (ec, conv);
3955                                 
3956                         statement.Emit (ec);
3957                         ig.Emit (OpCodes.Br, ec.LoopBegin);
3958                         ig.MarkLabel (end_try);
3959                         
3960                         // The runtime provides this for us.
3961                         // ig.Emit (OpCodes.Leave, end);
3962
3963                         //
3964                         // Now the finally block
3965                         //
3966                         if (hm.is_disposable) {
3967                                 Label call_dispose = ig.DefineLabel ();
3968                                 ig.BeginFinallyBlock ();
3969                                 
3970                                 enumerator.EmitThis ();
3971                                 enumerator.EmitLoad ();
3972                                 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
3973                                 ig.Emit (OpCodes.Dup);
3974                                 ig.Emit (OpCodes.Brtrue_S, call_dispose);
3975                                 ig.Emit (OpCodes.Pop);
3976                                 ig.Emit (OpCodes.Endfinally);
3977                                 
3978                                 ig.MarkLabel (call_dispose);
3979                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3980                                 
3981
3982                                 // The runtime generates this anyways.
3983                                 // ig.Emit (OpCodes.Endfinally);
3984
3985                                 ig.EndExceptionBlock ();
3986                         }
3987
3988                         ig.MarkLabel (ec.LoopEnd);
3989                         return false;
3990                 }
3991
3992                 //
3993                 // FIXME: possible optimization.
3994                 // We might be able to avoid creating `empty' if the type is the sam
3995                 //
3996                 bool EmitArrayForeach (EmitContext ec)
3997                 {
3998                         int rank = array_type.GetArrayRank ();
3999                         ILGenerator ig = ec.ig;
4000
4001                         VariableStorage copy = new VariableStorage (ec, array_type);
4002                         
4003                         //
4004                         // Make our copy of the array
4005                         //
4006                         copy.EmitThis ();
4007                         expr.Emit (ec);
4008                         copy.EmitStore ();
4009                         
4010                         if (rank == 1){
4011                                 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4012
4013                                 Label loop, test;
4014
4015                                 counter.EmitThis ();
4016                                 ig.Emit (OpCodes.Ldc_I4_0);
4017                                 counter.EmitStore ();
4018                                 test = ig.DefineLabel ();
4019                                 ig.Emit (OpCodes.Br, test);
4020
4021                                 loop = ig.DefineLabel ();
4022                                 ig.MarkLabel (loop);
4023
4024                                 if (ec.InIterator)
4025                                         ec.EmitThis ();
4026                                 
4027                                 copy.EmitThis ();
4028                                 copy.EmitLoad ();
4029                                 counter.EmitThis ();
4030                                 counter.EmitLoad ();
4031
4032                                 //
4033                                 // Load the value, we load the value using the underlying type,
4034                                 // then we use the variable.EmitAssign to load using the proper cast.
4035                                 //
4036                                 ArrayAccess.EmitLoadOpcode (ig, element_type);
4037                                 if (ec.InIterator){
4038                                         conv.Emit (ec);
4039                                         ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4040                                 } else 
4041                                         ((IAssignMethod)variable).EmitAssign (ec, conv);
4042
4043                                 statement.Emit (ec);
4044
4045                                 ig.MarkLabel (ec.LoopBegin);
4046                                 counter.EmitThis ();
4047                                 counter.EmitThis ();
4048                                 counter.EmitLoad ();
4049                                 ig.Emit (OpCodes.Ldc_I4_1);
4050                                 ig.Emit (OpCodes.Add);
4051                                 counter.EmitStore ();
4052
4053                                 ig.MarkLabel (test);
4054                                 counter.EmitThis ();
4055                                 counter.EmitLoad ();
4056                                 copy.EmitThis ();
4057                                 copy.EmitLoad ();
4058                                 ig.Emit (OpCodes.Ldlen);
4059                                 ig.Emit (OpCodes.Conv_I4);
4060                                 ig.Emit (OpCodes.Blt, loop);
4061                         } else {
4062                                 VariableStorage [] dim_len   = new VariableStorage [rank];
4063                                 VariableStorage [] dim_count = new VariableStorage [rank];
4064                                 Label [] loop = new Label [rank];
4065                                 Label [] test = new Label [rank];
4066                                 int dim;
4067                                 
4068                                 for (dim = 0; dim < rank; dim++){
4069                                         dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4070                                         dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4071                                         test [dim] = ig.DefineLabel ();
4072                                         loop [dim] = ig.DefineLabel ();
4073                                 }
4074                                         
4075                                 for (dim = 0; dim < rank; dim++){
4076                                         dim_len [dim].EmitThis ();
4077                                         copy.EmitThis ();
4078                                         copy.EmitLoad ();
4079                                         IntLiteral.EmitInt (ig, dim);
4080                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4081                                         dim_len [dim].EmitStore ();
4082                                         
4083                                 }
4084
4085                                 for (dim = 0; dim < rank; dim++){
4086                                         dim_count [dim].EmitThis ();
4087                                         ig.Emit (OpCodes.Ldc_I4_0);
4088                                         dim_count [dim].EmitStore ();
4089                                         ig.Emit (OpCodes.Br, test [dim]);
4090                                         ig.MarkLabel (loop [dim]);
4091                                 }
4092
4093                                 if (ec.InIterator)
4094                                         ec.EmitThis ();
4095                                 copy.EmitThis ();
4096                                 copy.EmitLoad ();
4097                                 for (dim = 0; dim < rank; dim++){
4098                                         dim_count [dim].EmitThis ();
4099                                         dim_count [dim].EmitLoad ();
4100                                 }
4101
4102                                 //
4103                                 // FIXME: Maybe we can cache the computation of `get'?
4104                                 //
4105                                 Type [] args = new Type [rank];
4106                                 MethodInfo get;
4107
4108                                 for (int i = 0; i < rank; i++)
4109                                         args [i] = TypeManager.int32_type;
4110
4111                                 ModuleBuilder mb = CodeGen.Module.Builder;
4112                                 get = mb.GetArrayMethod (
4113                                         array_type, "Get",
4114                                         CallingConventions.HasThis| CallingConventions.Standard,
4115                                         var_type, args);
4116                                 ig.Emit (OpCodes.Call, get);
4117                                 if (ec.InIterator){
4118                                         conv.Emit (ec);
4119                                         ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4120                                 } else 
4121                                         ((IAssignMethod)variable).EmitAssign (ec, conv);
4122                                 statement.Emit (ec);
4123                                 ig.MarkLabel (ec.LoopBegin);
4124                                 for (dim = rank - 1; dim >= 0; dim--){
4125                                         dim_count [dim].EmitThis ();
4126                                         dim_count [dim].EmitThis ();
4127                                         dim_count [dim].EmitLoad ();
4128                                         ig.Emit (OpCodes.Ldc_I4_1);
4129                                         ig.Emit (OpCodes.Add);
4130                                         dim_count [dim].EmitStore ();
4131
4132                                         ig.MarkLabel (test [dim]);
4133                                         dim_count [dim].EmitThis ();
4134                                         dim_count [dim].EmitLoad ();
4135                                         dim_len [dim].EmitThis ();
4136                                         dim_len [dim].EmitLoad ();
4137                                         ig.Emit (OpCodes.Blt, loop [dim]);
4138                                 }
4139                         }
4140                         ig.MarkLabel (ec.LoopEnd);
4141                         
4142                         return false;
4143                 }
4144                 
4145                 protected override void DoEmit (EmitContext ec)
4146                 {
4147                         ILGenerator ig = ec.ig;
4148                         
4149                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4150                         ec.LoopBegin = ig.DefineLabel ();
4151                         ec.LoopEnd = ig.DefineLabel ();
4152                         
4153                         if (hm != null)
4154                                 EmitCollectionForeach (ec);
4155                         else
4156                                 EmitArrayForeach (ec);
4157                         
4158                         ec.LoopBegin = old_begin;
4159                         ec.LoopEnd = old_end;
4160                 }
4161         }
4162 }