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