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