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