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