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 true;
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 true;
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 true;
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                                         if (num_params > 0)
1306                                                 parameters = new MyBitVector (parent.parameters, num_params);
1307                                 } else {
1308                                         locals = new MyBitVector (null, CountLocals);
1309                                         if (num_params > 0)
1310                                                 parameters = new MyBitVector (null, num_params);
1311                                 }
1312
1313                                 id = ++next_id;
1314                         }
1315
1316                         public UsageVector (UsageVector parent)
1317                                 : this (parent, parent.CountParameters, parent.CountLocals)
1318                         { }
1319
1320                         // <summary>
1321                         //   This does a deep copy of the usage vector.
1322                         // </summary>
1323                         public UsageVector Clone ()
1324                         {
1325                                 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1326
1327                                 retval.locals = locals.Clone ();
1328                                 if (parameters != null)
1329                                         retval.parameters = parameters.Clone ();
1330                                 retval.real_returns = real_returns;
1331                                 retval.real_breaks = real_breaks;
1332
1333                                 return retval;
1334                         }
1335
1336                         // 
1337                         // State of parameter `number'.
1338                         //
1339                         public bool this [int number]
1340                         {
1341                                 get {
1342                                         if (number == -1)
1343                                                 return true;
1344                                         else if (number == 0)
1345                                                 throw new ArgumentException ();
1346
1347                                         return parameters [number - 1];
1348                                 }
1349
1350                                 set {
1351                                         if (number == -1)
1352                                                 return;
1353                                         else if (number == 0)
1354                                                 throw new ArgumentException ();
1355
1356                                         parameters [number - 1] = value;
1357                                 }
1358                         }
1359
1360                         //
1361                         // State of the local variable `vi'.
1362                         //
1363                         public bool this [VariableInfo vi]
1364                         {
1365                                 get {
1366                                         if (vi.Number == -1)
1367                                                 return true;
1368                                         else if (vi.Number == 0)
1369                                                 throw new ArgumentException ();
1370
1371                                         return locals [vi.Number - 1];
1372                                 }
1373
1374                                 set {
1375                                         if (vi.Number == -1)
1376                                                 return;
1377                                         else if (vi.Number == 0)
1378                                                 throw new ArgumentException ();
1379
1380                                         locals [vi.Number - 1] = value;
1381                                 }
1382                         }
1383
1384                         // <summary>
1385                         //   Specifies when the current block returns.
1386                         // </summary>
1387                         public FlowReturns Returns {
1388                                 get {
1389                                         return real_returns;
1390                                 }
1391
1392                                 set {
1393                                         real_returns = value;
1394                                         returns_set = true;
1395                                 }
1396                         }
1397
1398                         // <summary>
1399                         //   Specifies whether control may return to our containing block
1400                         //   before reaching the end of this block.  This happens if there
1401                         //   is a break/continue/goto/return in it.
1402                         // </summary>
1403                         public FlowReturns Breaks {
1404                                 get {
1405                                         return real_breaks;
1406                                 }
1407
1408                                 set {
1409                                         real_breaks = value;
1410                                         breaks_set = true;
1411                                 }
1412                         }
1413
1414                         // <summary>
1415                         //   Merge a child branching.
1416                         // </summary>
1417                         public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1418                         {
1419                                 MyBitVector new_locals = null;
1420                                 MyBitVector new_params = null;
1421
1422                                 FlowReturns new_returns = FlowReturns.NEVER;
1423                                 FlowReturns new_breaks = FlowReturns.NEVER;
1424                                 bool new_returns_set = false, new_breaks_set = false;
1425                                 FlowReturns breaks;
1426
1427                                 Report.Debug (1, "MERGING CHILDREN", branching, this);
1428
1429                                 foreach (UsageVector child in children) {
1430                                         Report.Debug (1, "  MERGING CHILD", child);
1431
1432                                         // If Returns is already set, perform an `And' operation on it,
1433                                         // otherwise just set just.
1434                                         if (!new_returns_set) {
1435                                                 new_returns = child.Returns;
1436                                                 new_returns_set = true;
1437                                         } else
1438                                                 new_returns = AndFlowReturns (new_returns, child.Returns);
1439
1440                                         // If Breaks is already set, perform an `And' operation on it,
1441                                         // otherwise just set just.
1442                                         if (!new_breaks_set) {
1443                                                 new_breaks = child.Breaks;
1444                                                 new_breaks_set = true;
1445                                         } else
1446                                                 new_breaks = AndFlowReturns (new_breaks, child.Breaks);
1447
1448                                         // Ignore unreachable children.
1449                                         if (child.Returns == FlowReturns.UNREACHABLE)
1450                                                 continue;
1451
1452                                         // If we're a switch section, `break' won't leave the current
1453                                         // branching (NOTE: the type check here means that we're "a"
1454                                         // switch section, not that we're "in" a switch section!).
1455                                         breaks = (branching.Type == FlowBranchingType.SWITCH_SECTION) ?
1456                                                 child.Returns : child.Breaks;
1457
1458                                         // A local variable is initialized after a flow branching if it
1459                                         // has been initialized in all its branches which do neither
1460                                         // always return or always throw an exception.
1461                                         //
1462                                         // If a branch may return, but does not always return, then we
1463                                         // can treat it like a never-returning branch here: control will
1464                                         // only reach the code position after the branching if we did not
1465                                         // return here.
1466                                         //
1467                                         // It's important to distinguish between always and sometimes
1468                                         // returning branches here:
1469                                         //
1470                                         //    1   int a;
1471                                         //    2   if (something) {
1472                                         //    3      return;
1473                                         //    4      a = 5;
1474                                         //    5   }
1475                                         //    6   Console.WriteLine (a);
1476                                         //
1477                                         // The if block in lines 3-4 always returns, so we must not look
1478                                         // at the initialization of `a' in line 4 - thus it'll still be
1479                                         // uninitialized in line 6.
1480                                         //
1481                                         // On the other hand, the following is allowed:
1482                                         //
1483                                         //    1   int a;
1484                                         //    2   if (something)
1485                                         //    3      a = 5;
1486                                         //    4   else
1487                                         //    5      return;
1488                                         //    6   Console.WriteLine (a);
1489                                         //
1490                                         // Here, `a' is initialized in line 3 and we must not look at
1491                                         // line 5 since it always returns.
1492                                         // 
1493                                         if ((breaks != FlowReturns.EXCEPTION) &&
1494                                             (breaks != FlowReturns.ALWAYS)) {
1495                                                 if (new_locals != null)
1496                                                         new_locals.And (child.locals);
1497                                                 else {
1498                                                         new_locals = locals.Clone ();
1499                                                         new_locals.Or (child.locals);
1500                                                 }
1501                                         }
1502
1503                                         // An `out' parameter must be assigned in all branches which do
1504                                         // not always throw an exception.
1505                                         if (!child.is_finally && (child.Returns != FlowReturns.EXCEPTION)) {
1506                                                 if (parameters != null) {
1507                                                         if (new_params != null)
1508                                                                 new_params.And (child.parameters);
1509                                                         else {
1510                                                                 new_params = parameters.Clone ();
1511                                                                 new_params.Or (child.parameters);
1512                                                         }
1513                                                 }
1514                                         }
1515
1516                                         // If we always return, check whether all `out' parameters have
1517                                         // been assigned.
1518                                         if ((child.Returns == FlowReturns.ALWAYS) && (child.parameters != null)) {
1519                                                 branching.CheckOutParameters (
1520                                                         child.parameters, branching.Location);
1521                                         }
1522                                 }
1523
1524                                 // Set new `Returns' status.
1525                                 if (!returns_set) {
1526                                         Returns = new_returns;
1527                                         returns_set = true;
1528                                 } else
1529                                         Returns = AndFlowReturns (Returns, new_returns);
1530
1531                                 //
1532                                 // We've now either reached the point after the branching or we will
1533                                 // never get there since we always return or always throw an exception.
1534                                 //
1535                                 // If we can reach the point after the branching, mark all locals and
1536                                 // parameters as initialized which have been initialized in all branches
1537                                 // we need to look at (see above).
1538                                 //
1539
1540                                 breaks = (branching.Type == FlowBranchingType.SWITCH_SECTION) ?
1541                                         Returns : Breaks;
1542
1543                                 if ((new_locals != null) &&
1544                                     ((breaks == FlowReturns.NEVER) || (breaks == FlowReturns.SOMETIMES))) {
1545                                         locals.Or (new_locals);
1546                                 }
1547
1548                                 if ((new_params != null) && (Breaks == FlowReturns.NEVER))
1549                                         parameters.Or (new_params);
1550
1551                                 //
1552                                 // If we may have returned (this only happens if there was a reachable
1553                                 // `return' statement in one of the branches), then we may return to our
1554                                 // parent block before reaching the end of the block, so set `Breaks'.
1555                                 //
1556
1557                                 if ((Returns != FlowReturns.NEVER) && (Returns != FlowReturns.SOMETIMES)) {
1558                                         real_breaks = Returns;
1559                                         breaks_set = true;
1560                                 }
1561
1562                                 Report.Debug (1, "MERGING CHILDREN DONE", new_params, new_locals,
1563                                               new_returns, new_breaks, this);
1564
1565                                 return new_returns;
1566                         }
1567
1568                         // <summary>
1569                         //   Tells control flow analysis that the current code position may be reached with
1570                         //   a forward jump from any of the origins listed in `origin_vectors' which is a
1571                         //   list of UsageVectors.
1572                         //
1573                         //   This is used when resolving forward gotos - in the following example, the
1574                         //   variable `a' is uninitialized in line 8 becase this line may be reached via
1575                         //   the goto in line 4:
1576                         //
1577                         //      1     int a;
1578                         //
1579                         //      3     if (something)
1580                         //      4        goto World;
1581                         //
1582                         //      6     a = 5;
1583                         //
1584                         //      7  World:
1585                         //      8     Console.WriteLine (a);
1586                         //
1587                         // </summary>
1588                         public void MergeJumpOrigins (ICollection origin_vectors)
1589                         {
1590                                 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1591
1592                                 real_breaks = FlowReturns.NEVER;
1593                                 breaks_set = false;
1594
1595                                 foreach (UsageVector vector in origin_vectors) {
1596                                         Report.Debug (1, "  MERGING JUMP ORIGIN", vector);
1597
1598                                         locals.And (vector.locals);
1599                                         if (parameters != null)
1600                                                 parameters.And (vector.parameters);
1601                                         Breaks = AndFlowReturns (Breaks, vector.Breaks);
1602                                 }
1603
1604                                 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1605                         }
1606
1607                         // <summary>
1608                         //   This is used at the beginning of a finally block if there were
1609                         //   any return statements in the try block or one of the catch blocks.
1610                         // </summary>
1611                         public void MergeFinallyOrigins (ICollection finally_vectors)
1612                         {
1613                                 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1614
1615                                 real_breaks = FlowReturns.NEVER;
1616                                 breaks_set = false;
1617
1618                                 foreach (UsageVector vector in finally_vectors) {
1619                                         Report.Debug (1, "  MERGING FINALLY ORIGIN", vector);
1620
1621                                         if (parameters != null)
1622                                                 parameters.And (vector.parameters);
1623                                         Breaks = AndFlowReturns (Breaks, vector.Breaks);
1624                                 }
1625
1626                                 is_finally = true;
1627
1628                                 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1629                         }
1630
1631                         // <summary>
1632                         //   Performs an `or' operation on the locals and the parameters.
1633                         // </summary>
1634                         public void Or (UsageVector new_vector)
1635                         {
1636                                 locals.Or (new_vector.locals);
1637                                 if (parameters != null)
1638                                         parameters.Or (new_vector.parameters);
1639                         }
1640
1641                         // <summary>
1642                         //   Performs an `and' operation on the locals.
1643                         // </summary>
1644                         public void AndLocals (UsageVector new_vector)
1645                         {
1646                                 locals.And (new_vector.locals);
1647                         }
1648
1649                         // <summary>
1650                         //   Returns a deep copy of the parameters.
1651                         // </summary>
1652                         public MyBitVector Parameters {
1653                                 get {
1654                                         if (parameters != null)
1655                                                 return parameters.Clone ();
1656                                         else
1657                                                 return null;
1658                                 }
1659                         }
1660
1661                         // <summary>
1662                         //   Returns a deep copy of the locals.
1663                         // </summary>
1664                         public MyBitVector Locals {
1665                                 get {
1666                                         return locals.Clone ();
1667                                 }
1668                         }
1669
1670                         //
1671                         // Debugging stuff.
1672                         //
1673
1674                         public override string ToString ()
1675                         {
1676                                 StringBuilder sb = new StringBuilder ();
1677
1678                                 sb.Append ("Vector (");
1679                                 sb.Append (id);
1680                                 sb.Append (",");
1681                                 sb.Append (Returns);
1682                                 sb.Append (",");
1683                                 sb.Append (Breaks);
1684                                 if (parameters != null) {
1685                                         sb.Append (" - ");
1686                                         sb.Append (parameters);
1687                                 }
1688                                 sb.Append (" - ");
1689                                 sb.Append (locals);
1690                                 sb.Append (")");
1691
1692                                 return sb.ToString ();
1693                         }
1694                 }
1695
1696                 FlowBranching (FlowBranchingType type, Location loc)
1697                 {
1698                         this.Siblings = new ArrayList ();
1699                         this.Block = null;
1700                         this.Location = loc;
1701                         this.Type = type;
1702                         id = ++next_id;
1703                 }
1704
1705                 // <summary>
1706                 //   Creates a new flow branching for `block'.
1707                 //   This is used from Block.Resolve to create the top-level branching of
1708                 //   the block.
1709                 // </summary>
1710                 public FlowBranching (Block block, InternalParameters ip, Location loc)
1711                         : this (FlowBranchingType.BLOCK, loc)
1712                 {
1713                         Block = block;
1714                         Parent = null;
1715
1716                         param_info = ip;
1717                         param_map = new int [(param_info != null) ? param_info.Count : 0];
1718                         num_params = 0;
1719
1720                         for (int i = 0; i < param_map.Length; i++) {
1721                                 Parameter.Modifier mod = param_info.ParameterModifier (i);
1722
1723                                 if ((mod & Parameter.Modifier.OUT) == 0)
1724                                         continue;
1725
1726                                 param_map [i] = ++num_params;
1727                         }
1728
1729                         Siblings = new ArrayList ();
1730                         Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1731                 }
1732
1733                 // <summary>
1734                 //   Creates a new flow branching which is contained in `parent'.
1735                 //   You should only pass non-null for the `block' argument if this block
1736                 //   introduces any new variables - in this case, we need to create a new
1737                 //   usage vector with a different size than our parent's one.
1738                 // </summary>
1739                 public FlowBranching (FlowBranching parent, FlowBranchingType type,
1740                                       Block block, Location loc)
1741                         : this (type, loc)
1742                 {
1743                         Parent = parent;
1744                         Block = block;
1745
1746                         if (parent != null) {
1747                                 param_info = parent.param_info;
1748                                 param_map = parent.param_map;
1749                                 num_params = parent.num_params;
1750                         }
1751
1752                         UsageVector vector;
1753                         if (Block != null)
1754                                 vector = new UsageVector (parent.CurrentUsageVector, num_params,
1755                                                           Block.CountVariables);
1756                         else
1757                                 vector = new UsageVector (Parent.CurrentUsageVector);
1758
1759                         Siblings.Add (vector);
1760
1761                         switch (Type) {
1762                         case FlowBranchingType.EXCEPTION:
1763                                 finally_vectors = new ArrayList ();
1764                                 break;
1765
1766                         default:
1767                                 break;
1768                         }
1769                 }
1770
1771                 // <summary>
1772                 //   Returns the branching's current usage vector.
1773                 // </summary>
1774                 public UsageVector CurrentUsageVector
1775                 {
1776                         get {
1777                                 return (UsageVector) Siblings [Siblings.Count - 1];
1778                         }
1779                 }
1780
1781                 // <summary>
1782                 //   Creates a sibling of the current usage vector.
1783                 // </summary>
1784                 public void CreateSibling ()
1785                 {
1786                         Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
1787
1788                         Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
1789                 }
1790
1791                 // <summary>
1792                 //   Creates a sibling for a `finally' block.
1793                 // </summary>
1794                 public void CreateSiblingForFinally ()
1795                 {
1796                         if (Type != FlowBranchingType.EXCEPTION)
1797                                 throw new NotSupportedException ();
1798
1799                         CreateSibling ();
1800
1801                         CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
1802                 }
1803
1804                 // <summary>
1805                 //   Check whether all `out' parameters have been assigned.
1806                 // </summary>
1807                 public void CheckOutParameters (MyBitVector parameters, Location loc)
1808                 {
1809                         if (InTryBlock ())
1810                                 return;
1811
1812                         for (int i = 0; i < param_map.Length; i++) {
1813                                 if (param_map [i] == 0)
1814                                         continue;
1815
1816                                 if (!parameters [param_map [i] - 1]) {
1817                                         Report.Error (
1818                                                 177, loc, "The out parameter `" +
1819                                                 param_info.ParameterName (i) + "` must be " +
1820                                                 "assigned before control leave the current method.");
1821                                         param_map [i] = 0;
1822                                 }
1823                         }
1824                 }
1825
1826                 // <summary>
1827                 //   Merge a child branching.
1828                 // </summary>
1829                 public FlowReturns MergeChild (FlowBranching child)
1830                 {
1831                         return CurrentUsageVector.MergeChildren (child, child.Siblings);
1832                 }
1833
1834                 // <summary>
1835                 //   Does the toplevel merging.
1836                 // </summary>
1837                 public FlowReturns MergeTopBlock ()
1838                 {
1839                         if ((Type != FlowBranchingType.BLOCK) || (Block == null))
1840                                 throw new NotSupportedException ();
1841
1842                         UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
1843
1844                         vector.MergeChildren (this, Siblings);
1845
1846                         Siblings.Clear ();
1847                         Siblings.Add (vector);
1848
1849                         Report.Debug (1, "MERGING TOP BLOCK", vector);
1850
1851                         if (vector.Returns != FlowReturns.EXCEPTION)
1852                                 CheckOutParameters (CurrentUsageVector.Parameters, Location);
1853
1854                         return vector.Returns;
1855                 }
1856
1857                 public bool InTryBlock ()
1858                 {
1859                         if (finally_vectors != null)
1860                                 return true;
1861                         else if (Parent != null)
1862                                 return Parent.InTryBlock ();
1863                         else
1864                                 return false;
1865                 }
1866
1867                 public void AddFinallyVector (UsageVector vector)
1868                 {
1869                         if (finally_vectors != null) {
1870                                 finally_vectors.Add (vector.Clone ());
1871                                 return;
1872                         }
1873
1874                         if (Parent != null)
1875                                 Parent.AddFinallyVector (vector);
1876                         else
1877                                 throw new NotSupportedException ();
1878                 }
1879
1880                 public bool IsVariableAssigned (VariableInfo vi)
1881                 {
1882                         Report.Debug (2, "CHECK VARIABLE ACCESS", this, vi);
1883
1884                         if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1885                                 return true;
1886                         else
1887                                 return CurrentUsageVector [vi];
1888                 }
1889
1890                 public void SetVariableAssigned (VariableInfo vi)
1891                 {
1892                         Report.Debug (2, "SET VARIABLE ACCESS", this, vi, CurrentUsageVector);
1893
1894                         if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1895                                 return;
1896
1897                         CurrentUsageVector [vi] = true;
1898                 }
1899
1900                 public bool IsParameterAssigned (int number)
1901                 {
1902                         Report.Debug (2, "IS PARAMETER ASSIGNED", this, number);
1903
1904                         if (param_map [number] == 0)
1905                                 return true;
1906                         else
1907                                 return CurrentUsageVector [param_map [number]];
1908                 }
1909
1910                 public void SetParameterAssigned (int number)
1911                 {
1912                         Report.Debug (2, "SET PARAMETER ACCESS", this, number, param_map [number],
1913                                       CurrentUsageVector);
1914
1915                         if (param_map [number] == 0)
1916                                 return;
1917
1918                         if (CurrentUsageVector.Breaks == FlowReturns.NEVER)
1919                                 CurrentUsageVector [param_map [number]] = true;
1920                 }
1921
1922                 public override string ToString ()
1923                 {
1924                         StringBuilder sb = new StringBuilder ("FlowBranching (");
1925
1926                         sb.Append (id);
1927                         sb.Append (",");
1928                         sb.Append (Type);
1929                         if (Block != null) {
1930                                 sb.Append (" - ");
1931                                 sb.Append (Block.ID);
1932                                 sb.Append (" - ");
1933                                 sb.Append (Block.StartLocation);
1934                         }
1935                         sb.Append (" - ");
1936                         sb.Append (Siblings.Count);
1937                         sb.Append (" - ");
1938                         sb.Append (CurrentUsageVector);
1939                         sb.Append (")");
1940                         return sb.ToString ();
1941                 }
1942         }
1943         
1944         public class VariableInfo {
1945                 public Expression Type;
1946                 public LocalBuilder LocalBuilder;
1947                 public Type VariableType;
1948                 public readonly Location Location;
1949
1950                 public int Number;
1951                 
1952                 public bool Used;
1953                 public bool Assigned;
1954                 public bool ReadOnly;
1955                 
1956                 public VariableInfo (Expression type, Location l)
1957                 {
1958                         Type = type;
1959                         LocalBuilder = null;
1960                         Location = l;
1961                 }
1962
1963                 public void MakePinned ()
1964                 {
1965                         TypeManager.MakePinned (LocalBuilder);
1966                 }
1967
1968                 public override string ToString ()
1969                 {
1970                         return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
1971                 }
1972         }
1973                 
1974         /// <summary>
1975         ///   Block represents a C# block.
1976         /// </summary>
1977         ///
1978         /// <remarks>
1979         ///   This class is used in a number of places: either to represent
1980         ///   explicit blocks that the programmer places or implicit blocks.
1981         ///
1982         ///   Implicit blocks are used as labels or to introduce variable
1983         ///   declarations.
1984         /// </remarks>
1985         public class Block : Statement {
1986                 public readonly Block     Parent;
1987                 public readonly bool      Implicit;
1988                 public readonly Location  StartLocation;
1989                 public Location           EndLocation;
1990
1991                 //
1992                 // The statements in this block
1993                 //
1994                 ArrayList statements;
1995
1996                 //
1997                 // An array of Blocks.  We keep track of children just
1998                 // to generate the local variable declarations.
1999                 //
2000                 // Statements and child statements are handled through the
2001                 // statements.
2002                 //
2003                 ArrayList children;
2004                 
2005                 //
2006                 // Labels.  (label, block) pairs.
2007                 //
2008                 Hashtable labels;
2009
2010                 //
2011                 // Keeps track of (name, type) pairs
2012                 //
2013                 Hashtable variables;
2014
2015                 //
2016                 // Keeps track of constants
2017                 Hashtable constants;
2018
2019                 //
2020                 // Maps variable names to ILGenerator.LocalBuilders
2021                 //
2022                 Hashtable local_builders;
2023
2024                 bool used = false;
2025
2026                 static int id;
2027
2028                 int this_id;
2029                 
2030                 public Block (Block parent)
2031                         : this (parent, false, Location.Null, Location.Null)
2032                 { }
2033
2034                 public Block (Block parent, bool implicit_block)
2035                         : this (parent, implicit_block, Location.Null, Location.Null)
2036                 { }
2037
2038                 public Block (Block parent, Location start, Location end)
2039                         : this (parent, false, start, end)
2040                 { }
2041
2042                 public Block (Block parent, bool implicit_block, Location start, Location end)
2043                 {
2044                         if (parent != null)
2045                                 parent.AddChild (this);
2046                         
2047                         this.Parent = parent;
2048                         this.Implicit = implicit_block;
2049                         this.StartLocation = start;
2050                         this.EndLocation = end;
2051                         this.loc = start;
2052                         this_id = id++;
2053                         statements = new ArrayList ();
2054                 }
2055
2056                 public int ID {
2057                         get {
2058                                 return this_id;
2059                         }
2060                 }
2061                 
2062                 void AddChild (Block b)
2063                 {
2064                         if (children == null)
2065                                 children = new ArrayList ();
2066                         
2067                         children.Add (b);
2068                 }
2069
2070                 public void SetEndLocation (Location loc)
2071                 {
2072                         EndLocation = loc;
2073                 }
2074
2075                 /// <summary>
2076                 ///   Adds a label to the current block. 
2077                 /// </summary>
2078                 ///
2079                 /// <returns>
2080                 ///   false if the name already exists in this block. true
2081                 ///   otherwise.
2082                 /// </returns>
2083                 ///
2084                 public bool AddLabel (string name, LabeledStatement target)
2085                 {
2086                         if (labels == null)
2087                                 labels = new Hashtable ();
2088                         if (labels.Contains (name))
2089                                 return false;
2090                         
2091                         labels.Add (name, target);
2092                         return true;
2093                 }
2094
2095                 public LabeledStatement LookupLabel (string name)
2096                 {
2097                         if (labels != null){
2098                                 if (labels.Contains (name))
2099                                         return ((LabeledStatement) labels [name]);
2100                         }
2101
2102                         if (Parent != null)
2103                                 return Parent.LookupLabel (name);
2104
2105                         return null;
2106                 }
2107
2108                 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2109                 {
2110                         if (variables == null)
2111                                 variables = new Hashtable ();
2112
2113                         if (GetVariableType (name) != null)
2114                                 return null;
2115
2116                         if (pars != null) {
2117                                 int idx = 0;
2118                                 Parameter p = pars.GetParameterByName (name, out idx);
2119                                 if (p != null) 
2120                                         return null;
2121                         }
2122                         
2123                         VariableInfo vi = new VariableInfo (type, l);
2124
2125                         variables.Add (name, vi);
2126
2127                         if (variables_initialized)
2128                                 throw new Exception ();
2129
2130                         // Console.WriteLine ("Adding {0} to {1}", name, ID);
2131                         return vi;
2132                 }
2133
2134                 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2135                 {
2136                         if (AddVariable (type, name, pars, l) == null)
2137                                 return false;
2138                         
2139                         if (constants == null)
2140                                 constants = new Hashtable ();
2141
2142                         constants.Add (name, value);
2143                         return true;
2144                 }
2145
2146                 public Hashtable Variables {
2147                         get {
2148                                 return variables;
2149                         }
2150                 }
2151
2152                 public VariableInfo GetVariableInfo (string name)
2153                 {
2154                         if (variables != null) {
2155                                 object temp;
2156                                 temp = variables [name];
2157
2158                                 if (temp != null){
2159                                         return (VariableInfo) temp;
2160                                 }
2161                         }
2162
2163                         if (Parent != null)
2164                                 return Parent.GetVariableInfo (name);
2165
2166                         return null;
2167                 }
2168                 
2169                 public Expression GetVariableType (string name)
2170                 {
2171                         VariableInfo vi = GetVariableInfo (name);
2172
2173                         if (vi != null)
2174                                 return vi.Type;
2175
2176                         return null;
2177                 }
2178
2179                 public Expression GetConstantExpression (string name)
2180                 {
2181                         if (constants != null) {
2182                                 object temp;
2183                                 temp = constants [name];
2184                                 
2185                                 if (temp != null)
2186                                         return (Expression) temp;
2187                         }
2188                         
2189                         if (Parent != null)
2190                                 return Parent.GetConstantExpression (name);
2191
2192                         return null;
2193                 }
2194                 
2195                 /// <summary>
2196                 ///   True if the variable named @name has been defined
2197                 ///   in this block
2198                 /// </summary>
2199                 public bool IsVariableDefined (string name)
2200                 {
2201                         // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2202                         if (variables != null) {
2203                                 if (variables.Contains (name))
2204                                         return true;
2205                         }
2206                         
2207                         if (Parent != null)
2208                                 return Parent.IsVariableDefined (name);
2209
2210                         return false;
2211                 }
2212
2213                 /// <summary>
2214                 ///   True if the variable named @name is a constant
2215                 ///  </summary>
2216                 public bool IsConstant (string name)
2217                 {
2218                         Expression e = null;
2219                         
2220                         e = GetConstantExpression (name);
2221                         
2222                         return e != null;
2223                 }
2224                 
2225                 /// <summary>
2226                 ///   Use to fetch the statement associated with this label
2227                 /// </summary>
2228                 public Statement this [string name] {
2229                         get {
2230                                 return (Statement) labels [name];
2231                         }
2232                 }
2233
2234                 /// <returns>
2235                 ///   A list of labels that were not used within this block
2236                 /// </returns>
2237                 public string [] GetUnreferenced ()
2238                 {
2239                         // FIXME: Implement me
2240                         return null;
2241                 }
2242
2243                 public void AddStatement (Statement s)
2244                 {
2245                         statements.Add (s);
2246                         used = true;
2247                 }
2248
2249                 public bool Used {
2250                         get {
2251                                 return used;
2252                         }
2253                 }
2254
2255                 public void Use ()
2256                 {
2257                         used = true;
2258                 }
2259
2260                 bool variables_initialized = false;
2261                 int count_variables = 0, first_variable = 0;
2262
2263                 void UpdateVariableInfo (EmitContext ec)
2264                 {
2265                         DeclSpace ds = ec.DeclSpace;
2266
2267                         first_variable = 0;
2268
2269                         if (Parent != null)
2270                                 first_variable += Parent.CountVariables;
2271
2272                         count_variables = first_variable;
2273                         if (variables != null) {
2274                                 foreach (VariableInfo vi in variables.Values) {
2275                                         Report.Debug (2, "VARIABLE", vi);
2276
2277                                         Type type = ds.ResolveType (vi.Type, false, vi.Location);
2278                                         if (type == null) {
2279                                                 vi.Number = -1;
2280                                                 continue;
2281                                         }
2282
2283                                         vi.VariableType = type;
2284
2285                                         Report.Debug (2, "VARIABLE", vi, type, type.IsValueType,
2286                                                       TypeManager.IsValueType (type),
2287                                                       TypeManager.IsBuiltinType (type));
2288
2289                                         // FIXME: we don't have support for structs yet.
2290                                         if (TypeManager.IsValueType (type) && !TypeManager.IsBuiltinType (type))
2291                                                 vi.Number = -1;
2292                                         else
2293                                                 vi.Number = ++count_variables;
2294                                 }
2295                         }
2296
2297                         variables_initialized = true;
2298                 }
2299
2300                 //
2301                 // <returns>
2302                 //   The number of local variables in this block
2303                 // </returns>
2304                 public int CountVariables
2305                 {
2306                         get {
2307                                 if (!variables_initialized)
2308                                         throw new Exception ();
2309
2310                                 return count_variables;
2311                         }
2312                 }
2313
2314                 /// <summary>
2315                 ///   Emits the variable declarations and labels.
2316                 /// </summary>
2317                 /// <remarks>
2318                 ///   tc: is our typecontainer (to resolve type references)
2319                 ///   ig: is the code generator:
2320                 ///   toplevel: the toplevel block.  This is used for checking 
2321                 ///             that no two labels with the same name are used.
2322                 /// </remarks>
2323                 public void EmitMeta (EmitContext ec, Block toplevel)
2324                 {
2325                         DeclSpace ds = ec.DeclSpace;
2326                         ILGenerator ig = ec.ig;
2327
2328                         if (!variables_initialized)
2329                                 UpdateVariableInfo (ec);
2330
2331                         //
2332                         // Process this block variables
2333                         //
2334                         if (variables != null){
2335                                 local_builders = new Hashtable ();
2336                                 
2337                                 foreach (DictionaryEntry de in variables){
2338                                         string name = (string) de.Key;
2339                                         VariableInfo vi = (VariableInfo) de.Value;
2340
2341                                         if (vi.VariableType == null)
2342                                                 continue;
2343
2344                                         vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
2345
2346                                         if (CodeGen.SymbolWriter != null)
2347                                                 vi.LocalBuilder.SetLocalSymInfo (name);
2348
2349                                         if (constants == null)
2350                                                 continue;
2351
2352                                         Expression cv = (Expression) constants [name];
2353                                         if (cv == null)
2354                                                 continue;
2355
2356                                         Expression e = cv.Resolve (ec);
2357                                         if (e == null)
2358                                                 continue;
2359
2360                                         if (!(e is Constant)){
2361                                                 Report.Error (133, vi.Location,
2362                                                               "The expression being assigned to `" +
2363                                                               name + "' must be constant (" + e + ")");
2364                                                 continue;
2365                                         }
2366
2367                                         constants.Remove (name);
2368                                         constants.Add (name, e);
2369                                 }
2370                         }
2371
2372                         //
2373                         // Now, handle the children
2374                         //
2375                         if (children != null){
2376                                 foreach (Block b in children)
2377                                         b.EmitMeta (ec, toplevel);
2378                         }
2379                 }
2380
2381                 public void UsageWarning ()
2382                 {
2383                         string name;
2384                         
2385                         if (variables != null){
2386                                 foreach (DictionaryEntry de in variables){
2387                                         VariableInfo vi = (VariableInfo) de.Value;
2388                                         
2389                                         if (vi.Used)
2390                                                 continue;
2391                                         
2392                                         name = (string) de.Key;
2393                                                 
2394                                         if (vi.Assigned){
2395                                                 Report.Warning (
2396                                                         219, vi.Location, "The variable `" + name +
2397                                                         "' is assigned but its value is never used");
2398                                         } else {
2399                                                 Report.Warning (
2400                                                         168, vi.Location, "The variable `" +
2401                                                         name +
2402                                                         "' is declared but never used");
2403                                         } 
2404                                 }
2405                         }
2406
2407                         if (children != null)
2408                                 foreach (Block b in children)
2409                                         b.UsageWarning ();
2410                 }
2411
2412                 public override bool Resolve (EmitContext ec)
2413                 {
2414                         Block prev_block = ec.CurrentBlock;
2415                         bool ok = true;
2416
2417                         ec.CurrentBlock = this;
2418                         ec.StartFlowBranching (this);
2419
2420                         Report.Debug (1, "RESOLVE BLOCK", StartLocation);
2421
2422                         if (!variables_initialized)
2423                                 UpdateVariableInfo (ec);
2424
2425                         foreach (Statement s in statements){
2426                                 if (s.Resolve (ec) == false)
2427                                         ok = false;
2428                         }
2429
2430                         Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation);
2431
2432                         ec.EndFlowBranching ();
2433                         ec.CurrentBlock = prev_block;
2434                         return ok;
2435                 }
2436                 
2437                 public override bool Emit (EmitContext ec)
2438                 {
2439                         bool is_ret = false, this_ret = false;
2440                         Block prev_block = ec.CurrentBlock;
2441                         bool warning_shown = false;
2442
2443                         ec.CurrentBlock = this;
2444
2445                         if (CodeGen.SymbolWriter != null) {
2446                                 ec.Mark (StartLocation);
2447                                 
2448                                 foreach (Statement s in statements) {
2449                                         ec.Mark (s.loc);
2450                                         
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                                 ec.Mark (EndLocation); 
2461                         } else {
2462                                 foreach (Statement s in statements){
2463                                         if (is_ret && !warning_shown && !(s is EmptyStatement)){
2464                                                 warning_shown = true;
2465                                                 Warning_DeadCodeFound (s.loc);
2466                                         }
2467                                         this_ret = s.Emit (ec);
2468                                         if (this_ret)
2469                                                 is_ret = true;
2470                                 }
2471                         }
2472                         
2473                         ec.CurrentBlock = prev_block;
2474                         return is_ret;
2475                 }
2476         }
2477
2478         public class SwitchLabel {
2479                 Expression label;
2480                 object converted;
2481                 public Location loc;
2482                 public Label ILLabel;
2483                 public Label ILLabelCode;
2484
2485                 //
2486                 // if expr == null, then it is the default case.
2487                 //
2488                 public SwitchLabel (Expression expr, Location l)
2489                 {
2490                         label = expr;
2491                         loc = l;
2492                 }
2493
2494                 public Expression Label {
2495                         get {
2496                                 return label;
2497                         }
2498                 }
2499
2500                 public object Converted {
2501                         get {
2502                                 return converted;
2503                         }
2504                 }
2505
2506                 //
2507                 // Resolves the expression, reduces it to a literal if possible
2508                 // and then converts it to the requested type.
2509                 //
2510                 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2511                 {
2512                         ILLabel = ec.ig.DefineLabel ();
2513                         ILLabelCode = ec.ig.DefineLabel ();
2514
2515                         if (label == null)
2516                                 return true;
2517                         
2518                         Expression e = label.Resolve (ec);
2519
2520                         if (e == null)
2521                                 return false;
2522
2523                         if (!(e is Constant)){
2524                                 Console.WriteLine ("Value is: " + label);
2525                                 Report.Error (150, loc, "A constant value is expected");
2526                                 return false;
2527                         }
2528
2529                         if (e is StringConstant || e is NullLiteral){
2530                                 if (required_type == TypeManager.string_type){
2531                                         converted = label;
2532                                         ILLabel = ec.ig.DefineLabel ();
2533                                         return true;
2534                                 }
2535                         }
2536
2537                         converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2538                         if (converted == null)
2539                                 return false;
2540
2541                         return true;
2542                 }
2543         }
2544
2545         public class SwitchSection {
2546                 // An array of SwitchLabels.
2547                 public readonly ArrayList Labels;
2548                 public readonly Block Block;
2549                 
2550                 public SwitchSection (ArrayList labels, Block block)
2551                 {
2552                         Labels = labels;
2553                         Block = block;
2554                 }
2555         }
2556         
2557         public class Switch : Statement {
2558                 public readonly ArrayList Sections;
2559                 public Expression Expr;
2560
2561                 /// <summary>
2562                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
2563                 /// </summary>
2564                 public Hashtable Elements;
2565
2566                 /// <summary>
2567                 ///   The governing switch type
2568                 /// </summary>
2569                 public Type SwitchType;
2570
2571                 //
2572                 // Computed
2573                 //
2574                 bool got_default;
2575                 Label default_target;
2576                 Expression new_expr;
2577
2578                 //
2579                 // The types allowed to be implicitly cast from
2580                 // on the governing type
2581                 //
2582                 static Type [] allowed_types;
2583                 
2584                 public Switch (Expression e, ArrayList sects, Location l)
2585                 {
2586                         Expr = e;
2587                         Sections = sects;
2588                         loc = l;
2589                 }
2590
2591                 public bool GotDefault {
2592                         get {
2593                                 return got_default;
2594                         }
2595                 }
2596
2597                 public Label DefaultTarget {
2598                         get {
2599                                 return default_target;
2600                         }
2601                 }
2602
2603                 //
2604                 // Determines the governing type for a switch.  The returned
2605                 // expression might be the expression from the switch, or an
2606                 // expression that includes any potential conversions to the
2607                 // integral types or to string.
2608                 //
2609                 Expression SwitchGoverningType (EmitContext ec, Type t)
2610                 {
2611                         if (t == TypeManager.int32_type ||
2612                             t == TypeManager.uint32_type ||
2613                             t == TypeManager.char_type ||
2614                             t == TypeManager.byte_type ||
2615                             t == TypeManager.sbyte_type ||
2616                             t == TypeManager.ushort_type ||
2617                             t == TypeManager.short_type ||
2618                             t == TypeManager.uint64_type ||
2619                             t == TypeManager.int64_type ||
2620                             t == TypeManager.string_type ||
2621                                 t == TypeManager.bool_type ||
2622                                 t.IsSubclassOf (TypeManager.enum_type))
2623                                 return Expr;
2624
2625                         if (allowed_types == null){
2626                                 allowed_types = new Type [] {
2627                                         TypeManager.sbyte_type,
2628                                         TypeManager.byte_type,
2629                                         TypeManager.short_type,
2630                                         TypeManager.ushort_type,
2631                                         TypeManager.int32_type,
2632                                         TypeManager.uint32_type,
2633                                         TypeManager.int64_type,
2634                                         TypeManager.uint64_type,
2635                                         TypeManager.char_type,
2636                                         TypeManager.bool_type,
2637                                         TypeManager.string_type
2638                                 };
2639                         }
2640
2641                         //
2642                         // Try to find a *user* defined implicit conversion.
2643                         //
2644                         // If there is no implicit conversion, or if there are multiple
2645                         // conversions, we have to report an error
2646                         //
2647                         Expression converted = null;
2648                         foreach (Type tt in allowed_types){
2649                                 Expression e;
2650                                 
2651                                 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
2652                                 if (e == null)
2653                                         continue;
2654
2655                                 if (converted != null){
2656                                         Report.Error (-12, loc, "More than one conversion to an integral " +
2657                                                       " type exists for type `" +
2658                                                       TypeManager.CSharpName (Expr.Type)+"'");
2659                                         return null;
2660                                 } else
2661                                         converted = e;
2662                         }
2663                         return converted;
2664                 }
2665
2666                 void error152 (string n)
2667                 {
2668                         Report.Error (
2669                                 152, "The label `" + n + ":' " +
2670                                 "is already present on this switch statement");
2671                 }
2672                 
2673                 //
2674                 // Performs the basic sanity checks on the switch statement
2675                 // (looks for duplicate keys and non-constant expressions).
2676                 //
2677                 // It also returns a hashtable with the keys that we will later
2678                 // use to compute the switch tables
2679                 //
2680                 bool CheckSwitch (EmitContext ec)
2681                 {
2682                         Type compare_type;
2683                         bool error = false;
2684                         Elements = new Hashtable ();
2685                                 
2686                         got_default = false;
2687
2688                         if (TypeManager.IsEnumType (SwitchType)){
2689                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2690                         } else
2691                                 compare_type = SwitchType;
2692                         
2693                         foreach (SwitchSection ss in Sections){
2694                                 foreach (SwitchLabel sl in ss.Labels){
2695                                         if (!sl.ResolveAndReduce (ec, SwitchType)){
2696                                                 error = true;
2697                                                 continue;
2698                                         }
2699
2700                                         if (sl.Label == null){
2701                                                 if (got_default){
2702                                                         error152 ("default");
2703                                                         error = true;
2704                                                 }
2705                                                 got_default = true;
2706                                                 continue;
2707                                         }
2708                                         
2709                                         object key = sl.Converted;
2710
2711                                         if (key is Constant)
2712                                                 key = ((Constant) key).GetValue ();
2713
2714                                         if (key == null)
2715                                                 key = NullLiteral.Null;
2716                                         
2717                                         string lname = null;
2718                                         if (compare_type == TypeManager.uint64_type){
2719                                                 ulong v = (ulong) key;
2720
2721                                                 if (Elements.Contains (v))
2722                                                         lname = v.ToString ();
2723                                                 else
2724                                                         Elements.Add (v, sl);
2725                                         } else if (compare_type == TypeManager.int64_type){
2726                                                 long v = (long) key;
2727
2728                                                 if (Elements.Contains (v))
2729                                                         lname = v.ToString ();
2730                                                 else
2731                                                         Elements.Add (v, sl);
2732                                         } else if (compare_type == TypeManager.uint32_type){
2733                                                 uint v = (uint) key;
2734
2735                                                 if (Elements.Contains (v))
2736                                                         lname = v.ToString ();
2737                                                 else
2738                                                         Elements.Add (v, sl);
2739                                         } else if (compare_type == TypeManager.char_type){
2740                                                 char v = (char) key;
2741                                                 
2742                                                 if (Elements.Contains (v))
2743                                                         lname = v.ToString ();
2744                                                 else
2745                                                         Elements.Add (v, sl);
2746                                         } else if (compare_type == TypeManager.byte_type){
2747                                                 byte v = (byte) key;
2748                                                 
2749                                                 if (Elements.Contains (v))
2750                                                         lname = v.ToString ();
2751                                                 else
2752                                                         Elements.Add (v, sl);
2753                                         } else if (compare_type == TypeManager.sbyte_type){
2754                                                 sbyte v = (sbyte) key;
2755                                                 
2756                                                 if (Elements.Contains (v))
2757                                                         lname = v.ToString ();
2758                                                 else
2759                                                         Elements.Add (v, sl);
2760                                         } else if (compare_type == TypeManager.short_type){
2761                                                 short v = (short) key;
2762                                                 
2763                                                 if (Elements.Contains (v))
2764                                                         lname = v.ToString ();
2765                                                 else
2766                                                         Elements.Add (v, sl);
2767                                         } else if (compare_type == TypeManager.ushort_type){
2768                                                 ushort v = (ushort) key;
2769                                                 
2770                                                 if (Elements.Contains (v))
2771                                                         lname = v.ToString ();
2772                                                 else
2773                                                         Elements.Add (v, sl);
2774                                         } else if (compare_type == TypeManager.string_type){
2775                                                 if (key is NullLiteral){
2776                                                         if (Elements.Contains (NullLiteral.Null))
2777                                                                 lname = "null";
2778                                                         else
2779                                                                 Elements.Add (NullLiteral.Null, null);
2780                                                 } else {
2781                                                         string s = (string) key;
2782
2783                                                         if (Elements.Contains (s))
2784                                                                 lname = s;
2785                                                         else
2786                                                                 Elements.Add (s, sl);
2787                                                 }
2788                                         } else if (compare_type == TypeManager.int32_type) {
2789                                                 int v = (int) key;
2790
2791                                                 if (Elements.Contains (v))
2792                                                         lname = v.ToString ();
2793                                                 else
2794                                                         Elements.Add (v, sl);
2795                                         } else if (compare_type == TypeManager.bool_type) {
2796                                                 bool v = (bool) key;
2797
2798                                                 if (Elements.Contains (v))
2799                                                         lname = v.ToString ();
2800                                                 else
2801                                                         Elements.Add (v, sl);
2802                                         }
2803                                         else
2804                                         {
2805                                                 throw new Exception ("Unknown switch type!" +
2806                                                                      SwitchType + " " + compare_type);
2807                                         }
2808
2809                                         if (lname != null){
2810                                                 error152 ("case + " + lname);
2811                                                 error = true;
2812                                         }
2813                                 }
2814                         }
2815                         if (error)
2816                                 return false;
2817                         
2818                         return true;
2819                 }
2820
2821                 void EmitObjectInteger (ILGenerator ig, object k)
2822                 {
2823                         if (k is int)
2824                                 IntConstant.EmitInt (ig, (int) k);
2825                         else if (k is Constant) {
2826                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2827                         } 
2828                         else if (k is uint)
2829                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2830                         else if (k is long)
2831                         {
2832                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2833                                 {
2834                                         IntConstant.EmitInt (ig, (int) (long) k);
2835                                         ig.Emit (OpCodes.Conv_I8);
2836                                 }
2837                                 else
2838                                         LongConstant.EmitLong (ig, (long) k);
2839                         }
2840                         else if (k is ulong)
2841                         {
2842                                 if ((ulong) k < (1L<<32))
2843                                 {
2844                                         IntConstant.EmitInt (ig, (int) (long) k);
2845                                         ig.Emit (OpCodes.Conv_U8);
2846                                 }
2847                                 else
2848                                 {
2849                                         LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2850                                 }
2851                         }
2852                         else if (k is char)
2853                                 IntConstant.EmitInt (ig, (int) ((char) k));
2854                         else if (k is sbyte)
2855                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2856                         else if (k is byte)
2857                                 IntConstant.EmitInt (ig, (int) ((byte) k));
2858                         else if (k is short)
2859                                 IntConstant.EmitInt (ig, (int) ((short) k));
2860                         else if (k is ushort)
2861                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
2862                         else if (k is bool)
2863                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2864                         else
2865                                 throw new Exception ("Unhandled case");
2866                 }
2867                 
2868                 // structure used to hold blocks of keys while calculating table switch
2869                 class KeyBlock : IComparable
2870                 {
2871                         public KeyBlock (long _nFirst)
2872                         {
2873                                 nFirst = nLast = _nFirst;
2874                         }
2875                         public long nFirst;
2876                         public long nLast;
2877                         public ArrayList rgKeys = null;
2878                         public int Length
2879                         {
2880                                 get { return (int) (nLast - nFirst + 1); }
2881                         }
2882                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2883                         {
2884                                 return kbLast.nLast - kbFirst.nFirst + 1;
2885                         }
2886                         public int CompareTo (object obj)
2887                         {
2888                                 KeyBlock kb = (KeyBlock) obj;
2889                                 int nLength = Length;
2890                                 int nLengthOther = kb.Length;
2891                                 if (nLengthOther == nLength)
2892                                         return (int) (kb.nFirst - nFirst);
2893                                 return nLength - nLengthOther;
2894                         }
2895                 }
2896
2897                 /// <summary>
2898                 /// This method emits code for a lookup-based switch statement (non-string)
2899                 /// Basically it groups the cases into blocks that are at least half full,
2900                 /// and then spits out individual lookup opcodes for each block.
2901                 /// It emits the longest blocks first, and short blocks are just
2902                 /// handled with direct compares.
2903                 /// </summary>
2904                 /// <param name="ec"></param>
2905                 /// <param name="val"></param>
2906                 /// <returns></returns>
2907                 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
2908                 {
2909                         int cElements = Elements.Count;
2910                         object [] rgKeys = new object [cElements];
2911                         Elements.Keys.CopyTo (rgKeys, 0);
2912                         Array.Sort (rgKeys);
2913
2914                         // initialize the block list with one element per key
2915                         ArrayList rgKeyBlocks = new ArrayList ();
2916                         foreach (object key in rgKeys)
2917                                 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
2918
2919                         KeyBlock kbCurr;
2920                         // iteratively merge the blocks while they are at least half full
2921                         // there's probably a really cool way to do this with a tree...
2922                         while (rgKeyBlocks.Count > 1)
2923                         {
2924                                 ArrayList rgKeyBlocksNew = new ArrayList ();
2925                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2926                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2927                                 {
2928                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2929                                         if ((kbCurr.Length + kb.Length) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
2930                                         {
2931                                                 // merge blocks
2932                                                 kbCurr.nLast = kb.nLast;
2933                                         }
2934                                         else
2935                                         {
2936                                                 // start a new block
2937                                                 rgKeyBlocksNew.Add (kbCurr);
2938                                                 kbCurr = kb;
2939                                         }
2940                                 }
2941                                 rgKeyBlocksNew.Add (kbCurr);
2942                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2943                                         break;
2944                                 rgKeyBlocks = rgKeyBlocksNew;
2945                         }
2946
2947                         // initialize the key lists
2948                         foreach (KeyBlock kb in rgKeyBlocks)
2949                                 kb.rgKeys = new ArrayList ();
2950
2951                         // fill the key lists
2952                         int iBlockCurr = 0;
2953                         if (rgKeyBlocks.Count > 0) {
2954                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2955                                 foreach (object key in rgKeys)
2956                                 {
2957                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
2958                                         if (fNextBlock)
2959                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2960                                         kbCurr.rgKeys.Add (key);
2961                                 }
2962                         }
2963
2964                         // sort the blocks so we can tackle the largest ones first
2965                         rgKeyBlocks.Sort ();
2966
2967                         // okay now we can start...
2968                         ILGenerator ig = ec.ig;
2969                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
2970                         Label lblDefault = ig.DefineLabel ();
2971
2972                         Type typeKeys = null;
2973                         if (rgKeys.Length > 0)
2974                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
2975
2976                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2977                         {
2978                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2979                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2980                                 if (kb.Length <= 2)
2981                                 {
2982                                         foreach (object key in kb.rgKeys)
2983                                         {
2984                                                 ig.Emit (OpCodes.Ldloc, val);
2985                                                 EmitObjectInteger (ig, key);
2986                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
2987                                                 ig.Emit (OpCodes.Beq, sl.ILLabel);
2988                                         }
2989                                 }
2990                                 else
2991                                 {
2992                                         // TODO: if all the keys in the block are the same and there are
2993                                         //       no gaps/defaults then just use a range-check.
2994                                         if (SwitchType == TypeManager.int64_type ||
2995                                                 SwitchType == TypeManager.uint64_type)
2996                                         {
2997                                                 // TODO: optimize constant/I4 cases
2998
2999                                                 // check block range (could be > 2^31)
3000                                                 ig.Emit (OpCodes.Ldloc, val);
3001                                                 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3002                                                 ig.Emit (OpCodes.Blt, lblDefault);
3003                                                 ig.Emit (OpCodes.Ldloc, val);
3004                                                 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3005                                                 ig.Emit (OpCodes.Bgt, lblDefault);
3006
3007                                                 // normalize range
3008                                                 ig.Emit (OpCodes.Ldloc, val);
3009                                                 if (kb.nFirst != 0)
3010                                                 {
3011                                                         EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3012                                                         ig.Emit (OpCodes.Sub);
3013                                                 }
3014                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
3015                                         }
3016                                         else
3017                                         {
3018                                                 // normalize range
3019                                                 ig.Emit (OpCodes.Ldloc, val);
3020                                                 int nFirst = (int) kb.nFirst;
3021                                                 if (nFirst > 0)
3022                                                 {
3023                                                         IntConstant.EmitInt (ig, nFirst);
3024                                                         ig.Emit (OpCodes.Sub);
3025                                                 }
3026                                                 else if (nFirst < 0)
3027                                                 {
3028                                                         IntConstant.EmitInt (ig, -nFirst);
3029                                                         ig.Emit (OpCodes.Add);
3030                                                 }
3031                                         }
3032
3033                                         // first, build the list of labels for the switch
3034                                         int iKey = 0;
3035                                         int cJumps = kb.Length;
3036                                         Label [] rgLabels = new Label [cJumps];
3037                                         for (int iJump = 0; iJump < cJumps; iJump++)
3038                                         {
3039                                                 object key = kb.rgKeys [iKey];
3040                                                 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3041                                                 {
3042                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
3043                                                         rgLabels [iJump] = sl.ILLabel;
3044                                                         iKey++;
3045                                                 }
3046                                                 else
3047                                                         rgLabels [iJump] = lblDefault;
3048                                         }
3049                                         // emit the switch opcode
3050                                         ig.Emit (OpCodes.Switch, rgLabels);
3051                                 }
3052
3053                                 // mark the default for this block
3054                                 if (iBlock != 0)
3055                                         ig.MarkLabel (lblDefault);
3056                         }
3057
3058                         // TODO: find the default case and emit it here,
3059                         //       to prevent having to do the following jump.
3060                         //       make sure to mark other labels in the default section
3061
3062                         // the last default just goes to the end
3063                         ig.Emit (OpCodes.Br, lblDefault);
3064
3065                         // now emit the code for the sections
3066                         bool fFoundDefault = false;
3067                         bool fAllReturn = true;
3068                         foreach (SwitchSection ss in Sections)
3069                         {
3070                                 foreach (SwitchLabel sl in ss.Labels)
3071                                 {
3072                                         ig.MarkLabel (sl.ILLabel);
3073                                         ig.MarkLabel (sl.ILLabelCode);
3074                                         if (sl.Label == null)
3075                                         {
3076                                                 ig.MarkLabel (lblDefault);
3077                                                 fFoundDefault = true;
3078                                         }
3079                                 }
3080                                 fAllReturn &= ss.Block.Emit (ec);
3081                                 //ig.Emit (OpCodes.Br, lblEnd);
3082                         }
3083                         
3084                         if (!fFoundDefault) {
3085                                 ig.MarkLabel (lblDefault);
3086                                 fAllReturn = false;
3087                         }
3088                         ig.MarkLabel (lblEnd);
3089
3090                         return fAllReturn;
3091                 }
3092                 //
3093                 // This simple emit switch works, but does not take advantage of the
3094                 // `switch' opcode. 
3095                 // TODO: remove non-string logic from here
3096                 // TODO: binary search strings?
3097                 //
3098                 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3099                 {
3100                         ILGenerator ig = ec.ig;
3101                         Label end_of_switch = ig.DefineLabel ();
3102                         Label next_test = ig.DefineLabel ();
3103                         Label null_target = ig.DefineLabel ();
3104                         bool default_found = false;
3105                         bool first_test = true;
3106                         bool pending_goto_end = false;
3107                         bool all_return = true;
3108                         bool is_string = false;
3109                         bool null_found;
3110                         
3111                         //
3112                         // Special processing for strings: we cant compare
3113                         // against null.
3114                         //
3115                         if (SwitchType == TypeManager.string_type){
3116                                 ig.Emit (OpCodes.Ldloc, val);
3117                                 is_string = true;
3118                                 
3119                                 if (Elements.Contains (NullLiteral.Null)){
3120                                         ig.Emit (OpCodes.Brfalse, null_target);
3121                                 } else
3122                                         ig.Emit (OpCodes.Brfalse, default_target);
3123
3124                                 ig.Emit (OpCodes.Ldloc, val);
3125                                 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3126                                 ig.Emit (OpCodes.Stloc, val);
3127                         }
3128
3129                         SwitchSection last_section;
3130                         last_section = (SwitchSection) Sections [Sections.Count-1];
3131                         
3132                         foreach (SwitchSection ss in Sections){
3133                                 Label sec_begin = ig.DefineLabel ();
3134
3135                                 if (pending_goto_end)
3136                                         ig.Emit (OpCodes.Br, end_of_switch);
3137
3138                                 int label_count = ss.Labels.Count;
3139                                 null_found = false;
3140                                 foreach (SwitchLabel sl in ss.Labels){
3141                                         ig.MarkLabel (sl.ILLabel);
3142                                         
3143                                         if (!first_test){
3144                                                 ig.MarkLabel (next_test);
3145                                                 next_test = ig.DefineLabel ();
3146                                         }
3147                                         //
3148                                         // If we are the default target
3149                                         //
3150                                         if (sl.Label == null){
3151                                                 ig.MarkLabel (default_target);
3152                                                 default_found = true;
3153                                         } else {
3154                                                 object lit = sl.Converted;
3155
3156                                                 if (lit is NullLiteral){
3157                                                         null_found = true;
3158                                                         if (label_count == 1)
3159                                                                 ig.Emit (OpCodes.Br, next_test);
3160                                                         continue;
3161                                                                               
3162                                                 }
3163                                                 if (is_string){
3164                                                         StringConstant str = (StringConstant) lit;
3165
3166                                                         ig.Emit (OpCodes.Ldloc, val);
3167                                                         ig.Emit (OpCodes.Ldstr, str.Value);
3168                                                         if (label_count == 1)
3169                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
3170                                                         else
3171                                                                 ig.Emit (OpCodes.Beq, sec_begin);
3172                                                 } else {
3173                                                         ig.Emit (OpCodes.Ldloc, val);
3174                                                         EmitObjectInteger (ig, lit);
3175                                                         ig.Emit (OpCodes.Ceq);
3176                                                         if (label_count == 1)
3177                                                                 ig.Emit (OpCodes.Brfalse, next_test);
3178                                                         else
3179                                                                 ig.Emit (OpCodes.Brtrue, sec_begin);
3180                                                 }
3181                                         }
3182                                 }
3183                                 if (label_count != 1 && ss != last_section)
3184                                         ig.Emit (OpCodes.Br, next_test);
3185                                 
3186                                 if (null_found)
3187                                         ig.MarkLabel (null_target);
3188                                 ig.MarkLabel (sec_begin);
3189                                 foreach (SwitchLabel sl in ss.Labels)\r
3190                                         ig.MarkLabel (sl.ILLabelCode);
3191                                 if (ss.Block.Emit (ec))
3192                                         pending_goto_end = false;
3193                                 else {
3194                                         all_return = false;
3195                                         pending_goto_end = true;
3196                                 }
3197                                 first_test = false;
3198                         }
3199                         if (!default_found){
3200                                 ig.MarkLabel (default_target);
3201                                 all_return = false;
3202                         }
3203                         ig.MarkLabel (next_test);
3204                         ig.MarkLabel (end_of_switch);
3205                         
3206                         return all_return;
3207                 }
3208
3209                 public override bool Resolve (EmitContext ec)
3210                 {
3211                         Expr = Expr.Resolve (ec);
3212                         if (Expr == null)
3213                                 return false;
3214
3215                         new_expr = SwitchGoverningType (ec, Expr.Type);
3216                         if (new_expr == null){
3217                                 Report.Error (151, loc, "An integer type or string was expected for switch");
3218                                 return false;
3219                         }
3220
3221                         // Validate switch.
3222                         SwitchType = new_expr.Type;
3223
3224                         if (!CheckSwitch (ec))
3225                                 return false;
3226
3227                         Switch old_switch = ec.Switch;
3228                         ec.Switch = this;
3229                         ec.Switch.SwitchType = SwitchType;
3230
3231                         ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3232
3233                         bool first = true;
3234                         foreach (SwitchSection ss in Sections){
3235                                 if (!first)
3236                                         ec.CurrentBranching.CreateSibling ();
3237                                 else
3238                                         first = false;
3239
3240                                 if (ss.Block.Resolve (ec) != true)
3241                                         return false;
3242                         }
3243
3244                         ec.EndFlowBranching ();
3245                         ec.Switch = old_switch;
3246
3247                         return true;
3248                 }
3249                 
3250                 public override bool Emit (EmitContext ec)
3251                 {
3252                         // Store variable for comparission purposes
3253                         LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
3254                         new_expr.Emit (ec);
3255                         ec.ig.Emit (OpCodes.Stloc, value);
3256
3257                         ILGenerator ig = ec.ig;
3258
3259                         default_target = ig.DefineLabel ();
3260
3261                         //
3262                         // Setup the codegen context
3263                         //
3264                         Label old_end = ec.LoopEnd;
3265                         Switch old_switch = ec.Switch;
3266                         
3267                         ec.LoopEnd = ig.DefineLabel ();
3268                         ec.Switch = this;
3269
3270                         // Emit Code.
3271                         bool all_return;
3272                         if (SwitchType == TypeManager.string_type)
3273                                 all_return = SimpleSwitchEmit (ec, value);
3274                         else
3275                                 all_return = TableSwitchEmit (ec, value);
3276
3277                         // Restore context state. 
3278                         ig.MarkLabel (ec.LoopEnd);
3279
3280                         //
3281                         // Restore the previous context
3282                         //
3283                         ec.LoopEnd = old_end;
3284                         ec.Switch = old_switch;
3285                         
3286                         return all_return;
3287                 }
3288         }
3289
3290         public class Lock : Statement {
3291                 Expression expr;
3292                 Statement Statement;
3293                         
3294                 public Lock (Expression expr, Statement stmt, Location l)
3295                 {
3296                         this.expr = expr;
3297                         Statement = stmt;
3298                         loc = l;
3299                 }
3300
3301                 public override bool Resolve (EmitContext ec)
3302                 {
3303                         expr = expr.Resolve (ec);
3304                         return Statement.Resolve (ec) && expr != null;
3305                 }
3306                 
3307                 public override bool Emit (EmitContext ec)
3308                 {
3309                         Type type = expr.Type;
3310                         bool val;
3311                         
3312                         if (type.IsValueType){
3313                                 Report.Error (185, loc, "lock statement requires the expression to be " +
3314                                               " a reference type (type is: `" +
3315                                               TypeManager.CSharpName (type) + "'");
3316                                 return false;
3317                         }
3318
3319                         ILGenerator ig = ec.ig;
3320                         LocalBuilder temp = ig.DeclareLocal (type);
3321                                 
3322                         expr.Emit (ec);
3323                         ig.Emit (OpCodes.Dup);
3324                         ig.Emit (OpCodes.Stloc, temp);
3325                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3326
3327                         // try
3328                         Label end = ig.BeginExceptionBlock ();
3329                         bool old_in_try = ec.InTry;
3330                         ec.InTry = true;
3331                         Label finish = ig.DefineLabel ();
3332                         val = Statement.Emit (ec);
3333                         ec.InTry = old_in_try;
3334                         // ig.Emit (OpCodes.Leave, finish);
3335
3336                         ig.MarkLabel (finish);
3337                         
3338                         // finally
3339                         ig.BeginFinallyBlock ();
3340                         ig.Emit (OpCodes.Ldloc, temp);
3341                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3342                         ig.EndExceptionBlock ();
3343                         
3344                         return val;
3345                 }
3346         }
3347
3348         public class Unchecked : Statement {
3349                 public readonly Block Block;
3350                 
3351                 public Unchecked (Block b)
3352                 {
3353                         Block = b;
3354                 }
3355
3356                 public override bool Resolve (EmitContext ec)
3357                 {
3358                         return Block.Resolve (ec);
3359                 }
3360                 
3361                 public override bool Emit (EmitContext ec)
3362                 {
3363                         bool previous_state = ec.CheckState;
3364                         bool previous_state_const = ec.ConstantCheckState;
3365                         bool val;
3366                         
3367                         ec.CheckState = false;
3368                         ec.ConstantCheckState = false;
3369                         val = Block.Emit (ec);
3370                         ec.CheckState = previous_state;
3371                         ec.ConstantCheckState = previous_state_const;
3372
3373                         return val;
3374                 }
3375         }
3376
3377         public class Checked : Statement {
3378                 public readonly Block Block;
3379                 
3380                 public Checked (Block b)
3381                 {
3382                         Block = b;
3383                 }
3384
3385                 public override bool Resolve (EmitContext ec)
3386                 {
3387                         bool previous_state = ec.CheckState;
3388                         bool previous_state_const = ec.ConstantCheckState;
3389                         
3390                         ec.CheckState = true;
3391                         ec.ConstantCheckState = true;
3392                         bool ret = Block.Resolve (ec);
3393                         ec.CheckState = previous_state;
3394                         ec.ConstantCheckState = previous_state_const;
3395
3396                         return ret;
3397                 }
3398
3399                 public override bool Emit (EmitContext ec)
3400                 {
3401                         bool previous_state = ec.CheckState;
3402                         bool previous_state_const = ec.ConstantCheckState;
3403                         bool val;
3404                         
3405                         ec.CheckState = true;
3406                         ec.ConstantCheckState = true;
3407                         val = Block.Emit (ec);
3408                         ec.CheckState = previous_state;
3409                         ec.ConstantCheckState = previous_state_const;
3410
3411                         return val;
3412                 }
3413         }
3414
3415         public class Unsafe : Statement {
3416                 public readonly Block Block;
3417
3418                 public Unsafe (Block b)
3419                 {
3420                         Block = b;
3421                 }
3422
3423                 public override bool Resolve (EmitContext ec)
3424                 {
3425                         bool previous_state = ec.InUnsafe;
3426                         bool val;
3427                         
3428                         ec.InUnsafe = true;
3429                         val = Block.Resolve (ec);
3430                         ec.InUnsafe = previous_state;
3431
3432                         return val;
3433                 }
3434                 
3435                 public override bool Emit (EmitContext ec)
3436                 {
3437                         bool previous_state = ec.InUnsafe;
3438                         bool val;
3439                         
3440                         ec.InUnsafe = true;
3441                         val = Block.Emit (ec);
3442                         ec.InUnsafe = previous_state;
3443
3444                         return val;
3445                 }
3446         }
3447
3448         // 
3449         // Fixed statement
3450         //
3451         public class Fixed : Statement {
3452                 Expression type;
3453                 ArrayList declarators;
3454                 Statement statement;
3455                 Type expr_type;
3456                 FixedData[] data;
3457
3458                 struct FixedData {
3459                         public bool is_object;
3460                         public VariableInfo vi;
3461                         public Expression expr;
3462                         public Expression converted;
3463                 }                       
3464
3465                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3466                 {
3467                         this.type = type;
3468                         declarators = decls;
3469                         statement = stmt;
3470                         loc = l;
3471                 }
3472
3473                 public override bool Resolve (EmitContext ec)
3474                 {
3475                         expr_type = ec.DeclSpace.ResolveType (type, false, loc);
3476                         if (expr_type == null)
3477                                 return false;
3478
3479                         data = new FixedData [declarators.Count];
3480
3481                         int i = 0;
3482                         foreach (Pair p in declarators){
3483                                 VariableInfo vi = (VariableInfo) p.First;
3484                                 Expression e = (Expression) p.Second;
3485
3486                                 vi.Number = -1;
3487
3488                                 //
3489                                 // The rules for the possible declarators are pretty wise,
3490                                 // but the production on the grammar is more concise.
3491                                 //
3492                                 // So we have to enforce these rules here.
3493                                 //
3494                                 // We do not resolve before doing the case 1 test,
3495                                 // because the grammar is explicit in that the token &
3496                                 // is present, so we need to test for this particular case.
3497                                 //
3498
3499                                 //
3500                                 // Case 1: & object.
3501                                 //
3502                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3503                                         Expression child = ((Unary) e).Expr;
3504
3505                                         vi.MakePinned ();
3506                                         if (child is ParameterReference || child is LocalVariableReference){
3507                                                 Report.Error (
3508                                                         213, loc, 
3509                                                         "No need to use fixed statement for parameters or " +
3510                                                         "local variable declarations (address is already " +
3511                                                         "fixed)");
3512                                                 return false;
3513                                         }
3514                                         
3515                                         e = e.Resolve (ec);
3516                                         if (e == null)
3517                                                 return false;
3518
3519                                         child = ((Unary) e).Expr;
3520                                         
3521                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
3522                                                 return false;
3523
3524                                         data [i].is_object = true;
3525                                         data [i].expr = e;
3526                                         data [i].converted = null;
3527                                         data [i].vi = vi;
3528                                         i++;
3529
3530                                         continue;
3531                                 }
3532
3533                                 e = e.Resolve (ec);
3534                                 if (e == null)
3535                                         return false;
3536
3537                                 //
3538                                 // Case 2: Array
3539                                 //
3540                                 if (e.Type.IsArray){
3541                                         Type array_type = e.Type.GetElementType ();
3542                                         
3543                                         vi.MakePinned ();
3544                                         //
3545                                         // Provided that array_type is unmanaged,
3546                                         //
3547                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
3548                                                 return false;
3549
3550                                         //
3551                                         // and T* is implicitly convertible to the
3552                                         // pointer type given in the fixed statement.
3553                                         //
3554                                         ArrayPtr array_ptr = new ArrayPtr (e);
3555                                         
3556                                         Expression converted = Expression.ConvertImplicitRequired (
3557                                                 ec, array_ptr, vi.VariableType, loc);
3558                                         if (converted == null)
3559                                                 return false;
3560
3561                                         data [i].is_object = false;
3562                                         data [i].expr = e;
3563                                         data [i].converted = converted;
3564                                         data [i].vi = vi;
3565                                         i++;
3566
3567                                         continue;
3568                                 }
3569
3570                                 //
3571                                 // Case 3: string
3572                                 //
3573                                 if (e.Type == TypeManager.string_type){
3574                                         data [i].is_object = false;
3575                                         data [i].expr = e;
3576                                         data [i].converted = null;
3577                                         data [i].vi = vi;
3578                                         i++;
3579                                 }
3580                         }
3581
3582                         return statement.Resolve (ec);
3583                 }
3584                 
3585                 public override bool Emit (EmitContext ec)
3586                 {
3587                         ILGenerator ig = ec.ig;
3588
3589                         bool is_ret = false;
3590
3591                         for (int i = 0; i < data.Length; i++) {
3592                                 VariableInfo vi = data [i].vi;
3593
3594                                 //
3595                                 // Case 1: & object.
3596                                 //
3597                                 if (data [i].is_object) {
3598                                         //
3599                                         // Store pointer in pinned location
3600                                         //
3601                                         data [i].expr.Emit (ec);
3602                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3603
3604                                         is_ret = statement.Emit (ec);
3605
3606                                         // Clear the pinned variable.
3607                                         ig.Emit (OpCodes.Ldc_I4_0);
3608                                         ig.Emit (OpCodes.Conv_U);
3609                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3610
3611                                         continue;
3612                                 }
3613
3614                                 //
3615                                 // Case 2: Array
3616                                 //
3617                                 if (data [i].expr.Type.IsArray){
3618                                         //
3619                                         // Store pointer in pinned location
3620                                         //
3621                                         data [i].converted.Emit (ec);
3622                                         
3623                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3624
3625                                         is_ret = statement.Emit (ec);
3626                                         
3627                                         // Clear the pinned variable.
3628                                         ig.Emit (OpCodes.Ldc_I4_0);
3629                                         ig.Emit (OpCodes.Conv_U);
3630                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3631
3632                                         continue;
3633                                 }
3634
3635                                 //
3636                                 // Case 3: string
3637                                 //
3638                                 if (data [i].expr.Type == TypeManager.string_type){
3639                                         LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3640                                         TypeManager.MakePinned (pinned_string);
3641                                         
3642                                         data [i].expr.Emit (ec);
3643                                         ig.Emit (OpCodes.Stloc, pinned_string);
3644
3645                                         Expression sptr = new StringPtr (pinned_string);
3646                                         Expression converted = Expression.ConvertImplicitRequired (
3647                                                 ec, sptr, vi.VariableType, loc);
3648                                         
3649                                         if (converted == null)
3650                                                 continue;
3651
3652                                         converted.Emit (ec);
3653                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3654                                         
3655                                         is_ret = statement.Emit (ec);
3656
3657                                         // Clear the pinned variable
3658                                         ig.Emit (OpCodes.Ldnull);
3659                                         ig.Emit (OpCodes.Stloc, pinned_string);
3660                                 }
3661                         }
3662
3663                         return is_ret;
3664                 }
3665         }
3666         
3667         public class Catch {
3668                 public readonly string Name;
3669                 public readonly Block  Block;
3670                 public readonly Location Location;
3671
3672                 Expression type;
3673                 
3674                 public Catch (Expression type, string name, Block block, Location l)
3675                 {
3676                         this.type = type;
3677                         Name = name;
3678                         Block = block;
3679                         Location = l;
3680                 }
3681
3682                 public Type CatchType {
3683                         get {
3684                                 if (type == null)
3685                                         throw new InvalidOperationException ();
3686
3687                                 return type.Type;
3688                         }
3689                 }
3690
3691                 public bool IsGeneral {
3692                         get {
3693                                 return type == null;
3694                         }
3695                 }
3696
3697                 public bool Resolve (EmitContext ec)
3698                 {
3699                         if (type != null) {
3700                                 type = type.DoResolve (ec);
3701                                 if (type == null)
3702                                         return false;
3703
3704                                 Type t = type.Type;
3705                                 if (t != TypeManager.exception_type && !t.IsSubclassOf (TypeManager.exception_type)){
3706                                         Report.Error (155, Location,
3707                                                       "The type caught or thrown must be derived " +
3708                                                       "from System.Exception");
3709                                         return false;
3710                                 }
3711                         }
3712
3713                         if (!Block.Resolve (ec))
3714                                 return false;
3715
3716                         return true;
3717                 }
3718         }
3719
3720         public class Try : Statement {
3721                 public readonly Block Fini, Block;
3722                 public readonly ArrayList Specific;
3723                 public readonly Catch General;
3724                 
3725                 //
3726                 // specific, general and fini might all be null.
3727                 //
3728                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3729                 {
3730                         if (specific == null && general == null){
3731                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3732                         }
3733                         
3734                         this.Block = block;
3735                         this.Specific = specific;
3736                         this.General = general;
3737                         this.Fini = fini;
3738                         loc = l;
3739                 }
3740
3741                 public override bool Resolve (EmitContext ec)
3742                 {
3743                         bool ok = true;
3744                         
3745                         ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
3746
3747                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3748
3749                         if (!Block.Resolve (ec))
3750                                 ok = false;
3751
3752                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3753
3754                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
3755
3756                         foreach (Catch c in Specific){
3757                                 ec.CurrentBranching.CreateSibling ();
3758                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3759
3760                                 if (c.Name != null) {
3761                                         VariableInfo vi = c.Block.GetVariableInfo (c.Name);
3762                                         if (vi == null)
3763                                                 throw new Exception ();
3764
3765                                         vi.Number = -1;
3766                                 }
3767
3768                                 if (!c.Resolve (ec))
3769                                         ok = false;
3770
3771                                 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
3772
3773                                 if ((current.Returns == FlowReturns.NEVER) ||
3774                                     (current.Returns == FlowReturns.SOMETIMES)) {
3775                                         vector.AndLocals (current);
3776                                 }
3777                         }
3778
3779                         if (General != null){
3780                                 ec.CurrentBranching.CreateSibling ();
3781                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3782
3783                                 if (!General.Resolve (ec))
3784                                         ok = false;
3785
3786                                 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
3787
3788                                 if ((current.Returns == FlowReturns.NEVER) ||
3789                                     (current.Returns == FlowReturns.SOMETIMES)) {
3790                                         vector.AndLocals (current);
3791                                 }
3792                         }
3793
3794                         ec.CurrentBranching.CreateSiblingForFinally ();
3795                         Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3796
3797                         if (Fini != null)
3798                                 if (!Fini.Resolve (ec))
3799                                         ok = false;
3800
3801                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3802
3803                         FlowReturns returns = ec.EndFlowBranching ();
3804
3805                         Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
3806
3807                         if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
3808                                 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
3809                         }
3810
3811                         ec.CurrentBranching.CurrentUsageVector.Or (vector);
3812
3813                         Report.Debug (1, "END OF TRY", ec.CurrentBranching);
3814
3815                         return ok;
3816                 }
3817                 
3818                 public override bool Emit (EmitContext ec)
3819                 {
3820                         ILGenerator ig = ec.ig;
3821                         Label end;
3822                         Label finish = ig.DefineLabel ();;
3823                         bool returns;
3824
3825                         ec.TryCatchLevel++;
3826                         end = ig.BeginExceptionBlock ();
3827                         bool old_in_try = ec.InTry;
3828                         ec.InTry = true;
3829                         returns = Block.Emit (ec);
3830                         ec.InTry = old_in_try;
3831
3832                         //
3833                         // System.Reflection.Emit provides this automatically:
3834                         // ig.Emit (OpCodes.Leave, finish);
3835
3836                         bool old_in_catch = ec.InCatch;
3837                         ec.InCatch = true;
3838                         DeclSpace ds = ec.DeclSpace;
3839
3840                         foreach (Catch c in Specific){
3841                                 VariableInfo vi;
3842                                 
3843                                 ig.BeginCatchBlock (c.CatchType);
3844
3845                                 if (c.Name != null){
3846                                         vi = c.Block.GetVariableInfo (c.Name);
3847                                         if (vi == null)
3848                                                 throw new Exception ("Variable does not exist in this block");
3849
3850                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3851                                 } else
3852                                         ig.Emit (OpCodes.Pop);
3853                                 
3854                                 if (!c.Block.Emit (ec))
3855                                         returns = false;
3856                         }
3857
3858                         if (General != null){
3859                                 ig.BeginCatchBlock (TypeManager.object_type);
3860                                 ig.Emit (OpCodes.Pop);
3861                                 if (!General.Block.Emit (ec))
3862                                         returns = false;
3863                         }
3864                         ec.InCatch = old_in_catch;
3865
3866                         ig.MarkLabel (finish);
3867                         if (Fini != null){
3868                                 ig.BeginFinallyBlock ();
3869                                 bool old_in_finally = ec.InFinally;
3870                                 ec.InFinally = true;
3871                                 Fini.Emit (ec);
3872                                 ec.InFinally = old_in_finally;
3873                         }
3874                         
3875                         ig.EndExceptionBlock ();
3876                         ec.TryCatchLevel--;
3877
3878                         if (!returns || ec.InTry || ec.InCatch)
3879                                 return returns;
3880
3881                         // Unfortunately, System.Reflection.Emit automatically emits a leave
3882                         // to the end of the finally block.  This is a problem if `returns'
3883                         // is true since we may jump to a point after the end of the method.
3884                         // As a workaround, emit an explicit ret here.
3885
3886                         if (ec.ReturnType != null)
3887                                 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
3888                         ec.ig.Emit (OpCodes.Ret);
3889
3890                         return true;
3891                 }
3892         }
3893
3894         //
3895         // FIXME: We still do not support the expression variant of the using
3896         // statement.
3897         //
3898         public class Using : Statement {
3899                 object expression_or_block;
3900                 Statement Statement;
3901                 ArrayList var_list;
3902                 Expression expr;
3903                 Type expr_type;
3904                 Expression conv;
3905                 Expression [] converted_vars;
3906                 ExpressionStatement [] assign;
3907                 
3908                 public Using (object expression_or_block, Statement stmt, Location l)
3909                 {
3910                         this.expression_or_block = expression_or_block;
3911                         Statement = stmt;
3912                         loc = l;
3913                 }
3914
3915                 //
3916                 // Resolves for the case of using using a local variable declaration.
3917                 //
3918                 bool ResolveLocalVariableDecls (EmitContext ec)
3919                 {
3920                         bool need_conv = false;
3921                         expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3922                         int i = 0;
3923
3924                         if (expr_type == null)
3925                                 return false;
3926
3927                         //
3928                         // The type must be an IDisposable or an implicit conversion
3929                         // must exist.
3930                         //
3931                         converted_vars = new Expression [var_list.Count];
3932                         assign = new ExpressionStatement [var_list.Count];
3933                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3934                                 foreach (DictionaryEntry e in var_list){
3935                                         Expression var = (Expression) e.Key;
3936
3937                                         var = var.ResolveLValue (ec, new EmptyExpression ());
3938                                         if (var == null)
3939                                                 return false;
3940                                         
3941                                         converted_vars [i] = Expression.ConvertImplicit (
3942                                                 ec, var, TypeManager.idisposable_type, loc);
3943
3944                                         if (converted_vars [i] == null)
3945                                                 return false;
3946                                         i++;
3947                                 }
3948                                 need_conv = true;
3949                         }
3950
3951                         i = 0;
3952                         foreach (DictionaryEntry e in var_list){
3953                                 LocalVariableReference var = (LocalVariableReference) e.Key;
3954                                 Expression new_expr = (Expression) e.Value;
3955                                 Expression a;
3956
3957                                 a = new Assign (var, new_expr, loc);
3958                                 a = a.Resolve (ec);
3959                                 if (a == null)
3960                                         return false;
3961
3962                                 if (!need_conv)
3963                                         converted_vars [i] = var;
3964                                 assign [i] = (ExpressionStatement) a;
3965                                 i++;
3966                         }
3967
3968                         return true;
3969                 }
3970
3971                 bool ResolveExpression (EmitContext ec)
3972                 {
3973                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3974                                 conv = Expression.ConvertImplicit (
3975                                         ec, expr, TypeManager.idisposable_type, loc);
3976
3977                                 if (conv == null)
3978                                         return false;
3979                         }
3980
3981                         return true;
3982                 }
3983                 
3984                 //
3985                 // Emits the code for the case of using using a local variable declaration.
3986                 //
3987                 bool EmitLocalVariableDecls (EmitContext ec)
3988                 {
3989                         ILGenerator ig = ec.ig;
3990                         int i = 0;
3991
3992                         bool old_in_try = ec.InTry;
3993                         ec.InTry = true;
3994                         for (i = 0; i < assign.Length; i++) {
3995                                 assign [i].EmitStatement (ec);
3996                                 
3997                                 ig.BeginExceptionBlock ();
3998                         }
3999                         Statement.Emit (ec);
4000                         ec.InTry = old_in_try;
4001
4002                         bool old_in_finally = ec.InFinally;
4003                         ec.InFinally = true;
4004                         var_list.Reverse ();
4005                         foreach (DictionaryEntry e in var_list){
4006                                 LocalVariableReference var = (LocalVariableReference) e.Key;
4007                                 Label skip = ig.DefineLabel ();
4008                                 i--;
4009                                 
4010                                 ig.BeginFinallyBlock ();
4011                                 
4012                                 var.Emit (ec);
4013                                 ig.Emit (OpCodes.Brfalse, skip);
4014                                 converted_vars [i].Emit (ec);
4015                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4016                                 ig.MarkLabel (skip);
4017                                 ig.EndExceptionBlock ();
4018                         }
4019                         ec.InFinally = old_in_finally;
4020
4021                         return false;
4022                 }
4023
4024                 bool EmitExpression (EmitContext ec)
4025                 {
4026                         //
4027                         // Make a copy of the expression and operate on that.
4028                         //
4029                         ILGenerator ig = ec.ig;
4030                         LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4031                         if (conv != null)
4032                                 conv.Emit (ec);
4033                         else
4034                                 expr.Emit (ec);
4035                         ig.Emit (OpCodes.Stloc, local_copy);
4036
4037                         bool old_in_try = ec.InTry;
4038                         ec.InTry = true;
4039                         ig.BeginExceptionBlock ();
4040                         Statement.Emit (ec);
4041                         ec.InTry = old_in_try;
4042                         
4043                         Label skip = ig.DefineLabel ();
4044                         bool old_in_finally = ec.InFinally;
4045                         ig.BeginFinallyBlock ();
4046                         ig.Emit (OpCodes.Ldloc, local_copy);
4047                         ig.Emit (OpCodes.Brfalse, skip);
4048                         ig.Emit (OpCodes.Ldloc, local_copy);
4049                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4050                         ig.MarkLabel (skip);
4051                         ec.InFinally = old_in_finally;
4052                         ig.EndExceptionBlock ();
4053
4054                         return false;
4055                 }
4056                 
4057                 public override bool Resolve (EmitContext ec)
4058                 {
4059                         if (expression_or_block is DictionaryEntry){
4060                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4061                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4062
4063                                 if (!ResolveLocalVariableDecls (ec))
4064                                         return false;
4065
4066                         } else if (expression_or_block is Expression){
4067                                 expr = (Expression) expression_or_block;
4068
4069                                 expr = expr.Resolve (ec);
4070                                 if (expr == null)
4071                                         return false;
4072
4073                                 expr_type = expr.Type;
4074
4075                                 if (!ResolveExpression (ec))
4076                                         return false;
4077                         }                       
4078
4079                         return Statement.Resolve (ec);
4080                 }
4081                 
4082                 public override bool Emit (EmitContext ec)
4083                 {
4084                         if (expression_or_block is DictionaryEntry)
4085                                 return EmitLocalVariableDecls (ec);
4086                         else if (expression_or_block is Expression)
4087                                 return EmitExpression (ec);
4088
4089                         return false;
4090                 }
4091         }
4092
4093         /// <summary>
4094         ///   Implementation of the foreach C# statement
4095         /// </summary>
4096         public class Foreach : Statement {
4097                 Expression type;
4098                 LocalVariableReference variable;
4099                 Expression expr;
4100                 Statement statement;
4101                 ForeachHelperMethods hm;
4102                 Expression empty, conv;
4103                 Type array_type, element_type;
4104                 Type var_type;
4105                 
4106                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4107                                 Statement stmt, Location l)
4108                 {
4109                         this.type = type;
4110                         this.variable = var;
4111                         this.expr = expr;
4112                         statement = stmt;
4113                         loc = l;
4114                 }
4115                 
4116                 public override bool Resolve (EmitContext ec)
4117                 {
4118                         expr = expr.Resolve (ec);
4119                         if (expr == null)
4120                                 return false;
4121
4122                         var_type = ec.DeclSpace.ResolveType (type, false, loc);
4123                         if (var_type == null)
4124                                 return false;
4125                         
4126                         //
4127                         // We need an instance variable.  Not sure this is the best
4128                         // way of doing this.
4129                         //
4130                         // FIXME: When we implement propertyaccess, will those turn
4131                         // out to return values in ExprClass?  I think they should.
4132                         //
4133                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4134                               expr.eclass == ExprClass.PropertyAccess)){
4135                                 error1579 (expr.Type);
4136                                 return false;
4137                         }
4138
4139                         if (expr.Type.IsArray) {
4140                                 array_type = expr.Type;
4141                                 element_type = array_type.GetElementType ();
4142
4143                                 empty = new EmptyExpression (element_type);
4144                         } else {
4145                                 hm = ProbeCollectionType (ec, expr.Type);
4146                                 if (hm == null){
4147                                         error1579 (expr.Type);
4148                                         return false;
4149                                 }
4150
4151                                 array_type = expr.Type;
4152                                 element_type = hm.element_type;
4153
4154                                 empty = new EmptyExpression (hm.element_type);
4155                         }
4156
4157                         //
4158                         // FIXME: maybe we can apply the same trick we do in the
4159                         // array handling to avoid creating empty and conv in some cases.
4160                         //
4161                         // Although it is not as important in this case, as the type
4162                         // will not likely be object (what the enumerator will return).
4163                         //
4164                         conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4165                         if (conv == null)
4166                                 return false;
4167
4168                         if (variable.ResolveLValue (ec, empty) == null)
4169                                 return false;
4170
4171                         if (!statement.Resolve (ec))
4172                                 return false;
4173
4174                         return true;
4175                 }
4176                 
4177                 //
4178                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4179                 //
4180                 static MethodInfo FetchMethodMoveNext (Type t)
4181                 {
4182                         MemberInfo [] move_next_list;
4183                         
4184                         move_next_list = TypeContainer.FindMembers (
4185                                 t, MemberTypes.Method,
4186                                 BindingFlags.Public | BindingFlags.Instance,
4187                                 Type.FilterName, "MoveNext");
4188                         if (move_next_list == null || move_next_list.Length == 0)
4189                                 return null;
4190
4191                         foreach (MemberInfo m in move_next_list){
4192                                 MethodInfo mi = (MethodInfo) m;
4193                                 Type [] args;
4194                                 
4195                                 args = TypeManager.GetArgumentTypes (mi);
4196                                 if (args != null && args.Length == 0){
4197                                         if (mi.ReturnType == TypeManager.bool_type)
4198                                                 return mi;
4199                                 }
4200                         }
4201                         return null;
4202                 }
4203                 
4204                 //
4205                 // Retrieves a `public T get_Current ()' method from the Type `t'
4206                 //
4207                 static MethodInfo FetchMethodGetCurrent (Type t)
4208                 {
4209                         MemberInfo [] move_next_list;
4210                         
4211                         move_next_list = TypeContainer.FindMembers (
4212                                 t, MemberTypes.Method,
4213                                 BindingFlags.Public | BindingFlags.Instance,
4214                                 Type.FilterName, "get_Current");
4215                         if (move_next_list == null || move_next_list.Length == 0)
4216                                 return null;
4217
4218                         foreach (MemberInfo m in move_next_list){
4219                                 MethodInfo mi = (MethodInfo) m;
4220                                 Type [] args;
4221
4222                                 args = TypeManager.GetArgumentTypes (mi);
4223                                 if (args != null && args.Length == 0)
4224                                         return mi;
4225                         }
4226                         return null;
4227                 }
4228
4229                 // 
4230                 // This struct records the helper methods used by the Foreach construct
4231                 //
4232                 class ForeachHelperMethods {
4233                         public EmitContext ec;
4234                         public MethodInfo get_enumerator;
4235                         public MethodInfo move_next;
4236                         public MethodInfo get_current;
4237                         public Type element_type;
4238                         public Type enumerator_type;
4239                         public bool is_disposable;
4240
4241                         public ForeachHelperMethods (EmitContext ec)
4242                         {
4243                                 this.ec = ec;
4244                                 this.element_type = TypeManager.object_type;
4245                                 this.enumerator_type = TypeManager.ienumerator_type;
4246                                 this.is_disposable = true;
4247                         }
4248                 }
4249                 
4250                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4251                 {
4252                         if (m == null)
4253                                 return false;
4254                         
4255                         if (!(m is MethodInfo))
4256                                 return false;
4257                         
4258                         if (m.Name != "GetEnumerator")
4259                                 return false;
4260
4261                         MethodInfo mi = (MethodInfo) m;
4262                         Type [] args = TypeManager.GetArgumentTypes (mi);
4263                         if (args != null){
4264                                 if (args.Length != 0)
4265                                         return false;
4266                         }
4267                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4268                         EmitContext ec = hm.ec;
4269
4270                         //
4271                         // Check whether GetEnumerator is accessible to us
4272                         //
4273                         MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4274
4275                         Type declaring = mi.DeclaringType;
4276                         if (prot == MethodAttributes.Private){
4277                                 if (declaring != ec.ContainerType)
4278                                         return false;
4279                         } else if (prot == MethodAttributes.FamANDAssem){
4280                                 // If from a different assembly, false
4281                                 if (!(mi is MethodBuilder))
4282                                         return false;
4283                                 //
4284                                 // Are we being invoked from the same class, or from a derived method?
4285                                 //
4286                                 if (ec.ContainerType != declaring){
4287                                         if (!ec.ContainerType.IsSubclassOf (declaring))
4288                                                 return false;
4289                                 }
4290                         } else if (prot == MethodAttributes.FamORAssem){
4291                                 if (!(mi is MethodBuilder ||
4292                                       ec.ContainerType == declaring ||
4293                                       ec.ContainerType.IsSubclassOf (declaring)))
4294                                         return false;
4295                         } if (prot == MethodAttributes.Family){
4296                                 if (!(ec.ContainerType == declaring ||
4297                                       ec.ContainerType.IsSubclassOf (declaring)))
4298                                         return false;
4299                         }
4300
4301                         //
4302                         // Ok, we can access it, now make sure that we can do something
4303                         // with this `GetEnumerator'
4304                         //
4305
4306                         if (mi.ReturnType == TypeManager.ienumerator_type ||
4307                             TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
4308                             (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
4309                                 hm.move_next = TypeManager.bool_movenext_void;
4310                                 hm.get_current = TypeManager.object_getcurrent_void;
4311                                 return true;
4312                         }
4313
4314                         //
4315                         // Ok, so they dont return an IEnumerable, we will have to
4316                         // find if they support the GetEnumerator pattern.
4317                         //
4318                         Type return_type = mi.ReturnType;
4319
4320                         hm.move_next = FetchMethodMoveNext (return_type);
4321                         if (hm.move_next == null)
4322                                 return false;
4323                         hm.get_current = FetchMethodGetCurrent (return_type);
4324                         if (hm.get_current == null)
4325                                 return false;
4326
4327                         hm.element_type = hm.get_current.ReturnType;
4328                         hm.enumerator_type = return_type;
4329                         hm.is_disposable = TypeManager.ImplementsInterface (
4330                                 hm.enumerator_type, TypeManager.idisposable_type);
4331
4332                         return true;
4333                 }
4334                 
4335                 /// <summary>
4336                 ///   This filter is used to find the GetEnumerator method
4337                 ///   on which IEnumerator operates
4338                 /// </summary>
4339                 static MemberFilter FilterEnumerator;
4340                 
4341                 static Foreach ()
4342                 {
4343                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4344                 }
4345
4346                 void error1579 (Type t)
4347                 {
4348                         Report.Error (1579, loc,
4349                                       "foreach statement cannot operate on variables of type `" +
4350                                       t.FullName + "' because that class does not provide a " +
4351                                       " GetEnumerator method or it is inaccessible");
4352                 }
4353
4354                 static bool TryType (Type t, ForeachHelperMethods hm)
4355                 {
4356                         MemberInfo [] mi;
4357                         
4358                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4359                                                         BindingFlags.Public | BindingFlags.NonPublic |
4360                                                         BindingFlags.Instance,
4361                                                         FilterEnumerator, hm);
4362
4363                         if (mi == null || mi.Length == 0)
4364                                 return false;
4365
4366                         hm.get_enumerator = (MethodInfo) mi [0];
4367                         return true;    
4368                 }
4369                 
4370                 //
4371                 // Looks for a usable GetEnumerator in the Type, and if found returns
4372                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4373                 //
4374                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4375                 {
4376                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4377
4378                         if (TryType (t, hm))
4379                                 return hm;
4380
4381                         //
4382                         // Now try to find the method in the interfaces
4383                         //
4384                         while (t != null){
4385                                 Type [] ifaces = t.GetInterfaces ();
4386
4387                                 foreach (Type i in ifaces){
4388                                         if (TryType (i, hm))
4389                                                 return hm;
4390                                 }
4391                                 
4392                                 //
4393                                 // Since TypeBuilder.GetInterfaces only returns the interface
4394                                 // types for this type, we have to keep looping, but once
4395                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4396                                 // done, because it returns all the types
4397                                 //
4398                                 if ((t is TypeBuilder))
4399                                         t = t.BaseType;
4400                                 else
4401                                         break;
4402                         } 
4403
4404                         return null;
4405                 }
4406
4407                 //
4408                 // FIXME: possible optimization.
4409                 // We might be able to avoid creating `empty' if the type is the sam
4410                 //
4411                 bool EmitCollectionForeach (EmitContext ec)
4412                 {
4413                         ILGenerator ig = ec.ig;
4414                         LocalBuilder enumerator, disposable;
4415
4416                         enumerator = ig.DeclareLocal (hm.enumerator_type);
4417                         if (hm.is_disposable)
4418                                 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
4419                         else
4420                                 disposable = null;
4421                         
4422                         //
4423                         // Instantiate the enumerator
4424                         //
4425                         if (expr.Type.IsValueType){
4426                                 if (expr is IMemoryLocation){
4427                                         IMemoryLocation ml = (IMemoryLocation) expr;
4428
4429                                         ml.AddressOf (ec, AddressOp.Load);
4430                                 } else
4431                                         throw new Exception ("Expr " + expr + " of type " + expr.Type +
4432                                                              " does not implement IMemoryLocation");
4433                                 ig.Emit (OpCodes.Call, hm.get_enumerator);
4434                         } else {
4435                                 expr.Emit (ec);
4436                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4437                         }
4438                         ig.Emit (OpCodes.Stloc, enumerator);
4439
4440                         //
4441                         // Protect the code in a try/finalize block, so that
4442                         // if the beast implement IDisposable, we get rid of it
4443                         //
4444                         Label l;
4445                         bool old_in_try = ec.InTry;
4446
4447                         if (hm.is_disposable) {
4448                                 l = ig.BeginExceptionBlock ();
4449                                 ec.InTry = true;
4450                         }
4451                         
4452                         Label end_try = ig.DefineLabel ();
4453                         
4454                         ig.MarkLabel (ec.LoopBegin);
4455                         ig.Emit (OpCodes.Ldloc, enumerator);
4456                         ig.Emit (OpCodes.Callvirt, hm.move_next);
4457                         ig.Emit (OpCodes.Brfalse, end_try);
4458                         ig.Emit (OpCodes.Ldloc, enumerator);
4459                         ig.Emit (OpCodes.Callvirt, hm.get_current);
4460                         variable.EmitAssign (ec, conv);
4461                         statement.Emit (ec);
4462                         ig.Emit (OpCodes.Br, ec.LoopBegin);
4463                         ig.MarkLabel (end_try);
4464                         ec.InTry = old_in_try;
4465                         
4466                         // The runtime provides this for us.
4467                         // ig.Emit (OpCodes.Leave, end);
4468
4469                         //
4470                         // Now the finally block
4471                         //
4472                         if (hm.is_disposable) {
4473                                 Label end_finally = ig.DefineLabel ();
4474                                 bool old_in_finally = ec.InFinally;
4475                                 ec.InFinally = true;
4476                                 ig.BeginFinallyBlock ();
4477                         
4478                                 ig.Emit (OpCodes.Ldloc, enumerator);
4479                                 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4480                                 ig.Emit (OpCodes.Stloc, disposable);
4481                                 ig.Emit (OpCodes.Ldloc, disposable);
4482                                 ig.Emit (OpCodes.Brfalse, end_finally);
4483                                 ig.Emit (OpCodes.Ldloc, disposable);
4484                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4485                                 ig.MarkLabel (end_finally);
4486                                 ec.InFinally = old_in_finally;
4487
4488                                 // The runtime generates this anyways.
4489                                 // ig.Emit (OpCodes.Endfinally);
4490
4491                                 ig.EndExceptionBlock ();
4492                         }
4493
4494                         ig.MarkLabel (ec.LoopEnd);
4495                         return false;
4496                 }
4497
4498                 //
4499                 // FIXME: possible optimization.
4500                 // We might be able to avoid creating `empty' if the type is the sam
4501                 //
4502                 bool EmitArrayForeach (EmitContext ec)
4503                 {
4504                         int rank = array_type.GetArrayRank ();
4505                         ILGenerator ig = ec.ig;
4506
4507                         LocalBuilder copy = ig.DeclareLocal (array_type);
4508                         
4509                         //
4510                         // Make our copy of the array
4511                         //
4512                         expr.Emit (ec);
4513                         ig.Emit (OpCodes.Stloc, copy);
4514                         
4515                         if (rank == 1){
4516                                 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
4517
4518                                 Label loop, test;
4519                                 
4520                                 ig.Emit (OpCodes.Ldc_I4_0);
4521                                 ig.Emit (OpCodes.Stloc, counter);
4522                                 test = ig.DefineLabel ();
4523                                 ig.Emit (OpCodes.Br, test);
4524
4525                                 loop = ig.DefineLabel ();
4526                                 ig.MarkLabel (loop);
4527
4528                                 ig.Emit (OpCodes.Ldloc, copy);
4529                                 ig.Emit (OpCodes.Ldloc, counter);
4530                                 ArrayAccess.EmitLoadOpcode (ig, var_type);
4531
4532                                 variable.EmitAssign (ec, conv);
4533
4534                                 statement.Emit (ec);
4535
4536                                 ig.MarkLabel (ec.LoopBegin);
4537                                 ig.Emit (OpCodes.Ldloc, counter);
4538                                 ig.Emit (OpCodes.Ldc_I4_1);
4539                                 ig.Emit (OpCodes.Add);
4540                                 ig.Emit (OpCodes.Stloc, counter);
4541
4542                                 ig.MarkLabel (test);
4543                                 ig.Emit (OpCodes.Ldloc, counter);
4544                                 ig.Emit (OpCodes.Ldloc, copy);
4545                                 ig.Emit (OpCodes.Ldlen);
4546                                 ig.Emit (OpCodes.Conv_I4);
4547                                 ig.Emit (OpCodes.Blt, loop);
4548                         } else {
4549                                 LocalBuilder [] dim_len   = new LocalBuilder [rank];
4550                                 LocalBuilder [] dim_count = new LocalBuilder [rank];
4551                                 Label [] loop = new Label [rank];
4552                                 Label [] test = new Label [rank];
4553                                 int dim;
4554                                 
4555                                 for (dim = 0; dim < rank; dim++){
4556                                         dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
4557                                         dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
4558                                         test [dim] = ig.DefineLabel ();
4559                                         loop [dim] = ig.DefineLabel ();
4560                                 }
4561                                         
4562                                 for (dim = 0; dim < rank; dim++){
4563                                         ig.Emit (OpCodes.Ldloc, copy);
4564                                         IntLiteral.EmitInt (ig, dim);
4565                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4566                                         ig.Emit (OpCodes.Stloc, dim_len [dim]);
4567                                 }
4568
4569                                 for (dim = 0; dim < rank; dim++){
4570                                         ig.Emit (OpCodes.Ldc_I4_0);
4571                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
4572                                         ig.Emit (OpCodes.Br, test [dim]);
4573                                         ig.MarkLabel (loop [dim]);
4574                                 }
4575
4576                                 ig.Emit (OpCodes.Ldloc, copy);
4577                                 for (dim = 0; dim < rank; dim++)
4578                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4579
4580                                 //
4581                                 // FIXME: Maybe we can cache the computation of `get'?
4582                                 //
4583                                 Type [] args = new Type [rank];
4584                                 MethodInfo get;
4585
4586                                 for (int i = 0; i < rank; i++)
4587                                         args [i] = TypeManager.int32_type;
4588
4589                                 ModuleBuilder mb = CodeGen.ModuleBuilder;
4590                                 get = mb.GetArrayMethod (
4591                                         array_type, "Get",
4592                                         CallingConventions.HasThis| CallingConventions.Standard,
4593                                         var_type, args);
4594                                 ig.Emit (OpCodes.Call, get);
4595                                 variable.EmitAssign (ec, conv);
4596                                 statement.Emit (ec);
4597                                 ig.MarkLabel (ec.LoopBegin);
4598                                 for (dim = rank - 1; dim >= 0; dim--){
4599                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4600                                         ig.Emit (OpCodes.Ldc_I4_1);
4601                                         ig.Emit (OpCodes.Add);
4602                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
4603
4604                                         ig.MarkLabel (test [dim]);
4605                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4606                                         ig.Emit (OpCodes.Ldloc, dim_len [dim]);
4607                                         ig.Emit (OpCodes.Blt, loop [dim]);
4608                                 }
4609                         }
4610                         ig.MarkLabel (ec.LoopEnd);
4611                         
4612                         return false;
4613                 }
4614                 
4615                 public override bool Emit (EmitContext ec)
4616                 {
4617                         bool ret_val;
4618                         
4619                         ILGenerator ig = ec.ig;
4620                         
4621                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4622                         bool old_inloop = ec.InLoop;
4623                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
4624                         ec.LoopBegin = ig.DefineLabel ();
4625                         ec.LoopEnd = ig.DefineLabel ();
4626                         ec.InLoop = true;
4627                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
4628                         
4629                         if (hm != null)
4630                                 ret_val = EmitCollectionForeach (ec);
4631                         else
4632                                 ret_val = EmitArrayForeach (ec);
4633                         
4634                         ec.LoopBegin = old_begin;
4635                         ec.LoopEnd = old_end;
4636                         ec.InLoop = old_inloop;
4637                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
4638
4639                         return ret_val;
4640                 }
4641         }
4642 }
4643