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