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