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