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