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