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