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