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