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