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