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