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