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