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