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