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