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