38bb630563925b89f42a72e5f6b61e3ea222b196
[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                                         if (e == null)
1830                                                 continue;
1831
1832                                         Constant ce = e as Constant;
1833                                         if (ce == null){
1834                                                 Report.Error (133, vi.Location,
1835                                                               "The expression being assigned to `" +
1836                                                               name + "' must be constant (" + e + ")");
1837                                                 continue;
1838                                         }
1839
1840                                         if (e.Type != variable_type){
1841                                                 e = Const.ChangeType (vi.Location, ce, variable_type);
1842                                                 if (e == null)
1843                                                         continue;
1844                                         }
1845
1846                                         constants.Remove (name);
1847                                         constants.Add (name, e);
1848                                 }
1849                         }
1850                         ec.ConstantCheckState = old_check_state;
1851
1852                         //
1853                         // Now, handle the children
1854                         //
1855                         if (children != null){
1856                                 foreach (Block b in children)
1857                                         b.ResolveMeta (toplevel, ec, ip);
1858                         }
1859                         ec.InUnsafe = old_unsafe;
1860                 }
1861
1862                 //
1863                 // Emits the local variable declarations for a block
1864                 //
1865                 public void EmitMeta (EmitContext ec)
1866                 {
1867                         ILGenerator ig = ec.ig;
1868                         
1869                         if (variables != null){
1870                                 bool have_captured_vars = ec.HaveCapturedVariables ();
1871                                 bool remap_locals = ec.RemapToProxy;
1872                                 
1873                                 foreach (DictionaryEntry de in variables){
1874                                         LocalInfo vi = (LocalInfo) de.Value;
1875
1876                                         if (have_captured_vars && ec.IsCaptured (vi))
1877                                                 continue;
1878
1879                                         if (remap_locals){
1880                                                 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1881                                         } else {
1882                                                 if (vi.Pinned)
1883                                                         //
1884                                                         // This is needed to compile on both .NET 1.x and .NET 2.x
1885                                                         // the later introduced `DeclareLocal (Type t, bool pinned)'
1886                                                         //
1887                                                         vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1888                                                 else if (!vi.IsThis)
1889                                                         vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1890                                         }
1891                                 }
1892                         }
1893
1894                         if (children != null){
1895                                 foreach (Block b in children)
1896                                         b.EmitMeta (ec);
1897                         }
1898                 }
1899
1900                 void UsageWarning (FlowBranching.UsageVector vector)
1901                 {
1902                         string name;
1903                         
1904                         if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1905                                 foreach (DictionaryEntry de in variables){
1906                                         LocalInfo vi = (LocalInfo) de.Value;
1907                                         
1908                                         if (vi.Used)
1909                                                 continue;
1910                                         
1911                                         name = (string) de.Key;
1912                                                 
1913                                         if (vector.IsAssigned (vi.VariableInfo)){
1914                                                 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1915                                         } else {
1916                                                 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1917                                         }
1918                                 }
1919                         }
1920                 }
1921
1922                 bool unreachable_shown;
1923
1924                 public override bool Resolve (EmitContext ec)
1925                 {
1926                         Block prev_block = ec.CurrentBlock;
1927                         bool ok = true;
1928
1929                         int errors = Report.Errors;
1930
1931                         ec.CurrentBlock = this;
1932                         ec.StartFlowBranching (this);
1933
1934                         Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1935
1936                         //
1937                         // This flag is used to notate nested statements as unreachable from the beginning of this block.
1938                         // For the purposes of this resolution, it doesn't matter that the whole block is unreachable 
1939                         // from the beginning of the function.  The outer Resolve() that detected the unreachability is
1940                         // responsible for handling the situation.
1941                         //
1942                         bool unreachable = false;
1943
1944                         int statement_count = statements.Count;
1945                         for (int ix = 0; ix < statement_count; ix++){
1946                                 Statement s = (Statement) statements [ix];
1947                                 
1948                                 if (unreachable && !(s is LabeledStatement)) {
1949                                         if (s == EmptyStatement.Value)
1950                                                 s.loc = EndLocation;
1951
1952                                         if (!s.ResolveUnreachable (ec, !unreachable_shown))
1953                                                 ok = false;
1954
1955                                         if (s != EmptyStatement.Value)
1956                                                 unreachable_shown = true;
1957                                         else
1958                                                 s.loc = Location.Null;
1959
1960                                         if (ok && !(s is Block)) {
1961                                                 statements [ix] = EmptyStatement.Value;
1962                                                 continue;
1963                                         }
1964                                 }
1965
1966                                 if (s.Resolve (ec) == false) {
1967                                         ok = false;
1968                                         statements [ix] = EmptyStatement.Value;
1969                                         continue;
1970                                 }
1971
1972                                 num_statements = ix + 1;
1973
1974                                 if (s is LabeledStatement)
1975                                         unreachable = false;
1976                                 else
1977                                         unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1978                         }
1979
1980                         Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1981                                       ec.CurrentBranching, statement_count, num_statements);
1982
1983
1984                         FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1985
1986                         ec.CurrentBlock = prev_block;
1987
1988                         // If we're a non-static `struct' constructor which doesn't have an
1989                         // initializer, then we must initialize all of the struct's fields.
1990                         if ((this_variable != null) &&
1991                             (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1992                             !this_variable.IsThisAssigned (ec, loc))
1993                                 ok = false;
1994
1995                         if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1996                                 foreach (LabeledStatement label in labels.Values)
1997                                         if (!label.HasBeenReferenced)
1998                                                 Report.Warning (164, label.Location,
1999                                                                 "This label has not been referenced");
2000                         }
2001
2002                         Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2003
2004                         if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2005                             (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2006                             (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2007                                 flags |= Flags.HasRet;
2008
2009                         if (ok && (errors == Report.Errors)) {
2010                                 if (RootContext.WarningLevel >= 3)
2011                                         UsageWarning (vector);
2012                         }
2013
2014                         return ok;
2015                 }
2016                 
2017                 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2018                 {
2019                         unreachable_shown = true;
2020
2021                         if (warn && (RootContext.WarningLevel >= 2))
2022                                 Report.Warning (162, loc, "Unreachable code detected");
2023
2024                         if (Implicit)
2025                                 return Resolve (ec);
2026
2027                         ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2028                         bool ok = Resolve (ec);
2029                         ec.KillFlowBranching ();
2030
2031                         return ok;
2032                 }
2033                 
2034                 protected override void DoEmit (EmitContext ec)
2035                 {
2036                         for (int ix = 0; ix < num_statements; ix++){
2037                                 Statement s = (Statement) statements [ix];
2038
2039                                 // Check whether we are the last statement in a
2040                                 // top-level block.
2041
2042                                 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2043                                         ec.IsLastStatement = true;
2044                                 else
2045                                         ec.IsLastStatement = false;
2046
2047                                 s.Emit (ec);
2048                         }
2049                 }
2050
2051                 public override void Emit (EmitContext ec)
2052                 {
2053                         Block prev_block = ec.CurrentBlock;
2054
2055                         ec.CurrentBlock = this;
2056
2057                         bool emit_debug_info = (CodeGen.SymbolWriter != null);
2058                         bool is_lexical_block = !Implicit && (Parent != null);
2059
2060                         if (emit_debug_info) {
2061                                 if (is_lexical_block)
2062                                         ec.BeginScope ();
2063
2064                                 if (variables != null) {
2065                                         foreach (DictionaryEntry de in variables) {
2066                                                 string name = (string) de.Key;
2067                                                 LocalInfo vi = (LocalInfo) de.Value;
2068
2069                                                 if (vi.LocalBuilder == null)
2070                                                         continue;
2071
2072                                                 ec.DefineLocalVariable (name, vi.LocalBuilder);
2073                                         }
2074                                 }
2075                         }
2076
2077                         ec.Mark (StartLocation, true);
2078                         DoEmit (ec);
2079                         ec.Mark (EndLocation, true); 
2080
2081                         if (emit_debug_info && is_lexical_block)
2082                                 ec.EndScope ();
2083
2084                         ec.CurrentBlock = prev_block;
2085                 }
2086
2087                 //
2088                 // Returns true if we ar ea child of `b'.
2089                 //
2090                 public bool IsChildOf (Block b)
2091                 {
2092                         Block current = this;
2093                         
2094                         do {
2095                                 if (current.Parent == b)
2096                                         return true;
2097                                 current = current.Parent;
2098                         } while (current != null);
2099                         return false;
2100                 }
2101
2102                 public override string ToString ()
2103                 {
2104                         return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2105                 }
2106         }
2107
2108         //
2109         // A toplevel block contains extra information, the split is done
2110         // only to separate information that would otherwise bloat the more
2111         // lightweight Block.
2112         //
2113         // In particular, this was introduced when the support for Anonymous
2114         // Methods was implemented. 
2115         // 
2116         public class ToplevelBlock : Block {
2117                 //
2118                 // Pointer to the host of this anonymous method, or null
2119                 // if we are the topmost block
2120                 //
2121                 public ToplevelBlock Container;
2122                 CaptureContext capture_context;
2123                 FlowBranching top_level_branching;
2124
2125                 Hashtable capture_contexts;
2126
2127                 //
2128                 // The parameters for the block.
2129                 //
2130                 public readonly Parameters Parameters;
2131                         
2132                 public void RegisterCaptureContext (CaptureContext cc)
2133                 {
2134                         if (capture_contexts == null)
2135                                 capture_contexts = new Hashtable ();
2136                         capture_contexts [cc] = cc;
2137                 }
2138
2139                 public void CompleteContexts ()
2140                 {
2141                         if (capture_contexts == null)
2142                                 return;
2143
2144                         foreach (CaptureContext cc in capture_contexts.Keys){
2145                                 cc.AdjustScopes ();
2146                         }
2147                 }
2148                 
2149                 public CaptureContext ToplevelBlockCaptureContext {
2150                         get {
2151                                 return capture_context;
2152                         }
2153                 }
2154                 
2155                 //
2156                 // Parent is only used by anonymous blocks to link back to their
2157                 // parents
2158                 //
2159                 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2160                         this (container, (Flags) 0, parameters, start)
2161                 {
2162                 }
2163                 
2164                 public ToplevelBlock (Parameters parameters, Location start) :
2165                         this (null, (Flags) 0, parameters, start)
2166                 {
2167                 }
2168
2169                 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2170                         this (null, flags, parameters, start)
2171                 {
2172                 }
2173
2174                 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2175                         base (null, flags | Flags.IsToplevel, start, Location.Null)
2176                 {
2177                         Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2178                         Container = container;
2179                 }
2180
2181                 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2182                 {
2183                 }
2184
2185                 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2186                 {
2187                         if (capture_context == null)
2188                                 capture_context = new CaptureContext (this, loc, host);
2189                 }
2190
2191                 public CaptureContext CaptureContext {
2192                         get {
2193                                 return capture_context;
2194                         }
2195                 }
2196
2197                 public FlowBranching TopLevelBranching {
2198                         get {
2199                                 return top_level_branching;
2200                         }
2201                 }
2202
2203                 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2204                 {
2205                         int errors = Report.Errors;
2206
2207                         if (top_level_branching != null)
2208                                 return true;
2209
2210                         ResolveMeta (this, ec, ip);
2211
2212                         top_level_branching = ec.StartFlowBranching (this);
2213
2214                         return Report.Errors == errors;
2215                 }
2216         }
2217         
2218         public class SwitchLabel {
2219                 Expression label;
2220                 object converted;
2221                 public Location loc;
2222
2223                 Label il_label;
2224                 bool  il_label_set;
2225                 Label il_label_code;
2226                 bool  il_label_code_set;
2227
2228                 //
2229                 // if expr == null, then it is the default case.
2230                 //
2231                 public SwitchLabel (Expression expr, Location l)
2232                 {
2233                         label = expr;
2234                         loc = l;
2235                 }
2236
2237                 public Expression Label {
2238                         get {
2239                                 return label;
2240                         }
2241                 }
2242
2243                 public object Converted {
2244                         get {
2245                                 return converted;
2246                         }
2247                 }
2248
2249                 public Label GetILLabel (EmitContext ec)
2250                 {
2251                         if (!il_label_set){
2252                                 il_label = ec.ig.DefineLabel ();
2253                                 il_label_set = true;
2254                         }
2255                         return il_label;
2256                 }
2257
2258                 public Label GetILLabelCode (EmitContext ec)
2259                 {
2260                         if (!il_label_code_set){
2261                                 il_label_code = ec.ig.DefineLabel ();
2262                                 il_label_code_set = true;
2263                         }
2264                         return il_label_code;
2265                 }                               
2266                 
2267                 //
2268                 // Resolves the expression, reduces it to a literal if possible
2269                 // and then converts it to the requested type.
2270                 //
2271                 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2272                 {
2273                         if (label == null)
2274                                 return true;
2275                         
2276                         Expression e = label.Resolve (ec);
2277
2278                         if (e == null)
2279                                 return false;
2280
2281                         if (!(e is Constant)){
2282                                 Report.Error (150, loc, "A constant value is expected, got: " + e);
2283                                 return false;
2284                         }
2285
2286                         if (e is StringConstant || e is NullLiteral){
2287                                 if (required_type == TypeManager.string_type){
2288                                         converted = e;
2289                                         return true;
2290                                 }
2291                         }
2292
2293                         converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2294                         if (converted == null)
2295                                 return false;
2296
2297                         return true;
2298                 }
2299         }
2300
2301         public class SwitchSection {
2302                 // An array of SwitchLabels.
2303                 public readonly ArrayList Labels;
2304                 public readonly Block Block;
2305                 
2306                 public SwitchSection (ArrayList labels, Block block)
2307                 {
2308                         Labels = labels;
2309                         Block = block;
2310                 }
2311         }
2312         
2313         public class Switch : Statement {
2314                 public readonly ArrayList Sections;
2315                 public Expression Expr;
2316
2317                 /// <summary>
2318                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
2319                 /// </summary>
2320                 public Hashtable Elements;
2321
2322                 /// <summary>
2323                 ///   The governing switch type
2324                 /// </summary>
2325                 public Type SwitchType;
2326
2327                 //
2328                 // Computed
2329                 //
2330                 Label default_target;
2331                 Expression new_expr;
2332                 bool is_constant;
2333                 SwitchSection constant_section;
2334                 SwitchSection default_section;
2335
2336                 //
2337                 // The types allowed to be implicitly cast from
2338                 // on the governing type
2339                 //
2340                 static Type [] allowed_types;
2341                 
2342                 public Switch (Expression e, ArrayList sects, Location l)
2343                 {
2344                         Expr = e;
2345                         Sections = sects;
2346                         loc = l;
2347                 }
2348
2349                 public bool GotDefault {
2350                         get {
2351                                 return default_section != null;
2352                         }
2353                 }
2354
2355                 public Label DefaultTarget {
2356                         get {
2357                                 return default_target;
2358                         }
2359                 }
2360
2361                 //
2362                 // Determines the governing type for a switch.  The returned
2363                 // expression might be the expression from the switch, or an
2364                 // expression that includes any potential conversions to the
2365                 // integral types or to string.
2366                 //
2367                 Expression SwitchGoverningType (EmitContext ec, Type t)
2368                 {
2369                         if (t == TypeManager.int32_type ||
2370                             t == TypeManager.uint32_type ||
2371                             t == TypeManager.char_type ||
2372                             t == TypeManager.byte_type ||
2373                             t == TypeManager.sbyte_type ||
2374                             t == TypeManager.ushort_type ||
2375                             t == TypeManager.short_type ||
2376                             t == TypeManager.uint64_type ||
2377                             t == TypeManager.int64_type ||
2378                             t == TypeManager.string_type ||
2379                                 t == TypeManager.bool_type ||
2380                                 t.IsSubclassOf (TypeManager.enum_type))
2381                                 return Expr;
2382
2383                         if (allowed_types == null){
2384                                 allowed_types = new Type [] {
2385                                         TypeManager.int32_type,
2386                                         TypeManager.uint32_type,
2387                                         TypeManager.sbyte_type,
2388                                         TypeManager.byte_type,
2389                                         TypeManager.short_type,
2390                                         TypeManager.ushort_type,
2391                                         TypeManager.int64_type,
2392                                         TypeManager.uint64_type,
2393                                         TypeManager.char_type,
2394                                         TypeManager.bool_type,
2395                                         TypeManager.string_type
2396                                 };
2397                         }
2398
2399                         //
2400                         // Try to find a *user* defined implicit conversion.
2401                         //
2402                         // If there is no implicit conversion, or if there are multiple
2403                         // conversions, we have to report an error
2404                         //
2405                         Expression converted = null;
2406                         foreach (Type tt in allowed_types){
2407                                 Expression e;
2408                                 
2409                                 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2410                                 if (e == null)
2411                                         continue;
2412
2413                                 //
2414                                 // Ignore over-worked ImplicitUserConversions that do
2415                                 // an implicit conversion in addition to the user conversion.
2416                                 // 
2417                                 if (e is UserCast){
2418                                         UserCast ue = e as UserCast;
2419
2420                                         if (ue.Source != Expr)
2421                                                 e = null;
2422                                 }
2423                                 
2424                                 if (converted != null){
2425                                         Report.ExtraInformation (
2426                                                 loc,
2427                                                 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2428                                                                TypeManager.CSharpName (Expr.Type)));
2429                                         return null;
2430                                 } else {
2431                                         converted = e;
2432                                 }
2433                         }
2434                         return converted;
2435                 }
2436
2437                 static string Error152 {
2438                         get {
2439                                 return "The label '{0}:' already occurs in this switch statement";
2440                         }
2441                 }
2442                 
2443                 //
2444                 // Performs the basic sanity checks on the switch statement
2445                 // (looks for duplicate keys and non-constant expressions).
2446                 //
2447                 // It also returns a hashtable with the keys that we will later
2448                 // use to compute the switch tables
2449                 //
2450                 bool CheckSwitch (EmitContext ec)
2451                 {
2452                         Type compare_type;
2453                         bool error = false;
2454                         Elements = new Hashtable ();
2455                                 
2456                         if (TypeManager.IsEnumType (SwitchType)){
2457                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2458                         } else
2459                                 compare_type = SwitchType;
2460                         
2461                         foreach (SwitchSection ss in Sections){
2462                                 foreach (SwitchLabel sl in ss.Labels){
2463                                         if (!sl.ResolveAndReduce (ec, SwitchType)){
2464                                                 error = true;
2465                                                 continue;
2466                                         }
2467
2468                                         if (sl.Label == null){
2469                                                 if (default_section != null){
2470                                                         Report.Error (152, sl.loc, Error152, "default");
2471                                                         error = true;
2472                                                 }
2473                                                 default_section = ss;
2474                                                 continue;
2475                                         }
2476                                         
2477                                         object key = sl.Converted;
2478
2479                                         if (key is Constant)
2480                                                 key = ((Constant) key).GetValue ();
2481
2482                                         if (key == null)
2483                                                 key = NullLiteral.Null;
2484                                         
2485                                         string lname = null;
2486                                         if (compare_type == TypeManager.uint64_type){
2487                                                 ulong v = (ulong) key;
2488
2489                                                 if (Elements.Contains (v))
2490                                                         lname = v.ToString ();
2491                                                 else
2492                                                         Elements.Add (v, sl);
2493                                         } else if (compare_type == TypeManager.int64_type){
2494                                                 long v = (long) key;
2495
2496                                                 if (Elements.Contains (v))
2497                                                         lname = v.ToString ();
2498                                                 else
2499                                                         Elements.Add (v, sl);
2500                                         } else if (compare_type == TypeManager.uint32_type){
2501                                                 uint v = (uint) key;
2502
2503                                                 if (Elements.Contains (v))
2504                                                         lname = v.ToString ();
2505                                                 else
2506                                                         Elements.Add (v, sl);
2507                                         } else if (compare_type == TypeManager.char_type){
2508                                                 char v = (char) key;
2509                                                 
2510                                                 if (Elements.Contains (v))
2511                                                         lname = v.ToString ();
2512                                                 else
2513                                                         Elements.Add (v, sl);
2514                                         } else if (compare_type == TypeManager.byte_type){
2515                                                 byte v = (byte) key;
2516                                                 
2517                                                 if (Elements.Contains (v))
2518                                                         lname = v.ToString ();
2519                                                 else
2520                                                         Elements.Add (v, sl);
2521                                         } else if (compare_type == TypeManager.sbyte_type){
2522                                                 sbyte v = (sbyte) key;
2523                                                 
2524                                                 if (Elements.Contains (v))
2525                                                         lname = v.ToString ();
2526                                                 else
2527                                                         Elements.Add (v, sl);
2528                                         } else if (compare_type == TypeManager.short_type){
2529                                                 short v = (short) key;
2530                                                 
2531                                                 if (Elements.Contains (v))
2532                                                         lname = v.ToString ();
2533                                                 else
2534                                                         Elements.Add (v, sl);
2535                                         } else if (compare_type == TypeManager.ushort_type){
2536                                                 ushort v = (ushort) key;
2537                                                 
2538                                                 if (Elements.Contains (v))
2539                                                         lname = v.ToString ();
2540                                                 else
2541                                                         Elements.Add (v, sl);
2542                                         } else if (compare_type == TypeManager.string_type){
2543                                                 if (key is NullLiteral){
2544                                                         if (Elements.Contains (NullLiteral.Null))
2545                                                                 lname = "null";
2546                                                         else
2547                                                                 Elements.Add (NullLiteral.Null, null);
2548                                                 } else {
2549                                                         string s = (string) key;
2550
2551                                                         if (Elements.Contains (s))
2552                                                                 lname = s;
2553                                                         else
2554                                                                 Elements.Add (s, sl);
2555                                                 }
2556                                         } else if (compare_type == TypeManager.int32_type) {
2557                                                 int v = (int) key;
2558
2559                                                 if (Elements.Contains (v))
2560                                                         lname = v.ToString ();
2561                                                 else
2562                                                         Elements.Add (v, sl);
2563                                         } else if (compare_type == TypeManager.bool_type) {
2564                                                 bool v = (bool) key;
2565
2566                                                 if (Elements.Contains (v))
2567                                                         lname = v.ToString ();
2568                                                 else
2569                                                         Elements.Add (v, sl);
2570                                         }
2571                                         else
2572                                         {
2573                                                 throw new Exception ("Unknown switch type!" +
2574                                                                      SwitchType + " " + compare_type);
2575                                         }
2576
2577                                         if (lname != null){
2578                                                 Report.Error (152, sl.loc, Error152, "case " + lname);
2579                                                 error = true;
2580                                         }
2581                                 }
2582                         }
2583                         if (error)
2584                                 return false;
2585                         
2586                         return true;
2587                 }
2588
2589                 void EmitObjectInteger (ILGenerator ig, object k)
2590                 {
2591                         if (k is int)
2592                                 IntConstant.EmitInt (ig, (int) k);
2593                         else if (k is Constant) {
2594                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2595                         } 
2596                         else if (k is uint)
2597                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2598                         else if (k is long)
2599                         {
2600                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2601                                 {
2602                                         IntConstant.EmitInt (ig, (int) (long) k);
2603                                         ig.Emit (OpCodes.Conv_I8);
2604                                 }
2605                                 else
2606                                         LongConstant.EmitLong (ig, (long) k);
2607                         }
2608                         else if (k is ulong)
2609                         {
2610                                 if ((ulong) k < (1L<<32))
2611                                 {
2612                                         IntConstant.EmitInt (ig, (int) (long) k);
2613                                         ig.Emit (OpCodes.Conv_U8);
2614                                 }
2615                                 else
2616                                 {
2617                                         LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2618                                 }
2619                         }
2620                         else if (k is char)
2621                                 IntConstant.EmitInt (ig, (int) ((char) k));
2622                         else if (k is sbyte)
2623                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2624                         else if (k is byte)
2625                                 IntConstant.EmitInt (ig, (int) ((byte) k));
2626                         else if (k is short)
2627                                 IntConstant.EmitInt (ig, (int) ((short) k));
2628                         else if (k is ushort)
2629                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
2630                         else if (k is bool)
2631                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2632                         else
2633                                 throw new Exception ("Unhandled case");
2634                 }
2635                 
2636                 // structure used to hold blocks of keys while calculating table switch
2637                 class KeyBlock : IComparable
2638                 {
2639                         public KeyBlock (long _nFirst)
2640                         {
2641                                 nFirst = nLast = _nFirst;
2642                         }
2643                         public long nFirst;
2644                         public long nLast;
2645                         public ArrayList rgKeys = null;
2646                         // how many items are in the bucket
2647                         public int Size = 1;
2648                         public int Length
2649                         {
2650                                 get { return (int) (nLast - nFirst + 1); }
2651                         }
2652                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2653                         {
2654                                 return kbLast.nLast - kbFirst.nFirst + 1;
2655                         }
2656                         public int CompareTo (object obj)
2657                         {
2658                                 KeyBlock kb = (KeyBlock) obj;
2659                                 int nLength = Length;
2660                                 int nLengthOther = kb.Length;
2661                                 if (nLengthOther == nLength)
2662                                         return (int) (kb.nFirst - nFirst);
2663                                 return nLength - nLengthOther;
2664                         }
2665                 }
2666
2667                 /// <summary>
2668                 /// This method emits code for a lookup-based switch statement (non-string)
2669                 /// Basically it groups the cases into blocks that are at least half full,
2670                 /// and then spits out individual lookup opcodes for each block.
2671                 /// It emits the longest blocks first, and short blocks are just
2672                 /// handled with direct compares.
2673                 /// </summary>
2674                 /// <param name="ec"></param>
2675                 /// <param name="val"></param>
2676                 /// <returns></returns>
2677                 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2678                 {
2679                         int cElements = Elements.Count;
2680                         object [] rgKeys = new object [cElements];
2681                         Elements.Keys.CopyTo (rgKeys, 0);
2682                         Array.Sort (rgKeys);
2683
2684                         // initialize the block list with one element per key
2685                         ArrayList rgKeyBlocks = new ArrayList ();
2686                         foreach (object key in rgKeys)
2687                                 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2688
2689                         KeyBlock kbCurr;
2690                         // iteratively merge the blocks while they are at least half full
2691                         // there's probably a really cool way to do this with a tree...
2692                         while (rgKeyBlocks.Count > 1)
2693                         {
2694                                 ArrayList rgKeyBlocksNew = new ArrayList ();
2695                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2696                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2697                                 {
2698                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2699                                         if ((kbCurr.Size + kb.Size) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
2700                                         {
2701                                                 // merge blocks
2702                                                 kbCurr.nLast = kb.nLast;
2703                                                 kbCurr.Size += kb.Size;
2704                                         }
2705                                         else
2706                                         {
2707                                                 // start a new block
2708                                                 rgKeyBlocksNew.Add (kbCurr);
2709                                                 kbCurr = kb;
2710                                         }
2711                                 }
2712                                 rgKeyBlocksNew.Add (kbCurr);
2713                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2714                                         break;
2715                                 rgKeyBlocks = rgKeyBlocksNew;
2716                         }
2717
2718                         // initialize the key lists
2719                         foreach (KeyBlock kb in rgKeyBlocks)
2720                                 kb.rgKeys = new ArrayList ();
2721
2722                         // fill the key lists
2723                         int iBlockCurr = 0;
2724                         if (rgKeyBlocks.Count > 0) {
2725                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2726                                 foreach (object key in rgKeys)
2727                                 {
2728                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2729                                                 System.Convert.ToInt64 (key) > kbCurr.nLast;
2730                                         if (fNextBlock)
2731                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2732                                         kbCurr.rgKeys.Add (key);
2733                                 }
2734                         }
2735
2736                         // sort the blocks so we can tackle the largest ones first
2737                         rgKeyBlocks.Sort ();
2738
2739                         // okay now we can start...
2740                         ILGenerator ig = ec.ig;
2741                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
2742                         Label lblDefault = ig.DefineLabel ();
2743
2744                         Type typeKeys = null;
2745                         if (rgKeys.Length > 0)
2746                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
2747
2748                         Type compare_type;
2749                         
2750                         if (TypeManager.IsEnumType (SwitchType))
2751                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2752                         else
2753                                 compare_type = SwitchType;
2754                         
2755                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2756                         {
2757                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2758                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2759                                 if (kb.Length <= 2)
2760                                 {
2761                                         foreach (object key in kb.rgKeys)
2762                                         {
2763                                                 ig.Emit (OpCodes.Ldloc, val);
2764                                                 EmitObjectInteger (ig, key);
2765                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
2766                                                 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2767                                         }
2768                                 }
2769                                 else
2770                                 {
2771                                         // TODO: if all the keys in the block are the same and there are
2772                                         //       no gaps/defaults then just use a range-check.
2773                                         if (compare_type == TypeManager.int64_type ||
2774                                                 compare_type == TypeManager.uint64_type)
2775                                         {
2776                                                 // TODO: optimize constant/I4 cases
2777
2778                                                 // check block range (could be > 2^31)
2779                                                 ig.Emit (OpCodes.Ldloc, val);
2780                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2781                                                 ig.Emit (OpCodes.Blt, lblDefault);
2782                                                 ig.Emit (OpCodes.Ldloc, val);
2783                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2784                                                 ig.Emit (OpCodes.Bgt, lblDefault);
2785
2786                                                 // normalize range
2787                                                 ig.Emit (OpCodes.Ldloc, val);
2788                                                 if (kb.nFirst != 0)
2789                                                 {
2790                                                         EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2791                                                         ig.Emit (OpCodes.Sub);
2792                                                 }
2793                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
2794                                         }
2795                                         else
2796                                         {
2797                                                 // normalize range
2798                                                 ig.Emit (OpCodes.Ldloc, val);
2799                                                 int nFirst = (int) kb.nFirst;
2800                                                 if (nFirst > 0)
2801                                                 {
2802                                                         IntConstant.EmitInt (ig, nFirst);
2803                                                         ig.Emit (OpCodes.Sub);
2804                                                 }
2805                                                 else if (nFirst < 0)
2806                                                 {
2807                                                         IntConstant.EmitInt (ig, -nFirst);
2808                                                         ig.Emit (OpCodes.Add);
2809                                                 }
2810                                         }
2811
2812                                         // first, build the list of labels for the switch
2813                                         int iKey = 0;
2814                                         int cJumps = kb.Length;
2815                                         Label [] rgLabels = new Label [cJumps];
2816                                         for (int iJump = 0; iJump < cJumps; iJump++)
2817                                         {
2818                                                 object key = kb.rgKeys [iKey];
2819                                                 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2820                                                 {
2821                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
2822                                                         rgLabels [iJump] = sl.GetILLabel (ec);
2823                                                         iKey++;
2824                                                 }
2825                                                 else
2826                                                         rgLabels [iJump] = lblDefault;
2827                                         }
2828                                         // emit the switch opcode
2829                                         ig.Emit (OpCodes.Switch, rgLabels);
2830                                 }
2831
2832                                 // mark the default for this block
2833                                 if (iBlock != 0)
2834                                         ig.MarkLabel (lblDefault);
2835                         }
2836
2837                         // TODO: find the default case and emit it here,
2838                         //       to prevent having to do the following jump.
2839                         //       make sure to mark other labels in the default section
2840
2841                         // the last default just goes to the end
2842                         ig.Emit (OpCodes.Br, lblDefault);
2843
2844                         // now emit the code for the sections
2845                         bool fFoundDefault = false;
2846                         foreach (SwitchSection ss in Sections)
2847                         {
2848                                 foreach (SwitchLabel sl in ss.Labels)
2849                                 {
2850                                         ig.MarkLabel (sl.GetILLabel (ec));
2851                                         ig.MarkLabel (sl.GetILLabelCode (ec));
2852                                         if (sl.Label == null)
2853                                         {
2854                                                 ig.MarkLabel (lblDefault);
2855                                                 fFoundDefault = true;
2856                                         }
2857                                 }
2858                                 ss.Block.Emit (ec);
2859                                 //ig.Emit (OpCodes.Br, lblEnd);
2860                         }
2861                         
2862                         if (!fFoundDefault) {
2863                                 ig.MarkLabel (lblDefault);
2864                         }
2865                         ig.MarkLabel (lblEnd);
2866                 }
2867                 //
2868                 // This simple emit switch works, but does not take advantage of the
2869                 // `switch' opcode. 
2870                 // TODO: remove non-string logic from here
2871                 // TODO: binary search strings?
2872                 //
2873                 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2874                 {
2875                         ILGenerator ig = ec.ig;
2876                         Label end_of_switch = ig.DefineLabel ();
2877                         Label next_test = ig.DefineLabel ();
2878                         Label null_target = ig.DefineLabel ();
2879                         bool default_found = false;
2880                         bool first_test = true;
2881                         bool pending_goto_end = false;
2882                         bool null_found;
2883                         bool default_at_end = false;
2884                         
2885                         ig.Emit (OpCodes.Ldloc, val);
2886                         
2887                         if (Elements.Contains (NullLiteral.Null)){
2888                                 ig.Emit (OpCodes.Brfalse, null_target);
2889                         } else
2890                                 ig.Emit (OpCodes.Brfalse, default_target);
2891                         
2892                         ig.Emit (OpCodes.Ldloc, val);
2893                         ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2894                         ig.Emit (OpCodes.Stloc, val);
2895
2896                         int section_count = Sections.Count;
2897                         for (int section = 0; section < section_count; section++){
2898                                 SwitchSection ss = (SwitchSection) Sections [section];
2899                                 Label sec_begin = ig.DefineLabel ();
2900
2901                                 default_at_end = false;
2902
2903                                 if (pending_goto_end)
2904                                         ig.Emit (OpCodes.Br, end_of_switch);
2905
2906                                 int label_count = ss.Labels.Count;
2907                                 bool mark_default = false;
2908                                 null_found = false;
2909                                 for (int label = 0; label < label_count; label++){
2910                                         SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2911                                         ig.MarkLabel (sl.GetILLabel (ec));
2912                                         
2913                                         if (!first_test){
2914                                                 ig.MarkLabel (next_test);
2915                                                 next_test = ig.DefineLabel ();
2916                                         }
2917                                         //
2918                                         // If we are the default target
2919                                         //
2920                                         if (sl.Label == null){
2921                                                 if (label+1 == label_count)
2922                                                         default_at_end = true;
2923                                                 mark_default = true;
2924                                                 default_found = true;
2925                                         } else {
2926                                                 object lit = sl.Converted;
2927
2928                                                 if (lit is NullLiteral){
2929                                                         null_found = true;
2930                                                         if (label_count == 1)
2931                                                                 ig.Emit (OpCodes.Br, next_test);
2932                                                         continue;
2933                                                                               
2934                                                 }
2935                                                 StringConstant str = (StringConstant) lit;
2936                                                 
2937                                                 ig.Emit (OpCodes.Ldloc, val);
2938                                                 ig.Emit (OpCodes.Ldstr, str.Value);
2939                                                 if (label_count == 1)
2940                                                         ig.Emit (OpCodes.Bne_Un, next_test);
2941                                                 else {
2942                                                         if (label+1 == label_count)
2943                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
2944                                                         else
2945                                                                 ig.Emit (OpCodes.Beq, sec_begin);
2946                                                 }
2947                                         }
2948                                 }
2949                                 if (null_found)
2950                                         ig.MarkLabel (null_target);
2951                                 ig.MarkLabel (sec_begin);
2952                                 foreach (SwitchLabel sl in ss.Labels)
2953                                         ig.MarkLabel (sl.GetILLabelCode (ec));
2954
2955                                 if (mark_default)
2956                                         ig.MarkLabel (default_target);
2957                                 ss.Block.Emit (ec);
2958                                 pending_goto_end = !ss.Block.HasRet;
2959                                 first_test = false;
2960                         }
2961                         ig.MarkLabel (next_test);
2962                         if (default_found){
2963                                 if (!default_at_end)
2964                                         ig.Emit (OpCodes.Br, default_target);
2965                         } else 
2966                                 ig.MarkLabel (default_target);
2967                         ig.MarkLabel (end_of_switch);
2968                 }
2969
2970                 SwitchSection FindSection (SwitchLabel label)
2971                 {
2972                         foreach (SwitchSection ss in Sections){
2973                                 foreach (SwitchLabel sl in ss.Labels){
2974                                         if (label == sl)
2975                                                 return ss;
2976                                 }
2977                         }
2978
2979                         return null;
2980                 }
2981
2982                 public override bool Resolve (EmitContext ec)
2983                 {
2984                         Expr = Expr.Resolve (ec);
2985                         if (Expr == null)
2986                                 return false;
2987
2988                         new_expr = SwitchGoverningType (ec, Expr.Type);
2989                         if (new_expr == null){
2990                                 Report.Error (151, loc, "An integer type or string was expected for switch");
2991                                 return false;
2992                         }
2993
2994                         // Validate switch.
2995                         SwitchType = new_expr.Type;
2996
2997                         if (!CheckSwitch (ec))
2998                                 return false;
2999
3000                         Switch old_switch = ec.Switch;
3001                         ec.Switch = this;
3002                         ec.Switch.SwitchType = SwitchType;
3003
3004                         Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3005                         ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3006
3007                         is_constant = new_expr is Constant;
3008                         if (is_constant) {
3009                                 object key = ((Constant) new_expr).GetValue ();
3010                                 SwitchLabel label = (SwitchLabel) Elements [key];
3011
3012                                 constant_section = FindSection (label);
3013                                 if (constant_section == null)
3014                                         constant_section = default_section;
3015                         }
3016
3017                         bool first = true;
3018                         foreach (SwitchSection ss in Sections){
3019                                 if (!first)
3020                                         ec.CurrentBranching.CreateSibling (
3021                                                 null, FlowBranching.SiblingType.SwitchSection);
3022                                 else
3023                                         first = false;
3024
3025                                 if (is_constant && (ss != constant_section)) {
3026                                         // If we're a constant switch, we're only emitting
3027                                         // one single section - mark all the others as
3028                                         // unreachable.
3029                                         ec.CurrentBranching.CurrentUsageVector.Goto ();
3030                                         if (!ss.Block.ResolveUnreachable (ec, true))
3031                                                 return false;
3032                                 } else {
3033                                         if (!ss.Block.Resolve (ec))
3034                                                 return false;
3035                         }
3036                         }
3037
3038                         if (default_section == null)
3039                                 ec.CurrentBranching.CreateSibling (
3040                                         null, FlowBranching.SiblingType.SwitchSection);
3041
3042                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3043                         ec.Switch = old_switch;
3044
3045                         Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3046                                       reachability);
3047
3048                         return true;
3049                 }
3050                 
3051                 protected override void DoEmit (EmitContext ec)
3052                 {
3053                         ILGenerator ig = ec.ig;
3054
3055                         // Store variable for comparission purposes
3056                         LocalBuilder value;
3057                         if (!is_constant) {
3058                                 value = ig.DeclareLocal (SwitchType);
3059                         new_expr.Emit (ec);
3060                                 ig.Emit (OpCodes.Stloc, value);
3061                         } else
3062                                 value = null;
3063
3064                         default_target = ig.DefineLabel ();
3065
3066                         //
3067                         // Setup the codegen context
3068                         //
3069                         Label old_end = ec.LoopEnd;
3070                         Switch old_switch = ec.Switch;
3071                         
3072                         ec.LoopEnd = ig.DefineLabel ();
3073                         ec.Switch = this;
3074
3075                         // Emit Code.
3076                         if (is_constant) {
3077                                 if (constant_section != null)
3078                                         constant_section.Block.Emit (ec);
3079                         } else if (SwitchType == TypeManager.string_type)
3080                                 SimpleSwitchEmit (ec, value);
3081                         else
3082                                 TableSwitchEmit (ec, value);
3083
3084                         // Restore context state. 
3085                         ig.MarkLabel (ec.LoopEnd);
3086
3087                         //
3088                         // Restore the previous context
3089                         //
3090                         ec.LoopEnd = old_end;
3091                         ec.Switch = old_switch;
3092                 }
3093         }
3094
3095         public abstract class ExceptionStatement : Statement
3096         {
3097                 public abstract void EmitFinally (EmitContext ec);
3098
3099                 protected bool emit_finally = true;
3100                 ArrayList parent_vectors;
3101
3102                 protected void DoEmitFinally (EmitContext ec)
3103                 {
3104                         if (emit_finally)
3105                                 ec.ig.BeginFinallyBlock ();
3106                         else
3107                                 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3108                         EmitFinally (ec);
3109                 }
3110
3111                 protected void ResolveFinally (FlowBranchingException branching)
3112                 {
3113                         emit_finally = branching.EmitFinally;
3114                         if (!emit_finally)
3115                                 branching.Parent.StealFinallyClauses (ref parent_vectors);
3116                 }
3117         }
3118
3119         public class Lock : ExceptionStatement {
3120                 Expression expr;
3121                 Statement Statement;
3122                 LocalBuilder temp;
3123                         
3124                 public Lock (Expression expr, Statement stmt, Location l)
3125                 {
3126                         this.expr = expr;
3127                         Statement = stmt;
3128                         loc = l;
3129                 }
3130
3131                 public override bool Resolve (EmitContext ec)
3132                 {
3133                         expr = expr.Resolve (ec);
3134                         if (expr == null)
3135                                 return false;
3136
3137                         if (expr.Type.IsValueType){
3138                                 Error (185, "lock statement requires the expression to be " +
3139                                        " a reference type (type is: `{0}'",
3140                                        TypeManager.CSharpName (expr.Type));
3141                                 return false;
3142                         }
3143
3144                         FlowBranchingException branching = ec.StartFlowBranching (this);
3145                         bool ok = Statement.Resolve (ec);
3146                         if (!ok) {
3147                                 ec.KillFlowBranching ();
3148                                 return false;
3149                         }
3150
3151                         ResolveFinally (branching);
3152
3153                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3154                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3155                                 // Unfortunately, System.Reflection.Emit automatically emits
3156                                 // a leave to the end of the finally block.
3157                                 // This is a problem if `returns' is true since we may jump
3158                                 // to a point after the end of the method.
3159                                 // As a workaround, emit an explicit ret here.
3160                                 ec.NeedReturnLabel ();
3161                         }
3162
3163                         return true;
3164                 }
3165                 
3166                 protected override void DoEmit (EmitContext ec)
3167                 {
3168                         Type type = expr.Type;
3169                         
3170                         ILGenerator ig = ec.ig;
3171                         temp = ig.DeclareLocal (type);
3172                                 
3173                         expr.Emit (ec);
3174                         ig.Emit (OpCodes.Dup);
3175                         ig.Emit (OpCodes.Stloc, temp);
3176                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3177
3178                         // try
3179                         if (emit_finally)
3180                                 ig.BeginExceptionBlock ();
3181                         Statement.Emit (ec);
3182                         
3183                         // finally
3184                         DoEmitFinally (ec);
3185                         if (emit_finally)
3186                                 ig.EndExceptionBlock ();
3187                 }
3188
3189                 public override void EmitFinally (EmitContext ec)
3190                 {
3191                         ILGenerator ig = ec.ig;
3192                         ig.Emit (OpCodes.Ldloc, temp);
3193                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3194                 }
3195         }
3196
3197         public class Unchecked : Statement {
3198                 public readonly Block Block;
3199                 
3200                 public Unchecked (Block b)
3201                 {
3202                         Block = b;
3203                         b.Unchecked = true;
3204                 }
3205
3206                 public override bool Resolve (EmitContext ec)
3207                 {
3208                         bool previous_state = ec.CheckState;
3209                         bool previous_state_const = ec.ConstantCheckState;
3210
3211                         ec.CheckState = false;
3212                         ec.ConstantCheckState = false;
3213                         bool ret = Block.Resolve (ec);
3214                         ec.CheckState = previous_state;
3215                         ec.ConstantCheckState = previous_state_const;
3216
3217                         return ret;
3218                 }
3219                 
3220                 protected override void DoEmit (EmitContext ec)
3221                 {
3222                         bool previous_state = ec.CheckState;
3223                         bool previous_state_const = ec.ConstantCheckState;
3224                         
3225                         ec.CheckState = false;
3226                         ec.ConstantCheckState = false;
3227                         Block.Emit (ec);
3228                         ec.CheckState = previous_state;
3229                         ec.ConstantCheckState = previous_state_const;
3230                 }
3231         }
3232
3233         public class Checked : Statement {
3234                 public readonly Block Block;
3235                 
3236                 public Checked (Block b)
3237                 {
3238                         Block = b;
3239                         b.Unchecked = false;
3240                 }
3241
3242                 public override bool Resolve (EmitContext ec)
3243                 {
3244                         bool previous_state = ec.CheckState;
3245                         bool previous_state_const = ec.ConstantCheckState;
3246                         
3247                         ec.CheckState = true;
3248                         ec.ConstantCheckState = true;
3249                         bool ret = Block.Resolve (ec);
3250                         ec.CheckState = previous_state;
3251                         ec.ConstantCheckState = previous_state_const;
3252
3253                         return ret;
3254                 }
3255
3256                 protected override void DoEmit (EmitContext ec)
3257                 {
3258                         bool previous_state = ec.CheckState;
3259                         bool previous_state_const = ec.ConstantCheckState;
3260                         
3261                         ec.CheckState = true;
3262                         ec.ConstantCheckState = true;
3263                         Block.Emit (ec);
3264                         ec.CheckState = previous_state;
3265                         ec.ConstantCheckState = previous_state_const;
3266                 }
3267         }
3268
3269         public class Unsafe : Statement {
3270                 public readonly Block Block;
3271
3272                 public Unsafe (Block b)
3273                 {
3274                         Block = b;
3275                         Block.Unsafe = true;
3276                 }
3277
3278                 public override bool Resolve (EmitContext ec)
3279                 {
3280                         bool previous_state = ec.InUnsafe;
3281                         bool val;
3282                         
3283                         ec.InUnsafe = true;
3284                         val = Block.Resolve (ec);
3285                         ec.InUnsafe = previous_state;
3286
3287                         return val;
3288                 }
3289                 
3290                 protected override void DoEmit (EmitContext ec)
3291                 {
3292                         bool previous_state = ec.InUnsafe;
3293                         
3294                         ec.InUnsafe = true;
3295                         Block.Emit (ec);
3296                         ec.InUnsafe = previous_state;
3297                 }
3298         }
3299
3300         // 
3301         // Fixed statement
3302         //
3303         public class Fixed : Statement {
3304                 Expression type;
3305                 ArrayList declarators;
3306                 Statement statement;
3307                 Type expr_type;
3308                 Emitter[] data;
3309                 bool has_ret;
3310
3311                 abstract class Emitter
3312                 {
3313                         protected LocalInfo vi;
3314                         protected Expression converted;
3315
3316                         protected Emitter (Expression expr, LocalInfo li)
3317                         {
3318                                 converted = expr;
3319                                 vi = li;
3320                         }
3321
3322                         public abstract void Emit (EmitContext ec);
3323                         public abstract void EmitExit (ILGenerator ig);
3324                 }
3325
3326                 class ExpressionEmitter: Emitter {
3327                         public ExpressionEmitter (Expression converted, LocalInfo li) :
3328                                 base (converted, li)
3329                         {
3330                         }
3331
3332                         public override void Emit (EmitContext ec) {
3333                                 //
3334                                 // Store pointer in pinned location
3335                                 //
3336                                 converted.Emit (ec);
3337                                 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3338                         }
3339
3340                         public override void EmitExit (ILGenerator ig)
3341                         {
3342                                 ig.Emit (OpCodes.Ldc_I4_0);
3343                                 ig.Emit (OpCodes.Conv_U);
3344                                 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3345                         }
3346                 }
3347
3348                 class StringEmitter: Emitter {
3349                         LocalBuilder pinned_string;
3350                         Location loc;
3351
3352                         public StringEmitter (Expression expr, LocalInfo li, Location loc):
3353                                 base (expr, li)
3354                         {
3355                                 this.loc = loc;
3356                         }
3357
3358                         public override void Emit (EmitContext ec)
3359                         {
3360                                 ILGenerator ig = ec.ig;
3361                                 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3362                                         
3363                                 converted.Emit (ec);
3364                                 ig.Emit (OpCodes.Stloc, pinned_string);
3365
3366                                 Expression sptr = new StringPtr (pinned_string, loc);
3367                                 converted = Convert.ImplicitConversionRequired (
3368                                         ec, sptr, vi.VariableType, loc);
3369                                         
3370                                 if (converted == null)
3371                                         return;
3372
3373                                 converted.Emit (ec);
3374                                 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3375                         }
3376
3377                         public override void EmitExit(ILGenerator ig)
3378                         {
3379                                 ig.Emit (OpCodes.Ldnull);
3380                                 ig.Emit (OpCodes.Stloc, pinned_string);
3381                         }
3382                 }
3383
3384                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3385                 {
3386                         this.type = type;
3387                         declarators = decls;
3388                         statement = stmt;
3389                         loc = l;
3390                 }
3391
3392                 public override bool Resolve (EmitContext ec)
3393                 {
3394                         if (!ec.InUnsafe){
3395                                 Expression.UnsafeError (loc);
3396                                 return false;
3397                         }
3398                         
3399                         TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3400                         if (texpr == null)
3401                                 return false;
3402
3403                         expr_type = texpr.Type;
3404
3405                         CheckObsolete (expr_type);
3406
3407                         if (ec.RemapToProxy){
3408                                 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3409                                 return false;
3410                         }
3411                         
3412                         data = new Emitter [declarators.Count];
3413
3414                         if (!expr_type.IsPointer){
3415                                 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3416                                 return false;
3417                         }
3418                         
3419                         int i = 0;
3420                         foreach (Pair p in declarators){
3421                                 LocalInfo vi = (LocalInfo) p.First;
3422                                 Expression e = (Expression) p.Second;
3423
3424                                 vi.VariableInfo.SetAssigned (ec);
3425                                 vi.ReadOnly = true;
3426
3427                                 //
3428                                 // The rules for the possible declarators are pretty wise,
3429                                 // but the production on the grammar is more concise.
3430                                 //
3431                                 // So we have to enforce these rules here.
3432                                 //
3433                                 // We do not resolve before doing the case 1 test,
3434                                 // because the grammar is explicit in that the token &
3435                                 // is present, so we need to test for this particular case.
3436                                 //
3437
3438                                 if (e is Cast){
3439                                         Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3440                                         return false;
3441                                 }
3442                                 
3443                                 //
3444                                 // Case 1: & object.
3445                                 //
3446                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3447                                         Expression child = ((Unary) e).Expr;
3448
3449                                         if (child is ParameterReference || child is LocalVariableReference){
3450                                                 Report.Error (
3451                                                         213, loc, 
3452                                                         "No need to use fixed statement for parameters or " +
3453                                                         "local variable declarations (address is already " +
3454                                                         "fixed)");
3455                                                 return false;
3456                                         }
3457
3458                                         ec.InFixedInitializer = true;
3459                                         e = e.Resolve (ec);
3460                                         ec.InFixedInitializer = false;
3461                                         if (e == null)
3462                                                 return false;
3463
3464                                         child = ((Unary) e).Expr;
3465                                         
3466                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
3467                                                 return false;
3468
3469                                         data [i] = new ExpressionEmitter (e, vi);
3470                                         i++;
3471
3472                                         continue;
3473                                 }
3474
3475                                 ec.InFixedInitializer = true;
3476                                 e = e.Resolve (ec);
3477                                 ec.InFixedInitializer = false;
3478                                 if (e == null)
3479                                         return false;
3480
3481                                 //
3482                                 // Case 2: Array
3483                                 //
3484                                 if (e.Type.IsArray){
3485                                         Type array_type = TypeManager.GetElementType (e.Type);
3486                                         
3487                                         //
3488                                         // Provided that array_type is unmanaged,
3489                                         //
3490                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
3491                                                 return false;
3492
3493                                         //
3494                                         // and T* is implicitly convertible to the
3495                                         // pointer type given in the fixed statement.
3496                                         //
3497                                         ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3498                                         
3499                                         Expression converted = Convert.ImplicitConversionRequired (
3500                                                 ec, array_ptr, vi.VariableType, loc);
3501                                         if (converted == null)
3502                                                 return false;
3503
3504                                         data [i] = new ExpressionEmitter (converted, vi);
3505                                         i++;
3506
3507                                         continue;
3508                                 }
3509
3510                                 //
3511                                 // Case 3: string
3512                                 //
3513                                 if (e.Type == TypeManager.string_type){
3514                                         data [i] = new StringEmitter (e, vi, loc);
3515                                         i++;
3516                                         continue;
3517                                 }
3518
3519                                 // Case 4: fixed buffer
3520                                 FieldExpr fe = e as FieldExpr;
3521                                 if (fe != null) {
3522                                         IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3523                                         if (ff != null) {
3524                                                 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3525                                         
3526                                                 Expression converted = Convert.ImplicitConversionRequired (
3527                                                         ec, fixed_buffer_ptr, vi.VariableType, loc);
3528                                                 if (converted == null)
3529                                                         return false;
3530
3531                                                 data [i] = new ExpressionEmitter (converted, vi);
3532                                                 i++;
3533
3534                                                 continue;
3535                                         }
3536                                 }
3537
3538                                 //
3539                                 // For other cases, flag a `this is already fixed expression'
3540                                 //
3541                                 if (e is LocalVariableReference || e is ParameterReference ||
3542                                     Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3543                                     
3544                                         Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3545                                         return false;
3546                                 }
3547
3548                                 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3549                                 return false;
3550                         }
3551
3552                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3553
3554                         if (!statement.Resolve (ec)) {
3555                                 ec.KillFlowBranching ();
3556                                 return false;
3557                         }
3558
3559                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3560                         has_ret = reachability.IsUnreachable;
3561
3562                         return true;
3563                 }
3564                 
3565                 protected override void DoEmit (EmitContext ec)
3566                 {
3567                         for (int i = 0; i < data.Length; i++) {
3568                                 data [i].Emit (ec);
3569                         }
3570
3571                         statement.Emit (ec);
3572
3573                         if (has_ret)
3574                                 return;
3575
3576                         ILGenerator ig = ec.ig;
3577
3578                         //
3579                         // Clear the pinned variable
3580                         //
3581                         for (int i = 0; i < data.Length; i++) {
3582                                 data [i].EmitExit (ig);
3583                         }
3584                 }
3585         }
3586         
3587         public class Catch: Statement {
3588                 public readonly string Name;
3589                 public readonly Block  Block;
3590
3591                 Expression type_expr;
3592                 Type type;
3593                 
3594                 public Catch (Expression type, string name, Block block, Location l)
3595                 {
3596                         type_expr = type;
3597                         Name = name;
3598                         Block = block;
3599                         loc = l;
3600                 }
3601
3602                 public Type CatchType {
3603                         get {
3604                                 return type;
3605                         }
3606                 }
3607
3608                 public bool IsGeneral {
3609                         get {
3610                                 return type_expr == null;
3611                         }
3612                 }
3613
3614                 protected override void DoEmit(EmitContext ec)
3615                 {
3616                 }
3617
3618                 public override bool Resolve (EmitContext ec)
3619                 {
3620                         bool was_catch = ec.InCatch;
3621                         ec.InCatch = true;
3622                         try {
3623                                 if (type_expr != null) {
3624                                         TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3625                                         if (te == null)
3626                                                 return false;
3627
3628                                         type = te.ResolveType (ec);
3629
3630                                         CheckObsolete (type);
3631
3632                                         if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3633                                                 Error (155, "The type caught or thrown must be derived from System.Exception");
3634                                                 return false;
3635                                         }
3636                                 } else
3637                                         type = null;
3638
3639                                 return Block.Resolve (ec);
3640                         }
3641                         finally {
3642                                 ec.InCatch = was_catch;
3643                         }
3644                 }
3645         }
3646
3647         public class Try : ExceptionStatement {
3648                 public readonly Block Fini, Block;
3649                 public readonly ArrayList Specific;
3650                 public readonly Catch General;
3651
3652                 bool need_exc_block;
3653                 
3654                 //
3655                 // specific, general and fini might all be null.
3656                 //
3657                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3658                 {
3659                         if (specific == null && general == null){
3660                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3661                         }
3662                         
3663                         this.Block = block;
3664                         this.Specific = specific;
3665                         this.General = general;
3666                         this.Fini = fini;
3667                         loc = l;
3668                 }
3669
3670                 public override bool Resolve (EmitContext ec)
3671                 {
3672                         bool ok = true;
3673                         
3674                         FlowBranchingException branching = ec.StartFlowBranching (this);
3675
3676                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3677
3678                         if (!Block.Resolve (ec))
3679                                 ok = false;
3680
3681                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3682
3683                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
3684
3685                         Type[] prevCatches = new Type [Specific.Count];
3686                         int last_index = 0;
3687                         foreach (Catch c in Specific){
3688                                 ec.CurrentBranching.CreateSibling (
3689                                         c.Block, FlowBranching.SiblingType.Catch);
3690
3691                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3692
3693                                 if (c.Name != null) {
3694                                         LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3695                                         if (vi == null)
3696                                                 throw new Exception ();
3697
3698                                         vi.VariableInfo = null;
3699                                 }
3700
3701                                 if (!c.Resolve (ec))
3702                                         return false;
3703
3704                                 Type resolvedType = c.CatchType;
3705                                 for (int ii = 0; ii < last_index; ++ii) {
3706                                         if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3707                                                 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3708                                                 return false;
3709                                         }
3710                                 }
3711
3712                                 prevCatches [last_index++] = resolvedType;
3713                                 need_exc_block = true;
3714                         }
3715
3716                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3717
3718                         if (General != null){
3719                                 ec.CurrentBranching.CreateSibling (
3720                                         General.Block, FlowBranching.SiblingType.Catch);
3721
3722                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3723
3724                                 if (!General.Resolve (ec))
3725                                         ok = false;
3726
3727                                 need_exc_block = true;
3728                         }
3729
3730                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3731
3732                         if (Fini != null) {
3733                                 if (ok)
3734                                         ec.CurrentBranching.CreateSibling (
3735                                                 Fini, FlowBranching.SiblingType.Finally);
3736
3737                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3738                                 bool was_finally = ec.InFinally;
3739                                 ec.InFinally = true;
3740                                 if (!Fini.Resolve (ec))
3741                                         ok = false;
3742                                 ec.InFinally = was_finally;
3743                         }
3744
3745                         ResolveFinally (branching);
3746                         need_exc_block |= emit_finally;
3747
3748                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3749
3750                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3751
3752                         Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3753
3754                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3755                                 // Unfortunately, System.Reflection.Emit automatically emits
3756                                 // a leave to the end of the finally block.  This is a problem
3757                                 // if `returns' is true since we may jump to a point after the
3758                                 // end of the method.
3759                                 // As a workaround, emit an explicit ret here.
3760                                 ec.NeedReturnLabel ();
3761                         }
3762
3763                         return ok;
3764                 }
3765                 
3766                 protected override void DoEmit (EmitContext ec)
3767                 {
3768                         ILGenerator ig = ec.ig;
3769
3770                         if (need_exc_block)
3771                                 ig.BeginExceptionBlock ();
3772                         Block.Emit (ec);
3773
3774                         foreach (Catch c in Specific){
3775                                 LocalInfo vi;
3776                                 
3777                                 ig.BeginCatchBlock (c.CatchType);
3778
3779                                 if (c.Name != null){
3780                                         vi = c.Block.GetLocalInfo (c.Name);
3781                                         if (vi == null)
3782                                                 throw new Exception ("Variable does not exist in this block");
3783
3784                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3785                                 } else
3786                                         ig.Emit (OpCodes.Pop);
3787                                 
3788                                 c.Block.Emit (ec);
3789                         }
3790
3791                         if (General != null){
3792                                 ig.BeginCatchBlock (TypeManager.object_type);
3793                                 ig.Emit (OpCodes.Pop);
3794                                 General.Block.Emit (ec);
3795                         }
3796
3797                         DoEmitFinally (ec);
3798                         if (need_exc_block)
3799                                 ig.EndExceptionBlock ();
3800                 }
3801
3802                 public override void EmitFinally (EmitContext ec)
3803                 {
3804                         if (Fini != null){
3805                                 Fini.Emit (ec);
3806                         }
3807                 }
3808
3809                 public bool HasCatch
3810                 {
3811                         get {
3812                                 return General != null || Specific.Count > 0;
3813                         }
3814                 }
3815         }
3816
3817         public class Using : ExceptionStatement {
3818                 object expression_or_block;
3819                 Statement Statement;
3820                 ArrayList var_list;
3821                 Expression expr;
3822                 Type expr_type;
3823                 Expression conv;
3824                 Expression [] resolved_vars;
3825                 Expression [] converted_vars;
3826                 ExpressionStatement [] assign;
3827                 LocalBuilder local_copy;
3828                 
3829                 public Using (object expression_or_block, Statement stmt, Location l)
3830                 {
3831                         this.expression_or_block = expression_or_block;
3832                         Statement = stmt;
3833                         loc = l;
3834                 }
3835
3836                 //
3837                 // Resolves for the case of using using a local variable declaration.
3838                 //
3839                 bool ResolveLocalVariableDecls (EmitContext ec)
3840                 {
3841                         int i = 0;
3842
3843                         TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3844                         if (texpr == null)
3845                                 return false;
3846
3847                         expr_type = texpr.Type;
3848
3849                         //
3850                         // The type must be an IDisposable or an implicit conversion
3851                         // must exist.
3852                         //
3853                         converted_vars = new Expression [var_list.Count];
3854                         resolved_vars = new Expression [var_list.Count];
3855                         assign = new ExpressionStatement [var_list.Count];
3856
3857                         bool need_conv = !TypeManager.ImplementsInterface (
3858                                 expr_type, TypeManager.idisposable_type);
3859
3860                         foreach (DictionaryEntry e in var_list){
3861                                 Expression var = (Expression) e.Key;
3862
3863                                 var = var.ResolveLValue (ec, new EmptyExpression ());
3864                                 if (var == null)
3865                                         return false;
3866
3867                                 resolved_vars [i] = var;
3868
3869                                 if (!need_conv) {
3870                                         i++;
3871                                         continue;
3872                                 }
3873
3874                                 converted_vars [i] = Convert.ImplicitConversionRequired (
3875                                         ec, var, TypeManager.idisposable_type, loc);
3876
3877                                 if (converted_vars [i] == null)
3878                                         return false;
3879
3880                                 i++;
3881                         }
3882
3883                         i = 0;
3884                         foreach (DictionaryEntry e in var_list){
3885                                 Expression var = resolved_vars [i];
3886                                 Expression new_expr = (Expression) e.Value;
3887                                 Expression a;
3888
3889                                 a = new Assign (var, new_expr, loc);
3890                                 a = a.Resolve (ec);
3891                                 if (a == null)
3892                                         return false;
3893
3894                                 if (!need_conv)
3895                                         converted_vars [i] = var;
3896                                 assign [i] = (ExpressionStatement) a;
3897                                 i++;
3898                         }
3899
3900                         return true;
3901                 }
3902
3903                 bool ResolveExpression (EmitContext ec)
3904                 {
3905                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3906                                 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3907                                         Report.Error (1674, loc, "'{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3908                                                 TypeManager.CSharpName (expr_type));
3909                                         return false;
3910                                 }
3911                         }
3912
3913                         return true;
3914                 }
3915                 
3916                 //
3917                 // Emits the code for the case of using using a local variable declaration.
3918                 //
3919                 void EmitLocalVariableDecls (EmitContext ec)
3920                 {
3921                         ILGenerator ig = ec.ig;
3922                         int i = 0;
3923
3924                         for (i = 0; i < assign.Length; i++) {
3925                                 assign [i].EmitStatement (ec);
3926
3927                                 if (emit_finally)
3928                                         ig.BeginExceptionBlock ();
3929                         }
3930                         Statement.Emit (ec);
3931
3932                         var_list.Reverse ();
3933
3934                         DoEmitFinally (ec);
3935                 }
3936
3937                 void EmitLocalVariableDeclFinally (EmitContext ec)
3938                 {
3939                         ILGenerator ig = ec.ig;
3940
3941                         int i = assign.Length;
3942                         for (int ii = 0; ii < var_list.Count; ++ii){
3943                                 Expression var = resolved_vars [--i];
3944                                 Label skip = ig.DefineLabel ();
3945                                 
3946                                 ig.BeginFinallyBlock ();
3947                                 
3948                                 if (!var.Type.IsValueType) {
3949                                         var.Emit (ec);
3950                                         ig.Emit (OpCodes.Brfalse, skip);
3951                                         converted_vars [i].Emit (ec);
3952                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3953                                 } else {
3954                                         Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3955
3956                                         if (!(ml is MethodGroupExpr)) {
3957                                                 var.Emit (ec);
3958                                                 ig.Emit (OpCodes.Box, var.Type);
3959                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3960                                         } else {
3961                                                 MethodInfo mi = null;
3962
3963                                                 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3964                                                         if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3965                                                                 mi = mk;
3966                                                                 break;
3967                                                         }
3968                                                 }
3969
3970                                                 if (mi == null) {
3971                                                         Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3972                                                         return;
3973                                                 }
3974
3975                                                 IMemoryLocation mloc = (IMemoryLocation) var;
3976
3977                                                 mloc.AddressOf (ec, AddressOp.Load);
3978                                                 ig.Emit (OpCodes.Call, mi);
3979                                         }
3980                                 }
3981
3982                                 ig.MarkLabel (skip);
3983
3984                                 if (emit_finally) {
3985                                         ig.EndExceptionBlock ();
3986                                         if (i > 0)
3987                                                 ig.BeginFinallyBlock ();
3988                                 }
3989                         }
3990                 }
3991
3992                 void EmitExpression (EmitContext ec)
3993                 {
3994                         //
3995                         // Make a copy of the expression and operate on that.
3996                         //
3997                         ILGenerator ig = ec.ig;
3998                         local_copy = ig.DeclareLocal (expr_type);
3999                         if (conv != null)
4000                                 conv.Emit (ec);
4001                         else
4002                                 expr.Emit (ec);
4003                         ig.Emit (OpCodes.Stloc, local_copy);
4004
4005                         if (emit_finally)
4006                                 ig.BeginExceptionBlock ();
4007
4008                         Statement.Emit (ec);
4009                         
4010                         DoEmitFinally (ec);
4011                         if (emit_finally)
4012                                 ig.EndExceptionBlock ();
4013                 }
4014
4015                 void EmitExpressionFinally (EmitContext ec)
4016                 {
4017                         ILGenerator ig = ec.ig;
4018                         if (!local_copy.LocalType.IsValueType) {
4019                                 Label skip = ig.DefineLabel ();
4020                                 ig.Emit (OpCodes.Ldloc, local_copy);
4021                                 ig.Emit (OpCodes.Brfalse, skip);
4022                                 ig.Emit (OpCodes.Ldloc, local_copy);
4023                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4024                                 ig.MarkLabel (skip);
4025                         } else {
4026                                 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4027
4028                                 if (!(ml is MethodGroupExpr)) {
4029                                         ig.Emit (OpCodes.Ldloc, local_copy);
4030                                         ig.Emit (OpCodes.Box, local_copy.LocalType);
4031                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4032                                 } else {
4033                                         MethodInfo mi = null;
4034
4035                                         foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4036                                                 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4037                                                         mi = mk;
4038                                                         break;
4039                                                 }
4040                                         }
4041
4042                                         if (mi == null) {
4043                                                 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4044                                                 return;
4045                                         }
4046
4047                                         ig.Emit (OpCodes.Ldloca, local_copy);
4048                                         ig.Emit (OpCodes.Call, mi);
4049                                 }
4050                         }
4051                 }
4052                 
4053                 public override bool Resolve (EmitContext ec)
4054                 {
4055                         if (expression_or_block is DictionaryEntry){
4056                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4057                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4058
4059                                 if (!ResolveLocalVariableDecls (ec))
4060                                         return false;
4061
4062                         } else if (expression_or_block is Expression){
4063                                 expr = (Expression) expression_or_block;
4064
4065                                 expr = expr.Resolve (ec);
4066                                 if (expr == null)
4067                                         return false;
4068
4069                                 expr_type = expr.Type;
4070
4071                                 if (!ResolveExpression (ec))
4072                                         return false;
4073                         }
4074
4075                         FlowBranchingException branching = ec.StartFlowBranching (this);
4076
4077                         bool ok = Statement.Resolve (ec);
4078
4079                         if (!ok) {
4080                                 ec.KillFlowBranching ();
4081                                 return false;
4082                         }
4083
4084                         ResolveFinally (branching);                                     
4085                         FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4086
4087                         if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4088                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
4089                                 // to the end of the finally block.  This is a problem if `returns'
4090                                 // is true since we may jump to a point after the end of the method.
4091                                 // As a workaround, emit an explicit ret here.
4092                                 ec.NeedReturnLabel ();
4093                         }
4094
4095                         return true;
4096                 }
4097                 
4098                 protected override void DoEmit (EmitContext ec)
4099                 {
4100                         if (expression_or_block is DictionaryEntry)
4101                                 EmitLocalVariableDecls (ec);
4102                         else if (expression_or_block is Expression)
4103                                 EmitExpression (ec);
4104                 }
4105
4106                 public override void EmitFinally (EmitContext ec)
4107                 {
4108                         if (expression_or_block is DictionaryEntry)
4109                                 EmitLocalVariableDeclFinally (ec);
4110                         else if (expression_or_block is Expression)
4111                                 EmitExpressionFinally (ec);
4112                 }
4113         }
4114
4115         /// <summary>
4116         ///   Implementation of the foreach C# statement
4117         /// </summary>
4118         public class Foreach : ExceptionStatement {
4119                 Expression type;
4120                 Expression variable;
4121                 Expression expr;
4122                 Statement statement;
4123                 ForeachHelperMethods hm;
4124                 Expression empty, conv;
4125                 Type array_type, element_type;
4126                 Type var_type;
4127                 VariableStorage enumerator;
4128                 ArrayForeach array;
4129                 
4130                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4131                                 Statement stmt, Location l)
4132                 {
4133                         this.type = type;
4134                         this.variable = var;
4135                         this.expr = expr;
4136                         statement = stmt;
4137                         loc = l;
4138                 }
4139                 
4140                 public override bool Resolve (EmitContext ec)
4141                 {
4142                         expr = expr.Resolve (ec);
4143                         if (expr == null)
4144                                 return false;
4145
4146                         if (expr is NullLiteral) {
4147                                 Report.Error (186, expr.Location, "Use of null is not valid in this context");
4148                                 return false;
4149                         }
4150
4151                         TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4152                         if (texpr == null)
4153                                 return false;
4154                         
4155                         var_type = texpr.Type;
4156
4157                         //
4158                         // We need an instance variable.  Not sure this is the best
4159                         // way of doing this.
4160                         //
4161                         // FIXME: When we implement propertyaccess, will those turn
4162                         // out to return values in ExprClass?  I think they should.
4163                         //
4164                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4165                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4166                                 error1579 (expr.Type);
4167                                 return false;
4168                         }
4169
4170                         if (expr.Type.IsArray) {
4171                                 array_type = expr.Type;
4172                                 element_type = TypeManager.GetElementType (array_type);
4173
4174                                 empty = new EmptyExpression (element_type);
4175
4176                                 array = new ArrayForeach (type, variable, expr, statement, loc);
4177                                 return array.Resolve (ec);
4178                         } else {
4179                                 hm = ProbeCollectionType (ec, expr.Type);
4180                                 if (hm == null){
4181                                         error1579 (expr.Type);
4182                                         return false;
4183                                 }                       
4184
4185                                 array_type = expr.Type;
4186                                 element_type = hm.element_type;
4187
4188                                 empty = new EmptyExpression (hm.element_type);
4189                         }
4190
4191                         bool ok = true;
4192
4193                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4194                         ec.CurrentBranching.CreateSibling ();
4195
4196                         //
4197                         //
4198                         // FIXME: maybe we can apply the same trick we do in the
4199                         // array handling to avoid creating empty and conv in some cases.
4200                         //
4201                         // Although it is not as important in this case, as the type
4202                         // will not likely be object (what the enumerator will return).
4203                         //
4204                         conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4205                         if (conv == null)
4206                                 ok = false;
4207
4208                         variable = variable.ResolveLValue (ec, empty);
4209                         if (variable == null)
4210                                 ok = false;
4211
4212                         bool disposable = (hm != null) && hm.is_disposable;
4213                         FlowBranchingException branching = null;
4214                         if (disposable)
4215                                 branching = ec.StartFlowBranching (this);
4216
4217                         if (!statement.Resolve (ec))
4218                                 ok = false;
4219
4220                         if (disposable) {
4221                                 ResolveFinally (branching);
4222                                 ec.EndFlowBranching ();
4223                         } else
4224                                 emit_finally = true;
4225
4226                         ec.EndFlowBranching ();
4227
4228                         return ok;
4229                 }
4230                 
4231                 //
4232                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4233                 //
4234                 static MethodInfo FetchMethodMoveNext (Type t)
4235                 {
4236                         MemberList move_next_list;
4237                         
4238                         move_next_list = TypeContainer.FindMembers (
4239                                 t, MemberTypes.Method,
4240                                 BindingFlags.Public | BindingFlags.Instance,
4241                                 Type.FilterName, "MoveNext");
4242                         if (move_next_list.Count == 0)
4243                                 return null;
4244
4245                         foreach (MemberInfo m in move_next_list){
4246                                 MethodInfo mi = (MethodInfo) m;
4247                                 Type [] args;
4248                                 
4249                                 args = TypeManager.GetArgumentTypes (mi);
4250                                 if (args != null && args.Length == 0){
4251                                         if (TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type)
4252                                                 return mi;
4253                                 }
4254                         }
4255                         return null;
4256                 }
4257                 
4258                 //
4259                 // Retrieves a `public T get_Current ()' method from the Type `t'
4260                 //
4261                 static MethodInfo FetchMethodGetCurrent (Type t)
4262                 {
4263                         MemberList get_current_list;
4264
4265                         get_current_list = TypeContainer.FindMembers (
4266                                 t, MemberTypes.Method,
4267                                 BindingFlags.Public | BindingFlags.Instance,
4268                                 Type.FilterName, "get_Current");
4269                         if (get_current_list.Count == 0)
4270                                 return null;
4271
4272                         foreach (MemberInfo m in get_current_list){
4273                                 MethodInfo mi = (MethodInfo) m;
4274                                 Type [] args;
4275
4276                                 args = TypeManager.GetArgumentTypes (mi);
4277                                 if (args != null && args.Length == 0)
4278                                         return mi;
4279                         }
4280                         return null;
4281                 }
4282
4283                 // 
4284                 // Retrieves a `public void Dispose ()' method from the Type `t'
4285                 //
4286                 static MethodInfo FetchMethodDispose (Type t)
4287                 {
4288                         MemberList dispose_list;
4289                         
4290                         dispose_list = TypeContainer.FindMembers (
4291                                 t, MemberTypes.Method,
4292                                 BindingFlags.Public | BindingFlags.Instance,
4293                                 Type.FilterName, "Dispose");
4294                         if (dispose_list.Count == 0)
4295                                 return null;
4296
4297                         foreach (MemberInfo m in dispose_list){
4298                                 MethodInfo mi = (MethodInfo) m;
4299                                 Type [] args;
4300                                 
4301                                 args = TypeManager.GetArgumentTypes (mi);
4302                                 if (args != null && args.Length == 0){
4303                                         if (mi.ReturnType == TypeManager.void_type)
4304                                                 return mi;
4305                                 }
4306                         }
4307                         return null;
4308                 }
4309
4310                 // 
4311                 // This struct records the helper methods used by the Foreach construct
4312                 //
4313                 class ForeachHelperMethods {
4314                         public EmitContext ec;
4315                         public MethodInfo get_enumerator;
4316                         public MethodInfo move_next;
4317                         public MethodInfo get_current;
4318                         public Type element_type;
4319                         public Type enumerator_type;
4320                         public bool is_disposable;
4321
4322                         public ForeachHelperMethods (EmitContext ec)
4323                         {
4324                                 this.ec = ec;
4325                                 this.element_type = TypeManager.object_type;
4326                                 this.enumerator_type = TypeManager.ienumerator_type;
4327                                 this.is_disposable = true;
4328                         }
4329                 }
4330                 
4331                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4332                 {
4333                         if (m == null)
4334                                 return false;
4335
4336                         if (!(m is MethodInfo))
4337                                 return false;
4338                         
4339                         if (m.Name != "GetEnumerator")
4340                                 return false;
4341
4342                         MethodInfo mi = (MethodInfo) m;
4343                         Type [] args = TypeManager.GetArgumentTypes (mi);
4344                         if (args != null){
4345                                 if (args.Length != 0)
4346                                         return false;
4347                         }
4348                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4349
4350                         // Check whether GetEnumerator is public
4351                         if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4352                                         return false;
4353
4354                         if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4355                                 //
4356                                 // Apply the same optimization as MS: skip the GetEnumerator
4357                                 // returning an IEnumerator, and use the one returning a 
4358                                 // CharEnumerator instead. This allows us to avoid the 
4359                                 // try-finally block and the boxing.
4360                                 //
4361                                 return false;
4362
4363                         //
4364                         // Ok, we can access it, now make sure that we can do something
4365                         // with this `GetEnumerator'
4366                         //
4367
4368                         Type return_type = mi.ReturnType;
4369                         if (mi.ReturnType == TypeManager.ienumerator_type ||
4370                             TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4371                             (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4372                                 
4373                                 //
4374                                 // If it is not an interface, lets try to find the methods ourselves.
4375                                 // For example, if we have:
4376                                 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4377                                 // We can avoid the iface call. This is a runtime perf boost.
4378                                 // even bigger if we have a ValueType, because we avoid the cost
4379                                 // of boxing.
4380                                 //
4381                                 // We have to make sure that both methods exist for us to take
4382                                 // this path. If one of the methods does not exist, we will just
4383                                 // use the interface. Sadly, this complex if statement is the only
4384                                 // way I could do this without a goto
4385                                 //
4386                                 
4387                                 if (return_type.IsInterface ||
4388                                     (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4389                                     (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4390                                         
4391                                         hm.move_next = TypeManager.bool_movenext_void;
4392                                         hm.get_current = TypeManager.object_getcurrent_void;
4393                                         return true;    
4394                                 }
4395
4396                         } else {
4397
4398                                 //
4399                                 // Ok, so they dont return an IEnumerable, we will have to
4400                                 // find if they support the GetEnumerator pattern.
4401                                 //
4402                                 
4403                                 hm.move_next = FetchMethodMoveNext (return_type);
4404                                 if (hm.move_next == null)
4405                                         return false;
4406                                 
4407                                 hm.get_current = FetchMethodGetCurrent (return_type);
4408                                 if (hm.get_current == null)
4409                                         return false;
4410                         }
4411                         
4412                         hm.element_type = hm.get_current.ReturnType;
4413                         hm.enumerator_type = return_type;
4414                         hm.is_disposable = !hm.enumerator_type.IsSealed ||
4415                                 TypeManager.ImplementsInterface (
4416                                         hm.enumerator_type, TypeManager.idisposable_type);
4417
4418                         return true;
4419                 }
4420                 
4421                 /// <summary>
4422                 ///   This filter is used to find the GetEnumerator method
4423                 ///   on which IEnumerator operates
4424                 /// </summary>
4425                 static MemberFilter FilterEnumerator;
4426                 
4427                 static Foreach ()
4428                 {
4429                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4430                 }
4431
4432                 void error1579 (Type t)
4433                 {
4434                         Report.Error (1579, loc,
4435                                       "foreach statement cannot operate on variables of type `" +
4436                                       t.FullName + "' because that class does not provide a " +
4437                                       " GetEnumerator method or it is inaccessible");
4438                 }
4439
4440                 static bool TryType (Type t, ForeachHelperMethods hm)
4441                 {
4442                         MemberList mi;
4443                         
4444                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4445                                                         BindingFlags.Public | BindingFlags.NonPublic |
4446                                                         BindingFlags.Instance | BindingFlags.DeclaredOnly,
4447                                                         FilterEnumerator, hm);
4448
4449                         if (mi.Count == 0)
4450                                 return false;
4451
4452                         hm.get_enumerator = (MethodInfo) mi [0];
4453                         return true;    
4454                 }
4455                 
4456                 //
4457                 // Looks for a usable GetEnumerator in the Type, and if found returns
4458                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4459                 //
4460                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4461                 {
4462                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4463
4464                         for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4465                                 if (TryType (tt, hm))
4466                                         return hm;
4467                                 tt = tt.BaseType;
4468                         }
4469
4470                         //
4471                         // Now try to find the method in the interfaces
4472                         //
4473                         while (t != null){
4474                                 Type [] ifaces = t.GetInterfaces ();
4475
4476                                 foreach (Type i in ifaces){
4477                                         if (TryType (i, hm))
4478                                                 return hm;
4479                                 }
4480                                 
4481                                 //
4482                                 // Since TypeBuilder.GetInterfaces only returns the interface
4483                                 // types for this type, we have to keep looping, but once
4484                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4485                                 // done, because it returns all the types
4486                                 //
4487                                 if ((t is TypeBuilder))
4488                                         t = t.BaseType;
4489                                 else
4490                                         break;
4491                         } 
4492
4493                         return null;
4494                 }
4495
4496                 //
4497                 // FIXME: possible optimization.
4498                 // We might be able to avoid creating `empty' if the type is the sam
4499                 //
4500                 bool EmitCollectionForeach (EmitContext ec)
4501                 {
4502                         ILGenerator ig = ec.ig;
4503
4504                         enumerator = new VariableStorage (ec, hm.enumerator_type);
4505                         enumerator.EmitThis (ig);
4506                         //
4507                         // Instantiate the enumerator
4508                         //
4509                         if (expr.Type.IsValueType){
4510                                 IMemoryLocation ml = expr as IMemoryLocation;
4511                                 // Load the address of the value type.
4512                                 if (ml == null) {
4513                                         // This happens if, for example, you have a property
4514                                         // returning a struct which is IEnumerable
4515                                         LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4516                                                 expr.Emit(ec);
4517                                         ig.Emit (OpCodes.Stloc, t);
4518                                         ig.Emit (OpCodes.Ldloca, t);
4519                                         ec.FreeTemporaryLocal (t, expr.Type);
4520                                         } else {
4521                                                 ml.AddressOf (ec, AddressOp.Load);
4522                                         }
4523                                 
4524                                 // Emit the call.
4525                                 if (hm.get_enumerator.DeclaringType.IsValueType) {
4526                                         // the method is declared on the value type
4527                                         ig.Emit (OpCodes.Call, hm.get_enumerator);
4528                                 } else {
4529                                         // it is an interface method, so we must box
4530                                         ig.Emit (OpCodes.Box, expr.Type);
4531                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4532                                 }
4533                         } else {
4534                                 expr.Emit (ec);
4535                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4536                         }
4537                         enumerator.EmitStore (ig);
4538
4539                         //
4540                         // Protect the code in a try/finalize block, so that
4541                         // if the beast implement IDisposable, we get rid of it
4542                         //
4543                         if (hm.is_disposable && emit_finally)
4544                                 ig.BeginExceptionBlock ();
4545                         
4546                         Label end_try = ig.DefineLabel ();
4547                         
4548                         ig.MarkLabel (ec.LoopBegin);
4549                         
4550                         enumerator.EmitCall (ig, hm.move_next);
4551                         
4552                         ig.Emit (OpCodes.Brfalse, end_try);
4553
4554                         if (ec.InIterator)
4555                                 ig.Emit (OpCodes.Ldarg_0);
4556                         
4557                         enumerator.EmitCall (ig, hm.get_current);
4558
4559                         if (ec.InIterator){
4560                                 conv.Emit (ec);
4561                                 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4562                         } else 
4563                                 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4564                                 
4565                         statement.Emit (ec);
4566                         ig.Emit (OpCodes.Br, ec.LoopBegin);
4567                         ig.MarkLabel (end_try);
4568                         
4569                         // The runtime provides this for us.
4570                         // ig.Emit (OpCodes.Leave, end);
4571
4572                         //
4573                         // Now the finally block
4574                         //
4575                         if (hm.is_disposable) {
4576                                 DoEmitFinally (ec);
4577                                 if (emit_finally)
4578                                         ig.EndExceptionBlock ();
4579                         }
4580
4581                         ig.MarkLabel (ec.LoopEnd);
4582                         return false;
4583                 }
4584
4585                 public override void EmitFinally (EmitContext ec)
4586                 {
4587                         ILGenerator ig = ec.ig;
4588
4589                         if (hm.enumerator_type.IsValueType) {
4590                                 enumerator.EmitThis (ig);
4591
4592                                 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4593                                 if (mi != null) {
4594                                         enumerator.EmitLoadAddress (ig);
4595                                         ig.Emit (OpCodes.Call, mi);
4596                                 } else {
4597                                         enumerator.EmitLoad (ig);
4598                                         ig.Emit (OpCodes.Box, hm.enumerator_type);
4599                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4600                                 }
4601                         } else {
4602                                 Label call_dispose = ig.DefineLabel ();
4603
4604                                 enumerator.EmitThis (ig);
4605                                 enumerator.EmitLoad (ig);
4606                                 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4607                                 ig.Emit (OpCodes.Dup);
4608                                 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4609                                 ig.Emit (OpCodes.Pop);
4610
4611                                 Label end_finally = ig.DefineLabel ();
4612                                 ig.Emit (OpCodes.Br, end_finally);
4613
4614                                 ig.MarkLabel (call_dispose);
4615                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4616                                 ig.MarkLabel (end_finally);
4617
4618                                 if (emit_finally)
4619                                         ig.Emit (OpCodes.Endfinally);
4620                         }
4621                 }
4622
4623                 protected override void DoEmit (EmitContext ec)
4624                 {
4625                         ILGenerator ig = ec.ig;
4626                         
4627                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4628                         ec.LoopBegin = ig.DefineLabel ();
4629                         ec.LoopEnd = ig.DefineLabel ();
4630                         
4631                         if (hm != null)
4632                                 EmitCollectionForeach (ec);
4633                         else
4634                                 array.Emit (ec);
4635                         
4636                         ec.LoopBegin = old_begin;
4637                         ec.LoopEnd = old_end;
4638                 }
4639
4640                 protected class TemporaryVariable : Expression
4641                 {
4642                         FieldBuilder fb;
4643                         LocalBuilder local;
4644
4645                         public TemporaryVariable (Type type, Location loc)
4646                         {
4647                                 this.type = type;
4648                                 this.loc = loc;
4649                                 eclass = ExprClass.Value;
4650                         }
4651
4652                         static int count;
4653
4654                         public override Expression DoResolve (EmitContext ec)
4655                         {
4656                                 if (ec.InIterator) {
4657                                         count++;
4658                                         fb = ec.CurrentIterator.MapVariable (
4659                                                 "s_", count.ToString (), type);
4660                                 } else
4661                                         local = ec.ig.DeclareLocal (type);
4662
4663                                 return this;
4664                         }
4665
4666                         public override void Emit (EmitContext ec)
4667                         {
4668                                 ILGenerator ig = ec.ig;
4669
4670                                 if (fb != null) {
4671                                         ig.Emit (OpCodes.Ldarg_0);
4672                                         ig.Emit (OpCodes.Ldfld, fb);
4673                                 } else {
4674                                         ig.Emit (OpCodes.Ldloc, local);
4675                                 }
4676                         }
4677
4678                         public void Store (EmitContext ec, Expression right_side)
4679                         {
4680                                 if (fb != null)
4681                                         ec.ig.Emit (OpCodes.Ldarg_0);
4682                                 right_side.Emit (ec);
4683                                 if (fb == null)
4684                                         ec.ig.Emit (OpCodes.Stloc, local);
4685                                 else
4686                                         ec.ig.Emit (OpCodes.Stfld, fb);
4687                         }
4688
4689                         public void EmitThis (ILGenerator ig)
4690                         {
4691                                 if (fb != null)
4692                                         ig.Emit (OpCodes.Ldarg_0);
4693                         }
4694
4695                         public void EmitStore (ILGenerator ig)
4696                         {
4697                                 if (fb == null)
4698                                         ig.Emit (OpCodes.Stloc, local);
4699                                 else
4700                                         ig.Emit (OpCodes.Stfld, fb);
4701                         }
4702                 }
4703
4704                 protected class ArrayCounter : TemporaryVariable
4705                 {
4706                         public ArrayCounter (Location loc)
4707                                 : base (TypeManager.int32_type, loc)
4708                         { }
4709
4710                         public void Initialize (EmitContext ec)
4711                         {
4712                                 EmitThis (ec.ig);
4713                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
4714                                 EmitStore (ec.ig);
4715                         }
4716
4717                         public void Increment (EmitContext ec)
4718                         {
4719                                 EmitThis (ec.ig);
4720                                 Emit (ec);
4721                                 ec.ig.Emit (OpCodes.Ldc_I4_1);
4722                                 ec.ig.Emit (OpCodes.Add);
4723                                 EmitStore (ec.ig);
4724                         }
4725                 }
4726
4727                 protected class ArrayForeach : Statement
4728                 {
4729                         Expression type, variable, expr, conv;
4730                         Statement statement;
4731                         Type array_type, element_type;
4732                         Type var_type;
4733                         TemporaryVariable[] lengths;
4734                         ArrayCounter[] counter;
4735                         int rank;
4736
4737                         TemporaryVariable copy;
4738                         Expression access;
4739
4740                         public ArrayForeach (Expression type, Expression var,
4741                                              Expression expr, Statement stmt, Location l)
4742                         {
4743                                 this.type = type;
4744                                 this.variable = var;
4745                                 this.expr = expr;
4746                                 statement = stmt;
4747                                 loc = l;
4748                         }
4749
4750                         public override bool Resolve (EmitContext ec)
4751                         {                               
4752                                 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4753                                 if (texpr == null)
4754                                         return false;
4755                         
4756                                 var_type = texpr.Type;
4757
4758                                 array_type = expr.Type;
4759                                 element_type = TypeManager.GetElementType (array_type);
4760                                 rank = array_type.GetArrayRank ();
4761
4762                                 copy = new TemporaryVariable (array_type, loc);
4763                                 copy.Resolve (ec);
4764
4765                                 counter = new ArrayCounter [rank];
4766                                 lengths = new TemporaryVariable [rank];
4767
4768                                 ArrayList list = new ArrayList ();
4769                                 for (int i = 0; i < rank; i++) {
4770                                         counter [i] = new ArrayCounter (loc);
4771                                         counter [i].Resolve (ec);
4772
4773                                         lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4774                                         lengths [i].Resolve (ec);
4775
4776                                         list.Add (counter [i]);
4777                                 }
4778
4779                                 access = new ElementAccess (copy, list, loc).Resolve (ec);
4780                                 if (access == null)
4781                                         return false;
4782
4783                                 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4784                                 if (conv == null)
4785                                         return false;
4786
4787                                 bool ok = true;
4788
4789                                 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4790                                 ec.CurrentBranching.CreateSibling ();
4791
4792                                 variable = variable.ResolveLValue (ec, conv);
4793                                 if (variable == null)
4794                                         ok = false;
4795
4796                                 if (!statement.Resolve (ec))
4797                                         ok = false;
4798
4799                                 ec.EndFlowBranching ();
4800
4801                                 return ok;
4802                         }
4803
4804                         protected override void DoEmit (EmitContext ec)
4805                         {
4806                                 ILGenerator ig = ec.ig;
4807
4808                                 copy.Store (ec, expr);
4809
4810                                 Label[] test = new Label [rank];
4811                                 Label[] loop = new Label [rank];
4812
4813                                 for (int i = 0; i < rank; i++) {
4814                                         test [i] = ig.DefineLabel ();
4815                                         loop [i] = ig.DefineLabel ();
4816
4817                                         lengths [i].EmitThis (ig);
4818                                         ((ArrayAccess) access).EmitGetLength (ec, i);
4819                                         lengths [i].EmitStore (ig);
4820                                 }
4821
4822                                 for (int i = 0; i < rank; i++) {
4823                                         counter [i].Initialize (ec);
4824
4825                                         ig.Emit (OpCodes.Br, test [i]);
4826                                         ig.MarkLabel (loop [i]);
4827                                 }
4828
4829                                 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4830
4831                                 statement.Emit (ec);
4832
4833                                 ig.MarkLabel (ec.LoopBegin);
4834
4835                                 for (int i = rank - 1; i >= 0; i--){
4836                                         counter [i].Increment (ec);
4837
4838                                         ig.MarkLabel (test [i]);
4839                                         counter [i].Emit (ec);
4840                                         lengths [i].Emit (ec);
4841                                         ig.Emit (OpCodes.Blt, loop [i]);
4842                                 }
4843
4844                                 ig.MarkLabel (ec.LoopEnd);
4845                         }
4846                 }
4847         }
4848 }