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