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