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