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