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