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