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