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