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