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