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