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