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