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