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