ed3ea2ec6d2a44a85a11fff6b7c4d4308031e637
[mono.git] / mcs / gmcs / statement.cs
1 //
2 // statement.cs: Statement representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Martin Baulig (martin@ximian.com)
7 //
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 // (C) 2003, 2004 Novell, Inc.
10 //
11
12 using System;
13 using System.Text;
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Diagnostics;
17
18 namespace Mono.CSharp {
19
20         using System.Collections;
21         
22         public abstract class Statement {
23                 public Location loc;
24                 
25                 /// <summary>
26                 /// Resolves the statement, true means that all sub-statements
27                 /// did resolve ok.
28                 //  </summary>
29                 public virtual bool Resolve (EmitContext ec)
30                 {
31                         return true;
32                 }
33                 
34                 /// <summary>
35                 ///   We already know that the statement is unreachable, but we still
36                 ///   need to resolve it to catch errors.
37                 /// </summary>
38                 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
39                 {
40                         //
41                         // This conflicts with csc's way of doing this, but IMHO it's
42                         // the right thing to do.
43                         //
44                         // If something is unreachable, we still check whether it's
45                         // correct.  This means that you cannot use unassigned variables
46                         // in unreachable code, for instance.
47                         //
48
49                         if (warn && (RootContext.WarningLevel >= 2))
50                                 Report.Warning (162, loc, "Unreachable code detected");
51
52                         ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
53                         bool ok = Resolve (ec);
54                         ec.KillFlowBranching ();
55
56                         return ok;
57                 }
58                 
59                 protected void CheckObsolete (Type type)
60                 {
61                         ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
62                         if (obsolete_attr == null)
63                                 return;
64
65                         AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
66                 }
67                 
68                 /// <summary>
69                 ///   Return value indicates whether all code paths emitted return.
70                 /// </summary>
71                 protected abstract void DoEmit (EmitContext ec);
72
73                 /// <summary>
74                 ///   Utility wrapper routine for Error, just to beautify the code
75                 /// </summary>
76                 public void Error (int error, string format, params object[] args)
77                 {
78                         Error (error, String.Format (format, args));
79                 }
80                 
81                 public void Error (int error, string s)
82                 {
83                         if (!Location.IsNull (loc))
84                                 Report.Error (error, loc, s);
85                                 else
86                                 Report.Error (error, s);
87                 }
88
89                 /// <summary>
90                 ///   Return value indicates whether all code paths emitted return.
91                 /// </summary>
92                 public virtual void Emit (EmitContext ec)
93                 {
94                         ec.Mark (loc, true);
95                         DoEmit (ec);
96                 }
97         }
98
99         public sealed class EmptyStatement : Statement {
100                 
101                 private EmptyStatement () {}
102                 
103                 public static readonly EmptyStatement Value = new EmptyStatement ();
104                 
105                 public override bool Resolve (EmitContext ec)
106                 {
107                         return true;
108                 }
109                 
110                 protected override void DoEmit (EmitContext ec)
111                 {
112                 }
113         }
114         
115         public class If : Statement {
116                 Expression expr;
117                 public Statement TrueStatement;
118                 public Statement FalseStatement;
119                 
120                 bool is_true_ret;
121                 
122                 public If (Expression expr, Statement trueStatement, Location l)
123                 {
124                         this.expr = expr;
125                         TrueStatement = trueStatement;
126                         loc = l;
127                 }
128
129                 public If (Expression expr,
130                            Statement trueStatement,
131                            Statement falseStatement,
132                            Location l)
133                 {
134                         this.expr = expr;
135                         TrueStatement = trueStatement;
136                         FalseStatement = falseStatement;
137                         loc = l;
138                 }
139
140                 public override bool Resolve (EmitContext ec)
141                 {
142                         bool ok = true;
143
144                         Report.Debug (1, "START IF BLOCK", loc);
145
146                         expr = Expression.ResolveBoolean (ec, expr, loc);
147                         if (expr == null){
148                                 ok = false;
149                                 goto skip;
150                         }
151                         
152                         Assign ass = expr as Assign;
153                         if (ass != null && ass.Source is Constant) {
154                                 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
155                         }
156
157                         //
158                         // Dead code elimination
159                         //
160                         if (expr is BoolConstant){
161                                 bool take = ((BoolConstant) expr).Value;
162
163                                 if (take){
164                                         if (!TrueStatement.Resolve (ec))
165                                                 return false;
166
167                                         if ((FalseStatement != null) &&
168                                             !FalseStatement.ResolveUnreachable (ec, true))
169                                                 return false;
170                                         FalseStatement = null;
171                                 } else {
172                                         if (!TrueStatement.ResolveUnreachable (ec, true))
173                                                 return false;
174                                         TrueStatement = null;
175                         
176                                         if ((FalseStatement != null) &&
177                                             !FalseStatement.Resolve (ec))
178                                                 return false;
179                                 }
180
181                                 return true;
182                         }
183                 skip:
184                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
185                         
186                         ok &= TrueStatement.Resolve (ec);
187
188                         is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
189
190                         ec.CurrentBranching.CreateSibling ();
191
192                         if (FalseStatement != null)
193                                 ok &= FalseStatement.Resolve (ec);
194                                         
195                         ec.EndFlowBranching ();
196
197                         Report.Debug (1, "END IF BLOCK", loc);
198
199                         return ok;
200                 }
201                 
202                 protected override void DoEmit (EmitContext ec)
203                 {
204                         ILGenerator ig = ec.ig;
205                         Label false_target = ig.DefineLabel ();
206                         Label end;
207
208                         //
209                         // If we're a boolean expression, Resolve() already
210                         // eliminated dead code for us.
211                         //
212                         if (expr is BoolConstant){
213                                 bool take = ((BoolConstant) expr).Value;
214
215                                 if (take)
216                                         TrueStatement.Emit (ec);
217                                 else if (FalseStatement != null)
218                                                 FalseStatement.Emit (ec);
219
220                                                 return;
221                                         }
222                         
223                         expr.EmitBranchable (ec, false_target, false);
224
225                         TrueStatement.Emit (ec);
226
227                         if (FalseStatement != null){
228                                 bool branch_emitted = false;
229                                 
230                                 end = ig.DefineLabel ();
231                                 if (!is_true_ret){
232                                         ig.Emit (OpCodes.Br, end);
233                                         branch_emitted = true;
234                                 }
235
236                                 ig.MarkLabel (false_target);
237                                 FalseStatement.Emit (ec);
238
239                                 if (branch_emitted)
240                                         ig.MarkLabel (end);
241                         } else {
242                                 ig.MarkLabel (false_target);
243                         }
244                 }
245         }
246
247         public class Do : Statement {
248                 public Expression expr;
249                 public readonly Statement  EmbeddedStatement;
250                 bool infinite;
251                 
252                 public Do (Statement statement, Expression boolExpr, Location l)
253                 {
254                         expr = boolExpr;
255                         EmbeddedStatement = statement;
256                         loc = l;
257                 }
258
259                 public override bool Resolve (EmitContext ec)
260                 {
261                         bool ok = true;
262
263                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
264
265                         if (!EmbeddedStatement.Resolve (ec))
266                                 ok = false;
267
268                         expr = Expression.ResolveBoolean (ec, expr, loc);
269                         if (expr == null)
270                                 ok = false;
271                         else if (expr is BoolConstant){
272                                 bool res = ((BoolConstant) expr).Value;
273
274                                 if (res)
275                                         infinite = true;
276                         }
277
278                         ec.CurrentBranching.Infinite = infinite;
279                         ec.EndFlowBranching ();
280
281                         return ok;
282                 }
283                 
284                 protected override void DoEmit (EmitContext ec)
285                 {
286                         ILGenerator ig = ec.ig;
287                         Label loop = ig.DefineLabel ();
288                         Label old_begin = ec.LoopBegin;
289                         Label old_end = ec.LoopEnd;
290                         
291                         ec.LoopBegin = ig.DefineLabel ();
292                         ec.LoopEnd = ig.DefineLabel ();
293                                 
294                         ig.MarkLabel (loop);
295                         EmbeddedStatement.Emit (ec);
296                         ig.MarkLabel (ec.LoopBegin);
297
298                         //
299                         // Dead code elimination
300                         //
301                         if (expr is BoolConstant){
302                                 bool res = ((BoolConstant) expr).Value;
303
304                                 if (res)
305                                         ec.ig.Emit (OpCodes.Br, loop); 
306                         } else
307                                 expr.EmitBranchable (ec, loop, true);
308                         
309                         ig.MarkLabel (ec.LoopEnd);
310
311                         ec.LoopBegin = old_begin;
312                         ec.LoopEnd = old_end;
313                 }
314         }
315
316         public class While : Statement {
317                 public Expression expr;
318                 public readonly Statement Statement;
319                 bool infinite, empty;
320                 
321                 public While (Expression boolExpr, Statement statement, Location l)
322                 {
323                         this.expr = boolExpr;
324                         Statement = statement;
325                         loc = l;
326                 }
327
328                 public override bool Resolve (EmitContext ec)
329                 {
330                         bool ok = true;
331
332                         expr = Expression.ResolveBoolean (ec, expr, loc);
333                         if (expr == null)
334                                 return false;
335
336                         //
337                         // Inform whether we are infinite or not
338                         //
339                         if (expr is BoolConstant){
340                                 BoolConstant bc = (BoolConstant) expr;
341
342                                 if (bc.Value == false){
343                                         if (!Statement.ResolveUnreachable (ec, true))
344                                                 return false;
345                                         empty = true;
346                                         return true;
347                                 } else
348                                         infinite = true;
349                         }
350
351                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
352                         if (!infinite)
353                                 ec.CurrentBranching.CreateSibling ();
354
355                         if (!Statement.Resolve (ec))
356                                 ok = false;
357
358                         ec.CurrentBranching.Infinite = infinite;
359                         ec.EndFlowBranching ();
360
361                         return ok;
362                 }
363                 
364                 protected override void DoEmit (EmitContext ec)
365                 {
366                         if (empty)
367                                 return;
368
369                         ILGenerator ig = ec.ig;
370                         Label old_begin = ec.LoopBegin;
371                         Label old_end = ec.LoopEnd;
372                         
373                         ec.LoopBegin = ig.DefineLabel ();
374                         ec.LoopEnd = ig.DefineLabel ();
375
376                         //
377                         // Inform whether we are infinite or not
378                         //
379                         if (expr is BoolConstant){
380                                 ig.MarkLabel (ec.LoopBegin);
381                                 Statement.Emit (ec);
382                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
383                                         
384                                 //
385                                 // Inform that we are infinite (ie, `we return'), only
386                                 // if we do not `break' inside the code.
387                                 //
388                                 ig.MarkLabel (ec.LoopEnd);
389                         } else {
390                                 Label while_loop = ig.DefineLabel ();
391
392                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
393                                 ig.MarkLabel (while_loop);
394
395                                 Statement.Emit (ec);
396                         
397                                 ig.MarkLabel (ec.LoopBegin);
398
399                                 expr.EmitBranchable (ec, while_loop, true);
400                                 
401                                 ig.MarkLabel (ec.LoopEnd);
402                         }       
403
404                         ec.LoopBegin = old_begin;
405                         ec.LoopEnd = old_end;
406                 }
407         }
408
409         public class For : Statement {
410                 Expression Test;
411                 readonly Statement InitStatement;
412                 readonly Statement Increment;
413                 readonly Statement Statement;
414                 bool infinite, empty;
415                 
416                 public For (Statement initStatement,
417                             Expression test,
418                             Statement increment,
419                             Statement statement,
420                             Location l)
421                 {
422                         InitStatement = initStatement;
423                         Test = test;
424                         Increment = increment;
425                         Statement = statement;
426                         loc = l;
427                 }
428
429                 public override bool Resolve (EmitContext ec)
430                 {
431                         bool ok = true;
432
433                         if (InitStatement != null){
434                                 if (!InitStatement.Resolve (ec))
435                                         ok = false;
436                         }
437
438                         if (Test != null){
439                                 Test = Expression.ResolveBoolean (ec, Test, loc);
440                                 if (Test == null)
441                                         ok = false;
442                                 else if (Test is BoolConstant){
443                                         BoolConstant bc = (BoolConstant) Test;
444
445                                         if (bc.Value == false){
446                                                 if (!Statement.ResolveUnreachable (ec, true))
447                                                         return false;
448                                                 if ((Increment != null) &&
449                                                     !Increment.ResolveUnreachable (ec, false))
450                                                         return false;
451                                                 empty = true;
452                                                 return true;
453                                         } else
454                                                 infinite = true;
455                                 }
456                         } else
457                                 infinite = true;
458
459                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
460                         if (!infinite)
461                                 ec.CurrentBranching.CreateSibling ();
462
463                         if (!Statement.Resolve (ec))
464                                 ok = false;
465
466                         if (Increment != null){
467                                 if (!Increment.Resolve (ec))
468                                         ok = false;
469                         }
470
471                                 ec.CurrentBranching.Infinite = infinite;
472                                 ec.EndFlowBranching ();
473
474                         return ok;
475                 }
476                 
477                 protected override void DoEmit (EmitContext ec)
478                 {
479                         if (empty)
480                                 return;
481
482                         ILGenerator ig = ec.ig;
483                         Label old_begin = ec.LoopBegin;
484                         Label old_end = ec.LoopEnd;
485                         Label loop = ig.DefineLabel ();
486                         Label test = ig.DefineLabel ();
487                         
488                         if (InitStatement != null && InitStatement != EmptyStatement.Value)
489                                         InitStatement.Emit (ec);
490
491                         ec.LoopBegin = ig.DefineLabel ();
492                         ec.LoopEnd = ig.DefineLabel ();
493
494                         ig.Emit (OpCodes.Br, test);
495                         ig.MarkLabel (loop);
496                         Statement.Emit (ec);
497
498                         ig.MarkLabel (ec.LoopBegin);
499                         if (Increment != EmptyStatement.Value)
500                                 Increment.Emit (ec);
501
502                         ig.MarkLabel (test);
503                         //
504                         // If test is null, there is no test, and we are just
505                         // an infinite loop
506                         //
507                         if (Test != null){
508                                 //
509                                 // The Resolve code already catches the case for
510                                 // Test == BoolConstant (false) so we know that
511                                 // this is true
512                                 //
513                                 if (Test is BoolConstant)
514                                         ig.Emit (OpCodes.Br, loop);
515                                 else
516                                         Test.EmitBranchable (ec, loop, true);
517                                 
518                         } else
519                                 ig.Emit (OpCodes.Br, loop);
520                         ig.MarkLabel (ec.LoopEnd);
521
522                         ec.LoopBegin = old_begin;
523                         ec.LoopEnd = old_end;
524                 }
525         }
526         
527         public class StatementExpression : Statement {
528                 ExpressionStatement expr;
529                 
530                 public StatementExpression (ExpressionStatement expr, Location l)
531                 {
532                         this.expr = expr;
533                         loc = l;
534                 }
535
536                 public override bool Resolve (EmitContext ec)
537                 {
538                         if (expr != null)
539                                 expr = expr.ResolveStatement (ec);
540                         return expr != null;
541                 }
542                 
543                 protected override void DoEmit (EmitContext ec)
544                 {
545                         expr.EmitStatement (ec);
546                 }
547
548                 public override string ToString ()
549                 {
550                         return "StatementExpression (" + expr + ")";
551                 }
552         }
553
554         /// <summary>
555         ///   Implements the return statement
556         /// </summary>
557         public class Return : Statement {
558                 public Expression Expr;
559                 
560                 public Return (Expression expr, Location l)
561                 {
562                         Expr = expr;
563                         loc = l;
564                 }
565
566                 bool in_exc;
567
568                 public override bool Resolve (EmitContext ec)
569                 {
570                         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);
1063                                 if (texpr == null)
1064                                         return false;
1065                                 
1066                                 VariableType = texpr.Type;
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 (Toplevel.Parameters.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                         //
1956                         // This flag is used to notate nested statements as unreachable from the beginning of this block.
1957                         // For the purposes of this resolution, it doesn't matter that the whole block is unreachable 
1958                         // from the beginning of the function.  The outer Resolve() that detected the unreachability is
1959                         // responsible for handling the situation.
1960                         //
1961                         int statement_count = statements.Count;
1962                         for (int ix = 0; ix < statement_count; ix++){
1963                                 Statement s = (Statement) statements [ix];
1964
1965                                 if (unreachable) {
1966                                         if (s is Block)
1967                                                 ((Block) s).unreachable = true;
1968
1969                                         if (!unreachable_shown && (RootContext.WarningLevel >= 2)) {
1970                                                 Report.Warning (
1971                                                         162, loc, "Unreachable code detected");
1972                                                 unreachable_shown = true;
1973                                         }
1974                                 }
1975
1976                                 if (!s.Resolve (ec)) {
1977                                         ok = false;
1978                                         statements [ix] = EmptyStatement.Value;
1979                                         continue;
1980                                 }
1981
1982                                 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1983                                         statements [ix] = EmptyStatement.Value;
1984
1985                                 num_statements = ix + 1;
1986                                 if (s is LabeledStatement)
1987                                         unreachable = false;
1988                                 else
1989                                         unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1990                         }
1991
1992                         Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1993                                       ec.CurrentBranching, statement_count, num_statements);
1994
1995
1996                         FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1997
1998                         ec.CurrentBlock = prev_block;
1999
2000                         // If we're a non-static `struct' constructor which doesn't have an
2001                         // initializer, then we must initialize all of the struct's fields.
2002                         if ((this_variable != null) &&
2003                             (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
2004                             !this_variable.IsThisAssigned (ec, loc))
2005                                 ok = false;
2006
2007                         if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2008                                 foreach (LabeledStatement label in labels.Values)
2009                                         if (!label.HasBeenReferenced)
2010                                                 Report.Warning (164, label.Location,
2011                                                                 "This label has not been referenced");
2012                         }
2013
2014                         Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2015
2016                         if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2017                             (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2018                             (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2019                                 flags |= Flags.HasRet;
2020
2021                         if (ok && (errors == Report.Errors)) {
2022                                 if (RootContext.WarningLevel >= 3)
2023                                         UsageWarning (vector);
2024                         }
2025
2026                         return ok;
2027                 }
2028                 
2029                 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2030                 {
2031                         unreachable_shown = true;
2032                         unreachable = true;
2033
2034                         if (warn && (RootContext.WarningLevel >= 2))
2035                                 Report.Warning (162, loc, "Unreachable code detected");
2036
2037                         ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2038                         bool ok = Resolve (ec);
2039                         ec.KillFlowBranching ();
2040
2041                         return ok;
2042                 }
2043                 
2044                 protected override void DoEmit (EmitContext ec)
2045                 {
2046                         for (int ix = 0; ix < num_statements; ix++){
2047                                 Statement s = (Statement) statements [ix];
2048
2049                                 // Check whether we are the last statement in a
2050                                 // top-level block.
2051
2052                                 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2053                                         ec.IsLastStatement = true;
2054                                 else
2055                                         ec.IsLastStatement = false;
2056
2057                                 s.Emit (ec);
2058                         }
2059                 }
2060
2061                 public override void Emit (EmitContext ec)
2062                 {
2063                         Block prev_block = ec.CurrentBlock;
2064
2065                         ec.CurrentBlock = this;
2066
2067                         bool emit_debug_info = (CodeGen.SymbolWriter != null);
2068                         bool is_lexical_block = !Implicit && (Parent != null);
2069
2070                         if (emit_debug_info) {
2071                                 if (is_lexical_block)
2072                                         ec.BeginScope ();
2073
2074                                 if (variables != null) {
2075                                         foreach (DictionaryEntry de in variables) {
2076                                                 string name = (string) de.Key;
2077                                                 LocalInfo vi = (LocalInfo) de.Value;
2078
2079                                                 if (vi.LocalBuilder == null)
2080                                                         continue;
2081
2082                                                 ec.DefineLocalVariable (name, vi.LocalBuilder);
2083                                         }
2084                                 }
2085                         }
2086
2087                         ec.Mark (StartLocation, true);
2088                         DoEmit (ec);
2089                         ec.Mark (EndLocation, true); 
2090
2091                         if (emit_debug_info && is_lexical_block)
2092                                 ec.EndScope ();
2093
2094                         ec.CurrentBlock = prev_block;
2095                 }
2096
2097                 //
2098                 // Returns true if we ar ea child of `b'.
2099                 //
2100                 public bool IsChildOf (Block b)
2101                 {
2102                         Block current = this;
2103                         
2104                         do {
2105                                 if (current.Parent == b)
2106                                         return true;
2107                                 current = current.Parent;
2108                         } while (current != null);
2109                         return false;
2110                 }
2111
2112                 public override string ToString ()
2113                 {
2114                         return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2115                 }
2116         }
2117
2118         //
2119         // A toplevel block contains extra information, the split is done
2120         // only to separate information that would otherwise bloat the more
2121         // lightweight Block.
2122         //
2123         // In particular, this was introduced when the support for Anonymous
2124         // Methods was implemented. 
2125         // 
2126         public class ToplevelBlock : Block {
2127                 //
2128                 // Pointer to the host of this anonymous method, or null
2129                 // if we are the topmost block
2130                 //
2131                 public ToplevelBlock Container;
2132                 CaptureContext capture_context;
2133                 FlowBranching top_level_branching;
2134
2135                 Hashtable capture_contexts;
2136
2137                 //
2138                 // The parameters for the block.
2139                 //
2140                 public readonly Parameters Parameters;
2141                         
2142                 public void RegisterCaptureContext (CaptureContext cc)
2143                 {
2144                         if (capture_contexts == null)
2145                                 capture_contexts = new Hashtable ();
2146                         capture_contexts [cc] = cc;
2147                 }
2148
2149                 public void CompleteContexts ()
2150                 {
2151                         if (capture_contexts == null)
2152                                 return;
2153
2154                         foreach (CaptureContext cc in capture_contexts.Keys){
2155                                 cc.AdjustScopes ();
2156                         }
2157                 }
2158                 
2159                 public CaptureContext ToplevelBlockCaptureContext {
2160                         get {
2161                                 return capture_context;
2162                         }
2163                 }
2164                 
2165                 //
2166                 // Parent is only used by anonymous blocks to link back to their
2167                 // parents
2168                 //
2169                 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2170                         this (container, (Flags) 0, parameters, start)
2171                 {
2172                 }
2173                 
2174                 public ToplevelBlock (Parameters parameters, Location start) :
2175                         this (null, (Flags) 0, parameters, start)
2176                 {
2177                 }
2178
2179                 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2180                         this (null, flags, parameters, start)
2181                 {
2182                 }
2183
2184                 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2185                         base (null, flags | Flags.IsToplevel, start, Location.Null)
2186                 {
2187                         Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2188                         Container = container;
2189                 }
2190
2191                 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2192                 {
2193                 }
2194
2195                 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2196                 {
2197                         if (capture_context == null)
2198                                 capture_context = new CaptureContext (this, loc, host);
2199                 }
2200
2201                 public CaptureContext CaptureContext {
2202                         get {
2203                                 return capture_context;
2204                         }
2205                 }
2206
2207                 public FlowBranching TopLevelBranching {
2208                         get {
2209                                 return top_level_branching;
2210                         }
2211                 }
2212
2213                 //
2214                 // Returns a `ParameterReference' for the given name, or null if there
2215                 // is no such parameter
2216                 //
2217                 public ParameterReference GetParameterReference (string name, Location loc)
2218                 {
2219                         Parameter par;
2220                         int idx;
2221
2222                         for (ToplevelBlock t = this; t != null; t = t.Container) {
2223                                 Parameters pars = t.Parameters;
2224                                 par = pars.GetParameterByName (name, out idx);
2225                                 if (par != null)
2226                                         return new ParameterReference (pars, this, idx, name, loc);
2227                         }
2228                         return null;
2229                 }
2230
2231                 //
2232                 // Whether the parameter named `name' is local to this block, 
2233                 // or false, if the parameter belongs to an encompassing block.
2234                 //
2235                 public bool IsLocalParameter (string name)
2236                 {
2237                         return Parameters.GetParameterByName (name) != null;
2238                 }
2239                 
2240                 //
2241                 // Whether the `name' is a parameter reference
2242                 //
2243                 public bool IsParameterReference (string name)
2244                 {
2245                         for (ToplevelBlock t = this; t != null; t = t.Container) {
2246                                 if (t.IsLocalParameter (name))
2247                                         return true;
2248                         }
2249                         return false;
2250                 }
2251
2252                 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2253                 {
2254                         int errors = Report.Errors;
2255
2256                         if (top_level_branching != null)
2257                                 return true;
2258
2259                         ResolveMeta (this, ec, ip);
2260
2261                         top_level_branching = ec.StartFlowBranching (this);
2262
2263                         return Report.Errors == errors;
2264                 }
2265         }
2266         
2267         public class SwitchLabel {
2268                 Expression label;
2269                 object converted;
2270                 public Location loc;
2271
2272                 Label il_label;
2273                 bool  il_label_set;
2274                 Label il_label_code;
2275                 bool  il_label_code_set;
2276
2277                 //
2278                 // if expr == null, then it is the default case.
2279                 //
2280                 public SwitchLabel (Expression expr, Location l)
2281                 {
2282                         label = expr;
2283                         loc = l;
2284                 }
2285
2286                 public Expression Label {
2287                         get {
2288                                 return label;
2289                         }
2290                 }
2291
2292                 public object Converted {
2293                         get {
2294                                 return converted;
2295                         }
2296                 }
2297
2298                 public Label GetILLabel (EmitContext ec)
2299                 {
2300                         if (!il_label_set){
2301                                 il_label = ec.ig.DefineLabel ();
2302                                 il_label_set = true;
2303                         }
2304                         return il_label;
2305                 }
2306
2307                 public Label GetILLabelCode (EmitContext ec)
2308                 {
2309                         if (!il_label_code_set){
2310                                 il_label_code = ec.ig.DefineLabel ();
2311                                 il_label_code_set = true;
2312                         }
2313                         return il_label_code;
2314                 }                               
2315                 
2316                 //
2317                 // Resolves the expression, reduces it to a literal if possible
2318                 // and then converts it to the requested type.
2319                 //
2320                 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2321                 {
2322                         if (label == null)
2323                                 return true;
2324                         
2325                         Expression e = label.Resolve (ec);
2326
2327                         if (e == null)
2328                                 return false;
2329
2330                         if (!(e is Constant)){
2331                                 Report.Error (150, loc, "A constant value is expected, got: " + e);
2332                                 return false;
2333                         }
2334
2335                         if (e is StringConstant || e is NullLiteral){
2336                                 if (required_type == TypeManager.string_type){
2337                                         converted = e;
2338                                         return true;
2339                                 }
2340                         }
2341
2342                         converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2343                         if (converted == null)
2344                                 return false;
2345
2346                         return true;
2347                 }
2348         }
2349
2350         public class SwitchSection {
2351                 // An array of SwitchLabels.
2352                 public readonly ArrayList Labels;
2353                 public readonly Block Block;
2354                 
2355                 public SwitchSection (ArrayList labels, Block block)
2356                 {
2357                         Labels = labels;
2358                         Block = block;
2359                 }
2360         }
2361         
2362         public class Switch : Statement {
2363                 public readonly ArrayList Sections;
2364                 public Expression Expr;
2365
2366                 /// <summary>
2367                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
2368                 /// </summary>
2369                 public Hashtable Elements;
2370
2371                 /// <summary>
2372                 ///   The governing switch type
2373                 /// </summary>
2374                 public Type SwitchType;
2375
2376                 //
2377                 // Computed
2378                 //
2379                 Label default_target;
2380                 Expression new_expr;
2381                 bool is_constant;
2382                 SwitchSection constant_section;
2383                 SwitchSection default_section;
2384
2385                 //
2386                 // The types allowed to be implicitly cast from
2387                 // on the governing type
2388                 //
2389                 static Type [] allowed_types;
2390                 
2391                 public Switch (Expression e, ArrayList sects, Location l)
2392                 {
2393                         Expr = e;
2394                         Sections = sects;
2395                         loc = l;
2396                 }
2397
2398                 public bool GotDefault {
2399                         get {
2400                                 return default_section != null;
2401                         }
2402                 }
2403
2404                 public Label DefaultTarget {
2405                         get {
2406                                 return default_target;
2407                         }
2408                 }
2409
2410                 //
2411                 // Determines the governing type for a switch.  The returned
2412                 // expression might be the expression from the switch, or an
2413                 // expression that includes any potential conversions to the
2414                 // integral types or to string.
2415                 //
2416                 Expression SwitchGoverningType (EmitContext ec, Type t)
2417                 {
2418                         if (t == TypeManager.int32_type ||
2419                             t == TypeManager.uint32_type ||
2420                             t == TypeManager.char_type ||
2421                             t == TypeManager.byte_type ||
2422                             t == TypeManager.sbyte_type ||
2423                             t == TypeManager.ushort_type ||
2424                             t == TypeManager.short_type ||
2425                             t == TypeManager.uint64_type ||
2426                             t == TypeManager.int64_type ||
2427                             t == TypeManager.string_type ||
2428                                 t == TypeManager.bool_type ||
2429                                 t.IsSubclassOf (TypeManager.enum_type))
2430                                 return Expr;
2431
2432                         if (allowed_types == null){
2433                                 allowed_types = new Type [] {
2434                                         TypeManager.int32_type,
2435                                         TypeManager.uint32_type,
2436                                         TypeManager.sbyte_type,
2437                                         TypeManager.byte_type,
2438                                         TypeManager.short_type,
2439                                         TypeManager.ushort_type,
2440                                         TypeManager.int64_type,
2441                                         TypeManager.uint64_type,
2442                                         TypeManager.char_type,
2443                                         TypeManager.bool_type,
2444                                         TypeManager.string_type
2445                                 };
2446                         }
2447
2448                         //
2449                         // Try to find a *user* defined implicit conversion.
2450                         //
2451                         // If there is no implicit conversion, or if there are multiple
2452                         // conversions, we have to report an error
2453                         //
2454                         Expression converted = null;
2455                         foreach (Type tt in allowed_types){
2456                                 Expression e;
2457                                 
2458                                 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2459                                 if (e == null)
2460                                         continue;
2461
2462                                 //
2463                                 // Ignore over-worked ImplicitUserConversions that do
2464                                 // an implicit conversion in addition to the user conversion.
2465                                 // 
2466                                 if (e is UserCast){
2467                                         UserCast ue = e as UserCast;
2468
2469                                         if (ue.Source != Expr)
2470                                                 e = null;
2471                                 }
2472                                 
2473                                 if (converted != null){
2474                                         Report.ExtraInformation (
2475                                                 loc,
2476                                                 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2477                                                                TypeManager.CSharpName (Expr.Type)));
2478                                         return null;
2479                                 } else {
2480                                         converted = e;
2481                                 }
2482                         }
2483                         return converted;
2484                 }
2485
2486                 static string Error152 {
2487                         get {
2488                                 return "The label '{0}:' already occurs in this switch statement";
2489                         }
2490                 }
2491                 
2492                 //
2493                 // Performs the basic sanity checks on the switch statement
2494                 // (looks for duplicate keys and non-constant expressions).
2495                 //
2496                 // It also returns a hashtable with the keys that we will later
2497                 // use to compute the switch tables
2498                 //
2499                 bool CheckSwitch (EmitContext ec)
2500                 {
2501                         Type compare_type;
2502                         bool error = false;
2503                         Elements = new Hashtable ();
2504                                 
2505                         if (TypeManager.IsEnumType (SwitchType)){
2506                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2507                         } else
2508                                 compare_type = SwitchType;
2509                         
2510                         foreach (SwitchSection ss in Sections){
2511                                 foreach (SwitchLabel sl in ss.Labels){
2512                                         if (!sl.ResolveAndReduce (ec, SwitchType)){
2513                                                 error = true;
2514                                                 continue;
2515                                         }
2516
2517                                         if (sl.Label == null){
2518                                                 if (default_section != null){
2519                                                         Report.Error (152, sl.loc, Error152, "default");
2520                                                         error = true;
2521                                                 }
2522                                                 default_section = ss;
2523                                                 continue;
2524                                         }
2525                                         
2526                                         object key = sl.Converted;
2527
2528                                         if (key is Constant)
2529                                                 key = ((Constant) key).GetValue ();
2530
2531                                         if (key == null)
2532                                                 key = NullLiteral.Null;
2533                                         
2534                                         string lname = null;
2535                                         if (compare_type == TypeManager.uint64_type){
2536                                                 ulong v = (ulong) key;
2537
2538                                                 if (Elements.Contains (v))
2539                                                         lname = v.ToString ();
2540                                                 else
2541                                                         Elements.Add (v, sl);
2542                                         } else if (compare_type == TypeManager.int64_type){
2543                                                 long v = (long) key;
2544
2545                                                 if (Elements.Contains (v))
2546                                                         lname = v.ToString ();
2547                                                 else
2548                                                         Elements.Add (v, sl);
2549                                         } else if (compare_type == TypeManager.uint32_type){
2550                                                 uint v = (uint) key;
2551
2552                                                 if (Elements.Contains (v))
2553                                                         lname = v.ToString ();
2554                                                 else
2555                                                         Elements.Add (v, sl);
2556                                         } else if (compare_type == TypeManager.char_type){
2557                                                 char v = (char) key;
2558                                                 
2559                                                 if (Elements.Contains (v))
2560                                                         lname = v.ToString ();
2561                                                 else
2562                                                         Elements.Add (v, sl);
2563                                         } else if (compare_type == TypeManager.byte_type){
2564                                                 byte v = (byte) key;
2565                                                 
2566                                                 if (Elements.Contains (v))
2567                                                         lname = v.ToString ();
2568                                                 else
2569                                                         Elements.Add (v, sl);
2570                                         } else if (compare_type == TypeManager.sbyte_type){
2571                                                 sbyte v = (sbyte) key;
2572                                                 
2573                                                 if (Elements.Contains (v))
2574                                                         lname = v.ToString ();
2575                                                 else
2576                                                         Elements.Add (v, sl);
2577                                         } else if (compare_type == TypeManager.short_type){
2578                                                 short v = (short) key;
2579                                                 
2580                                                 if (Elements.Contains (v))
2581                                                         lname = v.ToString ();
2582                                                 else
2583                                                         Elements.Add (v, sl);
2584                                         } else if (compare_type == TypeManager.ushort_type){
2585                                                 ushort v = (ushort) key;
2586                                                 
2587                                                 if (Elements.Contains (v))
2588                                                         lname = v.ToString ();
2589                                                 else
2590                                                         Elements.Add (v, sl);
2591                                         } else if (compare_type == TypeManager.string_type){
2592                                                 if (key is NullLiteral){
2593                                                         if (Elements.Contains (NullLiteral.Null))
2594                                                                 lname = "null";
2595                                                         else
2596                                                                 Elements.Add (NullLiteral.Null, null);
2597                                                 } else {
2598                                                         string s = (string) key;
2599
2600                                                         if (Elements.Contains (s))
2601                                                                 lname = s;
2602                                                         else
2603                                                                 Elements.Add (s, sl);
2604                                                 }
2605                                         } else if (compare_type == TypeManager.int32_type) {
2606                                                 int v = (int) key;
2607
2608                                                 if (Elements.Contains (v))
2609                                                         lname = v.ToString ();
2610                                                 else
2611                                                         Elements.Add (v, sl);
2612                                         } else if (compare_type == TypeManager.bool_type) {
2613                                                 bool v = (bool) key;
2614
2615                                                 if (Elements.Contains (v))
2616                                                         lname = v.ToString ();
2617                                                 else
2618                                                         Elements.Add (v, sl);
2619                                         }
2620                                         else
2621                                         {
2622                                                 throw new Exception ("Unknown switch type!" +
2623                                                                      SwitchType + " " + compare_type);
2624                                         }
2625
2626                                         if (lname != null){
2627                                                 Report.Error (152, sl.loc, Error152, "case " + lname);
2628                                                 error = true;
2629                                         }
2630                                 }
2631                         }
2632                         if (error)
2633                                 return false;
2634                         
2635                         return true;
2636                 }
2637
2638                 void EmitObjectInteger (ILGenerator ig, object k)
2639                 {
2640                         if (k is int)
2641                                 IntConstant.EmitInt (ig, (int) k);
2642                         else if (k is Constant) {
2643                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2644                         } 
2645                         else if (k is uint)
2646                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2647                         else if (k is long)
2648                         {
2649                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2650                                 {
2651                                         IntConstant.EmitInt (ig, (int) (long) k);
2652                                         ig.Emit (OpCodes.Conv_I8);
2653                                 }
2654                                 else
2655                                         LongConstant.EmitLong (ig, (long) k);
2656                         }
2657                         else if (k is ulong)
2658                         {
2659                                 if ((ulong) k < (1L<<32))
2660                                 {
2661                                         IntConstant.EmitInt (ig, (int) (long) k);
2662                                         ig.Emit (OpCodes.Conv_U8);
2663                                 }
2664                                 else
2665                                 {
2666                                         LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2667                                 }
2668                         }
2669                         else if (k is char)
2670                                 IntConstant.EmitInt (ig, (int) ((char) k));
2671                         else if (k is sbyte)
2672                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2673                         else if (k is byte)
2674                                 IntConstant.EmitInt (ig, (int) ((byte) k));
2675                         else if (k is short)
2676                                 IntConstant.EmitInt (ig, (int) ((short) k));
2677                         else if (k is ushort)
2678                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
2679                         else if (k is bool)
2680                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2681                         else
2682                                 throw new Exception ("Unhandled case");
2683                 }
2684                 
2685                 // structure used to hold blocks of keys while calculating table switch
2686                 class KeyBlock : IComparable
2687                 {
2688                         public KeyBlock (long _nFirst)
2689                         {
2690                                 nFirst = nLast = _nFirst;
2691                         }
2692                         public long nFirst;
2693                         public long nLast;
2694                         public ArrayList rgKeys = null;
2695                         // how many items are in the bucket
2696                         public int Size = 1;
2697                         public int Length
2698                         {
2699                                 get { return (int) (nLast - nFirst + 1); }
2700                         }
2701                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2702                         {
2703                                 return kbLast.nLast - kbFirst.nFirst + 1;
2704                         }
2705                         public int CompareTo (object obj)
2706                         {
2707                                 KeyBlock kb = (KeyBlock) obj;
2708                                 int nLength = Length;
2709                                 int nLengthOther = kb.Length;
2710                                 if (nLengthOther == nLength)
2711                                         return (int) (kb.nFirst - nFirst);
2712                                 return nLength - nLengthOther;
2713                         }
2714                 }
2715
2716                 /// <summary>
2717                 /// This method emits code for a lookup-based switch statement (non-string)
2718                 /// Basically it groups the cases into blocks that are at least half full,
2719                 /// and then spits out individual lookup opcodes for each block.
2720                 /// It emits the longest blocks first, and short blocks are just
2721                 /// handled with direct compares.
2722                 /// </summary>
2723                 /// <param name="ec"></param>
2724                 /// <param name="val"></param>
2725                 /// <returns></returns>
2726                 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2727                 {
2728                         int cElements = Elements.Count;
2729                         object [] rgKeys = new object [cElements];
2730                         Elements.Keys.CopyTo (rgKeys, 0);
2731                         Array.Sort (rgKeys);
2732
2733                         // initialize the block list with one element per key
2734                         ArrayList rgKeyBlocks = new ArrayList ();
2735                         foreach (object key in rgKeys)
2736                                 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2737
2738                         KeyBlock kbCurr;
2739                         // iteratively merge the blocks while they are at least half full
2740                         // there's probably a really cool way to do this with a tree...
2741                         while (rgKeyBlocks.Count > 1)
2742                         {
2743                                 ArrayList rgKeyBlocksNew = new ArrayList ();
2744                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2745                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2746                                 {
2747                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2748                                         if ((kbCurr.Size + kb.Size) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
2749                                         {
2750                                                 // merge blocks
2751                                                 kbCurr.nLast = kb.nLast;
2752                                                 kbCurr.Size += kb.Size;
2753                                         }
2754                                         else
2755                                         {
2756                                                 // start a new block
2757                                                 rgKeyBlocksNew.Add (kbCurr);
2758                                                 kbCurr = kb;
2759                                         }
2760                                 }
2761                                 rgKeyBlocksNew.Add (kbCurr);
2762                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2763                                         break;
2764                                 rgKeyBlocks = rgKeyBlocksNew;
2765                         }
2766
2767                         // initialize the key lists
2768                         foreach (KeyBlock kb in rgKeyBlocks)
2769                                 kb.rgKeys = new ArrayList ();
2770
2771                         // fill the key lists
2772                         int iBlockCurr = 0;
2773                         if (rgKeyBlocks.Count > 0) {
2774                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2775                                 foreach (object key in rgKeys)
2776                                 {
2777                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2778                                                 System.Convert.ToInt64 (key) > kbCurr.nLast;
2779                                         if (fNextBlock)
2780                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2781                                         kbCurr.rgKeys.Add (key);
2782                                 }
2783                         }
2784
2785                         // sort the blocks so we can tackle the largest ones first
2786                         rgKeyBlocks.Sort ();
2787
2788                         // okay now we can start...
2789                         ILGenerator ig = ec.ig;
2790                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
2791                         Label lblDefault = ig.DefineLabel ();
2792
2793                         Type typeKeys = null;
2794                         if (rgKeys.Length > 0)
2795                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
2796
2797                         Type compare_type;
2798                         
2799                         if (TypeManager.IsEnumType (SwitchType))
2800                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2801                         else
2802                                 compare_type = SwitchType;
2803                         
2804                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2805                         {
2806                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2807                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2808                                 if (kb.Length <= 2)
2809                                 {
2810                                         foreach (object key in kb.rgKeys)
2811                                         {
2812                                                 ig.Emit (OpCodes.Ldloc, val);
2813                                                 EmitObjectInteger (ig, key);
2814                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
2815                                                 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2816                                         }
2817                                 }
2818                                 else
2819                                 {
2820                                         // TODO: if all the keys in the block are the same and there are
2821                                         //       no gaps/defaults then just use a range-check.
2822                                         if (compare_type == TypeManager.int64_type ||
2823                                                 compare_type == TypeManager.uint64_type)
2824                                         {
2825                                                 // TODO: optimize constant/I4 cases
2826
2827                                                 // check block range (could be > 2^31)
2828                                                 ig.Emit (OpCodes.Ldloc, val);
2829                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2830                                                 ig.Emit (OpCodes.Blt, lblDefault);
2831                                                 ig.Emit (OpCodes.Ldloc, val);
2832                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2833                                                 ig.Emit (OpCodes.Bgt, lblDefault);
2834
2835                                                 // normalize range
2836                                                 ig.Emit (OpCodes.Ldloc, val);
2837                                                 if (kb.nFirst != 0)
2838                                                 {
2839                                                         EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2840                                                         ig.Emit (OpCodes.Sub);
2841                                                 }
2842                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
2843                                         }
2844                                         else
2845                                         {
2846                                                 // normalize range
2847                                                 ig.Emit (OpCodes.Ldloc, val);
2848                                                 int nFirst = (int) kb.nFirst;
2849                                                 if (nFirst > 0)
2850                                                 {
2851                                                         IntConstant.EmitInt (ig, nFirst);
2852                                                         ig.Emit (OpCodes.Sub);
2853                                                 }
2854                                                 else if (nFirst < 0)
2855                                                 {
2856                                                         IntConstant.EmitInt (ig, -nFirst);
2857                                                         ig.Emit (OpCodes.Add);
2858                                                 }
2859                                         }
2860
2861                                         // first, build the list of labels for the switch
2862                                         int iKey = 0;
2863                                         int cJumps = kb.Length;
2864                                         Label [] rgLabels = new Label [cJumps];
2865                                         for (int iJump = 0; iJump < cJumps; iJump++)
2866                                         {
2867                                                 object key = kb.rgKeys [iKey];
2868                                                 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2869                                                 {
2870                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
2871                                                         rgLabels [iJump] = sl.GetILLabel (ec);
2872                                                         iKey++;
2873                                                 }
2874                                                 else
2875                                                         rgLabels [iJump] = lblDefault;
2876                                         }
2877                                         // emit the switch opcode
2878                                         ig.Emit (OpCodes.Switch, rgLabels);
2879                                 }
2880
2881                                 // mark the default for this block
2882                                 if (iBlock != 0)
2883                                         ig.MarkLabel (lblDefault);
2884                         }
2885
2886                         // TODO: find the default case and emit it here,
2887                         //       to prevent having to do the following jump.
2888                         //       make sure to mark other labels in the default section
2889
2890                         // the last default just goes to the end
2891                         ig.Emit (OpCodes.Br, lblDefault);
2892
2893                         // now emit the code for the sections
2894                         bool fFoundDefault = false;
2895                         foreach (SwitchSection ss in Sections)
2896                         {
2897                                 foreach (SwitchLabel sl in ss.Labels)
2898                                 {
2899                                         ig.MarkLabel (sl.GetILLabel (ec));
2900                                         ig.MarkLabel (sl.GetILLabelCode (ec));
2901                                         if (sl.Label == null)
2902                                         {
2903                                                 ig.MarkLabel (lblDefault);
2904                                                 fFoundDefault = true;
2905                                         }
2906                                 }
2907                                 ss.Block.Emit (ec);
2908                                 //ig.Emit (OpCodes.Br, lblEnd);
2909                         }
2910                         
2911                         if (!fFoundDefault) {
2912                                 ig.MarkLabel (lblDefault);
2913                         }
2914                         ig.MarkLabel (lblEnd);
2915                 }
2916                 //
2917                 // This simple emit switch works, but does not take advantage of the
2918                 // `switch' opcode. 
2919                 // TODO: remove non-string logic from here
2920                 // TODO: binary search strings?
2921                 //
2922                 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2923                 {
2924                         ILGenerator ig = ec.ig;
2925                         Label end_of_switch = ig.DefineLabel ();
2926                         Label next_test = ig.DefineLabel ();
2927                         Label null_target = ig.DefineLabel ();
2928                         bool first_test = true;
2929                         bool pending_goto_end = false;
2930                         bool null_marked = false;
2931                         bool null_found;
2932
2933                         ig.Emit (OpCodes.Ldloc, val);
2934                         
2935                         if (Elements.Contains (NullLiteral.Null)){
2936                                 ig.Emit (OpCodes.Brfalse, null_target);
2937                         } else
2938                                 ig.Emit (OpCodes.Brfalse, default_target);
2939                         
2940                         ig.Emit (OpCodes.Ldloc, val);
2941                         ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2942                         ig.Emit (OpCodes.Stloc, val);
2943
2944                         int section_count = Sections.Count;
2945                         for (int section = 0; section < section_count; section++){
2946                                 SwitchSection ss = (SwitchSection) Sections [section];
2947
2948                                 if (ss == default_section)
2949                                         continue;
2950
2951                                 Label sec_begin = ig.DefineLabel ();
2952
2953                                 ig.Emit (OpCodes.Nop);
2954
2955                                 if (pending_goto_end)
2956                                         ig.Emit (OpCodes.Br, end_of_switch);
2957
2958                                 int label_count = ss.Labels.Count;
2959                                 null_found = false;
2960                                 for (int label = 0; label < label_count; label++){
2961                                         SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2962                                         ig.MarkLabel (sl.GetILLabel (ec));
2963                                         
2964                                         if (!first_test){
2965                                                 ig.MarkLabel (next_test);
2966                                                 next_test = ig.DefineLabel ();
2967                                         }
2968                                         //
2969                                         // If we are the default target
2970                                         //
2971                                         if (sl.Label != null){
2972                                                 object lit = sl.Converted;
2973
2974                                                 if (lit is NullLiteral){
2975                                                         null_found = true;
2976                                                         if (label_count == 1)
2977                                                                 ig.Emit (OpCodes.Br, next_test);
2978                                                         continue;
2979                                                                               
2980                                                 }
2981                                                 StringConstant str = (StringConstant) lit;
2982                                                 
2983                                                 ig.Emit (OpCodes.Ldloc, val);
2984                                                 ig.Emit (OpCodes.Ldstr, str.Value);
2985                                                 if (label_count == 1)
2986                                                         ig.Emit (OpCodes.Bne_Un, next_test);
2987                                                 else {
2988                                                         if (label+1 == label_count)
2989                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
2990                                                         else
2991                                                                 ig.Emit (OpCodes.Beq, sec_begin);
2992                                                 }
2993                                         }
2994                                 }
2995                                 if (null_found) {
2996                                         ig.MarkLabel (null_target);
2997                                         null_marked = true;
2998                                 }
2999                                 ig.MarkLabel (sec_begin);
3000                                 foreach (SwitchLabel sl in ss.Labels)
3001                                         ig.MarkLabel (sl.GetILLabelCode (ec));
3002
3003                                 ss.Block.Emit (ec);
3004                                 pending_goto_end = !ss.Block.HasRet;
3005                                 first_test = false;
3006                         }
3007                         ig.MarkLabel (next_test);
3008                         ig.MarkLabel (default_target);
3009                         if (!null_marked)
3010                                 ig.MarkLabel (null_target);
3011                         if (default_section != null)
3012                                 default_section.Block.Emit (ec);
3013                         ig.MarkLabel (end_of_switch);
3014                 }
3015
3016                 SwitchSection FindSection (SwitchLabel label)
3017                 {
3018                         foreach (SwitchSection ss in Sections){
3019                                 foreach (SwitchLabel sl in ss.Labels){
3020                                         if (label == sl)
3021                                                 return ss;
3022                                 }
3023                         }
3024
3025                         return null;
3026                 }
3027
3028                 public override bool Resolve (EmitContext ec)
3029                 {
3030                         Expr = Expr.Resolve (ec);
3031                         if (Expr == null)
3032                                 return false;
3033
3034                         new_expr = SwitchGoverningType (ec, Expr.Type);
3035                         if (new_expr == null){
3036                                 Report.Error (151, loc, "An integer type or string was expected for switch");
3037                                 return false;
3038                         }
3039
3040                         // Validate switch.
3041                         SwitchType = new_expr.Type;
3042
3043                         if (!CheckSwitch (ec))
3044                                 return false;
3045
3046                         Switch old_switch = ec.Switch;
3047                         ec.Switch = this;
3048                         ec.Switch.SwitchType = SwitchType;
3049
3050                         Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3051                         ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3052
3053                         is_constant = new_expr is Constant;
3054                         if (is_constant) {
3055                                 object key = ((Constant) new_expr).GetValue ();
3056                                 SwitchLabel label = (SwitchLabel) Elements [key];
3057
3058                                 constant_section = FindSection (label);
3059                                 if (constant_section == null)
3060                                         constant_section = default_section;
3061                         }
3062
3063                         bool first = true;
3064                         foreach (SwitchSection ss in Sections){
3065                                 if (!first)
3066                                         ec.CurrentBranching.CreateSibling (
3067                                                 null, FlowBranching.SiblingType.SwitchSection);
3068                                 else
3069                                         first = false;
3070
3071                                 if (is_constant && (ss != constant_section)) {
3072                                         // If we're a constant switch, we're only emitting
3073                                         // one single section - mark all the others as
3074                                         // unreachable.
3075                                         ec.CurrentBranching.CurrentUsageVector.Goto ();
3076                                         if (!ss.Block.ResolveUnreachable (ec, true))
3077                                                 return false;
3078                                 } else {
3079                                         if (!ss.Block.Resolve (ec))
3080                                                 return false;
3081                         }
3082                         }
3083
3084                         if (default_section == null)
3085                                 ec.CurrentBranching.CreateSibling (
3086                                         null, FlowBranching.SiblingType.SwitchSection);
3087
3088                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3089                         ec.Switch = old_switch;
3090
3091                         Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3092                                       reachability);
3093
3094                         return true;
3095                 }
3096                 
3097                 protected override void DoEmit (EmitContext ec)
3098                 {
3099                         ILGenerator ig = ec.ig;
3100
3101                         // Store variable for comparission purposes
3102                         LocalBuilder value;
3103                         if (!is_constant) {
3104                                 value = ig.DeclareLocal (SwitchType);
3105                         new_expr.Emit (ec);
3106                                 ig.Emit (OpCodes.Stloc, value);
3107                         } else
3108                                 value = null;
3109
3110                         default_target = ig.DefineLabel ();
3111
3112                         //
3113                         // Setup the codegen context
3114                         //
3115                         Label old_end = ec.LoopEnd;
3116                         Switch old_switch = ec.Switch;
3117                         
3118                         ec.LoopEnd = ig.DefineLabel ();
3119                         ec.Switch = this;
3120
3121                         // Emit Code.
3122                         if (is_constant) {
3123                                 if (constant_section != null)
3124                                         constant_section.Block.Emit (ec);
3125                         } else if (SwitchType == TypeManager.string_type)
3126                                 SimpleSwitchEmit (ec, value);
3127                         else
3128                                 TableSwitchEmit (ec, value);
3129
3130                         // Restore context state. 
3131                         ig.MarkLabel (ec.LoopEnd);
3132
3133                         //
3134                         // Restore the previous context
3135                         //
3136                         ec.LoopEnd = old_end;
3137                         ec.Switch = old_switch;
3138                 }
3139         }
3140
3141         public abstract class ExceptionStatement : Statement
3142         {
3143                 public abstract void EmitFinally (EmitContext ec);
3144
3145                 protected bool emit_finally = true;
3146                 ArrayList parent_vectors;
3147
3148                 protected void DoEmitFinally (EmitContext ec)
3149                 {
3150                         if (emit_finally)
3151                                 ec.ig.BeginFinallyBlock ();
3152                         else if (ec.InIterator)
3153                                 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3154                         EmitFinally (ec);
3155                 }
3156
3157                 protected void ResolveFinally (FlowBranchingException branching)
3158                 {
3159                         emit_finally = branching.EmitFinally;
3160                         if (!emit_finally)
3161                                 branching.Parent.StealFinallyClauses (ref parent_vectors);
3162                 }
3163         }
3164
3165         public class Lock : ExceptionStatement {
3166                 Expression expr;
3167                 Statement Statement;
3168                 LocalBuilder temp;
3169                         
3170                 public Lock (Expression expr, Statement stmt, Location l)
3171                 {
3172                         this.expr = expr;
3173                         Statement = stmt;
3174                         loc = l;
3175                 }
3176
3177                 public override bool Resolve (EmitContext ec)
3178                 {
3179                         expr = expr.Resolve (ec);
3180                         if (expr == null)
3181                                 return false;
3182
3183                         if (expr.Type.IsValueType){
3184                                 Error (185, "lock statement requires the expression to be " +
3185                                        " a reference type (type is: `{0}'",
3186                                        TypeManager.CSharpName (expr.Type));
3187                                 return false;
3188                         }
3189
3190                         FlowBranchingException branching = ec.StartFlowBranching (this);
3191                         bool ok = Statement.Resolve (ec);
3192                         if (!ok) {
3193                                 ec.KillFlowBranching ();
3194                                 return false;
3195                         }
3196
3197                         ResolveFinally (branching);
3198
3199                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3200                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3201                                 // Unfortunately, System.Reflection.Emit automatically emits
3202                                 // a leave to the end of the finally block.
3203                                 // This is a problem if `returns' is true since we may jump
3204                                 // to a point after the end of the method.
3205                                 // As a workaround, emit an explicit ret here.
3206                                 ec.NeedReturnLabel ();
3207                         }
3208
3209                         return true;
3210                 }
3211                 
3212                 protected override void DoEmit (EmitContext ec)
3213                 {
3214                         Type type = expr.Type;
3215                         
3216                         ILGenerator ig = ec.ig;
3217                         temp = ig.DeclareLocal (type);
3218                                 
3219                         expr.Emit (ec);
3220                         ig.Emit (OpCodes.Dup);
3221                         ig.Emit (OpCodes.Stloc, temp);
3222                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3223
3224                         // try
3225                         if (emit_finally)
3226                                 ig.BeginExceptionBlock ();
3227                         Statement.Emit (ec);
3228                         
3229                         // finally
3230                         DoEmitFinally (ec);
3231                         if (emit_finally)
3232                                 ig.EndExceptionBlock ();
3233                 }
3234
3235                 public override void EmitFinally (EmitContext ec)
3236                 {
3237                         ILGenerator ig = ec.ig;
3238                         ig.Emit (OpCodes.Ldloc, temp);
3239                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3240                 }
3241         }
3242
3243         public class Unchecked : Statement {
3244                 public readonly Block Block;
3245                 
3246                 public Unchecked (Block b)
3247                 {
3248                         Block = b;
3249                         b.Unchecked = true;
3250                 }
3251
3252                 public override bool Resolve (EmitContext ec)
3253                 {
3254                         bool previous_state = ec.CheckState;
3255                         bool previous_state_const = ec.ConstantCheckState;
3256
3257                         ec.CheckState = false;
3258                         ec.ConstantCheckState = false;
3259                         bool ret = Block.Resolve (ec);
3260                         ec.CheckState = previous_state;
3261                         ec.ConstantCheckState = previous_state_const;
3262
3263                         return ret;
3264                 }
3265                 
3266                 protected override void DoEmit (EmitContext ec)
3267                 {
3268                         bool previous_state = ec.CheckState;
3269                         bool previous_state_const = ec.ConstantCheckState;
3270                         
3271                         ec.CheckState = false;
3272                         ec.ConstantCheckState = false;
3273                         Block.Emit (ec);
3274                         ec.CheckState = previous_state;
3275                         ec.ConstantCheckState = previous_state_const;
3276                 }
3277         }
3278
3279         public class Checked : Statement {
3280                 public readonly Block Block;
3281                 
3282                 public Checked (Block b)
3283                 {
3284                         Block = b;
3285                         b.Unchecked = false;
3286                 }
3287
3288                 public override bool Resolve (EmitContext ec)
3289                 {
3290                         bool previous_state = ec.CheckState;
3291                         bool previous_state_const = ec.ConstantCheckState;
3292                         
3293                         ec.CheckState = true;
3294                         ec.ConstantCheckState = true;
3295                         bool ret = Block.Resolve (ec);
3296                         ec.CheckState = previous_state;
3297                         ec.ConstantCheckState = previous_state_const;
3298
3299                         return ret;
3300                 }
3301
3302                 protected override void DoEmit (EmitContext ec)
3303                 {
3304                         bool previous_state = ec.CheckState;
3305                         bool previous_state_const = ec.ConstantCheckState;
3306                         
3307                         ec.CheckState = true;
3308                         ec.ConstantCheckState = true;
3309                         Block.Emit (ec);
3310                         ec.CheckState = previous_state;
3311                         ec.ConstantCheckState = previous_state_const;
3312                 }
3313         }
3314
3315         public class Unsafe : Statement {
3316                 public readonly Block Block;
3317
3318                 public Unsafe (Block b)
3319                 {
3320                         Block = b;
3321                         Block.Unsafe = true;
3322                 }
3323
3324                 public override bool Resolve (EmitContext ec)
3325                 {
3326                         bool previous_state = ec.InUnsafe;
3327                         bool val;
3328                         
3329                         ec.InUnsafe = true;
3330                         val = Block.Resolve (ec);
3331                         ec.InUnsafe = previous_state;
3332
3333                         return val;
3334                 }
3335                 
3336                 protected override void DoEmit (EmitContext ec)
3337                 {
3338                         bool previous_state = ec.InUnsafe;
3339                         
3340                         ec.InUnsafe = true;
3341                         Block.Emit (ec);
3342                         ec.InUnsafe = previous_state;
3343                 }
3344         }
3345
3346         // 
3347         // Fixed statement
3348         //
3349         public class Fixed : Statement {
3350                 Expression type;
3351                 ArrayList declarators;
3352                 Statement statement;
3353                 Type expr_type;
3354                 Emitter[] data;
3355                 bool has_ret;
3356
3357                 abstract class Emitter
3358                 {
3359                         protected LocalInfo vi;
3360                         protected Expression converted;
3361
3362                         protected Emitter (Expression expr, LocalInfo li)
3363                         {
3364                                 converted = expr;
3365                                 vi = li;
3366                         }
3367
3368                         public abstract void Emit (EmitContext ec);
3369                         public abstract void EmitExit (ILGenerator ig);
3370                 }
3371
3372                 class ExpressionEmitter: Emitter {
3373                         public ExpressionEmitter (Expression converted, LocalInfo li) :
3374                                 base (converted, li)
3375                         {
3376                         }
3377
3378                         public override void Emit (EmitContext ec) {
3379                                 //
3380                                 // Store pointer in pinned location
3381                                 //
3382                                 converted.Emit (ec);
3383                                 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3384                         }
3385
3386                         public override void EmitExit (ILGenerator ig)
3387                         {
3388                                 ig.Emit (OpCodes.Ldc_I4_0);
3389                                 ig.Emit (OpCodes.Conv_U);
3390                                 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3391                         }
3392                 }
3393
3394                 class StringEmitter: Emitter {
3395                         LocalBuilder pinned_string;
3396                         Location loc;
3397
3398                         public StringEmitter (Expression expr, LocalInfo li, Location loc):
3399                                 base (expr, li)
3400                         {
3401                                 this.loc = loc;
3402                         }
3403
3404                         public override void Emit (EmitContext ec)
3405                         {
3406                                 ILGenerator ig = ec.ig;
3407                                 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3408                                         
3409                                 converted.Emit (ec);
3410                                 ig.Emit (OpCodes.Stloc, pinned_string);
3411
3412                                 Expression sptr = new StringPtr (pinned_string, loc);
3413                                 converted = Convert.ImplicitConversionRequired (
3414                                         ec, sptr, vi.VariableType, loc);
3415                                         
3416                                 if (converted == null)
3417                                         return;
3418
3419                                 converted.Emit (ec);
3420                                 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3421                         }
3422
3423                         public override void EmitExit(ILGenerator ig)
3424                         {
3425                                 ig.Emit (OpCodes.Ldnull);
3426                                 ig.Emit (OpCodes.Stloc, pinned_string);
3427                         }
3428                 }
3429
3430                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3431                 {
3432                         this.type = type;
3433                         declarators = decls;
3434                         statement = stmt;
3435                         loc = l;
3436                 }
3437
3438                 public override bool Resolve (EmitContext ec)
3439                 {
3440                         if (!ec.InUnsafe){
3441                                 Expression.UnsafeError (loc);
3442                                 return false;
3443                         }
3444                         
3445                         TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3446                         if (texpr == null)
3447                                 return false;
3448
3449                         expr_type = texpr.Type;
3450
3451                         CheckObsolete (expr_type);
3452
3453                         if (ec.RemapToProxy){
3454                                 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3455                                 return false;
3456                         }
3457                         
3458                         data = new Emitter [declarators.Count];
3459
3460                         if (!expr_type.IsPointer){
3461                                 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3462                                 return false;
3463                         }
3464                         
3465                         int i = 0;
3466                         foreach (Pair p in declarators){
3467                                 LocalInfo vi = (LocalInfo) p.First;
3468                                 Expression e = (Expression) p.Second;
3469
3470                                 vi.VariableInfo.SetAssigned (ec);
3471                                 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3472
3473                                 //
3474                                 // The rules for the possible declarators are pretty wise,
3475                                 // but the production on the grammar is more concise.
3476                                 //
3477                                 // So we have to enforce these rules here.
3478                                 //
3479                                 // We do not resolve before doing the case 1 test,
3480                                 // because the grammar is explicit in that the token &
3481                                 // is present, so we need to test for this particular case.
3482                                 //
3483
3484                                 if (e is Cast){
3485                                         Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3486                                         return false;
3487                                 }
3488                                 
3489                                 //
3490                                 // Case 1: & object.
3491                                 //
3492                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3493                                         Expression child = ((Unary) e).Expr;
3494
3495                                         if (child is ParameterReference || child is LocalVariableReference){
3496                                                 Report.Error (
3497                                                         213, loc, 
3498                                                         "No need to use fixed statement for parameters or " +
3499                                                         "local variable declarations (address is already " +
3500                                                         "fixed)");
3501                                                 return false;
3502                                         }
3503
3504                                         ec.InFixedInitializer = true;
3505                                         e = e.Resolve (ec);
3506                                         ec.InFixedInitializer = false;
3507                                         if (e == null)
3508                                                 return false;
3509
3510                                         child = ((Unary) e).Expr;
3511                                         
3512                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
3513                                                 return false;
3514
3515                                         data [i] = new ExpressionEmitter (e, vi);
3516                                         i++;
3517
3518                                         continue;
3519                                 }
3520
3521                                 ec.InFixedInitializer = true;
3522                                 e = e.Resolve (ec);
3523                                 ec.InFixedInitializer = false;
3524                                 if (e == null)
3525                                         return false;
3526
3527                                 //
3528                                 // Case 2: Array
3529                                 //
3530                                 if (e.Type.IsArray){
3531                                         Type array_type = TypeManager.GetElementType (e.Type);
3532                                         
3533                                         //
3534                                         // Provided that array_type is unmanaged,
3535                                         //
3536                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
3537                                                 return false;
3538
3539                                         //
3540                                         // and T* is implicitly convertible to the
3541                                         // pointer type given in the fixed statement.
3542                                         //
3543                                         ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3544                                         
3545                                         Expression converted = Convert.ImplicitConversionRequired (
3546                                                 ec, array_ptr, vi.VariableType, loc);
3547                                         if (converted == null)
3548                                                 return false;
3549
3550                                         data [i] = new ExpressionEmitter (converted, vi);
3551                                         i++;
3552
3553                                         continue;
3554                                 }
3555
3556                                 //
3557                                 // Case 3: string
3558                                 //
3559                                 if (e.Type == TypeManager.string_type){
3560                                         data [i] = new StringEmitter (e, vi, loc);
3561                                         i++;
3562                                         continue;
3563                                 }
3564
3565                                 // Case 4: fixed buffer
3566                                 FieldExpr fe = e as FieldExpr;
3567                                 if (fe != null) {
3568                                         IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3569                                         if (ff != null) {
3570                                                 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3571                                         
3572                                                 Expression converted = Convert.ImplicitConversionRequired (
3573                                                         ec, fixed_buffer_ptr, vi.VariableType, loc);
3574                                                 if (converted == null)
3575                                                         return false;
3576
3577                                                 data [i] = new ExpressionEmitter (converted, vi);
3578                                                 i++;
3579
3580                                                 continue;
3581                                         }
3582                                 }
3583
3584                                 //
3585                                 // For other cases, flag a `this is already fixed expression'
3586                                 //
3587                                 if (e is LocalVariableReference || e is ParameterReference ||
3588                                     Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3589                                     
3590                                         Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3591                                         return false;
3592                                 }
3593
3594                                 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3595                                 return false;
3596                         }
3597
3598                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3599
3600                         if (!statement.Resolve (ec)) {
3601                                 ec.KillFlowBranching ();
3602                                 return false;
3603                         }
3604
3605                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3606                         has_ret = reachability.IsUnreachable;
3607
3608                         return true;
3609                 }
3610                 
3611                 protected override void DoEmit (EmitContext ec)
3612                 {
3613                         for (int i = 0; i < data.Length; i++) {
3614                                 data [i].Emit (ec);
3615                         }
3616
3617                         statement.Emit (ec);
3618
3619                         if (has_ret)
3620                                 return;
3621
3622                         ILGenerator ig = ec.ig;
3623
3624                         //
3625                         // Clear the pinned variable
3626                         //
3627                         for (int i = 0; i < data.Length; i++) {
3628                                 data [i].EmitExit (ig);
3629                         }
3630                 }
3631         }
3632         
3633         public class Catch: Statement {
3634                 public readonly string Name;
3635                 public readonly Block  Block;
3636
3637                 Expression type_expr;
3638                 Type type;
3639                 
3640                 public Catch (Expression type, string name, Block block, Location l)
3641                 {
3642                         type_expr = type;
3643                         Name = name;
3644                         Block = block;
3645                         loc = l;
3646                 }
3647
3648                 public Type CatchType {
3649                         get {
3650                                 return type;
3651                         }
3652                 }
3653
3654                 public bool IsGeneral {
3655                         get {
3656                                 return type_expr == null;
3657                         }
3658                 }
3659
3660                 protected override void DoEmit(EmitContext ec)
3661                 {
3662                 }
3663
3664                 public override bool Resolve (EmitContext ec)
3665                 {
3666                         bool was_catch = ec.InCatch;
3667                         ec.InCatch = true;
3668                         try {
3669                                 if (type_expr != null) {
3670                                         TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3671                                         if (te == null)
3672                                                 return false;
3673
3674                                         type = te.ResolveType (ec);
3675
3676                                         CheckObsolete (type);
3677
3678                                         if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3679                                                 Error (155, "The type caught or thrown must be derived from System.Exception");
3680                                                 return false;
3681                                         }
3682                                 } else
3683                                         type = null;
3684
3685                                 return Block.Resolve (ec);
3686                         }
3687                         finally {
3688                                 ec.InCatch = was_catch;
3689                         }
3690                 }
3691         }
3692
3693         public class Try : ExceptionStatement {
3694                 public readonly Block Fini, Block;
3695                 public readonly ArrayList Specific;
3696                 public readonly Catch General;
3697
3698                 bool need_exc_block;
3699                 
3700                 //
3701                 // specific, general and fini might all be null.
3702                 //
3703                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3704                 {
3705                         if (specific == null && general == null){
3706                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3707                         }
3708                         
3709                         this.Block = block;
3710                         this.Specific = specific;
3711                         this.General = general;
3712                         this.Fini = fini;
3713                         loc = l;
3714                 }
3715
3716                 public override bool Resolve (EmitContext ec)
3717                 {
3718                         bool ok = true;
3719                         
3720                         FlowBranchingException branching = ec.StartFlowBranching (this);
3721
3722                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3723
3724                         if (!Block.Resolve (ec))
3725                                 ok = false;
3726
3727                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3728
3729                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
3730
3731                         Type[] prevCatches = new Type [Specific.Count];
3732                         int last_index = 0;
3733                         foreach (Catch c in Specific){
3734                                 ec.CurrentBranching.CreateSibling (
3735                                         c.Block, FlowBranching.SiblingType.Catch);
3736
3737                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3738
3739                                 if (c.Name != null) {
3740                                         LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3741                                         if (vi == null)
3742                                                 throw new Exception ();
3743
3744                                         vi.VariableInfo = null;
3745                                 }
3746
3747                                 if (!c.Resolve (ec))
3748                                         return false;
3749
3750                                 Type resolvedType = c.CatchType;
3751                                 for (int ii = 0; ii < last_index; ++ii) {
3752                                         if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3753                                                 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3754                                                 return false;
3755                                         }
3756                                 }
3757
3758                                 prevCatches [last_index++] = resolvedType;
3759                                 need_exc_block = true;
3760                         }
3761
3762                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3763
3764                         if (General != null){
3765                                 ec.CurrentBranching.CreateSibling (
3766                                         General.Block, FlowBranching.SiblingType.Catch);
3767
3768                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3769
3770                                 if (!General.Resolve (ec))
3771                                         ok = false;
3772
3773                                 need_exc_block = true;
3774                         }
3775
3776                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3777
3778                         if (Fini != null) {
3779                                 if (ok)
3780                                         ec.CurrentBranching.CreateSibling (
3781                                                 Fini, FlowBranching.SiblingType.Finally);
3782
3783                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3784                                 bool was_finally = ec.InFinally;
3785                                 ec.InFinally = true;
3786                                 if (!Fini.Resolve (ec))
3787                                         ok = false;
3788                                 ec.InFinally = was_finally;
3789
3790                                 if (!ec.InIterator)
3791                                         need_exc_block = true;
3792                         }
3793
3794                         if (ec.InIterator) {
3795                                 ResolveFinally (branching);
3796                                 need_exc_block |= emit_finally;
3797                         } else
3798                                 emit_finally = Fini != null;
3799
3800                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3801
3802                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3803
3804                         Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3805
3806                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3807                                 // Unfortunately, System.Reflection.Emit automatically emits
3808                                 // a leave to the end of the finally block.  This is a problem
3809                                 // if `returns' is true since we may jump to a point after the
3810                                 // end of the method.
3811                                 // As a workaround, emit an explicit ret here.
3812                                 ec.NeedReturnLabel ();
3813                         }
3814
3815                         return ok;
3816                 }
3817                 
3818                 protected override void DoEmit (EmitContext ec)
3819                 {
3820                         ILGenerator ig = ec.ig;
3821
3822                         if (need_exc_block)
3823                                 ig.BeginExceptionBlock ();
3824                         Block.Emit (ec);
3825
3826                         foreach (Catch c in Specific){
3827                                 LocalInfo vi;
3828                                 
3829                                 ig.BeginCatchBlock (c.CatchType);
3830
3831                                 if (c.Name != null){
3832                                         vi = c.Block.GetLocalInfo (c.Name);
3833                                         if (vi == null)
3834                                                 throw new Exception ("Variable does not exist in this block");
3835
3836                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3837                                 } else
3838                                         ig.Emit (OpCodes.Pop);
3839                                 
3840                                 c.Block.Emit (ec);
3841                         }
3842
3843                         if (General != null){
3844                                 ig.BeginCatchBlock (TypeManager.object_type);
3845                                 ig.Emit (OpCodes.Pop);
3846                                 General.Block.Emit (ec);
3847                         }
3848
3849                         DoEmitFinally (ec);
3850                         if (need_exc_block)
3851                                 ig.EndExceptionBlock ();
3852                 }
3853
3854                 public override void EmitFinally (EmitContext ec)
3855                 {
3856                         if (Fini != null)
3857                                 Fini.Emit (ec);
3858                 }
3859
3860                 public bool HasCatch
3861                 {
3862                         get {
3863                                 return General != null || Specific.Count > 0;
3864                         }
3865                 }
3866         }
3867
3868         public class Using : ExceptionStatement {
3869                 object expression_or_block;
3870                 Statement Statement;
3871                 ArrayList var_list;
3872                 Expression expr;
3873                 Type expr_type;
3874                 Expression conv;
3875                 Expression [] resolved_vars;
3876                 Expression [] converted_vars;
3877                 ExpressionStatement [] assign;
3878                 LocalBuilder local_copy;
3879                 
3880                 public Using (object expression_or_block, Statement stmt, Location l)
3881                 {
3882                         this.expression_or_block = expression_or_block;
3883                         Statement = stmt;
3884                         loc = l;
3885                 }
3886
3887                 //
3888                 // Resolves for the case of using using a local variable declaration.
3889                 //
3890                 bool ResolveLocalVariableDecls (EmitContext ec)
3891                 {
3892                         int i = 0;
3893
3894                         TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3895                         if (texpr == null)
3896                                 return false;
3897
3898                         expr_type = texpr.Type;
3899
3900                         //
3901                         // The type must be an IDisposable or an implicit conversion
3902                         // must exist.
3903                         //
3904                         converted_vars = new Expression [var_list.Count];
3905                         resolved_vars = new Expression [var_list.Count];
3906                         assign = new ExpressionStatement [var_list.Count];
3907
3908                         bool need_conv = !TypeManager.ImplementsInterface (
3909                                 expr_type, TypeManager.idisposable_type);
3910
3911                         foreach (DictionaryEntry e in var_list){
3912                                 Expression var = (Expression) e.Key;
3913
3914                                 var = var.ResolveLValue (ec, new EmptyExpression ());
3915                                 if (var == null)
3916                                         return false;
3917
3918                                 resolved_vars [i] = var;
3919
3920                                 if (!need_conv) {
3921                                         i++;
3922                                         continue;
3923                                 }
3924
3925                                 converted_vars [i] = Convert.ImplicitConversionRequired (
3926                                         ec, var, TypeManager.idisposable_type, loc);
3927
3928                                 if (converted_vars [i] == null)
3929                                         return false;
3930
3931                                 i++;
3932                         }
3933
3934                         i = 0;
3935                         foreach (DictionaryEntry e in var_list){
3936                                 Expression var = resolved_vars [i];
3937                                 Expression new_expr = (Expression) e.Value;
3938                                 Expression a;
3939
3940                                 a = new Assign (var, new_expr, loc);
3941                                 a = a.Resolve (ec);
3942                                 if (a == null)
3943                                         return false;
3944
3945                                 if (!need_conv)
3946                                         converted_vars [i] = var;
3947                                 assign [i] = (ExpressionStatement) a;
3948                                 i++;
3949                         }
3950
3951                         return true;
3952                 }
3953
3954                 bool ResolveExpression (EmitContext ec)
3955                 {
3956                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3957                                 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3958                                         Report.Error (1674, loc, "'{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3959                                                 TypeManager.CSharpName (expr_type));
3960                                         return false;
3961                                 }
3962                         }
3963
3964                         return true;
3965                 }
3966                 
3967                 //
3968                 // Emits the code for the case of using using a local variable declaration.
3969                 //
3970                 void EmitLocalVariableDecls (EmitContext ec)
3971                 {
3972                         ILGenerator ig = ec.ig;
3973                         int i = 0;
3974
3975                         for (i = 0; i < assign.Length; i++) {
3976                                 assign [i].EmitStatement (ec);
3977
3978                                 if (emit_finally)
3979                                         ig.BeginExceptionBlock ();
3980                         }
3981                         Statement.Emit (ec);
3982
3983                         var_list.Reverse ();
3984
3985                         DoEmitFinally (ec);
3986                 }
3987
3988                 void EmitLocalVariableDeclFinally (EmitContext ec)
3989                 {
3990                         ILGenerator ig = ec.ig;
3991
3992                         int i = assign.Length;
3993                         for (int ii = 0; ii < var_list.Count; ++ii){
3994                                 Expression var = resolved_vars [--i];
3995                                 Label skip = ig.DefineLabel ();
3996                                 
3997                                 ig.BeginFinallyBlock ();
3998                                 
3999                                 if (!var.Type.IsValueType) {
4000                                         var.Emit (ec);
4001                                         ig.Emit (OpCodes.Brfalse, skip);
4002                                         converted_vars [i].Emit (ec);
4003                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4004                                 } else {
4005                                         Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4006
4007                                         if (!(ml is MethodGroupExpr)) {
4008                                                 var.Emit (ec);
4009                                                 ig.Emit (OpCodes.Box, var.Type);
4010                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4011                                         } else {
4012                                                 MethodInfo mi = null;
4013
4014                                                 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4015                                                         if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4016                                                                 mi = mk;
4017                                                                 break;
4018                                                         }
4019                                                 }
4020
4021                                                 if (mi == null) {
4022                                                         Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4023                                                         return;
4024                                                 }
4025
4026                                                 IMemoryLocation mloc = (IMemoryLocation) var;
4027
4028                                                 mloc.AddressOf (ec, AddressOp.Load);
4029                                                 ig.Emit (OpCodes.Call, mi);
4030                                         }
4031                                 }
4032
4033                                 ig.MarkLabel (skip);
4034
4035                                 if (emit_finally) {
4036                                         ig.EndExceptionBlock ();
4037                                         if (i > 0)
4038                                                 ig.BeginFinallyBlock ();
4039                                 }
4040                         }
4041                 }
4042
4043                 void EmitExpression (EmitContext ec)
4044                 {
4045                         //
4046                         // Make a copy of the expression and operate on that.
4047                         //
4048                         ILGenerator ig = ec.ig;
4049                         local_copy = ig.DeclareLocal (expr_type);
4050                         if (conv != null)
4051                                 conv.Emit (ec);
4052                         else
4053                                 expr.Emit (ec);
4054                         ig.Emit (OpCodes.Stloc, local_copy);
4055
4056                         if (emit_finally)
4057                                 ig.BeginExceptionBlock ();
4058
4059                         Statement.Emit (ec);
4060                         
4061                         DoEmitFinally (ec);
4062                         if (emit_finally)
4063                                 ig.EndExceptionBlock ();
4064                 }
4065
4066                 void EmitExpressionFinally (EmitContext ec)
4067                 {
4068                         ILGenerator ig = ec.ig;
4069                         if (!local_copy.LocalType.IsValueType) {
4070                                 Label skip = ig.DefineLabel ();
4071                                 ig.Emit (OpCodes.Ldloc, local_copy);
4072                                 ig.Emit (OpCodes.Brfalse, skip);
4073                                 ig.Emit (OpCodes.Ldloc, local_copy);
4074                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4075                                 ig.MarkLabel (skip);
4076                         } else {
4077                                 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4078
4079                                 if (!(ml is MethodGroupExpr)) {
4080                                         ig.Emit (OpCodes.Ldloc, local_copy);
4081                                         ig.Emit (OpCodes.Box, local_copy.LocalType);
4082                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4083                                 } else {
4084                                         MethodInfo mi = null;
4085
4086                                         foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4087                                                 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4088                                                         mi = mk;
4089                                                         break;
4090                                                 }
4091                                         }
4092
4093                                         if (mi == null) {
4094                                                 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4095                                                 return;
4096                                         }
4097
4098                                         ig.Emit (OpCodes.Ldloca, local_copy);
4099                                         ig.Emit (OpCodes.Call, mi);
4100                                 }
4101                         }
4102                 }
4103                 
4104                 public override bool Resolve (EmitContext ec)
4105                 {
4106                         if (expression_or_block is DictionaryEntry){
4107                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4108                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4109
4110                                 if (!ResolveLocalVariableDecls (ec))
4111                                         return false;
4112
4113                         } else if (expression_or_block is Expression){
4114                                 expr = (Expression) expression_or_block;
4115
4116                                 expr = expr.Resolve (ec);
4117                                 if (expr == null)
4118                                         return false;
4119
4120                                 expr_type = expr.Type;
4121
4122                                 if (!ResolveExpression (ec))
4123                                         return false;
4124                         }
4125
4126                         FlowBranchingException branching = ec.StartFlowBranching (this);
4127
4128                         bool ok = Statement.Resolve (ec);
4129
4130                         if (!ok) {
4131                                 ec.KillFlowBranching ();
4132                                 return false;
4133                         }
4134
4135                         ResolveFinally (branching);                                     
4136                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4137
4138                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4139                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
4140                                 // to the end of the finally block.  This is a problem if `returns'
4141                                 // is true since we may jump to a point after the end of the method.
4142                                 // As a workaround, emit an explicit ret here.
4143                                 ec.NeedReturnLabel ();
4144                         }
4145
4146                         return true;
4147                 }
4148                 
4149                 protected override void DoEmit (EmitContext ec)
4150                 {
4151                         if (expression_or_block is DictionaryEntry)
4152                                 EmitLocalVariableDecls (ec);
4153                         else if (expression_or_block is Expression)
4154                                 EmitExpression (ec);
4155                 }
4156
4157                 public override void EmitFinally (EmitContext ec)
4158                 {
4159                         if (expression_or_block is DictionaryEntry)
4160                                 EmitLocalVariableDeclFinally (ec);
4161                         else if (expression_or_block is Expression)
4162                                 EmitExpressionFinally (ec);
4163                 }
4164         }
4165
4166         /// <summary>
4167         ///   Implementation of the foreach C# statement
4168         /// </summary>
4169         public class Foreach : Statement {
4170                 Expression type;
4171                 Expression variable;
4172                 Expression expr;
4173                 Statement statement;
4174                 ArrayForeach array;
4175                 CollectionForeach collection;
4176                 
4177                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4178                                 Statement stmt, Location l)
4179                 {
4180                         this.type = type;
4181                         this.variable = var;
4182                         this.expr = expr;
4183                         statement = stmt;
4184                         loc = l;
4185                 }
4186                 
4187                 public override bool Resolve (EmitContext ec)
4188                 {
4189                         expr = expr.Resolve (ec);
4190                         if (expr == null)
4191                                 return false;
4192
4193                         if (expr is NullLiteral) {
4194                                 Report.Error (186, expr.Location, "Use of null is not valid in this context");
4195                                 return false;
4196                         }
4197
4198                         TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4199                         if (texpr == null)
4200                                 return false;
4201
4202                         Type var_type = texpr.Type;
4203
4204                         //
4205                         // We need an instance variable.  Not sure this is the best
4206                         // way of doing this.
4207                         //
4208                         // FIXME: When we implement propertyaccess, will those turn
4209                         // out to return values in ExprClass?  I think they should.
4210                         //
4211                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4212                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4213                                 CollectionForeach.error1579 (expr.Type, loc);
4214                                 return false;
4215                         }
4216
4217                         if (expr.Type.IsArray) {
4218                                 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4219                                 return array.Resolve (ec);
4220                         } else {
4221                                 collection = new CollectionForeach (
4222                                         var_type, variable, expr, statement, loc);
4223                                 return collection.Resolve (ec);
4224                         }
4225                 }
4226
4227                 protected override void DoEmit (EmitContext ec)
4228                 {
4229                         ILGenerator ig = ec.ig;
4230                         
4231                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4232                         ec.LoopBegin = ig.DefineLabel ();
4233                         ec.LoopEnd = ig.DefineLabel ();
4234
4235                         if (collection != null)
4236                                 collection.Emit (ec);
4237                         else
4238                                 array.Emit (ec);
4239                         
4240                         ec.LoopBegin = old_begin;
4241                         ec.LoopEnd = old_end;
4242                 }
4243
4244                 protected class TemporaryVariable : Expression, IMemoryLocation
4245                 {
4246                         FieldBuilder fb;
4247                         LocalInfo li;
4248
4249                         public TemporaryVariable (Type type, Location loc)
4250                         {
4251                                 this.type = type;
4252                                 this.loc = loc;
4253                                 eclass = ExprClass.Value;
4254                         }
4255
4256                         static int count;
4257
4258                         public override Expression DoResolve (EmitContext ec)
4259                         {
4260                                 if (ec.InIterator) {
4261                                         count++;
4262                                         fb = ec.CurrentIterator.MapVariable (
4263                                                 "s_", count.ToString (), type);
4264                                 } else {
4265                                         TypeExpr te = new TypeExpression (type, loc);
4266                                         li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
4267                                         if (!li.Resolve (ec))
4268                                                 return null;
4269                                 }
4270
4271                                 return this;
4272                         }
4273
4274                         public override void Emit (EmitContext ec)
4275                         {
4276                                 ILGenerator ig = ec.ig;
4277
4278                                 if (fb != null) {
4279                                         ig.Emit (OpCodes.Ldarg_0);
4280                                         ig.Emit (OpCodes.Ldfld, fb);
4281                                 } else {
4282                                         ig.Emit (OpCodes.Ldloc, li.LocalBuilder);
4283                                 }
4284                         }
4285
4286                         public void EmitLoadAddress (EmitContext ec)
4287                         {
4288                                 ILGenerator ig = ec.ig;
4289
4290                                 if (fb != null) {
4291                                         ig.Emit (OpCodes.Ldarg_0);
4292                                         ig.Emit (OpCodes.Ldflda, fb);
4293                                 } else {
4294                                         ig.Emit (OpCodes.Ldloca, li.LocalBuilder);
4295                                 }
4296                         }
4297
4298                         public void Store (EmitContext ec, Expression right_side)
4299                         {
4300                                 if (fb != null)
4301                                         ec.ig.Emit (OpCodes.Ldarg_0);
4302
4303                                 right_side.Emit (ec);
4304                                 if (fb != null)
4305                                         ec.ig.Emit (OpCodes.Stfld, fb);
4306                                 else
4307                                         ec.ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4308                         }
4309
4310                         public void EmitThis (ILGenerator ig)
4311                         {
4312                                 if (fb != null)
4313                                         ig.Emit (OpCodes.Ldarg_0);
4314                         }
4315
4316                         public void EmitStore (ILGenerator ig)
4317                         {
4318                                 if (fb != null)
4319                                         ig.Emit (OpCodes.Stfld, fb);
4320                                 else
4321                                         ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4322                         }
4323
4324                         public void AddressOf (EmitContext ec, AddressOp mode)
4325                         {
4326                                 EmitLoadAddress (ec);
4327                         }
4328                 }
4329
4330                 protected class ArrayCounter : TemporaryVariable
4331                 {
4332                         public ArrayCounter (Location loc)
4333                                 : base (TypeManager.int32_type, loc)
4334                         { }
4335
4336                         public void Initialize (EmitContext ec)
4337                         {
4338                                 EmitThis (ec.ig);
4339                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
4340                                 EmitStore (ec.ig);
4341                         }
4342
4343                         public void Increment (EmitContext ec)
4344                         {
4345                                 EmitThis (ec.ig);
4346                                 Emit (ec);
4347                                 ec.ig.Emit (OpCodes.Ldc_I4_1);
4348                                 ec.ig.Emit (OpCodes.Add);
4349                                 EmitStore (ec.ig);
4350                         }
4351                 }
4352
4353                 protected class ArrayForeach : Statement
4354                 {
4355                         Expression variable, expr, conv;
4356                         Statement statement;
4357                         Type array_type;
4358                         Type var_type;
4359                         TemporaryVariable[] lengths;
4360                         ArrayCounter[] counter;
4361                         int rank;
4362
4363                         TemporaryVariable copy;
4364                         Expression access;
4365
4366                         public ArrayForeach (Type var_type, Expression var,
4367                                              Expression expr, Statement stmt, Location l)
4368                         {
4369                                 this.var_type = var_type;
4370                                 this.variable = var;
4371                                 this.expr = expr;
4372                                 statement = stmt;
4373                                 loc = l;
4374                         }
4375
4376                         public override bool Resolve (EmitContext ec)
4377                         {                               
4378                                 array_type = expr.Type;
4379                                 rank = array_type.GetArrayRank ();
4380
4381                                 copy = new TemporaryVariable (array_type, loc);
4382                                 copy.Resolve (ec);
4383
4384                                 counter = new ArrayCounter [rank];
4385                                 lengths = new TemporaryVariable [rank];
4386
4387                                 ArrayList list = new ArrayList ();
4388                                 for (int i = 0; i < rank; i++) {
4389                                         counter [i] = new ArrayCounter (loc);
4390                                         counter [i].Resolve (ec);
4391
4392                                         lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4393                                         lengths [i].Resolve (ec);
4394
4395                                         list.Add (counter [i]);
4396                                 }
4397
4398                                 access = new ElementAccess (copy, list, loc).Resolve (ec);
4399                                 if (access == null)
4400                                         return false;
4401
4402                                 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4403                                 if (conv == null)
4404                                         return false;
4405
4406                                 bool ok = true;
4407
4408                                 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4409                                 ec.CurrentBranching.CreateSibling ();
4410
4411                                 variable = variable.ResolveLValue (ec, conv);
4412                                 if (variable == null)
4413                                         ok = false;
4414
4415                                 if (!statement.Resolve (ec))
4416                                         ok = false;
4417
4418                                 ec.EndFlowBranching ();
4419
4420                                 return ok;
4421                         }
4422
4423                         protected override void DoEmit (EmitContext ec)
4424                         {
4425                                 ILGenerator ig = ec.ig;
4426
4427                                 copy.Store (ec, expr);
4428
4429                                 Label[] test = new Label [rank];
4430                                 Label[] loop = new Label [rank];
4431
4432                                 for (int i = 0; i < rank; i++) {
4433                                         test [i] = ig.DefineLabel ();
4434                                         loop [i] = ig.DefineLabel ();
4435
4436                                         lengths [i].EmitThis (ig);
4437                                         ((ArrayAccess) access).EmitGetLength (ec, i);
4438                                         lengths [i].EmitStore (ig);
4439                                 }
4440
4441                                 for (int i = 0; i < rank; i++) {
4442                                         counter [i].Initialize (ec);
4443
4444                                         ig.Emit (OpCodes.Br, test [i]);
4445                                         ig.MarkLabel (loop [i]);
4446                                 }
4447
4448                                 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4449
4450                                 statement.Emit (ec);
4451
4452                                 ig.MarkLabel (ec.LoopBegin);
4453
4454                                 for (int i = rank - 1; i >= 0; i--){
4455                                         counter [i].Increment (ec);
4456
4457                                         ig.MarkLabel (test [i]);
4458                                         counter [i].Emit (ec);
4459                                         lengths [i].Emit (ec);
4460                                         ig.Emit (OpCodes.Blt, loop [i]);
4461                                 }
4462
4463                                 ig.MarkLabel (ec.LoopEnd);
4464                         }
4465                 }
4466
4467                 protected class CollectionForeach : ExceptionStatement
4468                 {
4469                         Expression variable, expr;
4470                         Statement statement;
4471
4472                         TemporaryVariable enumerator;
4473                         Expression init;
4474                         Statement loop;
4475
4476                         MethodGroupExpr get_enumerator;
4477                         PropertyExpr get_current;
4478                         MethodInfo move_next;
4479                         Type var_type, enumerator_type;
4480                         bool is_disposable;
4481
4482                         public CollectionForeach (Type var_type, Expression var,
4483                                                   Expression expr, Statement stmt, Location l)
4484                         {
4485                                 this.var_type = var_type;
4486                                 this.variable = var;
4487                                 this.expr = expr;
4488                                 statement = stmt;
4489                                 loc = l;
4490                         }
4491
4492                         bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4493                         {
4494                                 Type [] args = TypeManager.GetArgumentTypes (mi);
4495                                 if (args != null){
4496                                         if (args.Length != 0)
4497                                                 return false;
4498                                 }
4499
4500                                 if (TypeManager.IsOverride (mi))
4501                                         return false;
4502                         
4503                                 // Check whether GetEnumerator is public
4504                                 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4505                                         return false;
4506
4507                                 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4508                                         //
4509                                         // Apply the same optimization as MS: skip the GetEnumerator
4510                                         // returning an IEnumerator, and use the one returning a 
4511                                         // CharEnumerator instead. This allows us to avoid the 
4512                                         // try-finally block and the boxing.
4513                                         //
4514                                         return false;
4515
4516                                 //
4517                                 // Ok, we can access it, now make sure that we can do something
4518                                 // with this `GetEnumerator'
4519                                 //
4520
4521                                 Type return_type = mi.ReturnType;
4522                                 if (mi.ReturnType == TypeManager.ienumerator_type ||
4523                                     TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4524                                     (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4525                                         //
4526                                         // If it is not an interface, lets try to find the methods ourselves.
4527                                         // For example, if we have:
4528                                         // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4529                                         // We can avoid the iface call. This is a runtime perf boost.
4530                                         // even bigger if we have a ValueType, because we avoid the cost
4531                                         // of boxing.
4532                                         //
4533                                         // We have to make sure that both methods exist for us to take
4534                                         // this path. If one of the methods does not exist, we will just
4535                                         // use the interface. Sadly, this complex if statement is the only
4536                                         // way I could do this without a goto
4537                                         //
4538
4539                                         if (return_type.IsInterface ||
4540                                             !FetchMoveNext (ec, return_type) ||
4541                                             !FetchGetCurrent (ec, return_type)) {
4542                                                 move_next = TypeManager.bool_movenext_void;
4543                                                 get_current = new PropertyExpr (
4544                                                         ec, TypeManager.ienumerator_getcurrent, loc);
4545                                                 return true;
4546                                         }
4547                                 } else {
4548                                         //
4549                                         // Ok, so they dont return an IEnumerable, we will have to
4550                                         // find if they support the GetEnumerator pattern.
4551                                         //
4552
4553                                         if (!FetchMoveNext (ec, return_type))
4554                                                 return false;
4555
4556                                         if (!FetchGetCurrent (ec, return_type))
4557                                                 return false;
4558                                 }
4559
4560                                 enumerator_type = return_type;
4561                                 is_disposable = !enumerator_type.IsSealed ||
4562                                         TypeManager.ImplementsInterface (
4563                                                 enumerator_type, TypeManager.idisposable_type);
4564
4565                                 return true;
4566                         }
4567
4568                         //
4569                         // Retrieves a `public bool MoveNext ()' method from the Type `t'
4570                         //
4571                         bool FetchMoveNext (EmitContext ec, Type t)
4572                         {
4573                                 MemberList move_next_list;
4574
4575                                 move_next_list = TypeContainer.FindMembers (
4576                                         t, MemberTypes.Method,
4577                                         BindingFlags.Public | BindingFlags.Instance,
4578                                         Type.FilterName, "MoveNext");
4579                                 if (move_next_list.Count == 0)
4580                                         return false;
4581
4582                                 foreach (MemberInfo m in move_next_list){
4583                                         MethodInfo mi = (MethodInfo) m;
4584                                         Type [] args;
4585                                 
4586                                         args = TypeManager.GetArgumentTypes (mi);
4587                                         if ((args != null) && (args.Length == 0) &&
4588                                             TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4589                                                 move_next = mi;
4590                                                 return true;
4591                                         }
4592                                 }
4593
4594                                 return false;
4595                         }
4596                 
4597                         //
4598                         // Retrieves a `public T get_Current ()' method from the Type `t'
4599                         //
4600                         bool FetchGetCurrent (EmitContext ec, Type t)
4601                         {
4602                                 PropertyExpr pe = Expression.MemberLookup (
4603                                         ec, t, "Current", MemberTypes.Property,
4604                                         Expression.AllBindingFlags, loc) as PropertyExpr;
4605                                 if (pe == null)
4606                                         return false;
4607
4608                                 get_current = pe;
4609                                 return true;
4610                         }
4611
4612                         // 
4613                         // Retrieves a `public void Dispose ()' method from the Type `t'
4614                         //
4615                         static MethodInfo FetchMethodDispose (Type t)
4616                         {
4617                                 MemberList dispose_list;
4618
4619                                 dispose_list = TypeContainer.FindMembers (
4620                                         t, MemberTypes.Method,
4621                                         BindingFlags.Public | BindingFlags.Instance,
4622                                         Type.FilterName, "Dispose");
4623                                 if (dispose_list.Count == 0)
4624                                         return null;
4625
4626                                 foreach (MemberInfo m in dispose_list){
4627                                         MethodInfo mi = (MethodInfo) m;
4628                                         Type [] args;
4629
4630                                         args = TypeManager.GetArgumentTypes (mi);
4631                                         if (args != null && args.Length == 0){
4632                                                 if (mi.ReturnType == TypeManager.void_type)
4633                                                         return mi;
4634                                         }
4635                                 }
4636                                 return null;
4637                         }
4638
4639                         static public void error1579 (Type t, Location loc)
4640                         {
4641                                 Report.Error (1579, loc, "foreach statement cannot operate on " +
4642                                               "variables of type `{0}' because that class does " +
4643                                               "not provide a GetEnumerator method or it is " +
4644                                               "inaccessible", t.FullName);
4645                         }
4646
4647                         bool TryType (EmitContext ec, Type t)
4648                         {
4649                                 MethodGroupExpr mg = Expression.MemberLookup (
4650                                         ec, t, "GetEnumerator", MemberTypes.Method,
4651                                         Expression.AllBindingFlags, loc) as MethodGroupExpr;
4652                                 if (mg == null)
4653                                         return false;
4654
4655                                 foreach (MethodBase mb in mg.Methods) {
4656                                         if (!GetEnumeratorFilter (ec, (MethodInfo) mb))
4657                                                 continue;
4658
4659                                         MethodInfo[] mi = new MethodInfo[] { (MethodInfo) mb };
4660                                         get_enumerator = new MethodGroupExpr (mi, loc);
4661
4662                                         if (t != expr.Type) {
4663                                                 expr = Convert.ExplicitConversion (
4664                                                         ec, expr, t, loc);
4665                                                 if (expr == null)
4666                                                         throw new InternalErrorException ();
4667                                         }
4668
4669                                         get_enumerator.InstanceExpression = expr;
4670                                         get_enumerator.IsBase = t != expr.Type;
4671
4672                                         return true;
4673                                 }
4674
4675                                 return false;
4676                         }               
4677
4678                         bool ProbeCollectionType (EmitContext ec, Type t)
4679                         {
4680                                 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4681                                         if (TryType (ec, tt))
4682                                                 return true;
4683                                         tt = tt.BaseType;
4684                                 }
4685
4686                                 //
4687                                 // Now try to find the method in the interfaces
4688                                 //
4689                                 while (t != null){
4690                                         Type [] ifaces = t.GetInterfaces ();
4691
4692                                         foreach (Type i in ifaces){
4693                                                 if (TryType (ec, i))
4694                                                         return true;
4695                                         }
4696                                 
4697                                         //
4698                                         // Since TypeBuilder.GetInterfaces only returns the interface
4699                                         // types for this type, we have to keep looping, but once
4700                                         // we hit a non-TypeBuilder (ie, a Type), then we know we are
4701                                         // done, because it returns all the types
4702                                         //
4703                                         if ((t is TypeBuilder))
4704                                                 t = t.BaseType;
4705                                         else
4706                                                 break;
4707                                 }
4708
4709                                 return false;
4710                         }
4711
4712                         public override bool Resolve (EmitContext ec)
4713                         {
4714                                 enumerator_type = TypeManager.ienumerator_type;
4715                                 is_disposable = true;
4716
4717                                 if (!ProbeCollectionType (ec, expr.Type)) {
4718                                         error1579 (expr.Type, loc);
4719                                         return false;
4720                                 }
4721
4722                                 enumerator = new TemporaryVariable (enumerator_type, loc);
4723                                 enumerator.Resolve (ec);
4724
4725                                 init = new Invocation (get_enumerator, new ArrayList (), loc);
4726                                 init = init.Resolve (ec);
4727                                 if (init == null)
4728                                         return false;
4729
4730                                 Expression move_next_expr;
4731                                 {
4732                                         MemberInfo[] mi = new MemberInfo[] { move_next };
4733                                         MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4734                                         mg.InstanceExpression = enumerator;
4735
4736                                         move_next_expr = new Invocation (mg, new ArrayList (), loc);
4737                                 }
4738
4739                                 get_current.InstanceExpression = enumerator;
4740
4741                                 Statement block = new CollectionForeachStatement (
4742                                         var_type, variable, get_current, statement, loc);
4743
4744                                 loop = new While (move_next_expr, block, loc);
4745
4746                                 bool ok = true;
4747
4748                                 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4749                                 ec.CurrentBranching.CreateSibling ();
4750
4751                                 FlowBranchingException branching = null;
4752                                 if (is_disposable)
4753                                         branching = ec.StartFlowBranching (this);
4754
4755                                 if (!loop.Resolve (ec))
4756                                         ok = false;
4757
4758                                 if (is_disposable) {
4759                                         ResolveFinally (branching);
4760                                         ec.EndFlowBranching ();
4761                                 } else
4762                                         emit_finally = true;
4763
4764                                 ec.EndFlowBranching ();
4765
4766                                 return ok;
4767                         }
4768
4769                         protected override void DoEmit (EmitContext ec)
4770                         {
4771                                 ILGenerator ig = ec.ig;
4772
4773                                 enumerator.Store (ec, init);
4774
4775                                 //
4776                                 // Protect the code in a try/finalize block, so that
4777                                 // if the beast implement IDisposable, we get rid of it
4778                                 //
4779                                 if (is_disposable && emit_finally)
4780                                         ig.BeginExceptionBlock ();
4781                         
4782                                 loop.Emit (ec);
4783
4784                                 //
4785                                 // Now the finally block
4786                                 //
4787                                 if (is_disposable) {
4788                                         DoEmitFinally (ec);
4789                                         if (emit_finally)
4790                                                 ig.EndExceptionBlock ();
4791                                 }
4792                         }
4793
4794
4795                         public override void EmitFinally (EmitContext ec)
4796                         {
4797                                 ILGenerator ig = ec.ig;
4798
4799                                 if (enumerator_type.IsValueType) {
4800                                         enumerator.Emit (ec);
4801
4802                                         MethodInfo mi = FetchMethodDispose (enumerator_type);
4803                                         if (mi != null) {
4804                                                 enumerator.EmitLoadAddress (ec);
4805                                                 ig.Emit (OpCodes.Call, mi);
4806                                         } else {
4807                                                 enumerator.Emit (ec);
4808                                                 ig.Emit (OpCodes.Box, enumerator_type);
4809                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4810                                         }
4811                                 } else {
4812                                         Label call_dispose = ig.DefineLabel ();
4813
4814                                         enumerator.Emit (ec);
4815                                         ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4816                                         ig.Emit (OpCodes.Dup);
4817                                         ig.Emit (OpCodes.Brtrue_S, call_dispose);
4818                                         ig.Emit (OpCodes.Pop);
4819
4820                                         Label end_finally = ig.DefineLabel ();
4821                                         ig.Emit (OpCodes.Br, end_finally);
4822
4823                                         ig.MarkLabel (call_dispose);
4824                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4825                                         ig.MarkLabel (end_finally);
4826                                 }
4827                         }
4828                 }
4829
4830                 protected class CollectionForeachStatement : Statement
4831                 {
4832                         Type type;
4833                         Expression variable, current, conv;
4834                         Statement statement;
4835                         Assign assign;
4836
4837                         public CollectionForeachStatement (Type type, Expression variable,
4838                                                            Expression current, Statement statement,
4839                                                            Location loc)
4840                         {
4841                                 this.type = type;
4842                                 this.variable = variable;
4843                                 this.current = current;
4844                                 this.statement = statement;
4845                                 this.loc = loc;
4846                         }
4847
4848                         public override bool Resolve (EmitContext ec)
4849                         {
4850                                 current = current.Resolve (ec);
4851                                 if (current == null)
4852                                         return false;
4853
4854                                 conv = Convert.ExplicitConversion (ec, current, type, loc);
4855                                 if (conv == null)
4856                                         return false;
4857
4858                                 assign = new Assign (variable, conv, loc);
4859                                 if (assign.Resolve (ec) == null)
4860                                         return false;
4861
4862                                 if (!statement.Resolve (ec))
4863                                         return false;
4864
4865                                 return true;
4866                         }
4867
4868                         protected override void DoEmit (EmitContext ec)
4869                         {
4870                                 assign.EmitStatement (ec);
4871                                 statement.Emit (ec);
4872                         }
4873                 }
4874         }
4875 }