This commit was manufactured by cvs2svn to create branch 'mono-1-0'.
[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                         if (!ok) {
2738                                 ec.KillFlowBranching ();
2739                                 return false;
2740                         }
2741
2742                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2743                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
2744                                 // Unfortunately, System.Reflection.Emit automatically emits
2745                                 // a leave to the end of the finally block.
2746                                 // This is a problem if `returns' is true since we may jump
2747                                 // to a point after the end of the method.
2748                                 // As a workaround, emit an explicit ret here.
2749                                 ec.NeedReturnLabel ();
2750                         }
2751
2752                         return true;
2753                 }
2754                 
2755                 protected override void DoEmit (EmitContext ec)
2756                 {
2757                         Type type = expr.Type;
2758                         
2759                         ILGenerator ig = ec.ig;
2760                         LocalBuilder temp = ig.DeclareLocal (type);
2761                                 
2762                         expr.Emit (ec);
2763                         ig.Emit (OpCodes.Dup);
2764                         ig.Emit (OpCodes.Stloc, temp);
2765                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2766
2767                         // try
2768                         ig.BeginExceptionBlock ();
2769                         Label finish = ig.DefineLabel ();
2770                         Statement.Emit (ec);
2771                         // ig.Emit (OpCodes.Leave, finish);
2772
2773                         ig.MarkLabel (finish);
2774                         
2775                         // finally
2776                         ig.BeginFinallyBlock ();
2777                         ig.Emit (OpCodes.Ldloc, temp);
2778                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2779                         ig.EndExceptionBlock ();
2780                 }
2781         }
2782
2783         public class Unchecked : Statement {
2784                 public readonly Block Block;
2785                 
2786                 public Unchecked (Block b)
2787                 {
2788                         Block = b;
2789                         b.Unchecked = true;
2790                 }
2791
2792                 public override bool Resolve (EmitContext ec)
2793                 {
2794                         bool previous_state = ec.CheckState;
2795                         bool previous_state_const = ec.ConstantCheckState;
2796
2797                         ec.CheckState = false;
2798                         ec.ConstantCheckState = false;
2799                         bool ret = Block.Resolve (ec);
2800                         ec.CheckState = previous_state;
2801                         ec.ConstantCheckState = previous_state_const;
2802
2803                         return ret;
2804                 }
2805                 
2806                 protected override void DoEmit (EmitContext ec)
2807                 {
2808                         bool previous_state = ec.CheckState;
2809                         bool previous_state_const = ec.ConstantCheckState;
2810                         
2811                         ec.CheckState = false;
2812                         ec.ConstantCheckState = false;
2813                         Block.Emit (ec);
2814                         ec.CheckState = previous_state;
2815                         ec.ConstantCheckState = previous_state_const;
2816                 }
2817         }
2818
2819         public class Checked : Statement {
2820                 public readonly Block Block;
2821                 
2822                 public Checked (Block b)
2823                 {
2824                         Block = b;
2825                         b.Unchecked = false;
2826                 }
2827
2828                 public override bool Resolve (EmitContext ec)
2829                 {
2830                         bool previous_state = ec.CheckState;
2831                         bool previous_state_const = ec.ConstantCheckState;
2832                         
2833                         ec.CheckState = true;
2834                         ec.ConstantCheckState = true;
2835                         bool ret = Block.Resolve (ec);
2836                         ec.CheckState = previous_state;
2837                         ec.ConstantCheckState = previous_state_const;
2838
2839                         return ret;
2840                 }
2841
2842                 protected override void DoEmit (EmitContext ec)
2843                 {
2844                         bool previous_state = ec.CheckState;
2845                         bool previous_state_const = ec.ConstantCheckState;
2846                         
2847                         ec.CheckState = true;
2848                         ec.ConstantCheckState = true;
2849                         Block.Emit (ec);
2850                         ec.CheckState = previous_state;
2851                         ec.ConstantCheckState = previous_state_const;
2852                 }
2853         }
2854
2855         public class Unsafe : Statement {
2856                 public readonly Block Block;
2857
2858                 public Unsafe (Block b)
2859                 {
2860                         Block = b;
2861                 }
2862
2863                 public override bool Resolve (EmitContext ec)
2864                 {
2865                         bool previous_state = ec.InUnsafe;
2866                         bool val;
2867                         
2868                         ec.InUnsafe = true;
2869                         val = Block.Resolve (ec);
2870                         ec.InUnsafe = previous_state;
2871
2872                         return val;
2873                 }
2874                 
2875                 protected override void DoEmit (EmitContext ec)
2876                 {
2877                         bool previous_state = ec.InUnsafe;
2878                         
2879                         ec.InUnsafe = true;
2880                         Block.Emit (ec);
2881                         ec.InUnsafe = previous_state;
2882                 }
2883         }
2884
2885         // 
2886         // Fixed statement
2887         //
2888         public class Fixed : Statement {
2889                 Expression type;
2890                 ArrayList declarators;
2891                 Statement statement;
2892                 Type expr_type;
2893                 FixedData[] data;
2894                 bool has_ret;
2895
2896                 struct FixedData {
2897                         public bool is_object;
2898                         public LocalInfo vi;
2899                         public Expression expr;
2900                         public Expression converted;
2901                 }                       
2902
2903                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2904                 {
2905                         this.type = type;
2906                         declarators = decls;
2907                         statement = stmt;
2908                         loc = l;
2909                 }
2910
2911                 public override bool Resolve (EmitContext ec)
2912                 {
2913                         if (!ec.InUnsafe){
2914                                 Expression.UnsafeError (loc);
2915                                 return false;
2916                         }
2917                         
2918                         expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2919                         if (expr_type == null)
2920                                 return false;
2921
2922                         CheckObsolete (expr_type);
2923
2924                         if (ec.RemapToProxy){
2925                                 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2926                                 return false;
2927                         }
2928                         
2929                         data = new FixedData [declarators.Count];
2930
2931                         if (!expr_type.IsPointer){
2932                                 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2933                                 return false;
2934                         }
2935                         
2936                         int i = 0;
2937                         foreach (Pair p in declarators){
2938                                 LocalInfo vi = (LocalInfo) p.First;
2939                                 Expression e = (Expression) p.Second;
2940
2941                                 vi.VariableInfo = null;
2942                                 vi.ReadOnly = true;
2943
2944                                 //
2945                                 // The rules for the possible declarators are pretty wise,
2946                                 // but the production on the grammar is more concise.
2947                                 //
2948                                 // So we have to enforce these rules here.
2949                                 //
2950                                 // We do not resolve before doing the case 1 test,
2951                                 // because the grammar is explicit in that the token &
2952                                 // is present, so we need to test for this particular case.
2953                                 //
2954
2955                                 if (e is Cast){
2956                                         Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2957                                         return false;
2958                                 }
2959                                 
2960                                 //
2961                                 // Case 1: & object.
2962                                 //
2963                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2964                                         Expression child = ((Unary) e).Expr;
2965
2966                                         vi.MakePinned ();
2967                                         if (child is ParameterReference || child is LocalVariableReference){
2968                                                 Report.Error (
2969                                                         213, loc, 
2970                                                         "No need to use fixed statement for parameters or " +
2971                                                         "local variable declarations (address is already " +
2972                                                         "fixed)");
2973                                                 return false;
2974                                         }
2975
2976                                         ec.InFixedInitializer = true;
2977                                         e = e.Resolve (ec);
2978                                         ec.InFixedInitializer = false;
2979                                         if (e == null)
2980                                                 return false;
2981
2982                                         child = ((Unary) e).Expr;
2983                                         
2984                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
2985                                                 return false;
2986
2987                                         data [i].is_object = true;
2988                                         data [i].expr = e;
2989                                         data [i].converted = null;
2990                                         data [i].vi = vi;
2991                                         i++;
2992
2993                                         continue;
2994                                 }
2995
2996                                 ec.InFixedInitializer = true;
2997                                 e = e.Resolve (ec);
2998                                 ec.InFixedInitializer = false;
2999                                 if (e == null)
3000                                         return false;
3001
3002                                 //
3003                                 // Case 2: Array
3004                                 //
3005                                 if (e.Type.IsArray){
3006                                         Type array_type = TypeManager.GetElementType (e.Type);
3007                                         
3008                                         vi.MakePinned ();
3009                                         //
3010                                         // Provided that array_type is unmanaged,
3011                                         //
3012                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
3013                                                 return false;
3014
3015                                         //
3016                                         // and T* is implicitly convertible to the
3017                                         // pointer type given in the fixed statement.
3018                                         //
3019                                         ArrayPtr array_ptr = new ArrayPtr (e, loc);
3020                                         
3021                                         Expression converted = Convert.ImplicitConversionRequired (
3022                                                 ec, array_ptr, vi.VariableType, loc);
3023                                         if (converted == null)
3024                                                 return false;
3025
3026                                         data [i].is_object = false;
3027                                         data [i].expr = e;
3028                                         data [i].converted = converted;
3029                                         data [i].vi = vi;
3030                                         i++;
3031
3032                                         continue;
3033                                 }
3034
3035                                 //
3036                                 // Case 3: string
3037                                 //
3038                                 if (e.Type == TypeManager.string_type){
3039                                         data [i].is_object = false;
3040                                         data [i].expr = e;
3041                                         data [i].converted = null;
3042                                         data [i].vi = vi;
3043                                         i++;
3044                                         continue;
3045                                 }
3046
3047                                 //
3048                                 // For other cases, flag a `this is already fixed expression'
3049                                 //
3050                                 if (e is LocalVariableReference || e is ParameterReference ||
3051                                     Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3052                                     
3053                                         Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3054                                         return false;
3055                                 }
3056
3057                                 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3058                                 return false;
3059                         }
3060
3061                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3062
3063                         if (!statement.Resolve (ec)) {
3064                                 ec.KillFlowBranching ();
3065                                 return false;
3066                         }
3067
3068                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3069                         has_ret = reachability.IsUnreachable;
3070
3071                         return true;
3072                 }
3073                 
3074                 protected override void DoEmit (EmitContext ec)
3075                 {
3076                         ILGenerator ig = ec.ig;
3077
3078                         LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3079                         
3080                         for (int i = 0; i < data.Length; i++) {
3081                                 LocalInfo vi = data [i].vi;
3082
3083                                 //
3084                                 // Case 1: & object.
3085                                 //
3086                                 if (data [i].is_object) {
3087                                         //
3088                                         // Store pointer in pinned location
3089                                         //
3090                                         data [i].expr.Emit (ec);
3091                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3092                                         clear_list [i] = vi.LocalBuilder;
3093                                         continue;
3094                                 }
3095
3096                                 //
3097                                 // Case 2: Array
3098                                 //
3099                                 if (data [i].expr.Type.IsArray){
3100                                         //
3101                                         // Store pointer in pinned location
3102                                         //
3103                                         data [i].converted.Emit (ec);
3104                                         
3105                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3106                                         clear_list [i] = vi.LocalBuilder;
3107                                         continue;
3108                                 }
3109
3110                                 //
3111                                 // Case 3: string
3112                                 //
3113                                 if (data [i].expr.Type == TypeManager.string_type){
3114                                         LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3115                                         TypeManager.MakePinned (pinned_string);
3116                                         clear_list [i] = pinned_string;
3117                                         
3118                                         data [i].expr.Emit (ec);
3119                                         ig.Emit (OpCodes.Stloc, pinned_string);
3120
3121                                         Expression sptr = new StringPtr (pinned_string, loc);
3122                                         Expression converted = Convert.ImplicitConversionRequired (
3123                                                 ec, sptr, vi.VariableType, loc);
3124                                         
3125                                         if (converted == null)
3126                                                 continue;
3127
3128                                         converted.Emit (ec);
3129                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3130                                 }
3131                         }
3132
3133                         statement.Emit (ec);
3134
3135                         if (has_ret)
3136                                 return;
3137
3138                         //
3139                         // Clear the pinned variable
3140                         //
3141                         for (int i = 0; i < data.Length; i++) {
3142                                 if (data [i].is_object || data [i].expr.Type.IsArray) {
3143                                         ig.Emit (OpCodes.Ldc_I4_0);
3144                                         ig.Emit (OpCodes.Conv_U);
3145                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3146                                 } else if (data [i].expr.Type == TypeManager.string_type){
3147                                         ig.Emit (OpCodes.Ldnull);
3148                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3149                                 }
3150                         }
3151                 }
3152         }
3153         
3154         public class Catch: Statement {
3155                 public readonly string Name;
3156                 public readonly Block  Block;
3157
3158                 Expression type_expr;
3159                 Type type;
3160                 
3161                 public Catch (Expression type, string name, Block block, Location l)
3162                 {
3163                         type_expr = type;
3164                         Name = name;
3165                         Block = block;
3166                         loc = l;
3167                 }
3168
3169                 public Type CatchType {
3170                         get {
3171                                 return type;
3172                         }
3173                 }
3174
3175                 public bool IsGeneral {
3176                         get {
3177                                 return type_expr == null;
3178                         }
3179                 }
3180
3181                 protected override void DoEmit(EmitContext ec)
3182                 {
3183                 }
3184
3185                 public override bool Resolve (EmitContext ec)
3186                 {
3187                         if (type_expr != null) {
3188                                 type = ec.DeclSpace.ResolveType (type_expr, false, loc);
3189                                 if (type == null)
3190                                         return false;
3191
3192                                 CheckObsolete (type);
3193
3194                                 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3195                                         Error (155, "The type caught or thrown must be derived from System.Exception");
3196                                         return false;
3197                                 }
3198                         } else
3199                                 type = null;
3200
3201                         return Block.Resolve (ec);
3202                 }
3203         }
3204
3205         public class Try : Statement {
3206                 public readonly Block Fini, Block;
3207                 public readonly ArrayList Specific;
3208                 public readonly Catch General;
3209                 
3210                 //
3211                 // specific, general and fini might all be null.
3212                 //
3213                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3214                 {
3215                         if (specific == null && general == null){
3216                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3217                         }
3218                         
3219                         this.Block = block;
3220                         this.Specific = specific;
3221                         this.General = general;
3222                         this.Fini = fini;
3223                         loc = l;
3224                 }
3225
3226                 public override bool Resolve (EmitContext ec)
3227                 {
3228                         bool ok = true;
3229                         
3230                         ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3231
3232                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3233
3234                         if (!Block.Resolve (ec))
3235                                 ok = false;
3236
3237                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3238
3239                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
3240
3241                         Type[] prevCatches = new Type [Specific.Count];
3242                         int last_index = 0;
3243                         foreach (Catch c in Specific){
3244                                 ec.CurrentBranching.CreateSibling (
3245                                         c.Block, FlowBranching.SiblingType.Catch);
3246
3247                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3248
3249                                 if (c.Name != null) {
3250                                         LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3251                                         if (vi == null)
3252                                                 throw new Exception ();
3253
3254                                         vi.VariableInfo = null;
3255                                 }
3256
3257                                 if (!c.Resolve (ec))
3258                                         return false;
3259
3260                                 Type resolvedType = c.CatchType;
3261                                 for (int ii = 0; ii < last_index; ++ii) {
3262                                         if (resolvedType.IsSubclassOf (prevCatches [ii])) {
3263                                                 Report.Error_T (160, c.loc, prevCatches [ii].FullName);
3264                                                 return false;
3265                                         }
3266                                 }
3267
3268                                 prevCatches [last_index++] = resolvedType;
3269                         }
3270
3271                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3272
3273                         if (General != null){
3274                                 ec.CurrentBranching.CreateSibling (
3275                                         General.Block, FlowBranching.SiblingType.Catch);
3276
3277                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3278
3279                                 if (!General.Resolve (ec))
3280                                         ok = false;
3281                         }
3282
3283                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3284
3285                         if (Fini != null) {
3286                                 if (ok)
3287                                         ec.CurrentBranching.CreateSibling (
3288                                                 Fini, FlowBranching.SiblingType.Finally);
3289
3290                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3291
3292                                 if (!Fini.Resolve (ec))
3293                                         ok = false;
3294                         }
3295
3296                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3297
3298                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3299
3300                         Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3301
3302                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3303                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
3304                                 // to the end of the finally block.  This is a problem if `returns'
3305                                 // is true since we may jump to a point after the end of the method.
3306                                 // As a workaround, emit an explicit ret here.
3307                                 ec.NeedReturnLabel ();
3308                         }
3309
3310                         return ok;
3311                 }
3312                 
3313                 protected override void DoEmit (EmitContext ec)
3314                 {
3315                         ILGenerator ig = ec.ig;
3316                         Label finish = ig.DefineLabel ();;
3317
3318                         ig.BeginExceptionBlock ();
3319                         Block.Emit (ec);
3320
3321                         //
3322                         // System.Reflection.Emit provides this automatically:
3323                         // ig.Emit (OpCodes.Leave, finish);
3324
3325                         foreach (Catch c in Specific){
3326                                 LocalInfo vi;
3327                                 
3328                                 ig.BeginCatchBlock (c.CatchType);
3329
3330                                 if (c.Name != null){
3331                                         vi = c.Block.GetLocalInfo (c.Name);
3332                                         if (vi == null)
3333                                                 throw new Exception ("Variable does not exist in this block");
3334
3335                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3336                                 } else
3337                                         ig.Emit (OpCodes.Pop);
3338                                 
3339                                 c.Block.Emit (ec);
3340                         }
3341
3342                         if (General != null){
3343                                 ig.BeginCatchBlock (TypeManager.object_type);
3344                                 ig.Emit (OpCodes.Pop);
3345                                 General.Block.Emit (ec);
3346                         }
3347
3348                         ig.MarkLabel (finish);
3349                         if (Fini != null){
3350                                 ig.BeginFinallyBlock ();
3351                                 Fini.Emit (ec);
3352                         }
3353                         
3354                         ig.EndExceptionBlock ();
3355                 }
3356         }
3357
3358         public class Using : Statement {
3359                 object expression_or_block;
3360                 Statement Statement;
3361                 ArrayList var_list;
3362                 Expression expr;
3363                 Type expr_type;
3364                 Expression conv;
3365                 Expression [] converted_vars;
3366                 ExpressionStatement [] assign;
3367                 
3368                 public Using (object expression_or_block, Statement stmt, Location l)
3369                 {
3370                         this.expression_or_block = expression_or_block;
3371                         Statement = stmt;
3372                         loc = l;
3373                 }
3374
3375                 //
3376                 // Resolves for the case of using using a local variable declaration.
3377                 //
3378                 bool ResolveLocalVariableDecls (EmitContext ec)
3379                 {
3380                         bool need_conv = false;
3381                         expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3382                         int i = 0;
3383
3384                         if (expr_type == null)
3385                                 return false;
3386
3387                         //
3388                         // The type must be an IDisposable or an implicit conversion
3389                         // must exist.
3390                         //
3391                         converted_vars = new Expression [var_list.Count];
3392                         assign = new ExpressionStatement [var_list.Count];
3393                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3394                                 foreach (DictionaryEntry e in var_list){
3395                                         Expression var = (Expression) e.Key;
3396
3397                                         var = var.ResolveLValue (ec, new EmptyExpression ());
3398                                         if (var == null)
3399                                                 return false;
3400                                         
3401                                         converted_vars [i] = Convert.ImplicitConversionRequired (
3402                                                 ec, var, TypeManager.idisposable_type, loc);
3403
3404                                         if (converted_vars [i] == null)
3405                                                 return false;
3406                                         i++;
3407                                 }
3408                                 need_conv = true;
3409                         }
3410
3411                         i = 0;
3412                         foreach (DictionaryEntry e in var_list){
3413                                 LocalVariableReference var = (LocalVariableReference) e.Key;
3414                                 Expression new_expr = (Expression) e.Value;
3415                                 Expression a;
3416
3417                                 a = new Assign (var, new_expr, loc);
3418                                 a = a.Resolve (ec);
3419                                 if (a == null)
3420                                         return false;
3421
3422                                 if (!need_conv)
3423                                         converted_vars [i] = var;
3424                                 assign [i] = (ExpressionStatement) a;
3425                                 i++;
3426                         }
3427
3428                         return true;
3429                 }
3430
3431                 bool ResolveExpression (EmitContext ec)
3432                 {
3433                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3434                                 conv = Convert.ImplicitConversionRequired (
3435                                         ec, expr, TypeManager.idisposable_type, loc);
3436
3437                                 if (conv == null)
3438                                         return false;
3439                         }
3440
3441                         return true;
3442                 }
3443                 
3444                 //
3445                 // Emits the code for the case of using using a local variable declaration.
3446                 //
3447                 bool EmitLocalVariableDecls (EmitContext ec)
3448                 {
3449                         ILGenerator ig = ec.ig;
3450                         int i = 0;
3451
3452                         for (i = 0; i < assign.Length; i++) {
3453                                 assign [i].EmitStatement (ec);
3454                                 
3455                                 ig.BeginExceptionBlock ();
3456                         }
3457                         Statement.Emit (ec);
3458
3459                         var_list.Reverse ();
3460                         foreach (DictionaryEntry e in var_list){
3461                                 LocalVariableReference var = (LocalVariableReference) e.Key;
3462                                 Label skip = ig.DefineLabel ();
3463                                 i--;
3464                                 
3465                                 ig.BeginFinallyBlock ();
3466
3467                                 if (!var.Type.IsValueType) {
3468                                         var.Emit (ec);
3469                                         ig.Emit (OpCodes.Brfalse, skip);
3470                                         converted_vars [i].Emit (ec);
3471                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3472                                 } else {
3473                                         Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3474
3475                                         if (!(ml is MethodGroupExpr)) {
3476                                                 var.Emit (ec);
3477                                                 ig.Emit (OpCodes.Box, var.Type);
3478                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3479                                         } else {
3480                                                 MethodInfo mi = null;
3481
3482                                                 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3483                                                         if (mk.GetParameters().Length == 0) {
3484                                                                 mi = mk;
3485                                                                 break;
3486                                                         }
3487                                                 }
3488
3489                                                 if (mi == null) {
3490                                                         Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3491                                                         return false;
3492                                                 }
3493
3494                                                 var.AddressOf (ec, AddressOp.Load);
3495                                                 ig.Emit (OpCodes.Call, mi);
3496                                         }
3497                                 }
3498
3499                                 ig.MarkLabel (skip);
3500                                 ig.EndExceptionBlock ();
3501                         }
3502
3503                         return false;
3504                 }
3505
3506                 bool EmitExpression (EmitContext ec)
3507                 {
3508                         //
3509                         // Make a copy of the expression and operate on that.
3510                         //
3511                         ILGenerator ig = ec.ig;
3512                         LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3513                         if (conv != null)
3514                                 conv.Emit (ec);
3515                         else
3516                                 expr.Emit (ec);
3517                         ig.Emit (OpCodes.Stloc, local_copy);
3518
3519                         ig.BeginExceptionBlock ();
3520                         Statement.Emit (ec);
3521                         
3522                         Label skip = ig.DefineLabel ();
3523                         ig.BeginFinallyBlock ();
3524                         ig.Emit (OpCodes.Ldloc, local_copy);
3525                         ig.Emit (OpCodes.Brfalse, skip);
3526                         ig.Emit (OpCodes.Ldloc, local_copy);
3527                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3528                         ig.MarkLabel (skip);
3529                         ig.EndExceptionBlock ();
3530
3531                         return false;
3532                 }
3533                 
3534                 public override bool Resolve (EmitContext ec)
3535                 {
3536                         if (expression_or_block is DictionaryEntry){
3537                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3538                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3539
3540                                 if (!ResolveLocalVariableDecls (ec))
3541                                         return false;
3542
3543                         } else if (expression_or_block is Expression){
3544                                 expr = (Expression) expression_or_block;
3545
3546                                 expr = expr.Resolve (ec);
3547                                 if (expr == null)
3548                                         return false;
3549
3550                                 expr_type = expr.Type;
3551
3552                                 if (!ResolveExpression (ec))
3553                                         return false;
3554                         }
3555
3556                         ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3557
3558                         bool ok = Statement.Resolve (ec);
3559
3560                         if (!ok) {
3561                                 ec.KillFlowBranching ();
3562                                 return false;
3563                         }
3564                                         
3565                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3566
3567                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3568                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
3569                                 // to the end of the finally block.  This is a problem if `returns'
3570                                 // is true since we may jump to a point after the end of the method.
3571                                 // As a workaround, emit an explicit ret here.
3572                                 ec.NeedReturnLabel ();
3573                         }
3574
3575                         return true;
3576                 }
3577                 
3578                 protected override void DoEmit (EmitContext ec)
3579                 {
3580                         if (expression_or_block is DictionaryEntry)
3581                                 EmitLocalVariableDecls (ec);
3582                         else if (expression_or_block is Expression)
3583                                 EmitExpression (ec);
3584                 }
3585         }
3586
3587         /// <summary>
3588         ///   Implementation of the foreach C# statement
3589         /// </summary>
3590         public class Foreach : Statement {
3591                 Expression type;
3592                 Expression variable;
3593                 Expression expr;
3594                 Statement statement;
3595                 ForeachHelperMethods hm;
3596                 Expression empty, conv;
3597                 Type array_type, element_type;
3598                 Type var_type;
3599                 
3600                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3601                                 Statement stmt, Location l)
3602                 {
3603                         this.type = type;
3604                         this.variable = var;
3605                         this.expr = expr;
3606                         statement = stmt;
3607                         loc = l;
3608                 }
3609                 
3610                 public override bool Resolve (EmitContext ec)
3611                 {
3612                         expr = expr.Resolve (ec);
3613                         if (expr == null)
3614                                 return false;
3615
3616                         var_type = ec.DeclSpace.ResolveType (type, false, loc);
3617                         if (var_type == null)
3618                                 return false;
3619                         
3620                         //
3621                         // We need an instance variable.  Not sure this is the best
3622                         // way of doing this.
3623                         //
3624                         // FIXME: When we implement propertyaccess, will those turn
3625                         // out to return values in ExprClass?  I think they should.
3626                         //
3627                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3628                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3629                                 error1579 (expr.Type);
3630                                 return false;
3631                         }
3632
3633                         if (expr.Type.IsArray) {
3634                                 array_type = expr.Type;
3635                                 element_type = TypeManager.GetElementType (array_type);
3636
3637                                 empty = new EmptyExpression (element_type);
3638                         } else {
3639                                 hm = ProbeCollectionType (ec, expr.Type);
3640                                 if (hm == null){
3641                                         error1579 (expr.Type);
3642                                         return false;
3643                                 }                       
3644
3645                                 array_type = expr.Type;
3646                                 element_type = hm.element_type;
3647
3648                                 empty = new EmptyExpression (hm.element_type);
3649                         }
3650
3651                         bool ok = true;
3652
3653                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3654                         ec.CurrentBranching.CreateSibling ();
3655
3656                         //
3657                         //
3658                         // FIXME: maybe we can apply the same trick we do in the
3659                         // array handling to avoid creating empty and conv in some cases.
3660                         //
3661                         // Although it is not as important in this case, as the type
3662                         // will not likely be object (what the enumerator will return).
3663                         //
3664                         conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3665                         if (conv == null)
3666                                 ok = false;
3667
3668                         variable = variable.ResolveLValue (ec, empty);
3669                         if (variable == null)
3670                                 ok = false;
3671
3672                         bool disposable = (hm != null) && hm.is_disposable;
3673                         if (disposable)
3674                                 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3675
3676                         if (!statement.Resolve (ec))
3677                                 ok = false;
3678
3679                         if (disposable)
3680                                 ec.EndFlowBranching ();
3681
3682                         ec.EndFlowBranching ();
3683
3684                         return ok;
3685                 }
3686                 
3687                 //
3688                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3689                 //
3690                 static MethodInfo FetchMethodMoveNext (Type t)
3691                 {
3692                         MemberList move_next_list;
3693                         
3694                         move_next_list = TypeContainer.FindMembers (
3695                                 t, MemberTypes.Method,
3696                                 BindingFlags.Public | BindingFlags.Instance,
3697                                 Type.FilterName, "MoveNext");
3698                         if (move_next_list.Count == 0)
3699                                 return null;
3700
3701                         foreach (MemberInfo m in move_next_list){
3702                                 MethodInfo mi = (MethodInfo) m;
3703                                 Type [] args;
3704                                 
3705                                 args = TypeManager.GetArgumentTypes (mi);
3706                                 if (args != null && args.Length == 0){
3707                                         if (mi.ReturnType == TypeManager.bool_type)
3708                                                 return mi;
3709                                 }
3710                         }
3711                         return null;
3712                 }
3713                 
3714                 //
3715                 // Retrieves a `public T get_Current ()' method from the Type `t'
3716                 //
3717                 static MethodInfo FetchMethodGetCurrent (Type t)
3718                 {
3719                         MemberList get_current_list;
3720
3721                         get_current_list = TypeContainer.FindMembers (
3722                                 t, MemberTypes.Method,
3723                                 BindingFlags.Public | BindingFlags.Instance,
3724                                 Type.FilterName, "get_Current");
3725                         if (get_current_list.Count == 0)
3726                                 return null;
3727
3728                         foreach (MemberInfo m in get_current_list){
3729                                 MethodInfo mi = (MethodInfo) m;
3730                                 Type [] args;
3731
3732                                 args = TypeManager.GetArgumentTypes (mi);
3733                                 if (args != null && args.Length == 0)
3734                                         return mi;
3735                         }
3736                         return null;
3737                 }
3738
3739                 // 
3740                 // This struct records the helper methods used by the Foreach construct
3741                 //
3742                 class ForeachHelperMethods {
3743                         public EmitContext ec;
3744                         public MethodInfo get_enumerator;
3745                         public MethodInfo move_next;
3746                         public MethodInfo get_current;
3747                         public Type element_type;
3748                         public Type enumerator_type;
3749                         public bool is_disposable;
3750
3751                         public ForeachHelperMethods (EmitContext ec)
3752                         {
3753                                 this.ec = ec;
3754                                 this.element_type = TypeManager.object_type;
3755                                 this.enumerator_type = TypeManager.ienumerator_type;
3756                                 this.is_disposable = true;
3757                         }
3758                 }
3759                 
3760                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3761                 {
3762                         if (m == null)
3763                                 return false;
3764                         
3765                         if (!(m is MethodInfo))
3766                                 return false;
3767                         
3768                         if (m.Name != "GetEnumerator")
3769                                 return false;
3770
3771                         MethodInfo mi = (MethodInfo) m;
3772                         Type [] args = TypeManager.GetArgumentTypes (mi);
3773                         if (args != null){
3774                                 if (args.Length != 0)
3775                                         return false;
3776                         }
3777                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3778                         EmitContext ec = hm.ec;
3779
3780                         //
3781                         // Check whether GetEnumerator is accessible to us
3782                         //
3783                         MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3784
3785                         Type declaring = mi.DeclaringType;
3786                         if (prot == MethodAttributes.Private){
3787                                 if (declaring != ec.ContainerType)
3788                                         return false;
3789                         } else if (prot == MethodAttributes.FamANDAssem){
3790                                 // If from a different assembly, false
3791                                 if (!(mi is MethodBuilder))
3792                                         return false;
3793                                 //
3794                                 // Are we being invoked from the same class, or from a derived method?
3795                                 //
3796                                 if (ec.ContainerType != declaring){
3797                                         if (!ec.ContainerType.IsSubclassOf (declaring))
3798                                                 return false;
3799                                 }
3800                         } else if (prot == MethodAttributes.FamORAssem){
3801                                 if (!(mi is MethodBuilder ||
3802                                       ec.ContainerType == declaring ||
3803                                       ec.ContainerType.IsSubclassOf (declaring)))
3804                                         return false;
3805                         } if (prot == MethodAttributes.Family){
3806                                 if (!(ec.ContainerType == declaring ||
3807                                       ec.ContainerType.IsSubclassOf (declaring)))
3808                                         return false;
3809                         }
3810
3811                         if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3812                                 //
3813                                 // Apply the same optimization as MS: skip the GetEnumerator
3814                                 // returning an IEnumerator, and use the one returning a 
3815                                 // CharEnumerator instead. This allows us to avoid the 
3816                                 // try-finally block and the boxing.
3817                                 //
3818                                 return false;
3819
3820                         //
3821                         // Ok, we can access it, now make sure that we can do something
3822                         // with this `GetEnumerator'
3823                         //
3824                         
3825                         Type return_type = mi.ReturnType;
3826                         if (mi.ReturnType == TypeManager.ienumerator_type ||
3827                             TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3828                             (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3829                                 
3830                                 //
3831                                 // If it is not an interface, lets try to find the methods ourselves.
3832                                 // For example, if we have:
3833                                 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
3834                                 // We can avoid the iface call. This is a runtime perf boost.
3835                                 // even bigger if we have a ValueType, because we avoid the cost
3836                                 // of boxing.
3837                                 //
3838                                 // We have to make sure that both methods exist for us to take
3839                                 // this path. If one of the methods does not exist, we will just
3840                                 // use the interface. Sadly, this complex if statement is the only
3841                                 // way I could do this without a goto
3842                                 //
3843                                 
3844                                 if (return_type.IsInterface ||
3845                                     (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
3846                                     (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
3847                                         
3848                                         hm.move_next = TypeManager.bool_movenext_void;
3849                                         hm.get_current = TypeManager.object_getcurrent_void;
3850                                         return true;    
3851                                 }
3852
3853                         } else {
3854
3855                                 //
3856                                 // Ok, so they dont return an IEnumerable, we will have to
3857                                 // find if they support the GetEnumerator pattern.
3858                                 //
3859                                 
3860                                 hm.move_next = FetchMethodMoveNext (return_type);
3861                                 if (hm.move_next == null)
3862                                         return false;
3863                                 
3864                                 hm.get_current = FetchMethodGetCurrent (return_type);
3865                                 if (hm.get_current == null)
3866                                         return false;
3867                         }
3868                         
3869                         hm.element_type = hm.get_current.ReturnType;
3870                         hm.enumerator_type = return_type;
3871                         hm.is_disposable = !hm.enumerator_type.IsSealed ||
3872                                 TypeManager.ImplementsInterface (
3873                                         hm.enumerator_type, TypeManager.idisposable_type);
3874
3875                         return true;
3876                 }
3877                 
3878                 /// <summary>
3879                 ///   This filter is used to find the GetEnumerator method
3880                 ///   on which IEnumerator operates
3881                 /// </summary>
3882                 static MemberFilter FilterEnumerator;
3883                 
3884                 static Foreach ()
3885                 {
3886                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3887                 }
3888
3889                 void error1579 (Type t)
3890                 {
3891                         Report.Error (1579, loc,
3892                                       "foreach statement cannot operate on variables of type `" +
3893                                       t.FullName + "' because that class does not provide a " +
3894                                       " GetEnumerator method or it is inaccessible");
3895                 }
3896
3897                 static bool TryType (Type t, ForeachHelperMethods hm)
3898                 {
3899                         MemberList mi;
3900                         
3901                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3902                                                         BindingFlags.Public | BindingFlags.NonPublic |
3903                                                         BindingFlags.Instance | BindingFlags.DeclaredOnly,
3904                                                         FilterEnumerator, hm);
3905
3906                         if (mi.Count == 0)
3907                                 return false;
3908
3909                         hm.get_enumerator = (MethodInfo) mi [0];
3910                         return true;    
3911                 }
3912                 
3913                 //
3914                 // Looks for a usable GetEnumerator in the Type, and if found returns
3915                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3916                 //
3917                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3918                 {
3919                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3920
3921                         for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3922                                 if (TryType (tt, hm))
3923                                         return hm;
3924                                 tt = tt.BaseType;
3925                         }
3926
3927                         //
3928                         // Now try to find the method in the interfaces
3929                         //
3930                         while (t != null){
3931                                 Type [] ifaces = t.GetInterfaces ();
3932
3933                                 foreach (Type i in ifaces){
3934                                         if (TryType (i, hm))
3935                                                 return hm;
3936                                 }
3937                                 
3938                                 //
3939                                 // Since TypeBuilder.GetInterfaces only returns the interface
3940                                 // types for this type, we have to keep looping, but once
3941                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3942                                 // done, because it returns all the types
3943                                 //
3944                                 if ((t is TypeBuilder))
3945                                         t = t.BaseType;
3946                                 else
3947                                         break;
3948                         } 
3949
3950                         return null;
3951                 }
3952
3953                 //
3954                 // FIXME: possible optimization.
3955                 // We might be able to avoid creating `empty' if the type is the sam
3956                 //
3957                 bool EmitCollectionForeach (EmitContext ec)
3958                 {
3959                         ILGenerator ig = ec.ig;
3960                         VariableStorage enumerator;
3961
3962                         enumerator = new VariableStorage (ec, hm.enumerator_type);
3963                         enumerator.EmitThis ();
3964                         //
3965                         // Instantiate the enumerator
3966                         //
3967                         if (expr.Type.IsValueType) {
3968                                 IMemoryLocation ml = expr as IMemoryLocation;
3969                                 // Load the address of the value type.
3970                                 if (ml == null) {
3971                                         // This happens if, for example, you have a property
3972                                         // returning a struct which is IEnumerable
3973                                         LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
3974                                         expr.Emit (ec);
3975                                         ig.Emit (OpCodes.Stloc, t);
3976                                         ig.Emit (OpCodes.Ldloca, t);
3977                                         ec.FreeTemporaryLocal (t, expr.Type);
3978                                 } else {
3979                                         ml.AddressOf (ec, AddressOp.Load);
3980                                 }
3981                                 
3982                                 // Emit the call.
3983                                 if (hm.get_enumerator.DeclaringType.IsValueType) {
3984                                         // the method is declared on the value type
3985                                         ig.Emit (OpCodes.Call, hm.get_enumerator);
3986                                 } else {
3987                                         // it is an interface method, so we must box
3988                                         ig.Emit (OpCodes.Box, expr.Type);
3989                                         ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3990                                 }
3991                         } else {
3992                                 expr.Emit (ec);
3993                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3994                         }
3995                         enumerator.EmitStore ();
3996
3997                         //
3998                         // Protect the code in a try/finalize block, so that
3999                         // if the beast implement IDisposable, we get rid of it
4000                         //
4001                         if (hm.is_disposable)
4002                                 ig.BeginExceptionBlock ();
4003                         
4004                         Label end_try = ig.DefineLabel ();
4005                         
4006                         ig.MarkLabel (ec.LoopBegin);
4007                         
4008                         enumerator.EmitCall (hm.move_next);
4009                         
4010                         ig.Emit (OpCodes.Brfalse, end_try);
4011                         if (ec.InIterator)
4012                                 ec.EmitThis ();
4013                         
4014                         enumerator.EmitCall (hm.get_current);
4015
4016                         if (ec.InIterator){
4017                                 conv.Emit (ec);
4018                                 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4019                         } else 
4020                                 ((IAssignMethod)variable).EmitAssign (ec, conv);
4021                                 
4022                         statement.Emit (ec);
4023                         ig.Emit (OpCodes.Br, ec.LoopBegin);
4024                         ig.MarkLabel (end_try);
4025                         
4026                         // The runtime provides this for us.
4027                         // ig.Emit (OpCodes.Leave, end);
4028
4029                         //
4030                         // Now the finally block
4031                         //
4032                         if (hm.is_disposable) {
4033                                 Label call_dispose = ig.DefineLabel ();
4034                                 ig.BeginFinallyBlock ();
4035                                 
4036                                 enumerator.EmitThis ();
4037                                 enumerator.EmitLoad ();
4038                                 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4039                                 ig.Emit (OpCodes.Dup);
4040                                 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4041                                 ig.Emit (OpCodes.Pop);
4042                                 ig.Emit (OpCodes.Endfinally);
4043                                 
4044                                 ig.MarkLabel (call_dispose);
4045                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4046                                 
4047
4048                                 // The runtime generates this anyways.
4049                                 // ig.Emit (OpCodes.Endfinally);
4050
4051                                 ig.EndExceptionBlock ();
4052                         }
4053
4054                         ig.MarkLabel (ec.LoopEnd);
4055                         return false;
4056                 }
4057
4058                 //
4059                 // FIXME: possible optimization.
4060                 // We might be able to avoid creating `empty' if the type is the sam
4061                 //
4062                 bool EmitArrayForeach (EmitContext ec)
4063                 {
4064                         int rank = array_type.GetArrayRank ();
4065                         ILGenerator ig = ec.ig;
4066
4067                         VariableStorage copy = new VariableStorage (ec, array_type);
4068                         
4069                         //
4070                         // Make our copy of the array
4071                         //
4072                         copy.EmitThis ();
4073                         expr.Emit (ec);
4074                         copy.EmitStore ();
4075                         
4076                         if (rank == 1){
4077                                 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4078
4079                                 Label loop, test;
4080
4081                                 counter.EmitThis ();
4082                                 ig.Emit (OpCodes.Ldc_I4_0);
4083                                 counter.EmitStore ();
4084                                 test = ig.DefineLabel ();
4085                                 ig.Emit (OpCodes.Br, test);
4086
4087                                 loop = ig.DefineLabel ();
4088                                 ig.MarkLabel (loop);
4089
4090                                 if (ec.InIterator)
4091                                         ec.EmitThis ();
4092                                 
4093                                 copy.EmitThis ();
4094                                 copy.EmitLoad ();
4095                                 counter.EmitThis ();
4096                                 counter.EmitLoad ();
4097
4098                                 //
4099                                 // Load the value, we load the value using the underlying type,
4100                                 // then we use the variable.EmitAssign to load using the proper cast.
4101                                 //
4102                                 ArrayAccess.EmitLoadOpcode (ig, element_type);
4103                                 if (ec.InIterator){
4104                                         conv.Emit (ec);
4105                                         ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4106                                 } else 
4107                                         ((IAssignMethod)variable).EmitAssign (ec, conv);
4108
4109                                 statement.Emit (ec);
4110
4111                                 ig.MarkLabel (ec.LoopBegin);
4112                                 counter.EmitThis ();
4113                                 counter.EmitThis ();
4114                                 counter.EmitLoad ();
4115                                 ig.Emit (OpCodes.Ldc_I4_1);
4116                                 ig.Emit (OpCodes.Add);
4117                                 counter.EmitStore ();
4118
4119                                 ig.MarkLabel (test);
4120                                 counter.EmitThis ();
4121                                 counter.EmitLoad ();
4122                                 copy.EmitThis ();
4123                                 copy.EmitLoad ();
4124                                 ig.Emit (OpCodes.Ldlen);
4125                                 ig.Emit (OpCodes.Conv_I4);
4126                                 ig.Emit (OpCodes.Blt, loop);
4127                         } else {
4128                                 VariableStorage [] dim_len   = new VariableStorage [rank];
4129                                 VariableStorage [] dim_count = new VariableStorage [rank];
4130                                 Label [] loop = new Label [rank];
4131                                 Label [] test = new Label [rank];
4132                                 int dim;
4133                                 
4134                                 for (dim = 0; dim < rank; dim++){
4135                                         dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4136                                         dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4137                                         test [dim] = ig.DefineLabel ();
4138                                         loop [dim] = ig.DefineLabel ();
4139                                 }
4140                                         
4141                                 for (dim = 0; dim < rank; dim++){
4142                                         dim_len [dim].EmitThis ();
4143                                         copy.EmitThis ();
4144                                         copy.EmitLoad ();
4145                                         IntLiteral.EmitInt (ig, dim);
4146                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4147                                         dim_len [dim].EmitStore ();
4148                                         
4149                                 }
4150
4151                                 for (dim = 0; dim < rank; dim++){
4152                                         dim_count [dim].EmitThis ();
4153                                         ig.Emit (OpCodes.Ldc_I4_0);
4154                                         dim_count [dim].EmitStore ();
4155                                         ig.Emit (OpCodes.Br, test [dim]);
4156                                         ig.MarkLabel (loop [dim]);
4157                                 }
4158
4159                                 if (ec.InIterator)
4160                                         ec.EmitThis ();
4161                                 copy.EmitThis ();
4162                                 copy.EmitLoad ();
4163                                 for (dim = 0; dim < rank; dim++){
4164                                         dim_count [dim].EmitThis ();
4165                                         dim_count [dim].EmitLoad ();
4166                                 }
4167
4168                                 //
4169                                 // FIXME: Maybe we can cache the computation of `get'?
4170                                 //
4171                                 Type [] args = new Type [rank];
4172                                 MethodInfo get;
4173
4174                                 for (int i = 0; i < rank; i++)
4175                                         args [i] = TypeManager.int32_type;
4176
4177                                 ModuleBuilder mb = CodeGen.Module.Builder;
4178                                 get = mb.GetArrayMethod (
4179                                         array_type, "Get",
4180                                         CallingConventions.HasThis| CallingConventions.Standard,
4181                                         var_type, args);
4182                                 ig.Emit (OpCodes.Call, get);
4183                                 if (ec.InIterator){
4184                                         conv.Emit (ec);
4185                                         ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4186                                 } else 
4187                                         ((IAssignMethod)variable).EmitAssign (ec, conv);
4188                                 statement.Emit (ec);
4189                                 ig.MarkLabel (ec.LoopBegin);
4190                                 for (dim = rank - 1; dim >= 0; dim--){
4191                                         dim_count [dim].EmitThis ();
4192                                         dim_count [dim].EmitThis ();
4193                                         dim_count [dim].EmitLoad ();
4194                                         ig.Emit (OpCodes.Ldc_I4_1);
4195                                         ig.Emit (OpCodes.Add);
4196                                         dim_count [dim].EmitStore ();
4197
4198                                         ig.MarkLabel (test [dim]);
4199                                         dim_count [dim].EmitThis ();
4200                                         dim_count [dim].EmitLoad ();
4201                                         dim_len [dim].EmitThis ();
4202                                         dim_len [dim].EmitLoad ();
4203                                         ig.Emit (OpCodes.Blt, loop [dim]);
4204                                 }
4205                         }
4206                         ig.MarkLabel (ec.LoopEnd);
4207                         
4208                         return false;
4209                 }
4210                 
4211                 protected override void DoEmit (EmitContext ec)
4212                 {
4213                         ILGenerator ig = ec.ig;
4214                         
4215                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4216                         ec.LoopBegin = ig.DefineLabel ();
4217                         ec.LoopEnd = ig.DefineLabel ();
4218                         
4219                         if (hm != null)
4220                                 EmitCollectionForeach (ec);
4221                         else
4222                                 EmitArrayForeach (ec);
4223                         
4224                         ec.LoopBegin = old_begin;
4225                         ec.LoopEnd = old_end;
4226                 }
4227         }
4228 }