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