2004-10-31 Marek Safar <marek.safar@seznam.cz>
[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                         if (!child_variable_names.Contains (name))
1434                                 child_variable_names.Add (name, true);
1435                 }
1436
1437                 // <summary>
1438                 //   Checks whether a variable name has already been used in a child block.
1439                 // </summary>
1440                 public bool IsVariableNameUsedInChildBlock (string name)
1441                 {
1442                         if (child_variable_names == null)
1443                                 return false;
1444
1445                         return child_variable_names.Contains (name);
1446                 }
1447
1448                 // <summary>
1449                 //   This is used by non-static `struct' constructors which do not have an
1450                 //   initializer - in this case, the constructor must initialize all of the
1451                 //   struct's fields.  To do this, we add a "this" variable and use the flow
1452                 //   analysis code to ensure that it's been fully initialized before control
1453                 //   leaves the constructor.
1454                 // </summary>
1455                 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1456                 {
1457                         if (this_variable != null)
1458                                 return this_variable;
1459
1460                         if (variables == null)
1461                                 variables = new Hashtable ();
1462
1463                         this_variable = new LocalInfo (tc, this, l);
1464                         this_variable.Used = true;
1465                         this_variable.IsThis = true;
1466
1467                         variables.Add ("this", this_variable);
1468
1469                         return this_variable;
1470                 }
1471
1472                 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1473                 {
1474                         if (variables == null)
1475                                 variables = new Hashtable ();
1476
1477                         LocalInfo vi = GetLocalInfo (name);
1478                         if (vi != null) {
1479                                 if (vi.Block != this)
1480                                         Report.Error (136, l, "A local variable named `" + name + "' " +
1481                                                       "cannot be declared in this scope since it would " +
1482                                                       "give a different meaning to `" + name + "', which " +
1483                                                       "is already used in a `parent or current' scope to " +
1484                                                       "denote something else");
1485                                 else
1486                                         Report.Error (128, l, "A local variable `" + name + "' is already " +
1487                                                       "defined in this scope");
1488                                 return null;
1489                         }
1490
1491                         if (IsVariableNameUsedInChildBlock (name)) {
1492                                 Report.Error (136, l, "A local variable named `" + name + "' " +
1493                                               "cannot be declared in this scope since it would " +
1494                                               "give a different meaning to `" + name + "', which " +
1495                                               "is already used in a `child' scope to denote something " +
1496                                               "else");
1497                                 return null;
1498                         }
1499
1500                         if (pars != null) {
1501                                 int idx;
1502                                 Parameter p = pars.GetParameterByName (name, out idx);
1503                                 if (p != null) {
1504                                         Report.Error (136, l, "A local variable named `" + name + "' " +
1505                                                       "cannot be declared in this scope since it would " +
1506                                                       "give a different meaning to `" + name + "', which " +
1507                                                       "is already used in a `parent or current' scope to " +
1508                                                       "denote something else");
1509                                         return null;
1510                                 }
1511                         }
1512
1513                         vi = new LocalInfo (type, name, this, l);
1514
1515                         variables.Add (name, vi);
1516
1517                         // Mark 'name' as "used by a child block" in every surrounding block
1518                         Block cur = this;
1519                         while (cur != null && cur.Implicit) 
1520                                 cur = cur.Parent;
1521                         if (cur != null)
1522                                 for (Block par = cur.Parent; par != null; par = par.Parent)
1523                                         par.AddChildVariableName (name);
1524
1525                         if ((flags & Flags.VariablesInitialized) != 0)
1526                                 throw new Exception ();
1527
1528                         // Console.WriteLine ("Adding {0} to {1}", name, ID);
1529                         return vi;
1530                 }
1531
1532                 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1533                 {
1534                         if (AddVariable (type, name, pars, l) == null)
1535                                 return false;
1536                         
1537                         if (constants == null)
1538                                 constants = new Hashtable ();
1539
1540                         constants.Add (name, value);
1541                         return true;
1542                 }
1543
1544                 public Hashtable Variables {
1545                         get {
1546                                 return variables;
1547                         }
1548                 }
1549
1550                 public LocalInfo GetLocalInfo (string name)
1551                 {
1552                         for (Block b = this; b != null; b = b.Parent) {
1553                                 if (b.variables != null) {
1554                                         LocalInfo ret = b.variables [name] as LocalInfo;
1555                                         if (ret != null)
1556                                                 return ret;
1557                                 }
1558                         }
1559                         return null;
1560                 }
1561
1562                 public Expression GetVariableType (string name)
1563                 {
1564                         LocalInfo vi = GetLocalInfo (name);
1565
1566                         if (vi != null)
1567                                 return vi.Type;
1568
1569                         return null;
1570                 }
1571
1572                 public Expression GetConstantExpression (string name)
1573                 {
1574                         for (Block b = this; b != null; b = b.Parent) {
1575                                 if (b.constants != null) {
1576                                         Expression ret = b.constants [name] as Expression;
1577                                         if (ret != null)
1578                                                 return ret;
1579                                 }
1580                         }
1581                         return null;
1582                 }
1583                 
1584                 /// <summary>
1585                 ///   True if the variable named @name is a constant
1586                 ///  </summary>
1587                 public bool IsConstant (string name)
1588                 {
1589                         Expression e = null;
1590                         
1591                         e = GetConstantExpression (name);
1592                         
1593                         return e != null;
1594                 }
1595
1596                 //
1597                 // Returns a `ParameterReference' for the given name, or null if there
1598                 // is no such parameter
1599                 //
1600                 public ParameterReference GetParameterReference (string name, Location loc)
1601                 {
1602                         Block b = this;
1603
1604                         do {
1605                                 Parameters pars = b.parameters;
1606                                 
1607                                 if (pars != null){
1608                                         Parameter par;
1609                                         int idx;
1610                                         
1611                                         par = pars.GetParameterByName (name, out idx);
1612                                         if (par != null){
1613                                                 ParameterReference pr;
1614
1615                                                 pr = new ParameterReference (pars, this, idx, name, loc);
1616                                                 return pr;
1617                                         }
1618                                 }
1619                                 b = b.Parent;
1620                         } while (b != null);
1621                         return null;
1622                 }
1623
1624                 //
1625                 // Whether the parameter named `name' is local to this block, 
1626                 // or false, if the parameter belongs to an encompassing block.
1627                 //
1628                 public bool IsLocalParameter (string name)
1629                 {
1630                         Block b = this;
1631                         int toplevel_count = 0;
1632
1633                         do {
1634                                 if (this is ToplevelBlock)
1635                                         toplevel_count++;
1636
1637                                 Parameters pars = b.parameters;
1638                                 if (pars != null){
1639                                         if (pars.GetParameterByName (name) != null)
1640                                                 return true;
1641                                         return false;
1642                                 }
1643                                 if (toplevel_count > 0)
1644                                         return false;
1645                                 b = b.Parent;
1646                         } while (b != null);
1647                         return false;
1648                 }
1649                 
1650                 //
1651                 // Whether the `name' is a parameter reference
1652                 //
1653                 public bool IsParameterReference (string name)
1654                 {
1655                         Block b = this;
1656
1657                         do {
1658                                 Parameters pars = b.parameters;
1659                                 
1660                                 if (pars != null)
1661                                         if (pars.GetParameterByName (name) != null)
1662                                                 return true;
1663                                 b = b.Parent;
1664                         } while (b != null);
1665                         return false;
1666                 }
1667                 
1668                 /// <returns>
1669                 ///   A list of labels that were not used within this block
1670                 /// </returns>
1671                 public string [] GetUnreferenced ()
1672                 {
1673                         // FIXME: Implement me
1674                         return null;
1675                 }
1676
1677                 public void AddStatement (Statement s)
1678                 {
1679                         statements.Add (s);
1680                         flags |= Flags.BlockUsed;
1681                 }
1682
1683                 public bool Used {
1684                         get {
1685                                 return (flags & Flags.BlockUsed) != 0;
1686                         }
1687                 }
1688
1689                 public void Use ()
1690                 {
1691                         flags |= Flags.BlockUsed;
1692                 }
1693
1694                 public bool HasRet {
1695                         get {
1696                                 return (flags & Flags.HasRet) != 0;
1697                         }
1698                 }
1699
1700                 public bool IsDestructor {
1701                         get {
1702                                 return (flags & Flags.IsDestructor) != 0;
1703                         }
1704                 }
1705
1706                 public void SetDestructor ()
1707                 {
1708                         flags |= Flags.IsDestructor;
1709                 }
1710
1711                 VariableMap param_map, local_map;
1712
1713                 public VariableMap ParameterMap {
1714                         get {
1715                                 if ((flags & Flags.VariablesInitialized) == 0)
1716                                         throw new Exception ("Variables have not been initialized yet");
1717
1718                                 return param_map;
1719                         }
1720                 }
1721
1722                 public VariableMap LocalMap {
1723                         get {
1724                                 if ((flags & Flags.VariablesInitialized) == 0)
1725                                         throw new Exception ("Variables have not been initialized yet");
1726
1727                                 return local_map;
1728                         }
1729                 }
1730
1731                 /// <summary>
1732                 ///   Emits the variable declarations and labels.
1733                 /// </summary>
1734                 /// <remarks>
1735                 ///   tc: is our typecontainer (to resolve type references)
1736                 ///   ig: is the code generator:
1737                 /// </remarks>
1738                 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1739                 {
1740                         ILGenerator ig = ec.ig;
1741
1742                         bool old_unsafe = ec.InUnsafe;
1743
1744                         // If some parent block was unsafe, we remain unsafe even if this block
1745                         // isn't explicitly marked as such.
1746                         ec.InUnsafe |= Unsafe;
1747
1748                         //
1749                         // Compute the VariableMap's.
1750                         //
1751                         // Unfortunately, we don't know the type when adding variables with
1752                         // AddVariable(), so we need to compute this info here.
1753                         //
1754
1755                         LocalInfo[] locals;
1756                         if (variables != null) {
1757                                 foreach (LocalInfo li in variables.Values)
1758                                         li.Resolve (ec);
1759
1760                                 locals = new LocalInfo [variables.Count];
1761                                 variables.Values.CopyTo (locals, 0);
1762                         } else
1763                                 locals = new LocalInfo [0];
1764
1765                         if (Parent != null)
1766                                 local_map = new VariableMap (Parent.LocalMap, locals);
1767                         else
1768                                 local_map = new VariableMap (locals);
1769
1770                         param_map = new VariableMap (ip);
1771                         flags |= Flags.VariablesInitialized;
1772
1773                         bool old_check_state = ec.ConstantCheckState;
1774                         ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1775                         
1776                         //
1777                         // Process this block variables
1778                         //
1779                         if (variables != null){
1780                                 foreach (DictionaryEntry de in variables){
1781                                         string name = (string) de.Key;
1782                                         LocalInfo vi = (LocalInfo) de.Value;
1783                                         
1784                                         if (vi.VariableType == null)
1785                                                 continue;
1786
1787                                         Type variable_type = vi.VariableType;
1788
1789                                         if (variable_type.IsPointer){
1790                                                 //
1791                                                 // Am not really convinced that this test is required (Microsoft does it)
1792                                                 // but the fact is that you would not be able to use the pointer variable
1793                                                 // *anyways*
1794                                                 //
1795                                                 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1796                                                                                   vi.Location))
1797                                                         continue;
1798                                         }
1799
1800 #if false
1801                                         if (remap_locals)
1802                                                 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1803                                         else if (vi.Pinned)
1804                                                 //
1805                                                 // This is needed to compile on both .NET 1.x and .NET 2.x
1806                                                 // the later introduced `DeclareLocal (Type t, bool pinned)'
1807                                                 //
1808                                                 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1809                                         else if (!vi.IsThis)
1810                                                 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1811 #endif
1812
1813                                         if (constants == null)
1814                                                 continue;
1815
1816                                         Expression cv = (Expression) constants [name];
1817                                         if (cv == null)
1818                                                 continue;
1819
1820                                         ec.CurrentBlock = this;
1821                                         Expression e = cv.Resolve (ec);
1822                                         if (e == null)
1823                                                 continue;
1824
1825                                         Constant ce = e as Constant;
1826                                         if (ce == null){
1827                                                 Report.Error (133, vi.Location,
1828                                                               "The expression being assigned to `" +
1829                                                               name + "' must be constant (" + e + ")");
1830                                                 continue;
1831                                         }
1832
1833                                         if (e.Type != variable_type){
1834                                                 e = Const.ChangeType (vi.Location, ce, variable_type);
1835                                                 if (e == null)
1836                                                         continue;
1837                                         }
1838
1839                                         constants.Remove (name);
1840                                         constants.Add (name, e);
1841                                 }
1842                         }
1843                         ec.ConstantCheckState = old_check_state;
1844
1845                         //
1846                         // Now, handle the children
1847                         //
1848                         if (children != null){
1849                                 foreach (Block b in children)
1850                                         b.ResolveMeta (toplevel, ec, ip);
1851                         }
1852                         ec.InUnsafe = old_unsafe;
1853                 }
1854
1855                 //
1856                 // Emits the local variable declarations for a block
1857                 //
1858                 public void EmitMeta (EmitContext ec)
1859                 {
1860                         ILGenerator ig = ec.ig;
1861                         
1862                         if (variables != null){
1863                                 bool have_captured_vars = ec.HaveCapturedVariables ();
1864                                 bool remap_locals = ec.RemapToProxy;
1865                                 
1866                                 foreach (DictionaryEntry de in variables){
1867                                         LocalInfo vi = (LocalInfo) de.Value;
1868
1869                                         if (have_captured_vars && ec.IsCaptured (vi))
1870                                                 continue;
1871
1872                                         if (remap_locals){
1873                                                 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1874                                         } else {
1875                                                 if (vi.Pinned)
1876                                                         //
1877                                                         // This is needed to compile on both .NET 1.x and .NET 2.x
1878                                                         // the later introduced `DeclareLocal (Type t, bool pinned)'
1879                                                         //
1880                                                         vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1881                                                 else if (!vi.IsThis)
1882                                                         vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1883                                         }
1884                                 }
1885                         }
1886
1887                         if (children != null){
1888                                 foreach (Block b in children)
1889                                         b.EmitMeta (ec);
1890                         }
1891                 }
1892
1893                 void UsageWarning (FlowBranching.UsageVector vector)
1894                 {
1895                         string name;
1896
1897                         if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1898                                 foreach (DictionaryEntry de in variables){
1899                                         LocalInfo vi = (LocalInfo) de.Value;
1900                                         
1901                                         if (vi.Used)
1902                                                 continue;
1903                                         
1904                                         name = (string) de.Key;
1905
1906                                         if (vector.IsAssigned (vi.VariableInfo)){
1907                                                 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1908                                         } else {
1909                                                 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1910                                         }
1911                                 }
1912                         }
1913                 }
1914
1915                 bool unreachable_shown;
1916
1917                 public override bool Resolve (EmitContext ec)
1918                 {
1919                         Block prev_block = ec.CurrentBlock;
1920                         bool ok = true;
1921
1922                         int errors = Report.Errors;
1923
1924                         ec.CurrentBlock = this;
1925                         ec.StartFlowBranching (this);
1926
1927                         Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1928
1929                         bool unreachable = false;
1930
1931                         int statement_count = statements.Count;
1932                         for (int ix = 0; ix < statement_count; ix++){
1933                                 Statement s = (Statement) statements [ix];
1934
1935                                 if (unreachable && !(s is LabeledStatement)) {
1936                                         if (s == EmptyStatement.Value)
1937                                                 s.loc = EndLocation;
1938
1939                                         if (!s.ResolveUnreachable (ec, !unreachable_shown))
1940                                                 ok = false;
1941
1942                                         if (s != EmptyStatement.Value)
1943                                                 unreachable_shown = true;
1944                                         else
1945                                                 s.loc = Location.Null;
1946
1947                                         statements [ix] = EmptyStatement.Value;
1948                                         continue;
1949                                 }
1950
1951                                 if (s.Resolve (ec) == false) {
1952                                         ok = false;
1953                                         statements [ix] = EmptyStatement.Value;
1954                                         continue;
1955                                 }
1956
1957                                 num_statements = ix + 1;
1958
1959                                 if (s is LabeledStatement)
1960                                         unreachable = false;
1961                                 else
1962                                         unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1963                         }
1964
1965                         Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1966                                       ec.CurrentBranching, statement_count, num_statements);
1967
1968
1969                         FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1970
1971                         ec.CurrentBlock = prev_block;
1972
1973                         // If we're a non-static `struct' constructor which doesn't have an
1974                         // initializer, then we must initialize all of the struct's fields.
1975                         if ((this_variable != null) &&
1976                             (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1977                             !this_variable.IsThisAssigned (ec, loc))
1978                                 ok = false;
1979
1980                         if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1981                                 foreach (LabeledStatement label in labels.Values)
1982                                         if (!label.HasBeenReferenced)
1983                                                 Report.Warning (164, label.Location,
1984                                                                 "This label has not been referenced");
1985                         }
1986
1987                         Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1988
1989                         if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1990                             (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1991                             (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1992                                 flags |= Flags.HasRet;
1993
1994                         if (ok && (errors == Report.Errors)) {
1995                                 if (RootContext.WarningLevel >= 3)
1996                                         UsageWarning (vector);
1997                         }
1998
1999                         return ok;
2000                 }
2001
2002                 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2003                 {
2004                         unreachable_shown = true;
2005                         return base.ResolveUnreachable (ec, warn);
2006                 }
2007                 
2008                 protected override void DoEmit (EmitContext ec)
2009                 {
2010                         for (int ix = 0; ix < num_statements; ix++){
2011                                 Statement s = (Statement) statements [ix];
2012
2013                                 // Check whether we are the last statement in a
2014                                 // top-level block.
2015
2016                                 if ((Parent == null) && (ix+1 == num_statements))
2017                                         ec.IsLastStatement = true;
2018                                 else
2019                                         ec.IsLastStatement = false;
2020
2021                                 s.Emit (ec);
2022                         }
2023                 }
2024
2025                 public override void Emit (EmitContext ec)
2026                 {
2027                         Block prev_block = ec.CurrentBlock;
2028
2029                         ec.CurrentBlock = this;
2030
2031                         bool emit_debug_info = (CodeGen.SymbolWriter != null);
2032                         bool is_lexical_block = !Implicit && (Parent != null);
2033
2034                         if (emit_debug_info) {
2035                                 if (is_lexical_block)
2036                                         ec.ig.BeginScope ();
2037
2038                                 if (variables != null) {
2039                                         foreach (DictionaryEntry de in variables) {
2040                                                 string name = (string) de.Key;
2041                                                 LocalInfo vi = (LocalInfo) de.Value;
2042
2043                                                 if (vi.LocalBuilder == null)
2044                                                         continue;
2045
2046                                                 ec.DefineLocalVariable (name, vi.LocalBuilder);
2047                                         }
2048                                 }
2049                         }
2050
2051                         ec.Mark (StartLocation, true);
2052                         DoEmit (ec);
2053                         ec.Mark (EndLocation, true); 
2054
2055                         if (emit_debug_info && is_lexical_block)
2056                                 ec.ig.EndScope ();
2057
2058                         ec.CurrentBlock = prev_block;
2059                 }
2060
2061                 public ToplevelBlock Toplevel {
2062                         get {
2063                                 Block b = this;
2064                                 while (b.Parent != null){
2065                                         if ((b.flags & Flags.IsToplevel) != 0)
2066                                                 break;
2067                                         b = b.Parent;
2068                                 }
2069
2070                                 return (ToplevelBlock) b;
2071                         }
2072                 }
2073
2074                 //
2075                 // Returns true if we ar ea child of `b'.
2076                 //
2077                 public bool IsChildOf (Block b)
2078                 {
2079                         Block current = this;
2080                         
2081                         do {
2082                                 if (current.Parent == b)
2083                                         return true;
2084                                 current = current.Parent;
2085                         } while (current != null);
2086                         return false;
2087                 }
2088         }
2089
2090         //
2091         // A toplevel block contains extra information, the split is done
2092         // only to separate information that would otherwise bloat the more
2093         // lightweight Block.
2094         //
2095         // In particular, this was introduced when the support for Anonymous
2096         // Methods was implemented. 
2097         // 
2098         public class ToplevelBlock : Block {
2099                 //
2100                 // Pointer to the host of this anonymous method, or null
2101                 // if we are the topmost block
2102                 //
2103                 public ToplevelBlock Container;
2104                 CaptureContext capture_context;
2105
2106                 Hashtable capture_contexts;
2107
2108                 static int did = 0;
2109                 
2110                 int my_id = did++;
2111
2112                         
2113                 public void RegisterCaptureContext (CaptureContext cc)
2114                 {
2115                         if (capture_contexts == null)
2116                                 capture_contexts = new Hashtable ();
2117                         capture_contexts [cc] = cc;
2118                 }
2119
2120                 public void CompleteContexts ()
2121                 {
2122                         if (capture_contexts == null)
2123                                 return;
2124
2125                         foreach (CaptureContext cc in capture_contexts.Keys){
2126                                 cc.AdjustScopes ();
2127                         }
2128                 }
2129                 
2130                 public CaptureContext ToplevelBlockCaptureContext {
2131                         get {
2132                                 return capture_context;
2133                         }
2134                 }
2135                 
2136                 //
2137                 // Parent is only used by anonymous blocks to link back to their
2138                 // parents
2139                 //
2140                 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2141                         base (null, Flags.IsToplevel, parameters, start, Location.Null)
2142                 {
2143                         Container = container;
2144                 }
2145                 
2146                 public ToplevelBlock (Parameters parameters, Location start) :
2147                         base (null, Flags.IsToplevel, parameters, start, Location.Null)
2148                 {
2149                 }
2150
2151                 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2152                         base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2153                 {
2154                 }
2155
2156                 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2157                 {
2158                 }
2159
2160                 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2161                 {
2162                         if (capture_context == null)
2163                                 capture_context = new CaptureContext (this, loc, host);
2164                 }
2165
2166                 public CaptureContext CaptureContext {
2167                         get {
2168                                 return capture_context;
2169                         }
2170                 }
2171         }
2172         
2173         public class SwitchLabel {
2174                 Expression label;
2175                 object converted;
2176                 public Location loc;
2177
2178                 Label il_label;
2179                 bool  il_label_set;
2180                 Label il_label_code;
2181                 bool  il_label_code_set;
2182
2183                 //
2184                 // if expr == null, then it is the default case.
2185                 //
2186                 public SwitchLabel (Expression expr, Location l)
2187                 {
2188                         label = expr;
2189                         loc = l;
2190                 }
2191
2192                 public Expression Label {
2193                         get {
2194                                 return label;
2195                         }
2196                 }
2197
2198                 public object Converted {
2199                         get {
2200                                 return converted;
2201                         }
2202                 }
2203
2204                 public Label GetILLabel (EmitContext ec)
2205                 {
2206                         if (!il_label_set){
2207                                 il_label = ec.ig.DefineLabel ();
2208                                 il_label_set = true;
2209                         }
2210                         return il_label;
2211                 }
2212
2213                 public Label GetILLabelCode (EmitContext ec)
2214                 {
2215                         if (!il_label_code_set){
2216                                 il_label_code = ec.ig.DefineLabel ();
2217                                 il_label_code_set = true;
2218                         }
2219                         return il_label_code;
2220                 }                               
2221                 
2222                 //
2223                 // Resolves the expression, reduces it to a literal if possible
2224                 // and then converts it to the requested type.
2225                 //
2226                 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2227                 {
2228                         if (label == null)
2229                                 return true;
2230                         
2231                         Expression e = label.Resolve (ec);
2232
2233                         if (e == null)
2234                                 return false;
2235
2236                         if (!(e is Constant)){
2237                                 Report.Error (150, loc, "A constant value is expected, got: " + e);
2238                                 return false;
2239                         }
2240
2241                         if (e is StringConstant || e is NullLiteral){
2242                                 if (required_type == TypeManager.string_type){
2243                                         converted = e;
2244                                         return true;
2245                                 }
2246                         }
2247
2248                         converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2249                         if (converted == null)
2250                                 return false;
2251
2252                         return true;
2253                 }
2254         }
2255
2256         public class SwitchSection {
2257                 // An array of SwitchLabels.
2258                 public readonly ArrayList Labels;
2259                 public readonly Block Block;
2260                 
2261                 public SwitchSection (ArrayList labels, Block block)
2262                 {
2263                         Labels = labels;
2264                         Block = block;
2265                 }
2266         }
2267         
2268         public class Switch : Statement {
2269                 public readonly ArrayList Sections;
2270                 public Expression Expr;
2271
2272                 /// <summary>
2273                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
2274                 /// </summary>
2275                 public Hashtable Elements;
2276
2277                 /// <summary>
2278                 ///   The governing switch type
2279                 /// </summary>
2280                 public Type SwitchType;
2281
2282                 //
2283                 // Computed
2284                 //
2285                 bool got_default;
2286                 Label default_target;
2287                 Expression new_expr;
2288                 bool is_constant;
2289                 SwitchSection constant_section;
2290
2291                 //
2292                 // The types allowed to be implicitly cast from
2293                 // on the governing type
2294                 //
2295                 static Type [] allowed_types;
2296                 
2297                 public Switch (Expression e, ArrayList sects, Location l)
2298                 {
2299                         Expr = e;
2300                         Sections = sects;
2301                         loc = l;
2302                 }
2303
2304                 public bool GotDefault {
2305                         get {
2306                                 return got_default;
2307                         }
2308                 }
2309
2310                 public Label DefaultTarget {
2311                         get {
2312                                 return default_target;
2313                         }
2314                 }
2315
2316                 //
2317                 // Determines the governing type for a switch.  The returned
2318                 // expression might be the expression from the switch, or an
2319                 // expression that includes any potential conversions to the
2320                 // integral types or to string.
2321                 //
2322                 Expression SwitchGoverningType (EmitContext ec, Type t)
2323                 {
2324                         if (t == TypeManager.int32_type ||
2325                             t == TypeManager.uint32_type ||
2326                             t == TypeManager.char_type ||
2327                             t == TypeManager.byte_type ||
2328                             t == TypeManager.sbyte_type ||
2329                             t == TypeManager.ushort_type ||
2330                             t == TypeManager.short_type ||
2331                             t == TypeManager.uint64_type ||
2332                             t == TypeManager.int64_type ||
2333                             t == TypeManager.string_type ||
2334                                 t == TypeManager.bool_type ||
2335                                 t.IsSubclassOf (TypeManager.enum_type))
2336                                 return Expr;
2337
2338                         if (allowed_types == null){
2339                                 allowed_types = new Type [] {
2340                                         TypeManager.sbyte_type,
2341                                         TypeManager.byte_type,
2342                                         TypeManager.short_type,
2343                                         TypeManager.ushort_type,
2344                                         TypeManager.int32_type,
2345                                         TypeManager.uint32_type,
2346                                         TypeManager.int64_type,
2347                                         TypeManager.uint64_type,
2348                                         TypeManager.char_type,
2349                                         TypeManager.bool_type,
2350                                         TypeManager.string_type
2351                                 };
2352                         }
2353
2354                         //
2355                         // Try to find a *user* defined implicit conversion.
2356                         //
2357                         // If there is no implicit conversion, or if there are multiple
2358                         // conversions, we have to report an error
2359                         //
2360                         Expression converted = null;
2361                         foreach (Type tt in allowed_types){
2362                                 Expression e;
2363                                 
2364                                 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2365                                 if (e == null)
2366                                         continue;
2367
2368                                 if (converted != null){
2369                                         Report.Error (-12, loc, "More than one conversion to an integral " +
2370                                                       " type exists for type `" +
2371                                                       TypeManager.CSharpName (Expr.Type)+"'");
2372                                         return null;
2373                                 } else
2374                                         converted = e;
2375                         }
2376                         return converted;
2377                 }
2378
2379                 static string Error152 {
2380                         get {
2381                                 return "The label '{0}:' already occurs in this switch statement";
2382                         }
2383                 }
2384                 
2385                 //
2386                 // Performs the basic sanity checks on the switch statement
2387                 // (looks for duplicate keys and non-constant expressions).
2388                 //
2389                 // It also returns a hashtable with the keys that we will later
2390                 // use to compute the switch tables
2391                 //
2392                 bool CheckSwitch (EmitContext ec)
2393                 {
2394                         Type compare_type;
2395                         bool error = false;
2396                         Elements = new Hashtable ();
2397                                 
2398                         got_default = false;
2399
2400                         if (TypeManager.IsEnumType (SwitchType)){
2401                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2402                         } else
2403                                 compare_type = SwitchType;
2404                         
2405                         foreach (SwitchSection ss in Sections){
2406                                 foreach (SwitchLabel sl in ss.Labels){
2407                                         if (!sl.ResolveAndReduce (ec, SwitchType)){
2408                                                 error = true;
2409                                                 continue;
2410                                         }
2411
2412                                         if (sl.Label == null){
2413                                                 if (got_default){
2414                                                         Report.Error (152, sl.loc, Error152, "default");
2415                                                         error = true;
2416                                                 }
2417                                                 got_default = true;
2418                                                 continue;
2419                                         }
2420                                         
2421                                         object key = sl.Converted;
2422
2423                                         if (key is Constant)
2424                                                 key = ((Constant) key).GetValue ();
2425
2426                                         if (key == null)
2427                                                 key = NullLiteral.Null;
2428                                         
2429                                         string lname = null;
2430                                         if (compare_type == TypeManager.uint64_type){
2431                                                 ulong v = (ulong) key;
2432
2433                                                 if (Elements.Contains (v))
2434                                                         lname = v.ToString ();
2435                                                 else
2436                                                         Elements.Add (v, sl);
2437                                         } else if (compare_type == TypeManager.int64_type){
2438                                                 long v = (long) key;
2439
2440                                                 if (Elements.Contains (v))
2441                                                         lname = v.ToString ();
2442                                                 else
2443                                                         Elements.Add (v, sl);
2444                                         } else if (compare_type == TypeManager.uint32_type){
2445                                                 uint v = (uint) key;
2446
2447                                                 if (Elements.Contains (v))
2448                                                         lname = v.ToString ();
2449                                                 else
2450                                                         Elements.Add (v, sl);
2451                                         } else if (compare_type == TypeManager.char_type){
2452                                                 char v = (char) key;
2453                                                 
2454                                                 if (Elements.Contains (v))
2455                                                         lname = v.ToString ();
2456                                                 else
2457                                                         Elements.Add (v, sl);
2458                                         } else if (compare_type == TypeManager.byte_type){
2459                                                 byte v = (byte) key;
2460                                                 
2461                                                 if (Elements.Contains (v))
2462                                                         lname = v.ToString ();
2463                                                 else
2464                                                         Elements.Add (v, sl);
2465                                         } else if (compare_type == TypeManager.sbyte_type){
2466                                                 sbyte v = (sbyte) key;
2467                                                 
2468                                                 if (Elements.Contains (v))
2469                                                         lname = v.ToString ();
2470                                                 else
2471                                                         Elements.Add (v, sl);
2472                                         } else if (compare_type == TypeManager.short_type){
2473                                                 short v = (short) key;
2474                                                 
2475                                                 if (Elements.Contains (v))
2476                                                         lname = v.ToString ();
2477                                                 else
2478                                                         Elements.Add (v, sl);
2479                                         } else if (compare_type == TypeManager.ushort_type){
2480                                                 ushort v = (ushort) key;
2481                                                 
2482                                                 if (Elements.Contains (v))
2483                                                         lname = v.ToString ();
2484                                                 else
2485                                                         Elements.Add (v, sl);
2486                                         } else if (compare_type == TypeManager.string_type){
2487                                                 if (key is NullLiteral){
2488                                                         if (Elements.Contains (NullLiteral.Null))
2489                                                                 lname = "null";
2490                                                         else
2491                                                                 Elements.Add (NullLiteral.Null, null);
2492                                                 } else {
2493                                                         string s = (string) key;
2494
2495                                                         if (Elements.Contains (s))
2496                                                                 lname = s;
2497                                                         else
2498                                                                 Elements.Add (s, sl);
2499                                                 }
2500                                         } else if (compare_type == TypeManager.int32_type) {
2501                                                 int v = (int) key;
2502
2503                                                 if (Elements.Contains (v))
2504                                                         lname = v.ToString ();
2505                                                 else
2506                                                         Elements.Add (v, sl);
2507                                         } else if (compare_type == TypeManager.bool_type) {
2508                                                 bool v = (bool) key;
2509
2510                                                 if (Elements.Contains (v))
2511                                                         lname = v.ToString ();
2512                                                 else
2513                                                         Elements.Add (v, sl);
2514                                         }
2515                                         else
2516                                         {
2517                                                 throw new Exception ("Unknown switch type!" +
2518                                                                      SwitchType + " " + compare_type);
2519                                         }
2520
2521                                         if (lname != null) {
2522                                                 Report.Error (152, sl.loc, Error152, "case " + lname);
2523                                                 error = true;
2524                                         }
2525                                 }
2526                         }
2527                         if (error)
2528                                 return false;
2529
2530                         return true;
2531                 }
2532
2533                 void EmitObjectInteger (ILGenerator ig, object k)
2534                 {
2535                         if (k is int)
2536                                 IntConstant.EmitInt (ig, (int) k);
2537                         else if (k is Constant) {
2538                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2539                         } 
2540                         else if (k is uint)
2541                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2542                         else if (k is long)
2543                         {
2544                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2545                                 {
2546                                         IntConstant.EmitInt (ig, (int) (long) k);
2547                                         ig.Emit (OpCodes.Conv_I8);
2548                                 }
2549                                 else
2550                                         LongConstant.EmitLong (ig, (long) k);
2551                         }
2552                         else if (k is ulong)
2553                         {
2554                                 if ((ulong) k < (1L<<32))
2555                                 {
2556                                         IntConstant.EmitInt (ig, (int) (long) k);
2557                                         ig.Emit (OpCodes.Conv_U8);
2558                                 }
2559                                 else
2560                                 {
2561                                         LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2562                                 }
2563                         }
2564                         else if (k is char)
2565                                 IntConstant.EmitInt (ig, (int) ((char) k));
2566                         else if (k is sbyte)
2567                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2568                         else if (k is byte)
2569                                 IntConstant.EmitInt (ig, (int) ((byte) k));
2570                         else if (k is short)
2571                                 IntConstant.EmitInt (ig, (int) ((short) k));
2572                         else if (k is ushort)
2573                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
2574                         else if (k is bool)
2575                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2576                         else
2577                                 throw new Exception ("Unhandled case");
2578                 }
2579                 
2580                 // structure used to hold blocks of keys while calculating table switch
2581                 class KeyBlock : IComparable
2582                 {
2583                         public KeyBlock (long _nFirst)
2584                         {
2585                                 nFirst = nLast = _nFirst;
2586                         }
2587                         public long nFirst;
2588                         public long nLast;
2589                         public ArrayList rgKeys = null;
2590                         // how many items are in the bucket
2591                         public int Size = 1;
2592                         public int Length
2593                         {
2594                                 get { return (int) (nLast - nFirst + 1); }
2595                         }
2596                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2597                         {
2598                                 return kbLast.nLast - kbFirst.nFirst + 1;
2599                         }
2600                         public int CompareTo (object obj)
2601                         {
2602                                 KeyBlock kb = (KeyBlock) obj;
2603                                 int nLength = Length;
2604                                 int nLengthOther = kb.Length;
2605                                 if (nLengthOther == nLength)
2606                                         return (int) (kb.nFirst - nFirst);
2607                                 return nLength - nLengthOther;
2608                         }
2609                 }
2610
2611                 /// <summary>
2612                 /// This method emits code for a lookup-based switch statement (non-string)
2613                 /// Basically it groups the cases into blocks that are at least half full,
2614                 /// and then spits out individual lookup opcodes for each block.
2615                 /// It emits the longest blocks first, and short blocks are just
2616                 /// handled with direct compares.
2617                 /// </summary>
2618                 /// <param name="ec"></param>
2619                 /// <param name="val"></param>
2620                 /// <returns></returns>
2621                 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2622                 {
2623                         int cElements = Elements.Count;
2624                         object [] rgKeys = new object [cElements];
2625                         Elements.Keys.CopyTo (rgKeys, 0);
2626                         Array.Sort (rgKeys);
2627
2628                         // initialize the block list with one element per key
2629                         ArrayList rgKeyBlocks = new ArrayList ();
2630                         foreach (object key in rgKeys)
2631                                 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2632
2633                         KeyBlock kbCurr;
2634                         // iteratively merge the blocks while they are at least half full
2635                         // there's probably a really cool way to do this with a tree...
2636                         while (rgKeyBlocks.Count > 1)
2637                         {
2638                                 ArrayList rgKeyBlocksNew = new ArrayList ();
2639                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2640                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2641                                 {
2642                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2643                                         if ((kbCurr.Size + kb.Size) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
2644                                         {
2645                                                 // merge blocks
2646                                                 kbCurr.nLast = kb.nLast;
2647                                                 kbCurr.Size += kb.Size;
2648                                         }
2649                                         else
2650                                         {
2651                                                 // start a new block
2652                                                 rgKeyBlocksNew.Add (kbCurr);
2653                                                 kbCurr = kb;
2654                                         }
2655                                 }
2656                                 rgKeyBlocksNew.Add (kbCurr);
2657                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2658                                         break;
2659                                 rgKeyBlocks = rgKeyBlocksNew;
2660                         }
2661
2662                         // initialize the key lists
2663                         foreach (KeyBlock kb in rgKeyBlocks)
2664                                 kb.rgKeys = new ArrayList ();
2665
2666                         // fill the key lists
2667                         int iBlockCurr = 0;
2668                         if (rgKeyBlocks.Count > 0) {
2669                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2670                                 foreach (object key in rgKeys)
2671                                 {
2672                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2673                                                 System.Convert.ToInt64 (key) > kbCurr.nLast;
2674                                         if (fNextBlock)
2675                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2676                                         kbCurr.rgKeys.Add (key);
2677                                 }
2678                         }
2679
2680                         // sort the blocks so we can tackle the largest ones first
2681                         rgKeyBlocks.Sort ();
2682
2683                         // okay now we can start...
2684                         ILGenerator ig = ec.ig;
2685                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
2686                         Label lblDefault = ig.DefineLabel ();
2687
2688                         Type typeKeys = null;
2689                         if (rgKeys.Length > 0)
2690                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
2691
2692                         Type compare_type;
2693                         
2694                         if (TypeManager.IsEnumType (SwitchType))
2695                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2696                         else
2697                                 compare_type = SwitchType;
2698                         
2699                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2700                         {
2701                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2702                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2703                                 if (kb.Length <= 2)
2704                                 {
2705                                         foreach (object key in kb.rgKeys)
2706                                         {
2707                                                 ig.Emit (OpCodes.Ldloc, val);
2708                                                 EmitObjectInteger (ig, key);
2709                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
2710                                                 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2711                                         }
2712                                 }
2713                                 else
2714                                 {
2715                                         // TODO: if all the keys in the block are the same and there are
2716                                         //       no gaps/defaults then just use a range-check.
2717                                         if (compare_type == TypeManager.int64_type ||
2718                                                 compare_type == TypeManager.uint64_type)
2719                                         {
2720                                                 // TODO: optimize constant/I4 cases
2721
2722                                                 // check block range (could be > 2^31)
2723                                                 ig.Emit (OpCodes.Ldloc, val);
2724                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2725                                                 ig.Emit (OpCodes.Blt, lblDefault);
2726                                                 ig.Emit (OpCodes.Ldloc, val);
2727                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2728                                                 ig.Emit (OpCodes.Bgt, lblDefault);
2729
2730                                                 // normalize range
2731                                                 ig.Emit (OpCodes.Ldloc, val);
2732                                                 if (kb.nFirst != 0)
2733                                                 {
2734                                                         EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2735                                                         ig.Emit (OpCodes.Sub);
2736                                                 }
2737                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
2738                                         }
2739                                         else
2740                                         {
2741                                                 // normalize range
2742                                                 ig.Emit (OpCodes.Ldloc, val);
2743                                                 int nFirst = (int) kb.nFirst;
2744                                                 if (nFirst > 0)
2745                                                 {
2746                                                         IntConstant.EmitInt (ig, nFirst);
2747                                                         ig.Emit (OpCodes.Sub);
2748                                                 }
2749                                                 else if (nFirst < 0)
2750                                                 {
2751                                                         IntConstant.EmitInt (ig, -nFirst);
2752                                                         ig.Emit (OpCodes.Add);
2753                                                 }
2754                                         }
2755
2756                                         // first, build the list of labels for the switch
2757                                         int iKey = 0;
2758                                         int cJumps = kb.Length;
2759                                         Label [] rgLabels = new Label [cJumps];
2760                                         for (int iJump = 0; iJump < cJumps; iJump++)
2761                                         {
2762                                                 object key = kb.rgKeys [iKey];
2763                                                 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2764                                                 {
2765                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
2766                                                         rgLabels [iJump] = sl.GetILLabel (ec);
2767                                                         iKey++;
2768                                                 }
2769                                                 else
2770                                                         rgLabels [iJump] = lblDefault;
2771                                         }
2772                                         // emit the switch opcode
2773                                         ig.Emit (OpCodes.Switch, rgLabels);
2774                                 }
2775
2776                                 // mark the default for this block
2777                                 if (iBlock != 0)
2778                                         ig.MarkLabel (lblDefault);
2779                         }
2780
2781                         // TODO: find the default case and emit it here,
2782                         //       to prevent having to do the following jump.
2783                         //       make sure to mark other labels in the default section
2784
2785                         // the last default just goes to the end
2786                         ig.Emit (OpCodes.Br, lblDefault);
2787
2788                         // now emit the code for the sections
2789                         bool fFoundDefault = false;
2790                         foreach (SwitchSection ss in Sections)
2791                         {
2792                                 foreach (SwitchLabel sl in ss.Labels)
2793                                 {
2794                                         ig.MarkLabel (sl.GetILLabel (ec));
2795                                         ig.MarkLabel (sl.GetILLabelCode (ec));
2796                                         if (sl.Label == null)
2797                                         {
2798                                                 ig.MarkLabel (lblDefault);
2799                                                 fFoundDefault = true;
2800                                         }
2801                                 }
2802                                 ss.Block.Emit (ec);
2803                                 //ig.Emit (OpCodes.Br, lblEnd);
2804                         }
2805                         
2806                         if (!fFoundDefault) {
2807                                 ig.MarkLabel (lblDefault);
2808                         }
2809                         ig.MarkLabel (lblEnd);
2810                 }
2811                 //
2812                 // This simple emit switch works, but does not take advantage of the
2813                 // `switch' opcode. 
2814                 // TODO: remove non-string logic from here
2815                 // TODO: binary search strings?
2816                 //
2817                 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2818                 {
2819                         ILGenerator ig = ec.ig;
2820                         Label end_of_switch = ig.DefineLabel ();
2821                         Label next_test = ig.DefineLabel ();
2822                         Label null_target = ig.DefineLabel ();
2823                         bool default_found = false;
2824                         bool first_test = true;
2825                         bool pending_goto_end = false;
2826                         bool null_found;
2827                         bool default_at_end = false;
2828                         
2829                         ig.Emit (OpCodes.Ldloc, val);
2830                         
2831                         if (Elements.Contains (NullLiteral.Null)){
2832                                 ig.Emit (OpCodes.Brfalse, null_target);
2833                         } else
2834                                 ig.Emit (OpCodes.Brfalse, default_target);
2835                         
2836                         ig.Emit (OpCodes.Ldloc, val);
2837                         ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2838                         ig.Emit (OpCodes.Stloc, val);
2839                 
2840                         int section_count = Sections.Count;
2841                         for (int section = 0; section < section_count; section++){
2842                                 SwitchSection ss = (SwitchSection) Sections [section];
2843                                 Label sec_begin = ig.DefineLabel ();
2844
2845                                 if (pending_goto_end)
2846                                         ig.Emit (OpCodes.Br, end_of_switch);
2847
2848                                 int label_count = ss.Labels.Count;
2849                                 bool mark_default = false;
2850                                 null_found = false;
2851                                 for (int label = 0; label < label_count; label++){
2852                                         SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2853                                         ig.MarkLabel (sl.GetILLabel (ec));
2854                                         
2855                                         if (!first_test){
2856                                                 ig.MarkLabel (next_test);
2857                                                 next_test = ig.DefineLabel ();
2858                                         }
2859                                         //
2860                                         // If we are the default target
2861                                         //
2862                                         if (sl.Label == null){
2863                                                 if (label+1 == label_count)
2864                                                         default_at_end = true;
2865                                                 mark_default = true;
2866                                                 default_found = true;
2867                                         } else {
2868                                                 object lit = sl.Converted;
2869
2870                                                 if (lit is NullLiteral){
2871                                                         null_found = true;
2872                                                         if (label_count == 1)
2873                                                                 ig.Emit (OpCodes.Br, next_test);
2874                                                         continue;
2875                                                                               
2876                                                 }
2877                                                 StringConstant str = (StringConstant) lit;
2878                                                 
2879                                                 ig.Emit (OpCodes.Ldloc, val);
2880                                                 ig.Emit (OpCodes.Ldstr, str.Value);
2881                                                 if (label_count == 1)
2882                                                         ig.Emit (OpCodes.Bne_Un, next_test);
2883                                                 else {
2884                                                         if (label+1 == label_count)
2885                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
2886                                                         else
2887                                                                 ig.Emit (OpCodes.Beq, sec_begin);
2888                                                 }
2889                                         }
2890                                 }
2891                                 if (null_found)
2892                                         ig.MarkLabel (null_target);
2893                                 ig.MarkLabel (sec_begin);
2894                                 foreach (SwitchLabel sl in ss.Labels)
2895                                         ig.MarkLabel (sl.GetILLabelCode (ec));
2896
2897                                 if (mark_default)
2898                                         ig.MarkLabel (default_target);
2899                                 ss.Block.Emit (ec);
2900                                 pending_goto_end = !ss.Block.HasRet;
2901                                 first_test = false;
2902                         }
2903                         ig.MarkLabel (next_test);
2904                         if (default_found){
2905                                 if (!default_at_end)
2906                                         ig.Emit (OpCodes.Br, default_target);
2907                         } else 
2908                                 ig.MarkLabel (default_target);
2909                         ig.MarkLabel (end_of_switch);
2910                 }
2911
2912                 SwitchSection FindSection (SwitchLabel label)
2913                 {
2914                         foreach (SwitchSection ss in Sections){
2915                                 foreach (SwitchLabel sl in ss.Labels){
2916                                         if (label == sl)
2917                                                 return ss;
2918                                 }
2919                         }
2920
2921                         return null;
2922                 }
2923
2924                 bool ResolveConstantSwitch (EmitContext ec)
2925                 {
2926                         object key = ((Constant) new_expr).GetValue ();
2927                         SwitchLabel label = (SwitchLabel) Elements [key];
2928
2929                         if (label == null)
2930                                 return true;
2931
2932                         constant_section = FindSection (label);
2933                         if (constant_section == null)
2934                                 return true;
2935
2936                         if (constant_section.Block.Resolve (ec) != true)
2937                                 return false;
2938
2939                         return true;
2940                 }
2941
2942                 public override bool Resolve (EmitContext ec)
2943                 {
2944                         Expr = Expr.Resolve (ec);
2945                         if (Expr == null)
2946                                 return false;
2947
2948                         new_expr = SwitchGoverningType (ec, Expr.Type);
2949                         if (new_expr == null){
2950                                 Report.Error (151, loc, "An integer type or string was expected for switch");
2951                                 return false;
2952                         }
2953
2954                         // Validate switch.
2955                         SwitchType = new_expr.Type;
2956
2957                         if (!CheckSwitch (ec))
2958                                 return false;
2959
2960                         Switch old_switch = ec.Switch;
2961                         ec.Switch = this;
2962                         ec.Switch.SwitchType = SwitchType;
2963
2964                         Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2965                         ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2966
2967                         is_constant = new_expr is Constant;
2968                         if (is_constant) {
2969                                 object key = ((Constant) new_expr).GetValue ();
2970                                 SwitchLabel label = (SwitchLabel) Elements [key];
2971
2972                                 constant_section = FindSection (label);
2973                         }
2974
2975                         bool first = true;
2976                         foreach (SwitchSection ss in Sections){
2977                                 if (!first)
2978                                         ec.CurrentBranching.CreateSibling (
2979                                                 null, FlowBranching.SiblingType.SwitchSection);
2980                                 else
2981                                         first = false;
2982
2983                                 if (is_constant && (ss != constant_section)) {
2984                                         // If we're a constant switch, we're only emitting
2985                                         // one single section - mark all the others as
2986                                         // unreachable.
2987                                         ec.CurrentBranching.CurrentUsageVector.Goto ();
2988                                         if (!ss.Block.ResolveUnreachable (ec, true))
2989                                                 return false;
2990                                 } else {
2991                                         if (!ss.Block.Resolve (ec))
2992                                                 return false;
2993                                 }
2994                         }
2995
2996                         if (!got_default)
2997                                 ec.CurrentBranching.CreateSibling (
2998                                         null, FlowBranching.SiblingType.SwitchSection);
2999
3000                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3001                         ec.Switch = old_switch;
3002
3003                         Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3004                                       reachability);
3005
3006                         return true;
3007                 }
3008                 
3009                 protected override void DoEmit (EmitContext ec)
3010                 {
3011                         ILGenerator ig = ec.ig;
3012
3013                         // Store variable for comparission purposes
3014                         LocalBuilder value;
3015                         if (!is_constant) {
3016                                 value = ig.DeclareLocal (SwitchType);
3017                                 new_expr.Emit (ec);
3018                                 ig.Emit (OpCodes.Stloc, value);
3019                         } else
3020                                 value = null;
3021
3022                         default_target = ig.DefineLabel ();
3023
3024                         //
3025                         // Setup the codegen context
3026                         //
3027                         Label old_end = ec.LoopEnd;
3028                         Switch old_switch = ec.Switch;
3029                         
3030                         ec.LoopEnd = ig.DefineLabel ();
3031                         ec.Switch = this;
3032
3033                         // Emit Code.
3034                         if (is_constant) {
3035                                 if (constant_section != null)
3036                                         constant_section.Block.Emit (ec);
3037                         } else if (SwitchType == TypeManager.string_type)
3038                                 SimpleSwitchEmit (ec, value);
3039                         else
3040                                 TableSwitchEmit (ec, value);
3041
3042                         // Restore context state. 
3043                         ig.MarkLabel (ec.LoopEnd);
3044
3045                         //
3046                         // Restore the previous context
3047                         //
3048                         ec.LoopEnd = old_end;
3049                         ec.Switch = old_switch;
3050                 }
3051         }
3052
3053         public abstract class ExceptionStatement : Statement
3054         {
3055                 public abstract void EmitFinally (EmitContext ec);
3056
3057                 protected bool emit_finally = true;
3058                 ArrayList parent_vectors;
3059
3060                 protected void DoEmitFinally (EmitContext ec)
3061                 {
3062                         if (emit_finally)
3063                                 ec.ig.BeginFinallyBlock ();
3064                         else
3065                                 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3066                         EmitFinally (ec);
3067                 }
3068
3069                 protected void ResolveFinally (FlowBranchingException branching)
3070                 {
3071                         emit_finally = branching.EmitFinally;
3072                         if (!emit_finally)
3073                                 branching.Parent.StealFinallyClauses (ref parent_vectors);
3074                 }
3075         }
3076
3077         public class Lock : ExceptionStatement {
3078                 Expression expr;
3079                 Statement Statement;
3080                 LocalBuilder temp;
3081                         
3082                 public Lock (Expression expr, Statement stmt, Location l)
3083                 {
3084                         this.expr = expr;
3085                         Statement = stmt;
3086                         loc = l;
3087                 }
3088
3089                 public override bool Resolve (EmitContext ec)
3090                 {
3091                         expr = expr.Resolve (ec);
3092                         if (expr == null)
3093                                 return false;
3094
3095                         if (expr.Type.IsValueType){
3096                                 Error (185, "lock statement requires the expression to be " +
3097                                        " a reference type (type is: `{0}'",
3098                                        TypeManager.CSharpName (expr.Type));
3099                                 return false;
3100                         }
3101
3102                         FlowBranchingException branching = ec.StartFlowBranching (this);
3103                         bool ok = Statement.Resolve (ec);
3104                         if (!ok) {
3105                                 ec.KillFlowBranching ();
3106                                 return false;
3107                         }
3108
3109                         ResolveFinally (branching);
3110
3111                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3112                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3113                                 // Unfortunately, System.Reflection.Emit automatically emits
3114                                 // a leave to the end of the finally block.
3115                                 // This is a problem if `returns' is true since we may jump
3116                                 // to a point after the end of the method.
3117                                 // As a workaround, emit an explicit ret here.
3118                                 ec.NeedReturnLabel ();
3119                         }
3120
3121                         return true;
3122                 }
3123                 
3124                 protected override void DoEmit (EmitContext ec)
3125                 {
3126                         Type type = expr.Type;
3127                         
3128                         ILGenerator ig = ec.ig;
3129                         temp = ig.DeclareLocal (type);
3130                                 
3131                         expr.Emit (ec);
3132                         ig.Emit (OpCodes.Dup);
3133                         ig.Emit (OpCodes.Stloc, temp);
3134                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3135
3136                         // try
3137                         if (emit_finally)
3138                                 ig.BeginExceptionBlock ();
3139                         Statement.Emit (ec);
3140                         
3141                         // finally
3142                         DoEmitFinally (ec);
3143                         if (emit_finally)
3144                                 ig.EndExceptionBlock ();
3145                 }
3146
3147                 public override void EmitFinally (EmitContext ec)
3148                 {
3149                         ILGenerator ig = ec.ig;
3150                         ig.Emit (OpCodes.Ldloc, temp);
3151                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3152                 }
3153         }
3154
3155         public class Unchecked : Statement {
3156                 public readonly Block Block;
3157                 
3158                 public Unchecked (Block b)
3159                 {
3160                         Block = b;
3161                         b.Unchecked = true;
3162                 }
3163
3164                 public override bool Resolve (EmitContext ec)
3165                 {
3166                         bool previous_state = ec.CheckState;
3167                         bool previous_state_const = ec.ConstantCheckState;
3168
3169                         ec.CheckState = false;
3170                         ec.ConstantCheckState = false;
3171                         bool ret = Block.Resolve (ec);
3172                         ec.CheckState = previous_state;
3173                         ec.ConstantCheckState = previous_state_const;
3174
3175                         return ret;
3176                 }
3177                 
3178                 protected override void DoEmit (EmitContext ec)
3179                 {
3180                         bool previous_state = ec.CheckState;
3181                         bool previous_state_const = ec.ConstantCheckState;
3182                         
3183                         ec.CheckState = false;
3184                         ec.ConstantCheckState = false;
3185                         Block.Emit (ec);
3186                         ec.CheckState = previous_state;
3187                         ec.ConstantCheckState = previous_state_const;
3188                 }
3189         }
3190
3191         public class Checked : Statement {
3192                 public readonly Block Block;
3193                 
3194                 public Checked (Block b)
3195                 {
3196                         Block = b;
3197                         b.Unchecked = false;
3198                 }
3199
3200                 public override bool Resolve (EmitContext ec)
3201                 {
3202                         bool previous_state = ec.CheckState;
3203                         bool previous_state_const = ec.ConstantCheckState;
3204                         
3205                         ec.CheckState = true;
3206                         ec.ConstantCheckState = true;
3207                         bool ret = Block.Resolve (ec);
3208                         ec.CheckState = previous_state;
3209                         ec.ConstantCheckState = previous_state_const;
3210
3211                         return ret;
3212                 }
3213
3214                 protected override void DoEmit (EmitContext ec)
3215                 {
3216                         bool previous_state = ec.CheckState;
3217                         bool previous_state_const = ec.ConstantCheckState;
3218                         
3219                         ec.CheckState = true;
3220                         ec.ConstantCheckState = true;
3221                         Block.Emit (ec);
3222                         ec.CheckState = previous_state;
3223                         ec.ConstantCheckState = previous_state_const;
3224                 }
3225         }
3226
3227         public class Unsafe : Statement {
3228                 public readonly Block Block;
3229
3230                 public Unsafe (Block b)
3231                 {
3232                         Block = b;
3233                         Block.Unsafe = true;
3234                 }
3235
3236                 public override bool Resolve (EmitContext ec)
3237                 {
3238                         bool previous_state = ec.InUnsafe;
3239                         bool val;
3240                         
3241                         ec.InUnsafe = true;
3242                         val = Block.Resolve (ec);
3243                         ec.InUnsafe = previous_state;
3244
3245                         return val;
3246                 }
3247                 
3248                 protected override void DoEmit (EmitContext ec)
3249                 {
3250                         bool previous_state = ec.InUnsafe;
3251                         
3252                         ec.InUnsafe = true;
3253                         Block.Emit (ec);
3254                         ec.InUnsafe = previous_state;
3255                 }
3256         }
3257
3258         // 
3259         // Fixed statement
3260         //
3261         public class Fixed : Statement {
3262                 Expression type;
3263                 ArrayList declarators;
3264                 Statement statement;
3265                 Type expr_type;
3266                 FixedData[] data;
3267                 bool has_ret;
3268
3269                 struct FixedData {
3270                         public bool is_object;
3271                         public LocalInfo vi;
3272                         public Expression expr;
3273                         public Expression converted;
3274                 }                       
3275
3276                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3277                 {
3278                         this.type = type;
3279                         declarators = decls;
3280                         statement = stmt;
3281                         loc = l;
3282                 }
3283
3284                 public override bool Resolve (EmitContext ec)
3285                 {
3286                         if (!ec.InUnsafe){
3287                                 Expression.UnsafeError (loc);
3288                                 return false;
3289                         }
3290                         
3291                         TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3292                         if (texpr == null)
3293                                 return false;
3294
3295                         expr_type = texpr.ResolveType (ec);
3296
3297                         CheckObsolete (expr_type);
3298
3299                         if (ec.RemapToProxy){
3300                                 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3301                                 return false;
3302                         }
3303                         
3304                         data = new FixedData [declarators.Count];
3305
3306                         if (!expr_type.IsPointer){
3307                                 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3308                                 return false;
3309                         }
3310                         
3311                         int i = 0;
3312                         foreach (Pair p in declarators){
3313                                 LocalInfo vi = (LocalInfo) p.First;
3314                                 Expression e = (Expression) p.Second;
3315
3316                                 vi.VariableInfo.SetAssigned (ec);
3317                                 vi.ReadOnly = true;
3318
3319                                 //
3320                                 // The rules for the possible declarators are pretty wise,
3321                                 // but the production on the grammar is more concise.
3322                                 //
3323                                 // So we have to enforce these rules here.
3324                                 //
3325                                 // We do not resolve before doing the case 1 test,
3326                                 // because the grammar is explicit in that the token &
3327                                 // is present, so we need to test for this particular case.
3328                                 //
3329
3330                                 if (e is Cast){
3331                                         Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3332                                         return false;
3333                                 }
3334                                 
3335                                 //
3336                                 // Case 1: & object.
3337                                 //
3338                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3339                                         Expression child = ((Unary) e).Expr;
3340
3341                                         if (child is ParameterReference || child is LocalVariableReference){
3342                                                 Report.Error (
3343                                                         213, loc, 
3344                                                         "No need to use fixed statement for parameters or " +
3345                                                         "local variable declarations (address is already " +
3346                                                         "fixed)");
3347                                                 return false;
3348                                         }
3349
3350                                         ec.InFixedInitializer = true;
3351                                         e = e.Resolve (ec);
3352                                         ec.InFixedInitializer = false;
3353                                         if (e == null)
3354                                                 return false;
3355
3356                                         child = ((Unary) e).Expr;
3357                                         
3358                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
3359                                                 return false;
3360
3361                                         data [i].is_object = true;
3362                                         data [i].expr = e;
3363                                         data [i].converted = null;
3364                                         data [i].vi = vi;
3365                                         i++;
3366
3367                                         continue;
3368                                 }
3369
3370                                 ec.InFixedInitializer = true;
3371                                 e = e.Resolve (ec);
3372                                 ec.InFixedInitializer = false;
3373                                 if (e == null)
3374                                         return false;
3375
3376                                 //
3377                                 // Case 2: Array
3378                                 //
3379                                 if (e.Type.IsArray){
3380                                         Type array_type = TypeManager.GetElementType (e.Type);
3381                                         
3382                                         //
3383                                         // Provided that array_type is unmanaged,
3384                                         //
3385                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
3386                                                 return false;
3387
3388                                         //
3389                                         // and T* is implicitly convertible to the
3390                                         // pointer type given in the fixed statement.
3391                                         //
3392                                         ArrayPtr array_ptr = new ArrayPtr (e, loc);
3393                                         
3394                                         Expression converted = Convert.ImplicitConversionRequired (
3395                                                 ec, array_ptr, vi.VariableType, loc);
3396                                         if (converted == null)
3397                                                 return false;
3398
3399                                         data [i].is_object = false;
3400                                         data [i].expr = e;
3401                                         data [i].converted = converted;
3402                                         data [i].vi = vi;
3403                                         i++;
3404
3405                                         continue;
3406                                 }
3407
3408                                 //
3409                                 // Case 3: string
3410                                 //
3411                                 if (e.Type == TypeManager.string_type){
3412                                         data [i].is_object = false;
3413                                         data [i].expr = e;
3414                                         data [i].converted = null;
3415                                         data [i].vi = vi;
3416                                         i++;
3417                                         continue;
3418                                 }
3419
3420                                 //
3421                                 // For other cases, flag a `this is already fixed expression'
3422                                 //
3423                                 if (e is LocalVariableReference || e is ParameterReference ||
3424                                     Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3425                                     
3426                                         Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3427                                         return false;
3428                                 }
3429
3430                                 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3431                                 return false;
3432                         }
3433
3434                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3435
3436                         if (!statement.Resolve (ec)) {
3437                                 ec.KillFlowBranching ();
3438                                 return false;
3439                         }
3440
3441                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3442                         has_ret = reachability.IsUnreachable;
3443
3444                         return true;
3445                 }
3446                 
3447                 protected override void DoEmit (EmitContext ec)
3448                 {
3449                         ILGenerator ig = ec.ig;
3450
3451                         LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3452                         
3453                         for (int i = 0; i < data.Length; i++) {
3454                                 LocalInfo vi = data [i].vi;
3455
3456                                 //
3457                                 // Case 1: & object.
3458                                 //
3459                                 if (data [i].is_object) {
3460                                         //
3461                                         // Store pointer in pinned location
3462                                         //
3463                                         data [i].expr.Emit (ec);
3464                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3465                                         clear_list [i] = vi.LocalBuilder;
3466                                         continue;
3467                                 }
3468
3469                                 //
3470                                 // Case 2: Array
3471                                 //
3472                                 if (data [i].expr.Type.IsArray){
3473                                         //
3474                                         // Store pointer in pinned location
3475                                         //
3476                                         data [i].converted.Emit (ec);
3477                                         
3478                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3479                                         clear_list [i] = vi.LocalBuilder;
3480                                         continue;
3481                                 }
3482
3483                                 //
3484                                 // Case 3: string
3485                                 //
3486                                 if (data [i].expr.Type == TypeManager.string_type){
3487                                         LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3488                                         clear_list [i] = pinned_string;
3489                                         
3490                                         data [i].expr.Emit (ec);
3491                                         ig.Emit (OpCodes.Stloc, pinned_string);
3492
3493                                         Expression sptr = new StringPtr (pinned_string, loc);
3494                                         Expression converted = Convert.ImplicitConversionRequired (
3495                                                 ec, sptr, vi.VariableType, loc);
3496                                         
3497                                         if (converted == null)
3498                                                 continue;
3499
3500                                         converted.Emit (ec);
3501                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3502                                 }
3503                         }
3504
3505                         statement.Emit (ec);
3506
3507                         if (has_ret)
3508                                 return;
3509
3510                         //
3511                         // Clear the pinned variable
3512                         //
3513                         for (int i = 0; i < data.Length; i++) {
3514                                 if (data [i].is_object || data [i].expr.Type.IsArray) {
3515                                         ig.Emit (OpCodes.Ldc_I4_0);
3516                                         ig.Emit (OpCodes.Conv_U);
3517                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3518                                 } else if (data [i].expr.Type == TypeManager.string_type){
3519                                         ig.Emit (OpCodes.Ldnull);
3520                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3521                                 }
3522                         }
3523                 }
3524         }
3525         
3526         public class Catch: Statement {
3527                 public readonly string Name;
3528                 public readonly Block  Block;
3529
3530                 Expression type_expr;
3531                 Type type;
3532                 
3533                 public Catch (Expression type, string name, Block block, Location l)
3534                 {
3535                         type_expr = type;
3536                         Name = name;
3537                         Block = block;
3538                         loc = l;
3539                 }
3540
3541                 public Type CatchType {
3542                         get {
3543                                 return type;
3544                         }
3545                 }
3546
3547                 public bool IsGeneral {
3548                         get {
3549                                 return type_expr == null;
3550                         }
3551                 }
3552
3553                 protected override void DoEmit(EmitContext ec)
3554                 {
3555                 }
3556
3557                 public override bool Resolve (EmitContext ec)
3558                 {
3559                         if (type_expr != null) {
3560                                 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3561                                 if (te == null)
3562                                         return false;
3563
3564                                 type = te.ResolveType (ec);
3565
3566                                 CheckObsolete (type);
3567
3568                                 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3569                                         Error (155, "The type caught or thrown must be derived from System.Exception");
3570                                         return false;
3571                                 }
3572                         } else
3573                                 type = null;
3574
3575                         return Block.Resolve (ec);
3576                 }
3577         }
3578
3579         public class Try : ExceptionStatement {
3580                 public readonly Block Fini, Block;
3581                 public readonly ArrayList Specific;
3582                 public readonly Catch General;
3583
3584                 bool need_exc_block;
3585                 
3586                 //
3587                 // specific, general and fini might all be null.
3588                 //
3589                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3590                 {
3591                         if (specific == null && general == null){
3592                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3593                         }
3594                         
3595                         this.Block = block;
3596                         this.Specific = specific;
3597                         this.General = general;
3598                         this.Fini = fini;
3599                         loc = l;
3600                 }
3601
3602                 public override bool Resolve (EmitContext ec)
3603                 {
3604                         bool ok = true;
3605                         
3606                         FlowBranchingException branching = ec.StartFlowBranching (this);
3607
3608                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3609
3610                         if (!Block.Resolve (ec))
3611                                 ok = false;
3612
3613                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3614
3615                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
3616
3617                         Type[] prevCatches = new Type [Specific.Count];
3618                         int last_index = 0;
3619                         foreach (Catch c in Specific){
3620                                 ec.CurrentBranching.CreateSibling (
3621                                         c.Block, FlowBranching.SiblingType.Catch);
3622
3623                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3624
3625                                 if (c.Name != null) {
3626                                         LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3627                                         if (vi == null)
3628                                                 throw new Exception ();
3629
3630                                         vi.VariableInfo = null;
3631                                 }
3632
3633                                 if (!c.Resolve (ec))
3634                                         return false;
3635
3636                                 Type resolvedType = c.CatchType;
3637                                 for (int ii = 0; ii < last_index; ++ii) {
3638                                         if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3639                                                 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3640                                                 return false;
3641                                         }
3642                                 }
3643
3644                                 prevCatches [last_index++] = resolvedType;
3645                                 need_exc_block = true;
3646                         }
3647
3648                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3649
3650                         if (General != null){
3651                                 ec.CurrentBranching.CreateSibling (
3652                                         General.Block, FlowBranching.SiblingType.Catch);
3653
3654                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3655
3656                                 if (!General.Resolve (ec))
3657                                         ok = false;
3658
3659                                 need_exc_block = true;
3660                         }
3661
3662                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3663
3664                         if (Fini != null) {
3665                                 if (ok)
3666                                         ec.CurrentBranching.CreateSibling (
3667                                                 Fini, FlowBranching.SiblingType.Finally);
3668
3669                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3670
3671                                 if (!Fini.Resolve (ec))
3672                                         ok = false;
3673                         }
3674
3675                         ResolveFinally (branching);
3676                         need_exc_block |= emit_finally;
3677
3678                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3679
3680                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3681
3682                         Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3683
3684                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3685                                 // Unfortunately, System.Reflection.Emit automatically emits
3686                                 // a leave to the end of the finally block.  This is a problem
3687                                 // if `returns' is true since we may jump to a point after the
3688                                 // end of the method.
3689                                 // As a workaround, emit an explicit ret here.
3690                                 ec.NeedReturnLabel ();
3691                         }
3692
3693                         return ok;
3694                 }
3695                 
3696                 protected override void DoEmit (EmitContext ec)
3697                 {
3698                         ILGenerator ig = ec.ig;
3699
3700                         if (need_exc_block)
3701                                 ig.BeginExceptionBlock ();
3702                         Block.Emit (ec);
3703
3704                         foreach (Catch c in Specific){
3705                                 LocalInfo vi;
3706                                 
3707                                 ig.BeginCatchBlock (c.CatchType);
3708
3709                                 if (c.Name != null){
3710                                         vi = c.Block.GetLocalInfo (c.Name);
3711                                         if (vi == null)
3712                                                 throw new Exception ("Variable does not exist in this block");
3713
3714                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3715                                 } else
3716                                         ig.Emit (OpCodes.Pop);
3717                                 
3718                                 c.Block.Emit (ec);
3719                         }
3720
3721                         if (General != null){
3722                                 ig.BeginCatchBlock (TypeManager.object_type);
3723                                 ig.Emit (OpCodes.Pop);
3724                                 General.Block.Emit (ec);
3725                         }
3726
3727                         DoEmitFinally (ec);
3728                         if (need_exc_block)
3729                                 ig.EndExceptionBlock ();
3730                 }
3731
3732                 public override void EmitFinally (EmitContext ec)
3733                 {
3734                         if (Fini != null){
3735                                 Fini.Emit (ec);
3736                         }
3737                 }
3738         }
3739
3740         public class Using : ExceptionStatement {
3741                 object expression_or_block;
3742                 Statement Statement;
3743                 ArrayList var_list;
3744                 Expression expr;
3745                 Type expr_type;
3746                 Expression conv;
3747                 Expression [] resolved_vars;
3748                 Expression [] converted_vars;
3749                 ExpressionStatement [] assign;
3750                 LocalBuilder local_copy;
3751                 
3752                 public Using (object expression_or_block, Statement stmt, Location l)
3753                 {
3754                         this.expression_or_block = expression_or_block;
3755                         Statement = stmt;
3756                         loc = l;
3757                 }
3758
3759                 //
3760                 // Resolves for the case of using using a local variable declaration.
3761                 //
3762                 bool ResolveLocalVariableDecls (EmitContext ec)
3763                 {
3764                         int i = 0;
3765
3766                         TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3767                         if (texpr == null)
3768                                 return false;
3769
3770                         expr_type = texpr.ResolveType (ec);
3771
3772                         //
3773                         // The type must be an IDisposable or an implicit conversion
3774                         // must exist.
3775                         //
3776                         converted_vars = new Expression [var_list.Count];
3777                         resolved_vars = new Expression [var_list.Count];
3778                         assign = new ExpressionStatement [var_list.Count];
3779
3780                         bool need_conv = !TypeManager.ImplementsInterface (
3781                                 expr_type, TypeManager.idisposable_type);
3782
3783                         foreach (DictionaryEntry e in var_list){
3784                                 Expression var = (Expression) e.Key;
3785
3786                                 var = var.ResolveLValue (ec, new EmptyExpression ());
3787                                 if (var == null)
3788                                         return false;
3789
3790                                 resolved_vars [i] = var;
3791
3792                                 if (!need_conv) {
3793                                         i++;
3794                                         continue;
3795                                 }
3796
3797                                 converted_vars [i] = Convert.ImplicitConversionRequired (
3798                                         ec, var, TypeManager.idisposable_type, loc);
3799
3800                                 if (converted_vars [i] == null)
3801                                         return false;
3802
3803                                 i++;
3804                         }
3805
3806                         i = 0;
3807                         foreach (DictionaryEntry e in var_list){
3808                                 Expression var = resolved_vars [i];
3809                                 Expression new_expr = (Expression) e.Value;
3810                                 Expression a;
3811
3812                                 a = new Assign (var, new_expr, loc);
3813                                 a = a.Resolve (ec);
3814                                 if (a == null)
3815                                         return false;
3816
3817                                 if (!need_conv)
3818                                         converted_vars [i] = var;
3819                                 assign [i] = (ExpressionStatement) a;
3820                                 i++;
3821                         }
3822
3823                         return true;
3824                 }
3825
3826                 bool ResolveExpression (EmitContext ec)
3827                 {
3828                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3829                                 conv = Convert.ImplicitConversionRequired (
3830                                         ec, expr, TypeManager.idisposable_type, loc);
3831
3832                                 if (conv == null)
3833                                         return false;
3834                         }
3835
3836                         return true;
3837                 }
3838                 
3839                 //
3840                 // Emits the code for the case of using using a local variable declaration.
3841                 //
3842                 void EmitLocalVariableDecls (EmitContext ec)
3843                 {
3844                         ILGenerator ig = ec.ig;
3845                         int i = 0;
3846
3847                         for (i = 0; i < assign.Length; i++) {
3848                                 assign [i].EmitStatement (ec);
3849
3850                                 if (emit_finally)
3851                                         ig.BeginExceptionBlock ();
3852                         }
3853                         Statement.Emit (ec);
3854                         var_list.Reverse ();
3855
3856                         DoEmitFinally (ec);
3857                 }
3858
3859                 void EmitLocalVariableDeclFinally (EmitContext ec)
3860                 {
3861                         ILGenerator ig = ec.ig;
3862
3863                         int i = assign.Length;
3864                         foreach (DictionaryEntry e in var_list){
3865                                 Expression var = resolved_vars [--i];
3866                                 Label skip = ig.DefineLabel ();
3867
3868                                 if (!var.Type.IsValueType) {
3869                                         var.Emit (ec);
3870                                         ig.Emit (OpCodes.Brfalse, skip);
3871                                         converted_vars [i].Emit (ec);
3872                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3873                                 } else {
3874                                         Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3875
3876                                         if (!(ml is MethodGroupExpr)) {
3877                                                 var.Emit (ec);
3878                                                 ig.Emit (OpCodes.Box, var.Type);
3879                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3880                                         } else {
3881                                                 MethodInfo mi = null;
3882
3883                                                 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3884                                                         if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3885                                                                 mi = mk;
3886                                                                 break;
3887                                                         }
3888                                                 }
3889
3890                                                 if (mi == null) {
3891                                                         Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3892                                                         return;
3893                                                 }
3894
3895                                                 IMemoryLocation mloc = (IMemoryLocation) var;
3896
3897                                                 mloc.AddressOf (ec, AddressOp.Load);
3898                                                 ig.Emit (OpCodes.Call, mi);
3899                                         }
3900                                 }
3901
3902                                 ig.MarkLabel (skip);
3903
3904                                 if (emit_finally) {
3905                                         ig.EndExceptionBlock ();
3906                                         if (i > 0)
3907                                                 ig.BeginFinallyBlock ();
3908                                 }
3909                         }
3910                 }
3911
3912                 void EmitExpression (EmitContext ec)
3913                 {
3914                         //
3915                         // Make a copy of the expression and operate on that.
3916                         //
3917                         ILGenerator ig = ec.ig;
3918                         local_copy = ig.DeclareLocal (expr_type);
3919                         if (conv != null)
3920                                 conv.Emit (ec);
3921                         else
3922                                 expr.Emit (ec);
3923                         ig.Emit (OpCodes.Stloc, local_copy);
3924
3925                         if (emit_finally)
3926                                 ig.BeginExceptionBlock ();
3927
3928                         Statement.Emit (ec);
3929                         
3930                         DoEmitFinally (ec);
3931                         if (emit_finally)
3932                                 ig.EndExceptionBlock ();
3933                 }
3934
3935                 void EmitExpressionFinally (EmitContext ec)
3936                 {
3937                         ILGenerator ig = ec.ig;
3938                         Label skip = ig.DefineLabel ();
3939                         ig.Emit (OpCodes.Ldloc, local_copy);
3940                         ig.Emit (OpCodes.Brfalse, skip);
3941                         ig.Emit (OpCodes.Ldloc, local_copy);
3942                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3943                         ig.MarkLabel (skip);
3944                 }
3945                 
3946                 public override bool Resolve (EmitContext ec)
3947                 {
3948                         if (expression_or_block is DictionaryEntry){
3949                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3950                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3951
3952                                 if (!ResolveLocalVariableDecls (ec))
3953                                         return false;
3954
3955                         } else if (expression_or_block is Expression){
3956                                 expr = (Expression) expression_or_block;
3957
3958                                 expr = expr.Resolve (ec);
3959                                 if (expr == null)
3960                                         return false;
3961
3962                                 expr_type = expr.Type;
3963
3964                                 if (!ResolveExpression (ec))
3965                                         return false;
3966                         }
3967
3968                         FlowBranchingException branching = ec.StartFlowBranching (this);
3969
3970                         bool ok = Statement.Resolve (ec);
3971
3972                         if (!ok) {
3973                                 ec.KillFlowBranching ();
3974                                 return false;
3975                         }
3976
3977                         ResolveFinally (branching);                                     
3978                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3979
3980                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3981                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
3982                                 // to the end of the finally block.  This is a problem if `returns'
3983                                 // is true since we may jump to a point after the end of the method.
3984                                 // As a workaround, emit an explicit ret here.
3985                                 ec.NeedReturnLabel ();
3986                         }
3987
3988                         return true;
3989                 }
3990                 
3991                 protected override void DoEmit (EmitContext ec)
3992                 {
3993                         if (expression_or_block is DictionaryEntry)
3994                                 EmitLocalVariableDecls (ec);
3995                         else if (expression_or_block is Expression)
3996                                 EmitExpression (ec);
3997                 }
3998
3999                 public override void EmitFinally (EmitContext ec)
4000                 {
4001                         if (expression_or_block is DictionaryEntry)
4002                                 EmitLocalVariableDeclFinally (ec);
4003                         else if (expression_or_block is Expression)
4004                                 EmitExpressionFinally (ec);
4005                 }
4006         }
4007
4008         /// <summary>
4009         ///   Implementation of the foreach C# statement
4010         /// </summary>
4011         public class Foreach : ExceptionStatement {
4012                 Expression type;
4013                 Expression variable;
4014                 Expression expr;
4015                 Statement statement;
4016                 ForeachHelperMethods hm;
4017                 Expression empty, conv;
4018                 Type array_type, element_type;
4019                 Type var_type;
4020                 VariableStorage enumerator;
4021                 
4022                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4023                                 Statement stmt, Location l)
4024                 {
4025                         this.type = type;
4026                         this.variable = var;
4027                         this.expr = expr;
4028                         statement = stmt;
4029                         loc = l;
4030                 }
4031                 
4032                 public override bool Resolve (EmitContext ec)
4033                 {
4034                         expr = expr.Resolve (ec);
4035                         if (expr == null)
4036                                 return false;
4037
4038                         TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4039                         if (texpr == null)
4040                                 return false;
4041
4042                         var_type = texpr.ResolveType (ec);
4043                         
4044                         //
4045                         // We need an instance variable.  Not sure this is the best
4046                         // way of doing this.
4047                         //
4048                         // FIXME: When we implement propertyaccess, will those turn
4049                         // out to return values in ExprClass?  I think they should.
4050                         //
4051                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4052                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4053                                 error1579 (expr.Type);
4054                                 return false;
4055                         }
4056
4057                         if (expr.Type.IsArray) {
4058                                 array_type = expr.Type;
4059                                 element_type = TypeManager.GetElementType (array_type);
4060
4061                                 empty = new EmptyExpression (element_type);
4062                         } else {
4063                                 hm = ProbeCollectionType (ec, expr.Type);
4064                                 if (hm == null){
4065                                         error1579 (expr.Type);
4066                                         return false;
4067                                 }                       
4068
4069                                 array_type = expr.Type;
4070                                 element_type = hm.element_type;
4071
4072                                 empty = new EmptyExpression (hm.element_type);
4073                         }
4074
4075                         bool ok = true;
4076
4077                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4078                         ec.CurrentBranching.CreateSibling ();
4079
4080                         //
4081                         //
4082                         // FIXME: maybe we can apply the same trick we do in the
4083                         // array handling to avoid creating empty and conv in some cases.
4084                         //
4085                         // Although it is not as important in this case, as the type
4086                         // will not likely be object (what the enumerator will return).
4087                         //
4088                         conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4089                         if (conv == null)
4090                                 ok = false;
4091
4092                         variable = variable.ResolveLValue (ec, empty);
4093                         if (variable == null)
4094                                 ok = false;
4095
4096                         bool disposable = (hm != null) && hm.is_disposable;
4097                         FlowBranchingException branching = null;
4098                         if (disposable)
4099                                 branching = ec.StartFlowBranching (this);
4100
4101                         if (!statement.Resolve (ec))
4102                                 ok = false;
4103
4104                         if (disposable) {
4105                                 ResolveFinally (branching);
4106                                 ec.EndFlowBranching ();
4107                         } else
4108                                 emit_finally = true;
4109
4110                         ec.EndFlowBranching ();
4111
4112                         return ok;
4113                 }
4114                 
4115                 //
4116                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4117                 //
4118                 static MethodInfo FetchMethodMoveNext (Type t)
4119                 {
4120                         MemberList move_next_list;
4121                         
4122                         move_next_list = TypeContainer.FindMembers (
4123                                 t, MemberTypes.Method,
4124                                 BindingFlags.Public | BindingFlags.Instance,
4125                                 Type.FilterName, "MoveNext");
4126                         if (move_next_list.Count == 0)
4127                                 return null;
4128
4129                         foreach (MemberInfo m in move_next_list){
4130                                 MethodInfo mi = (MethodInfo) m;
4131                                 Type [] args;
4132                                 
4133                                 args = TypeManager.GetArgumentTypes (mi);
4134                                 if (args != null && args.Length == 0){
4135                                         if (mi.ReturnType == TypeManager.bool_type)
4136                                                 return mi;
4137                                 }
4138                         }
4139                         return null;
4140                 }
4141                 
4142                 //
4143                 // Retrieves a `public T get_Current ()' method from the Type `t'
4144                 //
4145                 static MethodInfo FetchMethodGetCurrent (Type t)
4146                 {
4147                         MemberList get_current_list;
4148
4149                         get_current_list = TypeContainer.FindMembers (
4150                                 t, MemberTypes.Method,
4151                                 BindingFlags.Public | BindingFlags.Instance,
4152                                 Type.FilterName, "get_Current");
4153                         if (get_current_list.Count == 0)
4154                                 return null;
4155
4156                         foreach (MemberInfo m in get_current_list){
4157                                 MethodInfo mi = (MethodInfo) m;
4158                                 Type [] args;
4159
4160                                 args = TypeManager.GetArgumentTypes (mi);
4161                                 if (args != null && args.Length == 0)
4162                                         return mi;
4163                         }
4164                         return null;
4165                 }
4166
4167                 //
4168                 // Retrieves a `public void Dispose ()' method from the Type `t'
4169                 //
4170                 static MethodInfo FetchMethodDispose (Type t)
4171                 {
4172                         MemberList dispose_list;
4173                         
4174                         dispose_list = TypeContainer.FindMembers (
4175                                 t, MemberTypes.Method,
4176                                 BindingFlags.Public | BindingFlags.Instance,
4177                                 Type.FilterName, "Dispose");
4178                         if (dispose_list.Count == 0)
4179                                 return null;
4180
4181                         foreach (MemberInfo m in dispose_list){
4182                                 MethodInfo mi = (MethodInfo) m;
4183                                 Type [] args;
4184                                 
4185                                 args = TypeManager.GetArgumentTypes (mi);
4186                                 if (args != null && args.Length == 0){
4187                                         if (mi.ReturnType == TypeManager.void_type)
4188                                                 return mi;
4189                                 }
4190                         }
4191                         return null;
4192                 }
4193
4194                 // 
4195                 // This struct records the helper methods used by the Foreach construct
4196                 //
4197                 class ForeachHelperMethods {
4198                         public EmitContext ec;
4199                         public MethodInfo get_enumerator;
4200                         public MethodInfo move_next;
4201                         public MethodInfo get_current;
4202                         public Type element_type;
4203                         public Type enumerator_type;
4204                         public bool is_disposable;
4205
4206                         public ForeachHelperMethods (EmitContext ec)
4207                         {
4208                                 this.ec = ec;
4209                                 this.element_type = TypeManager.object_type;
4210                                 this.enumerator_type = TypeManager.ienumerator_type;
4211                                 this.is_disposable = true;
4212                         }
4213                 }
4214                 
4215                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4216                 {
4217                         if (m == null)
4218                                 return false;
4219                         
4220                         if (!(m is MethodInfo))
4221                                 return false;
4222                         
4223                         if (m.Name != "GetEnumerator")
4224                                 return false;
4225
4226                         MethodInfo mi = (MethodInfo) m;
4227                         Type [] args = TypeManager.GetArgumentTypes (mi);
4228                         if (args != null){
4229                                 if (args.Length != 0)
4230                                         return false;
4231                         }
4232                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4233                         EmitContext ec = hm.ec;
4234
4235                         // Check whether GetEnumerator is public
4236                         if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4237                                 return false;
4238
4239                         if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4240                                 //
4241                                 // Apply the same optimization as MS: skip the GetEnumerator
4242                                 // returning an IEnumerator, and use the one returning a 
4243                                 // CharEnumerator instead. This allows us to avoid the 
4244                                 // try-finally block and the boxing.
4245                                 //
4246                                 return false;
4247
4248                         //
4249                         // Ok, we can access it, now make sure that we can do something
4250                         // with this `GetEnumerator'
4251                         //
4252                         
4253                         Type return_type = mi.ReturnType;
4254                         if (mi.ReturnType == TypeManager.ienumerator_type ||
4255                             TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4256                             (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4257                                 
4258                                 //
4259                                 // If it is not an interface, lets try to find the methods ourselves.
4260                                 // For example, if we have:
4261                                 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4262                                 // We can avoid the iface call. This is a runtime perf boost.
4263                                 // even bigger if we have a ValueType, because we avoid the cost
4264                                 // of boxing.
4265                                 //
4266                                 // We have to make sure that both methods exist for us to take
4267                                 // this path. If one of the methods does not exist, we will just
4268                                 // use the interface. Sadly, this complex if statement is the only
4269                                 // way I could do this without a goto
4270                                 //
4271                                 
4272                                 if (return_type.IsInterface ||
4273                                     (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4274                                     (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4275                                         
4276                                         hm.move_next = TypeManager.bool_movenext_void;
4277                                         hm.get_current = TypeManager.object_getcurrent_void;
4278                                         return true;    
4279                                 }
4280
4281                         } else {
4282
4283                                 //
4284                                 // Ok, so they dont return an IEnumerable, we will have to
4285                                 // find if they support the GetEnumerator pattern.
4286                                 //
4287                                 
4288                                 hm.move_next = FetchMethodMoveNext (return_type);
4289                                 if (hm.move_next == null)
4290                                         return false;
4291                                 
4292                                 hm.get_current = FetchMethodGetCurrent (return_type);
4293                                 if (hm.get_current == null)
4294                                         return false;
4295                         }
4296                         
4297                         hm.element_type = hm.get_current.ReturnType;
4298                         hm.enumerator_type = return_type;
4299                         hm.is_disposable = !hm.enumerator_type.IsSealed ||
4300                                 TypeManager.ImplementsInterface (
4301                                         hm.enumerator_type, TypeManager.idisposable_type);
4302
4303                         return true;
4304                 }
4305                 
4306                 /// <summary>
4307                 ///   This filter is used to find the GetEnumerator method
4308                 ///   on which IEnumerator operates
4309                 /// </summary>
4310                 static MemberFilter FilterEnumerator;
4311                 
4312                 static Foreach ()
4313                 {
4314                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4315                 }
4316
4317                 void error1579 (Type t)
4318                 {
4319                         Report.Error (1579, loc,
4320                                       "foreach statement cannot operate on variables of type `" +
4321                                       t.FullName + "' because that class does not provide a " +
4322                                       " GetEnumerator method or it is inaccessible");
4323                 }
4324
4325                 static bool TryType (Type t, ForeachHelperMethods hm)
4326                 {
4327                         MemberList mi;
4328                         
4329                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4330                                                         BindingFlags.Public | BindingFlags.NonPublic |
4331                                                         BindingFlags.Instance | BindingFlags.DeclaredOnly,
4332                                                         FilterEnumerator, hm);
4333
4334                         if (mi.Count == 0)
4335                                 return false;
4336
4337                         hm.get_enumerator = (MethodInfo) mi [0];
4338                         return true;    
4339                 }
4340                 
4341                 //
4342                 // Looks for a usable GetEnumerator in the Type, and if found returns
4343                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4344                 //
4345                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4346                 {
4347                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4348
4349                         for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4350                                 if (TryType (tt, hm))
4351                                         return hm;
4352                                 tt = tt.BaseType;
4353                         }
4354
4355                         //
4356                         // Now try to find the method in the interfaces
4357                         //
4358                         while (t != null){
4359                                 Type [] ifaces = t.GetInterfaces ();
4360
4361                                 foreach (Type i in ifaces){
4362                                         if (TryType (i, hm))
4363                                                 return hm;
4364                                 }
4365                                 
4366                                 //
4367                                 // Since TypeBuilder.GetInterfaces only returns the interface
4368                                 // types for this type, we have to keep looping, but once
4369                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4370                                 // done, because it returns all the types
4371                                 //
4372                                 if ((t is TypeBuilder))
4373                                         t = t.BaseType;
4374                                 else
4375                                         break;
4376                         } 
4377
4378                         return null;
4379                 }
4380
4381                 //
4382                 // FIXME: possible optimization.
4383                 // We might be able to avoid creating `empty' if the type is the sam
4384                 //
4385                 bool EmitCollectionForeach (EmitContext ec)
4386                 {
4387                         ILGenerator ig = ec.ig;
4388
4389                         enumerator = new VariableStorage (ec, hm.enumerator_type);
4390                         enumerator.EmitThis (ig);
4391                         //
4392                         // Instantiate the enumerator
4393                         //
4394                         if (expr.Type.IsValueType) {
4395                                 IMemoryLocation ml = expr as IMemoryLocation;
4396                                 // Load the address of the value type.
4397                                 if (ml == null) {
4398                                         // This happens if, for example, you have a property
4399                                         // returning a struct which is IEnumerable
4400                                         LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4401                                         expr.Emit (ec);
4402                                         ig.Emit (OpCodes.Stloc, t);
4403                                         ig.Emit (OpCodes.Ldloca, t);
4404                                         ec.FreeTemporaryLocal (t, expr.Type);
4405                                 } else {
4406                                         ml.AddressOf (ec, AddressOp.Load);
4407                                 }
4408                                 
4409                                 // Emit the call.
4410                                 if (hm.get_enumerator.DeclaringType.IsValueType) {
4411                                         // the method is declared on the value type
4412                                         ig.Emit (OpCodes.Call, hm.get_enumerator);
4413                                 } else {
4414                                         // it is an interface method, so we must box
4415                                         ig.Emit (OpCodes.Box, expr.Type);
4416                                         ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4417                                 }
4418                         } else {
4419                                 expr.Emit (ec);
4420                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4421                         }
4422                         enumerator.EmitStore (ig);
4423
4424                         //
4425                         // Protect the code in a try/finalize block, so that
4426                         // if the beast implement IDisposable, we get rid of it
4427                         //
4428                         if (hm.is_disposable && emit_finally)
4429                                 ig.BeginExceptionBlock ();
4430                         
4431                         Label end_try = ig.DefineLabel ();
4432                         
4433                         ig.MarkLabel (ec.LoopBegin);
4434                         
4435                         enumerator.EmitCall (ig, hm.move_next);
4436                         
4437                         ig.Emit (OpCodes.Brfalse, end_try);
4438
4439                         if (ec.InIterator)
4440                                 enumerator.EmitThis (ig);
4441                         enumerator.EmitCall (ig, hm.get_current);
4442
4443                         if (ec.InIterator){
4444                                 conv.Emit (ec);
4445                                 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4446                         } else 
4447                                 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4448                                 
4449                         statement.Emit (ec);
4450                         ig.Emit (OpCodes.Br, ec.LoopBegin);
4451                         ig.MarkLabel (end_try);
4452                         
4453                         //
4454                         // Now the finally block
4455                         //
4456                         if (hm.is_disposable) {
4457                                 DoEmitFinally (ec);
4458                                 if (emit_finally)
4459                                         ig.EndExceptionBlock ();
4460                         }
4461
4462                         ig.MarkLabel (ec.LoopEnd);
4463                         return false;
4464                 }
4465
4466                 public override void EmitFinally (EmitContext ec)
4467                 {
4468                         ILGenerator ig = ec.ig;
4469
4470                         if (hm.enumerator_type.IsValueType) {
4471                                 enumerator.EmitThis (ig);
4472
4473                                 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4474                                 if (mi != null) {
4475                                         enumerator.EmitLoadAddress (ig);
4476                                         ig.Emit (OpCodes.Call, mi);
4477                                 } else {
4478                                         enumerator.EmitLoad (ig);
4479                                         ig.Emit (OpCodes.Box, hm.enumerator_type);
4480                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4481                                 }
4482                         } else {
4483                                 Label call_dispose = ig.DefineLabel ();
4484
4485                                 enumerator.EmitThis (ig);
4486                                 enumerator.EmitLoad (ig);
4487                                 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4488                                 ig.Emit (OpCodes.Dup);
4489                                 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4490                                 ig.Emit (OpCodes.Pop);
4491
4492                                 Label end_finally = ig.DefineLabel ();
4493                                 ig.Emit (OpCodes.Br, end_finally);
4494
4495                                 ig.MarkLabel (call_dispose);
4496                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4497                                 ig.MarkLabel (end_finally);
4498
4499                                 if (emit_finally)
4500                                         ig.Emit (OpCodes.Endfinally);
4501                         }
4502                 }
4503
4504                 //
4505                 // FIXME: possible optimization.
4506                 // We might be able to avoid creating `empty' if the type is the sam
4507                 //
4508                 bool EmitArrayForeach (EmitContext ec)
4509                 {
4510                         int rank = array_type.GetArrayRank ();
4511                         ILGenerator ig = ec.ig;
4512
4513                         VariableStorage copy = new VariableStorage (ec, array_type);
4514                         
4515                         //
4516                         // Make our copy of the array
4517                         //
4518                         copy.EmitThis (ig);
4519                         expr.Emit (ec);
4520                         copy.EmitStore (ig);
4521                         
4522                         if (rank == 1){
4523                                 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4524
4525                                 Label loop, test;
4526
4527                                 counter.EmitThis (ig);
4528                                 ig.Emit (OpCodes.Ldc_I4_0);
4529                                 counter.EmitStore (ig);
4530                                 test = ig.DefineLabel ();
4531                                 ig.Emit (OpCodes.Br, test);
4532
4533                                 loop = ig.DefineLabel ();
4534                                 ig.MarkLabel (loop);
4535
4536                                 if (ec.InIterator)
4537                                         ec.EmitThis ();
4538                                 
4539                                 copy.EmitThis (ig);
4540                                 copy.EmitLoad (ig);
4541                                 counter.EmitThis (ig);
4542                                 counter.EmitLoad (ig);
4543
4544                                 //
4545                                 // Load the value, we load the value using the underlying type,
4546                                 // then we use the variable.EmitAssign to load using the proper cast.
4547                                 //
4548                                 ArrayAccess.EmitLoadOpcode (ig, element_type);
4549                                 if (ec.InIterator){
4550                                         conv.Emit (ec);
4551                                         ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4552                                 } else 
4553                                         ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4554
4555                                 statement.Emit (ec);
4556
4557                                 ig.MarkLabel (ec.LoopBegin);
4558                                 counter.EmitThis (ig);
4559                                 counter.EmitThis (ig);
4560                                 counter.EmitLoad (ig);
4561                                 ig.Emit (OpCodes.Ldc_I4_1);
4562                                 ig.Emit (OpCodes.Add);
4563                                 counter.EmitStore (ig);
4564
4565                                 ig.MarkLabel (test);
4566                                 counter.EmitThis (ig);
4567                                 counter.EmitLoad (ig);
4568                                 copy.EmitThis (ig);
4569                                 copy.EmitLoad (ig);
4570                                 ig.Emit (OpCodes.Ldlen);
4571                                 ig.Emit (OpCodes.Conv_I4);
4572                                 ig.Emit (OpCodes.Blt, loop);
4573                         } else {
4574                                 VariableStorage [] dim_len   = new VariableStorage [rank];
4575                                 VariableStorage [] dim_count = new VariableStorage [rank];
4576                                 Label [] loop = new Label [rank];
4577                                 Label [] test = new Label [rank];
4578                                 int dim;
4579                                 
4580                                 for (dim = 0; dim < rank; dim++){
4581                                         dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4582                                         dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4583                                         test [dim] = ig.DefineLabel ();
4584                                         loop [dim] = ig.DefineLabel ();
4585                                 }
4586                                         
4587                                 for (dim = 0; dim < rank; dim++){
4588                                         dim_len [dim].EmitThis (ig);
4589                                         copy.EmitThis (ig);
4590                                         copy.EmitLoad (ig);
4591                                         IntLiteral.EmitInt (ig, dim);
4592                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4593                                         dim_len [dim].EmitStore (ig);
4594                                         
4595                                 }
4596
4597                                 for (dim = 0; dim < rank; dim++){
4598                                         dim_count [dim].EmitThis (ig);
4599                                         ig.Emit (OpCodes.Ldc_I4_0);
4600                                         dim_count [dim].EmitStore (ig);
4601                                         ig.Emit (OpCodes.Br, test [dim]);
4602                                         ig.MarkLabel (loop [dim]);
4603                                 }
4604
4605                                 if (ec.InIterator)
4606                                         ec.EmitThis ();
4607                                 copy.EmitThis (ig);
4608                                 copy.EmitLoad (ig);
4609                                 for (dim = 0; dim < rank; dim++){
4610                                         dim_count [dim].EmitThis (ig);
4611                                         dim_count [dim].EmitLoad (ig);
4612                                 }
4613
4614                                 //
4615                                 // FIXME: Maybe we can cache the computation of `get'?
4616                                 //
4617                                 Type [] args = new Type [rank];
4618                                 MethodInfo get;
4619
4620                                 for (int i = 0; i < rank; i++)
4621                                         args [i] = TypeManager.int32_type;
4622
4623                                 ModuleBuilder mb = CodeGen.Module.Builder;
4624                                 get = mb.GetArrayMethod (
4625                                         array_type, "Get",
4626                                         CallingConventions.HasThis| CallingConventions.Standard,
4627                                         var_type, args);
4628                                 ig.Emit (OpCodes.Call, get);
4629                                 if (ec.InIterator){
4630                                         conv.Emit (ec);
4631                                         ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4632                                 } else 
4633                                         ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4634                                 statement.Emit (ec);
4635                                 ig.MarkLabel (ec.LoopBegin);
4636                                 for (dim = rank - 1; dim >= 0; dim--){
4637                                         dim_count [dim].EmitThis (ig);
4638                                         dim_count [dim].EmitThis (ig);
4639                                         dim_count [dim].EmitLoad (ig);
4640                                         ig.Emit (OpCodes.Ldc_I4_1);
4641                                         ig.Emit (OpCodes.Add);
4642                                         dim_count [dim].EmitStore (ig);
4643
4644                                         ig.MarkLabel (test [dim]);
4645                                         dim_count [dim].EmitThis (ig);
4646                                         dim_count [dim].EmitLoad (ig);
4647                                         dim_len [dim].EmitThis (ig);
4648                                         dim_len [dim].EmitLoad (ig);
4649                                         ig.Emit (OpCodes.Blt, loop [dim]);
4650                                 }
4651                         }
4652                         ig.MarkLabel (ec.LoopEnd);
4653                         
4654                         return false;
4655                 }
4656                 
4657                 protected override void DoEmit (EmitContext ec)
4658                 {
4659                         ILGenerator ig = ec.ig;
4660
4661                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4662                         ec.LoopBegin = ig.DefineLabel ();
4663                         ec.LoopEnd = ig.DefineLabel ();
4664                         
4665                         if (hm != null)
4666                                 EmitCollectionForeach (ec);
4667                         else
4668                                 EmitArrayForeach (ec);
4669                         
4670                         ec.LoopBegin = old_begin;
4671                         ec.LoopEnd = old_end;
4672                 }
4673         }
4674 }