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