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