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