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