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