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