**** Merged from MCS ****
[mono.git] / mcs / gmcs / 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 && (RootContext.WarningLevel >= 2))
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                         Pinned = 4,
972                         IsThis = 8      
973                 }
974
975                 Flags flags;
976
977                 public LocalInfo (Expression type, string name, Block block, Location l)
978                 {
979                         Type = type;
980                         Name = name;
981                         Block = block;
982                         Location = l;
983                 }
984
985                 public LocalInfo (TypeContainer tc, Block block, Location l)
986                 {
987                         VariableType = tc.TypeBuilder;
988                         Block = block;
989                         Location = l;
990                 }
991
992                 public bool IsThisAssigned (EmitContext ec, Location loc)
993                 {
994                         if (VariableInfo == null)
995                                 throw new Exception ();
996
997                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
998                                 return true;
999
1000                         return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1001                 }
1002
1003                 public bool IsAssigned (EmitContext ec)
1004                 {
1005                         if (VariableInfo == null)
1006                                 throw new Exception ();
1007
1008                         return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1009                 }
1010
1011                 public bool Resolve (EmitContext ec)
1012                 {
1013                         if (VariableType == null)
1014                                 VariableType = ec.DeclSpace.ResolveType (Type, false, Location);
1015
1016                         if (VariableType == TypeManager.void_type) {
1017                                 Report.Error (1547, Location,
1018                                               "Keyword 'void' cannot be used in this context");
1019                                 return false;
1020                         }
1021
1022                         if (VariableType == null)
1023                                 return false;
1024
1025                         if (VariableType.IsAbstract && VariableType.IsSealed) {
1026                                 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1027                                 return false;
1028                         }
1029 // TODO: breaks the build
1030 //                      if (VariableType.IsPointer && !ec.InUnsafe)
1031 //                              Expression.UnsafeError (Location);
1032
1033                         return true;
1034                 }
1035
1036                 //
1037                 // Whether the variable is Fixed (because its Pinned or its a value type)
1038                 //
1039                 public bool IsFixed {
1040                         get {
1041                                 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1042                                         return true;
1043                                 
1044                                 return false;
1045                         }
1046                 }
1047                 
1048                 public override string ToString ()
1049                 {
1050                         return String.Format ("LocalInfo ({0},{1},{2},{3})",
1051                                               Name, Type, VariableInfo, Location);
1052                 }
1053
1054                 public bool Used {
1055                         get {
1056                                 return (flags & Flags.Used) != 0;
1057                         }
1058                         set {
1059                                 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1060                         }
1061                 }
1062
1063                 public bool ReadOnly {
1064                         get {
1065                                 return (flags & Flags.ReadOnly) != 0;
1066                         }
1067                         set {
1068                                 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1069                         }
1070                 }
1071
1072                 //
1073                 // Whether the variable is pinned, if Pinned the variable has been 
1074                 // allocated in a pinned slot with DeclareLocal.
1075                 //
1076                 public bool Pinned {
1077                         get {
1078                                 return (flags & Flags.Pinned) != 0;
1079                         }
1080                         set {
1081                                 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1082                         }
1083                 }
1084
1085                 public bool IsThis {
1086                         get {
1087                                 return (flags & Flags.IsThis) != 0;
1088                         }
1089                         set {
1090                                 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1091                         }
1092                 }
1093         }
1094                 
1095         /// <summary>
1096         ///   Block represents a C# block.
1097         /// </summary>
1098         ///
1099         /// <remarks>
1100         ///   This class is used in a number of places: either to represent
1101         ///   explicit blocks that the programmer places or implicit blocks.
1102         ///
1103         ///   Implicit blocks are used as labels or to introduce variable
1104         ///   declarations.
1105         ///
1106         ///   Top-level blocks derive from Block, and they are called ToplevelBlock
1107         ///   they contain extra information that is not necessary on normal blocks.
1108         /// </remarks>
1109         public class Block : Statement {
1110                 public readonly Block     Parent;
1111                 public readonly Location  StartLocation;
1112                 public Location           EndLocation = Location.Null;
1113
1114                 [Flags]
1115                 public enum Flags : byte {
1116                         Implicit  = 1,
1117                         Unchecked = 2,
1118                         BlockUsed = 4,
1119                         VariablesInitialized = 8,
1120                         HasRet = 16,
1121                         IsDestructor = 32,
1122                         HasVarargs = 64 
1123                 }
1124                 Flags flags;
1125
1126                 public bool Implicit {
1127                         get {
1128                                 return (flags & Flags.Implicit) != 0;
1129                         }
1130                 }
1131
1132                 public bool Unchecked {
1133                         get {
1134                                 return (flags & Flags.Unchecked) != 0;
1135                         }
1136                         set {
1137                                 flags |= Flags.Unchecked;
1138                         }
1139                 }
1140
1141                 public bool HasVarargs {
1142                         get {
1143                                 if (Parent != null)
1144                                         return Parent.HasVarargs;
1145                                 else
1146                                         return (flags & Flags.HasVarargs) != 0;
1147                         }
1148                         set {
1149                                 flags |= Flags.HasVarargs;
1150                         }
1151                 }
1152
1153                 //
1154                 // The statements in this block
1155                 //
1156                 ArrayList statements;
1157                 int num_statements;
1158
1159                 //
1160                 // An array of Blocks.  We keep track of children just
1161                 // to generate the local variable declarations.
1162                 //
1163                 // Statements and child statements are handled through the
1164                 // statements.
1165                 //
1166                 ArrayList children;
1167                 
1168                 //
1169                 // Labels.  (label, block) pairs.
1170                 //
1171                 Hashtable labels;
1172
1173                 //
1174                 // Keeps track of (name, type) pairs
1175                 //
1176                 Hashtable variables;
1177
1178                 //
1179                 // Keeps track of constants
1180                 Hashtable constants;
1181
1182                 //
1183                 // If this is a switch section, the enclosing switch block.
1184                 //
1185                 Block switch_block;
1186
1187                 static int id;
1188
1189                 int this_id;
1190                 
1191                 public Block (Block parent)
1192                         : this (parent, (Flags) 0, Location.Null, Location.Null)
1193                 { }
1194
1195                 public Block (Block parent, Flags flags)
1196                         : this (parent, flags, Location.Null, Location.Null)
1197                 { }
1198
1199                 public Block (Block parent, Flags flags, Parameters parameters)
1200                         : this (parent, flags, parameters, Location.Null, Location.Null)
1201                 { }
1202
1203                 public Block (Block parent, Location start, Location end)
1204                         : this (parent, (Flags) 0, start, end)
1205                 { }
1206
1207                 public Block (Block parent, Parameters parameters, Location start, Location end)
1208                         : this (parent, (Flags) 0, parameters, start, end)
1209                 { }
1210
1211                 public Block (Block parent, Flags flags, Location start, Location end)
1212                         : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1213                 { }
1214
1215                 public Block (Block parent, Flags flags, Parameters parameters,
1216                               Location start, Location end)
1217                 {
1218                         if (parent != null)
1219                                 parent.AddChild (this);
1220                         
1221                         this.Parent = parent;
1222                         this.flags = flags;
1223                         this.parameters = parameters;
1224                         this.StartLocation = start;
1225                         this.EndLocation = end;
1226                         this.loc = start;
1227                         this_id = id++;
1228                         statements = new ArrayList ();
1229
1230                         if (parent != null && Implicit) {
1231                                 if (parent.child_variable_names == null)
1232                                         parent.child_variable_names = new Hashtable();
1233                                 // share with parent
1234                                 child_variable_names = parent.child_variable_names;
1235                         }
1236                                 
1237                 }
1238
1239                 public Block CreateSwitchBlock (Location start)
1240                 {
1241                         Block new_block = new Block (this, start, start);
1242                         new_block.switch_block = this;
1243                         return new_block;
1244                 }
1245
1246                 public int ID {
1247                         get {
1248                                 return this_id;
1249                         }
1250                 }
1251
1252                 void AddChild (Block b)
1253                 {
1254                         if (children == null)
1255                                 children = new ArrayList ();
1256                         
1257                         children.Add (b);
1258                 }
1259
1260                 public void SetEndLocation (Location loc)
1261                 {
1262                         EndLocation = loc;
1263                 }
1264
1265                 /// <summary>
1266                 ///   Adds a label to the current block. 
1267                 /// </summary>
1268                 ///
1269                 /// <returns>
1270                 ///   false if the name already exists in this block. true
1271                 ///   otherwise.
1272                 /// </returns>
1273                 ///
1274                 public bool AddLabel (string name, LabeledStatement target, Location loc)
1275                 {
1276                         if (switch_block != null)
1277                                 return switch_block.AddLabel (name, target, loc);
1278
1279                         Block cur = this;
1280                         while (cur != null) {
1281                                 if (cur.DoLookupLabel (name) != null) {
1282                                         Report.Error (
1283                                                 140, loc, "The label '{0}' is a duplicate",
1284                                                 name);
1285                                         return false;
1286                                 }
1287
1288                                 if (!Implicit)
1289                                         break;
1290
1291                                 cur = cur.Parent;
1292                         }
1293
1294                         while (cur != null) {
1295                                 if (cur.DoLookupLabel (name) != null) {
1296                                         Report.Error (
1297                                                 158, loc,
1298                                                 "The label '{0}' shadows another label " +
1299                                                 "by the same name in a containing scope.",
1300                                                 name);
1301                                         return false;
1302                                 }
1303
1304                                 if (children != null) {
1305                                         foreach (Block b in children) {
1306                                                 LabeledStatement s = b.DoLookupLabel (name);
1307                                                 if (s == null)
1308                                                         continue;
1309
1310                                                 Report.Error (
1311                                                         158, s.Location,
1312                                                         "The label '{0}' shadows another " +
1313                                                         "label by the same name in a " +
1314                                                         "containing scope.",
1315                                                         name);
1316                                                 return false;
1317                                         }
1318                                 }
1319
1320
1321                                 cur = cur.Parent;
1322                         }
1323
1324                         if (labels == null)
1325                                 labels = new Hashtable ();
1326
1327                         labels.Add (name, target);
1328                         return true;
1329                 }
1330
1331                 public LabeledStatement LookupLabel (string name)
1332                 {
1333                         LabeledStatement s = DoLookupLabel (name);
1334                         if (s != null)
1335                                 return s;
1336
1337                         if (children == null)
1338                                 return null;
1339
1340                         foreach (Block child in children) {
1341                                 if (!child.Implicit)
1342                                         continue;
1343
1344                                 s = child.LookupLabel (name);
1345                                 if (s != null)
1346                                         return s;
1347                         }
1348
1349                         return null;
1350                 }
1351
1352                 LabeledStatement DoLookupLabel (string name)
1353                 {
1354                         if (switch_block != null)
1355                                 return switch_block.LookupLabel (name);
1356
1357                         if (labels != null)
1358                                 if (labels.Contains (name))
1359                                         return ((LabeledStatement) labels [name]);
1360
1361                         return null;
1362                 }
1363
1364                 LocalInfo this_variable = null;
1365
1366                 // <summary>
1367                 //   Returns the "this" instance variable of this block.
1368                 //   See AddThisVariable() for more information.
1369                 // </summary>
1370                 public LocalInfo ThisVariable {
1371                         get {
1372                                 if (this_variable != null)
1373                                         return this_variable;
1374                                 else if (Parent != null)
1375                                         return Parent.ThisVariable;
1376                                 else
1377                                         return null;
1378                         }
1379                 }
1380
1381                 Hashtable child_variable_names;
1382
1383                 // <summary>
1384                 //   Marks a variable with name @name as being used in a child block.
1385                 //   If a variable name has been used in a child block, it's illegal to
1386                 //   declare a variable with the same name in the current block.
1387                 // </summary>
1388                 public void AddChildVariableName (string name)
1389                 {
1390                         if (child_variable_names == null)
1391                                 child_variable_names = new Hashtable ();
1392
1393                         if (!child_variable_names.Contains (name))
1394                                 child_variable_names.Add (name, true);
1395                 }
1396
1397                 // <summary>
1398                 //   Checks whether a variable name has already been used in a child block.
1399                 // </summary>
1400                 public bool IsVariableNameUsedInChildBlock (string name)
1401                 {
1402                         if (child_variable_names == null)
1403                                 return false;
1404
1405                         return child_variable_names.Contains (name);
1406                 }
1407
1408                 // <summary>
1409                 //   This is used by non-static `struct' constructors which do not have an
1410                 //   initializer - in this case, the constructor must initialize all of the
1411                 //   struct's fields.  To do this, we add a "this" variable and use the flow
1412                 //   analysis code to ensure that it's been fully initialized before control
1413                 //   leaves the constructor.
1414                 // </summary>
1415                 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1416                 {
1417                         if (this_variable != null)
1418                                 return this_variable;
1419
1420                         if (variables == null)
1421                                 variables = new Hashtable ();
1422
1423                         this_variable = new LocalInfo (tc, this, l);
1424                         this_variable.Used = true;
1425                         this_variable.IsThis = true;
1426
1427                         variables.Add ("this", this_variable);
1428
1429                         return this_variable;
1430                 }
1431
1432                 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1433                 {
1434                         if (variables == null)
1435                                 variables = new Hashtable ();
1436
1437                         LocalInfo vi = GetLocalInfo (name);
1438                         if (vi != null) {
1439                                 if (vi.Block != this)
1440                                         Report.Error (136, l, "A local variable named `" + name + "' " +
1441                                                       "cannot be declared in this scope since it would " +
1442                                                       "give a different meaning to `" + name + "', which " +
1443                                                       "is already used in a `parent or current' scope to " +
1444                                                       "denote something else");
1445                                 else
1446                                         Report.Error (128, l, "A local variable `" + name + "' is already " +
1447                                                       "defined in this scope");
1448                                 return null;
1449                         }
1450
1451                         if (IsVariableNameUsedInChildBlock (name)) {
1452                                 Report.Error (136, l, "A local variable named `" + name + "' " +
1453                                               "cannot be declared in this scope since it would " +
1454                                               "give a different meaning to `" + name + "', which " +
1455                                               "is already used in a `child' scope to denote something " +
1456                                               "else");
1457                                 return null;
1458                         }
1459
1460                         if (pars != null) {
1461                                 int idx;
1462                                 Parameter p = pars.GetParameterByName (name, out idx);
1463                                 if (p != null) {
1464                                         Report.Error (136, l, "A local variable named `" + name + "' " +
1465                                                       "cannot be declared in this scope since it would " +
1466                                                       "give a different meaning to `" + name + "', which " +
1467                                                       "is already used in a `parent or current' scope to " +
1468                                                       "denote something else");
1469                                         return null;
1470                                 }
1471                         }
1472
1473                         vi = new LocalInfo (type, name, this, l);
1474
1475                         variables.Add (name, vi);
1476
1477                         // Mark 'name' as "used by a child block" in every surrounding block
1478                         Block cur = this;
1479                         while (cur != null && cur.Implicit) 
1480                                 cur = cur.Parent;
1481                         if (cur != null)
1482                                 for (Block par = cur.Parent; par != null; par = par.Parent)
1483                                         par.AddChildVariableName (name);
1484
1485                         if ((flags & Flags.VariablesInitialized) != 0)
1486                                 throw new Exception ();
1487
1488                         // Console.WriteLine ("Adding {0} to {1}", name, ID);
1489                         return vi;
1490                 }
1491
1492                 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1493                 {
1494                         if (AddVariable (type, name, pars, l) == null)
1495                                 return false;
1496                         
1497                         if (constants == null)
1498                                 constants = new Hashtable ();
1499
1500                         constants.Add (name, value);
1501                         return true;
1502                 }
1503
1504                 public Hashtable Variables {
1505                         get {
1506                                 return variables;
1507                         }
1508                 }
1509
1510                 public LocalInfo GetLocalInfo (string name)
1511                 {
1512                         for (Block b = this; b != null; b = b.Parent) {
1513                                 if (b.variables != null) {
1514                                         LocalInfo ret = b.variables [name] as LocalInfo;
1515                                         if (ret != null)
1516                                                 return ret;
1517                                 }
1518                         }
1519                         return null;
1520                 }
1521
1522                 public Expression GetVariableType (string name)
1523                 {
1524                         LocalInfo vi = GetLocalInfo (name);
1525
1526                         if (vi != null)
1527                                 return vi.Type;
1528
1529                         return null;
1530                 }
1531
1532                 public Expression GetConstantExpression (string name)
1533                 {
1534                         for (Block b = this; b != null; b = b.Parent) {
1535                                 if (b.constants != null) {
1536                                         Expression ret = b.constants [name] as Expression;
1537                                         if (ret != null)
1538                                                 return ret;
1539                                 }
1540                         }
1541                         return null;
1542                 }
1543                 
1544                 /// <summary>
1545                 ///   True if the variable named @name is a constant
1546                 ///  </summary>
1547                 public bool IsConstant (string name)
1548                 {
1549                         Expression e = null;
1550                         
1551                         e = GetConstantExpression (name);
1552                         
1553                         return e != null;
1554                 }
1555                 
1556                 Parameters parameters = null;
1557                 public Parameters Parameters {
1558                         get {
1559                                 Block b = this;
1560                                 while (b.Parent != null)
1561                                         b = b.Parent;
1562                                 return b.parameters;
1563                         }
1564                 }
1565
1566                 /// <returns>
1567                 ///   A list of labels that were not used within this block
1568                 /// </returns>
1569                 public string [] GetUnreferenced ()
1570                 {
1571                         // FIXME: Implement me
1572                         return null;
1573                 }
1574
1575                 public void AddStatement (Statement s)
1576                 {
1577                         statements.Add (s);
1578                         flags |= Flags.BlockUsed;
1579                 }
1580
1581                 public bool Used {
1582                         get {
1583                                 return (flags & Flags.BlockUsed) != 0;
1584                         }
1585                 }
1586
1587                 public void Use ()
1588                 {
1589                         flags |= Flags.BlockUsed;
1590                 }
1591
1592                 public bool HasRet {
1593                         get {
1594                                 return (flags & Flags.HasRet) != 0;
1595                         }
1596                 }
1597
1598                 public bool IsDestructor {
1599                         get {
1600                                 return (flags & Flags.IsDestructor) != 0;
1601                         }
1602                 }
1603
1604                 public void SetDestructor ()
1605                 {
1606                         flags |= Flags.IsDestructor;
1607                 }
1608
1609                 VariableMap param_map, local_map;
1610
1611                 public VariableMap ParameterMap {
1612                         get {
1613                                 if ((flags & Flags.VariablesInitialized) == 0)
1614                                         throw new Exception ();
1615
1616                                 return param_map;
1617                         }
1618                 }
1619
1620                 public VariableMap LocalMap {
1621                         get {
1622                                 if ((flags & Flags.VariablesInitialized) == 0)
1623                                         throw new Exception ();
1624
1625                                 return local_map;
1626                         }
1627                 }
1628
1629                 public bool LiftVariable (LocalInfo local_info)
1630                 {
1631                         return false;
1632                 }
1633                 
1634                 /// <summary>
1635                 ///   Emits the variable declarations and labels.
1636                 /// </summary>
1637                 /// <remarks>
1638                 ///   tc: is our typecontainer (to resolve type references)
1639                 ///   ig: is the code generator:
1640                 /// </remarks>
1641                 public void EmitMeta (EmitContext ec, InternalParameters ip)
1642                 {
1643                         ILGenerator ig = ec.ig;
1644
1645                         //
1646                         // Compute the VariableMap's.
1647                         //
1648                         // Unfortunately, we don't know the type when adding variables with
1649                         // AddVariable(), so we need to compute this info here.
1650                         //
1651
1652                         LocalInfo[] locals;
1653                         if (variables != null) {
1654                                 foreach (LocalInfo li in variables.Values)
1655                                         li.Resolve (ec);
1656
1657                                 locals = new LocalInfo [variables.Count];
1658                                 variables.Values.CopyTo (locals, 0);
1659                         } else
1660                                 locals = new LocalInfo [0];
1661
1662                         if (Parent != null)
1663                                 local_map = new VariableMap (Parent.LocalMap, locals);
1664                         else
1665                                 local_map = new VariableMap (locals);
1666
1667                         param_map = new VariableMap (ip);
1668                         flags |= Flags.VariablesInitialized;
1669
1670                         bool old_check_state = ec.ConstantCheckState;
1671                         ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1672                         bool remap_locals = ec.RemapToProxy;
1673                                 
1674                         //
1675                         // Process this block variables
1676                         //
1677                         if (variables != null){
1678                                 foreach (DictionaryEntry de in variables){
1679                                         string name = (string) de.Key;
1680                                         LocalInfo vi = (LocalInfo) de.Value;
1681                                         
1682                                         if (vi.VariableType == null)
1683                                                 continue;
1684
1685                                         Type variable_type = vi.VariableType;
1686
1687                                         if (variable_type.IsPointer){
1688                                                 //
1689                                                 // Am not really convinced that this test is required (Microsoft does it)
1690                                                 // but the fact is that you would not be able to use the pointer variable
1691                                                 // *anyways*
1692                                                 //
1693                                                 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1694                                                                                   vi.Location))
1695                                                         continue;
1696                                         }
1697
1698                                         if (remap_locals)
1699                                                 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1700                                         else if (vi.Pinned)
1701                                                 //
1702                                                 // This is needed to compile on both .NET 1.x and .NET 2.x
1703                                                 // the later introduced `DeclareLocal (Type t, bool pinned)'
1704                                                 //
1705                                                 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1706                                         else if (!vi.IsThis)
1707                                                 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1708
1709                                         if (constants == null)
1710                                                 continue;
1711
1712                                         Expression cv = (Expression) constants [name];
1713                                         if (cv == null)
1714                                                 continue;
1715
1716                                         ec.CurrentBlock = this;
1717                                         Expression e = cv.Resolve (ec);
1718                                         if (e == null)
1719                                                 continue;
1720
1721                                         Constant ce = e as Constant;
1722                                         if (ce == null){
1723                                                 Report.Error (133, vi.Location,
1724                                                               "The expression being assigned to `" +
1725                                                               name + "' must be constant (" + e + ")");
1726                                                 continue;
1727                                         }
1728
1729                                         if (e.Type != variable_type){
1730                                                 e = Const.ChangeType (vi.Location, ce, variable_type);
1731                                                 if (e == null)
1732                                                         continue;
1733                                         }
1734
1735                                         constants.Remove (name);
1736                                         constants.Add (name, e);
1737                                 }
1738                         }
1739                         ec.ConstantCheckState = old_check_state;
1740
1741                         //
1742                         // Now, handle the children
1743                         //
1744                         if (children != null){
1745                                 foreach (Block b in children)
1746                                         b.EmitMeta (ec, ip);
1747                         }
1748                 }
1749
1750                 void UsageWarning (FlowBranching.UsageVector vector)
1751                 {
1752                         string name;
1753                         
1754                         if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1755                                 foreach (DictionaryEntry de in variables){
1756                                         LocalInfo vi = (LocalInfo) de.Value;
1757                                         
1758                                         if (vi.Used)
1759                                                 continue;
1760                                         
1761                                         name = (string) de.Key;
1762                                                 
1763                                         if (vector.IsAssigned (vi.VariableInfo)){
1764                                                 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1765                                         } else {
1766                                                 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1767                                         }
1768                                 }
1769                         }
1770                 }
1771
1772                 bool unreachable_shown;
1773
1774                 public override bool Resolve (EmitContext ec)
1775                 {
1776                         Block prev_block = ec.CurrentBlock;
1777                         bool ok = true;
1778
1779                         int errors = Report.Errors;
1780
1781                         ec.CurrentBlock = this;
1782                         ec.StartFlowBranching (this);
1783
1784                         Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1785
1786                         bool unreachable = false;
1787
1788                         int statement_count = statements.Count;
1789                         for (int ix = 0; ix < statement_count; ix++){
1790                                 Statement s = (Statement) statements [ix];
1791                                 
1792                                 if (unreachable && !(s is LabeledStatement)) {
1793                                         if (s == EmptyStatement.Value)
1794                                                 s.loc = EndLocation;
1795
1796                                         if (!s.ResolveUnreachable (ec, !unreachable_shown))
1797                                                 ok = false;
1798
1799                                         if (s != EmptyStatement.Value)
1800                                                 unreachable_shown = true;
1801                                         else
1802                                                 s.loc = Location.Null;
1803
1804                                         statements [ix] = EmptyStatement.Value;
1805                                         continue;
1806                                 }
1807
1808                                 if (s.Resolve (ec) == false) {
1809                                         ok = false;
1810                                         statements [ix] = EmptyStatement.Value;
1811                                         continue;
1812                                 }
1813
1814                                 num_statements = ix + 1;
1815
1816                                 if (s is LabeledStatement)
1817                                         unreachable = false;
1818                                 else
1819                                         unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1820                         }
1821
1822                         Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1823                                       ec.CurrentBranching, statement_count, num_statements);
1824
1825
1826                         FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1827
1828                         ec.CurrentBlock = prev_block;
1829
1830                         // If we're a non-static `struct' constructor which doesn't have an
1831                         // initializer, then we must initialize all of the struct's fields.
1832                         if ((this_variable != null) &&
1833                             (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1834                             !this_variable.IsThisAssigned (ec, loc))
1835                                 ok = false;
1836
1837                         if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1838                                 foreach (LabeledStatement label in labels.Values)
1839                                         if (!label.HasBeenReferenced)
1840                                                 Report.Warning (164, label.Location,
1841                                                                 "This label has not been referenced");
1842                         }
1843
1844                         Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1845
1846                         if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1847                             (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1848                             (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1849                                 flags |= Flags.HasRet;
1850
1851                         if (ok && (errors == Report.Errors)) {
1852                                 if (RootContext.WarningLevel >= 3)
1853                                         UsageWarning (vector);
1854                         }
1855
1856                         return ok;
1857                 }
1858                 
1859                 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1860                 {
1861                         unreachable_shown = true;
1862                         return base.ResolveUnreachable (ec, warn);
1863                 }
1864                 
1865                 protected override void DoEmit (EmitContext ec)
1866                 {
1867                         for (int ix = 0; ix < num_statements; ix++){
1868                                 Statement s = (Statement) statements [ix];
1869
1870                                 // Check whether we are the last statement in a
1871                                 // top-level block.
1872
1873                                 if ((Parent == null) && (ix+1 == num_statements))
1874                                         ec.IsLastStatement = true;
1875                                 else
1876                                         ec.IsLastStatement = false;
1877
1878                                 s.Emit (ec);
1879                         }
1880                 }
1881
1882                 public override void Emit (EmitContext ec)
1883                 {
1884                         Block prev_block = ec.CurrentBlock;
1885
1886                         ec.CurrentBlock = this;
1887
1888                         bool emit_debug_info = (CodeGen.SymbolWriter != null);
1889                         bool is_lexical_block = !Implicit && (Parent != null);
1890
1891                         if (emit_debug_info) {
1892                                 if (is_lexical_block)
1893                                         ec.ig.BeginScope ();
1894
1895                                 if (variables != null) {
1896                                         foreach (DictionaryEntry de in variables) {
1897                                                 string name = (string) de.Key;
1898                                                 LocalInfo vi = (LocalInfo) de.Value;
1899
1900                                                 if (vi.LocalBuilder == null)
1901                                                         continue;
1902
1903                                                 ec.DefineLocalVariable (name, vi.LocalBuilder);
1904                                         }
1905                                 }
1906                         }
1907
1908                         ec.Mark (StartLocation, true);
1909                         DoEmit (ec);
1910                         ec.Mark (EndLocation, true); 
1911
1912                         if (emit_debug_info && is_lexical_block)
1913                                 ec.ig.EndScope ();
1914
1915                         ec.CurrentBlock = prev_block;
1916                 }
1917         }
1918
1919         //
1920         // 
1921         public class ToplevelBlock : Block {
1922                 public ToplevelBlock (Parameters parameters, Location start) :
1923                         base (null, parameters, start, Location.Null)
1924                 {
1925                 }
1926
1927                 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
1928                         base (null, flags, parameters, start, Location.Null)
1929                 {
1930                 }
1931         }
1932         
1933         public class SwitchLabel {
1934                 Expression label;
1935                 object converted;
1936                 public Location loc;
1937                 public Label ILLabel;
1938                 public Label ILLabelCode;
1939
1940                 //
1941                 // if expr == null, then it is the default case.
1942                 //
1943                 public SwitchLabel (Expression expr, Location l)
1944                 {
1945                         label = expr;
1946                         loc = l;
1947                 }
1948
1949                 public Expression Label {
1950                         get {
1951                                 return label;
1952                         }
1953                 }
1954
1955                 public object Converted {
1956                         get {
1957                                 return converted;
1958                         }
1959                 }
1960
1961                 //
1962                 // Resolves the expression, reduces it to a literal if possible
1963                 // and then converts it to the requested type.
1964                 //
1965                 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1966                 {
1967                         ILLabel = ec.ig.DefineLabel ();
1968                         ILLabelCode = ec.ig.DefineLabel ();
1969
1970                         if (label == null)
1971                                 return true;
1972                         
1973                         Expression e = label.Resolve (ec);
1974
1975                         if (e == null)
1976                                 return false;
1977
1978                         if (!(e is Constant)){
1979                                 Report.Error (150, loc, "A constant value is expected, got: " + e);
1980                                 return false;
1981                         }
1982
1983                         if (e is StringConstant || e is NullLiteral){
1984                                 if (required_type == TypeManager.string_type){
1985                                         converted = e;
1986                                         ILLabel = ec.ig.DefineLabel ();
1987                                         return true;
1988                                 }
1989                         }
1990
1991                         converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1992                         if (converted == null)
1993                                 return false;
1994
1995                         return true;
1996                 }
1997         }
1998
1999         public class SwitchSection {
2000                 // An array of SwitchLabels.
2001                 public readonly ArrayList Labels;
2002                 public readonly Block Block;
2003                 
2004                 public SwitchSection (ArrayList labels, Block block)
2005                 {
2006                         Labels = labels;
2007                         Block = block;
2008                 }
2009         }
2010         
2011         public class Switch : Statement {
2012                 public readonly ArrayList Sections;
2013                 public Expression Expr;
2014
2015                 /// <summary>
2016                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
2017                 /// </summary>
2018                 public Hashtable Elements;
2019
2020                 /// <summary>
2021                 ///   The governing switch type
2022                 /// </summary>
2023                 public Type SwitchType;
2024
2025                 //
2026                 // Computed
2027                 //
2028                 bool got_default;
2029                 Label default_target;
2030                 Expression new_expr;
2031                 bool is_constant;
2032                 SwitchSection constant_section;
2033
2034                 //
2035                 // The types allowed to be implicitly cast from
2036                 // on the governing type
2037                 //
2038                 static Type [] allowed_types;
2039                 
2040                 public Switch (Expression e, ArrayList sects, Location l)
2041                 {
2042                         Expr = e;
2043                         Sections = sects;
2044                         loc = l;
2045                 }
2046
2047                 public bool GotDefault {
2048                         get {
2049                                 return got_default;
2050                         }
2051                 }
2052
2053                 public Label DefaultTarget {
2054                         get {
2055                                 return default_target;
2056                         }
2057                 }
2058
2059                 //
2060                 // Determines the governing type for a switch.  The returned
2061                 // expression might be the expression from the switch, or an
2062                 // expression that includes any potential conversions to the
2063                 // integral types or to string.
2064                 //
2065                 Expression SwitchGoverningType (EmitContext ec, Type t)
2066                 {
2067                         if (t == TypeManager.int32_type ||
2068                             t == TypeManager.uint32_type ||
2069                             t == TypeManager.char_type ||
2070                             t == TypeManager.byte_type ||
2071                             t == TypeManager.sbyte_type ||
2072                             t == TypeManager.ushort_type ||
2073                             t == TypeManager.short_type ||
2074                             t == TypeManager.uint64_type ||
2075                             t == TypeManager.int64_type ||
2076                             t == TypeManager.string_type ||
2077                                 t == TypeManager.bool_type ||
2078                                 t.IsSubclassOf (TypeManager.enum_type))
2079                                 return Expr;
2080
2081                         if (allowed_types == null){
2082                                 allowed_types = new Type [] {
2083                                         TypeManager.sbyte_type,
2084                                         TypeManager.byte_type,
2085                                         TypeManager.short_type,
2086                                         TypeManager.ushort_type,
2087                                         TypeManager.int32_type,
2088                                         TypeManager.uint32_type,
2089                                         TypeManager.int64_type,
2090                                         TypeManager.uint64_type,
2091                                         TypeManager.char_type,
2092                                         TypeManager.bool_type,
2093                                         TypeManager.string_type
2094                                 };
2095                         }
2096
2097                         //
2098                         // Try to find a *user* defined implicit conversion.
2099                         //
2100                         // If there is no implicit conversion, or if there are multiple
2101                         // conversions, we have to report an error
2102                         //
2103                         Expression converted = null;
2104                         foreach (Type tt in allowed_types){
2105                                 Expression e;
2106                                 
2107                                 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2108                                 if (e == null)
2109                                         continue;
2110
2111                                 if (converted != null){
2112                                         Report.Error (-12, loc, "More than one conversion to an integral " +
2113                                                       " type exists for type `" +
2114                                                       TypeManager.CSharpName (Expr.Type)+"'");
2115                                         return null;
2116                                 } else
2117                                         converted = e;
2118                         }
2119                         return converted;
2120                 }
2121
2122                 void error152 (string n)
2123                 {
2124                         Report.Error (
2125                                 152, "The label `" + n + ":' " +
2126                                 "is already present on this switch statement");
2127                 }
2128                 
2129                 //
2130                 // Performs the basic sanity checks on the switch statement
2131                 // (looks for duplicate keys and non-constant expressions).
2132                 //
2133                 // It also returns a hashtable with the keys that we will later
2134                 // use to compute the switch tables
2135                 //
2136                 bool CheckSwitch (EmitContext ec)
2137                 {
2138                         Type compare_type;
2139                         bool error = false;
2140                         Elements = new Hashtable ();
2141                                 
2142                         got_default = false;
2143
2144                         if (TypeManager.IsEnumType (SwitchType)){
2145                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2146                         } else
2147                                 compare_type = SwitchType;
2148                         
2149                         foreach (SwitchSection ss in Sections){
2150                                 foreach (SwitchLabel sl in ss.Labels){
2151                                         if (!sl.ResolveAndReduce (ec, SwitchType)){
2152                                                 error = true;
2153                                                 continue;
2154                                         }
2155
2156                                         if (sl.Label == null){
2157                                                 if (got_default){
2158                                                         error152 ("default");
2159                                                         error = true;
2160                                                 }
2161                                                 got_default = true;
2162                                                 continue;
2163                                         }
2164                                         
2165                                         object key = sl.Converted;
2166
2167                                         if (key is Constant)
2168                                                 key = ((Constant) key).GetValue ();
2169
2170                                         if (key == null)
2171                                                 key = NullLiteral.Null;
2172                                         
2173                                         string lname = null;
2174                                         if (compare_type == TypeManager.uint64_type){
2175                                                 ulong v = (ulong) key;
2176
2177                                                 if (Elements.Contains (v))
2178                                                         lname = v.ToString ();
2179                                                 else
2180                                                         Elements.Add (v, sl);
2181                                         } else if (compare_type == TypeManager.int64_type){
2182                                                 long v = (long) key;
2183
2184                                                 if (Elements.Contains (v))
2185                                                         lname = v.ToString ();
2186                                                 else
2187                                                         Elements.Add (v, sl);
2188                                         } else if (compare_type == TypeManager.uint32_type){
2189                                                 uint v = (uint) key;
2190
2191                                                 if (Elements.Contains (v))
2192                                                         lname = v.ToString ();
2193                                                 else
2194                                                         Elements.Add (v, sl);
2195                                         } else if (compare_type == TypeManager.char_type){
2196                                                 char v = (char) key;
2197                                                 
2198                                                 if (Elements.Contains (v))
2199                                                         lname = v.ToString ();
2200                                                 else
2201                                                         Elements.Add (v, sl);
2202                                         } else if (compare_type == TypeManager.byte_type){
2203                                                 byte v = (byte) key;
2204                                                 
2205                                                 if (Elements.Contains (v))
2206                                                         lname = v.ToString ();
2207                                                 else
2208                                                         Elements.Add (v, sl);
2209                                         } else if (compare_type == TypeManager.sbyte_type){
2210                                                 sbyte v = (sbyte) key;
2211                                                 
2212                                                 if (Elements.Contains (v))
2213                                                         lname = v.ToString ();
2214                                                 else
2215                                                         Elements.Add (v, sl);
2216                                         } else if (compare_type == TypeManager.short_type){
2217                                                 short v = (short) key;
2218                                                 
2219                                                 if (Elements.Contains (v))
2220                                                         lname = v.ToString ();
2221                                                 else
2222                                                         Elements.Add (v, sl);
2223                                         } else if (compare_type == TypeManager.ushort_type){
2224                                                 ushort v = (ushort) key;
2225                                                 
2226                                                 if (Elements.Contains (v))
2227                                                         lname = v.ToString ();
2228                                                 else
2229                                                         Elements.Add (v, sl);
2230                                         } else if (compare_type == TypeManager.string_type){
2231                                                 if (key is NullLiteral){
2232                                                         if (Elements.Contains (NullLiteral.Null))
2233                                                                 lname = "null";
2234                                                         else
2235                                                                 Elements.Add (NullLiteral.Null, null);
2236                                                 } else {
2237                                                         string s = (string) key;
2238
2239                                                         if (Elements.Contains (s))
2240                                                                 lname = s;
2241                                                         else
2242                                                                 Elements.Add (s, sl);
2243                                                 }
2244                                         } else if (compare_type == TypeManager.int32_type) {
2245                                                 int v = (int) key;
2246
2247                                                 if (Elements.Contains (v))
2248                                                         lname = v.ToString ();
2249                                                 else
2250                                                         Elements.Add (v, sl);
2251                                         } else if (compare_type == TypeManager.bool_type) {
2252                                                 bool v = (bool) key;
2253
2254                                                 if (Elements.Contains (v))
2255                                                         lname = v.ToString ();
2256                                                 else
2257                                                         Elements.Add (v, sl);
2258                                         }
2259                                         else
2260                                         {
2261                                                 throw new Exception ("Unknown switch type!" +
2262                                                                      SwitchType + " " + compare_type);
2263                                         }
2264
2265                                         if (lname != null){
2266                                                 error152 ("case + " + lname);
2267                                                 error = true;
2268                                         }
2269                                 }
2270                         }
2271                         if (error)
2272                                 return false;
2273                         
2274                         return true;
2275                 }
2276
2277                 void EmitObjectInteger (ILGenerator ig, object k)
2278                 {
2279                         if (k is int)
2280                                 IntConstant.EmitInt (ig, (int) k);
2281                         else if (k is Constant) {
2282                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2283                         } 
2284                         else if (k is uint)
2285                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2286                         else if (k is long)
2287                         {
2288                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2289                                 {
2290                                         IntConstant.EmitInt (ig, (int) (long) k);
2291                                         ig.Emit (OpCodes.Conv_I8);
2292                                 }
2293                                 else
2294                                         LongConstant.EmitLong (ig, (long) k);
2295                         }
2296                         else if (k is ulong)
2297                         {
2298                                 if ((ulong) k < (1L<<32))
2299                                 {
2300                                         IntConstant.EmitInt (ig, (int) (long) k);
2301                                         ig.Emit (OpCodes.Conv_U8);
2302                                 }
2303                                 else
2304                                 {
2305                                         LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2306                                 }
2307                         }
2308                         else if (k is char)
2309                                 IntConstant.EmitInt (ig, (int) ((char) k));
2310                         else if (k is sbyte)
2311                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2312                         else if (k is byte)
2313                                 IntConstant.EmitInt (ig, (int) ((byte) k));
2314                         else if (k is short)
2315                                 IntConstant.EmitInt (ig, (int) ((short) k));
2316                         else if (k is ushort)
2317                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
2318                         else if (k is bool)
2319                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2320                         else
2321                                 throw new Exception ("Unhandled case");
2322                 }
2323                 
2324                 // structure used to hold blocks of keys while calculating table switch
2325                 class KeyBlock : IComparable
2326                 {
2327                         public KeyBlock (long _nFirst)
2328                         {
2329                                 nFirst = nLast = _nFirst;
2330                         }
2331                         public long nFirst;
2332                         public long nLast;
2333                         public ArrayList rgKeys = null;
2334                         // how many items are in the bucket
2335                         public int Size = 1;
2336                         public int Length
2337                         {
2338                                 get { return (int) (nLast - nFirst + 1); }
2339                         }
2340                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2341                         {
2342                                 return kbLast.nLast - kbFirst.nFirst + 1;
2343                         }
2344                         public int CompareTo (object obj)
2345                         {
2346                                 KeyBlock kb = (KeyBlock) obj;
2347                                 int nLength = Length;
2348                                 int nLengthOther = kb.Length;
2349                                 if (nLengthOther == nLength)
2350                                         return (int) (kb.nFirst - nFirst);
2351                                 return nLength - nLengthOther;
2352                         }
2353                 }
2354
2355                 /// <summary>
2356                 /// This method emits code for a lookup-based switch statement (non-string)
2357                 /// Basically it groups the cases into blocks that are at least half full,
2358                 /// and then spits out individual lookup opcodes for each block.
2359                 /// It emits the longest blocks first, and short blocks are just
2360                 /// handled with direct compares.
2361                 /// </summary>
2362                 /// <param name="ec"></param>
2363                 /// <param name="val"></param>
2364                 /// <returns></returns>
2365                 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2366                 {
2367                         int cElements = Elements.Count;
2368                         object [] rgKeys = new object [cElements];
2369                         Elements.Keys.CopyTo (rgKeys, 0);
2370                         Array.Sort (rgKeys);
2371
2372                         // initialize the block list with one element per key
2373                         ArrayList rgKeyBlocks = new ArrayList ();
2374                         foreach (object key in rgKeys)
2375                                 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2376
2377                         KeyBlock kbCurr;
2378                         // iteratively merge the blocks while they are at least half full
2379                         // there's probably a really cool way to do this with a tree...
2380                         while (rgKeyBlocks.Count > 1)
2381                         {
2382                                 ArrayList rgKeyBlocksNew = new ArrayList ();
2383                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2384                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2385                                 {
2386                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2387                                         if ((kbCurr.Size + kb.Size) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
2388                                         {
2389                                                 // merge blocks
2390                                                 kbCurr.nLast = kb.nLast;
2391                                                 kbCurr.Size += kb.Size;
2392                                         }
2393                                         else
2394                                         {
2395                                                 // start a new block
2396                                                 rgKeyBlocksNew.Add (kbCurr);
2397                                                 kbCurr = kb;
2398                                         }
2399                                 }
2400                                 rgKeyBlocksNew.Add (kbCurr);
2401                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2402                                         break;
2403                                 rgKeyBlocks = rgKeyBlocksNew;
2404                         }
2405
2406                         // initialize the key lists
2407                         foreach (KeyBlock kb in rgKeyBlocks)
2408                                 kb.rgKeys = new ArrayList ();
2409
2410                         // fill the key lists
2411                         int iBlockCurr = 0;
2412                         if (rgKeyBlocks.Count > 0) {
2413                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2414                                 foreach (object key in rgKeys)
2415                                 {
2416                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2417                                                 System.Convert.ToInt64 (key) > kbCurr.nLast;
2418                                         if (fNextBlock)
2419                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2420                                         kbCurr.rgKeys.Add (key);
2421                                 }
2422                         }
2423
2424                         // sort the blocks so we can tackle the largest ones first
2425                         rgKeyBlocks.Sort ();
2426
2427                         // okay now we can start...
2428                         ILGenerator ig = ec.ig;
2429                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
2430                         Label lblDefault = ig.DefineLabel ();
2431
2432                         Type typeKeys = null;
2433                         if (rgKeys.Length > 0)
2434                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
2435
2436                         Type compare_type;
2437                         
2438                         if (TypeManager.IsEnumType (SwitchType))
2439                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2440                         else
2441                                 compare_type = SwitchType;
2442                         
2443                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2444                         {
2445                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2446                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2447                                 if (kb.Length <= 2)
2448                                 {
2449                                         foreach (object key in kb.rgKeys)
2450                                         {
2451                                                 ig.Emit (OpCodes.Ldloc, val);
2452                                                 EmitObjectInteger (ig, key);
2453                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
2454                                                 ig.Emit (OpCodes.Beq, sl.ILLabel);
2455                                         }
2456                                 }
2457                                 else
2458                                 {
2459                                         // TODO: if all the keys in the block are the same and there are
2460                                         //       no gaps/defaults then just use a range-check.
2461                                         if (compare_type == TypeManager.int64_type ||
2462                                                 compare_type == TypeManager.uint64_type)
2463                                         {
2464                                                 // TODO: optimize constant/I4 cases
2465
2466                                                 // check block range (could be > 2^31)
2467                                                 ig.Emit (OpCodes.Ldloc, val);
2468                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2469                                                 ig.Emit (OpCodes.Blt, lblDefault);
2470                                                 ig.Emit (OpCodes.Ldloc, val);
2471                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2472                                                 ig.Emit (OpCodes.Bgt, lblDefault);
2473
2474                                                 // normalize range
2475                                                 ig.Emit (OpCodes.Ldloc, val);
2476                                                 if (kb.nFirst != 0)
2477                                                 {
2478                                                         EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2479                                                         ig.Emit (OpCodes.Sub);
2480                                                 }
2481                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
2482                                         }
2483                                         else
2484                                         {
2485                                                 // normalize range
2486                                                 ig.Emit (OpCodes.Ldloc, val);
2487                                                 int nFirst = (int) kb.nFirst;
2488                                                 if (nFirst > 0)
2489                                                 {
2490                                                         IntConstant.EmitInt (ig, nFirst);
2491                                                         ig.Emit (OpCodes.Sub);
2492                                                 }
2493                                                 else if (nFirst < 0)
2494                                                 {
2495                                                         IntConstant.EmitInt (ig, -nFirst);
2496                                                         ig.Emit (OpCodes.Add);
2497                                                 }
2498                                         }
2499
2500                                         // first, build the list of labels for the switch
2501                                         int iKey = 0;
2502                                         int cJumps = kb.Length;
2503                                         Label [] rgLabels = new Label [cJumps];
2504                                         for (int iJump = 0; iJump < cJumps; iJump++)
2505                                         {
2506                                                 object key = kb.rgKeys [iKey];
2507                                                 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2508                                                 {
2509                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
2510                                                         rgLabels [iJump] = sl.ILLabel;
2511                                                         iKey++;
2512                                                 }
2513                                                 else
2514                                                         rgLabels [iJump] = lblDefault;
2515                                         }
2516                                         // emit the switch opcode
2517                                         ig.Emit (OpCodes.Switch, rgLabels);
2518                                 }
2519
2520                                 // mark the default for this block
2521                                 if (iBlock != 0)
2522                                         ig.MarkLabel (lblDefault);
2523                         }
2524
2525                         // TODO: find the default case and emit it here,
2526                         //       to prevent having to do the following jump.
2527                         //       make sure to mark other labels in the default section
2528
2529                         // the last default just goes to the end
2530                         ig.Emit (OpCodes.Br, lblDefault);
2531
2532                         // now emit the code for the sections
2533                         bool fFoundDefault = false;
2534                         foreach (SwitchSection ss in Sections)
2535                         {
2536                                 foreach (SwitchLabel sl in ss.Labels)
2537                                 {
2538                                         ig.MarkLabel (sl.ILLabel);
2539                                         ig.MarkLabel (sl.ILLabelCode);
2540                                         if (sl.Label == null)
2541                                         {
2542                                                 ig.MarkLabel (lblDefault);
2543                                                 fFoundDefault = true;
2544                                         }
2545                                 }
2546                                 ss.Block.Emit (ec);
2547                                 //ig.Emit (OpCodes.Br, lblEnd);
2548                         }
2549                         
2550                         if (!fFoundDefault) {
2551                                 ig.MarkLabel (lblDefault);
2552                         }
2553                         ig.MarkLabel (lblEnd);
2554                 }
2555                 //
2556                 // This simple emit switch works, but does not take advantage of the
2557                 // `switch' opcode. 
2558                 // TODO: remove non-string logic from here
2559                 // TODO: binary search strings?
2560                 //
2561                 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2562                 {
2563                         ILGenerator ig = ec.ig;
2564                         Label end_of_switch = ig.DefineLabel ();
2565                         Label next_test = ig.DefineLabel ();
2566                         Label null_target = ig.DefineLabel ();
2567                         bool default_found = false;
2568                         bool first_test = true;
2569                         bool pending_goto_end = false;
2570                         bool null_found;
2571                         bool default_at_end = false;
2572                         
2573                         ig.Emit (OpCodes.Ldloc, val);
2574                         
2575                         if (Elements.Contains (NullLiteral.Null)){
2576                                 ig.Emit (OpCodes.Brfalse, null_target);
2577                         } else
2578                                 ig.Emit (OpCodes.Brfalse, default_target);
2579                         
2580                         ig.Emit (OpCodes.Ldloc, val);
2581                         ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2582                         ig.Emit (OpCodes.Stloc, val);
2583                 
2584                         int section_count = Sections.Count;
2585                         for (int section = 0; section < section_count; section++){
2586                                 SwitchSection ss = (SwitchSection) Sections [section];
2587                                 Label sec_begin = ig.DefineLabel ();
2588
2589                                 if (pending_goto_end)
2590                                         ig.Emit (OpCodes.Br, end_of_switch);
2591
2592                                 int label_count = ss.Labels.Count;
2593                                 bool mark_default = false;
2594                                 null_found = false;
2595                                 for (int label = 0; label < label_count; label++){
2596                                         SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2597                                         ig.MarkLabel (sl.ILLabel);
2598                                         
2599                                         if (!first_test){
2600                                                 ig.MarkLabel (next_test);
2601                                                 next_test = ig.DefineLabel ();
2602                                         }
2603                                         //
2604                                         // If we are the default target
2605                                         //
2606                                         if (sl.Label == null){
2607                                                 if (label+1 == label_count)
2608                                                         default_at_end = true;
2609                                                 mark_default = true;
2610                                                 default_found = true;
2611                                         } else {
2612                                                 object lit = sl.Converted;
2613
2614                                                 if (lit is NullLiteral){
2615                                                         null_found = true;
2616                                                         if (label_count == 1)
2617                                                                 ig.Emit (OpCodes.Br, next_test);
2618                                                         continue;
2619                                                                               
2620                                                 }
2621                                                 StringConstant str = (StringConstant) lit;
2622                                                 
2623                                                 ig.Emit (OpCodes.Ldloc, val);
2624                                                 ig.Emit (OpCodes.Ldstr, str.Value);
2625                                                 if (label_count == 1)
2626                                                         ig.Emit (OpCodes.Bne_Un, next_test);
2627                                                 else {
2628                                                         if (label+1 == label_count)
2629                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
2630                                                         else
2631                                                                 ig.Emit (OpCodes.Beq, sec_begin);
2632                                                 }
2633                                         }
2634                                 }
2635                                 if (null_found)
2636                                         ig.MarkLabel (null_target);
2637                                 ig.MarkLabel (sec_begin);
2638                                 foreach (SwitchLabel sl in ss.Labels)
2639                                         ig.MarkLabel (sl.ILLabelCode);
2640
2641                                 if (mark_default)
2642                                         ig.MarkLabel (default_target);
2643                                 ss.Block.Emit (ec);
2644                                 pending_goto_end = !ss.Block.HasRet;
2645                                 first_test = false;
2646                         }
2647                         ig.MarkLabel (next_test);
2648                         if (default_found){
2649                                 if (!default_at_end)
2650                                         ig.Emit (OpCodes.Br, default_target);
2651                         } else 
2652                                 ig.MarkLabel (default_target);
2653                         ig.MarkLabel (end_of_switch);
2654                 }
2655
2656                 SwitchSection FindSection (SwitchLabel label)
2657                 {
2658                         foreach (SwitchSection ss in Sections){
2659                                 foreach (SwitchLabel sl in ss.Labels){
2660                                         if (label == sl)
2661                                                 return ss;
2662                                 }
2663                         }
2664
2665                         return null;
2666                 }
2667
2668                 bool ResolveConstantSwitch (EmitContext ec)
2669                 {
2670                         object key = ((Constant) new_expr).GetValue ();
2671                         SwitchLabel label = (SwitchLabel) Elements [key];
2672
2673                         if (label == null)
2674                                 return true;
2675
2676                         constant_section = FindSection (label);
2677                         if (constant_section == null)
2678                                 return true;
2679
2680                         if (constant_section.Block.Resolve (ec) != true)
2681                                 return false;
2682
2683                         return true;
2684                 }
2685
2686                 public override bool Resolve (EmitContext ec)
2687                 {
2688                         Expr = Expr.Resolve (ec);
2689                         if (Expr == null)
2690                                 return false;
2691
2692                         new_expr = SwitchGoverningType (ec, Expr.Type);
2693                         if (new_expr == null){
2694                                 Report.Error (151, loc, "An integer type or string was expected for switch");
2695                                 return false;
2696                         }
2697
2698                         // Validate switch.
2699                         SwitchType = new_expr.Type;
2700
2701                         if (!CheckSwitch (ec))
2702                                 return false;
2703
2704                         Switch old_switch = ec.Switch;
2705                         ec.Switch = this;
2706                         ec.Switch.SwitchType = SwitchType;
2707
2708                         Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2709                         ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2710
2711                         is_constant = new_expr is Constant;
2712                         if (is_constant) {
2713                                 object key = ((Constant) new_expr).GetValue ();
2714                                 SwitchLabel label = (SwitchLabel) Elements [key];
2715
2716                                 constant_section = FindSection (label);
2717                         }
2718
2719                         bool first = true;
2720                         foreach (SwitchSection ss in Sections){
2721                                 if (!first)
2722                                         ec.CurrentBranching.CreateSibling (
2723                                                 null, FlowBranching.SiblingType.SwitchSection);
2724                                 else
2725                                         first = false;
2726
2727                                 if (is_constant && (ss != constant_section)) {
2728                                         // If we're a constant switch, we're only emitting
2729                                         // one single section - mark all the others as
2730                                         // unreachable.
2731                                         ec.CurrentBranching.CurrentUsageVector.Goto ();
2732                                         if (!ss.Block.ResolveUnreachable (ec, true))
2733                                                 return false;
2734                                 } else {
2735                                         if (!ss.Block.Resolve (ec))
2736                                         return false;
2737                         }
2738                         }
2739
2740                         if (!got_default)
2741                                 ec.CurrentBranching.CreateSibling (
2742                                         null, FlowBranching.SiblingType.SwitchSection);
2743
2744                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2745                         ec.Switch = old_switch;
2746
2747                         Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2748                                       reachability);
2749
2750                         return true;
2751                 }
2752                 
2753                 protected override void DoEmit (EmitContext ec)
2754                 {
2755                         ILGenerator ig = ec.ig;
2756
2757                         // Store variable for comparission purposes
2758                         LocalBuilder value;
2759                         if (!is_constant) {
2760                                 value = ig.DeclareLocal (SwitchType);
2761                         new_expr.Emit (ec);
2762                                 ig.Emit (OpCodes.Stloc, value);
2763                         } else
2764                                 value = null;
2765
2766                         default_target = ig.DefineLabel ();
2767
2768                         //
2769                         // Setup the codegen context
2770                         //
2771                         Label old_end = ec.LoopEnd;
2772                         Switch old_switch = ec.Switch;
2773                         
2774                         ec.LoopEnd = ig.DefineLabel ();
2775                         ec.Switch = this;
2776
2777                         // Emit Code.
2778                         if (is_constant) {
2779                                 if (constant_section != null)
2780                                         constant_section.Block.Emit (ec);
2781                         } else if (SwitchType == TypeManager.string_type)
2782                                 SimpleSwitchEmit (ec, value);
2783                         else
2784                                 TableSwitchEmit (ec, value);
2785
2786                         // Restore context state. 
2787                         ig.MarkLabel (ec.LoopEnd);
2788
2789                         //
2790                         // Restore the previous context
2791                         //
2792                         ec.LoopEnd = old_end;
2793                         ec.Switch = old_switch;
2794                 }
2795         }
2796
2797         public abstract class ExceptionStatement : Statement
2798         {
2799                 public abstract void EmitFinally (EmitContext ec);
2800
2801                 protected bool emit_finally = true;
2802                 ArrayList parent_vectors;
2803
2804                 protected void DoEmitFinally (EmitContext ec)
2805                 {
2806                         if (emit_finally)
2807                                 ec.ig.BeginFinallyBlock ();
2808                         else
2809                                 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
2810                         EmitFinally (ec);
2811                 }
2812
2813                 protected void ResolveFinally (FlowBranchingException branching)
2814                 {
2815                         emit_finally = branching.EmitFinally;
2816                         if (!emit_finally)
2817                                 branching.Parent.StealFinallyClauses (ref parent_vectors);
2818                 }
2819         }
2820
2821         public class Lock : ExceptionStatement {
2822                 Expression expr;
2823                 Statement Statement;
2824                 LocalBuilder temp;
2825                         
2826                 public Lock (Expression expr, Statement stmt, Location l)
2827                 {
2828                         this.expr = expr;
2829                         Statement = stmt;
2830                         loc = l;
2831                 }
2832
2833                 public override bool Resolve (EmitContext ec)
2834                 {
2835                         expr = expr.Resolve (ec);
2836                         if (expr == null)
2837                                 return false;
2838
2839                         if (expr.Type.IsValueType){
2840                                 Error (185, "lock statement requires the expression to be " +
2841                                        " a reference type (type is: `{0}'",
2842                                        TypeManager.CSharpName (expr.Type));
2843                                 return false;
2844                         }
2845
2846                         FlowBranchingException branching = ec.StartFlowBranching (this);
2847                         bool ok = Statement.Resolve (ec);
2848                         if (!ok) {
2849                                 ec.KillFlowBranching ();
2850                                 return false;
2851                         }
2852
2853                         ResolveFinally (branching);
2854
2855                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2856                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
2857                                 // Unfortunately, System.Reflection.Emit automatically emits
2858                                 // a leave to the end of the finally block.
2859                                 // This is a problem if `returns' is true since we may jump
2860                                 // to a point after the end of the method.
2861                                 // As a workaround, emit an explicit ret here.
2862                                 ec.NeedReturnLabel ();
2863                         }
2864
2865                         return true;
2866                 }
2867                 
2868                 protected override void DoEmit (EmitContext ec)
2869                 {
2870                         Type type = expr.Type;
2871                         
2872                         ILGenerator ig = ec.ig;
2873                         temp = ig.DeclareLocal (type);
2874                                 
2875                         expr.Emit (ec);
2876                         ig.Emit (OpCodes.Dup);
2877                         ig.Emit (OpCodes.Stloc, temp);
2878                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2879
2880                         // try
2881                         if (emit_finally)
2882                                 ig.BeginExceptionBlock ();
2883                         Statement.Emit (ec);
2884                         
2885                         // finally
2886                         DoEmitFinally (ec);
2887                         if (emit_finally)
2888                                 ig.EndExceptionBlock ();
2889                 }
2890
2891                 public override void EmitFinally (EmitContext ec)
2892                 {
2893                         ILGenerator ig = ec.ig;
2894                         ig.Emit (OpCodes.Ldloc, temp);
2895                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2896                 }
2897         }
2898
2899         public class Unchecked : Statement {
2900                 public readonly Block Block;
2901                 
2902                 public Unchecked (Block b)
2903                 {
2904                         Block = b;
2905                         b.Unchecked = true;
2906                 }
2907
2908                 public override bool Resolve (EmitContext ec)
2909                 {
2910                         bool previous_state = ec.CheckState;
2911                         bool previous_state_const = ec.ConstantCheckState;
2912
2913                         ec.CheckState = false;
2914                         ec.ConstantCheckState = false;
2915                         bool ret = Block.Resolve (ec);
2916                         ec.CheckState = previous_state;
2917                         ec.ConstantCheckState = previous_state_const;
2918
2919                         return ret;
2920                 }
2921                 
2922                 protected override void DoEmit (EmitContext ec)
2923                 {
2924                         bool previous_state = ec.CheckState;
2925                         bool previous_state_const = ec.ConstantCheckState;
2926                         
2927                         ec.CheckState = false;
2928                         ec.ConstantCheckState = false;
2929                         Block.Emit (ec);
2930                         ec.CheckState = previous_state;
2931                         ec.ConstantCheckState = previous_state_const;
2932                 }
2933         }
2934
2935         public class Checked : Statement {
2936                 public readonly Block Block;
2937                 
2938                 public Checked (Block b)
2939                 {
2940                         Block = b;
2941                         b.Unchecked = false;
2942                 }
2943
2944                 public override bool Resolve (EmitContext ec)
2945                 {
2946                         bool previous_state = ec.CheckState;
2947                         bool previous_state_const = ec.ConstantCheckState;
2948                         
2949                         ec.CheckState = true;
2950                         ec.ConstantCheckState = true;
2951                         bool ret = Block.Resolve (ec);
2952                         ec.CheckState = previous_state;
2953                         ec.ConstantCheckState = previous_state_const;
2954
2955                         return ret;
2956                 }
2957
2958                 protected override void DoEmit (EmitContext ec)
2959                 {
2960                         bool previous_state = ec.CheckState;
2961                         bool previous_state_const = ec.ConstantCheckState;
2962                         
2963                         ec.CheckState = true;
2964                         ec.ConstantCheckState = true;
2965                         Block.Emit (ec);
2966                         ec.CheckState = previous_state;
2967                         ec.ConstantCheckState = previous_state_const;
2968                 }
2969         }
2970
2971         public class Unsafe : Statement {
2972                 public readonly Block Block;
2973
2974                 public Unsafe (Block b)
2975                 {
2976                         Block = b;
2977                 }
2978
2979                 public override bool Resolve (EmitContext ec)
2980                 {
2981                         bool previous_state = ec.InUnsafe;
2982                         bool val;
2983                         
2984                         ec.InUnsafe = true;
2985                         val = Block.Resolve (ec);
2986                         ec.InUnsafe = previous_state;
2987
2988                         return val;
2989                 }
2990                 
2991                 protected override void DoEmit (EmitContext ec)
2992                 {
2993                         bool previous_state = ec.InUnsafe;
2994                         
2995                         ec.InUnsafe = true;
2996                         Block.Emit (ec);
2997                         ec.InUnsafe = previous_state;
2998                 }
2999         }
3000
3001         // 
3002         // Fixed statement
3003         //
3004         public class Fixed : Statement {
3005                 Expression type;
3006                 ArrayList declarators;
3007                 Statement statement;
3008                 Type expr_type;
3009                 FixedData[] data;
3010                 bool has_ret;
3011
3012                 struct FixedData {
3013                         public bool is_object;
3014                         public LocalInfo vi;
3015                         public Expression expr;
3016                         public Expression converted;
3017                 }                       
3018
3019                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3020                 {
3021                         this.type = type;
3022                         declarators = decls;
3023                         statement = stmt;
3024                         loc = l;
3025                 }
3026
3027                 public override bool Resolve (EmitContext ec)
3028                 {
3029                         if (!ec.InUnsafe){
3030                                 Expression.UnsafeError (loc);
3031                                 return false;
3032                         }
3033                         
3034                         expr_type = ec.DeclSpace.ResolveType (type, false, loc);
3035                         if (expr_type == null)
3036                                 return false;
3037
3038                         CheckObsolete (expr_type);
3039
3040                         if (ec.RemapToProxy){
3041                                 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3042                                 return false;
3043                         }
3044                         
3045                         data = new FixedData [declarators.Count];
3046
3047                         if (!expr_type.IsPointer){
3048                                 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3049                                 return false;
3050                         }
3051                         
3052                         int i = 0;
3053                         foreach (Pair p in declarators){
3054                                 LocalInfo vi = (LocalInfo) p.First;
3055                                 Expression e = (Expression) p.Second;
3056
3057                                 vi.VariableInfo = null;
3058                                 vi.ReadOnly = true;
3059
3060                                 //
3061                                 // The rules for the possible declarators are pretty wise,
3062                                 // but the production on the grammar is more concise.
3063                                 //
3064                                 // So we have to enforce these rules here.
3065                                 //
3066                                 // We do not resolve before doing the case 1 test,
3067                                 // because the grammar is explicit in that the token &
3068                                 // is present, so we need to test for this particular case.
3069                                 //
3070
3071                                 if (e is Cast){
3072                                         Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3073                                         return false;
3074                                 }
3075                                 
3076                                 //
3077                                 // Case 1: & object.
3078                                 //
3079                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3080                                         Expression child = ((Unary) e).Expr;
3081
3082                                         if (child is ParameterReference || child is LocalVariableReference){
3083                                                 Report.Error (
3084                                                         213, loc, 
3085                                                         "No need to use fixed statement for parameters or " +
3086                                                         "local variable declarations (address is already " +
3087                                                         "fixed)");
3088                                                 return false;
3089                                         }
3090
3091                                         ec.InFixedInitializer = true;
3092                                         e = e.Resolve (ec);
3093                                         ec.InFixedInitializer = false;
3094                                         if (e == null)
3095                                                 return false;
3096
3097                                         child = ((Unary) e).Expr;
3098                                         
3099                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
3100                                                 return false;
3101
3102                                         data [i].is_object = true;
3103                                         data [i].expr = e;
3104                                         data [i].converted = null;
3105                                         data [i].vi = vi;
3106                                         i++;
3107
3108                                         continue;
3109                                 }
3110
3111                                 ec.InFixedInitializer = true;
3112                                 e = e.Resolve (ec);
3113                                 ec.InFixedInitializer = false;
3114                                 if (e == null)
3115                                         return false;
3116
3117                                 //
3118                                 // Case 2: Array
3119                                 //
3120                                 if (e.Type.IsArray){
3121                                         Type array_type = TypeManager.GetElementType (e.Type);
3122                                         
3123                                         //
3124                                         // Provided that array_type is unmanaged,
3125                                         //
3126                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
3127                                                 return false;
3128
3129                                         //
3130                                         // and T* is implicitly convertible to the
3131                                         // pointer type given in the fixed statement.
3132                                         //
3133                                         ArrayPtr array_ptr = new ArrayPtr (e, loc);
3134                                         
3135                                         Expression converted = Convert.ImplicitConversionRequired (
3136                                                 ec, array_ptr, vi.VariableType, loc);
3137                                         if (converted == null)
3138                                                 return false;
3139
3140                                         data [i].is_object = false;
3141                                         data [i].expr = e;
3142                                         data [i].converted = converted;
3143                                         data [i].vi = vi;
3144                                         i++;
3145
3146                                         continue;
3147                                 }
3148
3149                                 //
3150                                 // Case 3: string
3151                                 //
3152                                 if (e.Type == TypeManager.string_type){
3153                                         data [i].is_object = false;
3154                                         data [i].expr = e;
3155                                         data [i].converted = null;
3156                                         data [i].vi = vi;
3157                                         i++;
3158                                         continue;
3159                                 }
3160
3161                                 //
3162                                 // For other cases, flag a `this is already fixed expression'
3163                                 //
3164                                 if (e is LocalVariableReference || e is ParameterReference ||
3165                                     Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3166                                     
3167                                         Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3168                                         return false;
3169                                 }
3170
3171                                 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3172                                 return false;
3173                         }
3174
3175                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3176
3177                         if (!statement.Resolve (ec)) {
3178                                 ec.KillFlowBranching ();
3179                                 return false;
3180                         }
3181
3182                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3183                         has_ret = reachability.IsUnreachable;
3184
3185                         return true;
3186                 }
3187                 
3188                 protected override void DoEmit (EmitContext ec)
3189                 {
3190                         ILGenerator ig = ec.ig;
3191
3192                         LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3193                         
3194                         for (int i = 0; i < data.Length; i++) {
3195                                 LocalInfo vi = data [i].vi;
3196
3197                                 //
3198                                 // Case 1: & object.
3199                                 //
3200                                 if (data [i].is_object) {
3201                                         //
3202                                         // Store pointer in pinned location
3203                                         //
3204                                         data [i].expr.Emit (ec);
3205                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3206                                         clear_list [i] = vi.LocalBuilder;
3207                                         continue;
3208                                 }
3209
3210                                 //
3211                                 // Case 2: Array
3212                                 //
3213                                 if (data [i].expr.Type.IsArray){
3214                                         //
3215                                         // Store pointer in pinned location
3216                                         //
3217                                         data [i].converted.Emit (ec);
3218                                         
3219                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3220                                         clear_list [i] = vi.LocalBuilder;
3221                                         continue;
3222                                 }
3223
3224                                 //
3225                                 // Case 3: string
3226                                 //
3227                                 if (data [i].expr.Type == TypeManager.string_type){
3228                                         LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3229                                         clear_list [i] = pinned_string;
3230                                         
3231                                         data [i].expr.Emit (ec);
3232                                         ig.Emit (OpCodes.Stloc, pinned_string);
3233
3234                                         Expression sptr = new StringPtr (pinned_string, loc);
3235                                         Expression converted = Convert.ImplicitConversionRequired (
3236                                                 ec, sptr, vi.VariableType, loc);
3237                                         
3238                                         if (converted == null)
3239                                                 continue;
3240
3241                                         converted.Emit (ec);
3242                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3243                                 }
3244                         }
3245
3246                         statement.Emit (ec);
3247
3248                         if (has_ret)
3249                                 return;
3250
3251                         //
3252                         // Clear the pinned variable
3253                         //
3254                         for (int i = 0; i < data.Length; i++) {
3255                                 if (data [i].is_object || data [i].expr.Type.IsArray) {
3256                                         ig.Emit (OpCodes.Ldc_I4_0);
3257                                         ig.Emit (OpCodes.Conv_U);
3258                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3259                                 } else if (data [i].expr.Type == TypeManager.string_type){
3260                                         ig.Emit (OpCodes.Ldnull);
3261                                         ig.Emit (OpCodes.Stloc, clear_list [i]);
3262                                 }
3263                         }
3264                 }
3265         }
3266         
3267         public class Catch: Statement {
3268                 public readonly string Name;
3269                 public readonly Block  Block;
3270
3271                 Expression type_expr;
3272                 Type type;
3273                 
3274                 public Catch (Expression type, string name, Block block, Location l)
3275                 {
3276                         type_expr = type;
3277                         Name = name;
3278                         Block = block;
3279                         loc = l;
3280                 }
3281
3282                 public Type CatchType {
3283                         get {
3284                                 return type;
3285                         }
3286                 }
3287
3288                 public bool IsGeneral {
3289                         get {
3290                                 return type_expr == null;
3291                         }
3292                 }
3293
3294                 protected override void DoEmit(EmitContext ec)
3295                 {
3296                 }
3297
3298                 public override bool Resolve (EmitContext ec)
3299                 {
3300                         if (type_expr != null) {
3301                                 type = ec.DeclSpace.ResolveType (type_expr, false, loc);
3302                                 if (type == null)
3303                                         return false;
3304
3305                                 CheckObsolete (type);
3306
3307                                 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3308                                         Error (155, "The type caught or thrown must be derived from System.Exception");
3309                                         return false;
3310                                 }
3311                         } else
3312                                 type = null;
3313
3314                         return Block.Resolve (ec);
3315                 }
3316         }
3317
3318         public class Try : ExceptionStatement {
3319                 public readonly Block Fini, Block;
3320                 public readonly ArrayList Specific;
3321                 public readonly Catch General;
3322
3323                 bool need_exc_block;
3324                 
3325                 //
3326                 // specific, general and fini might all be null.
3327                 //
3328                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3329                 {
3330                         if (specific == null && general == null){
3331                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3332                         }
3333                         
3334                         this.Block = block;
3335                         this.Specific = specific;
3336                         this.General = general;
3337                         this.Fini = fini;
3338                         loc = l;
3339                 }
3340
3341                 public override bool Resolve (EmitContext ec)
3342                 {
3343                         bool ok = true;
3344                         
3345                         FlowBranchingException branching = ec.StartFlowBranching (this);
3346
3347                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3348
3349                         if (!Block.Resolve (ec))
3350                                 ok = false;
3351
3352                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3353
3354                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
3355
3356                         Type[] prevCatches = new Type [Specific.Count];
3357                         int last_index = 0;
3358                         foreach (Catch c in Specific){
3359                                 ec.CurrentBranching.CreateSibling (
3360                                         c.Block, FlowBranching.SiblingType.Catch);
3361
3362                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3363
3364                                 if (c.Name != null) {
3365                                         LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3366                                         if (vi == null)
3367                                                 throw new Exception ();
3368
3369                                         vi.VariableInfo = null;
3370                                 }
3371
3372                                 if (!c.Resolve (ec))
3373                                         return false;
3374
3375                                 Type resolvedType = c.CatchType;
3376                                 for (int ii = 0; ii < last_index; ++ii) {
3377                                         if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3378                                                 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3379                                                 return false;
3380                                         }
3381                                 }
3382
3383                                 prevCatches [last_index++] = resolvedType;
3384                                 need_exc_block = true;
3385                         }
3386
3387                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3388
3389                         if (General != null){
3390                                 ec.CurrentBranching.CreateSibling (
3391                                         General.Block, FlowBranching.SiblingType.Catch);
3392
3393                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3394
3395                                 if (!General.Resolve (ec))
3396                                         ok = false;
3397
3398                                 need_exc_block = true;
3399                         }
3400
3401                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3402
3403                         if (Fini != null) {
3404                                 if (ok)
3405                                         ec.CurrentBranching.CreateSibling (
3406                                                 Fini, FlowBranching.SiblingType.Finally);
3407
3408                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3409
3410                                 if (!Fini.Resolve (ec))
3411                                         ok = false;
3412                         }
3413
3414                         ResolveFinally (branching);
3415                         need_exc_block |= emit_finally;
3416
3417                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3418
3419                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3420
3421                         Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3422
3423                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3424                                 // Unfortunately, System.Reflection.Emit automatically emits
3425                                 // a leave to the end of the finally block.  This is a problem
3426                                 // if `returns' is true since we may jump to a point after the
3427                                 // end of the method.
3428                                 // As a workaround, emit an explicit ret here.
3429                                 ec.NeedReturnLabel ();
3430                         }
3431
3432                         return ok;
3433                 }
3434                 
3435                 protected override void DoEmit (EmitContext ec)
3436                 {
3437                         ILGenerator ig = ec.ig;
3438
3439                         if (need_exc_block)
3440                                 ig.BeginExceptionBlock ();
3441                         Block.Emit (ec);
3442
3443                         foreach (Catch c in Specific){
3444                                 LocalInfo vi;
3445                                 
3446                                 ig.BeginCatchBlock (c.CatchType);
3447
3448                                 if (c.Name != null){
3449                                         vi = c.Block.GetLocalInfo (c.Name);
3450                                         if (vi == null)
3451                                                 throw new Exception ("Variable does not exist in this block");
3452
3453                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3454                                 } else
3455                                         ig.Emit (OpCodes.Pop);
3456                                 
3457                                 c.Block.Emit (ec);
3458                         }
3459
3460                         if (General != null){
3461                                 ig.BeginCatchBlock (TypeManager.object_type);
3462                                 ig.Emit (OpCodes.Pop);
3463                                 General.Block.Emit (ec);
3464                         }
3465
3466                         DoEmitFinally (ec);
3467                         if (need_exc_block)
3468                                 ig.EndExceptionBlock ();
3469                 }
3470
3471                 public override void EmitFinally (EmitContext ec)
3472                 {
3473                         if (Fini != null){
3474                                 Fini.Emit (ec);
3475                         }
3476                 }
3477         }
3478
3479         public class Using : ExceptionStatement {
3480                 object expression_or_block;
3481                 Statement Statement;
3482                 ArrayList var_list;
3483                 Expression expr;
3484                 Type expr_type;
3485                 Expression conv;
3486                 Expression [] resolved_vars;
3487                 Expression [] converted_vars;
3488                 ExpressionStatement [] assign;
3489                 LocalBuilder local_copy;
3490                 
3491                 public Using (object expression_or_block, Statement stmt, Location l)
3492                 {
3493                         this.expression_or_block = expression_or_block;
3494                         Statement = stmt;
3495                         loc = l;
3496                 }
3497
3498                 //
3499                 // Resolves for the case of using using a local variable declaration.
3500                 //
3501                 bool ResolveLocalVariableDecls (EmitContext ec)
3502                 {
3503                         expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3504                         int i = 0;
3505
3506                         if (expr_type == null)
3507                                 return false;
3508
3509                         //
3510                         // The type must be an IDisposable or an implicit conversion
3511                         // must exist.
3512                         //
3513                         converted_vars = new Expression [var_list.Count];
3514                         resolved_vars = new Expression [var_list.Count];
3515                         assign = new ExpressionStatement [var_list.Count];
3516
3517                         bool need_conv = !TypeManager.ImplementsInterface (
3518                                 expr_type, TypeManager.idisposable_type);
3519
3520                         foreach (DictionaryEntry e in var_list){
3521                                 Expression var = (Expression) e.Key;
3522
3523                                 var = var.ResolveLValue (ec, new EmptyExpression ());
3524                                 if (var == null)
3525                                         return false;
3526
3527                                 resolved_vars [i] = var;
3528
3529                                 if (!need_conv) {
3530                                         i++;
3531                                         continue;
3532                                 }
3533
3534                                 converted_vars [i] = Convert.ImplicitConversionRequired (
3535                                         ec, var, TypeManager.idisposable_type, loc);
3536
3537                                 if (converted_vars [i] == null)
3538                                         return false;
3539
3540                                 i++;
3541                         }
3542
3543                         i = 0;
3544                         foreach (DictionaryEntry e in var_list){
3545                                 Expression var = resolved_vars [i];
3546                                 Expression new_expr = (Expression) e.Value;
3547                                 Expression a;
3548
3549                                 a = new Assign (var, new_expr, loc);
3550                                 a = a.Resolve (ec);
3551                                 if (a == null)
3552                                         return false;
3553
3554                                 if (!need_conv)
3555                                         converted_vars [i] = var;
3556                                 assign [i] = (ExpressionStatement) a;
3557                                 i++;
3558                         }
3559
3560                         return true;
3561                 }
3562
3563                 bool ResolveExpression (EmitContext ec)
3564                 {
3565                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3566                                 conv = Convert.ImplicitConversionRequired (
3567                                         ec, expr, TypeManager.idisposable_type, loc);
3568
3569                                 if (conv == null)
3570                                         return false;
3571                         }
3572
3573                         return true;
3574                 }
3575                 
3576                 //
3577                 // Emits the code for the case of using using a local variable declaration.
3578                 //
3579                 void EmitLocalVariableDecls (EmitContext ec)
3580                 {
3581                         ILGenerator ig = ec.ig;
3582                         int i = 0;
3583
3584                         for (i = 0; i < assign.Length; i++) {
3585                                 assign [i].EmitStatement (ec);
3586
3587                                 if (emit_finally)
3588                                         ig.BeginExceptionBlock ();
3589                         }
3590                         Statement.Emit (ec);
3591
3592                         var_list.Reverse ();
3593
3594                         DoEmitFinally (ec);
3595                 }
3596
3597                 void EmitLocalVariableDeclFinally (EmitContext ec)
3598                 {
3599                         ILGenerator ig = ec.ig;
3600
3601                         int i = assign.Length;
3602                         foreach (DictionaryEntry e in var_list){
3603                                 Expression var = resolved_vars [--i];
3604                                 Label skip = ig.DefineLabel ();
3605                                 
3606                                 ig.BeginFinallyBlock ();
3607                                 
3608                                 if (!var.Type.IsValueType) {
3609                                         var.Emit (ec);
3610                                         ig.Emit (OpCodes.Brfalse, skip);
3611                                         converted_vars [i].Emit (ec);
3612                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3613                                 } else {
3614                                         Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3615
3616                                         if (!(ml is MethodGroupExpr)) {
3617                                                 var.Emit (ec);
3618                                                 ig.Emit (OpCodes.Box, var.Type);
3619                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3620                                         } else {
3621                                                 MethodInfo mi = null;
3622
3623                                                 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3624                                                         if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3625                                                                 mi = mk;
3626                                                                 break;
3627                                                         }
3628                                                 }
3629
3630                                                 if (mi == null) {
3631                                                         Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3632                                                         return;
3633                                                 }
3634
3635                                                 IMemoryLocation mloc = (IMemoryLocation) var;
3636
3637                                                 mloc.AddressOf (ec, AddressOp.Load);
3638                                                 ig.Emit (OpCodes.Call, mi);
3639                                         }
3640                                 }
3641
3642                                 ig.MarkLabel (skip);
3643
3644                                 if (emit_finally) {
3645                                         ig.EndExceptionBlock ();
3646                                         if (i > 0)
3647                                                 ig.BeginFinallyBlock ();
3648                                 }
3649                         }
3650                 }
3651
3652                 void EmitExpression (EmitContext ec)
3653                 {
3654                         //
3655                         // Make a copy of the expression and operate on that.
3656                         //
3657                         ILGenerator ig = ec.ig;
3658                         local_copy = ig.DeclareLocal (expr_type);
3659                         if (conv != null)
3660                                 conv.Emit (ec);
3661                         else
3662                                 expr.Emit (ec);
3663                         ig.Emit (OpCodes.Stloc, local_copy);
3664
3665                         if (emit_finally)
3666                                 ig.BeginExceptionBlock ();
3667
3668                         Statement.Emit (ec);
3669                         
3670                         DoEmitFinally (ec);
3671                         if (emit_finally)
3672                                 ig.EndExceptionBlock ();
3673                 }
3674
3675                 void EmitExpressionFinally (EmitContext ec)
3676                 {
3677                         ILGenerator ig = ec.ig;
3678                         Label skip = ig.DefineLabel ();
3679                         ig.Emit (OpCodes.Ldloc, local_copy);
3680                         ig.Emit (OpCodes.Brfalse, skip);
3681                         ig.Emit (OpCodes.Ldloc, local_copy);
3682                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3683                         ig.MarkLabel (skip);
3684                 }
3685                 
3686                 public override bool Resolve (EmitContext ec)
3687                 {
3688                         if (expression_or_block is DictionaryEntry){
3689                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3690                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3691
3692                                 if (!ResolveLocalVariableDecls (ec))
3693                                         return false;
3694
3695                         } else if (expression_or_block is Expression){
3696                                 expr = (Expression) expression_or_block;
3697
3698                                 expr = expr.Resolve (ec);
3699                                 if (expr == null)
3700                                         return false;
3701
3702                                 expr_type = expr.Type;
3703
3704                                 if (!ResolveExpression (ec))
3705                                         return false;
3706                         }
3707
3708                         FlowBranchingException branching = ec.StartFlowBranching (this);
3709
3710                         bool ok = Statement.Resolve (ec);
3711
3712                         if (!ok) {
3713                                 ec.KillFlowBranching ();
3714                                 return false;
3715                         }
3716
3717                         ResolveFinally (branching);                                     
3718                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3719
3720                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3721                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
3722                                 // to the end of the finally block.  This is a problem if `returns'
3723                                 // is true since we may jump to a point after the end of the method.
3724                                 // As a workaround, emit an explicit ret here.
3725                                 ec.NeedReturnLabel ();
3726                         }
3727
3728                         return true;
3729                 }
3730                 
3731                 protected override void DoEmit (EmitContext ec)
3732                 {
3733                         if (expression_or_block is DictionaryEntry)
3734                                 EmitLocalVariableDecls (ec);
3735                         else if (expression_or_block is Expression)
3736                                 EmitExpression (ec);
3737                 }
3738
3739                 public override void EmitFinally (EmitContext ec)
3740                 {
3741                         if (expression_or_block is DictionaryEntry)
3742                                 EmitLocalVariableDeclFinally (ec);
3743                         else if (expression_or_block is Expression)
3744                                 EmitExpressionFinally (ec);
3745                 }
3746         }
3747
3748         /// <summary>
3749         ///   Implementation of the foreach C# statement
3750         /// </summary>
3751         public class Foreach : ExceptionStatement {
3752                 Expression type;
3753                 Expression variable;
3754                 Expression expr;
3755                 Statement statement;
3756                 ForeachHelperMethods hm;
3757                 Expression empty, conv;
3758                 Type array_type, element_type;
3759                 Type var_type;
3760                 VariableStorage enumerator;
3761                 
3762                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3763                                 Statement stmt, Location l)
3764                 {
3765                         this.type = type;
3766                         this.variable = var;
3767                         this.expr = expr;
3768                         statement = stmt;
3769                         loc = l;
3770                 }
3771                 
3772                 public override bool Resolve (EmitContext ec)
3773                 {
3774                         expr = expr.Resolve (ec);
3775                         if (expr == null)
3776                                 return false;
3777
3778                         var_type = ec.DeclSpace.ResolveType (type, false, loc);
3779                         if (var_type == null)
3780                                 return false;
3781                         
3782                         //
3783                         // We need an instance variable.  Not sure this is the best
3784                         // way of doing this.
3785                         //
3786                         // FIXME: When we implement propertyaccess, will those turn
3787                         // out to return values in ExprClass?  I think they should.
3788                         //
3789                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3790                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3791                                 error1579 (expr.Type);
3792                                 return false;
3793                         }
3794
3795                         if (expr.Type.IsArray) {
3796                                 array_type = expr.Type;
3797                                 element_type = TypeManager.GetElementType (array_type);
3798
3799                                 empty = new EmptyExpression (element_type);
3800                         } else {
3801                                 hm = ProbeCollectionType (ec, expr.Type);
3802                                 if (hm == null){
3803                                         error1579 (expr.Type);
3804                                         return false;
3805                                 }                       
3806
3807                                 array_type = expr.Type;
3808                                 element_type = hm.element_type;
3809
3810                                 empty = new EmptyExpression (hm.element_type);
3811                         }
3812
3813                         bool ok = true;
3814
3815                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3816                         ec.CurrentBranching.CreateSibling ();
3817
3818                         //
3819                         //
3820                         // FIXME: maybe we can apply the same trick we do in the
3821                         // array handling to avoid creating empty and conv in some cases.
3822                         //
3823                         // Although it is not as important in this case, as the type
3824                         // will not likely be object (what the enumerator will return).
3825                         //
3826                         conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3827                         if (conv == null)
3828                                 ok = false;
3829
3830                         variable = variable.ResolveLValue (ec, empty);
3831                         if (variable == null)
3832                                 ok = false;
3833
3834                         bool disposable = (hm != null) && hm.is_disposable;
3835                         FlowBranchingException branching = null;
3836                         if (disposable)
3837                                 branching = ec.StartFlowBranching (this);
3838
3839                         if (!statement.Resolve (ec))
3840                                 ok = false;
3841
3842                         if (disposable) {
3843                                 ResolveFinally (branching);
3844                                 ec.EndFlowBranching ();
3845                         } else
3846                                 emit_finally = true;
3847
3848                         ec.EndFlowBranching ();
3849
3850                         return ok;
3851                 }
3852                 
3853                 //
3854                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3855                 //
3856                 static MethodInfo FetchMethodMoveNext (Type t)
3857                 {
3858                         MemberList move_next_list;
3859                         
3860                         move_next_list = TypeContainer.FindMembers (
3861                                 t, MemberTypes.Method,
3862                                 BindingFlags.Public | BindingFlags.Instance,
3863                                 Type.FilterName, "MoveNext");
3864                         if (move_next_list.Count == 0)
3865                                 return null;
3866
3867                         foreach (MemberInfo m in move_next_list){
3868                                 MethodInfo mi = (MethodInfo) m;
3869                                 Type [] args;
3870                                 
3871                                 args = TypeManager.GetArgumentTypes (mi);
3872                                 if (args != null && args.Length == 0){
3873                                         if (mi.ReturnType == TypeManager.bool_type)
3874                                                 return mi;
3875                                 }
3876                         }
3877                         return null;
3878                 }
3879                 
3880                 //
3881                 // Retrieves a `public T get_Current ()' method from the Type `t'
3882                 //
3883                 static MethodInfo FetchMethodGetCurrent (Type t)
3884                 {
3885                         MemberList get_current_list;
3886
3887                         get_current_list = TypeContainer.FindMembers (
3888                                 t, MemberTypes.Method,
3889                                 BindingFlags.Public | BindingFlags.Instance,
3890                                 Type.FilterName, "get_Current");
3891                         if (get_current_list.Count == 0)
3892                                 return null;
3893
3894                         foreach (MemberInfo m in get_current_list){
3895                                 MethodInfo mi = (MethodInfo) m;
3896                                 Type [] args;
3897
3898                                 args = TypeManager.GetArgumentTypes (mi);
3899                                 if (args != null && args.Length == 0)
3900                                         return mi;
3901                         }
3902                         return null;
3903                 }
3904
3905                 // 
3906                 // Retrieves a `public void Dispose ()' method from the Type `t'
3907                 //
3908                 static MethodInfo FetchMethodDispose (Type t)
3909                 {
3910                         MemberList dispose_list;
3911                         
3912                         dispose_list = TypeContainer.FindMembers (
3913                                 t, MemberTypes.Method,
3914                                 BindingFlags.Public | BindingFlags.Instance,
3915                                 Type.FilterName, "Dispose");
3916                         if (dispose_list.Count == 0)
3917                                 return null;
3918
3919                         foreach (MemberInfo m in dispose_list){
3920                                 MethodInfo mi = (MethodInfo) m;
3921                                 Type [] args;
3922                                 
3923                                 args = TypeManager.GetArgumentTypes (mi);
3924                                 if (args != null && args.Length == 0){
3925                                         if (mi.ReturnType == TypeManager.void_type)
3926                                                 return mi;
3927                                 }
3928                         }
3929                         return null;
3930                 }
3931
3932                 // 
3933                 // This struct records the helper methods used by the Foreach construct
3934                 //
3935                 class ForeachHelperMethods {
3936                         public EmitContext ec;
3937                         public MethodInfo get_enumerator;
3938                         public MethodInfo move_next;
3939                         public MethodInfo get_current;
3940                         public Type element_type;
3941                         public Type enumerator_type;
3942                         public bool is_disposable;
3943
3944                         public ForeachHelperMethods (EmitContext ec)
3945                         {
3946                                 this.ec = ec;
3947                                 this.element_type = TypeManager.object_type;
3948                                 this.enumerator_type = TypeManager.ienumerator_type;
3949                                 this.is_disposable = true;
3950                         }
3951                 }
3952                 
3953                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3954                 {
3955                         if (m == null)
3956                                 return false;
3957                         
3958                         if (!(m is MethodInfo))
3959                                 return false;
3960                         
3961                         if (m.Name != "GetEnumerator")
3962                                 return false;
3963
3964                         MethodInfo mi = (MethodInfo) m;
3965                         Type [] args = TypeManager.GetArgumentTypes (mi);
3966                         if (args != null){
3967                                 if (args.Length != 0)
3968                                         return false;
3969                         }
3970                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3971                         EmitContext ec = hm.ec;
3972
3973                         // Check whether GetEnumerator is public
3974                         if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
3975                                         return false;
3976
3977                         if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
3978                                 //
3979                                 // Apply the same optimization as MS: skip the GetEnumerator
3980                                 // returning an IEnumerator, and use the one returning a 
3981                                 // CharEnumerator instead. This allows us to avoid the 
3982                                 // try-finally block and the boxing.
3983                                 //
3984                                 return false;
3985
3986                         //
3987                         // Ok, we can access it, now make sure that we can do something
3988                         // with this `GetEnumerator'
3989                         //
3990                         
3991                         Type return_type = mi.ReturnType;
3992                         if (mi.ReturnType == TypeManager.ienumerator_type ||
3993                             TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3994                             (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3995                                 
3996                                 //
3997                                 // If it is not an interface, lets try to find the methods ourselves.
3998                                 // For example, if we have:
3999                                 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4000                                 // We can avoid the iface call. This is a runtime perf boost.
4001                                 // even bigger if we have a ValueType, because we avoid the cost
4002                                 // of boxing.
4003                                 //
4004                                 // We have to make sure that both methods exist for us to take
4005                                 // this path. If one of the methods does not exist, we will just
4006                                 // use the interface. Sadly, this complex if statement is the only
4007                                 // way I could do this without a goto
4008                                 //
4009                                 
4010                                 if (return_type.IsInterface ||
4011                                     (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4012                                     (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4013                                         
4014                                         hm.move_next = TypeManager.bool_movenext_void;
4015                                         hm.get_current = TypeManager.object_getcurrent_void;
4016                                         return true;    
4017                                 }
4018
4019                         } else {
4020
4021                                 //
4022                                 // Ok, so they dont return an IEnumerable, we will have to
4023                                 // find if they support the GetEnumerator pattern.
4024                                 //
4025                                 
4026                                 hm.move_next = FetchMethodMoveNext (return_type);
4027                                 if (hm.move_next == null)
4028                                         return false;
4029                                 
4030                                 hm.get_current = FetchMethodGetCurrent (return_type);
4031                                 if (hm.get_current == null)
4032                                         return false;
4033                         }
4034                         
4035                         hm.element_type = hm.get_current.ReturnType;
4036                         hm.enumerator_type = return_type;
4037                         hm.is_disposable = !hm.enumerator_type.IsSealed ||
4038                                 TypeManager.ImplementsInterface (
4039                                         hm.enumerator_type, TypeManager.idisposable_type);
4040
4041                         return true;
4042                 }
4043                 
4044                 /// <summary>
4045                 ///   This filter is used to find the GetEnumerator method
4046                 ///   on which IEnumerator operates
4047                 /// </summary>
4048                 static MemberFilter FilterEnumerator;
4049                 
4050                 static Foreach ()
4051                 {
4052                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4053                 }
4054
4055                 void error1579 (Type t)
4056                 {
4057                         Report.Error (1579, loc,
4058                                       "foreach statement cannot operate on variables of type `" +
4059                                       t.FullName + "' because that class does not provide a " +
4060                                       " GetEnumerator method or it is inaccessible");
4061                 }
4062
4063                 static bool TryType (Type t, ForeachHelperMethods hm)
4064                 {
4065                         MemberList mi;
4066                         
4067                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4068                                                         BindingFlags.Public | BindingFlags.NonPublic |
4069                                                         BindingFlags.Instance | BindingFlags.DeclaredOnly,
4070                                                         FilterEnumerator, hm);
4071
4072                         if (mi.Count == 0)
4073                                 return false;
4074
4075                         hm.get_enumerator = (MethodInfo) mi [0];
4076                         return true;    
4077                 }
4078                 
4079                 //
4080                 // Looks for a usable GetEnumerator in the Type, and if found returns
4081                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4082                 //
4083                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4084                 {
4085                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4086
4087                         for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4088                                 if (TryType (tt, hm))
4089                                         return hm;
4090                                 tt = tt.BaseType;
4091                         }
4092
4093                         //
4094                         // Now try to find the method in the interfaces
4095                         //
4096                         while (t != null){
4097                                 Type [] ifaces = t.GetInterfaces ();
4098
4099                                 foreach (Type i in ifaces){
4100                                         if (TryType (i, hm))
4101                                                 return hm;
4102                                 }
4103                                 
4104                                 //
4105                                 // Since TypeBuilder.GetInterfaces only returns the interface
4106                                 // types for this type, we have to keep looping, but once
4107                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4108                                 // done, because it returns all the types
4109                                 //
4110                                 if ((t is TypeBuilder))
4111                                         t = t.BaseType;
4112                                 else
4113                                         break;
4114                         } 
4115
4116                         return null;
4117                 }
4118
4119                 //
4120                 // FIXME: possible optimization.
4121                 // We might be able to avoid creating `empty' if the type is the sam
4122                 //
4123                 bool EmitCollectionForeach (EmitContext ec)
4124                 {
4125                         ILGenerator ig = ec.ig;
4126
4127                         enumerator = new VariableStorage (ec, hm.enumerator_type);
4128                         enumerator.EmitThis ();
4129                         //
4130                         // Instantiate the enumerator
4131                         //
4132                         if (expr.Type.IsValueType){
4133                                 IMemoryLocation ml = expr as IMemoryLocation;
4134                                 // Load the address of the value type.
4135                                 if (ml == null) {
4136                                         // This happens if, for example, you have a property
4137                                         // returning a struct which is IEnumerable
4138                                         LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4139                                                 expr.Emit(ec);
4140                                         ig.Emit (OpCodes.Stloc, t);
4141                                         ig.Emit (OpCodes.Ldloca, t);
4142                                         ec.FreeTemporaryLocal (t, expr.Type);
4143                                         } else {
4144                                                 ml.AddressOf (ec, AddressOp.Load);
4145                                         }
4146                                 
4147                                 // Emit the call.
4148                                 if (hm.get_enumerator.DeclaringType.IsValueType) {
4149                                         // the method is declared on the value type
4150                                         ig.Emit (OpCodes.Call, hm.get_enumerator);
4151                                 } else {
4152                                         // it is an interface method, so we must box
4153                                         ig.Emit (OpCodes.Box, expr.Type);
4154                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4155                                 }
4156                         } else {
4157                                 expr.Emit (ec);
4158                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4159                         }
4160                         enumerator.EmitStore ();
4161
4162                         //
4163                         // Protect the code in a try/finalize block, so that
4164                         // if the beast implement IDisposable, we get rid of it
4165                         //
4166                         if (hm.is_disposable && emit_finally)
4167                                 ig.BeginExceptionBlock ();
4168                         
4169                         Label end_try = ig.DefineLabel ();
4170                         
4171                         ig.MarkLabel (ec.LoopBegin);
4172                         
4173                         enumerator.EmitCall (hm.move_next);
4174                         
4175                         ig.Emit (OpCodes.Brfalse, end_try);
4176                         if (ec.InIterator)
4177                                 ec.EmitThis ();
4178                         
4179                         enumerator.EmitCall (hm.get_current);
4180
4181                         if (ec.InIterator){
4182                                 conv.Emit (ec);
4183                                 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4184                         } else 
4185                                 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4186                                 
4187                         statement.Emit (ec);
4188                         ig.Emit (OpCodes.Br, ec.LoopBegin);
4189                         ig.MarkLabel (end_try);
4190                         
4191                         // The runtime provides this for us.
4192                         // ig.Emit (OpCodes.Leave, end);
4193
4194                         //
4195                         // Now the finally block
4196                         //
4197                         if (hm.is_disposable) {
4198                                 DoEmitFinally (ec);
4199                                 if (emit_finally)
4200                                         ig.EndExceptionBlock ();
4201                         }
4202
4203                         ig.MarkLabel (ec.LoopEnd);
4204                         return false;
4205                 }
4206
4207                 public override void EmitFinally (EmitContext ec)
4208                 {
4209                         ILGenerator ig = ec.ig;
4210
4211                         if (hm.enumerator_type.IsValueType) {
4212                                 enumerator.EmitThis ();
4213
4214                                 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4215                                 if (mi != null) {
4216                                         enumerator.EmitLoadAddress ();
4217                                         ig.Emit (OpCodes.Call, mi);
4218                                 } else {
4219                                         enumerator.EmitLoad ();
4220                                         ig.Emit (OpCodes.Box, hm.enumerator_type);
4221                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4222                                 }
4223                         } else {
4224                                 Label call_dispose = ig.DefineLabel ();
4225
4226                                 enumerator.EmitThis ();
4227                                 enumerator.EmitLoad ();
4228                                 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4229                                 ig.Emit (OpCodes.Dup);
4230                                 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4231                                 ig.Emit (OpCodes.Pop);
4232                                 ig.Emit (OpCodes.Endfinally);
4233
4234                                 ig.MarkLabel (call_dispose);
4235                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4236                         }
4237                 }
4238
4239                 //
4240                 // FIXME: possible optimization.
4241                 // We might be able to avoid creating `empty' if the type is the sam
4242                 //
4243                 bool EmitArrayForeach (EmitContext ec)
4244                 {
4245                         int rank = array_type.GetArrayRank ();
4246                         ILGenerator ig = ec.ig;
4247
4248                         VariableStorage copy = new VariableStorage (ec, array_type);
4249                         
4250                         //
4251                         // Make our copy of the array
4252                         //
4253                         copy.EmitThis ();
4254                         expr.Emit (ec);
4255                         copy.EmitStore ();
4256                         
4257                         if (rank == 1){
4258                                 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4259
4260                                 Label loop, test;
4261
4262                                 counter.EmitThis ();
4263                                 ig.Emit (OpCodes.Ldc_I4_0);
4264                                 counter.EmitStore ();
4265                                 test = ig.DefineLabel ();
4266                                 ig.Emit (OpCodes.Br, test);
4267
4268                                 loop = ig.DefineLabel ();
4269                                 ig.MarkLabel (loop);
4270
4271                                 if (ec.InIterator)
4272                                         ec.EmitThis ();
4273                                 
4274                                 copy.EmitThis ();
4275                                 copy.EmitLoad ();
4276                                 counter.EmitThis ();
4277                                 counter.EmitLoad ();
4278
4279                                 //
4280                                 // Load the value, we load the value using the underlying type,
4281                                 // then we use the variable.EmitAssign to load using the proper cast.
4282                                 //
4283                                 ArrayAccess.EmitLoadOpcode (ig, element_type);
4284                                 if (ec.InIterator){
4285                                         conv.Emit (ec);
4286                                         ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4287                                 } else 
4288                                         ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4289
4290                                 statement.Emit (ec);
4291
4292                                 ig.MarkLabel (ec.LoopBegin);
4293                                 counter.EmitThis ();
4294                                 counter.EmitThis ();
4295                                 counter.EmitLoad ();
4296                                 ig.Emit (OpCodes.Ldc_I4_1);
4297                                 ig.Emit (OpCodes.Add);
4298                                 counter.EmitStore ();
4299
4300                                 ig.MarkLabel (test);
4301                                 counter.EmitThis ();
4302                                 counter.EmitLoad ();
4303                                 copy.EmitThis ();
4304                                 copy.EmitLoad ();
4305                                 ig.Emit (OpCodes.Ldlen);
4306                                 ig.Emit (OpCodes.Conv_I4);
4307                                 ig.Emit (OpCodes.Blt, loop);
4308                         } else {
4309                                 VariableStorage [] dim_len   = new VariableStorage [rank];
4310                                 VariableStorage [] dim_count = new VariableStorage [rank];
4311                                 Label [] loop = new Label [rank];
4312                                 Label [] test = new Label [rank];
4313                                 int dim;
4314                                 
4315                                 for (dim = 0; dim < rank; dim++){
4316                                         dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4317                                         dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4318                                         test [dim] = ig.DefineLabel ();
4319                                         loop [dim] = ig.DefineLabel ();
4320                                 }
4321                                         
4322                                 for (dim = 0; dim < rank; dim++){
4323                                         dim_len [dim].EmitThis ();
4324                                         copy.EmitThis ();
4325                                         copy.EmitLoad ();
4326                                         IntLiteral.EmitInt (ig, dim);
4327                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4328                                         dim_len [dim].EmitStore ();
4329                                         
4330                                 }
4331
4332                                 for (dim = 0; dim < rank; dim++){
4333                                         dim_count [dim].EmitThis ();
4334                                         ig.Emit (OpCodes.Ldc_I4_0);
4335                                         dim_count [dim].EmitStore ();
4336                                         ig.Emit (OpCodes.Br, test [dim]);
4337                                         ig.MarkLabel (loop [dim]);
4338                                 }
4339
4340                                 if (ec.InIterator)
4341                                         ec.EmitThis ();
4342                                 copy.EmitThis ();
4343                                 copy.EmitLoad ();
4344                                 for (dim = 0; dim < rank; dim++){
4345                                         dim_count [dim].EmitThis ();
4346                                         dim_count [dim].EmitLoad ();
4347                                 }
4348
4349                                 //
4350                                 // FIXME: Maybe we can cache the computation of `get'?
4351                                 //
4352                                 Type [] args = new Type [rank];
4353                                 MethodInfo get;
4354
4355                                 for (int i = 0; i < rank; i++)
4356                                         args [i] = TypeManager.int32_type;
4357
4358                                 ModuleBuilder mb = CodeGen.Module.Builder;
4359                                 get = mb.GetArrayMethod (
4360                                         array_type, "Get",
4361                                         CallingConventions.HasThis| CallingConventions.Standard,
4362                                         var_type, args);
4363                                 ig.Emit (OpCodes.Call, get);
4364                                 if (ec.InIterator){
4365                                         conv.Emit (ec);
4366                                         ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4367                                 } else 
4368                                         ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4369                                 statement.Emit (ec);
4370                                 ig.MarkLabel (ec.LoopBegin);
4371                                 for (dim = rank - 1; dim >= 0; dim--){
4372                                         dim_count [dim].EmitThis ();
4373                                         dim_count [dim].EmitThis ();
4374                                         dim_count [dim].EmitLoad ();
4375                                         ig.Emit (OpCodes.Ldc_I4_1);
4376                                         ig.Emit (OpCodes.Add);
4377                                         dim_count [dim].EmitStore ();
4378
4379                                         ig.MarkLabel (test [dim]);
4380                                         dim_count [dim].EmitThis ();
4381                                         dim_count [dim].EmitLoad ();
4382                                         dim_len [dim].EmitThis ();
4383                                         dim_len [dim].EmitLoad ();
4384                                         ig.Emit (OpCodes.Blt, loop [dim]);
4385                                 }
4386                         }
4387                         ig.MarkLabel (ec.LoopEnd);
4388                         
4389                         return false;
4390                 }
4391                 
4392                 protected override void DoEmit (EmitContext ec)
4393                 {
4394                         ILGenerator ig = ec.ig;
4395                         
4396                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4397                         ec.LoopBegin = ig.DefineLabel ();
4398                         ec.LoopEnd = ig.DefineLabel ();
4399                         
4400                         if (hm != null)
4401                                 EmitCollectionForeach (ec);
4402                         else
4403                                 EmitArrayForeach (ec);
4404                         
4405                         ec.LoopBegin = old_begin;
4406                         ec.LoopEnd = old_end;
4407                 }
4408         }
4409 }