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