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