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