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