2007-10-24 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / mcs / statement.cs
1 //
2 // statement.cs: Statement representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Martin Baulig (martin@ximian.com)
7 //   Marek Safar (marek.safar@seznam.cz)
8 //
9 // (C) 2001, 2002, 2003 Ximian, Inc.
10 // (C) 2003, 2004 Novell, Inc.
11 //
12
13 using System;
14 using System.Text;
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Diagnostics;
18 using System.Collections;
19 using System.Collections.Specialized;
20
21 namespace Mono.CSharp {
22         
23         public abstract class Statement {
24                 public Location loc;
25                 
26                 /// <summary>
27                 ///   Resolves the statement, true means that all sub-statements
28                 ///   did resolve ok.
29                 //  </summary>
30                 public virtual bool Resolve (EmitContext ec)
31                 {
32                         return true;
33                 }
34
35                 /// <summary>
36                 ///   We already know that the statement is unreachable, but we still
37                 ///   need to resolve it to catch errors.
38                 /// </summary>
39                 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
40                 {
41                         //
42                         // This conflicts with csc's way of doing this, but IMHO it's
43                         // the right thing to do.
44                         //
45                         // If something is unreachable, we still check whether it's
46                         // correct.  This means that you cannot use unassigned variables
47                         // in unreachable code, for instance.
48                         //
49
50                         if (warn)
51                                 Report.Warning (162, 2, loc, "Unreachable code detected");
52
53                         ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
54                         bool ok = Resolve (ec);
55                         ec.KillFlowBranching ();
56
57                         return ok;
58                 }
59                                 
60                 /// <summary>
61                 ///   Return value indicates whether all code paths emitted return.
62                 /// </summary>
63                 protected abstract void DoEmit (EmitContext ec);
64
65                 /// <summary>
66                 ///   Utility wrapper routine for Error, just to beautify the code
67                 /// </summary>
68                 public void Error (int error, string format, params object[] args)
69                 {
70                         Error (error, String.Format (format, args));
71                 }
72
73                 public void Error (int error, string s)
74                 {
75                         if (!loc.IsNull)
76                                 Report.Error (error, loc, s);
77                         else
78                                 Report.Error (error, s);
79                 }
80
81                 /// <summary>
82                 ///   Return value indicates whether all code paths emitted return.
83                 /// </summary>
84                 public virtual void Emit (EmitContext ec)
85                 {
86                         ec.Mark (loc, true);
87                         DoEmit (ec);
88                 }
89
90                 //
91                 // This routine must be overrided in derived classes and make copies
92                 // of all the data that might be modified if resolved
93                 // 
94                 protected virtual void CloneTo (CloneContext clonectx, Statement target)
95                 {
96                         throw new InternalErrorException ("{0} does not implement Statement.CloneTo", this.GetType ());
97                 }
98
99                 public Statement Clone (CloneContext clonectx)
100                 {
101                         Statement s = (Statement) this.MemberwiseClone ();
102                         CloneTo (clonectx, s);
103                         return s;
104                 }
105
106                 public 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 trueStatement, Location l)
213                 {
214                         this.expr = expr;
215                         TrueStatement = trueStatement;
216                         loc = l;
217                 }
218
219                 public If (Expression expr,
220                            Statement trueStatement,
221                            Statement falseStatement,
222                            Location l)
223                 {
224                         this.expr = expr;
225                         TrueStatement = trueStatement;
226                         FalseStatement = falseStatement;
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 boolExpr, Location l)
353                 {
354                         expr = boolExpr;
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 boolExpr, Statement statement, Location l)
438                 {
439                         this.expr = boolExpr;
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 initStatement,
545                             Expression test,
546                             Statement increment,
547                             Statement statement,
548                             Location l)
549                 {
550                         InitStatement = initStatement;
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                 //
2672                 // Whether the parameter named `name' is local to this block, 
2673                 // or false, if the parameter belongs to an encompassing block.
2674                 //
2675                 public bool IsLocalParameter (string name)
2676                 {
2677                         return Parameters.GetParameterByName (name) != null;
2678                 }
2679                 
2680                 //
2681                 // Whether the `name' is a parameter reference
2682                 //
2683                 public bool IsParameterReference (string name)
2684                 {
2685                         for (ToplevelBlock t = this; t != null; t = t.Container) {
2686                                 if (t.IsLocalParameter (name))
2687                                         return true;
2688                         }
2689                         return false;
2690                 }
2691
2692                 LocalInfo this_variable = null;
2693
2694                 // <summary>
2695                 //   Returns the "this" instance variable of this block.
2696                 //   See AddThisVariable() for more information.
2697                 // </summary>
2698                 public LocalInfo ThisVariable {
2699                         get { return this_variable; }
2700                 }
2701
2702
2703                 // <summary>
2704                 //   This is used by non-static `struct' constructors which do not have an
2705                 //   initializer - in this case, the constructor must initialize all of the
2706                 //   struct's fields.  To do this, we add a "this" variable and use the flow
2707                 //   analysis code to ensure that it's been fully initialized before control
2708                 //   leaves the constructor.
2709                 // </summary>
2710                 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2711                 {
2712                         if (this_variable == null) {
2713                                 this_variable = new LocalInfo (ds, this, l);
2714                                 this_variable.Used = true;
2715                                 this_variable.IsThis = true;
2716
2717                                 Variables.Add ("this", this_variable);
2718                         }
2719
2720                         return this_variable;
2721                 }
2722
2723                 public bool IsThisAssigned (EmitContext ec)
2724                 {
2725                         return this_variable == null || this_variable.IsThisAssigned (ec);
2726                 }
2727
2728                 public bool ResolveMeta (EmitContext ec, Parameters ip)
2729                 {
2730                         int errors = Report.Errors;
2731                         int orig_count = parameters.Count;
2732
2733                         if (top_level_branching != null)
2734                                 return true;
2735
2736                         if (ip != null)
2737                                 parameters = ip;
2738
2739                         // Assert: orig_count != parameter.Count => orig_count == 0
2740                         if (orig_count != 0 && orig_count != parameters.Count)
2741                                 throw new InternalErrorException ("parameter information mismatch");
2742
2743                         int offset = Parent == null ? 0 : Parent.AssignableSlots;
2744
2745                         for (int i = 0; i < orig_count; ++i) {
2746                                 Parameter.Modifier mod = parameters.ParameterModifier (i);
2747
2748                                 if ((mod & Parameter.Modifier.OUT) != Parameter.Modifier.OUT)
2749                                         continue;
2750
2751                                 VariableInfo vi = new VariableInfo (ip, i, offset);
2752                                 parameter_info [i].VariableInfo = vi;
2753                                 offset += vi.Length;
2754                         }
2755
2756                         ResolveMeta (ec, offset);
2757
2758                         top_level_branching = ec.StartFlowBranching (this);
2759
2760                         return Report.Errors == errors;
2761                 }
2762
2763                 // <summary>
2764                 //   Check whether all `out' parameters have been assigned.
2765                 // </summary>
2766                 public void CheckOutParameters (FlowBranching.UsageVector vector, Location loc)
2767                 {
2768                         if (vector.IsUnreachable)
2769                                 return;
2770
2771                         int n = parameter_info == null ? 0 : parameter_info.Length;
2772
2773                         for (int i = 0; i < n; i++) {
2774                                 VariableInfo var = parameter_info [i].VariableInfo;
2775
2776                                 if (var == null)
2777                                         continue;
2778
2779                                 if (vector.IsAssigned (var, false))
2780                                         continue;
2781
2782                                 Report.Error (177, loc, "The out parameter `{0}' must be assigned to before control leaves the current method",
2783                                         var.Name);
2784                         }
2785                 }
2786
2787                 public override void EmitMeta (EmitContext ec)
2788                 {
2789                         base.EmitMeta (ec);
2790                         parameters.ResolveVariable (this);
2791                 }
2792
2793                 public void MakeIterator (Iterator iterator)
2794                 {
2795                         flags |= Flags.IsIterator;
2796
2797                         Block block = new ExplicitBlock (this, StartLocation, EndLocation);
2798                         foreach (Statement stmt in statements)
2799                                 block.AddStatement (stmt);
2800                         statements.Clear ();
2801                         statements.Add (new MoveNextStatement (iterator, block));
2802                 }
2803
2804                 protected class MoveNextStatement : Statement {
2805                         Iterator iterator;
2806                         Block block;
2807
2808                         public MoveNextStatement (Iterator iterator, Block block)
2809                         {
2810                                 this.iterator = iterator;
2811                                 this.block = block;
2812                                 this.loc = iterator.Location;
2813                         }
2814
2815                         public override bool Resolve (EmitContext ec)
2816                         {
2817                                 return block.Resolve (ec);
2818                         }
2819
2820                         protected override void DoEmit (EmitContext ec)
2821                         {
2822                                 iterator.EmitMoveNext (ec, block);
2823                         }
2824                 }
2825
2826                 public override string ToString ()
2827                 {
2828                         return String.Format ("{0} ({1}:{2}{3}:{4})", GetType (), ID, StartLocation,
2829                                               root_scope, anonymous_container != null ?
2830                                               anonymous_container.Scope : null);
2831                 }
2832         }
2833         
2834         public class SwitchLabel {
2835                 Expression label;
2836                 object converted;
2837                 Location loc;
2838
2839                 Label il_label;
2840                 bool  il_label_set;
2841                 Label il_label_code;
2842                 bool  il_label_code_set;
2843
2844                 public static readonly object NullStringCase = new object ();
2845
2846                 //
2847                 // if expr == null, then it is the default case.
2848                 //
2849                 public SwitchLabel (Expression expr, Location l)
2850                 {
2851                         label = expr;
2852                         loc = l;
2853                 }
2854
2855                 public Expression Label {
2856                         get {
2857                                 return label;
2858                         }
2859                 }
2860
2861                 public object Converted {
2862                         get {
2863                                 return converted;
2864                         }
2865                 }
2866
2867                 public Label GetILLabel (EmitContext ec)
2868                 {
2869                         if (!il_label_set){
2870                                 il_label = ec.ig.DefineLabel ();
2871                                 il_label_set = true;
2872                         }
2873                         return il_label;
2874                 }
2875
2876                 public Label GetILLabelCode (EmitContext ec)
2877                 {
2878                         if (!il_label_code_set){
2879                                 il_label_code = ec.ig.DefineLabel ();
2880                                 il_label_code_set = true;
2881                         }
2882                         return il_label_code;
2883                 }                               
2884                 
2885                 //
2886                 // Resolves the expression, reduces it to a literal if possible
2887                 // and then converts it to the requested type.
2888                 //
2889                 public bool ResolveAndReduce (EmitContext ec, Type required_type, bool allow_nullable)
2890                 {       
2891                         Expression e = label.Resolve (ec);
2892
2893                         if (e == null)
2894                                 return false;
2895
2896                         Constant c = e as Constant;
2897                         if (c == null){
2898                                 Report.Error (150, loc, "A constant value is expected");
2899                                 return false;
2900                         }
2901
2902                         if (required_type == TypeManager.string_type && c.GetValue () == null) {
2903                                 converted = NullStringCase;
2904                                 return true;
2905                         }
2906
2907                         if (allow_nullable && c.GetValue () == null) {
2908                                 converted = NullStringCase;
2909                                 return true;
2910                         }
2911
2912                         c = c.ImplicitConversionRequired (required_type, loc);
2913                         if (c == null)
2914                                 return false;
2915
2916                         converted = c.GetValue ();
2917                         return true;
2918                 }
2919
2920                 public void Erorr_AlreadyOccurs (Type switchType, SwitchLabel collisionWith)
2921                 {
2922                         string label;
2923                         if (converted == null)
2924                                 label = "default";
2925                         else if (converted == NullStringCase)
2926                                 label = "null";
2927                         else if (TypeManager.IsEnumType (switchType)) 
2928                                 label = TypeManager.CSharpEnumValue (switchType, converted);
2929                         else
2930                                 label = converted.ToString ();
2931                         
2932                         Report.SymbolRelatedToPreviousError (collisionWith.loc, null);
2933                         Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2934                 }
2935
2936                 public SwitchLabel Clone (CloneContext clonectx)
2937                 {
2938                         return new SwitchLabel (label.Clone (clonectx), loc);
2939                 }
2940         }
2941
2942         public class SwitchSection {
2943                 // An array of SwitchLabels.
2944                 public readonly ArrayList Labels;
2945                 public readonly Block Block;
2946                 
2947                 public SwitchSection (ArrayList labels, Block block)
2948                 {
2949                         Labels = labels;
2950                         Block = block;
2951                 }
2952
2953                 public SwitchSection Clone (CloneContext clonectx)
2954                 {
2955                         ArrayList cloned_labels = new ArrayList ();
2956
2957                         foreach (SwitchLabel sl in cloned_labels)
2958                                 cloned_labels.Add (sl.Clone (clonectx));
2959                         
2960                         return new SwitchSection (cloned_labels, clonectx.LookupBlock (Block));
2961                 }
2962         }
2963         
2964         public class Switch : Statement {
2965                 public ArrayList Sections;
2966                 public Expression Expr;
2967
2968                 /// <summary>
2969                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
2970                 /// </summary>
2971                 public IDictionary Elements;
2972
2973                 /// <summary>
2974                 ///   The governing switch type
2975                 /// </summary>
2976                 public Type SwitchType;
2977
2978                 //
2979                 // Computed
2980                 //
2981                 Label default_target;
2982                 Label null_target;
2983                 Expression new_expr;
2984                 bool is_constant;
2985                 SwitchSection constant_section;
2986                 SwitchSection default_section;
2987
2988 #if GMCS_SOURCE
2989                 //
2990                 // Nullable Types support for GMCS.
2991                 //
2992                 Nullable.Unwrap unwrap;
2993
2994                 protected bool HaveUnwrap {
2995                         get { return unwrap != null; }
2996                 }
2997 #else
2998                 protected bool HaveUnwrap {
2999                         get { return false; }
3000                 }
3001 #endif
3002
3003                 //
3004                 // The types allowed to be implicitly cast from
3005                 // on the governing type
3006                 //
3007                 static Type [] allowed_types;
3008                 
3009                 public Switch (Expression e, ArrayList sects, Location l)
3010                 {
3011                         Expr = e;
3012                         Sections = sects;
3013                         loc = l;
3014                 }
3015
3016                 public bool GotDefault {
3017                         get {
3018                                 return default_section != null;
3019                         }
3020                 }
3021
3022                 public Label DefaultTarget {
3023                         get {
3024                                 return default_target;
3025                         }
3026                 }
3027
3028                 //
3029                 // Determines the governing type for a switch.  The returned
3030                 // expression might be the expression from the switch, or an
3031                 // expression that includes any potential conversions to the
3032                 // integral types or to string.
3033                 //
3034                 Expression SwitchGoverningType (EmitContext ec, Expression expr)
3035                 {
3036                         Type t = TypeManager.DropGenericTypeArguments (expr.Type);
3037
3038                         if (t == TypeManager.byte_type ||
3039                             t == TypeManager.sbyte_type ||
3040                             t == TypeManager.ushort_type ||
3041                             t == TypeManager.short_type ||
3042                             t == TypeManager.uint32_type ||
3043                             t == TypeManager.int32_type ||
3044                             t == TypeManager.uint64_type ||
3045                             t == TypeManager.int64_type ||
3046                             t == TypeManager.char_type ||
3047                             t == TypeManager.string_type ||
3048                             t == TypeManager.bool_type ||
3049                             t.IsSubclassOf (TypeManager.enum_type))
3050                                 return expr;
3051
3052                         if (allowed_types == null){
3053                                 allowed_types = new Type [] {
3054                                         TypeManager.sbyte_type,
3055                                         TypeManager.byte_type,
3056                                         TypeManager.short_type,
3057                                         TypeManager.ushort_type,
3058                                         TypeManager.int32_type,
3059                                         TypeManager.uint32_type,
3060                                         TypeManager.int64_type,
3061                                         TypeManager.uint64_type,
3062                                         TypeManager.char_type,
3063                                         TypeManager.string_type,
3064                                         TypeManager.bool_type
3065                                 };
3066                         }
3067
3068                         //
3069                         // Try to find a *user* defined implicit conversion.
3070                         //
3071                         // If there is no implicit conversion, or if there are multiple
3072                         // conversions, we have to report an error
3073                         //
3074                         Expression converted = null;
3075                         foreach (Type tt in allowed_types){
3076                                 Expression e;
3077                                 
3078                                 e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
3079                                 if (e == null)
3080                                         continue;
3081
3082                                 //
3083                                 // Ignore over-worked ImplicitUserConversions that do
3084                                 // an implicit conversion in addition to the user conversion.
3085                                 // 
3086                                 if (!(e is UserCast))
3087                                         continue;
3088
3089                                 if (converted != null){
3090                                         Report.ExtraInformation (
3091                                                 loc,
3092                                                 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
3093                                                                TypeManager.CSharpName (expr.Type)));
3094                                         return null;
3095                                 }
3096
3097                                 converted = e;
3098                         }
3099                         return converted;
3100                 }
3101
3102                 //
3103                 // Performs the basic sanity checks on the switch statement
3104                 // (looks for duplicate keys and non-constant expressions).
3105                 //
3106                 // It also returns a hashtable with the keys that we will later
3107                 // use to compute the switch tables
3108                 //
3109                 bool CheckSwitch (EmitContext ec)
3110                 {
3111                         bool error = false;
3112                         Elements = Sections.Count > 10 ? 
3113                                 (IDictionary)new Hashtable () : 
3114                                 (IDictionary)new ListDictionary ();
3115                                 
3116                         foreach (SwitchSection ss in Sections){
3117                                 foreach (SwitchLabel sl in ss.Labels){
3118                                         if (sl.Label == null){
3119                                                 if (default_section != null){
3120                                                         sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)default_section.Labels [0]);
3121                                                         error = true;
3122                                                 }
3123                                                 default_section = ss;
3124                                                 continue;
3125                                         }
3126
3127                                         if (!sl.ResolveAndReduce (ec, SwitchType, HaveUnwrap)) {
3128                                                 error = true;
3129                                                 continue;
3130                                         }
3131                                         
3132                                         object key = sl.Converted;
3133                                         try {
3134                                                 Elements.Add (key, sl);
3135                                         } catch (ArgumentException) {
3136                                                 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)Elements [key]);
3137                                                 error = true;
3138                                         }
3139                                 }
3140                         }
3141                         return !error;
3142                 }
3143
3144                 void EmitObjectInteger (ILGenerator ig, object k)
3145                 {
3146                         if (k is int)
3147                                 IntConstant.EmitInt (ig, (int) k);
3148                         else if (k is Constant) {
3149                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3150                         } 
3151                         else if (k is uint)
3152                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3153                         else if (k is long)
3154                         {
3155                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3156                                 {
3157                                         IntConstant.EmitInt (ig, (int) (long) k);
3158                                         ig.Emit (OpCodes.Conv_I8);
3159                                 }
3160                                 else
3161                                         LongConstant.EmitLong (ig, (long) k);
3162                         }
3163                         else if (k is ulong)
3164                         {
3165                                 ulong ul = (ulong) k;
3166                                 if (ul < (1L<<32))
3167                                 {
3168                                         IntConstant.EmitInt (ig, unchecked ((int) ul));
3169                                         ig.Emit (OpCodes.Conv_U8);
3170                                 }
3171                                 else
3172                                 {
3173                                         LongConstant.EmitLong (ig, unchecked ((long) ul));
3174                                 }
3175                         }
3176                         else if (k is char)
3177                                 IntConstant.EmitInt (ig, (int) ((char) k));
3178                         else if (k is sbyte)
3179                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3180                         else if (k is byte)
3181                                 IntConstant.EmitInt (ig, (int) ((byte) k));
3182                         else if (k is short)
3183                                 IntConstant.EmitInt (ig, (int) ((short) k));
3184                         else if (k is ushort)
3185                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
3186                         else if (k is bool)
3187                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3188                         else
3189                                 throw new Exception ("Unhandled case");
3190                 }
3191                 
3192                 // structure used to hold blocks of keys while calculating table switch
3193                 class KeyBlock : IComparable
3194                 {
3195                         public KeyBlock (long _nFirst)
3196                         {
3197                                 nFirst = nLast = _nFirst;
3198                         }
3199                         public long nFirst;
3200                         public long nLast;
3201                         public ArrayList rgKeys = null;
3202                         // how many items are in the bucket
3203                         public int Size = 1;
3204                         public int Length
3205                         {
3206                                 get { return (int) (nLast - nFirst + 1); }
3207                         }
3208                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3209                         {
3210                                 return kbLast.nLast - kbFirst.nFirst + 1;
3211                         }
3212                         public int CompareTo (object obj)
3213                         {
3214                                 KeyBlock kb = (KeyBlock) obj;
3215                                 int nLength = Length;
3216                                 int nLengthOther = kb.Length;
3217                                 if (nLengthOther == nLength)
3218                                         return (int) (kb.nFirst - nFirst);
3219                                 return nLength - nLengthOther;
3220                         }
3221                 }
3222
3223                 /// <summary>
3224                 /// This method emits code for a lookup-based switch statement (non-string)
3225                 /// Basically it groups the cases into blocks that are at least half full,
3226                 /// and then spits out individual lookup opcodes for each block.
3227                 /// It emits the longest blocks first, and short blocks are just
3228                 /// handled with direct compares.
3229                 /// </summary>
3230                 /// <param name="ec"></param>
3231                 /// <param name="val"></param>
3232                 /// <returns></returns>
3233                 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
3234                 {
3235                         int cElements = Elements.Count;
3236                         object [] rgKeys = new object [cElements];
3237                         Elements.Keys.CopyTo (rgKeys, 0);
3238                         Array.Sort (rgKeys);
3239
3240                         // initialize the block list with one element per key
3241                         ArrayList rgKeyBlocks = new ArrayList ();
3242                         foreach (object key in rgKeys)
3243                                 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
3244
3245                         KeyBlock kbCurr;
3246                         // iteratively merge the blocks while they are at least half full
3247                         // there's probably a really cool way to do this with a tree...
3248                         while (rgKeyBlocks.Count > 1)
3249                         {
3250                                 ArrayList rgKeyBlocksNew = new ArrayList ();
3251                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
3252                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3253                                 {
3254                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3255                                         if ((kbCurr.Size + kb.Size) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
3256                                         {
3257                                                 // merge blocks
3258                                                 kbCurr.nLast = kb.nLast;
3259                                                 kbCurr.Size += kb.Size;
3260                                         }
3261                                         else
3262                                         {
3263                                                 // start a new block
3264                                                 rgKeyBlocksNew.Add (kbCurr);
3265                                                 kbCurr = kb;
3266                                         }
3267                                 }
3268                                 rgKeyBlocksNew.Add (kbCurr);
3269                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3270                                         break;
3271                                 rgKeyBlocks = rgKeyBlocksNew;
3272                         }
3273
3274                         // initialize the key lists
3275                         foreach (KeyBlock kb in rgKeyBlocks)
3276                                 kb.rgKeys = new ArrayList ();
3277
3278                         // fill the key lists
3279                         int iBlockCurr = 0;
3280                         if (rgKeyBlocks.Count > 0) {
3281                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
3282                                 foreach (object key in rgKeys)
3283                                 {
3284                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
3285                                                 System.Convert.ToInt64 (key) > kbCurr.nLast;
3286                                         if (fNextBlock)
3287                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3288                                         kbCurr.rgKeys.Add (key);
3289                                 }
3290                         }
3291
3292                         // sort the blocks so we can tackle the largest ones first
3293                         rgKeyBlocks.Sort ();
3294
3295                         // okay now we can start...
3296                         ILGenerator ig = ec.ig;
3297                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
3298                         Label lblDefault = ig.DefineLabel ();
3299
3300                         Type typeKeys = null;
3301                         if (rgKeys.Length > 0)
3302                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
3303
3304                         Type compare_type;
3305                         
3306                         if (TypeManager.IsEnumType (SwitchType))
3307                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3308                         else
3309                                 compare_type = SwitchType;
3310                         
3311                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3312                         {
3313                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3314                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3315                                 if (kb.Length <= 2)
3316                                 {
3317                                         foreach (object key in kb.rgKeys)
3318                                         {
3319                                                 ig.Emit (OpCodes.Ldloc, val);
3320                                                 EmitObjectInteger (ig, key);
3321                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
3322                                                 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
3323                                         }
3324                                 }
3325                                 else
3326                                 {
3327                                         // TODO: if all the keys in the block are the same and there are
3328                                         //       no gaps/defaults then just use a range-check.
3329                                         if (compare_type == TypeManager.int64_type ||
3330                                                 compare_type == TypeManager.uint64_type)
3331                                         {
3332                                                 // TODO: optimize constant/I4 cases
3333
3334                                                 // check block range (could be > 2^31)
3335                                                 ig.Emit (OpCodes.Ldloc, val);
3336                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3337                                                 ig.Emit (OpCodes.Blt, lblDefault);
3338                                                 ig.Emit (OpCodes.Ldloc, val);
3339                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
3340                                                 ig.Emit (OpCodes.Bgt, lblDefault);
3341
3342                                                 // normalize range
3343                                                 ig.Emit (OpCodes.Ldloc, val);
3344                                                 if (kb.nFirst != 0)
3345                                                 {
3346                                                         EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3347                                                         ig.Emit (OpCodes.Sub);
3348                                                 }
3349                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
3350                                         }
3351                                         else
3352                                         {
3353                                                 // normalize range
3354                                                 ig.Emit (OpCodes.Ldloc, val);
3355                                                 int nFirst = (int) kb.nFirst;
3356                                                 if (nFirst > 0)
3357                                                 {
3358                                                         IntConstant.EmitInt (ig, nFirst);
3359                                                         ig.Emit (OpCodes.Sub);
3360                                                 }
3361                                                 else if (nFirst < 0)
3362                                                 {
3363                                                         IntConstant.EmitInt (ig, -nFirst);
3364                                                         ig.Emit (OpCodes.Add);
3365                                                 }
3366                                         }
3367
3368                                         // first, build the list of labels for the switch
3369                                         int iKey = 0;
3370                                         int cJumps = kb.Length;
3371                                         Label [] rgLabels = new Label [cJumps];
3372                                         for (int iJump = 0; iJump < cJumps; iJump++)
3373                                         {
3374                                                 object key = kb.rgKeys [iKey];
3375                                                 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
3376                                                 {
3377                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
3378                                                         rgLabels [iJump] = sl.GetILLabel (ec);
3379                                                         iKey++;
3380                                                 }
3381                                                 else
3382                                                         rgLabels [iJump] = lblDefault;
3383                                         }
3384                                         // emit the switch opcode
3385                                         ig.Emit (OpCodes.Switch, rgLabels);
3386                                 }
3387
3388                                 // mark the default for this block
3389                                 if (iBlock != 0)
3390                                         ig.MarkLabel (lblDefault);
3391                         }
3392
3393                         // TODO: find the default case and emit it here,
3394                         //       to prevent having to do the following jump.
3395                         //       make sure to mark other labels in the default section
3396
3397                         // the last default just goes to the end
3398                         ig.Emit (OpCodes.Br, lblDefault);
3399
3400                         // now emit the code for the sections
3401                         bool fFoundDefault = false;
3402                         bool fFoundNull = false;
3403                         foreach (SwitchSection ss in Sections)
3404                         {
3405                                 foreach (SwitchLabel sl in ss.Labels)
3406                                         if (sl.Converted == SwitchLabel.NullStringCase)
3407                                                 fFoundNull = true;
3408                         }
3409
3410                         foreach (SwitchSection ss in Sections)
3411                         {
3412                                 foreach (SwitchLabel sl in ss.Labels)
3413                                 {
3414                                         ig.MarkLabel (sl.GetILLabel (ec));
3415                                         ig.MarkLabel (sl.GetILLabelCode (ec));
3416                                         if (sl.Converted == SwitchLabel.NullStringCase)
3417                                                 ig.MarkLabel (null_target);
3418                                         else if (sl.Label == null) {
3419                                                 ig.MarkLabel (lblDefault);
3420                                                 fFoundDefault = true;
3421                                                 if (!fFoundNull)
3422                                                         ig.MarkLabel (null_target);
3423                                         }
3424                                 }
3425                                 ss.Block.Emit (ec);
3426                         }
3427                         
3428                         if (!fFoundDefault) {
3429                                 ig.MarkLabel (lblDefault);
3430                                 if (HaveUnwrap && !fFoundNull) {
3431                                         ig.MarkLabel (null_target);
3432                                 }
3433                         }
3434                         
3435                         ig.MarkLabel (lblEnd);
3436                 }
3437                 //
3438                 // This simple emit switch works, but does not take advantage of the
3439                 // `switch' opcode. 
3440                 // TODO: remove non-string logic from here
3441                 // TODO: binary search strings?
3442                 //
3443                 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3444                 {
3445                         ILGenerator ig = ec.ig;
3446                         Label end_of_switch = ig.DefineLabel ();
3447                         Label next_test = ig.DefineLabel ();
3448                         bool first_test = true;
3449                         bool pending_goto_end = false;
3450                         bool null_marked = false;
3451                         bool null_found;
3452                         int section_count = Sections.Count;
3453
3454                         // TODO: implement switch optimization for string by using Hashtable
3455                         //if (SwitchType == TypeManager.string_type && section_count > 7)
3456                         //      Console.WriteLine ("Switch optimization possible " + loc);
3457
3458                         ig.Emit (OpCodes.Ldloc, val);
3459                         
3460                         if (Elements.Contains (SwitchLabel.NullStringCase)){
3461                                 ig.Emit (OpCodes.Brfalse, null_target);
3462                         } else
3463                                 ig.Emit (OpCodes.Brfalse, default_target);
3464                         
3465                         ig.Emit (OpCodes.Ldloc, val);
3466                         ig.Emit (OpCodes.Call, TypeManager.string_isinterned_string);
3467                         ig.Emit (OpCodes.Stloc, val);
3468
3469                         for (int section = 0; section < section_count; section++){
3470                                 SwitchSection ss = (SwitchSection) Sections [section];
3471
3472                                 if (ss == default_section)
3473                                         continue;
3474
3475                                 Label sec_begin = ig.DefineLabel ();
3476
3477                                 ig.Emit (OpCodes.Nop);
3478
3479                                 if (pending_goto_end)
3480                                         ig.Emit (OpCodes.Br, end_of_switch);
3481
3482                                 int label_count = ss.Labels.Count;
3483                                 null_found = false;
3484                                 for (int label = 0; label < label_count; label++){
3485                                         SwitchLabel sl = (SwitchLabel) ss.Labels [label];
3486                                         ig.MarkLabel (sl.GetILLabel (ec));
3487                                         
3488                                         if (!first_test){
3489                                                 ig.MarkLabel (next_test);
3490                                                 next_test = ig.DefineLabel ();
3491                                         }
3492                                         //
3493                                         // If we are the default target
3494                                         //
3495                                         if (sl.Label != null){
3496                                                 object lit = sl.Converted;
3497
3498                                                 if (lit == SwitchLabel.NullStringCase){
3499                                                         null_found = true;
3500                                                         if (label + 1 == label_count)
3501                                                                 ig.Emit (OpCodes.Br, next_test);
3502                                                         continue;
3503                                                 }
3504                                                 
3505                                                 ig.Emit (OpCodes.Ldloc, val);
3506                                                 ig.Emit (OpCodes.Ldstr, (string)lit);
3507                                                 if (label_count == 1)
3508                                                         ig.Emit (OpCodes.Bne_Un, next_test);
3509                                                 else {
3510                                                         if (label+1 == label_count)
3511                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
3512                                                         else
3513                                                                 ig.Emit (OpCodes.Beq, sec_begin);
3514                                                 }
3515                                         }
3516                                 }
3517                                 if (null_found) {
3518                                         ig.MarkLabel (null_target);
3519                                         null_marked = true;
3520                                 }
3521                                 ig.MarkLabel (sec_begin);
3522                                 foreach (SwitchLabel sl in ss.Labels)
3523                                         ig.MarkLabel (sl.GetILLabelCode (ec));
3524
3525                                 ss.Block.Emit (ec);
3526                                 pending_goto_end = !ss.Block.HasRet;
3527                                 first_test = false;
3528                         }
3529                         ig.MarkLabel (next_test);
3530                         ig.MarkLabel (default_target);
3531                         if (!null_marked)
3532                                 ig.MarkLabel (null_target);
3533                         if (default_section != null)
3534                                 default_section.Block.Emit (ec);
3535                         ig.MarkLabel (end_of_switch);
3536                 }
3537
3538                 SwitchSection FindSection (SwitchLabel label)
3539                 {
3540                         foreach (SwitchSection ss in Sections){
3541                                 foreach (SwitchLabel sl in ss.Labels){
3542                                         if (label == sl)
3543                                                 return ss;
3544                                 }
3545                         }
3546
3547                         return null;
3548                 }
3549
3550                 public override bool Resolve (EmitContext ec)
3551                 {
3552                         Expr = Expr.Resolve (ec);
3553                         if (Expr == null)
3554                                 return false;
3555
3556                         new_expr = SwitchGoverningType (ec, Expr);
3557
3558 #if GMCS_SOURCE
3559                         if ((new_expr == null) && TypeManager.IsNullableType (Expr.Type)) {
3560                                 unwrap = Nullable.Unwrap.Create (Expr, ec);
3561                                 if (unwrap == null)
3562                                         return false;
3563
3564                                 new_expr = SwitchGoverningType (ec, unwrap);
3565                         }
3566 #endif
3567
3568                         if (new_expr == null){
3569                                 Report.Error (151, loc, "A value of an integral type or string expected for switch");
3570                                 return false;
3571                         }
3572
3573                         // Validate switch.
3574                         SwitchType = new_expr.Type;
3575
3576                         if (RootContext.Version == LanguageVersion.ISO_1 && SwitchType == TypeManager.bool_type) {
3577                                 Report.FeatureIsNotAvailable (loc, "switch expression of boolean type");
3578                                 return false;
3579                         }
3580
3581                         if (!CheckSwitch (ec))
3582                                 return false;
3583
3584                         if (HaveUnwrap)
3585                                 Elements.Remove (SwitchLabel.NullStringCase);
3586
3587                         Switch old_switch = ec.Switch;
3588                         ec.Switch = this;
3589                         ec.Switch.SwitchType = SwitchType;
3590
3591                         Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3592                         ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3593
3594                         is_constant = new_expr is Constant;
3595                         if (is_constant) {
3596                                 object key = ((Constant) new_expr).GetValue ();
3597                                 SwitchLabel label = (SwitchLabel) Elements [key];
3598
3599                                 constant_section = FindSection (label);
3600                                 if (constant_section == null)
3601                                         constant_section = default_section;
3602                         }
3603
3604                         bool first = true;
3605                         foreach (SwitchSection ss in Sections){
3606                                 if (!first)
3607                                         ec.CurrentBranching.CreateSibling (
3608                                                 null, FlowBranching.SiblingType.SwitchSection);
3609                                 else
3610                                         first = false;
3611
3612                                 if (is_constant && (ss != constant_section)) {
3613                                         // If we're a constant switch, we're only emitting
3614                                         // one single section - mark all the others as
3615                                         // unreachable.
3616                                         ec.CurrentBranching.CurrentUsageVector.Goto ();
3617                                         if (!ss.Block.ResolveUnreachable (ec, true))
3618                                                 return false;
3619                                 } else {
3620                                         if (!ss.Block.Resolve (ec))
3621                                                 return false;
3622                                 }
3623                         }
3624
3625                         if (default_section == null)
3626                                 ec.CurrentBranching.CreateSibling (
3627                                         null, FlowBranching.SiblingType.SwitchSection);
3628
3629                         ec.EndFlowBranching ();
3630                         ec.Switch = old_switch;
3631
3632                         Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching);
3633
3634                         return true;
3635                 }
3636                 
3637                 protected override void DoEmit (EmitContext ec)
3638                 {
3639                         ILGenerator ig = ec.ig;
3640
3641                         default_target = ig.DefineLabel ();
3642                         null_target = ig.DefineLabel ();
3643
3644                         // Store variable for comparission purposes
3645                         LocalBuilder value;
3646                         if (HaveUnwrap) {
3647                                 value = ig.DeclareLocal (SwitchType);
3648 #if GMCS_SOURCE
3649                                 unwrap.EmitCheck (ec);
3650                                 ig.Emit (OpCodes.Brfalse, null_target);
3651                                 new_expr.Emit (ec);
3652                                 ig.Emit (OpCodes.Stloc, value);
3653 #endif
3654                         } else if (!is_constant) {
3655                                 value = ig.DeclareLocal (SwitchType);
3656                                 new_expr.Emit (ec);
3657                                 ig.Emit (OpCodes.Stloc, value);
3658                         } else
3659                                 value = null;
3660
3661                         //
3662                         // Setup the codegen context
3663                         //
3664                         Label old_end = ec.LoopEnd;
3665                         Switch old_switch = ec.Switch;
3666                         
3667                         ec.LoopEnd = ig.DefineLabel ();
3668                         ec.Switch = this;
3669
3670                         // Emit Code.
3671                         if (is_constant) {
3672                                 if (constant_section != null)
3673                                         constant_section.Block.Emit (ec);
3674                         } else if (SwitchType == TypeManager.string_type)
3675                                 SimpleSwitchEmit (ec, value);
3676                         else
3677                                 TableSwitchEmit (ec, value);
3678
3679                         // Restore context state. 
3680                         ig.MarkLabel (ec.LoopEnd);
3681
3682                         //
3683                         // Restore the previous context
3684                         //
3685                         ec.LoopEnd = old_end;
3686                         ec.Switch = old_switch;
3687                 }
3688
3689                 protected override void CloneTo (CloneContext clonectx, Statement t)
3690                 {
3691                         Switch target = (Switch) t;
3692
3693                         target.Expr = Expr.Clone (clonectx);
3694                         target.Sections = new ArrayList ();
3695                         foreach (SwitchSection ss in Sections){
3696                                 target.Sections.Add (ss.Clone (clonectx));
3697                         }
3698                 }
3699         }
3700
3701         public abstract class ExceptionStatement : Statement
3702         {
3703                 public abstract void EmitFinally (EmitContext ec);
3704
3705                 protected bool emit_finally = true;
3706                 ArrayList parent_vectors;
3707
3708                 protected void DoEmitFinally (EmitContext ec)
3709                 {
3710                         if (emit_finally)
3711                                 ec.ig.BeginFinallyBlock ();
3712                         else if (ec.InIterator)
3713                                 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3714                         EmitFinally (ec);
3715                 }
3716
3717                 protected void ResolveFinally (FlowBranchingException branching)
3718                 {
3719                         emit_finally = branching.EmitFinally;
3720                         if (!emit_finally)
3721                                 branching.Parent.StealFinallyClauses (ref parent_vectors);
3722                 }
3723         }
3724
3725         public class Lock : ExceptionStatement {
3726                 Expression expr;
3727                 public Statement Statement;
3728                 TemporaryVariable temp;
3729                         
3730                 public Lock (Expression expr, Statement stmt, Location l)
3731                 {
3732                         this.expr = expr;
3733                         Statement = stmt;
3734                         loc = l;
3735                 }
3736
3737                 public override bool Resolve (EmitContext ec)
3738                 {
3739                         expr = expr.Resolve (ec);
3740                         if (expr == null)
3741                                 return false;
3742
3743                         if (expr.Type.IsValueType){
3744                                 Report.Error (185, loc,
3745                                               "`{0}' is not a reference type as required by the lock statement",
3746                                               TypeManager.CSharpName (expr.Type));
3747                                 return false;
3748                         }
3749
3750                         FlowBranchingException branching = ec.StartFlowBranching (this);
3751                         bool ok = Statement.Resolve (ec);
3752
3753                         ResolveFinally (branching);
3754
3755                         ec.EndFlowBranching ();
3756
3757                         // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
3758                         // So, ensure there's some IL code after the finally block.
3759                         ec.NeedReturnLabel ();
3760
3761                         // Avoid creating libraries that reference the internal
3762                         // mcs NullType:
3763                         Type t = expr.Type;
3764                         if (t == TypeManager.null_type)
3765                                 t = TypeManager.object_type;
3766                         
3767                         temp = new TemporaryVariable (t, loc);
3768                         temp.Resolve (ec);
3769                         
3770                         return ok;
3771                 }
3772                 
3773                 protected override void DoEmit (EmitContext ec)
3774                 {
3775                         ILGenerator ig = ec.ig;
3776
3777                         temp.Store (ec, expr);
3778                         temp.Emit (ec);
3779                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3780
3781                         // try
3782                         if (emit_finally)
3783                                 ig.BeginExceptionBlock ();
3784                         Statement.Emit (ec);
3785                         
3786                         // finally
3787                         DoEmitFinally (ec);
3788                         if (emit_finally)
3789                                 ig.EndExceptionBlock ();
3790                 }
3791
3792                 public override void EmitFinally (EmitContext ec)
3793                 {
3794                         temp.Emit (ec);
3795                         ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3796                 }
3797                 
3798                 protected override void CloneTo (CloneContext clonectx, Statement t)
3799                 {
3800                         Lock target = (Lock) t;
3801
3802                         target.expr = expr.Clone (clonectx);
3803                         target.Statement = Statement.Clone (clonectx);
3804                 }
3805         }
3806
3807         public class Unchecked : Statement {
3808                 public Block Block;
3809                 
3810                 public Unchecked (Block b)
3811                 {
3812                         Block = b;
3813                         b.Unchecked = true;
3814                 }
3815
3816                 public override bool Resolve (EmitContext ec)
3817                 {
3818                         using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3819                                 return Block.Resolve (ec);
3820                 }
3821                 
3822                 protected override void DoEmit (EmitContext ec)
3823                 {
3824                         using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3825                                 Block.Emit (ec);
3826                 }
3827
3828                 protected override void CloneTo (CloneContext clonectx, Statement t)
3829                 {
3830                         Unchecked target = (Unchecked) t;
3831
3832                         target.Block = clonectx.LookupBlock (Block);
3833                 }
3834         }
3835
3836         public class Checked : Statement {
3837                 public Block Block;
3838                 
3839                 public Checked (Block b)
3840                 {
3841                         Block = b;
3842                         b.Unchecked = false;
3843                 }
3844
3845                 public override bool Resolve (EmitContext ec)
3846                 {
3847                         using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3848                                 return Block.Resolve (ec);
3849                 }
3850
3851                 protected override void DoEmit (EmitContext ec)
3852                 {
3853                         using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3854                                 Block.Emit (ec);
3855                 }
3856
3857                 protected override void CloneTo (CloneContext clonectx, Statement t)
3858                 {
3859                         Checked target = (Checked) t;
3860
3861                         target.Block = clonectx.LookupBlock (Block);
3862                 }
3863         }
3864
3865         public class Unsafe : Statement {
3866                 public Block Block;
3867
3868                 public Unsafe (Block b)
3869                 {
3870                         Block = b;
3871                         Block.Unsafe = true;
3872                 }
3873
3874                 public override bool Resolve (EmitContext ec)
3875                 {
3876                         using (ec.With (EmitContext.Flags.InUnsafe, true))
3877                                 return Block.Resolve (ec);
3878                 }
3879                 
3880                 protected override void DoEmit (EmitContext ec)
3881                 {
3882                         using (ec.With (EmitContext.Flags.InUnsafe, true))
3883                                 Block.Emit (ec);
3884                 }
3885                 protected override void CloneTo (CloneContext clonectx, Statement t)
3886                 {
3887                         Unsafe target = (Unsafe) t;
3888
3889                         target.Block = clonectx.LookupBlock (Block);
3890                 }
3891         }
3892
3893         // 
3894         // Fixed statement
3895         //
3896         public class Fixed : Statement {
3897                 Expression type;
3898                 ArrayList declarators;
3899                 Statement statement;
3900                 Type expr_type;
3901                 Emitter[] data;
3902                 bool has_ret;
3903
3904                 abstract class Emitter
3905                 {
3906                         protected LocalInfo vi;
3907                         protected Expression converted;
3908
3909                         protected Emitter (Expression expr, LocalInfo li)
3910                         {
3911                                 converted = expr;
3912                                 vi = li;
3913                         }
3914
3915                         public abstract void Emit (EmitContext ec);
3916                         public abstract void EmitExit (EmitContext ec);
3917                 }
3918
3919                 class ExpressionEmitter : Emitter {
3920                         public ExpressionEmitter (Expression converted, LocalInfo li) :
3921                                 base (converted, li)
3922                         {
3923                         }
3924
3925                         public override void Emit (EmitContext ec) {
3926                                 //
3927                                 // Store pointer in pinned location
3928                                 //
3929                                 converted.Emit (ec);
3930                                 vi.Variable.EmitAssign (ec);
3931                         }
3932
3933                         public override void EmitExit (EmitContext ec)
3934                         {
3935                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
3936                                 ec.ig.Emit (OpCodes.Conv_U);
3937                                 vi.Variable.EmitAssign (ec);
3938                         }
3939                 }
3940
3941                 class StringEmitter : Emitter {
3942                         LocalBuilder pinned_string;
3943                         Location loc;
3944
3945                         public StringEmitter (Expression expr, LocalInfo li, Location loc):
3946                                 base (expr, li)
3947                         {
3948                                 this.loc = loc;
3949                         }
3950
3951                         public override void Emit (EmitContext ec)
3952                         {
3953                                 ILGenerator ig = ec.ig;
3954                                 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3955                                         
3956                                 converted.Emit (ec);
3957                                 ig.Emit (OpCodes.Stloc, pinned_string);
3958
3959                                 Expression sptr = new StringPtr (pinned_string, loc);
3960                                 converted = Convert.ImplicitConversionRequired (
3961                                         ec, sptr, vi.VariableType, loc);
3962                                         
3963                                 if (converted == null)
3964                                         return;
3965
3966                                 converted.Emit (ec);
3967                                 vi.Variable.EmitAssign (ec);
3968                         }
3969
3970                         public override void EmitExit (EmitContext ec)
3971                         {
3972                                 ec.ig.Emit (OpCodes.Ldnull);
3973                                 ec.ig.Emit (OpCodes.Stloc, pinned_string);
3974                         }
3975                 }
3976
3977                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3978                 {
3979                         this.type = type;
3980                         declarators = decls;
3981                         statement = stmt;
3982                         loc = l;
3983                 }
3984
3985                 public Statement Statement {
3986                         get { return statement; }
3987                 }
3988
3989                 public override bool Resolve (EmitContext ec)
3990                 {
3991                         if (!ec.InUnsafe){
3992                                 Expression.UnsafeError (loc);
3993                                 return false;
3994                         }
3995                         
3996                         TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3997                         if (texpr == null)
3998                                 return false;
3999
4000                         expr_type = texpr.Type;
4001
4002                         data = new Emitter [declarators.Count];
4003
4004                         if (!expr_type.IsPointer){
4005                                 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
4006                                 return false;
4007                         }
4008                         
4009                         int i = 0;
4010                         foreach (Pair p in declarators){
4011                                 LocalInfo vi = (LocalInfo) p.First;
4012                                 Expression e = (Expression) p.Second;
4013                                 
4014                                 vi.VariableInfo.SetAssigned (ec);
4015                                 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
4016
4017                                 //
4018                                 // The rules for the possible declarators are pretty wise,
4019                                 // but the production on the grammar is more concise.
4020                                 //
4021                                 // So we have to enforce these rules here.
4022                                 //
4023                                 // We do not resolve before doing the case 1 test,
4024                                 // because the grammar is explicit in that the token &
4025                                 // is present, so we need to test for this particular case.
4026                                 //
4027
4028                                 if (e is Cast){
4029                                         Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
4030                                         return false;
4031                                 }
4032                                 
4033                                 //
4034                                 // Case 1: & object.
4035                                 //
4036                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4037                                         Expression child = ((Unary) e).Expr;
4038
4039                                         if (child is ParameterReference || child is LocalVariableReference){
4040                                                 Report.Error (
4041                                                         213, loc, 
4042                                                         "No need to use fixed statement for parameters or " +
4043                                                         "local variable declarations (address is already " +
4044                                                         "fixed)");
4045                                                 return false;
4046                                         }
4047
4048                                         ec.InFixedInitializer = true;
4049                                         e = e.Resolve (ec);
4050                                         ec.InFixedInitializer = false;
4051                                         if (e == null)
4052                                                 return false;
4053
4054                                         child = ((Unary) e).Expr;
4055                                         
4056                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
4057                                                 return false;
4058
4059                                         if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
4060                                                 e.Error_ValueCannotBeConverted (ec, e.Location, expr_type, false);
4061                                                 return false;
4062                                         }
4063
4064                                         data [i] = new ExpressionEmitter (e, vi);
4065                                         i++;
4066
4067                                         continue;
4068                                 }
4069
4070                                 ec.InFixedInitializer = true;
4071                                 e = e.Resolve (ec);
4072                                 ec.InFixedInitializer = false;
4073                                 if (e == null)
4074                                         return false;
4075
4076                                 //
4077                                 // Case 2: Array
4078                                 //
4079                                 if (e.Type.IsArray){
4080                                         Type array_type = TypeManager.GetElementType (e.Type);
4081                                         
4082                                         //
4083                                         // Provided that array_type is unmanaged,
4084                                         //
4085                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
4086                                                 return false;
4087
4088                                         //
4089                                         // and T* is implicitly convertible to the
4090                                         // pointer type given in the fixed statement.
4091                                         //
4092                                         ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
4093                                         
4094                                         Expression converted = Convert.ImplicitConversionRequired (
4095                                                 ec, array_ptr, vi.VariableType, loc);
4096                                         if (converted == null)
4097                                                 return false;
4098                                         
4099                                         //
4100                                         // fixed (T* e_ptr = (e == null || e.Length == 0) ? null : converted [0])
4101                                         //
4102                                         converted = new Conditional (new Binary (Binary.Operator.LogicalOr,
4103                                                 new Binary (Binary.Operator.Equality, e, new NullConstant (loc)),
4104                                                 new Binary (Binary.Operator.Equality, new MemberAccess (e, "Length"), new IntConstant (0, loc))),
4105                                                         NullPointer.Null,
4106                                                         converted);
4107
4108                                         converted = converted.Resolve (ec);                                     
4109
4110                                         data [i] = new ExpressionEmitter (converted, vi);
4111                                         i++;
4112
4113                                         continue;
4114                                 }
4115
4116                                 //
4117                                 // Case 3: string
4118                                 //
4119                                 if (e.Type == TypeManager.string_type){
4120                                         data [i] = new StringEmitter (e, vi, loc);
4121                                         i++;
4122                                         continue;
4123                                 }
4124
4125                                 // Case 4: fixed buffer
4126                                 FixedBufferPtr fixed_buffer_ptr = e as FixedBufferPtr;
4127                                 if (fixed_buffer_ptr != null) {
4128                                         data [i++] = new ExpressionEmitter (fixed_buffer_ptr, vi);
4129                                         continue;
4130                                 }
4131
4132                                 //
4133                                 // For other cases, flag a `this is already fixed expression'
4134                                 //
4135                                 if (e is LocalVariableReference || e is ParameterReference ||
4136                                     Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
4137                                     
4138                                         Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
4139                                         return false;
4140                                 }
4141
4142                                 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
4143                                 return false;
4144                         }
4145
4146                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
4147                         bool ok = statement.Resolve (ec);
4148                         bool flow_unreachable = ec.EndFlowBranching ();
4149                         has_ret = flow_unreachable;
4150
4151                         return ok;
4152                 }
4153                 
4154                 protected override void DoEmit (EmitContext ec)
4155                 {
4156                         for (int i = 0; i < data.Length; i++) {
4157                                 data [i].Emit (ec);
4158                         }
4159
4160                         statement.Emit (ec);
4161
4162                         if (has_ret)
4163                                 return;
4164
4165                         //
4166                         // Clear the pinned variable
4167                         //
4168                         for (int i = 0; i < data.Length; i++) {
4169                                 data [i].EmitExit (ec);
4170                         }
4171                 }
4172
4173                 protected override void CloneTo (CloneContext clonectx, Statement t)
4174                 {
4175                         Fixed target = (Fixed) t;
4176
4177                         target.type = type.Clone (clonectx);
4178                         target.declarators = new ArrayList (declarators.Count);
4179                         foreach (Pair p in declarators) {
4180                                 LocalInfo vi = (LocalInfo) p.First;
4181                                 Expression e = (Expression) p.Second;
4182
4183                                 target.declarators.Add (
4184                                         new Pair (clonectx.LookupVariable (vi), e.Clone (clonectx)));                           
4185                         }
4186                         
4187                         target.statement = statement.Clone (clonectx);
4188                 }
4189         }
4190         
4191         public class Catch : Statement {
4192                 public readonly string Name;
4193                 public Block  Block;
4194                 public Block  VarBlock;
4195
4196                 Expression type_expr;
4197                 Type type;
4198                 
4199                 public Catch (Expression type, string name, Block block, Block var_block, Location l)
4200                 {
4201                         type_expr = type;
4202                         Name = name;
4203                         Block = block;
4204                         VarBlock = var_block;
4205                         loc = l;
4206                 }
4207
4208                 public Type CatchType {
4209                         get {
4210                                 return type;
4211                         }
4212                 }
4213
4214                 public bool IsGeneral {
4215                         get {
4216                                 return type_expr == null;
4217                         }
4218                 }
4219
4220                 protected override void DoEmit(EmitContext ec)
4221                 {
4222                         ILGenerator ig = ec.ig;
4223
4224                         if (CatchType != null)
4225                                 ig.BeginCatchBlock (CatchType);
4226                         else
4227                                 ig.BeginCatchBlock (TypeManager.object_type);
4228
4229                         if (VarBlock != null)
4230                                 VarBlock.Emit (ec);
4231
4232                         if (Name != null) {
4233                                 LocalInfo vi = Block.GetLocalInfo (Name);
4234                                 if (vi == null)
4235                                         throw new Exception ("Variable does not exist in this block");
4236
4237                                 if (vi.Variable.NeedsTemporary) {
4238                                         LocalBuilder e = ig.DeclareLocal (vi.VariableType);
4239                                         ig.Emit (OpCodes.Stloc, e);
4240
4241                                         vi.Variable.EmitInstance (ec);
4242                                         ig.Emit (OpCodes.Ldloc, e);
4243                                         vi.Variable.EmitAssign (ec);
4244                                 } else
4245                                         vi.Variable.EmitAssign (ec);
4246                         } else
4247                                 ig.Emit (OpCodes.Pop);
4248
4249                         Block.Emit (ec);
4250                 }
4251
4252                 public override bool Resolve (EmitContext ec)
4253                 {
4254                         using (ec.With (EmitContext.Flags.InCatch, true)) {
4255                                 if (type_expr != null) {
4256                                         TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
4257                                         if (te == null)
4258                                                 return false;
4259
4260                                         type = te.Type;
4261
4262                                         if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4263                                                 Error (155, "The type caught or thrown must be derived from System.Exception");
4264                                                 return false;
4265                                         }
4266                                 } else
4267                                         type = null;
4268
4269                                 if (!Block.Resolve (ec))
4270                                         return false;
4271
4272                                 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
4273                                 // emit the "unused variable" warnings.
4274                                 if (VarBlock != null)
4275                                         return VarBlock.Resolve (ec);
4276
4277                                 return true;
4278                         }
4279                 }
4280
4281                 protected override void CloneTo (CloneContext clonectx, Statement t)
4282                 {
4283                         Catch target = (Catch) t;
4284
4285                         if (type_expr != null)
4286                                 target.type_expr = type_expr.Clone (clonectx);
4287                         if (VarBlock != null)
4288                                 target.VarBlock = clonectx.LookupBlock (VarBlock);                      
4289                         target.Block = clonectx.LookupBlock (Block);
4290                 }
4291         }
4292
4293         public class Try : ExceptionStatement {
4294                 public Block Fini, Block;
4295                 public ArrayList Specific;
4296                 public Catch General;
4297
4298                 bool need_exc_block;
4299                 
4300                 //
4301                 // specific, general and fini might all be null.
4302                 //
4303                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4304                 {
4305                         if (specific == null && general == null){
4306                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4307                         }
4308                         
4309                         this.Block = block;
4310                         this.Specific = specific;
4311                         this.General = general;
4312                         this.Fini = fini;
4313                         loc = l;
4314                 }
4315
4316                 public override bool Resolve (EmitContext ec)
4317                 {
4318                         bool ok = true;
4319                         
4320                         FlowBranchingException branching = ec.StartFlowBranching (this);
4321
4322                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4323
4324                         if (!Block.Resolve (ec))
4325                                 ok = false;
4326
4327                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4328
4329                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
4330
4331                         Type[] prevCatches = new Type [Specific.Count];
4332                         int last_index = 0;
4333                         foreach (Catch c in Specific){
4334                                 ec.CurrentBranching.CreateSibling (
4335                                         c.Block, FlowBranching.SiblingType.Catch);
4336
4337                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4338
4339                                 if (c.Name != null) {
4340                                         LocalInfo vi = c.Block.GetLocalInfo (c.Name);
4341                                         if (vi == null)
4342                                                 throw new Exception ();
4343
4344                                         vi.VariableInfo = null;
4345                                 }
4346
4347                                 if (!c.Resolve (ec))
4348                                         return false;
4349
4350                                 Type resolvedType = c.CatchType;
4351                                 for (int ii = 0; ii < last_index; ++ii) {
4352                                         if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
4353                                                 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
4354                                                 return false;
4355                                         }
4356                                 }
4357
4358                                 prevCatches [last_index++] = resolvedType;
4359                                 need_exc_block = true;
4360                         }
4361
4362                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4363
4364                         if (General != null){
4365                                 if (CodeGen.Assembly.WrapNonExceptionThrows) {
4366                                         foreach (Catch c in Specific){
4367                                                 if (c.CatchType == TypeManager.exception_type) {
4368                                                         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'");
4369                                                 }
4370                                         }
4371                                 }
4372
4373                                 ec.CurrentBranching.CreateSibling (
4374                                         General.Block, FlowBranching.SiblingType.Catch);
4375
4376                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4377
4378                                 if (!General.Resolve (ec))
4379                                         ok = false;
4380
4381                                 need_exc_block = true;
4382                         }
4383
4384                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4385
4386                         if (Fini != null) {
4387                                 if (ok)
4388                                         ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
4389
4390                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4391                                 using (ec.With (EmitContext.Flags.InFinally, true)) {
4392                                         if (!Fini.Resolve (ec))
4393                                                 ok = false;
4394                                 }
4395
4396                                 if (!ec.InIterator)
4397                                         need_exc_block = true;
4398                         }
4399
4400                         if (ec.InIterator) {
4401                                 ResolveFinally (branching);
4402                                 need_exc_block |= emit_finally;
4403                         } else
4404                                 emit_finally = Fini != null;
4405
4406                         ec.EndFlowBranching ();
4407
4408                         // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4409                         // So, ensure there's some IL code after the finally block.
4410                         ec.NeedReturnLabel ();
4411
4412                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4413
4414                         Report.Debug (1, "END OF TRY", ec.CurrentBranching, vector, f_vector);
4415
4416                         return ok;
4417                 }
4418                 
4419                 protected override void DoEmit (EmitContext ec)
4420                 {
4421                         ILGenerator ig = ec.ig;
4422
4423                         if (need_exc_block)
4424                                 ig.BeginExceptionBlock ();
4425                         Block.Emit (ec);
4426
4427                         foreach (Catch c in Specific)
4428                                 c.Emit (ec);
4429
4430                         if (General != null)
4431                                 General.Emit (ec);
4432
4433                         DoEmitFinally (ec);
4434                         if (need_exc_block)
4435                                 ig.EndExceptionBlock ();
4436                 }
4437
4438                 public override void EmitFinally (EmitContext ec)
4439                 {
4440                         if (Fini != null)
4441                                 Fini.Emit (ec);
4442                 }
4443
4444                 public bool HasCatch
4445                 {
4446                         get {
4447                                 return General != null || Specific.Count > 0;
4448                         }
4449                 }
4450
4451                 protected override void CloneTo (CloneContext clonectx, Statement t)
4452                 {
4453                         Try target = (Try) t;
4454
4455                         target.Block = clonectx.LookupBlock (Block);
4456                         if (Fini != null)
4457                                 target.Fini = clonectx.LookupBlock (Fini);
4458                         if (General != null)
4459                                 target.General = (Catch) General.Clone (clonectx);
4460                         if (Specific != null){
4461                                 target.Specific = new ArrayList ();
4462                                 foreach (Catch c in Specific)
4463                                         target.Specific.Add (c.Clone (clonectx));
4464                         }
4465                 }
4466         }
4467
4468         public class Using : ExceptionStatement {
4469                 object expression_or_block;
4470                 public Statement Statement;
4471                 ArrayList var_list;
4472                 Expression expr;
4473                 Type expr_type;
4474                 Expression [] resolved_vars;
4475                 Expression [] converted_vars;
4476                 Expression [] assign;
4477                 TemporaryVariable local_copy;
4478                 
4479                 public Using (object expression_or_block, Statement stmt, Location l)
4480                 {
4481                         this.expression_or_block = expression_or_block;
4482                         Statement = stmt;
4483                         loc = l;
4484                 }
4485
4486                 //
4487                 // Resolves for the case of using using a local variable declaration.
4488                 //
4489                 bool ResolveLocalVariableDecls (EmitContext ec)
4490                 {
4491                         resolved_vars = new Expression[var_list.Count];
4492                         assign = new Expression [var_list.Count];
4493                         converted_vars = new Expression[var_list.Count];
4494
4495                         for (int i = 0; i < assign.Length; ++i) {
4496                                 DictionaryEntry e = (DictionaryEntry) var_list [i];
4497                                 Expression var = (Expression) e.Key;
4498                                 Expression new_expr = (Expression) e.Value;
4499
4500                                 Expression a = new Assign (var, new_expr, loc);
4501                                 a = a.Resolve (ec);
4502                                 if (a == null)
4503                                         return false;
4504
4505                                 resolved_vars [i] = var;
4506                                 assign [i] = a;
4507
4508                                 if (TypeManager.ImplementsInterface (a.Type, TypeManager.idisposable_type)) {
4509                                         converted_vars [i] = var;
4510                                         continue;
4511                                 }
4512
4513                                 a = Convert.ImplicitConversionStandard (ec, a, TypeManager.idisposable_type, var.Location);
4514                                 if (a == null) {
4515                                         Error_IsNotConvertibleToIDisposable (var);
4516                                         return false;
4517                                 }
4518
4519                                 converted_vars [i] = a;
4520                         }
4521
4522                         return true;
4523                 }
4524
4525                 static void Error_IsNotConvertibleToIDisposable (Expression expr)
4526                 {
4527                         Report.SymbolRelatedToPreviousError (expr.Type);
4528                         Report.Error (1674, expr.Location, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
4529                                 expr.GetSignatureForError ());
4530                 }
4531
4532                 bool ResolveExpression (EmitContext ec)
4533                 {
4534                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4535                                 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
4536                                         Error_IsNotConvertibleToIDisposable (expr);
4537                                         return false;
4538                                 }
4539                         }
4540
4541                         local_copy = new TemporaryVariable (expr_type, loc);
4542                         local_copy.Resolve (ec);
4543
4544                         return true;
4545                 }
4546                 
4547                 //
4548                 // Emits the code for the case of using using a local variable declaration.
4549                 //
4550                 void EmitLocalVariableDecls (EmitContext ec)
4551                 {
4552                         ILGenerator ig = ec.ig;
4553                         int i = 0;
4554
4555                         for (i = 0; i < assign.Length; i++) {
4556                                 ExpressionStatement es = assign [i] as ExpressionStatement;
4557
4558                                 if (es != null)
4559                                         es.EmitStatement (ec);
4560                                 else {
4561                                         assign [i].Emit (ec);
4562                                         ig.Emit (OpCodes.Pop);
4563                                 }
4564
4565                                 if (emit_finally)
4566                                         ig.BeginExceptionBlock ();
4567                         }
4568                         Statement.Emit (ec);
4569
4570                         var_list.Reverse ();
4571
4572                         DoEmitFinally (ec);
4573                 }
4574
4575                 void EmitLocalVariableDeclFinally (EmitContext ec)
4576                 {
4577                         ILGenerator ig = ec.ig;
4578
4579                         int i = assign.Length;
4580                         for (int ii = 0; ii < var_list.Count; ++ii){
4581                                 Expression var = resolved_vars [--i];
4582                                 Label skip = ig.DefineLabel ();
4583
4584                                 if (emit_finally)
4585                                         ig.BeginFinallyBlock ();
4586                                 
4587                                 if (!var.Type.IsValueType) {
4588                                         var.Emit (ec);
4589                                         ig.Emit (OpCodes.Brfalse, skip);
4590                                         converted_vars [i].Emit (ec);
4591                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4592                                 } else {
4593                                         Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4594
4595                                         if (!(ml is MethodGroupExpr)) {
4596                                                 var.Emit (ec);
4597                                                 ig.Emit (OpCodes.Box, var.Type);
4598                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4599                                         } else {
4600                                                 MethodInfo mi = null;
4601
4602                                                 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4603                                                         if (TypeManager.GetParameterData (mk).Count == 0) {
4604                                                                 mi = mk;
4605                                                                 break;
4606                                                         }
4607                                                 }
4608
4609                                                 if (mi == null) {
4610                                                         Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4611                                                         return;
4612                                                 }
4613
4614                                                 IMemoryLocation mloc = (IMemoryLocation) var;
4615
4616                                                 mloc.AddressOf (ec, AddressOp.Load);
4617                                                 ig.Emit (OpCodes.Call, mi);
4618                                         }
4619                                 }
4620
4621                                 ig.MarkLabel (skip);
4622
4623                                 if (emit_finally) {
4624                                         ig.EndExceptionBlock ();
4625                                         if (i > 0)
4626                                                 ig.BeginFinallyBlock ();
4627                                 }
4628                         }
4629                 }
4630
4631                 void EmitExpression (EmitContext ec)
4632                 {
4633                         //
4634                         // Make a copy of the expression and operate on that.
4635                         //
4636                         ILGenerator ig = ec.ig;
4637
4638                         local_copy.Store (ec, expr);
4639
4640                         if (emit_finally)
4641                                 ig.BeginExceptionBlock ();
4642
4643                         Statement.Emit (ec);
4644                         
4645                         DoEmitFinally (ec);
4646                         if (emit_finally)
4647                                 ig.EndExceptionBlock ();
4648                 }
4649
4650                 void EmitExpressionFinally (EmitContext ec)
4651                 {
4652                         ILGenerator ig = ec.ig;
4653                         if (!expr_type.IsValueType) {
4654                                 Label skip = ig.DefineLabel ();
4655                                 local_copy.Emit (ec);
4656                                 ig.Emit (OpCodes.Brfalse, skip);
4657                                 local_copy.Emit (ec);
4658                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4659                                 ig.MarkLabel (skip);
4660                         } else {
4661                                 Expression ml = Expression.MemberLookup (
4662                                         ec.ContainerType, TypeManager.idisposable_type, expr_type,
4663                                         "Dispose", Location.Null);
4664
4665                                 if (!(ml is MethodGroupExpr)) {
4666                                         local_copy.Emit (ec);
4667                                         ig.Emit (OpCodes.Box, expr_type);
4668                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4669                                 } else {
4670                                         MethodInfo mi = null;
4671
4672                                         foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4673                                                 if (TypeManager.GetParameterData (mk).Count == 0) {
4674                                                         mi = mk;
4675                                                         break;
4676                                                 }
4677                                         }
4678
4679                                         if (mi == null) {
4680                                                 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4681                                                 return;
4682                                         }
4683
4684                                         local_copy.AddressOf (ec, AddressOp.Load);
4685                                         ig.Emit (OpCodes.Call, mi);
4686                                 }
4687                         }
4688                 }
4689                 
4690                 public override bool Resolve (EmitContext ec)
4691                 {
4692                         if (expression_or_block is DictionaryEntry){
4693                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4694                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4695
4696                                 if (!ResolveLocalVariableDecls (ec))
4697                                         return false;
4698
4699                         } else if (expression_or_block is Expression){
4700                                 expr = (Expression) expression_or_block;
4701
4702                                 expr = expr.Resolve (ec);
4703                                 if (expr == null)
4704                                         return false;
4705
4706                                 expr_type = expr.Type;
4707
4708                                 if (!ResolveExpression (ec))
4709                                         return false;
4710                         }
4711
4712                         FlowBranchingException branching = ec.StartFlowBranching (this);
4713
4714                         bool ok = Statement.Resolve (ec);
4715
4716                         ResolveFinally (branching);
4717
4718                         ec.EndFlowBranching ();
4719
4720                         // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4721                         // So, ensure there's some IL code after the finally block.
4722                         ec.NeedReturnLabel ();
4723
4724                         return ok;
4725                 }
4726                 
4727                 protected override void DoEmit (EmitContext ec)
4728                 {
4729                         if (expression_or_block is DictionaryEntry)
4730                                 EmitLocalVariableDecls (ec);
4731                         else if (expression_or_block is Expression)
4732                                 EmitExpression (ec);
4733                 }
4734
4735                 public override void EmitFinally (EmitContext ec)
4736                 {
4737                         if (expression_or_block is DictionaryEntry)
4738                                 EmitLocalVariableDeclFinally (ec);
4739                         else if (expression_or_block is Expression)
4740                                 EmitExpressionFinally (ec);
4741                 }
4742
4743                 protected override void CloneTo (CloneContext clonectx, Statement t)
4744                 {
4745                         Using target = (Using) t;
4746
4747                         if (expression_or_block is Expression)
4748                                 target.expression_or_block = ((Expression) expression_or_block).Clone (clonectx);
4749                         else
4750                                 target.expression_or_block = ((Statement) expression_or_block).Clone (clonectx);
4751                         
4752                         target.Statement = Statement.Clone (clonectx);
4753                 }
4754         }
4755
4756         /// <summary>
4757         ///   Implementation of the foreach C# statement
4758         /// </summary>
4759         public class Foreach : Statement {
4760                 Expression type;
4761                 Expression variable;
4762                 Expression expr;
4763                 Statement statement;
4764                 ArrayForeach array;
4765                 CollectionForeach collection;
4766                 
4767                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4768                                 Statement stmt, Location l)
4769                 {
4770                         this.type = type;
4771                         this.variable = var;
4772                         this.expr = expr;
4773                         statement = stmt;
4774                         loc = l;
4775                 }
4776
4777                 public Statement Statement {
4778                         get { return statement; }
4779                 }
4780
4781                 public override bool Resolve (EmitContext ec)
4782                 {
4783                         expr = expr.Resolve (ec);
4784                         if (expr == null)
4785                                 return false;
4786
4787                         if (expr.Type == TypeManager.null_type) {
4788                                 Report.Error (186, loc, "Use of null is not valid in this context");
4789                                 return false;
4790                         }
4791
4792                         if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
4793                                 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4794                                         expr.ExprClassName);
4795                                 return false;
4796                         }
4797
4798                         //
4799                         // We need an instance variable.  Not sure this is the best
4800                         // way of doing this.
4801                         //
4802                         // FIXME: When we implement propertyaccess, will those turn
4803                         // out to return values in ExprClass?  I think they should.
4804                         //
4805                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4806                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4807                                 collection.Error_Enumerator ();
4808                                 return false;
4809                         }
4810
4811                         if (expr.Type.IsArray) {
4812                                 array = new ArrayForeach (type, variable, expr, statement, loc);
4813                                 return array.Resolve (ec);
4814                         }
4815                         
4816                         collection = new CollectionForeach (type, variable, expr, statement, loc);
4817                         return collection.Resolve (ec);
4818                 }
4819
4820                 protected override void DoEmit (EmitContext ec)
4821                 {
4822                         ILGenerator ig = ec.ig;
4823                         
4824                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4825                         ec.LoopBegin = ig.DefineLabel ();
4826                         ec.LoopEnd = ig.DefineLabel ();
4827
4828                         if (collection != null)
4829                                 collection.Emit (ec);
4830                         else
4831                                 array.Emit (ec);
4832                         
4833                         ec.LoopBegin = old_begin;
4834                         ec.LoopEnd = old_end;
4835                 }
4836
4837                 protected class ArrayCounter : TemporaryVariable
4838                 {
4839                         public ArrayCounter (Location loc)
4840                                 : base (TypeManager.int32_type, loc)
4841                         { }
4842
4843                         public void Initialize (EmitContext ec)
4844                         {
4845                                 EmitThis (ec);
4846                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
4847                                 EmitStore (ec);
4848                         }
4849
4850                         public void Increment (EmitContext ec)
4851                         {
4852                                 EmitThis (ec);
4853                                 Emit (ec);
4854                                 ec.ig.Emit (OpCodes.Ldc_I4_1);
4855                                 ec.ig.Emit (OpCodes.Add);
4856                                 EmitStore (ec);
4857                         }
4858                 }
4859
4860                 protected class ArrayForeach : Statement
4861                 {
4862                         Expression variable, expr, conv;
4863                         Statement statement;
4864                         Type array_type;
4865                         Expression var_type;
4866                         TemporaryVariable[] lengths;
4867                         ArrayCounter[] counter;
4868                         int rank;
4869
4870                         TemporaryVariable copy;
4871                         Expression access;
4872
4873                         public ArrayForeach (Expression var_type, Expression var,
4874                                              Expression expr, Statement stmt, Location l)
4875                         {
4876                                 this.var_type = var_type;
4877                                 this.variable = var;
4878                                 this.expr = expr;
4879                                 statement = stmt;
4880                                 loc = l;
4881                         }
4882
4883                         public override bool Resolve (EmitContext ec)
4884                         {
4885                                 array_type = expr.Type;
4886                                 rank = array_type.GetArrayRank ();
4887
4888                                 copy = new TemporaryVariable (array_type, loc);
4889                                 copy.Resolve (ec);
4890
4891                                 counter = new ArrayCounter [rank];
4892                                 lengths = new TemporaryVariable [rank];
4893
4894                                 ArrayList list = new ArrayList ();
4895                                 for (int i = 0; i < rank; i++) {
4896                                         counter [i] = new ArrayCounter (loc);
4897                                         counter [i].Resolve (ec);
4898
4899                                         lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4900                                         lengths [i].Resolve (ec);
4901
4902                                         list.Add (counter [i]);
4903                                 }
4904
4905                                 access = new ElementAccess (copy, list).Resolve (ec);
4906                                 if (access == null)
4907                                         return false;
4908
4909                                 VarExpr ve = var_type as VarExpr;
4910                                 if (ve != null) {
4911                                         // Infer implicitly typed local variable from foreach array type
4912                                         var_type = new TypeExpression (access.Type, ve.Location);
4913                                 }
4914
4915                                 var_type = var_type.ResolveAsTypeTerminal (ec, false);
4916                                 if (var_type == null)
4917                                         return false;
4918
4919                                 conv = Convert.ExplicitConversion (ec, access, var_type.Type, loc);
4920                                 if (conv == null)
4921                                         return false;
4922
4923                                 bool ok = true;
4924
4925                                 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4926                                 ec.CurrentBranching.CreateSibling ();
4927
4928                                 variable = variable.ResolveLValue (ec, conv, loc);
4929                                 if (variable == null)
4930                                         ok = false;
4931
4932                                 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4933                                 if (!statement.Resolve (ec))
4934                                         ok = false;
4935                                 ec.EndFlowBranching ();
4936
4937                                 // There's no direct control flow from the end of the embedded statement to the end of the loop
4938                                 ec.CurrentBranching.CurrentUsageVector.Goto ();
4939
4940                                 ec.EndFlowBranching ();
4941
4942                                 return ok;
4943                         }
4944
4945                         protected override void DoEmit (EmitContext ec)
4946                         {
4947                                 ILGenerator ig = ec.ig;
4948
4949                                 copy.Store (ec, expr);
4950
4951                                 Label[] test = new Label [rank];
4952                                 Label[] loop = new Label [rank];
4953
4954                                 for (int i = 0; i < rank; i++) {
4955                                         test [i] = ig.DefineLabel ();
4956                                         loop [i] = ig.DefineLabel ();
4957
4958                                         lengths [i].EmitThis (ec);
4959                                         ((ArrayAccess) access).EmitGetLength (ec, i);
4960                                         lengths [i].EmitStore (ec);
4961                                 }
4962
4963                                 for (int i = 0; i < rank; i++) {
4964                                         counter [i].Initialize (ec);
4965
4966                                         ig.Emit (OpCodes.Br, test [i]);
4967                                         ig.MarkLabel (loop [i]);
4968                                 }
4969
4970                                 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4971
4972                                 statement.Emit (ec);
4973
4974                                 ig.MarkLabel (ec.LoopBegin);
4975
4976                                 for (int i = rank - 1; i >= 0; i--){
4977                                         counter [i].Increment (ec);
4978
4979                                         ig.MarkLabel (test [i]);
4980                                         counter [i].Emit (ec);
4981                                         lengths [i].Emit (ec);
4982                                         ig.Emit (OpCodes.Blt, loop [i]);
4983                                 }
4984
4985                                 ig.MarkLabel (ec.LoopEnd);
4986                         }
4987                 }
4988
4989                 protected class CollectionForeach : ExceptionStatement
4990                 {
4991                         Expression variable, expr;
4992                         Statement statement;
4993
4994                         TemporaryVariable enumerator;
4995                         Expression init;
4996                         Statement loop;
4997
4998                         MethodGroupExpr get_enumerator;
4999                         PropertyExpr get_current;
5000                         MethodInfo move_next;
5001                         Expression var_type;
5002                         Type enumerator_type;
5003                         bool is_disposable;
5004                         bool enumerator_found;
5005
5006                         public CollectionForeach (Expression var_type, Expression var,
5007                                                   Expression expr, Statement stmt, Location l)
5008                         {
5009                                 this.var_type = var_type;
5010                                 this.variable = var;
5011                                 this.expr = expr;
5012                                 statement = stmt;
5013                                 loc = l;
5014                         }
5015
5016                         bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
5017                         {
5018                                 Type return_type = mi.ReturnType;
5019
5020                                 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
5021                                         //
5022                                         // Apply the same optimization as MS: skip the GetEnumerator
5023                                         // returning an IEnumerator, and use the one returning a 
5024                                         // CharEnumerator instead. This allows us to avoid the 
5025                                         // try-finally block and the boxing.
5026                                         //
5027                                         return false;
5028
5029                                 //
5030                                 // Ok, we can access it, now make sure that we can do something
5031                                 // with this `GetEnumerator'
5032                                 //
5033
5034                                 if (return_type == TypeManager.ienumerator_type ||
5035                                     TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
5036                                     (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
5037                                         //
5038                                         // If it is not an interface, lets try to find the methods ourselves.
5039                                         // For example, if we have:
5040                                         // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
5041                                         // We can avoid the iface call. This is a runtime perf boost.
5042                                         // even bigger if we have a ValueType, because we avoid the cost
5043                                         // of boxing.
5044                                         //
5045                                         // We have to make sure that both methods exist for us to take
5046                                         // this path. If one of the methods does not exist, we will just
5047                                         // use the interface. Sadly, this complex if statement is the only
5048                                         // way I could do this without a goto
5049                                         //
5050
5051 #if GMCS_SOURCE
5052                                         //
5053                                         // Prefer a generic enumerator over a non-generic one.
5054                                         //
5055                                         if (return_type.IsInterface && return_type.IsGenericType) {
5056                                                 enumerator_type = return_type;
5057                                                 if (!FetchGetCurrent (ec, return_type))
5058                                                         get_current = new PropertyExpr (
5059                                                                 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
5060                                                 if (!FetchMoveNext (return_type))
5061                                                         move_next = TypeManager.bool_movenext_void;
5062                                                 return true;
5063                                         }
5064 #endif
5065
5066                                         if (return_type.IsInterface ||
5067                                             !FetchMoveNext (return_type) ||
5068                                             !FetchGetCurrent (ec, return_type)) {
5069                                                 enumerator_type = return_type;
5070                                                 move_next = TypeManager.bool_movenext_void;
5071                                                 get_current = new PropertyExpr (
5072                                                         ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
5073                                                 return true;
5074                                         }
5075                                 } else {
5076                                         //
5077                                         // Ok, so they dont return an IEnumerable, we will have to
5078                                         // find if they support the GetEnumerator pattern.
5079                                         //
5080
5081                                         if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
5082                                                 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",
5083                                                         TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
5084                                                 return false;
5085                                         }
5086                                 }
5087
5088                                 enumerator_type = return_type;
5089                                 is_disposable = !enumerator_type.IsSealed ||
5090                                         TypeManager.ImplementsInterface (
5091                                                 enumerator_type, TypeManager.idisposable_type);
5092
5093                                 return true;
5094                         }
5095
5096                         //
5097                         // Retrieves a `public bool MoveNext ()' method from the Type `t'
5098                         //
5099                         bool FetchMoveNext (Type t)
5100                         {
5101                                 MemberList move_next_list;
5102
5103                                 move_next_list = TypeContainer.FindMembers (
5104                                         t, MemberTypes.Method,
5105                                         BindingFlags.Public | BindingFlags.Instance,
5106                                         Type.FilterName, "MoveNext");
5107                                 if (move_next_list.Count == 0)
5108                                         return false;
5109
5110                                 foreach (MemberInfo m in move_next_list){
5111                                         MethodInfo mi = (MethodInfo) m;
5112                                 
5113                                         if ((TypeManager.GetParameterData (mi).Count == 0) &&
5114                                             TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
5115                                                 move_next = mi;
5116                                                 return true;
5117                                         }
5118                                 }
5119
5120                                 return false;
5121                         }
5122                 
5123                         //
5124                         // Retrieves a `public T get_Current ()' method from the Type `t'
5125                         //
5126                         bool FetchGetCurrent (EmitContext ec, Type t)
5127                         {
5128                                 PropertyExpr pe = Expression.MemberLookup (
5129                                         ec.ContainerType, t, "Current", MemberTypes.Property,
5130                                         Expression.AllBindingFlags, loc) as PropertyExpr;
5131                                 if (pe == null)
5132                                         return false;
5133
5134                                 get_current = pe;
5135                                 return true;
5136                         }
5137
5138                         // 
5139                         // Retrieves a `public void Dispose ()' method from the Type `t'
5140                         //
5141                         static MethodInfo FetchMethodDispose (Type t)
5142                         {
5143                                 MemberList dispose_list;
5144
5145                                 dispose_list = TypeContainer.FindMembers (
5146                                         t, MemberTypes.Method,
5147                                         BindingFlags.Public | BindingFlags.Instance,
5148                                         Type.FilterName, "Dispose");
5149                                 if (dispose_list.Count == 0)
5150                                         return null;
5151
5152                                 foreach (MemberInfo m in dispose_list){
5153                                         MethodInfo mi = (MethodInfo) m;
5154
5155                                         if (TypeManager.GetParameterData (mi).Count == 0){
5156                                                 if (mi.ReturnType == TypeManager.void_type)
5157                                                         return mi;
5158                                         }
5159                                 }
5160                                 return null;
5161                         }
5162
5163                         public void Error_Enumerator ()
5164                         {
5165                                 if (enumerator_found) {
5166                                         return;
5167                                 }
5168
5169                             Report.Error (1579, loc,
5170                                         "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
5171                                         TypeManager.CSharpName (expr.Type));
5172                         }
5173
5174                         bool IsOverride (MethodInfo m)
5175                         {
5176                                 m = (MethodInfo) TypeManager.DropGenericMethodArguments (m);
5177
5178                                 if (!m.IsVirtual || ((m.Attributes & MethodAttributes.NewSlot) != 0))
5179                                         return false;
5180                                 if (m is MethodBuilder)
5181                                         return true;
5182
5183                                 MethodInfo base_method = m.GetBaseDefinition ();
5184                                 return base_method != m;
5185                         }
5186
5187                         bool TryType (EmitContext ec, Type t)
5188                         {
5189                                 MethodGroupExpr mg = Expression.MemberLookup (
5190                                         ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
5191                                         Expression.AllBindingFlags, loc) as MethodGroupExpr;
5192                                 if (mg == null)
5193                                         return false;
5194
5195                                 MethodInfo result = null;
5196                                 MethodInfo tmp_move_next = null;
5197                                 PropertyExpr tmp_get_cur = null;
5198                                 Type tmp_enumerator_type = enumerator_type;
5199                                 foreach (MethodInfo mi in mg.Methods) {
5200                                         if (TypeManager.GetParameterData (mi).Count != 0)
5201                                                 continue;
5202                         
5203                                         // Check whether GetEnumerator is public
5204                                         if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
5205                                                 continue;
5206
5207                                         if (IsOverride (mi))
5208                                                 continue;
5209
5210                                         enumerator_found = true;
5211
5212                                         if (!GetEnumeratorFilter (ec, mi))
5213                                                 continue;
5214
5215                                         if (result != null) {
5216                                                 if (TypeManager.IsGenericType (result.ReturnType)) {
5217                                                         if (!TypeManager.IsGenericType (mi.ReturnType))
5218                                                                 continue;
5219
5220                                                         MethodBase mb = TypeManager.DropGenericMethodArguments (mi);
5221                                                         Report.SymbolRelatedToPreviousError (t);
5222                                                         Report.Error(1640, loc, "foreach statement cannot operate on variables of type `{0}' " +
5223                                                                      "because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
5224                                                                      TypeManager.CSharpName (t), TypeManager.CSharpSignature (mb));
5225                                                         return false;
5226                                                 }
5227
5228                                                 // Always prefer generics enumerators
5229                                                 if (!TypeManager.IsGenericType (mi.ReturnType)) {
5230                                                         if (TypeManager.ImplementsInterface (mi.DeclaringType, result.DeclaringType) ||
5231                                                             TypeManager.ImplementsInterface (result.DeclaringType, mi.DeclaringType))
5232                                                                 continue;
5233
5234                                                         Report.SymbolRelatedToPreviousError (result);
5235                                                         Report.SymbolRelatedToPreviousError (mi);
5236                                                         Report.Warning (278, 2, loc, "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
5237                                                                         TypeManager.CSharpName (t), "enumerable", TypeManager.CSharpSignature (result), TypeManager.CSharpSignature (mi));
5238                                                         return false;
5239                                                 }
5240                                         }
5241                                         result = mi;
5242                                         tmp_move_next = move_next;
5243                                         tmp_get_cur = get_current;
5244                                         tmp_enumerator_type = enumerator_type;
5245                                         if (mi.DeclaringType == t)
5246                                                 break;
5247                                 }
5248
5249                                 if (result != null) {
5250                                         move_next = tmp_move_next;
5251                                         get_current = tmp_get_cur;
5252                                         enumerator_type = tmp_enumerator_type;
5253                                         MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
5254                                         get_enumerator = new MethodGroupExpr (mi, enumerator_type, loc);
5255
5256                                         if (t != expr.Type) {
5257                                                 expr = Convert.ExplicitConversion (
5258                                                         ec, expr, t, loc);
5259                                                 if (expr == null)
5260                                                         throw new InternalErrorException ();
5261                                         }
5262
5263                                         get_enumerator.InstanceExpression = expr;
5264                                         get_enumerator.IsBase = t != expr.Type;
5265
5266                                         return true;
5267                                 }
5268
5269                                 return false;
5270                         }               
5271
5272                         bool ProbeCollectionType (EmitContext ec, Type t)
5273                         {
5274                                 int errors = Report.Errors;
5275                                 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
5276                                         if (TryType (ec, tt))
5277                                                 return true;
5278                                         tt = tt.BaseType;
5279                                 }
5280
5281                                 if (Report.Errors > errors)
5282                                         return false;
5283
5284                                 //
5285                                 // Now try to find the method in the interfaces
5286                                 //
5287                                 Type [] ifaces = TypeManager.GetInterfaces (t);
5288                                 foreach (Type i in ifaces){
5289                                         if (TryType (ec, i))
5290                                                 return true;
5291                                 }
5292
5293                                 return false;
5294                         }
5295
5296                         public override bool Resolve (EmitContext ec)
5297                         {
5298                                 enumerator_type = TypeManager.ienumerator_type;
5299                                 is_disposable = true;
5300
5301                                 if (!ProbeCollectionType (ec, expr.Type)) {
5302                                         Error_Enumerator ();
5303                                         return false;
5304                                 }
5305
5306                                 VarExpr ve = var_type as VarExpr;
5307                                 if (ve != null) {
5308                                         // Infer implicitly typed local variable from foreach enumerable type
5309                                         var_type = new TypeExpression (get_current.PropertyInfo.PropertyType, var_type.Location);
5310                                 }
5311
5312                                 var_type = var_type.ResolveAsTypeTerminal (ec, false);
5313                                 if (var_type == null)
5314                                         return false;
5315                                                                 
5316                                 enumerator = new TemporaryVariable (enumerator_type, loc);
5317                                 enumerator.Resolve (ec);
5318
5319                                 init = new Invocation (get_enumerator, null);
5320                                 init = init.Resolve (ec);
5321                                 if (init == null)
5322                                         return false;
5323
5324                                 Expression move_next_expr;
5325                                 {
5326                                         MemberInfo[] mi = new MemberInfo[] { move_next };
5327                                         MethodGroupExpr mg = new MethodGroupExpr (mi, var_type.Type, loc);
5328                                         mg.InstanceExpression = enumerator;
5329
5330                                         move_next_expr = new Invocation (mg, null);
5331                                 }
5332
5333                                 get_current.InstanceExpression = enumerator;
5334
5335                                 Statement block = new CollectionForeachStatement (
5336                                         var_type.Type, variable, get_current, statement, loc);
5337
5338                                 loop = new While (move_next_expr, block, loc);
5339
5340                                 bool ok = true;
5341
5342                                 FlowBranchingException branching = null;
5343                                 if (is_disposable)
5344                                         branching = ec.StartFlowBranching (this);
5345
5346                                 if (!loop.Resolve (ec))
5347                                         ok = false;
5348
5349                                 if (is_disposable) {
5350                                         ResolveFinally (branching);
5351                                         ec.EndFlowBranching ();
5352                                 } else
5353                                         emit_finally = true;
5354
5355                                 return ok;
5356                         }
5357
5358                         protected override void DoEmit (EmitContext ec)
5359                         {
5360                                 ILGenerator ig = ec.ig;
5361
5362                                 enumerator.Store (ec, init);
5363
5364                                 //
5365                                 // Protect the code in a try/finalize block, so that
5366                                 // if the beast implement IDisposable, we get rid of it
5367                                 //
5368                                 if (is_disposable && emit_finally)
5369                                         ig.BeginExceptionBlock ();
5370                         
5371                                 loop.Emit (ec);
5372
5373                                 //
5374                                 // Now the finally block
5375                                 //
5376                                 if (is_disposable) {
5377                                         DoEmitFinally (ec);
5378                                         if (emit_finally)
5379                                                 ig.EndExceptionBlock ();
5380                                 }
5381                         }
5382
5383
5384                         public override void EmitFinally (EmitContext ec)
5385                         {
5386                                 ILGenerator ig = ec.ig;
5387
5388                                 if (enumerator_type.IsValueType) {
5389                                         MethodInfo mi = FetchMethodDispose (enumerator_type);
5390                                         if (mi != null) {
5391                                                 enumerator.EmitLoadAddress (ec);
5392                                                 ig.Emit (OpCodes.Call, mi);
5393                                         } else {
5394                                                 enumerator.Emit (ec);
5395                                                 ig.Emit (OpCodes.Box, enumerator_type);
5396                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5397                                         }
5398                                 } else {
5399                                         Label call_dispose = ig.DefineLabel ();
5400
5401                                         enumerator.Emit (ec);
5402                                         ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5403                                         ig.Emit (OpCodes.Dup);
5404                                         ig.Emit (OpCodes.Brtrue_S, call_dispose);
5405                                         ig.Emit (OpCodes.Pop);
5406
5407                                         Label end_finally = ig.DefineLabel ();
5408                                         ig.Emit (OpCodes.Br, end_finally);
5409
5410                                         ig.MarkLabel (call_dispose);
5411                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5412                                         ig.MarkLabel (end_finally);
5413                                 }
5414                         }
5415                 }
5416
5417                 protected class CollectionForeachStatement : Statement
5418                 {
5419                         Type type;
5420                         Expression variable, current, conv;
5421                         Statement statement;
5422                         Assign assign;
5423
5424                         public CollectionForeachStatement (Type type, Expression variable,
5425                                                            Expression current, Statement statement,
5426                                                            Location loc)
5427                         {
5428                                 this.type = type;
5429                                 this.variable = variable;
5430                                 this.current = current;
5431                                 this.statement = statement;
5432                                 this.loc = loc;
5433                         }
5434
5435                         public override bool Resolve (EmitContext ec)
5436                         {
5437                                 current = current.Resolve (ec);
5438                                 if (current == null)
5439                                         return false;
5440
5441                                 conv = Convert.ExplicitConversion (ec, current, type, loc);
5442                                 if (conv == null)
5443                                         return false;
5444
5445                                 assign = new Assign (variable, conv, loc);
5446                                 if (assign.Resolve (ec) == null)
5447                                         return false;
5448
5449                                 if (!statement.Resolve (ec))
5450                                         return false;
5451
5452                                 return true;
5453                         }
5454
5455                         protected override void DoEmit (EmitContext ec)
5456                         {
5457                                 assign.EmitStatement (ec);
5458                                 statement.Emit (ec);
5459                         }
5460                 }
5461
5462                 protected override void CloneTo (CloneContext clonectx, Statement t)
5463                 {
5464                         Foreach target = (Foreach) t;
5465
5466                         target.type = type.Clone (clonectx);
5467                         target.variable = variable.Clone (clonectx);
5468                         target.expr = expr.Clone (clonectx);
5469                         target.statement = statement.Clone (clonectx);
5470                 }
5471         }
5472 }