Reflect latest API changes.
[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, 2003 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                 /// <summary>
25                 ///   Resolves the statement, true means that all sub-statements
26                 ///   did resolve ok.
27                 //  </summary>
28                 public virtual bool Resolve (EmitContext ec)
29                 {
30                         return true;
31                 }
32
33                 /// <summary>
34                 ///   We already know that the statement is unreachable, but we still
35                 ///   need to resolve it to catch errors.
36                 /// </summary>
37                 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
38                 {
39                         //
40                         // This conflicts with csc's way of doing this, but IMHO it's
41                         // the right thing to do.
42                         //
43                         // If something is unreachable, we still check whether it's
44                         // correct.  This means that you cannot use unassigned variables
45                         // in unreachable code, for instance.
46                         //
47
48                         ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
49                         bool ok = Resolve (ec);
50                         ec.KillFlowBranching ();
51
52                         if (!ok)
53                                 return false;
54
55                         if (warn)
56                                 Report.Warning (162, loc, "Unreachable code detected");
57                         return true;
58                 }
59                 
60                 protected void CheckObsolete (Type type)
61                 {
62                         ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
63                         if (obsolete_attr == null)
64                                 return;
65
66                         AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
67                 }
68                 
69                 /// <summary>
70                 ///   Return value indicates whether all code paths emitted return.
71                 /// </summary>
72                 protected abstract void DoEmit (EmitContext ec);
73
74                 /// <summary>
75                 ///   Utility wrapper routine for Error, just to beautify the code
76                 /// </summary>
77                 public void Error (int error, string format, params object[] args)
78                 {
79                         Error (error, String.Format (format, args));
80                 }
81
82                 public void Error (int error, string s)
83                 {
84                         if (!Location.IsNull (loc))
85                                 Report.Error (error, loc, s);
86                         else
87                                 Report.Error (error, s);
88                 }
89
90                 /// <summary>
91                 ///   Return value indicates whether all code paths emitted return.
92                 /// </summary>
93                 public virtual void Emit (EmitContext ec)
94                 {
95                         ec.Mark (loc, true);
96                         DoEmit (ec);
97                 }               
98         }
99
100         public sealed class EmptyStatement : Statement {
101                 
102                 private EmptyStatement () {}
103                 
104                 public static readonly EmptyStatement Value = new EmptyStatement ();
105                 
106                 public override bool Resolve (EmitContext ec)
107                 {
108                         return true;
109                 }
110                 
111                 protected override void DoEmit (EmitContext ec)
112                 {
113                 }
114         }
115         
116         public class If : Statement {
117                 Expression expr;
118                 public Statement TrueStatement;
119                 public Statement FalseStatement;
120
121                 bool is_true_ret;
122                 
123                 public If (Expression expr, Statement trueStatement, Location l)
124                 {
125                         this.expr = expr;
126                         TrueStatement = trueStatement;
127                         loc = l;
128                 }
129
130                 public If (Expression expr,
131                            Statement trueStatement,
132                            Statement falseStatement,
133                            Location l)
134                 {
135                         this.expr = expr;
136                         TrueStatement = trueStatement;
137                         FalseStatement = falseStatement;
138                         loc = l;
139                 }
140
141                 public override bool Resolve (EmitContext ec)
142                 {
143                         Report.Debug (1, "START IF BLOCK", loc);
144
145                         expr = Expression.ResolveBoolean (ec, expr, loc);
146                         if (expr == null){
147                                 return false;
148                         }
149
150                         //
151                         // Dead code elimination
152                         //
153                         if (expr is BoolConstant){
154                                 bool take = ((BoolConstant) expr).Value;
155
156                                 if (take){
157                                         if (!TrueStatement.Resolve (ec))
158                                                 return false;
159
160                                         if ((FalseStatement != null) &&
161                                             !FalseStatement.ResolveUnreachable (ec, true))
162                                                 return false;
163                                         FalseStatement = null;
164                                 } else {
165                                         if (!TrueStatement.ResolveUnreachable (ec, true))
166                                                 return false;
167                                         TrueStatement = null;
168
169                                         if ((FalseStatement != null) &&
170                                             !FalseStatement.Resolve (ec))
171                                                 return false;
172                                 }
173
174                                 return true;
175                         }
176                         
177                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
178                         
179                         bool ok = TrueStatement.Resolve (ec);
180
181                         is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
182
183                         ec.CurrentBranching.CreateSibling ();
184
185                         if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
186                                 ok = false;
187                                         
188                         ec.EndFlowBranching ();
189
190                         Report.Debug (1, "END IF BLOCK", loc);
191
192                         return ok;
193                 }
194                 
195                 protected override void DoEmit (EmitContext ec)
196                 {
197                         ILGenerator ig = ec.ig;
198                         Label false_target = ig.DefineLabel ();
199                         Label end;
200
201                         //
202                         // If we're a boolean expression, Resolve() already
203                         // eliminated dead code for us.
204                         //
205                         if (expr is BoolConstant){
206                                 bool take = ((BoolConstant) expr).Value;
207
208                                 if (take)
209                                         TrueStatement.Emit (ec);
210                                 else if (FalseStatement != null)
211                                         FalseStatement.Emit (ec);
212
213                                 return;
214                         }
215                         
216                         expr.EmitBranchable (ec, false_target, false);
217                         
218                         TrueStatement.Emit (ec);
219
220                         if (FalseStatement != null){
221                                 bool branch_emitted = false;
222                                 
223                                 end = ig.DefineLabel ();
224                                 if (!is_true_ret){
225                                         ig.Emit (OpCodes.Br, end);
226                                         branch_emitted = true;
227                                 }
228
229                                 ig.MarkLabel (false_target);
230                                 FalseStatement.Emit (ec);
231
232                                 if (branch_emitted)
233                                         ig.MarkLabel (end);
234                         } else {
235                                 ig.MarkLabel (false_target);
236                         }
237                 }
238         }
239
240         public class Do : Statement {
241                 public Expression expr;
242                 public readonly Statement  EmbeddedStatement;
243                 bool infinite;
244                 
245                 public Do (Statement statement, Expression boolExpr, Location l)
246                 {
247                         expr = boolExpr;
248                         EmbeddedStatement = statement;
249                         loc = l;
250                 }
251
252                 public override bool Resolve (EmitContext ec)
253                 {
254                         bool ok = true;
255
256                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
257
258                         if (!EmbeddedStatement.Resolve (ec))
259                                 ok = false;
260
261                         expr = Expression.ResolveBoolean (ec, expr, loc);
262                         if (expr == null)
263                                 ok = false;
264                         else if (expr is BoolConstant){
265                                 bool res = ((BoolConstant) expr).Value;
266
267                                 if (res)
268                                         infinite = true;
269                         }
270
271                         ec.CurrentBranching.Infinite = infinite;
272                         ec.EndFlowBranching ();
273
274                         return ok;
275                 }
276                 
277                 protected override void DoEmit (EmitContext ec)
278                 {
279                         ILGenerator ig = ec.ig;
280                         Label loop = ig.DefineLabel ();
281                         Label old_begin = ec.LoopBegin;
282                         Label old_end = ec.LoopEnd;
283                         
284                         ec.LoopBegin = ig.DefineLabel ();
285                         ec.LoopEnd = ig.DefineLabel ();
286                                 
287                         ig.MarkLabel (loop);
288                         EmbeddedStatement.Emit (ec);
289                         ig.MarkLabel (ec.LoopBegin);
290
291                         //
292                         // Dead code elimination
293                         //
294                         if (expr is BoolConstant){
295                                 bool res = ((BoolConstant) expr).Value;
296
297                                 if (res)
298                                         ec.ig.Emit (OpCodes.Br, loop); 
299                         } else
300                                 expr.EmitBranchable (ec, loop, true);
301                         
302                         ig.MarkLabel (ec.LoopEnd);
303
304                         ec.LoopBegin = old_begin;
305                         ec.LoopEnd = old_end;
306                 }
307         }
308
309         public class While : Statement {
310                 public Expression expr;
311                 public readonly Statement Statement;
312                 bool infinite, empty;
313                 
314                 public While (Expression boolExpr, Statement statement, Location l)
315                 {
316                         this.expr = boolExpr;
317                         Statement = statement;
318                         loc = l;
319                 }
320
321                 public override bool Resolve (EmitContext ec)
322                 {
323                         bool ok = true;
324
325                         expr = Expression.ResolveBoolean (ec, expr, loc);
326                         if (expr == null)
327                                 return false;
328
329                         //
330                         // Inform whether we are infinite or not
331                         //
332                         if (expr is BoolConstant){
333                                 BoolConstant bc = (BoolConstant) expr;
334
335                                 if (bc.Value == false){
336                                         if (!Statement.ResolveUnreachable (ec, true))
337                                                 return false;
338                                         empty = true;
339                                         return true;
340                                 } else
341                                         infinite = true;
342                         }
343
344                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
345
346                         if (!Statement.Resolve (ec))
347                                 ok = false;
348
349                         ec.CurrentBranching.Infinite = infinite;
350                         ec.EndFlowBranching ();
351
352                         return ok;
353                 }
354                 
355                 protected override void DoEmit (EmitContext ec)
356                 {
357                         if (empty)
358                                 return;
359
360                         ILGenerator ig = ec.ig;
361                         Label old_begin = ec.LoopBegin;
362                         Label old_end = ec.LoopEnd;
363                         
364                         ec.LoopBegin = ig.DefineLabel ();
365                         ec.LoopEnd = ig.DefineLabel ();
366
367                         //
368                         // Inform whether we are infinite or not
369                         //
370                         if (expr is BoolConstant){
371                                 ig.MarkLabel (ec.LoopBegin);
372                                 Statement.Emit (ec);
373                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
374                                         
375                                 //
376                                 // Inform that we are infinite (ie, `we return'), only
377                                 // if we do not `break' inside the code.
378                                 //
379                                 ig.MarkLabel (ec.LoopEnd);
380                         } else {
381                                 Label while_loop = ig.DefineLabel ();
382
383                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
384                                 ig.MarkLabel (while_loop);
385
386                                 Statement.Emit (ec);
387                         
388                                 ig.MarkLabel (ec.LoopBegin);
389
390                                 expr.EmitBranchable (ec, while_loop, true);
391                                 
392                                 ig.MarkLabel (ec.LoopEnd);
393                         }       
394
395                         ec.LoopBegin = old_begin;
396                         ec.LoopEnd = old_end;
397                 }
398         }
399
400         public class For : Statement {
401                 Expression Test;
402                 readonly Statement InitStatement;
403                 readonly Statement Increment;
404                 readonly Statement Statement;
405                 bool infinite, empty;
406                 
407                 public For (Statement initStatement,
408                             Expression test,
409                             Statement increment,
410                             Statement statement,
411                             Location l)
412                 {
413                         InitStatement = initStatement;
414                         Test = test;
415                         Increment = increment;
416                         Statement = statement;
417                         loc = l;
418                 }
419
420                 public override bool Resolve (EmitContext ec)
421                 {
422                         bool ok = true;
423
424                         if (InitStatement != null){
425                                 if (!InitStatement.Resolve (ec))
426                                         ok = false;
427                         }
428
429                         if (Test != null){
430                                 Test = Expression.ResolveBoolean (ec, Test, loc);
431                                 if (Test == null)
432                                         ok = false;
433                                 else if (Test is BoolConstant){
434                                         BoolConstant bc = (BoolConstant) Test;
435
436                                         if (bc.Value == false){
437                                                 if (!Statement.ResolveUnreachable (ec, true))
438                                                         return false;
439                                                 if ((Increment != null) &&
440                                                     !Increment.ResolveUnreachable (ec, false))
441                                                         return false;
442                                                 empty = true;
443                                                 return true;
444                                         } else
445                                                 infinite = true;
446                                 }
447                         } else
448                                 infinite = true;
449
450                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
451                         if (!infinite)
452                                 ec.CurrentBranching.CreateSibling ();
453
454                         if (!Statement.Resolve (ec))
455                                 ok = false;
456
457                         if (Increment != null){
458                                 if (!Increment.Resolve (ec))
459                                         ok = false;
460                         }
461
462                         ec.CurrentBranching.Infinite = infinite;
463                         ec.EndFlowBranching ();
464
465                         return ok;
466                 }
467                 
468                 protected override void DoEmit (EmitContext ec)
469                 {
470                         if (empty)
471                                 return;
472
473                         ILGenerator ig = ec.ig;
474                         Label old_begin = ec.LoopBegin;
475                         Label old_end = ec.LoopEnd;
476                         Label loop = ig.DefineLabel ();
477                         Label test = ig.DefineLabel ();
478                         
479                         if (InitStatement != null && InitStatement != EmptyStatement.Value)
480                                 InitStatement.Emit (ec);
481
482                         ec.LoopBegin = ig.DefineLabel ();
483                         ec.LoopEnd = ig.DefineLabel ();
484
485                         ig.Emit (OpCodes.Br, test);
486                         ig.MarkLabel (loop);
487                         Statement.Emit (ec);
488
489                         ig.MarkLabel (ec.LoopBegin);
490                         if (Increment != EmptyStatement.Value)
491                                 Increment.Emit (ec);
492
493                         ig.MarkLabel (test);
494                         //
495                         // If test is null, there is no test, and we are just
496                         // an infinite loop
497                         //
498                         if (Test != null){
499                                 //
500                                 // The Resolve code already catches the case for
501                                 // Test == BoolConstant (false) so we know that
502                                 // this is true
503                                 //
504                                 if (Test is BoolConstant)
505                                         ig.Emit (OpCodes.Br, loop);
506                                 else
507                                         Test.EmitBranchable (ec, loop, true);
508                                 
509                         } else
510                                 ig.Emit (OpCodes.Br, loop);
511                         ig.MarkLabel (ec.LoopEnd);
512
513                         ec.LoopBegin = old_begin;
514                         ec.LoopEnd = old_end;
515                 }
516         }
517         
518         public class StatementExpression : Statement {
519                 ExpressionStatement 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 = expr.ResolveStatement (ec);
530                         return expr != null;
531                 }
532                 
533                 protected override void DoEmit (EmitContext ec)
534                 {
535                         expr.EmitStatement (ec);
536                 }
537
538                 public override string ToString ()
539                 {
540                         return "StatementExpression (" + expr + ")";
541                 }
542         }
543
544         /// <summary>
545         ///   Implements the return statement
546         /// </summary>
547         public class Return : Statement {
548                 public Expression Expr;
549                 
550                 public Return (Expression expr, Location l)
551                 {
552                         Expr = expr;
553                         loc = l;
554                 }
555
556                 bool in_exc;
557
558                 public override bool Resolve (EmitContext ec)
559                 {
560                         if (ec.ReturnType == null){
561                                 if (Expr != null){
562                                         Error (127, "Return with a value not allowed here");
563                                         return false;
564                                 }
565                         } else {
566                                 if (Expr == null){
567                                         Error (126, "An object of type `{0}' is expected " +
568                                                "for the return statement",
569                                                TypeManager.CSharpName (ec.ReturnType));
570                                         return false;
571                                 }
572
573                                 Expr = Expr.Resolve (ec);
574                                 if (Expr == null)
575                                         return false;
576
577                                 if (Expr.Type != ec.ReturnType) {
578                                         Expr = Convert.ImplicitConversionRequired (
579                                                 ec, Expr, ec.ReturnType, loc);
580                                         if (Expr == null)
581                                                 return false;
582                                 }
583                         }
584
585                         if (ec.InIterator){
586                                 Error (-206, "Return statement not allowed inside iterators");
587                                 return false;
588                         }
589                                 
590                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
591
592                         if (ec.CurrentBranching.InTryOrCatch (true)) {
593                                 ec.CurrentBranching.AddFinallyVector (vector);
594                                 in_exc = true;
595                         } else if (ec.CurrentBranching.InFinally (true)) {
596                                 Error (157, "Control can not leave the body of the finally block");
597                                 return false;
598                         } else
599                                 vector.CheckOutParameters (ec.CurrentBranching);
600
601                         ec.CurrentBranching.CurrentUsageVector.Return ();
602                         return true;
603                 }
604                 
605                 protected override void DoEmit (EmitContext ec)
606                 {
607                         if (Expr != null) {
608                                 Expr.Emit (ec);
609
610                                 if (in_exc)
611                                         ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
612                         }
613
614                         if (in_exc) {
615                                 ec.NeedReturnLabel ();
616                                 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
617                         } else {
618                                 ec.ig.Emit (OpCodes.Ret);
619                         }
620                 }
621         }
622
623         public class Goto : Statement {
624                 string target;
625                 Block block;
626                 LabeledStatement label;
627                 
628                 public override bool Resolve (EmitContext ec)
629                 {
630                         label = ec.CurrentBranching.LookupLabel (target, loc);
631                         if (label == null)
632                                 return false;
633
634                         // If this is a forward goto.
635                         if (!label.IsDefined)
636                                 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
637
638                         ec.CurrentBranching.CurrentUsageVector.Goto ();
639
640                         return true;
641                 }
642                 
643                 public Goto (Block parent_block, string label, Location l)
644                 {
645                         block = parent_block;
646                         loc = l;
647                         target = label;
648                 }
649
650                 public string Target {
651                         get {
652                                 return target;
653                         }
654                 }
655
656                 protected override void DoEmit (EmitContext ec)
657                 {
658                         Label l = label.LabelTarget (ec);
659                         ec.ig.Emit (OpCodes.Br, l);
660                 }
661         }
662
663         public class LabeledStatement : Statement {
664                 public readonly Location Location;
665                 bool defined;
666                 bool referenced;
667                 Label label;
668
669                 FlowBranching.UsageVector vectors;
670                 
671                 public LabeledStatement (string label_name, Location l)
672                 {
673                         this.Location = l;
674                 }
675
676                 public Label LabelTarget (EmitContext ec)
677                 {
678                         if (defined)
679                                 return label;
680                         label = ec.ig.DefineLabel ();
681                         defined = true;
682
683                         return label;
684                 }
685
686                 public bool IsDefined {
687                         get {
688                                 return defined;
689                         }
690                 }
691
692                 public bool HasBeenReferenced {
693                         get {
694                                 return referenced;
695                         }
696                 }
697
698                 public void AddUsageVector (FlowBranching.UsageVector vector)
699                 {
700                         vector = vector.Clone ();
701                         vector.Next = vectors;
702                         vectors = vector;
703                 }
704
705                 public override bool Resolve (EmitContext ec)
706                 {
707                         ec.CurrentBranching.Label (vectors);
708
709                         referenced = true;
710
711                         return true;
712                 }
713
714                 protected override void DoEmit (EmitContext ec)
715                 {
716                         LabelTarget (ec);
717                         ec.ig.MarkLabel (label);
718                 }
719         }
720         
721
722         /// <summary>
723         ///   `goto default' statement
724         /// </summary>
725         public class GotoDefault : Statement {
726                 
727                 public GotoDefault (Location l)
728                 {
729                         loc = l;
730                 }
731
732                 public override bool Resolve (EmitContext ec)
733                 {
734                         ec.CurrentBranching.CurrentUsageVector.Goto ();
735                         return true;
736                 }
737
738                 protected override void DoEmit (EmitContext ec)
739                 {
740                         if (ec.Switch == null){
741                                 Report.Error (153, loc, "goto default is only valid in a switch statement");
742                                 return;
743                         }
744
745                         if (!ec.Switch.GotDefault){
746                                 Report.Error (159, loc, "No default target on switch statement");
747                                 return;
748                         }
749                         ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
750                 }
751         }
752
753         /// <summary>
754         ///   `goto case' statement
755         /// </summary>
756         public class GotoCase : Statement {
757                 Expression expr;
758                 Label label;
759                 
760                 public GotoCase (Expression e, Location l)
761                 {
762                         expr = e;
763                         loc = l;
764                 }
765
766                 public override bool Resolve (EmitContext ec)
767                 {
768                         if (ec.Switch == null){
769                                 Report.Error (153, loc, "goto case is only valid in a switch statement");
770                                 return false;
771                         }
772
773                         expr = expr.Resolve (ec);
774                         if (expr == null)
775                                 return false;
776
777                         if (!(expr is Constant)){
778                                 Report.Error (159, loc, "Target expression for goto case is not constant");
779                                 return false;
780                         }
781
782                         object val = Expression.ConvertIntLiteral (
783                                 (Constant) expr, ec.Switch.SwitchType, loc);
784
785                         if (val == null)
786                                 return false;
787                                         
788                         SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
789
790                         if (sl == null){
791                                 Report.Error (
792                                         159, loc,
793                                         "No such label 'case " + val + "': for the goto case");
794                                 return false;
795                         }
796
797                         label = sl.ILLabelCode;
798
799                         ec.CurrentBranching.CurrentUsageVector.Goto ();
800                         return true;
801                 }
802
803                 protected override void DoEmit (EmitContext ec)
804                 {
805                         ec.ig.Emit (OpCodes.Br, label);
806                 }
807         }
808         
809         public class Throw : Statement {
810                 Expression expr;
811                 
812                 public Throw (Expression expr, Location l)
813                 {
814                         this.expr = expr;
815                         loc = l;
816                 }
817
818                 public override bool Resolve (EmitContext ec)
819                 {
820                         bool in_catch = ec.CurrentBranching.InCatch ();
821                         ec.CurrentBranching.CurrentUsageVector.Throw ();
822
823                         if (expr != null){
824                                 expr = expr.Resolve (ec);
825                                 if (expr == null)
826                                         return false;
827
828                                 ExprClass eclass = expr.eclass;
829
830                                 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
831                                       eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
832                                         expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
833                                         return false;
834                                 }
835
836                                 Type t = expr.Type;
837                                 
838                                 if ((t != TypeManager.exception_type) &&
839                                     !t.IsSubclassOf (TypeManager.exception_type) &&
840                                     !(expr is NullLiteral)) {
841                                         Error (155,
842                                                "The type caught or thrown must be derived " +
843                                                "from System.Exception");
844                                         return false;
845                                 }
846                         } else if (!in_catch) {
847                                 Error (156,
848                                        "A throw statement with no argument is only " +
849                                        "allowed in a catch clause");
850                                 return false;
851                         }
852
853                         return true;
854                 }
855                         
856                 protected override void DoEmit (EmitContext ec)
857                 {
858                         if (expr == null)
859                                 ec.ig.Emit (OpCodes.Rethrow);
860                         else {
861                                 expr.Emit (ec);
862
863                                 ec.ig.Emit (OpCodes.Throw);
864                         }
865                 }
866         }
867
868         public class Break : Statement {
869                 
870                 public Break (Location l)
871                 {
872                         loc = l;
873                 }
874
875                 bool crossing_exc;
876
877                 public override bool Resolve (EmitContext ec)
878                 {
879                         if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
880                                 Error (139, "No enclosing loop or switch to continue to");
881                                 return false;
882                         } else if (ec.CurrentBranching.InFinally (false)) {
883                                 Error (157, "Control can not leave the body of the finally block");
884                                 return false;
885                         } else if (ec.CurrentBranching.InTryOrCatch (false))
886                                 ec.CurrentBranching.AddFinallyVector (
887                                         ec.CurrentBranching.CurrentUsageVector);
888                         else if (ec.CurrentBranching.InLoop ())
889                                 ec.CurrentBranching.AddBreakVector (
890                                         ec.CurrentBranching.CurrentUsageVector);
891
892                         crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
893
894                         ec.CurrentBranching.CurrentUsageVector.Break ();
895                         return true;
896                 }
897
898                 protected override void DoEmit (EmitContext ec)
899                 {
900                         ILGenerator ig = ec.ig;
901
902                         if (crossing_exc)
903                                 ig.Emit (OpCodes.Leave, ec.LoopEnd);
904                         else {
905                                 ec.NeedReturnLabel ();
906                                 ig.Emit (OpCodes.Br, ec.LoopEnd);
907                         }
908                 }
909         }
910
911         public class Continue : Statement {
912                 
913                 public Continue (Location l)
914                 {
915                         loc = l;
916                 }
917
918                 bool crossing_exc;
919
920                 public override bool Resolve (EmitContext ec)
921                 {
922                         if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
923                                 Error (139, "No enclosing loop to continue to");
924                                 return false;
925                         } else if (ec.CurrentBranching.InFinally (false)) {
926                                 Error (157, "Control can not leave the body of the finally block");
927                                 return false;
928                         } else if (ec.CurrentBranching.InTryOrCatch (false))
929                                 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
930
931                         crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
932
933                         ec.CurrentBranching.CurrentUsageVector.Goto ();
934                         return true;
935                 }
936
937                 protected override void DoEmit (EmitContext ec)
938                 {
939                         Label begin = ec.LoopBegin;
940                         
941                         if (crossing_exc)
942                                 ec.ig.Emit (OpCodes.Leave, begin);
943                         else
944                                 ec.ig.Emit (OpCodes.Br, begin);
945                 }
946         }
947
948         public class LocalInfo {
949                 public Expression Type;
950
951                 //
952                 // Most of the time a variable will be stored in a LocalBuilder
953                 //
954                 // But sometimes, it will be stored in a field.  The context of the field will
955                 // be stored in the EmitContext
956                 //
957                 //
958                 public LocalBuilder LocalBuilder;
959                 public FieldBuilder FieldBuilder;
960
961                 public Type VariableType;
962                 public readonly string Name;
963                 public readonly Location Location;
964                 public readonly Block Block;
965
966                 public VariableInfo VariableInfo;
967
968                 enum Flags : byte {
969                         Used = 1,
970                         ReadOnly = 2,
971                         Fixed = 4
972                 }
973
974                 Flags flags;
975                 
976                 public LocalInfo (Expression type, string name, Block block, Location l)
977                 {
978                         Type = type;
979                         Name = name;
980                         Block = block;
981                         Location = l;
982                 }
983
984                 public LocalInfo (TypeContainer tc, Block block, Location l)
985                 {
986                         VariableType = tc.TypeBuilder;
987                         Block = block;
988                         Location = l;
989                 }
990
991                 public bool IsThisAssigned (EmitContext ec, Location loc)
992                 {
993                         if (VariableInfo == null)
994                                 throw new Exception ();
995
996                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
997                                 return true;
998
999                         return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1000                 }
1001
1002                 public bool IsAssigned (EmitContext ec)
1003                 {
1004                         if (VariableInfo == null)
1005                                 throw new Exception ();
1006
1007                         return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1008                 }
1009
1010                 public bool Resolve (EmitContext ec)
1011                 {
1012                         if (VariableType == null)
1013                                 VariableType = ec.DeclSpace.ResolveType (Type, false, Location);
1014
1015                         if (VariableType == TypeManager.void_type) {
1016                                 Report.Error (1547, Location,
1017                                               "Keyword 'void' cannot be used in this context");
1018                                 return false;
1019                         }
1020
1021                         if (VariableType == null)
1022                                 return false;
1023
1024 // TODO: breaks the build
1025 //                      if (VariableType.IsPointer && !ec.InUnsafe)
1026 //                              Expression.UnsafeError (Location);
1027
1028                         return true;
1029                 }
1030
1031                 public void MakePinned ()
1032                 {
1033                         TypeManager.MakePinned (LocalBuilder);
1034                         flags |= Flags.Fixed;
1035                 }
1036
1037                 public bool IsFixed {
1038                         get {
1039                                 if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
1040                                         return true;
1041
1042                                 return false;
1043                         }
1044                 }
1045
1046                 public override string ToString ()
1047                 {
1048                         return String.Format ("LocalInfo ({0},{1},{2},{3})",
1049                                               Name, Type, VariableInfo, Location);
1050                 }
1051
1052                 public bool Used {
1053                         get {
1054                                 return (flags & Flags.Used) != 0;
1055                         }
1056                         set {
1057                                 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1058                         }
1059                 }
1060
1061                 public bool ReadOnly {
1062                         get {
1063                                 return (flags & Flags.ReadOnly) != 0;
1064                         }
1065                         set {
1066                                 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1067                         }
1068                 }
1069
1070                 
1071                 
1072         }
1073                 
1074         /// <summary>
1075         ///   Block represents a C# block.
1076         /// </summary>
1077         ///
1078         /// <remarks>
1079         ///   This class is used in a number of places: either to represent
1080         ///   explicit blocks that the programmer places or implicit blocks.
1081         ///
1082         ///   Implicit blocks are used as labels or to introduce variable
1083         ///   declarations.
1084         ///
1085         ///   Top-level blocks derive from Block, and they are called ToplevelBlock
1086         ///   they contain extra information that is not necessary on normal blocks.
1087         /// </remarks>
1088         public class Block : Statement {
1089                 public readonly Block     Parent;
1090                 public readonly Location  StartLocation;
1091                 public Location           EndLocation = Location.Null;
1092
1093                 [Flags]
1094                 public enum Flags : byte {
1095                         Implicit  = 1,
1096                         Unchecked = 2,
1097                         BlockUsed = 4,
1098                         VariablesInitialized = 8,
1099                         HasRet = 16,
1100                         IsDestructor = 32,
1101                         HasVarargs = 64 
1102                 }
1103                 Flags flags;
1104
1105                 public bool Implicit {
1106                         get {
1107                                 return (flags & Flags.Implicit) != 0;
1108                         }
1109                 }
1110
1111                 public bool Unchecked {
1112                         get {
1113                                 return (flags & Flags.Unchecked) != 0;
1114                         }
1115                         set {
1116                                 flags |= Flags.Unchecked;
1117                         }
1118                 }
1119
1120                 public bool HasVarargs {
1121                         get {
1122                                 if (Parent != null)
1123                                         return Parent.HasVarargs;
1124                                 else
1125                                         return (flags & Flags.HasVarargs) != 0;
1126                         }
1127                         set {
1128                                 flags |= Flags.HasVarargs;
1129                         }
1130                 }
1131
1132                 //
1133                 // The statements in this block
1134                 //
1135                 ArrayList statements;
1136                 int num_statements;
1137
1138                 //
1139                 // An array of Blocks.  We keep track of children just
1140                 // to generate the local variable declarations.
1141                 //
1142                 // Statements and child statements are handled through the
1143                 // statements.
1144                 //
1145                 ArrayList children;
1146                 
1147                 //
1148                 // Labels.  (label, block) pairs.
1149                 //
1150                 Hashtable labels;
1151
1152                 //
1153                 // Keeps track of (name, type) pairs
1154                 //
1155                 Hashtable variables;
1156
1157                 //
1158                 // Keeps track of constants
1159                 Hashtable constants;
1160
1161                 //
1162                 // If this is a switch section, the enclosing switch block.
1163                 //
1164                 Block switch_block;
1165
1166                 static int id;
1167
1168                 int this_id;
1169                 
1170                 public Block (Block parent)
1171                         : this (parent, (Flags) 0, Location.Null, Location.Null)
1172                 { }
1173
1174                 public Block (Block parent, Flags flags)
1175                         : this (parent, flags, Location.Null, Location.Null)
1176                 { }
1177
1178                 public Block (Block parent, Flags flags, Parameters parameters)
1179                         : this (parent, flags, parameters, Location.Null, Location.Null)
1180                 { }
1181
1182                 public Block (Block parent, Location start, Location end)
1183                         : this (parent, (Flags) 0, start, end)
1184                 { }
1185
1186                 public Block (Block parent, Parameters parameters, Location start, Location end)
1187                         : this (parent, (Flags) 0, parameters, start, end)
1188                 { }
1189
1190                 public Block (Block parent, Flags flags, Location start, Location end)
1191                         : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1192                 { }
1193
1194                 public Block (Block parent, Flags flags, Parameters parameters,
1195                               Location start, Location end)
1196                 {
1197                         if (parent != null)
1198                                 parent.AddChild (this);
1199                         
1200                         this.Parent = parent;
1201                         this.flags = flags;
1202                         this.parameters = parameters;
1203                         this.StartLocation = start;
1204                         this.EndLocation = end;
1205                         this.loc = start;
1206                         this_id = id++;
1207                         statements = new ArrayList ();
1208
1209                         if (parent != null && Implicit) {
1210                                 if (parent.child_variable_names == null)
1211                                         parent.child_variable_names = new Hashtable();
1212                                 // share with parent
1213                                 child_variable_names = parent.child_variable_names;
1214                         }
1215                                 
1216                 }
1217
1218                 public Block CreateSwitchBlock (Location start)
1219                 {
1220                         Block new_block = new Block (this, start, start);
1221                         new_block.switch_block = this;
1222                         return new_block;
1223                 }
1224
1225                 public int ID {
1226                         get {
1227                                 return this_id;
1228                         }
1229                 }
1230
1231                 void AddChild (Block b)
1232                 {
1233                         if (children == null)
1234                                 children = new ArrayList ();
1235                         
1236                         children.Add (b);
1237                 }
1238
1239                 public void SetEndLocation (Location loc)
1240                 {
1241                         EndLocation = loc;
1242                 }
1243
1244                 /// <summary>
1245                 ///   Adds a label to the current block. 
1246                 /// </summary>
1247                 ///
1248                 /// <returns>
1249                 ///   false if the name already exists in this block. true
1250                 ///   otherwise.
1251                 /// </returns>
1252                 ///
1253                 public bool AddLabel (string name, LabeledStatement target, Location loc)
1254                 {
1255                         if (switch_block != null)
1256                                 return switch_block.AddLabel (name, target, loc);
1257
1258                         Block cur = this;
1259                         while (cur != null) {
1260                                 if (cur.DoLookupLabel (name) != null) {
1261                                         Report.Error (
1262                                                 140, loc, "The label '{0}' is a duplicate",
1263                                                 name);
1264                                         return false;
1265                                 }
1266
1267                                 if (!Implicit)
1268                                         break;
1269
1270                                 cur = cur.Parent;
1271                         }
1272
1273                         while (cur != null) {
1274                                 if (cur.DoLookupLabel (name) != null) {
1275                                         Report.Error (
1276                                                 158, loc,
1277                                                 "The label '{0}' shadows another label " +
1278                                                 "by the same name in a containing scope.",
1279                                                 name);
1280                                         return false;
1281                                 }
1282
1283                                 if (children != null) {
1284                                         foreach (Block b in children) {
1285                                                 LabeledStatement s = b.DoLookupLabel (name);
1286                                                 if (s == null)
1287                                                         continue;
1288
1289                                                 Report.Error (
1290                                                         158, s.Location,
1291                                                         "The label '{0}' shadows another " +
1292                                                         "label by the same name in a " +
1293                                                         "containing scope.",
1294                                                         name);
1295                                                 return false;
1296                                         }
1297                                 }
1298
1299
1300                                 cur = cur.Parent;
1301                         }
1302
1303                         if (labels == null)
1304                                 labels = new Hashtable ();
1305
1306                         labels.Add (name, target);
1307                         return true;
1308                 }
1309
1310                 public LabeledStatement LookupLabel (string name)
1311                 {
1312                         LabeledStatement s = DoLookupLabel (name);
1313                         if (s != null)
1314                                 return s;
1315
1316                         if (children == null)
1317                                 return null;
1318
1319                         foreach (Block child in children) {
1320                                 if (!child.Implicit)
1321                                         continue;
1322
1323                                 s = child.LookupLabel (name);
1324                                 if (s != null)
1325                                         return s;
1326                         }
1327
1328                         return null;
1329                 }
1330
1331                 LabeledStatement DoLookupLabel (string name)
1332                 {
1333                         if (switch_block != null)
1334                                 return switch_block.LookupLabel (name);
1335
1336                         if (labels != null)
1337                                 if (labels.Contains (name))
1338                                         return ((LabeledStatement) labels [name]);
1339
1340                         return null;
1341                 }
1342
1343                 LocalInfo this_variable = null;
1344
1345                 // <summary>
1346                 //   Returns the "this" instance variable of this block.
1347                 //   See AddThisVariable() for more information.
1348                 // </summary>
1349                 public LocalInfo ThisVariable {
1350                         get {
1351                                 if (this_variable != null)
1352                                         return this_variable;
1353                                 else if (Parent != null)
1354                                         return Parent.ThisVariable;
1355                                 else
1356                                         return null;
1357                         }
1358                 }
1359
1360                 Hashtable child_variable_names;
1361
1362                 // <summary>
1363                 //   Marks a variable with name @name as being used in a child block.
1364                 //   If a variable name has been used in a child block, it's illegal to
1365                 //   declare a variable with the same name in the current block.
1366                 // </summary>
1367                 public void AddChildVariableName (string name)
1368                 {
1369                         if (child_variable_names == null)
1370                                 child_variable_names = new Hashtable ();
1371
1372                         if (!child_variable_names.Contains (name))
1373                                 child_variable_names.Add (name, true);
1374                 }
1375
1376                 // <summary>
1377                 //   Checks whether a variable name has already been used in a child block.
1378                 // </summary>
1379                 public bool IsVariableNameUsedInChildBlock (string name)
1380                 {
1381                         if (child_variable_names == null)
1382                                 return false;
1383
1384                         return child_variable_names.Contains (name);
1385                 }
1386
1387                 // <summary>
1388                 //   This is used by non-static `struct' constructors which do not have an
1389                 //   initializer - in this case, the constructor must initialize all of the
1390                 //   struct's fields.  To do this, we add a "this" variable and use the flow
1391                 //   analysis code to ensure that it's been fully initialized before control
1392                 //   leaves the constructor.
1393                 // </summary>
1394                 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1395                 {
1396                         if (this_variable != null)
1397                                 return this_variable;
1398
1399                         if (variables == null)
1400                                 variables = new Hashtable ();
1401
1402                         this_variable = new LocalInfo (tc, this, l);
1403                         this_variable.Used = true;
1404
1405                         variables.Add ("this", this_variable);
1406
1407                         return this_variable;
1408                 }
1409
1410                 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1411                 {
1412                         if (variables == null)
1413                                 variables = new Hashtable ();
1414
1415                         LocalInfo vi = GetLocalInfo (name);
1416                         if (vi != null) {
1417                                 if (vi.Block != this)
1418                                         Report.Error (136, l, "A local variable named `" + name + "' " +
1419                                                       "cannot be declared in this scope since it would " +
1420                                                       "give a different meaning to `" + name + "', which " +
1421                                                       "is already used in a `parent or current' scope to " +
1422                                                       "denote something else");
1423                                 else
1424                                         Report.Error (128, l, "A local variable `" + name + "' is already " +
1425                                                       "defined in this scope");
1426                                 return null;
1427                         }
1428
1429                         if (IsVariableNameUsedInChildBlock (name)) {
1430                                 Report.Error (136, l, "A local variable named `" + name + "' " +
1431                                               "cannot be declared in this scope since it would " +
1432                                               "give a different meaning to `" + name + "', which " +
1433                                               "is already used in a `child' scope to denote something " +
1434                                               "else");
1435                                 return null;
1436                         }
1437
1438                         if (pars != null) {
1439                                 int idx;
1440                                 Parameter p = pars.GetParameterByName (name, out idx);
1441                                 if (p != null) {
1442                                         Report.Error (136, l, "A local variable named `" + name + "' " +
1443                                                       "cannot be declared in this scope since it would " +
1444                                                       "give a different meaning to `" + name + "', which " +
1445                                                       "is already used in a `parent or current' scope to " +
1446                                                       "denote something else");
1447                                         return null;
1448                                 }
1449                         }
1450
1451                         vi = new LocalInfo (type, name, this, l);
1452
1453                         variables.Add (name, vi);
1454
1455                         // Mark 'name' as "used by a child block" in every surrounding block
1456                         Block cur = this;
1457                         while (cur != null && cur.Implicit) 
1458                                 cur = cur.Parent;
1459                         if (cur != null)
1460                                 for (Block par = cur.Parent; par != null; par = par.Parent)
1461                                         par.AddChildVariableName (name);
1462
1463                         if ((flags & Flags.VariablesInitialized) != 0)
1464                                 throw new Exception ();
1465
1466                         // Console.WriteLine ("Adding {0} to {1}", name, ID);
1467                         return vi;
1468                 }
1469
1470                 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1471                 {
1472                         if (AddVariable (type, name, pars, l) == null)
1473                                 return false;
1474                         
1475                         if (constants == null)
1476                                 constants = new Hashtable ();
1477
1478                         constants.Add (name, value);
1479                         return true;
1480                 }
1481
1482                 public Hashtable Variables {
1483                         get {
1484                                 return variables;
1485                         }
1486                 }
1487
1488                 public LocalInfo GetLocalInfo (string name)
1489                 {
1490                         for (Block b = this; b != null; b = b.Parent) {
1491                                 if (b.variables != null) {
1492                                         LocalInfo ret = b.variables [name] as LocalInfo;
1493                                         if (ret != null)
1494                                                 return ret;
1495                                 }
1496                         }
1497                         return null;
1498                 }
1499
1500                 public Expression GetVariableType (string name)
1501                 {
1502                         LocalInfo vi = GetLocalInfo (name);
1503
1504                         if (vi != null)
1505                                 return vi.Type;
1506
1507                         return null;
1508                 }
1509
1510                 public Expression GetConstantExpression (string name)
1511                 {
1512                         for (Block b = this; b != null; b = b.Parent) {
1513                                 if (b.constants != null) {
1514                                         Expression ret = b.constants [name] as Expression;
1515                                         if (ret != null)
1516                                                 return ret;
1517                                 }
1518                         }
1519                         return null;
1520                 }
1521                 
1522                 /// <summary>
1523                 ///   True if the variable named @name is a constant
1524                 ///  </summary>
1525                 public bool IsConstant (string name)
1526                 {
1527                         Expression e = null;
1528                         
1529                         e = GetConstantExpression (name);
1530                         
1531                         return e != null;
1532                 }
1533                 
1534                 Parameters parameters = null;
1535                 public Parameters Parameters {
1536                         get {
1537                                 Block b = this;
1538                                 while (b.Parent != null)
1539                                         b = b.Parent;
1540                                 return b.parameters;
1541                         }
1542                 }
1543
1544                 /// <returns>
1545                 ///   A list of labels that were not used within this block
1546                 /// </returns>
1547                 public string [] GetUnreferenced ()
1548                 {
1549                         // FIXME: Implement me
1550                         return null;
1551                 }
1552
1553                 public void AddStatement (Statement s)
1554                 {
1555                         statements.Add (s);
1556                         flags |= Flags.BlockUsed;
1557                 }
1558
1559                 public bool Used {
1560                         get {
1561                                 return (flags & Flags.BlockUsed) != 0;
1562                         }
1563                 }
1564
1565                 public void Use ()
1566                 {
1567                         flags |= Flags.BlockUsed;
1568                 }
1569
1570                 public bool HasRet {
1571                         get {
1572                                 return (flags & Flags.HasRet) != 0;
1573                         }
1574                 }
1575
1576                 public bool IsDestructor {
1577                         get {
1578                                 return (flags & Flags.IsDestructor) != 0;
1579                         }
1580                 }
1581
1582                 public void SetDestructor ()
1583                 {
1584                         flags |= Flags.IsDestructor;
1585                 }
1586
1587                 VariableMap param_map, local_map;
1588
1589                 public VariableMap ParameterMap {
1590                         get {
1591                                 if ((flags & Flags.VariablesInitialized) == 0)
1592                                         throw new Exception ();
1593
1594                                 return param_map;
1595                         }
1596                 }
1597
1598                 public VariableMap LocalMap {
1599                         get {
1600                                 if ((flags & Flags.VariablesInitialized) == 0)
1601                                         throw new Exception ();
1602
1603                                 return local_map;
1604                         }
1605                 }
1606
1607                 public bool LiftVariable (LocalInfo local_info)
1608                 {
1609                         return false;
1610                 }
1611                 
1612                 /// <summary>
1613                 ///   Emits the variable declarations and labels.
1614                 /// </summary>
1615                 /// <remarks>
1616                 ///   tc: is our typecontainer (to resolve type references)
1617                 ///   ig: is the code generator:
1618                 /// </remarks>
1619                 public void EmitMeta (EmitContext ec, InternalParameters ip)
1620                 {
1621                         ILGenerator ig = ec.ig;
1622
1623                         //
1624                         // Compute the VariableMap's.
1625                         //
1626                         // Unfortunately, we don't know the type when adding variables with
1627                         // AddVariable(), so we need to compute this info here.
1628                         //
1629
1630                         LocalInfo[] locals;
1631                         if (variables != null) {
1632                                 foreach (LocalInfo li in variables.Values)
1633                                         li.Resolve (ec);
1634
1635                                 locals = new LocalInfo [variables.Count];
1636                                 variables.Values.CopyTo (locals, 0);
1637                         } else
1638                                 locals = new LocalInfo [0];
1639
1640                         if (Parent != null)
1641                                 local_map = new VariableMap (Parent.LocalMap, locals);
1642                         else
1643                                 local_map = new VariableMap (locals);
1644
1645                         param_map = new VariableMap (ip);
1646                         flags |= Flags.VariablesInitialized;
1647
1648                         bool old_check_state = ec.ConstantCheckState;
1649                         ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1650                         bool remap_locals = ec.RemapToProxy;
1651                                 
1652                         //
1653                         // Process this block variables
1654                         //
1655                         if (variables != null){
1656                                 foreach (DictionaryEntry de in variables){
1657                                         string name = (string) de.Key;
1658                                         LocalInfo vi = (LocalInfo) de.Value;
1659                                         
1660                                         if (vi.VariableType == null)
1661                                                 continue;
1662
1663                                         Type variable_type = vi.VariableType;
1664
1665                                         if (variable_type.IsPointer){
1666                                                 //
1667                                                 // Am not really convinced that this test is required (Microsoft does it)
1668                                                 // but the fact is that you would not be able to use the pointer variable
1669                                                 // *anyways*
1670                                                 //
1671                                                 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1672                                                                                   vi.Location))
1673                                                         continue;
1674                                         }
1675
1676                                         if (remap_locals)
1677                                                 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1678                                         else
1679                                                 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1680
1681                                         if (constants == null)
1682                                                 continue;
1683
1684                                         Expression cv = (Expression) constants [name];
1685                                         if (cv == null)
1686                                                 continue;
1687
1688                                         ec.CurrentBlock = this;
1689                                         Expression e = cv.Resolve (ec);
1690                                         if (e == null)
1691                                                 continue;
1692
1693                                         Constant ce = e as Constant;
1694                                         if (ce == null){
1695                                                 Report.Error (133, vi.Location,
1696                                                               "The expression being assigned to `" +
1697                                                               name + "' must be constant (" + e + ")");
1698                                                 continue;
1699                                         }
1700
1701                                         if (e.Type != variable_type){
1702                                                 e = Const.ChangeType (vi.Location, ce, variable_type);
1703                                                 if (e == null)
1704                                                         continue;
1705                                         }
1706
1707                                         constants.Remove (name);
1708                                         constants.Add (name, e);
1709                                 }
1710                         }
1711                         ec.ConstantCheckState = old_check_state;
1712
1713                         //
1714                         // Now, handle the children
1715                         //
1716                         if (children != null){
1717                                 foreach (Block b in children)
1718                                         b.EmitMeta (ec, ip);
1719                         }
1720                 }
1721
1722                 void UsageWarning (FlowBranching.UsageVector vector)
1723                 {
1724                         string name;
1725
1726                         if (variables != null){
1727                                 foreach (DictionaryEntry de in variables){
1728                                         LocalInfo vi = (LocalInfo) de.Value;
1729                                         
1730                                         if (vi.Used)
1731                                                 continue;
1732                                         
1733                                         name = (string) de.Key;
1734
1735                                         if (vector.IsAssigned (vi.VariableInfo)){
1736                                                 Report.Warning (
1737                                                         219, vi.Location, "The variable `" + name +
1738                                                         "' is assigned but its value is never used");
1739                                         } else {
1740                                                 Report.Warning (
1741                                                         168, vi.Location, "The variable `" +
1742                                                         name +
1743                                                         "' is declared but never used");
1744                                         } 
1745                                 }
1746                         }
1747                 }
1748
1749                 public override bool Resolve (EmitContext ec)
1750                 {
1751                         Block prev_block = ec.CurrentBlock;
1752                         bool ok = true;
1753
1754                         int errors = Report.Errors;
1755
1756                         ec.CurrentBlock = this;
1757                         ec.StartFlowBranching (this);
1758
1759                         Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1760
1761                         bool unreachable = false, warning_shown = false;
1762
1763                         int statement_count = statements.Count;
1764                         for (int ix = 0; ix < statement_count; ix++){
1765                                 Statement s = (Statement) statements [ix];
1766
1767                                 if (unreachable && !(s is LabeledStatement)) {
1768                                         if (s == EmptyStatement.Value)
1769                                                 s.loc = EndLocation;
1770
1771                                         if (!s.ResolveUnreachable (ec, !warning_shown))
1772                                                 ok = false;
1773
1774                                         if (s != EmptyStatement.Value)
1775                                                 warning_shown = true;
1776                                         else
1777                                                 s.loc = Location.Null;
1778
1779                                         statements [ix] = EmptyStatement.Value;
1780                                         continue;
1781                                 }
1782
1783                                 if (s.Resolve (ec) == false) {
1784                                         ok = false;
1785                                         statements [ix] = EmptyStatement.Value;
1786                                         continue;
1787                                 }
1788
1789                                 num_statements = ix + 1;
1790
1791                                 if (s is LabeledStatement)
1792                                         unreachable = false;
1793                                 else
1794                                         unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1795                         }
1796
1797                         Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1798                                       ec.CurrentBranching, statement_count, num_statements);
1799
1800
1801                         FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1802
1803                         ec.CurrentBlock = prev_block;
1804
1805                         // If we're a non-static `struct' constructor which doesn't have an
1806                         // initializer, then we must initialize all of the struct's fields.
1807                         if ((this_variable != null) &&
1808                             (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1809                             !this_variable.IsThisAssigned (ec, loc))
1810                                 ok = false;
1811
1812                         if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1813                                 foreach (LabeledStatement label in labels.Values)
1814                                         if (!label.HasBeenReferenced)
1815                                                 Report.Warning (164, label.Location,
1816                                                                 "This label has not been referenced");
1817                         }
1818
1819                         Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1820
1821                         if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1822                             (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1823                             (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1824                                 flags |= Flags.HasRet;
1825
1826                         if (ok && (errors == Report.Errors)) {
1827                                 if (RootContext.WarningLevel >= 3)
1828                                         UsageWarning (vector);
1829                         }
1830
1831                         return ok;
1832                 }
1833                 
1834                 protected override void DoEmit (EmitContext ec)
1835                 {
1836                         for (int ix = 0; ix < num_statements; ix++){
1837                                 Statement s = (Statement) statements [ix];
1838
1839                                 // Check whether we are the last statement in a
1840                                 // top-level block.
1841
1842                                 if ((Parent == null) && (ix+1 == num_statements))
1843                                         ec.IsLastStatement = true;
1844                                 else
1845                                         ec.IsLastStatement = false;
1846
1847                                 s.Emit (ec);
1848                         }
1849                 }
1850
1851                 public override void Emit (EmitContext ec)
1852                 {
1853                         Block prev_block = ec.CurrentBlock;
1854
1855                         ec.CurrentBlock = this;
1856
1857                         bool emit_debug_info = (CodeGen.SymbolWriter != null);
1858                         bool is_lexical_block = !Implicit && (Parent != null);
1859
1860                         if (emit_debug_info) {
1861                                 if (is_lexical_block)
1862                                         ec.ig.BeginScope ();
1863
1864                                 if (variables != null) {
1865                                         foreach (DictionaryEntry de in variables) {
1866                                                 string name = (string) de.Key;
1867                                                 LocalInfo vi = (LocalInfo) de.Value;
1868
1869                                                 if (vi.LocalBuilder == null)
1870                                                         continue;
1871
1872                                                 vi.LocalBuilder.SetLocalSymInfo (name);
1873                                         }
1874                                 }
1875                         }
1876
1877                         ec.Mark (StartLocation, true);
1878                         DoEmit (ec);
1879                         ec.Mark (EndLocation, true); 
1880
1881                         if (emit_debug_info && is_lexical_block)
1882                                 ec.ig.EndScope ();
1883
1884                         ec.CurrentBlock = prev_block;
1885                 }
1886         }
1887
1888         //
1889         // 
1890         public class ToplevelBlock : Block {
1891                 public ToplevelBlock (Parameters parameters, Location start) :
1892                         base (null, parameters, start, Location.Null)
1893                 {
1894                 }
1895
1896                 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
1897                         base (null, flags, parameters, start, Location.Null)
1898                 {
1899                 }
1900         }
1901         
1902         public class SwitchLabel {
1903                 Expression label;
1904                 object converted;
1905                 public Location loc;
1906                 public Label ILLabel;
1907                 public Label ILLabelCode;
1908
1909                 //
1910                 // if expr == null, then it is the default case.
1911                 //
1912                 public SwitchLabel (Expression expr, Location l)
1913                 {
1914                         label = expr;
1915                         loc = l;
1916                 }
1917
1918                 public Expression Label {
1919                         get {
1920                                 return label;
1921                         }
1922                 }
1923
1924                 public object Converted {
1925                         get {
1926                                 return converted;
1927                         }
1928                 }
1929
1930                 //
1931                 // Resolves the expression, reduces it to a literal if possible
1932                 // and then converts it to the requested type.
1933                 //
1934                 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1935                 {
1936                         ILLabel = ec.ig.DefineLabel ();
1937                         ILLabelCode = ec.ig.DefineLabel ();
1938
1939                         if (label == null)
1940                                 return true;
1941                         
1942                         Expression e = label.Resolve (ec);
1943
1944                         if (e == null)
1945                                 return false;
1946
1947                         if (!(e is Constant)){
1948                                 Report.Error (150, loc, "A constant value is expected, got: " + e);
1949                                 return false;
1950                         }
1951
1952                         if (e is StringConstant || e is NullLiteral){
1953                                 if (required_type == TypeManager.string_type){
1954                                         converted = e;
1955                                         ILLabel = ec.ig.DefineLabel ();
1956                                         return true;
1957                                 }
1958                         }
1959
1960                         converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1961                         if (converted == null)
1962                                 return false;
1963
1964                         return true;
1965                 }
1966         }
1967
1968         public class SwitchSection {
1969                 // An array of SwitchLabels.
1970                 public readonly ArrayList Labels;
1971                 public readonly Block Block;
1972                 
1973                 public SwitchSection (ArrayList labels, Block block)
1974                 {
1975                         Labels = labels;
1976                         Block = block;
1977                 }
1978         }
1979         
1980         public class Switch : Statement {
1981                 public readonly ArrayList Sections;
1982                 public Expression Expr;
1983
1984                 /// <summary>
1985                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
1986                 /// </summary>
1987                 public Hashtable Elements;
1988
1989                 /// <summary>
1990                 ///   The governing switch type
1991                 /// </summary>
1992                 public Type SwitchType;
1993
1994                 //
1995                 // Computed
1996                 //
1997                 bool got_default;
1998                 Label default_target;
1999                 Expression new_expr;
2000
2001                 //
2002                 // The types allowed to be implicitly cast from
2003                 // on the governing type
2004                 //
2005                 static Type [] allowed_types;
2006                 
2007                 public Switch (Expression e, ArrayList sects, Location l)
2008                 {
2009                         Expr = e;
2010                         Sections = sects;
2011                         loc = l;
2012                 }
2013
2014                 public bool GotDefault {
2015                         get {
2016                                 return got_default;
2017                         }
2018                 }
2019
2020                 public Label DefaultTarget {
2021                         get {
2022                                 return default_target;
2023                         }
2024                 }
2025
2026                 //
2027                 // Determines the governing type for a switch.  The returned
2028                 // expression might be the expression from the switch, or an
2029                 // expression that includes any potential conversions to the
2030                 // integral types or to string.
2031                 //
2032                 Expression SwitchGoverningType (EmitContext ec, Type t)
2033                 {
2034                         if (t == TypeManager.int32_type ||
2035                             t == TypeManager.uint32_type ||
2036                             t == TypeManager.char_type ||
2037                             t == TypeManager.byte_type ||
2038                             t == TypeManager.sbyte_type ||
2039                             t == TypeManager.ushort_type ||
2040                             t == TypeManager.short_type ||
2041                             t == TypeManager.uint64_type ||
2042                             t == TypeManager.int64_type ||
2043                             t == TypeManager.string_type ||
2044                                 t == TypeManager.bool_type ||
2045                                 t.IsSubclassOf (TypeManager.enum_type))
2046                                 return Expr;
2047
2048                         if (allowed_types == null){
2049                                 allowed_types = new Type [] {
2050                                         TypeManager.sbyte_type,
2051                                         TypeManager.byte_type,
2052                                         TypeManager.short_type,
2053                                         TypeManager.ushort_type,
2054                                         TypeManager.int32_type,
2055                                         TypeManager.uint32_type,
2056                                         TypeManager.int64_type,
2057                                         TypeManager.uint64_type,
2058                                         TypeManager.char_type,
2059                                         TypeManager.bool_type,
2060                                         TypeManager.string_type
2061                                 };
2062                         }
2063
2064                         //
2065                         // Try to find a *user* defined implicit conversion.
2066                         //
2067                         // If there is no implicit conversion, or if there are multiple
2068                         // conversions, we have to report an error
2069                         //
2070                         Expression converted = null;
2071                         foreach (Type tt in allowed_types){
2072                                 Expression e;
2073                                 
2074                                 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2075                                 if (e == null)
2076                                         continue;
2077
2078                                 if (converted != null){
2079                                         Report.Error (-12, loc, "More than one conversion to an integral " +
2080                                                       " type exists for type `" +
2081                                                       TypeManager.CSharpName (Expr.Type)+"'");
2082                                         return null;
2083                                 } else
2084                                         converted = e;
2085                         }
2086                         return converted;
2087                 }
2088
2089                 void error152 (string n)
2090                 {
2091                         Report.Error (
2092                                 152, "The label `" + n + ":' " +
2093                                 "is already present on this switch statement");
2094                 }
2095                 
2096                 //
2097                 // Performs the basic sanity checks on the switch statement
2098                 // (looks for duplicate keys and non-constant expressions).
2099                 //
2100                 // It also returns a hashtable with the keys that we will later
2101                 // use to compute the switch tables
2102                 //
2103                 bool CheckSwitch (EmitContext ec)
2104                 {
2105                         Type compare_type;
2106                         bool error = false;
2107                         Elements = new Hashtable ();
2108                                 
2109                         got_default = false;
2110
2111                         if (TypeManager.IsEnumType (SwitchType)){
2112                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2113                         } else
2114                                 compare_type = SwitchType;
2115                         
2116                         foreach (SwitchSection ss in Sections){
2117                                 foreach (SwitchLabel sl in ss.Labels){
2118                                         if (!sl.ResolveAndReduce (ec, SwitchType)){
2119                                                 error = true;
2120                                                 continue;
2121                                         }
2122
2123                                         if (sl.Label == null){
2124                                                 if (got_default){
2125                                                         error152 ("default");
2126                                                         error = true;
2127                                                 }
2128                                                 got_default = true;
2129                                                 continue;
2130                                         }
2131                                         
2132                                         object key = sl.Converted;
2133
2134                                         if (key is Constant)
2135                                                 key = ((Constant) key).GetValue ();
2136
2137                                         if (key == null)
2138                                                 key = NullLiteral.Null;
2139                                         
2140                                         string lname = null;
2141                                         if (compare_type == TypeManager.uint64_type){
2142                                                 ulong v = (ulong) key;
2143
2144                                                 if (Elements.Contains (v))
2145                                                         lname = v.ToString ();
2146                                                 else
2147                                                         Elements.Add (v, sl);
2148                                         } else if (compare_type == TypeManager.int64_type){
2149                                                 long v = (long) key;
2150
2151                                                 if (Elements.Contains (v))
2152                                                         lname = v.ToString ();
2153                                                 else
2154                                                         Elements.Add (v, sl);
2155                                         } else if (compare_type == TypeManager.uint32_type){
2156                                                 uint v = (uint) key;
2157
2158                                                 if (Elements.Contains (v))
2159                                                         lname = v.ToString ();
2160                                                 else
2161                                                         Elements.Add (v, sl);
2162                                         } else if (compare_type == TypeManager.char_type){
2163                                                 char v = (char) key;
2164                                                 
2165                                                 if (Elements.Contains (v))
2166                                                         lname = v.ToString ();
2167                                                 else
2168                                                         Elements.Add (v, sl);
2169                                         } else if (compare_type == TypeManager.byte_type){
2170                                                 byte v = (byte) key;
2171                                                 
2172                                                 if (Elements.Contains (v))
2173                                                         lname = v.ToString ();
2174                                                 else
2175                                                         Elements.Add (v, sl);
2176                                         } else if (compare_type == TypeManager.sbyte_type){
2177                                                 sbyte v = (sbyte) key;
2178                                                 
2179                                                 if (Elements.Contains (v))
2180                                                         lname = v.ToString ();
2181                                                 else
2182                                                         Elements.Add (v, sl);
2183                                         } else if (compare_type == TypeManager.short_type){
2184                                                 short v = (short) key;
2185                                                 
2186                                                 if (Elements.Contains (v))
2187                                                         lname = v.ToString ();
2188                                                 else
2189                                                         Elements.Add (v, sl);
2190                                         } else if (compare_type == TypeManager.ushort_type){
2191                                                 ushort v = (ushort) key;
2192                                                 
2193                                                 if (Elements.Contains (v))
2194                                                         lname = v.ToString ();
2195                                                 else
2196                                                         Elements.Add (v, sl);
2197                                         } else if (compare_type == TypeManager.string_type){
2198                                                 if (key is NullLiteral){
2199                                                         if (Elements.Contains (NullLiteral.Null))
2200                                                                 lname = "null";
2201                                                         else
2202                                                                 Elements.Add (NullLiteral.Null, null);
2203                                                 } else {
2204                                                         string s = (string) key;
2205
2206                                                         if (Elements.Contains (s))
2207                                                                 lname = s;
2208                                                         else
2209                                                                 Elements.Add (s, sl);
2210                                                 }
2211                                         } else if (compare_type == TypeManager.int32_type) {
2212                                                 int v = (int) key;
2213
2214                                                 if (Elements.Contains (v))
2215                                                         lname = v.ToString ();
2216                                                 else
2217                                                         Elements.Add (v, sl);
2218                                         } else if (compare_type == TypeManager.bool_type) {
2219                                                 bool v = (bool) key;
2220
2221                                                 if (Elements.Contains (v))
2222                                                         lname = v.ToString ();
2223                                                 else
2224                                                         Elements.Add (v, sl);
2225                                         }
2226                                         else
2227                                         {
2228                                                 throw new Exception ("Unknown switch type!" +
2229                                                                      SwitchType + " " + compare_type);
2230                                         }
2231
2232                                         if (lname != null){
2233                                                 error152 ("case + " + lname);
2234                                                 error = true;
2235                                         }
2236                                 }
2237                         }
2238                         if (error)
2239                                 return false;
2240
2241                         return true;
2242                 }
2243
2244                 void EmitObjectInteger (ILGenerator ig, object k)
2245                 {
2246                         if (k is int)
2247                                 IntConstant.EmitInt (ig, (int) k);
2248                         else if (k is Constant) {
2249                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2250                         } 
2251                         else if (k is uint)
2252                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2253                         else if (k is long)
2254                         {
2255                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2256                                 {
2257                                         IntConstant.EmitInt (ig, (int) (long) k);
2258                                         ig.Emit (OpCodes.Conv_I8);
2259                                 }
2260                                 else
2261                                         LongConstant.EmitLong (ig, (long) k);
2262                         }
2263                         else if (k is ulong)
2264                         {
2265                                 if ((ulong) k < (1L<<32))
2266                                 {
2267                                         IntConstant.EmitInt (ig, (int) (long) k);
2268                                         ig.Emit (OpCodes.Conv_U8);
2269                                 }
2270                                 else
2271                                 {
2272                                         LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2273                                 }
2274                         }
2275                         else if (k is char)
2276                                 IntConstant.EmitInt (ig, (int) ((char) k));
2277                         else if (k is sbyte)
2278                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2279                         else if (k is byte)
2280                                 IntConstant.EmitInt (ig, (int) ((byte) k));
2281                         else if (k is short)
2282                                 IntConstant.EmitInt (ig, (int) ((short) k));
2283                         else if (k is ushort)
2284                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
2285                         else if (k is bool)
2286                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2287                         else
2288                                 throw new Exception ("Unhandled case");
2289                 }
2290                 
2291                 // structure used to hold blocks of keys while calculating table switch
2292                 class KeyBlock : IComparable
2293                 {
2294                         public KeyBlock (long _nFirst)
2295                         {
2296                                 nFirst = nLast = _nFirst;
2297                         }
2298                         public long nFirst;
2299                         public long nLast;
2300                         public ArrayList rgKeys = null;
2301                         // how many items are in the bucket
2302                         public int Size = 1;
2303                         public int Length
2304                         {
2305                                 get { return (int) (nLast - nFirst + 1); }
2306                         }
2307                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2308                         {
2309                                 return kbLast.nLast - kbFirst.nFirst + 1;
2310                         }
2311                         public int CompareTo (object obj)
2312                         {
2313                                 KeyBlock kb = (KeyBlock) obj;
2314                                 int nLength = Length;
2315                                 int nLengthOther = kb.Length;
2316                                 if (nLengthOther == nLength)
2317                                         return (int) (kb.nFirst - nFirst);
2318                                 return nLength - nLengthOther;
2319                         }
2320                 }
2321
2322                 /// <summary>
2323                 /// This method emits code for a lookup-based switch statement (non-string)
2324                 /// Basically it groups the cases into blocks that are at least half full,
2325                 /// and then spits out individual lookup opcodes for each block.
2326                 /// It emits the longest blocks first, and short blocks are just
2327                 /// handled with direct compares.
2328                 /// </summary>
2329                 /// <param name="ec"></param>
2330                 /// <param name="val"></param>
2331                 /// <returns></returns>
2332                 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2333                 {
2334                         int cElements = Elements.Count;
2335                         object [] rgKeys = new object [cElements];
2336                         Elements.Keys.CopyTo (rgKeys, 0);
2337                         Array.Sort (rgKeys);
2338
2339                         // initialize the block list with one element per key
2340                         ArrayList rgKeyBlocks = new ArrayList ();
2341                         foreach (object key in rgKeys)
2342                                 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2343
2344                         KeyBlock kbCurr;
2345                         // iteratively merge the blocks while they are at least half full
2346                         // there's probably a really cool way to do this with a tree...
2347                         while (rgKeyBlocks.Count > 1)
2348                         {
2349                                 ArrayList rgKeyBlocksNew = new ArrayList ();
2350                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2351                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2352                                 {
2353                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2354                                         if ((kbCurr.Size + kb.Size) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
2355                                         {
2356                                                 // merge blocks
2357                                                 kbCurr.nLast = kb.nLast;
2358                                                 kbCurr.Size += kb.Size;
2359                                         }
2360                                         else
2361                                         {
2362                                                 // start a new block
2363                                                 rgKeyBlocksNew.Add (kbCurr);
2364                                                 kbCurr = kb;
2365                                         }
2366                                 }
2367                                 rgKeyBlocksNew.Add (kbCurr);
2368                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2369                                         break;
2370                                 rgKeyBlocks = rgKeyBlocksNew;
2371                         }
2372
2373                         // initialize the key lists
2374                         foreach (KeyBlock kb in rgKeyBlocks)
2375                                 kb.rgKeys = new ArrayList ();
2376
2377                         // fill the key lists
2378                         int iBlockCurr = 0;
2379                         if (rgKeyBlocks.Count > 0) {
2380                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2381                                 foreach (object key in rgKeys)
2382                                 {
2383                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2384                                                 System.Convert.ToInt64 (key) > kbCurr.nLast;
2385                                         if (fNextBlock)
2386                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2387                                         kbCurr.rgKeys.Add (key);
2388                                 }
2389                         }
2390
2391                         // sort the blocks so we can tackle the largest ones first
2392                         rgKeyBlocks.Sort ();
2393
2394                         // okay now we can start...
2395                         ILGenerator ig = ec.ig;
2396                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
2397                         Label lblDefault = ig.DefineLabel ();
2398
2399                         Type typeKeys = null;
2400                         if (rgKeys.Length > 0)
2401                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
2402
2403                         Type compare_type;
2404                         
2405                         if (TypeManager.IsEnumType (SwitchType))
2406                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2407                         else
2408                                 compare_type = SwitchType;
2409                         
2410                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2411                         {
2412                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2413                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2414                                 if (kb.Length <= 2)
2415                                 {
2416                                         foreach (object key in kb.rgKeys)
2417                                         {
2418                                                 ig.Emit (OpCodes.Ldloc, val);
2419                                                 EmitObjectInteger (ig, key);
2420                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
2421                                                 ig.Emit (OpCodes.Beq, sl.ILLabel);
2422                                         }
2423                                 }
2424                                 else
2425                                 {
2426                                         // TODO: if all the keys in the block are the same and there are
2427                                         //       no gaps/defaults then just use a range-check.
2428                                         if (compare_type == TypeManager.int64_type ||
2429                                                 compare_type == TypeManager.uint64_type)
2430                                         {
2431                                                 // TODO: optimize constant/I4 cases
2432
2433                                                 // check block range (could be > 2^31)
2434                                                 ig.Emit (OpCodes.Ldloc, val);
2435                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2436                                                 ig.Emit (OpCodes.Blt, lblDefault);
2437                                                 ig.Emit (OpCodes.Ldloc, val);
2438                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2439                                                 ig.Emit (OpCodes.Bgt, lblDefault);
2440
2441                                                 // normalize range
2442                                                 ig.Emit (OpCodes.Ldloc, val);
2443                                                 if (kb.nFirst != 0)
2444                                                 {
2445                                                         EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2446                                                         ig.Emit (OpCodes.Sub);
2447                                                 }
2448                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
2449                                         }
2450                                         else
2451                                         {
2452                                                 // normalize range
2453                                                 ig.Emit (OpCodes.Ldloc, val);
2454                                                 int nFirst = (int) kb.nFirst;
2455                                                 if (nFirst > 0)
2456                                                 {
2457                                                         IntConstant.EmitInt (ig, nFirst);
2458                                                         ig.Emit (OpCodes.Sub);
2459                                                 }
2460                                                 else if (nFirst < 0)
2461                                                 {
2462                                                         IntConstant.EmitInt (ig, -nFirst);
2463                                                         ig.Emit (OpCodes.Add);
2464                                                 }
2465                                         }
2466
2467                                         // first, build the list of labels for the switch
2468                                         int iKey = 0;
2469                                         int cJumps = kb.Length;
2470                                         Label [] rgLabels = new Label [cJumps];
2471                                         for (int iJump = 0; iJump < cJumps; iJump++)
2472                                         {
2473                                                 object key = kb.rgKeys [iKey];
2474                                                 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2475                                                 {
2476                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
2477                                                         rgLabels [iJump] = sl.ILLabel;
2478                                                         iKey++;
2479                                                 }
2480                                                 else
2481                                                         rgLabels [iJump] = lblDefault;
2482                                         }
2483                                         // emit the switch opcode
2484                                         ig.Emit (OpCodes.Switch, rgLabels);
2485                                 }
2486
2487                                 // mark the default for this block
2488                                 if (iBlock != 0)
2489                                         ig.MarkLabel (lblDefault);
2490                         }
2491
2492                         // TODO: find the default case and emit it here,
2493                         //       to prevent having to do the following jump.
2494                         //       make sure to mark other labels in the default section
2495
2496                         // the last default just goes to the end
2497                         ig.Emit (OpCodes.Br, lblDefault);
2498
2499                         // now emit the code for the sections
2500                         bool fFoundDefault = false;
2501                         foreach (SwitchSection ss in Sections)
2502                         {
2503                                 foreach (SwitchLabel sl in ss.Labels)
2504                                 {
2505                                         ig.MarkLabel (sl.ILLabel);
2506                                         ig.MarkLabel (sl.ILLabelCode);
2507                                         if (sl.Label == null)
2508                                         {
2509                                                 ig.MarkLabel (lblDefault);
2510                                                 fFoundDefault = true;
2511                                         }
2512                                 }
2513                                 ss.Block.Emit (ec);
2514                                 //ig.Emit (OpCodes.Br, lblEnd);
2515                         }
2516                         
2517                         if (!fFoundDefault) {
2518                                 ig.MarkLabel (lblDefault);
2519                         }
2520                         ig.MarkLabel (lblEnd);
2521                 }
2522                 //
2523                 // This simple emit switch works, but does not take advantage of the
2524                 // `switch' opcode. 
2525                 // TODO: remove non-string logic from here
2526                 // TODO: binary search strings?
2527                 //
2528                 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2529                 {
2530                         ILGenerator ig = ec.ig;
2531                         Label end_of_switch = ig.DefineLabel ();
2532                         Label next_test = ig.DefineLabel ();
2533                         Label null_target = ig.DefineLabel ();
2534                         bool default_found = false;
2535                         bool first_test = true;
2536                         bool pending_goto_end = false;
2537                         bool null_found;
2538                         bool default_at_end = false;
2539                         
2540                         ig.Emit (OpCodes.Ldloc, val);
2541                         
2542                         if (Elements.Contains (NullLiteral.Null)){
2543                                 ig.Emit (OpCodes.Brfalse, null_target);
2544                         } else
2545                                 ig.Emit (OpCodes.Brfalse, default_target);
2546                         
2547                         ig.Emit (OpCodes.Ldloc, val);
2548                         ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2549                         ig.Emit (OpCodes.Stloc, val);
2550                 
2551                         int section_count = Sections.Count;
2552                         for (int section = 0; section < section_count; section++){
2553                                 SwitchSection ss = (SwitchSection) Sections [section];
2554                                 Label sec_begin = ig.DefineLabel ();
2555
2556                                 if (pending_goto_end)
2557                                         ig.Emit (OpCodes.Br, end_of_switch);
2558
2559                                 int label_count = ss.Labels.Count;
2560                                 bool mark_default = false;
2561                                 null_found = false;
2562                                 for (int label = 0; label < label_count; label++){
2563                                         SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2564                                         ig.MarkLabel (sl.ILLabel);
2565                                         
2566                                         if (!first_test){
2567                                                 ig.MarkLabel (next_test);
2568                                                 next_test = ig.DefineLabel ();
2569                                         }
2570                                         //
2571                                         // If we are the default target
2572                                         //
2573                                         if (sl.Label == null){
2574                                                 if (label+1 == label_count)
2575                                                         default_at_end = true;
2576                                                 mark_default = true;
2577                                                 default_found = true;
2578                                         } else {
2579                                                 object lit = sl.Converted;
2580
2581                                                 if (lit is NullLiteral){
2582                                                         null_found = true;
2583                                                         if (label_count == 1)
2584                                                                 ig.Emit (OpCodes.Br, next_test);
2585                                                         continue;
2586                                                                               
2587                                                 }
2588                                                 StringConstant str = (StringConstant) lit;
2589                                                 
2590                                                 ig.Emit (OpCodes.Ldloc, val);
2591                                                 ig.Emit (OpCodes.Ldstr, str.Value);
2592                                                 if (label_count == 1)
2593                                                         ig.Emit (OpCodes.Bne_Un, next_test);
2594                                                 else {
2595                                                         if (label+1 == label_count)
2596                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
2597                                                         else
2598                                                                 ig.Emit (OpCodes.Beq, sec_begin);
2599                                                 }
2600                                         }
2601                                 }
2602                                 if (null_found)
2603                                         ig.MarkLabel (null_target);
2604                                 ig.MarkLabel (sec_begin);
2605                                 foreach (SwitchLabel sl in ss.Labels)
2606                                         ig.MarkLabel (sl.ILLabelCode);
2607
2608                                 if (mark_default)
2609                                         ig.MarkLabel (default_target);
2610                                 ss.Block.Emit (ec);
2611                                 pending_goto_end = !ss.Block.HasRet;
2612                                 first_test = false;
2613                         }
2614                         ig.MarkLabel (next_test);
2615                         if (default_found){
2616                                 if (!default_at_end)
2617                                         ig.Emit (OpCodes.Br, default_target);
2618                         } else 
2619                                 ig.MarkLabel (default_target);
2620                         ig.MarkLabel (end_of_switch);
2621                 }
2622
2623                 public override bool Resolve (EmitContext ec)
2624                 {
2625                         Expr = Expr.Resolve (ec);
2626                         if (Expr == null)
2627                                 return false;
2628
2629                         new_expr = SwitchGoverningType (ec, Expr.Type);
2630                         if (new_expr == null){
2631                                 Report.Error (151, loc, "An integer type or string was expected for switch");
2632                                 return false;
2633                         }
2634
2635                         // Validate switch.
2636                         SwitchType = new_expr.Type;
2637
2638                         if (!CheckSwitch (ec))
2639                                 return false;
2640
2641                         Switch old_switch = ec.Switch;
2642                         ec.Switch = this;
2643                         ec.Switch.SwitchType = SwitchType;
2644
2645                         Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2646                         ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2647
2648                         bool first = true;
2649                         foreach (SwitchSection ss in Sections){
2650                                 if (!first)
2651                                         ec.CurrentBranching.CreateSibling (
2652                                                 null, FlowBranching.SiblingType.SwitchSection);
2653                                 else
2654                                         first = false;
2655
2656                                 if (ss.Block.Resolve (ec) != true)
2657                                         return false;
2658                         }
2659
2660
2661                         if (!got_default)
2662                                 ec.CurrentBranching.CreateSibling (
2663                                         null, FlowBranching.SiblingType.SwitchSection);
2664
2665                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2666                         ec.Switch = old_switch;
2667
2668                         Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2669                                       reachability);
2670
2671                         return true;
2672                 }
2673                 
2674                 protected override void DoEmit (EmitContext ec)
2675                 {
2676                         // Store variable for comparission purposes
2677                         LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2678                         new_expr.Emit (ec);
2679                         ec.ig.Emit (OpCodes.Stloc, value);
2680
2681                         ILGenerator ig = ec.ig;
2682
2683                         default_target = ig.DefineLabel ();
2684
2685                         //
2686                         // Setup the codegen context
2687                         //
2688                         Label old_end = ec.LoopEnd;
2689                         Switch old_switch = ec.Switch;
2690                         
2691                         ec.LoopEnd = ig.DefineLabel ();
2692                         ec.Switch = this;
2693
2694                         // Emit Code.
2695                         if (SwitchType == TypeManager.string_type)
2696                                 SimpleSwitchEmit (ec, value);
2697                         else
2698                                 TableSwitchEmit (ec, value);
2699
2700                         // Restore context state. 
2701                         ig.MarkLabel (ec.LoopEnd);
2702
2703                         //
2704                         // Restore the previous context
2705                         //
2706                         ec.LoopEnd = old_end;
2707                         ec.Switch = old_switch;
2708                 }
2709         }
2710
2711         public class Lock : Statement {
2712                 Expression expr;
2713                 Statement Statement;
2714                         
2715                 public Lock (Expression expr, Statement stmt, Location l)
2716                 {
2717                         this.expr = expr;
2718                         Statement = stmt;
2719                         loc = l;
2720                 }
2721
2722                 public override bool Resolve (EmitContext ec)
2723                 {
2724                         expr = expr.Resolve (ec);
2725                         if (expr == null)
2726                                 return false;
2727
2728                         if (expr.Type.IsValueType){
2729                                 Error (185, "lock statement requires the expression to be " +
2730                                        " a reference type (type is: `{0}'",
2731                                        TypeManager.CSharpName (expr.Type));
2732                                 return false;
2733                         }
2734
2735                         ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
2736                         bool ok = Statement.Resolve (ec);
2737                         ec.EndFlowBranching ();
2738
2739                         return ok;
2740                 }
2741                 
2742                 protected override void DoEmit (EmitContext ec)
2743                 {
2744                         Type type = expr.Type;
2745                         
2746                         ILGenerator ig = ec.ig;
2747                         LocalBuilder temp = ig.DeclareLocal (type);
2748                                 
2749                         expr.Emit (ec);
2750                         ig.Emit (OpCodes.Dup);
2751                         ig.Emit (OpCodes.Stloc, temp);
2752                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2753
2754                         // try
2755                         ig.BeginExceptionBlock ();
2756                         Label finish = ig.DefineLabel ();
2757                         Statement.Emit (ec);
2758                         // ig.Emit (OpCodes.Leave, finish);
2759
2760                         ig.MarkLabel (finish);
2761                         
2762                         // finally
2763                         ig.BeginFinallyBlock ();
2764                         ig.Emit (OpCodes.Ldloc, temp);
2765                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2766                         ig.EndExceptionBlock ();
2767                 }
2768         }
2769
2770         public class Unchecked : Statement {
2771                 public readonly Block Block;
2772                 
2773                 public Unchecked (Block b)
2774                 {
2775                         Block = b;
2776                         b.Unchecked = true;
2777                 }
2778
2779                 public override bool Resolve (EmitContext ec)
2780                 {
2781                         bool previous_state = ec.CheckState;
2782                         bool previous_state_const = ec.ConstantCheckState;
2783
2784                         ec.CheckState = false;
2785                         ec.ConstantCheckState = false;
2786                         bool ret = Block.Resolve (ec);
2787                         ec.CheckState = previous_state;
2788                         ec.ConstantCheckState = previous_state_const;
2789
2790                         return ret;
2791                 }
2792                 
2793                 protected override void DoEmit (EmitContext ec)
2794                 {
2795                         bool previous_state = ec.CheckState;
2796                         bool previous_state_const = ec.ConstantCheckState;
2797                         
2798                         ec.CheckState = false;
2799                         ec.ConstantCheckState = false;
2800                         Block.Emit (ec);
2801                         ec.CheckState = previous_state;
2802                         ec.ConstantCheckState = previous_state_const;
2803                 }
2804         }
2805
2806         public class Checked : Statement {
2807                 public readonly Block Block;
2808                 
2809                 public Checked (Block b)
2810                 {
2811                         Block = b;
2812                         b.Unchecked = false;
2813                 }
2814
2815                 public override bool Resolve (EmitContext ec)
2816                 {
2817                         bool previous_state = ec.CheckState;
2818                         bool previous_state_const = ec.ConstantCheckState;
2819                         
2820                         ec.CheckState = true;
2821                         ec.ConstantCheckState = true;
2822                         bool ret = Block.Resolve (ec);
2823                         ec.CheckState = previous_state;
2824                         ec.ConstantCheckState = previous_state_const;
2825
2826                         return ret;
2827                 }
2828
2829                 protected override void DoEmit (EmitContext ec)
2830                 {
2831                         bool previous_state = ec.CheckState;
2832                         bool previous_state_const = ec.ConstantCheckState;
2833                         
2834                         ec.CheckState = true;
2835                         ec.ConstantCheckState = true;
2836                         Block.Emit (ec);
2837                         ec.CheckState = previous_state;
2838                         ec.ConstantCheckState = previous_state_const;
2839                 }
2840         }
2841
2842         public class Unsafe : Statement {
2843                 public readonly Block Block;
2844
2845                 public Unsafe (Block b)
2846                 {
2847                         Block = b;
2848                 }
2849
2850                 public override bool Resolve (EmitContext ec)
2851                 {
2852                         bool previous_state = ec.InUnsafe;
2853                         bool val;
2854                         
2855                         ec.InUnsafe = true;
2856                         val = Block.Resolve (ec);
2857                         ec.InUnsafe = previous_state;
2858
2859                         return val;
2860                 }
2861                 
2862                 protected override void DoEmit (EmitContext ec)
2863                 {
2864                         bool previous_state = ec.InUnsafe;
2865                         
2866                         ec.InUnsafe = true;
2867                         Block.Emit (ec);
2868                         ec.InUnsafe = previous_state;
2869                 }
2870         }
2871
2872         // 
2873         // Fixed statement
2874         //
2875         public class Fixed : Statement {
2876                 Expression type;
2877                 ArrayList declarators;
2878                 Statement statement;
2879                 Type expr_type;
2880                 FixedData[] data;
2881                 bool has_ret;
2882
2883                 struct FixedData {
2884                         public bool is_object;
2885                         public LocalInfo vi;
2886                         public Expression expr;
2887                         public Expression converted;
2888                 }                       
2889
2890                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2891                 {
2892                         this.type = type;
2893                         declarators = decls;
2894                         statement = stmt;
2895                         loc = l;
2896                 }
2897
2898                 public override bool Resolve (EmitContext ec)
2899                 {
2900                         if (!ec.InUnsafe){
2901                                 Expression.UnsafeError (loc);
2902                                 return false;
2903                         }
2904                         
2905                         expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2906                         if (expr_type == null)
2907                                 return false;
2908
2909                         CheckObsolete (expr_type);
2910
2911                         if (ec.RemapToProxy){
2912                                 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2913                                 return false;
2914                         }
2915                         
2916                         data = new FixedData [declarators.Count];
2917
2918                         if (!expr_type.IsPointer){
2919                                 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2920                                 return false;
2921                         }
2922                         
2923                         int i = 0;
2924                         foreach (Pair p in declarators){
2925                                 LocalInfo vi = (LocalInfo) p.First;
2926                                 Expression e = (Expression) p.Second;
2927
2928                                 vi.VariableInfo = null;
2929                                 vi.ReadOnly = true;
2930
2931                                 //
2932                                 // The rules for the possible declarators are pretty wise,
2933                                 // but the production on the grammar is more concise.
2934                                 //
2935                                 // So we have to enforce these rules here.
2936                                 //
2937                                 // We do not resolve before doing the case 1 test,
2938                                 // because the grammar is explicit in that the token &
2939                                 // is present, so we need to test for this particular case.
2940                                 //
2941
2942                                 if (e is Cast){
2943                                         Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2944                                         return false;
2945                                 }
2946                                 
2947                                 //
2948                                 // Case 1: & object.
2949                                 //
2950                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2951                                         Expression child = ((Unary) e).Expr;
2952
2953                                         vi.MakePinned ();
2954                                         if (child is ParameterReference || child is LocalVariableReference){
2955                                                 Report.Error (
2956                                                         213, loc, 
2957                                                         "No need to use fixed statement for parameters or " +
2958                                                         "local variable declarations (address is already " +
2959                                                         "fixed)");
2960                                                 return false;
2961                                         }
2962
2963                                         ec.InFixedInitializer = true;
2964                                         e = e.Resolve (ec);
2965                                         ec.InFixedInitializer = false;
2966                                         if (e == null)
2967                                                 return false;
2968
2969                                         child = ((Unary) e).Expr;
2970                                         
2971                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
2972                                                 return false;
2973
2974                                         data [i].is_object = true;
2975                                         data [i].expr = e;
2976                                         data [i].converted = null;
2977                                         data [i].vi = vi;
2978                                         i++;
2979
2980                                         continue;
2981                                 }
2982
2983                                 ec.InFixedInitializer = true;
2984                                 e = e.Resolve (ec);
2985                                 ec.InFixedInitializer = false;
2986                                 if (e == null)
2987                                         return false;
2988
2989                                 //
2990                                 // Case 2: Array
2991                                 //
2992                                 if (e.Type.IsArray){
2993                                         Type array_type = TypeManager.GetElementType (e.Type);
2994                                         
2995                                         vi.MakePinned ();
2996                                         //
2997                                         // Provided that array_type is unmanaged,
2998                                         //
2999                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
3000                                                 return false;
3001
3002                                         //
3003                                         // and T* is implicitly convertible to the
3004                                         // pointer type given in the fixed statement.
3005                                         //
3006                                         ArrayPtr array_ptr = new ArrayPtr (e, loc);
3007                                         
3008                                         Expression converted = Convert.ImplicitConversionRequired (
3009                                                 ec, array_ptr, vi.VariableType, loc);
3010                                         if (converted == null)
3011                                                 return false;
3012
3013                                         data [i].is_object = false;
3014                                         data [i].expr = e;
3015                                         data [i].converted = converted;
3016                                         data [i].vi = vi;
3017                                         i++;
3018
3019                                         continue;
3020                                 }
3021
3022                                 //
3023                                 // Case 3: string
3024                                 //
3025                                 if (e.Type == TypeManager.string_type){
3026                                         data [i].is_object = false;
3027                                         data [i].expr = e;
3028                                         data [i].converted = null;
3029                                         data [i].vi = vi;
3030                                         i++;
3031                                         continue;
3032                                 }
3033
3034                                 //
3035                                 // For other cases, flag a `this is already fixed expression'
3036                                 //
3037                                 if (e is LocalVariableReference || e is ParameterReference ||
3038                                     Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3039                                     
3040                                         Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3041                                         return false;
3042                                 }
3043
3044                                 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3045                                 return false;
3046                         }
3047
3048                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3049
3050                         if (!statement.Resolve (ec)) {
3051                                 ec.KillFlowBranching ();
3052                                 return false;
3053                         }
3054
3055                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3056                         has_ret = reachability.IsUnreachable;
3057
3058                         return true;
3059                 }
3060                 
3061                 protected override void DoEmit (EmitContext ec)
3062                 {
3063                         ILGenerator ig = ec.ig;
3064
3065                         LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3066                         
3067                         for (int i = 0; i < data.Length; i++) {
3068                                 LocalInfo vi = data [i].vi;
3069
3070                                 //
3071                                 // Case 1: & object.
3072                                 //
3073                                 if (data [i].is_object) {
3074                                         //
3075                                         // Store pointer in pinned location
3076                                         //
3077                                         data [i].expr.Emit (ec);
3078                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3079                                         clear_list [i] = vi.LocalBuilder;
3080                                         continue;
3081                                 }
3082
3083                                 //
3084                                 // Case 2: Array
3085                                 //
3086                                 if (data [i].expr.Type.IsArray){
3087                                         //
3088                                         // Store pointer in pinned location
3089                                         //
3090                                         data [i].converted.Emit (ec);
3091                                         
3092                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3093                                         clear_list [i] = vi.LocalBuilder;
3094                                         continue;
3095                                 }
3096
3097                                 //
3098                                 // Case 3: string
3099                                 //
3100                                 if (data [i].expr.Type == TypeManager.string_type){
3101                                         LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3102                                         TypeManager.MakePinned (pinned_string);
3103                                         clear_list [i] = pinned_string;
3104                                         
3105                                         data [i].expr.Emit (ec);
3106                                         ig.Emit (OpCodes.Stloc, pinned_string);
3107
3108                                         Expression sptr = new StringPtr (pinned_string, loc);
3109                                         Expression converted = Convert.ImplicitConversionRequired (
3110                                                 ec, sptr, vi.VariableType, loc);
3111                                         
3112                                         if (converted == null)
3113                                                 continue;
3114
3115                                         converted.Emit (ec);
3116                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3117                                 }
3118                         }
3119
3120                         statement.Emit (ec);
3121
3122                         if (has_ret)
3123                                 return;
3124
3125                         //
3126                         // Clear the pinned variable
3127                         //
3128                         for (int i = 0; i < data.Length; i++) {
3129                                 if (data [i].is_object || data [i].expr.Type.IsArray) {
3130                                         ig.Emit (OpCodes.Ldc_I4_0);
3131                                         ig.Emit (OpCodes.Conv_U);
3132                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3133                                 } else if (data [i].expr.Type == TypeManager.string_type){
3134                                         ig.Emit (OpCodes.Ldnull);
3135                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3136                                 }
3137                         }
3138                 }
3139         }
3140         
3141         public class Catch: Statement {
3142                 public readonly string Name;
3143                 public readonly Block  Block;
3144
3145                 Expression type_expr;
3146                 Type type;
3147                 
3148                 public Catch (Expression type, string name, Block block, Location l)
3149                 {
3150                         type_expr = type;
3151                         Name = name;
3152                         Block = block;
3153                         loc = l;
3154                 }
3155
3156                 public Type CatchType {
3157                         get {
3158                                 return type;
3159                         }
3160                 }
3161
3162                 public bool IsGeneral {
3163                         get {
3164                                 return type_expr == null;
3165                         }
3166                 }
3167
3168                 protected override void DoEmit(EmitContext ec)
3169                 {
3170                 }
3171
3172                 public override bool Resolve (EmitContext ec)
3173                 {
3174                         if (type_expr != null) {
3175                                 type = ec.DeclSpace.ResolveType (type_expr, false, loc);
3176                                 if (type == null)
3177                                         return false;
3178
3179                                 CheckObsolete (type);
3180
3181                                 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3182                                         Error (155, "The type caught or thrown must be derived from System.Exception");
3183                                         return false;
3184                                 }
3185                         } else
3186                                 type = null;
3187
3188                         return Block.Resolve (ec);
3189                 }
3190         }
3191
3192         public class Try : Statement {
3193                 public readonly Block Fini, Block;
3194                 public readonly ArrayList Specific;
3195                 public readonly Catch General;
3196                 
3197                 //
3198                 // specific, general and fini might all be null.
3199                 //
3200                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3201                 {
3202                         if (specific == null && general == null){
3203                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3204                         }
3205                         
3206                         this.Block = block;
3207                         this.Specific = specific;
3208                         this.General = general;
3209                         this.Fini = fini;
3210                         loc = l;
3211                 }
3212
3213                 public override bool Resolve (EmitContext ec)
3214                 {
3215                         bool ok = true;
3216                         
3217                         ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3218
3219                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3220
3221                         if (!Block.Resolve (ec))
3222                                 ok = false;
3223
3224                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3225
3226                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
3227
3228                         Type[] prevCatches = new Type [Specific.Count];
3229                         int last_index = 0;
3230                         foreach (Catch c in Specific){
3231                                 ec.CurrentBranching.CreateSibling (
3232                                         c.Block, FlowBranching.SiblingType.Catch);
3233
3234                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3235
3236                                 if (c.Name != null) {
3237                                         LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3238                                         if (vi == null)
3239                                                 throw new Exception ();
3240
3241                                         vi.VariableInfo = null;
3242                                 }
3243
3244                                 if (!c.Resolve (ec))
3245                                         return false;
3246
3247                                 Type resolvedType = c.CatchType;
3248                                 for (int ii = 0; ii < last_index; ++ii) {
3249                                         if (resolvedType.IsSubclassOf (prevCatches [ii])) {
3250                                                 Report.Error_T (160, c.loc, prevCatches [ii].FullName);
3251                                                 return false;
3252                                         }
3253                                 }
3254
3255                                 prevCatches [last_index++] = resolvedType;
3256                         }
3257
3258                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3259
3260                         if (General != null){
3261                                 ec.CurrentBranching.CreateSibling (
3262                                         General.Block, FlowBranching.SiblingType.Catch);
3263
3264                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3265
3266                                 if (!General.Resolve (ec))
3267                                         ok = false;
3268                         }
3269
3270                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3271
3272                         if (Fini != null) {
3273                                 if (ok)
3274                                         ec.CurrentBranching.CreateSibling (
3275                                                 Fini, FlowBranching.SiblingType.Finally);
3276
3277                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3278
3279                                 if (!Fini.Resolve (ec))
3280                                         ok = false;
3281                         }
3282
3283                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3284
3285                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3286
3287                         Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3288
3289                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3290                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
3291                                 // to the end of the finally block.  This is a problem if `returns'
3292                                 // is true since we may jump to a point after the end of the method.
3293                                 // As a workaround, emit an explicit ret here.
3294                                 ec.NeedReturnLabel ();
3295                         }
3296
3297                         return ok;
3298                 }
3299                 
3300                 protected override void DoEmit (EmitContext ec)
3301                 {
3302                         ILGenerator ig = ec.ig;
3303                         Label finish = ig.DefineLabel ();;
3304
3305                         ig.BeginExceptionBlock ();
3306                         Block.Emit (ec);
3307
3308                         //
3309                         // System.Reflection.Emit provides this automatically:
3310                         // ig.Emit (OpCodes.Leave, finish);
3311
3312                         foreach (Catch c in Specific){
3313                                 LocalInfo vi;
3314                                 
3315                                 ig.BeginCatchBlock (c.CatchType);
3316
3317                                 if (c.Name != null){
3318                                         vi = c.Block.GetLocalInfo (c.Name);
3319                                         if (vi == null)
3320                                                 throw new Exception ("Variable does not exist in this block");
3321
3322                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3323                                 } else
3324                                         ig.Emit (OpCodes.Pop);
3325                                 
3326                                 c.Block.Emit (ec);
3327                         }
3328
3329                         if (General != null){
3330                                 ig.BeginCatchBlock (TypeManager.object_type);
3331                                 ig.Emit (OpCodes.Pop);
3332                                 General.Block.Emit (ec);
3333                         }
3334
3335                         ig.MarkLabel (finish);
3336                         if (Fini != null){
3337                                 ig.BeginFinallyBlock ();
3338                                 Fini.Emit (ec);
3339                         }
3340                         
3341                         ig.EndExceptionBlock ();
3342                 }
3343         }
3344
3345         public class Using : Statement {
3346                 object expression_or_block;
3347                 Statement Statement;
3348                 ArrayList var_list;
3349                 Expression expr;
3350                 Type expr_type;
3351                 Expression conv;
3352                 Expression [] converted_vars;
3353                 ExpressionStatement [] assign;
3354                 
3355                 public Using (object expression_or_block, Statement stmt, Location l)
3356                 {
3357                         this.expression_or_block = expression_or_block;
3358                         Statement = stmt;
3359                         loc = l;
3360                 }
3361
3362                 //
3363                 // Resolves for the case of using using a local variable declaration.
3364                 //
3365                 bool ResolveLocalVariableDecls (EmitContext ec)
3366                 {
3367                         bool need_conv = false;
3368                         expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3369                         int i = 0;
3370
3371                         if (expr_type == null)
3372                                 return false;
3373
3374                         //
3375                         // The type must be an IDisposable or an implicit conversion
3376                         // must exist.
3377                         //
3378                         converted_vars = new Expression [var_list.Count];
3379                         assign = new ExpressionStatement [var_list.Count];
3380                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3381                                 foreach (DictionaryEntry e in var_list){
3382                                         Expression var = (Expression) e.Key;
3383
3384                                         var = var.ResolveLValue (ec, new EmptyExpression ());
3385                                         if (var == null)
3386                                                 return false;
3387                                         
3388                                         converted_vars [i] = Convert.ImplicitConversionRequired (
3389                                                 ec, var, TypeManager.idisposable_type, loc);
3390
3391                                         if (converted_vars [i] == null)
3392                                                 return false;
3393                                         i++;
3394                                 }
3395                                 need_conv = true;
3396                         }
3397
3398                         i = 0;
3399                         foreach (DictionaryEntry e in var_list){
3400                                 LocalVariableReference var = (LocalVariableReference) e.Key;
3401                                 Expression new_expr = (Expression) e.Value;
3402                                 Expression a;
3403
3404                                 a = new Assign (var, new_expr, loc);
3405                                 a = a.Resolve (ec);
3406                                 if (a == null)
3407                                         return false;
3408
3409                                 if (!need_conv)
3410                                         converted_vars [i] = var;
3411                                 assign [i] = (ExpressionStatement) a;
3412                                 i++;
3413                         }
3414
3415                         return true;
3416                 }
3417
3418                 bool ResolveExpression (EmitContext ec)
3419                 {
3420                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3421                                 conv = Convert.ImplicitConversionRequired (
3422                                         ec, expr, TypeManager.idisposable_type, loc);
3423
3424                                 if (conv == null)
3425                                         return false;
3426                         }
3427
3428                         return true;
3429                 }
3430                 
3431                 //
3432                 // Emits the code for the case of using using a local variable declaration.
3433                 //
3434                 bool EmitLocalVariableDecls (EmitContext ec)
3435                 {
3436                         ILGenerator ig = ec.ig;
3437                         int i = 0;
3438
3439                         for (i = 0; i < assign.Length; i++) {
3440                                 assign [i].EmitStatement (ec);
3441                                 
3442                                 ig.BeginExceptionBlock ();
3443                         }
3444                         Statement.Emit (ec);
3445
3446                         var_list.Reverse ();
3447                         foreach (DictionaryEntry e in var_list){
3448                                 LocalVariableReference var = (LocalVariableReference) e.Key;
3449                                 Label skip = ig.DefineLabel ();
3450                                 i--;
3451                                 
3452                                 ig.BeginFinallyBlock ();
3453
3454                                 if (!var.Type.IsValueType) {
3455                                         var.Emit (ec);
3456                                         ig.Emit (OpCodes.Brfalse, skip);
3457                                         converted_vars [i].Emit (ec);
3458                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3459                                 } else {
3460                                         Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3461
3462                                         if (!(ml is MethodGroupExpr)) {
3463                                                 var.Emit (ec);
3464                                                 ig.Emit (OpCodes.Box, var.Type);
3465                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3466                                         } else {
3467                                                 MethodInfo mi = null;
3468
3469                                                 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3470                                                         if (mk.GetParameters().Length == 0) {
3471                                                                 mi = mk;
3472                                                                 break;
3473                                                         }
3474                                                 }
3475
3476                                                 if (mi == null) {
3477                                                         Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3478                                                         return false;
3479                                                 }
3480
3481                                                 var.AddressOf (ec, AddressOp.Load);
3482                                                 ig.Emit (OpCodes.Call, mi);
3483                                         }
3484                                 }
3485
3486                                 ig.MarkLabel (skip);
3487                                 ig.EndExceptionBlock ();
3488                         }
3489
3490                         return false;
3491                 }
3492
3493                 bool EmitExpression (EmitContext ec)
3494                 {
3495                         //
3496                         // Make a copy of the expression and operate on that.
3497                         //
3498                         ILGenerator ig = ec.ig;
3499                         LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3500                         if (conv != null)
3501                                 conv.Emit (ec);
3502                         else
3503                                 expr.Emit (ec);
3504                         ig.Emit (OpCodes.Stloc, local_copy);
3505
3506                         ig.BeginExceptionBlock ();
3507                         Statement.Emit (ec);
3508                         
3509                         Label skip = ig.DefineLabel ();
3510                         ig.BeginFinallyBlock ();
3511                         ig.Emit (OpCodes.Ldloc, local_copy);
3512                         ig.Emit (OpCodes.Brfalse, skip);
3513                         ig.Emit (OpCodes.Ldloc, local_copy);
3514                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3515                         ig.MarkLabel (skip);
3516                         ig.EndExceptionBlock ();
3517
3518                         return false;
3519                 }
3520                 
3521                 public override bool Resolve (EmitContext ec)
3522                 {
3523                         if (expression_or_block is DictionaryEntry){
3524                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3525                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3526
3527                                 if (!ResolveLocalVariableDecls (ec))
3528                                         return false;
3529
3530                         } else if (expression_or_block is Expression){
3531                                 expr = (Expression) expression_or_block;
3532
3533                                 expr = expr.Resolve (ec);
3534                                 if (expr == null)
3535                                         return false;
3536
3537                                 expr_type = expr.Type;
3538
3539                                 if (!ResolveExpression (ec))
3540                                         return false;
3541                         }
3542
3543                         ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3544
3545                         bool ok = Statement.Resolve (ec);
3546
3547                         if (!ok) {
3548                                 ec.KillFlowBranching ();
3549                                 return false;
3550                         }
3551                                         
3552                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3553
3554                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3555                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
3556                                 // to the end of the finally block.  This is a problem if `returns'
3557                                 // is true since we may jump to a point after the end of the method.
3558                                 // As a workaround, emit an explicit ret here.
3559                                 ec.NeedReturnLabel ();
3560                         }
3561
3562                         return true;
3563                 }
3564                 
3565                 protected override void DoEmit (EmitContext ec)
3566                 {
3567                         if (expression_or_block is DictionaryEntry)
3568                                 EmitLocalVariableDecls (ec);
3569                         else if (expression_or_block is Expression)
3570                                 EmitExpression (ec);
3571                 }
3572         }
3573
3574         /// <summary>
3575         ///   Implementation of the foreach C# statement
3576         /// </summary>
3577         public class Foreach : Statement {
3578                 Expression type;
3579                 Expression variable;
3580                 Expression expr;
3581                 Statement statement;
3582                 ForeachHelperMethods hm;
3583                 Expression empty, conv;
3584                 Type array_type, element_type;
3585                 Type var_type;
3586                 
3587                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3588                                 Statement stmt, Location l)
3589                 {
3590                         this.type = type;
3591                         this.variable = var;
3592                         this.expr = expr;
3593                         statement = stmt;
3594                         loc = l;
3595                 }
3596                 
3597                 public override bool Resolve (EmitContext ec)
3598                 {
3599                         expr = expr.Resolve (ec);
3600                         if (expr == null)
3601                                 return false;
3602
3603                         var_type = ec.DeclSpace.ResolveType (type, false, loc);
3604                         if (var_type == null)
3605                                 return false;
3606                         
3607                         //
3608                         // We need an instance variable.  Not sure this is the best
3609                         // way of doing this.
3610                         //
3611                         // FIXME: When we implement propertyaccess, will those turn
3612                         // out to return values in ExprClass?  I think they should.
3613                         //
3614                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3615                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3616                                 error1579 (expr.Type);
3617                                 return false;
3618                         }
3619
3620                         if (expr.Type.IsArray) {
3621                                 array_type = expr.Type;
3622                                 element_type = TypeManager.GetElementType (array_type);
3623
3624                                 empty = new EmptyExpression (element_type);
3625                         } else {
3626                                 hm = ProbeCollectionType (ec, expr.Type);
3627                                 if (hm == null){
3628                                         error1579 (expr.Type);
3629                                         return false;
3630                                 }                       
3631
3632                                 array_type = expr.Type;
3633                                 element_type = hm.element_type;
3634
3635                                 empty = new EmptyExpression (hm.element_type);
3636                         }
3637
3638                         bool ok = true;
3639
3640                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3641                         ec.CurrentBranching.CreateSibling ();
3642
3643                         //
3644                         //
3645                         // FIXME: maybe we can apply the same trick we do in the
3646                         // array handling to avoid creating empty and conv in some cases.
3647                         //
3648                         // Although it is not as important in this case, as the type
3649                         // will not likely be object (what the enumerator will return).
3650                         //
3651                         conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3652                         if (conv == null)
3653                                 ok = false;
3654
3655                         variable = variable.ResolveLValue (ec, empty);
3656                         if (variable == null)
3657                                 ok = false;
3658
3659                         bool disposable = (hm != null) && hm.is_disposable;
3660                         if (disposable)
3661                                 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3662
3663                         if (!statement.Resolve (ec))
3664                                 ok = false;
3665
3666                         if (disposable)
3667                                 ec.EndFlowBranching ();
3668
3669                         ec.EndFlowBranching ();
3670
3671                         return ok;
3672                 }
3673                 
3674                 //
3675                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3676                 //
3677                 static MethodInfo FetchMethodMoveNext (Type t)
3678                 {
3679                         MemberList move_next_list;
3680                         
3681                         move_next_list = TypeContainer.FindMembers (
3682                                 t, MemberTypes.Method,
3683                                 BindingFlags.Public | BindingFlags.Instance,
3684                                 Type.FilterName, "MoveNext");
3685                         if (move_next_list.Count == 0)
3686                                 return null;
3687
3688                         foreach (MemberInfo m in move_next_list){
3689                                 MethodInfo mi = (MethodInfo) m;
3690                                 Type [] args;
3691                                 
3692                                 args = TypeManager.GetArgumentTypes (mi);
3693                                 if (args != null && args.Length == 0){
3694                                         if (mi.ReturnType == TypeManager.bool_type)
3695                                                 return mi;
3696                                 }
3697                         }
3698                         return null;
3699                 }
3700                 
3701                 //
3702                 // Retrieves a `public T get_Current ()' method from the Type `t'
3703                 //
3704                 static MethodInfo FetchMethodGetCurrent (Type t)
3705                 {
3706                         MemberList get_current_list;
3707
3708                         get_current_list = TypeContainer.FindMembers (
3709                                 t, MemberTypes.Method,
3710                                 BindingFlags.Public | BindingFlags.Instance,
3711                                 Type.FilterName, "get_Current");
3712                         if (get_current_list.Count == 0)
3713                                 return null;
3714
3715                         foreach (MemberInfo m in get_current_list){
3716                                 MethodInfo mi = (MethodInfo) m;
3717                                 Type [] args;
3718
3719                                 args = TypeManager.GetArgumentTypes (mi);
3720                                 if (args != null && args.Length == 0)
3721                                         return mi;
3722                         }
3723                         return null;
3724                 }
3725
3726                 // 
3727                 // This struct records the helper methods used by the Foreach construct
3728                 //
3729                 class ForeachHelperMethods {
3730                         public EmitContext ec;
3731                         public MethodInfo get_enumerator;
3732                         public MethodInfo move_next;
3733                         public MethodInfo get_current;
3734                         public Type element_type;
3735                         public Type enumerator_type;
3736                         public bool is_disposable;
3737
3738                         public ForeachHelperMethods (EmitContext ec)
3739                         {
3740                                 this.ec = ec;
3741                                 this.element_type = TypeManager.object_type;
3742                                 this.enumerator_type = TypeManager.ienumerator_type;
3743                                 this.is_disposable = true;
3744                         }
3745                 }
3746                 
3747                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3748                 {
3749                         if (m == null)
3750                                 return false;
3751                         
3752                         if (!(m is MethodInfo))
3753                                 return false;
3754                         
3755                         if (m.Name != "GetEnumerator")
3756                                 return false;
3757
3758                         MethodInfo mi = (MethodInfo) m;
3759                         Type [] args = TypeManager.GetArgumentTypes (mi);
3760                         if (args != null){
3761                                 if (args.Length != 0)
3762                                         return false;
3763                         }
3764                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3765                         EmitContext ec = hm.ec;
3766
3767                         //
3768                         // Check whether GetEnumerator is accessible to us
3769                         //
3770                         MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3771
3772                         Type declaring = mi.DeclaringType;
3773                         if (prot == MethodAttributes.Private){
3774                                 if (declaring != ec.ContainerType)
3775                                         return false;
3776                         } else if (prot == MethodAttributes.FamANDAssem){
3777                                 // If from a different assembly, false
3778                                 if (!(mi is MethodBuilder))
3779                                         return false;
3780                                 //
3781                                 // Are we being invoked from the same class, or from a derived method?
3782                                 //
3783                                 if (ec.ContainerType != declaring){
3784                                         if (!ec.ContainerType.IsSubclassOf (declaring))
3785                                                 return false;
3786                                 }
3787                         } else if (prot == MethodAttributes.FamORAssem){
3788                                 if (!(mi is MethodBuilder ||
3789                                       ec.ContainerType == declaring ||
3790                                       ec.ContainerType.IsSubclassOf (declaring)))
3791                                         return false;
3792                         } if (prot == MethodAttributes.Family){
3793                                 if (!(ec.ContainerType == declaring ||
3794                                       ec.ContainerType.IsSubclassOf (declaring)))
3795                                         return false;
3796                         }
3797
3798                         if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3799                                 //
3800                                 // Apply the same optimization as MS: skip the GetEnumerator
3801                                 // returning an IEnumerator, and use the one returning a 
3802                                 // CharEnumerator instead. This allows us to avoid the 
3803                                 // try-finally block and the boxing.
3804                                 //
3805                                 return false;
3806
3807                         //
3808                         // Ok, we can access it, now make sure that we can do something
3809                         // with this `GetEnumerator'
3810                         //
3811                         
3812                         Type return_type = mi.ReturnType;
3813                         if (mi.ReturnType == TypeManager.ienumerator_type ||
3814                             TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3815                             (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3816                                 
3817                                 //
3818                                 // If it is not an interface, lets try to find the methods ourselves.
3819                                 // For example, if we have:
3820                                 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
3821                                 // We can avoid the iface call. This is a runtime perf boost.
3822                                 // even bigger if we have a ValueType, because we avoid the cost
3823                                 // of boxing.
3824                                 //
3825                                 // We have to make sure that both methods exist for us to take
3826                                 // this path. If one of the methods does not exist, we will just
3827                                 // use the interface. Sadly, this complex if statement is the only
3828                                 // way I could do this without a goto
3829                                 //
3830                                 
3831                                 if (return_type.IsInterface ||
3832                                     (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
3833                                     (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
3834                                         
3835                                         hm.move_next = TypeManager.bool_movenext_void;
3836                                         hm.get_current = TypeManager.object_getcurrent_void;
3837                                         return true;    
3838                                 }
3839
3840                         } else {
3841
3842                                 //
3843                                 // Ok, so they dont return an IEnumerable, we will have to
3844                                 // find if they support the GetEnumerator pattern.
3845                                 //
3846                                 
3847                                 hm.move_next = FetchMethodMoveNext (return_type);
3848                                 if (hm.move_next == null)
3849                                         return false;
3850                                 
3851                                 hm.get_current = FetchMethodGetCurrent (return_type);
3852                                 if (hm.get_current == null)
3853                                         return false;
3854                         }
3855                         
3856                         hm.element_type = hm.get_current.ReturnType;
3857                         hm.enumerator_type = return_type;
3858                         hm.is_disposable = !hm.enumerator_type.IsSealed ||
3859                                 TypeManager.ImplementsInterface (
3860                                         hm.enumerator_type, TypeManager.idisposable_type);
3861
3862                         return true;
3863                 }
3864                 
3865                 /// <summary>
3866                 ///   This filter is used to find the GetEnumerator method
3867                 ///   on which IEnumerator operates
3868                 /// </summary>
3869                 static MemberFilter FilterEnumerator;
3870                 
3871                 static Foreach ()
3872                 {
3873                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3874                 }
3875
3876                 void error1579 (Type t)
3877                 {
3878                         Report.Error (1579, loc,
3879                                       "foreach statement cannot operate on variables of type `" +
3880                                       t.FullName + "' because that class does not provide a " +
3881                                       " GetEnumerator method or it is inaccessible");
3882                 }
3883
3884                 static bool TryType (Type t, ForeachHelperMethods hm)
3885                 {
3886                         MemberList mi;
3887                         
3888                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3889                                                         BindingFlags.Public | BindingFlags.NonPublic |
3890                                                         BindingFlags.Instance | BindingFlags.DeclaredOnly,
3891                                                         FilterEnumerator, hm);
3892
3893                         if (mi.Count == 0)
3894                                 return false;
3895
3896                         hm.get_enumerator = (MethodInfo) mi [0];
3897                         return true;    
3898                 }
3899                 
3900                 //
3901                 // Looks for a usable GetEnumerator in the Type, and if found returns
3902                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3903                 //
3904                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3905                 {
3906                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3907
3908                         for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3909                                 if (TryType (tt, hm))
3910                                         return hm;
3911                                 tt = tt.BaseType;
3912                         }
3913
3914                         //
3915                         // Now try to find the method in the interfaces
3916                         //
3917                         while (t != null){
3918                                 Type [] ifaces = t.GetInterfaces ();
3919
3920                                 foreach (Type i in ifaces){
3921                                         if (TryType (i, hm))
3922                                                 return hm;
3923                                 }
3924                                 
3925                                 //
3926                                 // Since TypeBuilder.GetInterfaces only returns the interface
3927                                 // types for this type, we have to keep looping, but once
3928                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3929                                 // done, because it returns all the types
3930                                 //
3931                                 if ((t is TypeBuilder))
3932                                         t = t.BaseType;
3933                                 else
3934                                         break;
3935                         } 
3936
3937                         return null;
3938                 }
3939
3940                 //
3941                 // FIXME: possible optimization.
3942                 // We might be able to avoid creating `empty' if the type is the sam
3943                 //
3944                 bool EmitCollectionForeach (EmitContext ec)
3945                 {
3946                         ILGenerator ig = ec.ig;
3947                         VariableStorage enumerator;
3948
3949                         enumerator = new VariableStorage (ec, hm.enumerator_type);
3950                         enumerator.EmitThis ();
3951                         //
3952                         // Instantiate the enumerator
3953                         //
3954                         if (expr.Type.IsValueType){
3955                                 if (expr is IMemoryLocation){
3956                                         IMemoryLocation ml = (IMemoryLocation) expr;
3957
3958                                         Expression ml1 = Expression.MemberLookup(ec, TypeManager.ienumerator_type, expr.Type, "GetEnumerator", Mono.CSharp.Location.Null);
3959
3960                                         if (!(ml1 is MethodGroupExpr)) {
3961                                                 expr.Emit(ec);
3962                                                 ec.ig.Emit(OpCodes.Box, expr.Type);
3963                                         } else {
3964                                                 ml.AddressOf (ec, AddressOp.Load);
3965                                         }
3966                                 } else
3967                                         throw new Exception ("Expr " + expr + " of type " + expr.Type +
3968                                                              " does not implement IMemoryLocation");
3969                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3970                         } else {
3971                                 expr.Emit (ec);
3972                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3973                         }
3974                         enumerator.EmitStore ();
3975
3976                         //
3977                         // Protect the code in a try/finalize block, so that
3978                         // if the beast implement IDisposable, we get rid of it
3979                         //
3980                         if (hm.is_disposable)
3981                                 ig.BeginExceptionBlock ();
3982                         
3983                         Label end_try = ig.DefineLabel ();
3984                         
3985                         ig.MarkLabel (ec.LoopBegin);
3986                         
3987                         enumerator.EmitCall (hm.move_next);
3988                         
3989                         ig.Emit (OpCodes.Brfalse, end_try);
3990                         if (ec.InIterator)
3991                                 ec.EmitThis ();
3992                         
3993                         enumerator.EmitCall (hm.get_current);
3994
3995                         if (ec.InIterator){
3996                                 conv.Emit (ec);
3997                                 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3998                         } else 
3999                                 ((IAssignMethod)variable).EmitAssign (ec, conv);
4000                                 
4001                         statement.Emit (ec);
4002                         ig.Emit (OpCodes.Br, ec.LoopBegin);
4003                         ig.MarkLabel (end_try);
4004                         
4005                         // The runtime provides this for us.
4006                         // ig.Emit (OpCodes.Leave, end);
4007
4008                         //
4009                         // Now the finally block
4010                         //
4011                         if (hm.is_disposable) {
4012                                 Label call_dispose = ig.DefineLabel ();
4013                                 ig.BeginFinallyBlock ();
4014                                 
4015                                 enumerator.EmitThis ();
4016                                 enumerator.EmitLoad ();
4017                                 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4018                                 ig.Emit (OpCodes.Dup);
4019                                 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4020                                 ig.Emit (OpCodes.Pop);
4021                                 ig.Emit (OpCodes.Endfinally);
4022                                 
4023                                 ig.MarkLabel (call_dispose);
4024                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4025                                 
4026
4027                                 // The runtime generates this anyways.
4028                                 // ig.Emit (OpCodes.Endfinally);
4029
4030                                 ig.EndExceptionBlock ();
4031                         }
4032
4033                         ig.MarkLabel (ec.LoopEnd);
4034                         return false;
4035                 }
4036
4037                 //
4038                 // FIXME: possible optimization.
4039                 // We might be able to avoid creating `empty' if the type is the sam
4040                 //
4041                 bool EmitArrayForeach (EmitContext ec)
4042                 {
4043                         int rank = array_type.GetArrayRank ();
4044                         ILGenerator ig = ec.ig;
4045
4046                         VariableStorage copy = new VariableStorage (ec, array_type);
4047                         
4048                         //
4049                         // Make our copy of the array
4050                         //
4051                         copy.EmitThis ();
4052                         expr.Emit (ec);
4053                         copy.EmitStore ();
4054                         
4055                         if (rank == 1){
4056                                 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4057
4058                                 Label loop, test;
4059
4060                                 counter.EmitThis ();
4061                                 ig.Emit (OpCodes.Ldc_I4_0);
4062                                 counter.EmitStore ();
4063                                 test = ig.DefineLabel ();
4064                                 ig.Emit (OpCodes.Br, test);
4065
4066                                 loop = ig.DefineLabel ();
4067                                 ig.MarkLabel (loop);
4068
4069                                 if (ec.InIterator)
4070                                         ec.EmitThis ();
4071                                 
4072                                 copy.EmitThis ();
4073                                 copy.EmitLoad ();
4074                                 counter.EmitThis ();
4075                                 counter.EmitLoad ();
4076
4077                                 //
4078                                 // Load the value, we load the value using the underlying type,
4079                                 // then we use the variable.EmitAssign to load using the proper cast.
4080                                 //
4081                                 ArrayAccess.EmitLoadOpcode (ig, element_type);
4082                                 if (ec.InIterator){
4083                                         conv.Emit (ec);
4084                                         ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4085                                 } else 
4086                                         ((IAssignMethod)variable).EmitAssign (ec, conv);
4087
4088                                 statement.Emit (ec);
4089
4090                                 ig.MarkLabel (ec.LoopBegin);
4091                                 counter.EmitThis ();
4092                                 counter.EmitThis ();
4093                                 counter.EmitLoad ();
4094                                 ig.Emit (OpCodes.Ldc_I4_1);
4095                                 ig.Emit (OpCodes.Add);
4096                                 counter.EmitStore ();
4097
4098                                 ig.MarkLabel (test);
4099                                 counter.EmitThis ();
4100                                 counter.EmitLoad ();
4101                                 copy.EmitThis ();
4102                                 copy.EmitLoad ();
4103                                 ig.Emit (OpCodes.Ldlen);
4104                                 ig.Emit (OpCodes.Conv_I4);
4105                                 ig.Emit (OpCodes.Blt, loop);
4106                         } else {
4107                                 VariableStorage [] dim_len   = new VariableStorage [rank];
4108                                 VariableStorage [] dim_count = new VariableStorage [rank];
4109                                 Label [] loop = new Label [rank];
4110                                 Label [] test = new Label [rank];
4111                                 int dim;
4112                                 
4113                                 for (dim = 0; dim < rank; dim++){
4114                                         dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4115                                         dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4116                                         test [dim] = ig.DefineLabel ();
4117                                         loop [dim] = ig.DefineLabel ();
4118                                 }
4119                                         
4120                                 for (dim = 0; dim < rank; dim++){
4121                                         dim_len [dim].EmitThis ();
4122                                         copy.EmitThis ();
4123                                         copy.EmitLoad ();
4124                                         IntLiteral.EmitInt (ig, dim);
4125                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4126                                         dim_len [dim].EmitStore ();
4127                                         
4128                                 }
4129
4130                                 for (dim = 0; dim < rank; dim++){
4131                                         dim_count [dim].EmitThis ();
4132                                         ig.Emit (OpCodes.Ldc_I4_0);
4133                                         dim_count [dim].EmitStore ();
4134                                         ig.Emit (OpCodes.Br, test [dim]);
4135                                         ig.MarkLabel (loop [dim]);
4136                                 }
4137
4138                                 if (ec.InIterator)
4139                                         ec.EmitThis ();
4140                                 copy.EmitThis ();
4141                                 copy.EmitLoad ();
4142                                 for (dim = 0; dim < rank; dim++){
4143                                         dim_count [dim].EmitThis ();
4144                                         dim_count [dim].EmitLoad ();
4145                                 }
4146
4147                                 //
4148                                 // FIXME: Maybe we can cache the computation of `get'?
4149                                 //
4150                                 Type [] args = new Type [rank];
4151                                 MethodInfo get;
4152
4153                                 for (int i = 0; i < rank; i++)
4154                                         args [i] = TypeManager.int32_type;
4155
4156                                 ModuleBuilder mb = CodeGen.Module.Builder;
4157                                 get = mb.GetArrayMethod (
4158                                         array_type, "Get",
4159                                         CallingConventions.HasThis| CallingConventions.Standard,
4160                                         var_type, args);
4161                                 ig.Emit (OpCodes.Call, get);
4162                                 if (ec.InIterator){
4163                                         conv.Emit (ec);
4164                                         ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4165                                 } else 
4166                                         ((IAssignMethod)variable).EmitAssign (ec, conv);
4167                                 statement.Emit (ec);
4168                                 ig.MarkLabel (ec.LoopBegin);
4169                                 for (dim = rank - 1; dim >= 0; dim--){
4170                                         dim_count [dim].EmitThis ();
4171                                         dim_count [dim].EmitThis ();
4172                                         dim_count [dim].EmitLoad ();
4173                                         ig.Emit (OpCodes.Ldc_I4_1);
4174                                         ig.Emit (OpCodes.Add);
4175                                         dim_count [dim].EmitStore ();
4176
4177                                         ig.MarkLabel (test [dim]);
4178                                         dim_count [dim].EmitThis ();
4179                                         dim_count [dim].EmitLoad ();
4180                                         dim_len [dim].EmitThis ();
4181                                         dim_len [dim].EmitLoad ();
4182                                         ig.Emit (OpCodes.Blt, loop [dim]);
4183                                 }
4184                         }
4185                         ig.MarkLabel (ec.LoopEnd);
4186                         
4187                         return false;
4188                 }
4189                 
4190                 protected override void DoEmit (EmitContext ec)
4191                 {
4192                         ILGenerator ig = ec.ig;
4193                         
4194                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4195                         ec.LoopBegin = ig.DefineLabel ();
4196                         ec.LoopEnd = ig.DefineLabel ();
4197                         
4198                         if (hm != null)
4199                                 EmitCollectionForeach (ec);
4200                         else
4201                                 EmitArrayForeach (ec);
4202                         
4203                         ec.LoopBegin = old_begin;
4204                         ec.LoopEnd = old_end;
4205                 }
4206         }
4207 }