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