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