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