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