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