* HtmlControl.cs: Make disabled an attribute of the control so it
[mono.git] / mcs / mcs / statement.cs
1 //
2 // statement.cs: Statement representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Martin Baulig (martin@gnome.org)
7 //
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 //
10
11 using System;
12 using System.Text;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
16
17 namespace Mono.CSharp {
18
19         using System.Collections;
20         
21         public abstract class Statement {
22                 public Location loc;
23                 
24                 ///
25                 /// Resolves the statement, true means that all sub-statements
26                 /// did resolve ok.
27                 //
28                 public virtual bool Resolve (EmitContext ec)
29                 {
30                         return true;
31                 }
32                 
33                 /// <summary>
34                 ///   Return value indicates whether all code paths emitted return.
35                 /// </summary>
36                 protected abstract 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                         Type compare_type;
2327                         
2328                         if (TypeManager.IsEnumType (SwitchType))
2329                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2330                         else
2331                                 compare_type = SwitchType;
2332                         
2333                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2334                         {
2335                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2336                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2337                                 if (kb.Length <= 2)
2338                                 {
2339                                         foreach (object key in kb.rgKeys)
2340                                         {
2341                                                 ig.Emit (OpCodes.Ldloc, val);
2342                                                 EmitObjectInteger (ig, key);
2343                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
2344                                                 ig.Emit (OpCodes.Beq, sl.ILLabel);
2345                                         }
2346                                 }
2347                                 else
2348                                 {
2349                                         // TODO: if all the keys in the block are the same and there are
2350                                         //       no gaps/defaults then just use a range-check.
2351                                         if (compare_type == TypeManager.int64_type ||
2352                                                 compare_type == TypeManager.uint64_type)
2353                                         {
2354                                                 // TODO: optimize constant/I4 cases
2355
2356                                                 // check block range (could be > 2^31)
2357                                                 ig.Emit (OpCodes.Ldloc, val);
2358                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2359                                                 ig.Emit (OpCodes.Blt, lblDefault);
2360                                                 ig.Emit (OpCodes.Ldloc, val);
2361                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2362                                                 ig.Emit (OpCodes.Bgt, lblDefault);
2363
2364                                                 // normalize range
2365                                                 ig.Emit (OpCodes.Ldloc, val);
2366                                                 if (kb.nFirst != 0)
2367                                                 {
2368                                                         EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2369                                                         ig.Emit (OpCodes.Sub);
2370                                                 }
2371                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
2372                                         }
2373                                         else
2374                                         {
2375                                                 // normalize range
2376                                                 ig.Emit (OpCodes.Ldloc, val);
2377                                                 int nFirst = (int) kb.nFirst;
2378                                                 if (nFirst > 0)
2379                                                 {
2380                                                         IntConstant.EmitInt (ig, nFirst);
2381                                                         ig.Emit (OpCodes.Sub);
2382                                                 }
2383                                                 else if (nFirst < 0)
2384                                                 {
2385                                                         IntConstant.EmitInt (ig, -nFirst);
2386                                                         ig.Emit (OpCodes.Add);
2387                                                 }
2388                                         }
2389
2390                                         // first, build the list of labels for the switch
2391                                         int iKey = 0;
2392                                         int cJumps = kb.Length;
2393                                         Label [] rgLabels = new Label [cJumps];
2394                                         for (int iJump = 0; iJump < cJumps; iJump++)
2395                                         {
2396                                                 object key = kb.rgKeys [iKey];
2397                                                 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2398                                                 {
2399                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
2400                                                         rgLabels [iJump] = sl.ILLabel;
2401                                                         iKey++;
2402                                                 }
2403                                                 else
2404                                                         rgLabels [iJump] = lblDefault;
2405                                         }
2406                                         // emit the switch opcode
2407                                         ig.Emit (OpCodes.Switch, rgLabels);
2408                                 }
2409
2410                                 // mark the default for this block
2411                                 if (iBlock != 0)
2412                                         ig.MarkLabel (lblDefault);
2413                         }
2414
2415                         // TODO: find the default case and emit it here,
2416                         //       to prevent having to do the following jump.
2417                         //       make sure to mark other labels in the default section
2418
2419                         // the last default just goes to the end
2420                         ig.Emit (OpCodes.Br, lblDefault);
2421
2422                         // now emit the code for the sections
2423                         bool fFoundDefault = false;
2424                         bool fAllReturn = true;
2425                         foreach (SwitchSection ss in Sections)
2426                         {
2427                                 foreach (SwitchLabel sl in ss.Labels)
2428                                 {
2429                                         ig.MarkLabel (sl.ILLabel);
2430                                         ig.MarkLabel (sl.ILLabelCode);
2431                                         if (sl.Label == null)
2432                                         {
2433                                                 ig.MarkLabel (lblDefault);
2434                                                 fFoundDefault = true;
2435                                         }
2436                                 }
2437                                 bool returns = ss.Block.Emit (ec);
2438                                 fAllReturn &= returns;
2439                                 //ig.Emit (OpCodes.Br, lblEnd);
2440                         }
2441                         
2442                         if (!fFoundDefault) {
2443                                 ig.MarkLabel (lblDefault);
2444                                 fAllReturn = false;
2445                         }
2446                         ig.MarkLabel (lblEnd);
2447
2448                         return fAllReturn;
2449                 }
2450                 //
2451                 // This simple emit switch works, but does not take advantage of the
2452                 // `switch' opcode. 
2453                 // TODO: remove non-string logic from here
2454                 // TODO: binary search strings?
2455                 //
2456                 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2457                 {
2458                         ILGenerator ig = ec.ig;
2459                         Label end_of_switch = ig.DefineLabel ();
2460                         Label next_test = ig.DefineLabel ();
2461                         Label null_target = ig.DefineLabel ();
2462                         bool default_found = false;
2463                         bool first_test = true;
2464                         bool pending_goto_end = false;
2465                         bool all_return = true;
2466                         bool null_found;
2467                         
2468                         ig.Emit (OpCodes.Ldloc, val);
2469                         
2470                         if (Elements.Contains (NullLiteral.Null)){
2471                                 ig.Emit (OpCodes.Brfalse, null_target);
2472                         } else
2473                                 ig.Emit (OpCodes.Brfalse, default_target);
2474                         
2475                         ig.Emit (OpCodes.Ldloc, val);
2476                         ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2477                         ig.Emit (OpCodes.Stloc, val);
2478                 
2479                         int section_count = Sections.Count;
2480                         for (int section = 0; section < section_count; section++){
2481                                 SwitchSection ss = (SwitchSection) Sections [section];
2482                                 Label sec_begin = ig.DefineLabel ();
2483
2484                                 if (pending_goto_end)
2485                                         ig.Emit (OpCodes.Br, end_of_switch);
2486
2487                                 int label_count = ss.Labels.Count;
2488                                 null_found = false;
2489                                 for (int label = 0; label < label_count; label++){
2490                                         SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2491                                         ig.MarkLabel (sl.ILLabel);
2492                                         
2493                                         if (!first_test){
2494                                                 ig.MarkLabel (next_test);
2495                                                 next_test = ig.DefineLabel ();
2496                                         }
2497                                         //
2498                                         // If we are the default target
2499                                         //
2500                                         if (sl.Label == null){
2501                                                 ig.MarkLabel (default_target);
2502                                                 default_found = true;
2503                                         } else {
2504                                                 object lit = sl.Converted;
2505
2506                                                 if (lit is NullLiteral){
2507                                                         null_found = true;
2508                                                         if (label_count == 1)
2509                                                                 ig.Emit (OpCodes.Br, next_test);
2510                                                         continue;
2511                                                                               
2512                                                 }
2513                                                 StringConstant str = (StringConstant) lit;
2514                                                 
2515                                                 ig.Emit (OpCodes.Ldloc, val);
2516                                                 ig.Emit (OpCodes.Ldstr, str.Value);
2517                                                 if (label_count == 1)
2518                                                         ig.Emit (OpCodes.Bne_Un, next_test);
2519                                                 else {
2520                                                         if (label+1 == label_count)
2521                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
2522                                                         else
2523                                                                 ig.Emit (OpCodes.Beq, sec_begin);
2524                                                 }
2525                                         }
2526                                 }
2527                                 if (null_found)
2528                                         ig.MarkLabel (null_target);
2529                                 ig.MarkLabel (sec_begin);
2530                                 foreach (SwitchLabel sl in ss.Labels)
2531                                         ig.MarkLabel (sl.ILLabelCode);
2532
2533                                 bool returns = ss.Block.Emit (ec);
2534                                 if (returns)
2535                                         pending_goto_end = false;
2536                                 else {
2537                                         all_return = false;
2538                                         pending_goto_end = true;
2539                                 }
2540                                 first_test = false;
2541                         }
2542                         if (!default_found){
2543                                 ig.MarkLabel (default_target);
2544                                 all_return = false;
2545                         }
2546                         ig.MarkLabel (next_test);
2547                         ig.MarkLabel (end_of_switch);
2548
2549                         return all_return;
2550                 }
2551
2552                 public override bool Resolve (EmitContext ec)
2553                 {
2554                         Expr = Expr.Resolve (ec);
2555                         if (Expr == null)
2556                                 return false;
2557
2558                         new_expr = SwitchGoverningType (ec, Expr.Type);
2559                         if (new_expr == null){
2560                                 Report.Error (151, loc, "An integer type or string was expected for switch");
2561                                 return false;
2562                         }
2563
2564                         // Validate switch.
2565                         SwitchType = new_expr.Type;
2566
2567                         if (!CheckSwitch (ec))
2568                                 return false;
2569
2570                         Switch old_switch = ec.Switch;
2571                         ec.Switch = this;
2572                         ec.Switch.SwitchType = SwitchType;
2573
2574                         ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2575
2576                         bool first = true;
2577                         foreach (SwitchSection ss in Sections){
2578                                 if (!first)
2579                                         ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2580                                 else
2581                                         first = false;
2582
2583                                 if (ss.Block.Resolve (ec) != true)
2584                                         return false;
2585                         }
2586
2587
2588                         if (!got_default)
2589                                 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2590
2591                         ec.EndFlowBranching ();
2592                         ec.Switch = old_switch;
2593
2594                         return true;
2595                 }
2596                 
2597                 protected override bool DoEmit (EmitContext ec)
2598                 {
2599                         // Store variable for comparission purposes
2600                         LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2601                         new_expr.Emit (ec);
2602                         ec.ig.Emit (OpCodes.Stloc, value);
2603
2604                         ILGenerator ig = ec.ig;
2605
2606                         default_target = ig.DefineLabel ();
2607
2608                         //
2609                         // Setup the codegen context
2610                         //
2611                         Label old_end = ec.LoopEnd;
2612                         Switch old_switch = ec.Switch;
2613                         
2614                         ec.LoopEnd = ig.DefineLabel ();
2615                         ec.Switch = this;
2616
2617                         // Emit Code.
2618                         bool all_return;
2619                         if (SwitchType == TypeManager.string_type)
2620                                 all_return = SimpleSwitchEmit (ec, value);
2621                         else
2622                                 all_return = TableSwitchEmit (ec, value);
2623
2624                         // Restore context state. 
2625                         ig.MarkLabel (ec.LoopEnd);
2626
2627                         //
2628                         // Restore the previous context
2629                         //
2630                         ec.LoopEnd = old_end;
2631                         ec.Switch = old_switch;
2632                         
2633                         return all_return;
2634                 }
2635         }
2636
2637         public class Lock : Statement {
2638                 Expression expr;
2639                 Statement Statement;
2640                         
2641                 public Lock (Expression expr, Statement stmt, Location l)
2642                 {
2643                         this.expr = expr;
2644                         Statement = stmt;
2645                         loc = l;
2646                 }
2647
2648                 public override bool Resolve (EmitContext ec)
2649                 {
2650                         expr = expr.Resolve (ec);
2651                         return Statement.Resolve (ec) && expr != null;
2652                 }
2653                 
2654                 protected override bool DoEmit (EmitContext ec)
2655                 {
2656                         Type type = expr.Type;
2657                         bool val;
2658                         
2659                         if (type.IsValueType){
2660                                 Report.Error (185, loc, "lock statement requires the expression to be " +
2661                                               " a reference type (type is: `" +
2662                                               TypeManager.CSharpName (type) + "'");
2663                                 return false;
2664                         }
2665
2666                         ILGenerator ig = ec.ig;
2667                         LocalBuilder temp = ig.DeclareLocal (type);
2668                                 
2669                         expr.Emit (ec);
2670                         ig.Emit (OpCodes.Dup);
2671                         ig.Emit (OpCodes.Stloc, temp);
2672                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2673
2674                         // try
2675                         Label end = ig.BeginExceptionBlock ();
2676                         bool old_in_try = ec.InTry;
2677                         ec.InTry = true;
2678                         Label finish = ig.DefineLabel ();
2679                         val = Statement.Emit (ec);
2680                         ec.InTry = old_in_try;
2681                         // ig.Emit (OpCodes.Leave, finish);
2682
2683                         ig.MarkLabel (finish);
2684                         
2685                         // finally
2686                         ig.BeginFinallyBlock ();
2687                         ig.Emit (OpCodes.Ldloc, temp);
2688                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2689                         ig.EndExceptionBlock ();
2690                         
2691                         return val;
2692                 }
2693         }
2694
2695         public class Unchecked : Statement {
2696                 public readonly Block Block;
2697                 
2698                 public Unchecked (Block b)
2699                 {
2700                         Block = b;
2701                         b.Unchecked = true;
2702                 }
2703
2704                 public override bool Resolve (EmitContext ec)
2705                 {
2706                         bool previous_state = ec.CheckState;
2707                         bool previous_state_const = ec.ConstantCheckState;
2708
2709                         ec.CheckState = false;
2710                         ec.ConstantCheckState = false;
2711                         bool ret = Block.Resolve (ec);
2712                         ec.CheckState = previous_state;
2713                         ec.ConstantCheckState = previous_state_const;
2714
2715                         return ret;
2716                 }
2717                 
2718                 protected override bool DoEmit (EmitContext ec)
2719                 {
2720                         bool previous_state = ec.CheckState;
2721                         bool previous_state_const = ec.ConstantCheckState;
2722                         bool val;
2723                         
2724                         ec.CheckState = false;
2725                         ec.ConstantCheckState = false;
2726                         val = Block.Emit (ec);
2727                         ec.CheckState = previous_state;
2728                         ec.ConstantCheckState = previous_state_const;
2729
2730                         return val;
2731                 }
2732         }
2733
2734         public class Checked : Statement {
2735                 public readonly Block Block;
2736                 
2737                 public Checked (Block b)
2738                 {
2739                         Block = b;
2740                         b.Unchecked = false;
2741                 }
2742
2743                 public override bool Resolve (EmitContext ec)
2744                 {
2745                         bool previous_state = ec.CheckState;
2746                         bool previous_state_const = ec.ConstantCheckState;
2747                         
2748                         ec.CheckState = true;
2749                         ec.ConstantCheckState = true;
2750                         bool ret = Block.Resolve (ec);
2751                         ec.CheckState = previous_state;
2752                         ec.ConstantCheckState = previous_state_const;
2753
2754                         return ret;
2755                 }
2756
2757                 protected override bool DoEmit (EmitContext ec)
2758                 {
2759                         bool previous_state = ec.CheckState;
2760                         bool previous_state_const = ec.ConstantCheckState;
2761                         bool val;
2762                         
2763                         ec.CheckState = true;
2764                         ec.ConstantCheckState = true;
2765                         val = Block.Emit (ec);
2766                         ec.CheckState = previous_state;
2767                         ec.ConstantCheckState = previous_state_const;
2768
2769                         return val;
2770                 }
2771         }
2772
2773         public class Unsafe : Statement {
2774                 public readonly Block Block;
2775
2776                 public Unsafe (Block b)
2777                 {
2778                         Block = b;
2779                 }
2780
2781                 public override bool Resolve (EmitContext ec)
2782                 {
2783                         bool previous_state = ec.InUnsafe;
2784                         bool val;
2785                         
2786                         ec.InUnsafe = true;
2787                         val = Block.Resolve (ec);
2788                         ec.InUnsafe = previous_state;
2789
2790                         return val;
2791                 }
2792                 
2793                 protected override bool DoEmit (EmitContext ec)
2794                 {
2795                         bool previous_state = ec.InUnsafe;
2796                         bool val;
2797                         
2798                         ec.InUnsafe = true;
2799                         val = Block.Emit (ec);
2800                         ec.InUnsafe = previous_state;
2801
2802                         return val;
2803                 }
2804         }
2805
2806         // 
2807         // Fixed statement
2808         //
2809         public class Fixed : Statement {
2810                 Expression type;
2811                 ArrayList declarators;
2812                 Statement statement;
2813                 Type expr_type;
2814                 FixedData[] data;
2815
2816                 struct FixedData {
2817                         public bool is_object;
2818                         public LocalInfo vi;
2819                         public Expression expr;
2820                         public Expression converted;
2821                 }                       
2822
2823                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2824                 {
2825                         this.type = type;
2826                         declarators = decls;
2827                         statement = stmt;
2828                         loc = l;
2829                 }
2830
2831                 public override bool Resolve (EmitContext ec)
2832                 {
2833                         if (!ec.InUnsafe){
2834                                 Expression.UnsafeError (loc);
2835                                 return false;
2836                         }
2837                         
2838                         expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2839                         if (expr_type == null)
2840                                 return false;
2841
2842                         if (ec.RemapToProxy){
2843                                 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2844                                 return false;
2845                         }
2846                         
2847                         data = new FixedData [declarators.Count];
2848
2849                         if (!expr_type.IsPointer){
2850                                 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2851                                 return false;
2852                         }
2853                         
2854                         int i = 0;
2855                         foreach (Pair p in declarators){
2856                                 LocalInfo vi = (LocalInfo) p.First;
2857                                 Expression e = (Expression) p.Second;
2858
2859                                 vi.VariableInfo = null;
2860                                 vi.ReadOnly = true;
2861
2862                                 //
2863                                 // The rules for the possible declarators are pretty wise,
2864                                 // but the production on the grammar is more concise.
2865                                 //
2866                                 // So we have to enforce these rules here.
2867                                 //
2868                                 // We do not resolve before doing the case 1 test,
2869                                 // because the grammar is explicit in that the token &
2870                                 // is present, so we need to test for this particular case.
2871                                 //
2872
2873                                 //
2874                                 // Case 1: & object.
2875                                 //
2876                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2877                                         Expression child = ((Unary) e).Expr;
2878
2879                                         vi.MakePinned ();
2880                                         if (child is ParameterReference || child is LocalVariableReference){
2881                                                 Report.Error (
2882                                                         213, loc, 
2883                                                         "No need to use fixed statement for parameters or " +
2884                                                         "local variable declarations (address is already " +
2885                                                         "fixed)");
2886                                                 return false;
2887                                         }
2888
2889                                         ec.InFixedInitializer = true;
2890                                         e = e.Resolve (ec);
2891                                         ec.InFixedInitializer = false;
2892                                         if (e == null)
2893                                                 return false;
2894
2895                                         child = ((Unary) e).Expr;
2896                                         
2897                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
2898                                                 return false;
2899
2900                                         data [i].is_object = true;
2901                                         data [i].expr = e;
2902                                         data [i].converted = null;
2903                                         data [i].vi = vi;
2904                                         i++;
2905
2906                                         continue;
2907                                 }
2908
2909                                 ec.InFixedInitializer = true;
2910                                 e = e.Resolve (ec);
2911                                 ec.InFixedInitializer = false;
2912                                 if (e == null)
2913                                         return false;
2914
2915                                 //
2916                                 // Case 2: Array
2917                                 //
2918                                 if (e.Type.IsArray){
2919                                         Type array_type = TypeManager.GetElementType (e.Type);
2920                                         
2921                                         vi.MakePinned ();
2922                                         //
2923                                         // Provided that array_type is unmanaged,
2924                                         //
2925                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
2926                                                 return false;
2927
2928                                         //
2929                                         // and T* is implicitly convertible to the
2930                                         // pointer type given in the fixed statement.
2931                                         //
2932                                         ArrayPtr array_ptr = new ArrayPtr (e, loc);
2933                                         
2934                                         Expression converted = Convert.ImplicitConversionRequired (
2935                                                 ec, array_ptr, vi.VariableType, loc);
2936                                         if (converted == null)
2937                                                 return false;
2938
2939                                         data [i].is_object = false;
2940                                         data [i].expr = e;
2941                                         data [i].converted = converted;
2942                                         data [i].vi = vi;
2943                                         i++;
2944
2945                                         continue;
2946                                 }
2947
2948                                 //
2949                                 // Case 3: string
2950                                 //
2951                                 if (e.Type == TypeManager.string_type){
2952                                         data [i].is_object = false;
2953                                         data [i].expr = e;
2954                                         data [i].converted = null;
2955                                         data [i].vi = vi;
2956                                         i++;
2957                                 }
2958                         }
2959
2960                         return statement.Resolve (ec);
2961                 }
2962                 
2963                 protected override bool DoEmit (EmitContext ec)
2964                 {
2965                         ILGenerator ig = ec.ig;
2966
2967                         bool is_ret = false;
2968                         LocalBuilder [] clear_list = new LocalBuilder [data.Length];
2969                         
2970                         for (int i = 0; i < data.Length; i++) {
2971                                 LocalInfo vi = data [i].vi;
2972
2973                                 //
2974                                 // Case 1: & object.
2975                                 //
2976                                 if (data [i].is_object) {
2977                                         //
2978                                         // Store pointer in pinned location
2979                                         //
2980                                         data [i].expr.Emit (ec);
2981                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2982                                         clear_list [i] = vi.LocalBuilder;
2983                                         continue;
2984                                 }
2985
2986                                 //
2987                                 // Case 2: Array
2988                                 //
2989                                 if (data [i].expr.Type.IsArray){
2990                                         //
2991                                         // Store pointer in pinned location
2992                                         //
2993                                         data [i].converted.Emit (ec);
2994                                         
2995                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2996                                         clear_list [i] = vi.LocalBuilder;
2997                                         continue;
2998                                 }
2999
3000                                 //
3001                                 // Case 3: string
3002                                 //
3003                                 if (data [i].expr.Type == TypeManager.string_type){
3004                                         LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3005                                         TypeManager.MakePinned (pinned_string);
3006                                         clear_list [i] = pinned_string;
3007                                         
3008                                         data [i].expr.Emit (ec);
3009                                         ig.Emit (OpCodes.Stloc, pinned_string);
3010
3011                                         Expression sptr = new StringPtr (pinned_string, loc);
3012                                         Expression converted = Convert.ImplicitConversionRequired (
3013                                                 ec, sptr, vi.VariableType, loc);
3014                                         
3015                                         if (converted == null)
3016                                                 continue;
3017
3018                                         converted.Emit (ec);
3019                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3020                                 }
3021                         }
3022
3023                         is_ret = statement.Emit (ec);
3024
3025                         if (is_ret)
3026                                 return is_ret;
3027                         //
3028                         // Clear the pinned variable
3029                         //
3030                         for (int i = 0; i < data.Length; i++) {
3031                                 LocalInfo vi = data [i].vi;
3032
3033                                 if (data [i].is_object || data [i].expr.Type.IsArray) {
3034                                         ig.Emit (OpCodes.Ldc_I4_0);
3035                                         ig.Emit (OpCodes.Conv_U);
3036                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3037                                 } else if (data [i].expr.Type == TypeManager.string_type){
3038                                         ig.Emit (OpCodes.Ldnull);
3039                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3040                                 }
3041                         }
3042
3043                         return is_ret;
3044                 }
3045         }
3046         
3047         public class Catch {
3048                 public readonly string Name;
3049                 public readonly Block  Block;
3050                 public readonly Location Location;
3051
3052                 Expression type_expr;
3053                 Type type;
3054                 
3055                 public Catch (Expression type, string name, Block block, Location l)
3056                 {
3057                         type_expr = type;
3058                         Name = name;
3059                         Block = block;
3060                         Location = l;
3061                 }
3062
3063                 public Type CatchType {
3064                         get {
3065                                 return type;
3066                         }
3067                 }
3068
3069                 public bool IsGeneral {
3070                         get {
3071                                 return type_expr == null;
3072                         }
3073                 }
3074
3075                 public bool Resolve (EmitContext ec)
3076                 {
3077                         if (type_expr != null) {
3078                                 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3079                                 if (type == null)
3080                                         return false;
3081
3082                                 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3083                                         Report.Error (155, Location,
3084                                                       "The type caught or thrown must be derived " +
3085                                                       "from System.Exception");
3086                                         return false;
3087                                 }
3088                         } else
3089                                 type = null;
3090
3091                         if (!Block.Resolve (ec))
3092                                 return false;
3093
3094                         return true;
3095                 }
3096         }
3097
3098         public class Try : Statement {
3099                 public readonly Block Fini, Block;
3100                 public readonly ArrayList Specific;
3101                 public readonly Catch General;
3102                 
3103                 //
3104                 // specific, general and fini might all be null.
3105                 //
3106                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3107                 {
3108                         if (specific == null && general == null){
3109                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3110                         }
3111                         
3112                         this.Block = block;
3113                         this.Specific = specific;
3114                         this.General = general;
3115                         this.Fini = fini;
3116                         loc = l;
3117                 }
3118
3119                 public override bool Resolve (EmitContext ec)
3120                 {
3121                         bool ok = true;
3122                         
3123                         ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3124
3125                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3126
3127                         bool old_in_try = ec.InTry;
3128                         ec.InTry = true;
3129
3130                         if (!Block.Resolve (ec))
3131                                 ok = false;
3132
3133                         ec.InTry = old_in_try;
3134
3135                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3136
3137                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
3138
3139                         foreach (Catch c in Specific){
3140                                 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3141                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3142
3143                                 if (c.Name != null) {
3144                                         LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3145                                         if (vi == null)
3146                                                 throw new Exception ();
3147
3148                                         vi.VariableInfo = null;
3149                                 }
3150
3151                                 bool old_in_catch = ec.InCatch;
3152                                 ec.InCatch = true;
3153
3154                                 if (!c.Resolve (ec))
3155                                         ok = false;
3156
3157                                 ec.InCatch = old_in_catch;
3158                         }
3159
3160                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3161
3162                         if (General != null){
3163                                 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3164                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3165
3166                                 bool old_in_catch = ec.InCatch;
3167                                 ec.InCatch = true;
3168
3169                                 if (!General.Resolve (ec))
3170                                         ok = false;
3171
3172                                 ec.InCatch = old_in_catch;
3173                         }
3174
3175                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3176
3177                         if (Fini != null) {
3178                                 if (ok)
3179                                         ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Finally);
3180                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3181
3182                                 bool old_in_finally = ec.InFinally;
3183                                 ec.InFinally = true;
3184
3185                                 if (!Fini.Resolve (ec))
3186                                         ok = false;
3187
3188                                 ec.InFinally = old_in_finally;
3189                         }
3190
3191                         FlowBranching.FlowReturns returns = ec.EndFlowBranching ();
3192
3193                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3194
3195                         Report.Debug (1, "END OF TRY", ec.CurrentBranching, returns, vector, f_vector);
3196
3197                         if (returns != FlowBranching.FlowReturns.Always) {
3198                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
3199                                 // to the end of the finally block.  This is a problem if `returns'
3200                                 // is true since we may jump to a point after the end of the method.
3201                                 // As a workaround, emit an explicit ret here.
3202                                 ec.NeedExplicitReturn = true;
3203                         }
3204
3205                         return ok;
3206                 }
3207                 
3208                 protected override bool DoEmit (EmitContext ec)
3209                 {
3210                         ILGenerator ig = ec.ig;
3211                         Label end;
3212                         Label finish = ig.DefineLabel ();;
3213                         bool returns;
3214
3215                         ec.TryCatchLevel++;
3216                         end = ig.BeginExceptionBlock ();
3217                         bool old_in_try = ec.InTry;
3218                         ec.InTry = true;
3219                         returns = Block.Emit (ec);
3220                         ec.InTry = old_in_try;
3221
3222                         //
3223                         // System.Reflection.Emit provides this automatically:
3224                         // ig.Emit (OpCodes.Leave, finish);
3225
3226                         bool old_in_catch = ec.InCatch;
3227                         ec.InCatch = true;
3228                         DeclSpace ds = ec.DeclSpace;
3229
3230                         foreach (Catch c in Specific){
3231                                 LocalInfo vi;
3232                                 
3233                                 ig.BeginCatchBlock (c.CatchType);
3234
3235                                 if (c.Name != null){
3236                                         vi = c.Block.GetLocalInfo (c.Name);
3237                                         if (vi == null)
3238                                                 throw new Exception ("Variable does not exist in this block");
3239
3240                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3241                                 } else
3242                                         ig.Emit (OpCodes.Pop);
3243                                 
3244                                 if (!c.Block.Emit (ec))
3245                                         returns = false;
3246                         }
3247
3248                         if (General != null){
3249                                 ig.BeginCatchBlock (TypeManager.object_type);
3250                                 ig.Emit (OpCodes.Pop);
3251                                 if (!General.Block.Emit (ec))
3252                                         returns = false;
3253                         }
3254                         ec.InCatch = old_in_catch;
3255
3256                         ig.MarkLabel (finish);
3257                         if (Fini != null){
3258                                 ig.BeginFinallyBlock ();
3259                                 bool old_in_finally = ec.InFinally;
3260                                 ec.InFinally = true;
3261                                 Fini.Emit (ec);
3262                                 ec.InFinally = old_in_finally;
3263                         }
3264                         
3265                         ig.EndExceptionBlock ();
3266                         ec.TryCatchLevel--;
3267
3268                         return returns;
3269                 }
3270         }
3271
3272         public class Using : Statement {
3273                 object expression_or_block;
3274                 Statement Statement;
3275                 ArrayList var_list;
3276                 Expression expr;
3277                 Type expr_type;
3278                 Expression conv;
3279                 Expression [] converted_vars;
3280                 ExpressionStatement [] assign;
3281                 
3282                 public Using (object expression_or_block, Statement stmt, Location l)
3283                 {
3284                         this.expression_or_block = expression_or_block;
3285                         Statement = stmt;
3286                         loc = l;
3287                 }
3288
3289                 //
3290                 // Resolves for the case of using using a local variable declaration.
3291                 //
3292                 bool ResolveLocalVariableDecls (EmitContext ec)
3293                 {
3294                         bool need_conv = false;
3295                         expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3296                         int i = 0;
3297
3298                         if (expr_type == null)
3299                                 return false;
3300
3301                         //
3302                         // The type must be an IDisposable or an implicit conversion
3303                         // must exist.
3304                         //
3305                         converted_vars = new Expression [var_list.Count];
3306                         assign = new ExpressionStatement [var_list.Count];
3307                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3308                                 foreach (DictionaryEntry e in var_list){
3309                                         Expression var = (Expression) e.Key;
3310
3311                                         var = var.ResolveLValue (ec, new EmptyExpression ());
3312                                         if (var == null)
3313                                                 return false;
3314                                         
3315                                         converted_vars [i] = Convert.ImplicitConversionRequired (
3316                                                 ec, var, TypeManager.idisposable_type, loc);
3317
3318                                         if (converted_vars [i] == null)
3319                                                 return false;
3320                                         i++;
3321                                 }
3322                                 need_conv = true;
3323                         }
3324
3325                         i = 0;
3326                         foreach (DictionaryEntry e in var_list){
3327                                 LocalVariableReference var = (LocalVariableReference) e.Key;
3328                                 Expression new_expr = (Expression) e.Value;
3329                                 Expression a;
3330
3331                                 a = new Assign (var, new_expr, loc);
3332                                 a = a.Resolve (ec);
3333                                 if (a == null)
3334                                         return false;
3335
3336                                 if (!need_conv)
3337                                         converted_vars [i] = var;
3338                                 assign [i] = (ExpressionStatement) a;
3339                                 i++;
3340                         }
3341
3342                         return true;
3343                 }
3344
3345                 bool ResolveExpression (EmitContext ec)
3346                 {
3347                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3348                                 conv = Convert.ImplicitConversionRequired (
3349                                         ec, expr, TypeManager.idisposable_type, loc);
3350
3351                                 if (conv == null)
3352                                         return false;
3353                         }
3354
3355                         return true;
3356                 }
3357                 
3358                 //
3359                 // Emits the code for the case of using using a local variable declaration.
3360                 //
3361                 bool EmitLocalVariableDecls (EmitContext ec)
3362                 {
3363                         ILGenerator ig = ec.ig;
3364                         int i = 0;
3365
3366                         bool old_in_try = ec.InTry;
3367                         ec.InTry = true;
3368                         for (i = 0; i < assign.Length; i++) {
3369                                 assign [i].EmitStatement (ec);
3370                                 
3371                                 ig.BeginExceptionBlock ();
3372                         }
3373                         Statement.Emit (ec);
3374                         ec.InTry = old_in_try;
3375
3376                         bool old_in_finally = ec.InFinally;
3377                         ec.InFinally = true;
3378                         var_list.Reverse ();
3379                         foreach (DictionaryEntry e in var_list){
3380                                 LocalVariableReference var = (LocalVariableReference) e.Key;
3381                                 Label skip = ig.DefineLabel ();
3382                                 i--;
3383                                 
3384                                 ig.BeginFinallyBlock ();
3385                                 
3386                                 var.Emit (ec);
3387                                 ig.Emit (OpCodes.Brfalse, skip);
3388                                 converted_vars [i].Emit (ec);
3389                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3390                                 ig.MarkLabel (skip);
3391                                 ig.EndExceptionBlock ();
3392                         }
3393                         ec.InFinally = old_in_finally;
3394
3395                         return false;
3396                 }
3397
3398                 bool EmitExpression (EmitContext ec)
3399                 {
3400                         //
3401                         // Make a copy of the expression and operate on that.
3402                         //
3403                         ILGenerator ig = ec.ig;
3404                         LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3405                         if (conv != null)
3406                                 conv.Emit (ec);
3407                         else
3408                                 expr.Emit (ec);
3409                         ig.Emit (OpCodes.Stloc, local_copy);
3410
3411                         bool old_in_try = ec.InTry;
3412                         ec.InTry = true;
3413                         ig.BeginExceptionBlock ();
3414                         Statement.Emit (ec);
3415                         ec.InTry = old_in_try;
3416                         
3417                         Label skip = ig.DefineLabel ();
3418                         bool old_in_finally = ec.InFinally;
3419                         ig.BeginFinallyBlock ();
3420                         ig.Emit (OpCodes.Ldloc, local_copy);
3421                         ig.Emit (OpCodes.Brfalse, skip);
3422                         ig.Emit (OpCodes.Ldloc, local_copy);
3423                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3424                         ig.MarkLabel (skip);
3425                         ec.InFinally = old_in_finally;
3426                         ig.EndExceptionBlock ();
3427
3428                         return false;
3429                 }
3430                 
3431                 public override bool Resolve (EmitContext ec)
3432                 {
3433                         if (expression_or_block is DictionaryEntry){
3434                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3435                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3436
3437                                 if (!ResolveLocalVariableDecls (ec))
3438                                         return false;
3439
3440                         } else if (expression_or_block is Expression){
3441                                 expr = (Expression) expression_or_block;
3442
3443                                 expr = expr.Resolve (ec);
3444                                 if (expr == null)
3445                                         return false;
3446
3447                                 expr_type = expr.Type;
3448
3449                                 if (!ResolveExpression (ec))
3450                                         return false;
3451                         }
3452
3453                         ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
3454
3455                         bool ok = Statement.Resolve (ec);
3456
3457                         if (!ok) {
3458                                 ec.KillFlowBranching ();
3459                                 return false;
3460                         }
3461                                         
3462                         FlowBranching.FlowReturns returns = ec.EndFlowBranching ();
3463
3464                         if (returns != FlowBranching.FlowReturns.Always) {
3465                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
3466                                 // to the end of the finally block.  This is a problem if `returns'
3467                                 // is true since we may jump to a point after the end of the method.
3468                                 // As a workaround, emit an explicit ret here.
3469                                 ec.NeedExplicitReturn = true;
3470                         }
3471
3472                         return true;
3473                 }
3474                 
3475                 protected override bool DoEmit (EmitContext ec)
3476                 {
3477                         if (expression_or_block is DictionaryEntry)
3478                                 return EmitLocalVariableDecls (ec);
3479                         else if (expression_or_block is Expression)
3480                                 return EmitExpression (ec);
3481
3482                         return false;
3483                 }
3484         }
3485
3486         /// <summary>
3487         ///   Implementation of the foreach C# statement
3488         /// </summary>
3489         public class Foreach : Statement {
3490                 Expression type;
3491                 Expression variable;
3492                 Expression expr;
3493                 Statement statement;
3494                 ForeachHelperMethods hm;
3495                 Expression empty, conv;
3496                 Type array_type, element_type;
3497                 Type var_type;
3498                 
3499                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3500                                 Statement stmt, Location l)
3501                 {
3502                         this.type = type;
3503                         this.variable = var;
3504                         this.expr = expr;
3505                         statement = stmt;
3506                         loc = l;
3507                 }
3508                 
3509                 public override bool Resolve (EmitContext ec)
3510                 {
3511                         expr = expr.Resolve (ec);
3512                         if (expr == null)
3513                                 return false;
3514
3515                         var_type = ec.DeclSpace.ResolveType (type, false, loc);
3516                         if (var_type == null)
3517                                 return false;
3518                         
3519                         //
3520                         // We need an instance variable.  Not sure this is the best
3521                         // way of doing this.
3522                         //
3523                         // FIXME: When we implement propertyaccess, will those turn
3524                         // out to return values in ExprClass?  I think they should.
3525                         //
3526                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3527                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3528                                 error1579 (expr.Type);
3529                                 return false;
3530                         }
3531
3532                         if (expr.Type.IsArray) {
3533                                 array_type = expr.Type;
3534                                 element_type = TypeManager.GetElementType (array_type);
3535
3536                                 empty = new EmptyExpression (element_type);
3537                         } else {
3538                                 hm = ProbeCollectionType (ec, expr.Type);
3539                                 if (hm == null){
3540                                         error1579 (expr.Type);
3541                                         return false;
3542                                 }
3543
3544                                 array_type = expr.Type;
3545                                 element_type = hm.element_type;
3546
3547                                 empty = new EmptyExpression (hm.element_type);
3548                         }
3549
3550                         ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
3551                         ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
3552
3553                         //
3554                         //
3555                         // FIXME: maybe we can apply the same trick we do in the
3556                         // array handling to avoid creating empty and conv in some cases.
3557                         //
3558                         // Although it is not as important in this case, as the type
3559                         // will not likely be object (what the enumerator will return).
3560                         //
3561                         conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3562                         if (conv == null)
3563                                 return false;
3564
3565                         variable = variable.ResolveLValue (ec, empty);
3566                         if (variable == null)
3567                                 return false;
3568
3569                         if (!statement.Resolve (ec))
3570                                 return false;
3571
3572                         FlowBranching.FlowReturns returns = ec.EndFlowBranching ();
3573
3574                         return true;
3575                 }
3576                 
3577                 //
3578                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3579                 //
3580                 static MethodInfo FetchMethodMoveNext (Type t)
3581                 {
3582                         MemberList move_next_list;
3583                         
3584                         move_next_list = TypeContainer.FindMembers (
3585                                 t, MemberTypes.Method,
3586                                 BindingFlags.Public | BindingFlags.Instance,
3587                                 Type.FilterName, "MoveNext");
3588                         if (move_next_list.Count == 0)
3589                                 return null;
3590
3591                         foreach (MemberInfo m in move_next_list){
3592                                 MethodInfo mi = (MethodInfo) m;
3593                                 Type [] args;
3594                                 
3595                                 args = TypeManager.GetArgumentTypes (mi);
3596                                 if (args != null && args.Length == 0){
3597                                         if (mi.ReturnType == TypeManager.bool_type)
3598                                                 return mi;
3599                                 }
3600                         }
3601                         return null;
3602                 }
3603                 
3604                 //
3605                 // Retrieves a `public T get_Current ()' method from the Type `t'
3606                 //
3607                 static MethodInfo FetchMethodGetCurrent (Type t)
3608                 {
3609                         MemberList move_next_list;
3610                         
3611                         move_next_list = TypeContainer.FindMembers (
3612                                 t, MemberTypes.Method,
3613                                 BindingFlags.Public | BindingFlags.Instance,
3614                                 Type.FilterName, "get_Current");
3615                         if (move_next_list.Count == 0)
3616                                 return null;
3617
3618                         foreach (MemberInfo m in move_next_list){
3619                                 MethodInfo mi = (MethodInfo) m;
3620                                 Type [] args;
3621
3622                                 args = TypeManager.GetArgumentTypes (mi);
3623                                 if (args != null && args.Length == 0)
3624                                         return mi;
3625                         }
3626                         return null;
3627                 }
3628
3629                 // 
3630                 // This struct records the helper methods used by the Foreach construct
3631                 //
3632                 class ForeachHelperMethods {
3633                         public EmitContext ec;
3634                         public MethodInfo get_enumerator;
3635                         public MethodInfo move_next;
3636                         public MethodInfo get_current;
3637                         public Type element_type;
3638                         public Type enumerator_type;
3639                         public bool is_disposable;
3640
3641                         public ForeachHelperMethods (EmitContext ec)
3642                         {
3643                                 this.ec = ec;
3644                                 this.element_type = TypeManager.object_type;
3645                                 this.enumerator_type = TypeManager.ienumerator_type;
3646                                 this.is_disposable = true;
3647                         }
3648                 }
3649                 
3650                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3651                 {
3652                         if (m == null)
3653                                 return false;
3654                         
3655                         if (!(m is MethodInfo))
3656                                 return false;
3657                         
3658                         if (m.Name != "GetEnumerator")
3659                                 return false;
3660
3661                         MethodInfo mi = (MethodInfo) m;
3662                         Type [] args = TypeManager.GetArgumentTypes (mi);
3663                         if (args != null){
3664                                 if (args.Length != 0)
3665                                         return false;
3666                         }
3667                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3668                         EmitContext ec = hm.ec;
3669
3670                         //
3671                         // Check whether GetEnumerator is accessible to us
3672                         //
3673                         MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3674
3675                         Type declaring = mi.DeclaringType;
3676                         if (prot == MethodAttributes.Private){
3677                                 if (declaring != ec.ContainerType)
3678                                         return false;
3679                         } else if (prot == MethodAttributes.FamANDAssem){
3680                                 // If from a different assembly, false
3681                                 if (!(mi is MethodBuilder))
3682                                         return false;
3683                                 //
3684                                 // Are we being invoked from the same class, or from a derived method?
3685                                 //
3686                                 if (ec.ContainerType != declaring){
3687                                         if (!ec.ContainerType.IsSubclassOf (declaring))
3688                                                 return false;
3689                                 }
3690                         } else if (prot == MethodAttributes.FamORAssem){
3691                                 if (!(mi is MethodBuilder ||
3692                                       ec.ContainerType == declaring ||
3693                                       ec.ContainerType.IsSubclassOf (declaring)))
3694                                         return false;
3695                         } if (prot == MethodAttributes.Family){
3696                                 if (!(ec.ContainerType == declaring ||
3697                                       ec.ContainerType.IsSubclassOf (declaring)))
3698                                         return false;
3699                         }
3700
3701                         if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3702                                 //
3703                                 // Apply the same optimization as MS: skip the GetEnumerator
3704                                 // returning an IEnumerator, and use the one returning a 
3705                                 // CharEnumerator instead. This allows us to avoid the 
3706                                 // try-finally block and the boxing.
3707                                 //
3708                                 return false;
3709
3710                         //
3711                         // Ok, we can access it, now make sure that we can do something
3712                         // with this `GetEnumerator'
3713                         //
3714
3715                         if (mi.ReturnType == TypeManager.ienumerator_type ||
3716                             TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
3717                             (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
3718                                 if (declaring != TypeManager.string_type) {
3719                                         hm.move_next = TypeManager.bool_movenext_void;
3720                                         hm.get_current = TypeManager.object_getcurrent_void;
3721                                         return true;
3722                                 }
3723                         }
3724
3725                         //
3726                         // Ok, so they dont return an IEnumerable, we will have to
3727                         // find if they support the GetEnumerator pattern.
3728                         //
3729                         Type return_type = mi.ReturnType;
3730
3731                         hm.move_next = FetchMethodMoveNext (return_type);
3732                         if (hm.move_next == null)
3733                                 return false;
3734                         hm.get_current = FetchMethodGetCurrent (return_type);
3735                         if (hm.get_current == null)
3736                                 return false;
3737
3738                         hm.element_type = hm.get_current.ReturnType;
3739                         hm.enumerator_type = return_type;
3740                         hm.is_disposable = !hm.enumerator_type.IsSealed ||
3741                                 TypeManager.ImplementsInterface (
3742                                         hm.enumerator_type, TypeManager.idisposable_type);
3743
3744                         return true;
3745                 }
3746                 
3747                 /// <summary>
3748                 ///   This filter is used to find the GetEnumerator method
3749                 ///   on which IEnumerator operates
3750                 /// </summary>
3751                 static MemberFilter FilterEnumerator;
3752                 
3753                 static Foreach ()
3754                 {
3755                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3756                 }
3757
3758                 void error1579 (Type t)
3759                 {
3760                         Report.Error (1579, loc,
3761                                       "foreach statement cannot operate on variables of type `" +
3762                                       t.FullName + "' because that class does not provide a " +
3763                                       " GetEnumerator method or it is inaccessible");
3764                 }
3765
3766                 static bool TryType (Type t, ForeachHelperMethods hm)
3767                 {
3768                         MemberList mi;
3769                         
3770                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3771                                                         BindingFlags.Public | BindingFlags.NonPublic |
3772                                                         BindingFlags.Instance,
3773                                                         FilterEnumerator, hm);
3774
3775                         if (mi.Count == 0)
3776                                 return false;
3777
3778                         hm.get_enumerator = (MethodInfo) mi [0];
3779                         return true;    
3780                 }
3781                 
3782                 //
3783                 // Looks for a usable GetEnumerator in the Type, and if found returns
3784                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3785                 //
3786                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3787                 {
3788                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3789
3790                         if (TryType (t, hm))
3791                                 return hm;
3792
3793                         //
3794                         // Now try to find the method in the interfaces
3795                         //
3796                         while (t != null){
3797                                 Type [] ifaces = t.GetInterfaces ();
3798
3799                                 foreach (Type i in ifaces){
3800                                         if (TryType (i, hm))
3801                                                 return hm;
3802                                 }
3803                                 
3804                                 //
3805                                 // Since TypeBuilder.GetInterfaces only returns the interface
3806                                 // types for this type, we have to keep looping, but once
3807                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3808                                 // done, because it returns all the types
3809                                 //
3810                                 if ((t is TypeBuilder))
3811                                         t = t.BaseType;
3812                                 else
3813                                         break;
3814                         } 
3815
3816                         return null;
3817                 }
3818
3819                 //
3820                 // FIXME: possible optimization.
3821                 // We might be able to avoid creating `empty' if the type is the sam
3822                 //
3823                 bool EmitCollectionForeach (EmitContext ec)
3824                 {
3825                         ILGenerator ig = ec.ig;
3826                         VariableStorage enumerator, disposable;
3827
3828                         enumerator = new VariableStorage (ec, hm.enumerator_type);
3829                         if (hm.is_disposable)
3830                                 disposable = new VariableStorage (ec, TypeManager.idisposable_type);
3831                         else
3832                                 disposable = null;
3833
3834                         enumerator.EmitThis ();
3835                         //
3836                         // Instantiate the enumerator
3837                         //
3838                         if (expr.Type.IsValueType){
3839                                 if (expr is IMemoryLocation){
3840                                         IMemoryLocation ml = (IMemoryLocation) expr;
3841
3842                                         ml.AddressOf (ec, AddressOp.Load);
3843                                 } else
3844                                         throw new Exception ("Expr " + expr + " of type " + expr.Type +
3845                                                              " does not implement IMemoryLocation");
3846                                 ig.Emit (OpCodes.Call, hm.get_enumerator);
3847                         } else {
3848                                 expr.Emit (ec);
3849                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3850                         }
3851                         enumerator.EmitStore ();
3852
3853                         //
3854                         // Protect the code in a try/finalize block, so that
3855                         // if the beast implement IDisposable, we get rid of it
3856                         //
3857                         Label l;
3858                         bool old_in_try = ec.InTry;
3859
3860                         if (hm.is_disposable) {
3861                                 l = ig.BeginExceptionBlock ();
3862                                 ec.InTry = true;
3863                         }
3864                         
3865                         Label end_try = ig.DefineLabel ();
3866                         
3867                         ig.MarkLabel (ec.LoopBegin);
3868                         enumerator.EmitLoad ();
3869                         ig.Emit (OpCodes.Callvirt, hm.move_next);
3870                         ig.Emit (OpCodes.Brfalse, end_try);
3871                         if (ec.InIterator)
3872                                 ec.EmitThis ();
3873                         
3874                         enumerator.EmitLoad ();
3875                         ig.Emit (OpCodes.Callvirt, hm.get_current);
3876
3877                         if (ec.InIterator){
3878                                 conv.Emit (ec);
3879                                 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3880                         } else 
3881                                 ((IAssignMethod)variable).EmitAssign (ec, conv);
3882                                 
3883                         statement.Emit (ec);
3884                         ig.Emit (OpCodes.Br, ec.LoopBegin);
3885                         ig.MarkLabel (end_try);
3886                         ec.InTry = old_in_try;
3887                         
3888                         // The runtime provides this for us.
3889                         // ig.Emit (OpCodes.Leave, end);
3890
3891                         //
3892                         // Now the finally block
3893                         //
3894                         if (hm.is_disposable) {
3895                                 Label end_finally = ig.DefineLabel ();
3896                                 bool old_in_finally = ec.InFinally;
3897                                 ec.InFinally = true;
3898                                 ig.BeginFinallyBlock ();
3899
3900                                 disposable.EmitThis ();
3901                                 enumerator.EmitThis ();
3902                                 enumerator.EmitLoad ();
3903                                 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
3904                                 disposable.EmitStore ();
3905                                 disposable.EmitLoad ();
3906                                 ig.Emit (OpCodes.Brfalse, end_finally);
3907                                 disposable.EmitThis ();
3908                                 disposable.EmitLoad ();
3909                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3910                                 ig.MarkLabel (end_finally);
3911                                 ec.InFinally = old_in_finally;
3912
3913                                 // The runtime generates this anyways.
3914                                 // ig.Emit (OpCodes.Endfinally);
3915
3916                                 ig.EndExceptionBlock ();
3917                         }
3918
3919                         ig.MarkLabel (ec.LoopEnd);
3920                         return false;
3921                 }
3922
3923                 //
3924                 // FIXME: possible optimization.
3925                 // We might be able to avoid creating `empty' if the type is the sam
3926                 //
3927                 bool EmitArrayForeach (EmitContext ec)
3928                 {
3929                         int rank = array_type.GetArrayRank ();
3930                         ILGenerator ig = ec.ig;
3931
3932                         VariableStorage copy = new VariableStorage (ec, array_type);
3933                         
3934                         //
3935                         // Make our copy of the array
3936                         //
3937                         copy.EmitThis ();
3938                         expr.Emit (ec);
3939                         copy.EmitStore ();
3940                         
3941                         if (rank == 1){
3942                                 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
3943
3944                                 Label loop, test;
3945
3946                                 counter.EmitThis ();
3947                                 ig.Emit (OpCodes.Ldc_I4_0);
3948                                 counter.EmitStore ();
3949                                 test = ig.DefineLabel ();
3950                                 ig.Emit (OpCodes.Br, test);
3951
3952                                 loop = ig.DefineLabel ();
3953                                 ig.MarkLabel (loop);
3954
3955                                 if (ec.InIterator)
3956                                         ec.EmitThis ();
3957                                 
3958                                 copy.EmitThis ();
3959                                 copy.EmitLoad ();
3960                                 counter.EmitThis ();
3961                                 counter.EmitLoad ();
3962
3963                                 //
3964                                 // Load the value, we load the value using the underlying type,
3965                                 // then we use the variable.EmitAssign to load using the proper cast.
3966                                 //
3967                                 ArrayAccess.EmitLoadOpcode (ig, element_type);
3968                                 if (ec.InIterator){
3969                                         conv.Emit (ec);
3970                                         ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3971                                 } else 
3972                                         ((IAssignMethod)variable).EmitAssign (ec, conv);
3973
3974                                 statement.Emit (ec);
3975
3976                                 ig.MarkLabel (ec.LoopBegin);
3977                                 counter.EmitThis ();
3978                                 counter.EmitThis ();
3979                                 counter.EmitLoad ();
3980                                 ig.Emit (OpCodes.Ldc_I4_1);
3981                                 ig.Emit (OpCodes.Add);
3982                                 counter.EmitStore ();
3983
3984                                 ig.MarkLabel (test);
3985                                 counter.EmitThis ();
3986                                 counter.EmitLoad ();
3987                                 copy.EmitThis ();
3988                                 copy.EmitLoad ();
3989                                 ig.Emit (OpCodes.Ldlen);
3990                                 ig.Emit (OpCodes.Conv_I4);
3991                                 ig.Emit (OpCodes.Blt, loop);
3992                         } else {
3993                                 VariableStorage [] dim_len   = new VariableStorage [rank];
3994                                 VariableStorage [] dim_count = new VariableStorage [rank];
3995                                 Label [] loop = new Label [rank];
3996                                 Label [] test = new Label [rank];
3997                                 int dim;
3998                                 
3999                                 for (dim = 0; dim < rank; dim++){
4000                                         dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4001                                         dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4002                                         test [dim] = ig.DefineLabel ();
4003                                         loop [dim] = ig.DefineLabel ();
4004                                 }
4005                                         
4006                                 for (dim = 0; dim < rank; dim++){
4007                                         dim_len [dim].EmitThis ();
4008                                         copy.EmitThis ();
4009                                         copy.EmitLoad ();
4010                                         IntLiteral.EmitInt (ig, dim);
4011                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4012                                         dim_len [dim].EmitStore ();
4013                                         
4014                                 }
4015
4016                                 for (dim = 0; dim < rank; dim++){
4017                                         dim_count [dim].EmitThis ();
4018                                         ig.Emit (OpCodes.Ldc_I4_0);
4019                                         dim_count [dim].EmitStore ();
4020                                         ig.Emit (OpCodes.Br, test [dim]);
4021                                         ig.MarkLabel (loop [dim]);
4022                                 }
4023
4024                                 if (ec.InIterator)
4025                                         ec.EmitThis ();
4026                                 copy.EmitThis ();
4027                                 copy.EmitLoad ();
4028                                 for (dim = 0; dim < rank; dim++){
4029                                         dim_count [dim].EmitThis ();
4030                                         dim_count [dim].EmitLoad ();
4031                                 }
4032
4033                                 //
4034                                 // FIXME: Maybe we can cache the computation of `get'?
4035                                 //
4036                                 Type [] args = new Type [rank];
4037                                 MethodInfo get;
4038
4039                                 for (int i = 0; i < rank; i++)
4040                                         args [i] = TypeManager.int32_type;
4041
4042                                 ModuleBuilder mb = CodeGen.ModuleBuilder;
4043                                 get = mb.GetArrayMethod (
4044                                         array_type, "Get",
4045                                         CallingConventions.HasThis| CallingConventions.Standard,
4046                                         var_type, args);
4047                                 ig.Emit (OpCodes.Call, get);
4048                                 if (ec.InIterator){
4049                                         conv.Emit (ec);
4050                                         ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4051                                 } else 
4052                                         ((IAssignMethod)variable).EmitAssign (ec, conv);
4053                                 statement.Emit (ec);
4054                                 ig.MarkLabel (ec.LoopBegin);
4055                                 for (dim = rank - 1; dim >= 0; dim--){
4056                                         dim_count [dim].EmitThis ();
4057                                         dim_count [dim].EmitThis ();
4058                                         dim_count [dim].EmitLoad ();
4059                                         ig.Emit (OpCodes.Ldc_I4_1);
4060                                         ig.Emit (OpCodes.Add);
4061                                         dim_count [dim].EmitStore ();
4062
4063                                         ig.MarkLabel (test [dim]);
4064                                         dim_count [dim].EmitThis ();
4065                                         dim_count [dim].EmitLoad ();
4066                                         dim_len [dim].EmitThis ();
4067                                         dim_len [dim].EmitLoad ();
4068                                         ig.Emit (OpCodes.Blt, loop [dim]);
4069                                 }
4070                         }
4071                         ig.MarkLabel (ec.LoopEnd);
4072                         
4073                         return false;
4074                 }
4075                 
4076                 protected override bool DoEmit (EmitContext ec)
4077                 {
4078                         bool ret_val;
4079                         
4080                         ILGenerator ig = ec.ig;
4081                         
4082                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4083                         bool old_inloop = ec.InLoop;
4084                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
4085                         ec.LoopBegin = ig.DefineLabel ();
4086                         ec.LoopEnd = ig.DefineLabel ();
4087                         ec.InLoop = true;
4088                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
4089                         
4090                         if (hm != null)
4091                                 ret_val = EmitCollectionForeach (ec);
4092                         else
4093                                 ret_val = EmitArrayForeach (ec);
4094                         
4095                         ec.LoopBegin = old_begin;
4096                         ec.LoopEnd = old_end;
4097                         ec.InLoop = old_inloop;
4098                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
4099
4100                         return ret_val;
4101                 }
4102         }
4103 }