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