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