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