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