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