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