2002-03-12 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 //
7 // (C) 2001 Ximian, Inc.
8 //
9
10 using System;
11 using System.Reflection;
12 using System.Reflection.Emit;
13 using System.Diagnostics;
14
15 namespace Mono.CSharp {
16
17         using System.Collections;
18         
19         public abstract class Statement {
20
21                 /// <summary>
22                 ///   Return value indicates whether all code paths emitted return.
23                 /// </summary>
24                 public abstract bool Emit (EmitContext ec);
25
26                 /// <remarks>
27                 ///    Emits a bool expression.
28                 /// </remarks>
29                 public static Expression EmitBoolExpression (EmitContext ec, Expression e,
30                                                              Label target, bool isTrue, Location loc)
31                 {
32                         e = e.Resolve (ec);
33
34                         if (e == null)
35                                 return null;
36
37                         if (e.Type != TypeManager.bool_type){
38                                 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type,
39                                                                 new Location (-1));
40                         }
41
42                         if (e == null){
43                                 Report.Error (
44                                         31, loc, "Can not convert the expression to a boolean");
45                                 return null;
46                         }
47
48                         bool invert = false;
49                         if (e is Unary){
50                                 Unary u = (Unary) e;
51                                 
52                                 if (u.Oper == Unary.Operator.LogicalNot){
53                                         invert = true;
54
55                                         u.EmitLogicalNot (ec);
56                                 }
57                         } 
58
59                         if (!invert)
60                                 e.Emit (ec);
61
62                         if (isTrue){
63                                 if (invert)
64                                         ec.ig.Emit (OpCodes.Brfalse, target);
65                                 else
66                                         ec.ig.Emit (OpCodes.Brtrue, target);
67                         } else {
68                                 if (invert)
69                                         ec.ig.Emit (OpCodes.Brtrue, target);
70                                 else
71                                         ec.ig.Emit (OpCodes.Brfalse, target);
72                         }
73                         
74                         return e;
75                 }
76
77         }
78
79         public class EmptyStatement : Statement {
80                 public override bool Emit (EmitContext ec)
81                 {
82                         return false;
83                 }
84         }
85         
86         public class If : Statement {
87                 public readonly Expression  Expr;
88                 public readonly Statement   TrueStatement;
89                 public readonly Statement   FalseStatement;
90                 Location loc;
91                 
92                 public If (Expression expr, Statement trueStatement, Location l)
93                 {
94                         Expr = expr;
95                         TrueStatement = trueStatement;
96                         loc = l;
97                 }
98
99                 public If (Expression expr,
100                            Statement trueStatement,
101                            Statement falseStatement,
102                            Location l)
103                 {
104                         Expr = expr;
105                         TrueStatement = trueStatement;
106                         FalseStatement = falseStatement;
107                         loc = l;
108                 }
109
110                 public override bool Emit (EmitContext ec)
111                 {
112                         ILGenerator ig = ec.ig;
113                         Label false_target = ig.DefineLabel ();
114                         Label end;
115                         bool is_true_ret, is_false_ret;
116                         
117                         if (EmitBoolExpression (ec, Expr, false_target, false, loc) == null)
118                                 return false;
119                         
120                         is_true_ret = TrueStatement.Emit (ec);
121                         is_false_ret = is_true_ret;
122
123                         if (FalseStatement != null){
124                                 bool branch_emitted = false;
125                                 
126                                 end = ig.DefineLabel ();
127                                 if (!is_true_ret){
128                                         ig.Emit (OpCodes.Br, end);
129                                         branch_emitted = true;
130                                 }
131                         
132                                 ig.MarkLabel (false_target);
133                                 is_false_ret = FalseStatement.Emit (ec);
134
135                                 if (branch_emitted)
136                                         ig.MarkLabel (end);
137                         } else {
138                                 ig.MarkLabel (false_target);
139                                 is_false_ret = false;
140                         }
141
142                         return is_true_ret && is_false_ret;
143                 }
144         }
145
146         public class Do : Statement {
147                 public readonly Expression Expr;
148                 public readonly Statement  EmbeddedStatement;
149                 Location loc;
150                 
151                 public Do (Statement statement, Expression boolExpr, Location l)
152                 {
153                         Expr = boolExpr;
154                         EmbeddedStatement = statement;
155                         loc = l;
156                 }
157
158                 public override bool Emit (EmitContext ec)
159                 {
160                         ILGenerator ig = ec.ig;
161                         Label loop = ig.DefineLabel ();
162                         Label old_begin = ec.LoopBegin;
163                         Label old_end = ec.LoopEnd;
164                         bool  old_inloop = ec.InLoop;
165                         Expression e;
166                         
167                         ec.LoopBegin = ig.DefineLabel ();
168                         ec.LoopEnd = ig.DefineLabel ();
169                         ec.InLoop = true;
170                                 
171                         ig.MarkLabel (loop);
172                         EmbeddedStatement.Emit (ec);
173                         ig.MarkLabel (ec.LoopBegin);
174                         e = EmitBoolExpression (ec, Expr, loop, true, loc);
175                         ig.MarkLabel (ec.LoopEnd);
176
177                         ec.LoopBegin = old_begin;
178                         ec.LoopEnd = old_end;
179                         ec.InLoop = old_inloop;
180
181                         //
182                         // Inform whether we are infinite or not
183                         //
184                         if (e is BoolConstant){
185                                 BoolConstant bc = (BoolConstant) e;
186
187                                 if (bc.Value == true)
188                                         return true;
189                         }
190                         
191                         return false;
192                 }
193         }
194
195         public class While : Statement {
196                 public readonly Expression Expr;
197                 public readonly Statement Statement;
198                 Location loc;
199                 
200                 public While (Expression boolExpr, Statement statement, Location l)
201                 {
202                         Expr = boolExpr;
203                         Statement = statement;
204                         loc = l;
205                 }
206
207                 public override bool Emit (EmitContext ec)
208                 {
209                         ILGenerator ig = ec.ig;
210                         Label old_begin = ec.LoopBegin;
211                         Label old_end = ec.LoopEnd;
212                         bool old_inloop = ec.InLoop;
213                         Expression e;
214                         
215                         ec.LoopBegin = ig.DefineLabel ();
216                         ec.LoopEnd = ig.DefineLabel ();
217                         ec.InLoop = true;
218                         
219                         ig.MarkLabel (ec.LoopBegin);
220                         e = EmitBoolExpression (ec, Expr, ec.LoopEnd, false, loc);
221                         Statement.Emit (ec);
222                         ig.Emit (OpCodes.Br, ec.LoopBegin);
223                         ig.MarkLabel (ec.LoopEnd);
224
225                         ec.LoopBegin = old_begin;
226                         ec.LoopEnd = old_end;
227                         ec.InLoop = old_inloop;
228
229                         //
230                         // Inform whether we are infinite or not
231                         //
232                         if (e is BoolConstant){
233                                 BoolConstant bc = (BoolConstant) e;
234
235                                 if (bc.Value == true)
236                                         return true;
237                         }
238                         return false;
239                 }
240         }
241
242         public class For : Statement {
243                 public readonly Statement InitStatement;
244                 public readonly Expression Test;
245                 public readonly Statement Increment;
246                 public readonly Statement Statement;
247                 Location loc;
248                 
249                 public For (Statement initStatement,
250                             Expression test,
251                             Statement increment,
252                             Statement statement,
253                             Location l)
254                 {
255                         InitStatement = initStatement;
256                         Test = test;
257                         Increment = increment;
258                         Statement = statement;
259                         loc = l;
260                 }
261
262                 public override bool Emit (EmitContext ec)
263                 {
264                         ILGenerator ig = ec.ig;
265                         Label old_begin = ec.LoopBegin;
266                         Label old_end = ec.LoopEnd;
267                         bool old_inloop = ec.InLoop;
268                         Label loop = ig.DefineLabel ();
269                         Expression e = null;
270
271                         if (InitStatement != null)
272                                 if (! (InitStatement is EmptyStatement))
273                                         InitStatement.Emit (ec);
274
275                         ec.LoopBegin = ig.DefineLabel ();
276                         ec.LoopEnd = ig.DefineLabel ();
277                         ec.InLoop = true;
278
279                         ig.MarkLabel (loop);
280
281                         //
282                         // If test is null, there is no test, and we are just
283                         // an infinite loop
284                         //
285                         if (Test != null)
286                                 e = EmitBoolExpression (ec, Test, ec.LoopEnd, false, loc);
287                 
288                         Statement.Emit (ec);
289                         ig.MarkLabel (ec.LoopBegin);
290                         if (!(Increment is EmptyStatement))
291                                 Increment.Emit (ec);
292                         ig.Emit (OpCodes.Br, loop);
293                         ig.MarkLabel (ec.LoopEnd);
294
295                         ec.LoopBegin = old_begin;
296                         ec.LoopEnd = old_end;
297                         ec.InLoop = old_inloop;
298
299                         //
300                         // Inform whether we are infinite or not
301                         //
302                         if (Test != null){
303                                 if (e is BoolConstant){
304                                         BoolConstant bc = (BoolConstant) e;
305
306                                         if (bc.Value)
307                                                 return true;
308                                 }
309                                 return false;
310                         } else
311                                 return true;
312                 }
313         }
314         
315         public class StatementExpression : Statement {
316                 public readonly ExpressionStatement Expr;
317                 
318                 public StatementExpression (ExpressionStatement expr)
319                 {
320                         Expr = expr;
321                 }
322
323                 public override bool Emit (EmitContext ec)
324                 {
325                         ILGenerator ig = ec.ig;
326                         Expression ne;
327                         
328                         ne = Expr.Resolve (ec);
329                         if (ne != null){
330                                 if (ne is ExpressionStatement)
331                                         ((ExpressionStatement) ne).EmitStatement (ec);
332                                 else {
333                                         ne.Emit (ec);
334                                         ig.Emit (OpCodes.Pop);
335                                 }
336                         }
337
338                         return false;
339                 }
340
341                 public override string ToString ()
342                 {
343                         return "StatementExpression (" + Expr + ")";
344                 }
345         }
346
347         /// <summary>
348         ///   Implements the return statement
349         /// </summary>
350         public class Return : Statement {
351                 public Expression Expr;
352                 public readonly Location loc;
353                 
354                 public Return (Expression expr, Location l)
355                 {
356                         Expr = expr;
357                         loc = l;
358                 }
359
360                 public override bool Emit (EmitContext ec)
361                 {
362                         if (ec.InFinally){
363                                 Report.Error (157,loc,"Control can not leave the body of the finally block");
364                                 return false;
365                         }
366                         
367                         if (ec.ReturnType == null){
368                                 if (Expr != null){
369                                         Report.Error (127, loc, "Return with a value not allowed here");
370                                         return false;
371                                 }
372                         } else {
373                                 if (Expr == null){
374                                         Report.Error (126, loc, "An object of type `" +
375                                                       TypeManager.CSharpName (ec.ReturnType) + "' is " +
376                                                       "expected for the return statement");
377                                         return false;
378                                 }
379
380                                 Expr = Expr.Resolve (ec);
381                                 if (Expr == null)
382                                         return false;
383
384                                 if (Expr.Type != ec.ReturnType)
385                                         Expr = Expression.ConvertImplicitRequired (
386                                                 ec, Expr, ec.ReturnType, loc);
387
388                                 if (Expr == null)
389                                         return false;
390
391                                 Expr.Emit (ec);
392
393                                 if (ec.InTry || ec.InCatch)
394                                         ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
395                         }
396
397                         if (ec.InTry || ec.InCatch){
398                                 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
399                                 return false; 
400                         } else {
401                                 ec.ig.Emit (OpCodes.Ret);
402                                 return true;
403                         }
404                 }
405         }
406
407         public class Goto : Statement {
408                 string target;
409                 Location loc;
410                 Block block;
411                 
412                 public Goto (Block parent_block, string label, Location l)
413                 {
414                         block = parent_block;
415                         loc = l;
416                         target = label;
417                 }
418
419                 public string Target {
420                         get {
421                                 return target;
422                         }
423                 }
424
425                 public override bool Emit (EmitContext ec)
426                 {
427                         LabeledStatement label = block.LookupLabel (target);
428
429                         if (label == null){
430                                 //
431                                 // Maybe we should catch this before?
432                                 //
433                                 Report.Error (
434                                         159, loc,
435                                         "No such label `" + target + "' in this scope");
436                                 return false;
437                         }
438                         Label l = label.LabelTarget (ec);
439                         ec.ig.Emit (OpCodes.Br, l);
440                         
441                         return false;
442                 }
443         }
444
445         public class LabeledStatement : Statement {
446                 string label_name;
447                 bool defined;
448                 Label label;
449                 
450                 public LabeledStatement (string label_name)
451                 {
452                         this.label_name = label_name;
453                 }
454
455                 public Label LabelTarget (EmitContext ec)
456                 {
457                         if (defined)
458                                 return label;
459                         label = ec.ig.DefineLabel ();
460                         defined = true;
461
462                         return label;
463                 }
464                 
465                 public override bool Emit (EmitContext ec)
466                 {
467                         LabelTarget (ec);
468                         ec.ig.MarkLabel (label);
469
470                         return false;
471                 }
472         }
473         
474
475         /// <summary>
476         ///   `goto default' statement
477         /// </summary>
478         public class GotoDefault : Statement {
479                 Location loc;
480                 
481                 public GotoDefault (Location l)
482                 {
483                         loc = l;
484                 }
485
486                 public override bool Emit (EmitContext ec)
487                 {
488                         if (ec.Switch == null){
489                                 Report.Error (153, loc, "goto default is only valid in a switch statement");
490                                 return false;
491                         }
492
493                         if (!ec.Switch.GotDefault){
494                                 Report.Error (159, loc, "No default target on switch statement");
495                                 return false;
496                         }
497                         ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
498                         return false;
499                 }
500         }
501
502         /// <summary>
503         ///   `goto case' statement
504         /// </summary>
505         public class GotoCase : Statement {
506                 Location loc;
507                 Expression expr;
508                 
509                 public GotoCase (Expression e, Location l)
510                 {
511                         expr = e;
512                         loc = l;
513                 }
514
515                 public override bool Emit (EmitContext ec)
516                 {
517                         if (ec.Switch == null){
518                                 Report.Error (153, loc, "goto case is only valid in a switch statement");
519                                 return false;
520                         }
521
522                         expr = expr.Resolve (ec);
523                         if (expr == null)
524                                 return false;
525
526                         if (!(expr is Constant)){
527                                 Report.Error (159, loc, "Target expression for goto case is not constant");
528                                 return false;
529                         }
530
531                         object val = Expression.ConvertIntLiteral (
532                                 (Constant) expr, ec.Switch.SwitchType, loc);
533
534                         if (val == null)
535                                 return false;
536                                         
537                         SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
538
539                         if (sl == null){
540                                 Report.Error (
541                                         159, loc,
542                                         "No such label 'case " + val + "': for the goto case");
543                         }
544
545                         ec.ig.Emit (OpCodes.Br, sl.ILLabel);
546                         return false;
547                 }
548         }
549         
550         public class Throw : Statement {
551                 public readonly Expression Expr;
552                 Location loc;
553                 
554                 public Throw (Expression expr, Location l)
555                 {
556                         Expr = expr;
557                         loc = l;
558                 }
559
560                 public override bool Emit (EmitContext ec)
561                 {
562                         if (Expr == null){
563                                 if (ec.InCatch)
564                                         ec.ig.Emit (OpCodes.Rethrow);
565                                 else {
566                                         Report.Error (
567                                                 156, loc,
568                                                 "A throw statement with no argument is only " +
569                                                 "allowed in a catch clause");
570                                 }
571                                 return false;
572                         }
573                         
574                         Expression e = Expr.Resolve (ec);
575
576                         if (e == null)
577                                 return false;
578                         
579                         e.Emit (ec);
580
581                         ec.ig.Emit (OpCodes.Throw);
582
583                         return true;
584                 }
585         }
586
587         public class Break : Statement {
588                 Location loc;
589                 
590                 public Break (Location l)
591                 {
592                         loc = l;
593                 }
594
595                 public override bool Emit (EmitContext ec)
596                 {
597                         ILGenerator ig = ec.ig;
598
599                         if (ec.InLoop == false && ec.Switch == null){
600                                 Report.Error (139, loc, "No enclosing loop or switch to continue to");
601                                 return false;
602                         }
603                         
604                         ig.Emit (OpCodes.Br, ec.LoopEnd);
605                         return false;
606                 }
607         }
608
609         public class Continue : Statement {
610                 Location loc;
611                 
612                 public Continue (Location l)
613                 {
614                         loc = l;
615                 }
616
617                 public override bool Emit (EmitContext ec)
618                 {
619                         Label begin = ec.LoopBegin;
620                         
621                         if (!ec.InLoop){
622                                 Report.Error (139, loc, "No enclosing loop to continue to");
623                                 return false;
624                         } 
625
626                         //
627                         // UGH: Non trivial.  This Br might cross a try/catch boundary
628                         // How can we tell?
629                         //
630                         // while () {
631                         //   try { ... } catch { continue; }
632                         // }
633                         //
634                         // From:
635                         // try {} catch { while () { continue; }}
636                         //
637                         ec.ig.Emit (OpCodes.Br, begin);
638                         return false;
639                 }
640         }
641         
642         public class VariableInfo {
643                 public readonly string Type;
644                 public LocalBuilder LocalBuilder;
645                 public Type VariableType;
646                 public readonly Location Location;
647                 
648                 int  idx;
649                 public bool Used;
650                 public bool Assigned;
651                 public bool ReadOnly;
652                 
653                 public VariableInfo (string type, Location l)
654                 {
655                         Type = type;
656                         LocalBuilder = null;
657                         idx = -1;
658                         Location = l;
659                 }
660
661                 public int Idx {
662                         get {
663                                 if (idx == -1)
664                                         throw new Exception ("Unassigned idx for variable");
665                                 
666                                 return idx;
667                         }
668
669                         set {
670                                 idx = value;
671                         }
672                 }
673
674                 public void MakePinned ()
675                 {
676                         TypeManager.MakePinned (LocalBuilder);
677                 }                               
678         }
679                 
680         /// <summary>
681         ///   Block represents a C# block.
682         /// </summary>
683         ///
684         /// <remarks>
685         ///   This class is used in a number of places: either to represent
686         ///   explicit blocks that the programmer places or implicit blocks.
687         ///
688         ///   Implicit blocks are used as labels or to introduce variable
689         ///   declarations.
690         /// </remarks>
691         public class Block : Statement {
692                 public readonly Block  Parent;
693                 public readonly bool   Implicit;
694
695                 //
696                 // The statements in this block
697                 //
698                 StatementCollection statements;
699
700                 //
701                 // An array of Blocks.  We keep track of children just
702                 // to generate the local variable declarations.
703                 //
704                 // Statements and child statements are handled through the
705                 // statements.
706                 //
707                 ArrayList children;
708                 
709                 //
710                 // Labels.  (label, block) pairs.
711                 //
712                 Hashtable labels;
713
714                 //
715                 // Keeps track of (name, type) pairs
716                 //
717                 Hashtable variables;
718
719                 //
720                 // Keeps track of constants
721                 Hashtable constants;
722
723                 //
724                 // Maps variable names to ILGenerator.LocalBuilders
725                 //
726                 Hashtable local_builders;
727
728                 bool used = false;
729
730                 static int id;
731
732                 int this_id;
733                 
734                 public Block (Block parent)
735                 {
736                         if (parent != null)
737                                 parent.AddChild (this);
738                         
739                         this.Parent = parent;
740                         this.Implicit = false;
741
742                         this_id = id++;
743                 }
744
745                 public Block (Block parent, bool implicit_block)
746                 {
747                         if (parent != null)
748                                 parent.AddChild (this);
749                         
750                         this.Parent = parent;
751                         this.Implicit = true;
752                         this_id = id++;
753                 }
754
755                 public int ID {
756                         get {
757                                 return this_id;
758                         }
759                 }
760                 
761                 void AddChild (Block b)
762                 {
763                         if (children == null)
764                                 children = new ArrayList ();
765                         
766                         children.Add (b);
767                 }
768
769                 /// <summary>
770                 ///   Adds a label to the current block. 
771                 /// </summary>
772                 ///
773                 /// <returns>
774                 ///   false if the name already exists in this block. true
775                 ///   otherwise.
776                 /// </returns>
777                 ///
778                 public bool AddLabel (string name, LabeledStatement target)
779                 {
780                         if (labels == null)
781                                 labels = new Hashtable ();
782                         if (labels.Contains (name))
783                                 return false;
784                         
785                         labels.Add (name, target);
786                         return true;
787                 }
788
789                 public LabeledStatement LookupLabel (string name)
790                 {
791                         if (labels != null){
792                                 if (labels.Contains (name))
793                                         return ((LabeledStatement) labels [name]);
794                         }
795
796                         if (Parent != null)
797                                 return Parent.LookupLabel (name);
798
799                         return null;
800                 }
801
802                 public VariableInfo AddVariable (string type, string name, Parameters pars, Location l)
803                 {
804                         if (variables == null)
805                                 variables = new Hashtable ();
806
807                         if (GetVariableType (name) != null)
808                                 return null;
809
810                         if (pars != null) {
811                                 int idx = 0;
812                                 Parameter p = pars.GetParameterByName (name, out idx);
813                                 if (p != null) 
814                                         return null;
815                         }
816                         
817                         VariableInfo vi = new VariableInfo (type, l);
818
819                         variables.Add (name, vi);
820
821                         // Console.WriteLine ("Adding {0} to {1}", name, ID);
822                         return vi;
823                 }
824
825                 public bool AddConstant (string type, string name, Expression value, Parameters pars, Location l)
826                 {
827                         if (AddVariable (type, name, pars, l) == null)
828                                 return false;
829                         
830                         if (constants == null)
831                                 constants = new Hashtable ();
832
833                         constants.Add (name, value);
834                         return true;
835                 }
836
837                 public Hashtable Variables {
838                         get {
839                                 return variables;
840                         }
841                 }
842
843                 public VariableInfo GetVariableInfo (string name)
844                 {
845                         if (variables != null) {
846                                 object temp;
847                                 temp = variables [name];
848
849                                 if (temp != null){
850                                         return (VariableInfo) temp;
851                                 }
852                         }
853
854                         if (Parent != null)
855                                 return Parent.GetVariableInfo (name);
856
857                         return null;
858                 }
859                 
860                 public string GetVariableType (string name)
861                 {
862                         VariableInfo vi = GetVariableInfo (name);
863
864                         if (vi != null)
865                                 return vi.Type;
866
867                         return null;
868                 }
869
870                 public Expression GetConstantExpression (string name)
871                 {
872                         if (constants != null) {
873                                 object temp;
874                                 temp = constants [name];
875                                 
876                                 if (temp != null)
877                                         return (Expression) temp;
878                         }
879                         
880                         if (Parent != null)
881                                 return Parent.GetConstantExpression (name);
882
883                         return null;
884                 }
885                 
886                 /// <summary>
887                 ///   True if the variable named @name has been defined
888                 ///   in this block
889                 /// </summary>
890                 public bool IsVariableDefined (string name)
891                 {
892                         // Console.WriteLine ("Looking up {0} in {1}", name, ID);
893                         if (variables != null) {
894                                 if (variables.Contains (name))
895                                         return true;
896                         }
897                         
898                         if (Parent != null)
899                                 return Parent.IsVariableDefined (name);
900
901                         return false;
902                 }
903
904                 /// <summary>
905                 ///   True if the variable named @name is a constant
906                 ///  </summary>
907                 public bool IsConstant (string name)
908                 {
909                         Expression e = null;
910                         
911                         e = GetConstantExpression (name);
912                         
913                         return e != null;
914                 }
915                 
916                 /// <summary>
917                 ///   Use to fetch the statement associated with this label
918                 /// </summary>
919                 public Statement this [string name] {
920                         get {
921                                 return (Statement) labels [name];
922                         }
923                 }
924
925                 /// <returns>
926                 ///   A list of labels that were not used within this block
927                 /// </returns>
928                 public string [] GetUnreferenced ()
929                 {
930                         // FIXME: Implement me
931                         return null;
932                 }
933
934                 public StatementCollection Statements {
935                         get {
936                                 if (statements == null)
937                                         statements = new StatementCollection ();
938
939                                 return statements;
940                         }
941                 }
942
943                 public void AddStatement (Statement s)
944                 {
945                         if (statements == null)
946                                 statements = new StatementCollection ();
947
948                         statements.Add (s);
949                         used = true;
950                 }
951
952                 public bool Used {
953                         get {
954                                 return used;
955                         }
956                 }
957
958                 public void Use ()
959                 {
960                         used = true;
961                 }
962                 
963                 /// <summary>
964                 ///   Emits the variable declarations and labels.
965                 /// </summary>
966                 /// <remarks>
967                 ///   tc: is our typecontainer (to resolve type references)
968                 ///   ig: is the code generator:
969                 ///   toplevel: the toplevel block.  This is used for checking 
970                 ///             that no two labels with the same name are used.
971                 /// </remarks>
972                 public int EmitMeta (EmitContext ec, Block toplevel, int count)
973                 {
974                         DeclSpace ds = ec.DeclSpace;
975                         ILGenerator ig = ec.ig;
976                                 
977                         //
978                         // Process this block variables
979                         //
980                         if (variables != null){
981                                 local_builders = new Hashtable ();
982                                 
983                                 foreach (DictionaryEntry de in variables){
984                                         string name = (string) de.Key;
985                                         VariableInfo vi = (VariableInfo) de.Value;
986                                         Type t;
987
988                                         t = RootContext.LookupType (ds, vi.Type, false, vi.Location);
989                                         if (t == null)
990                                                 continue;
991
992                                         vi.VariableType = t;
993                                         vi.LocalBuilder = ig.DeclareLocal (t);
994                                         vi.Idx = count++;
995
996                                         if (constants == null)
997                                                 continue;
998
999                                         Expression cv = (Expression) constants [name];
1000                                         if (cv == null)
1001                                                 continue;
1002
1003                                         Expression e = cv.Resolve (ec);
1004                                         if (e == null)
1005                                                 continue;
1006
1007                                         if (!(e is Constant)){
1008                                                 Report.Error (133, vi.Location,
1009                                                               "The expression being assigned to `" +
1010                                                               name + "' must be constant (" + e + ")");
1011                                                 continue;
1012                                         }
1013
1014                                         constants.Remove (name);
1015                                         constants.Add (name, e);
1016                                 }
1017                         }
1018
1019                         //
1020                         // Now, handle the children
1021                         //
1022                         if (children != null){
1023                                 foreach (Block b in children)
1024                                         count = b.EmitMeta (ec, toplevel, count);
1025                         }
1026
1027                         return count;
1028                 }
1029
1030                 public void UsageWarning ()
1031                 {
1032                         string name;
1033                         
1034                         if (variables != null){
1035                                 foreach (DictionaryEntry de in variables){
1036                                         VariableInfo vi = (VariableInfo) de.Value;
1037                                         
1038                                         if (vi.Used)
1039                                                 continue;
1040                                         
1041                                         name = (string) de.Key;
1042                                                 
1043                                         if (vi.Assigned){
1044                                                 Report.Warning (
1045                                                         219, vi.Location, "The variable `" + name +
1046                                                         "' is assigned but its value is never used");
1047                                         } else {
1048                                                 Report.Warning (
1049                                                         168, vi.Location, "The variable `" +
1050                                                         name +
1051                                                         "' is declared but never used");
1052                                         } 
1053                                 }
1054                         }
1055
1056                         if (children != null)
1057                                 foreach (Block b in children)
1058                                         b.UsageWarning ();
1059                 }
1060
1061 //              static int count;
1062                 
1063                 public override bool Emit (EmitContext ec)
1064                 {
1065                         bool is_ret = false;
1066                         Block prev_block = ec.CurrentBlock;
1067
1068 //                      count++;
1069                         ec.CurrentBlock = this;
1070 //                      if (count == 40)
1071 //                              throw new Exception ();
1072                         foreach (Statement s in Statements)
1073                                 is_ret = s.Emit (ec);
1074 //                      count--;
1075                         
1076                         ec.CurrentBlock = prev_block;
1077                         return is_ret;
1078                 }
1079         }
1080
1081         public class SwitchLabel {
1082                 Expression label;
1083                 object converted;
1084                 public Location loc;
1085                 public Label ILLabel;
1086                 
1087                 //
1088                 // if expr == null, then it is the default case.
1089                 //
1090                 public SwitchLabel (Expression expr, Location l)
1091                 {
1092                         label = expr;
1093                         loc = l;
1094                 }
1095
1096                 public Expression Label {
1097                         get {
1098                                 return label;
1099                         }
1100                 }
1101
1102                 public object Converted {
1103                         get {
1104                                 return converted;
1105                         }
1106                 }
1107                 
1108                 //
1109                 // Resolves the expression, reduces it to a literal if possible
1110                 // and then converts it to the requested type.
1111                 //
1112                 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1113                 {
1114                         ILLabel = ec.ig.DefineLabel ();
1115
1116                         if (label == null)
1117                                 return true;
1118                         
1119                         Expression e = label.Resolve (ec);
1120
1121                         if (e == null)
1122                                 return false;
1123
1124                         if (!(e is Constant)){
1125                                 Console.WriteLine ("Value is: " + label);
1126                                 Report.Error (150, loc, "A constant value is expected");
1127                                 return false;
1128                         }
1129
1130                         if (e is StringConstant || e is NullLiteral){
1131                                 if (required_type == TypeManager.string_type){
1132                                         converted = label;
1133                                         ILLabel = ec.ig.DefineLabel ();
1134                                         return true;
1135                                 }
1136                         }
1137
1138                         converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1139                         if (converted == null)
1140                                 return false;
1141
1142                         return true;
1143                 }
1144         }
1145
1146         public class SwitchSection {
1147                 // An array of SwitchLabels.
1148                 public readonly ArrayList Labels;
1149                 public readonly Block Block;
1150                 
1151                 public SwitchSection (ArrayList labels, Block block)
1152                 {
1153                         Labels = labels;
1154                         Block = block;
1155                 }
1156         }
1157         
1158         public class Switch : Statement {
1159                 public readonly ArrayList Sections;
1160                 public Expression Expr;
1161
1162                 /// <summary>
1163                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
1164                 /// </summary>
1165                 public Hashtable Elements;
1166
1167                 /// <summary>
1168                 ///   The governing switch type
1169                 /// </summary>
1170                 public Type SwitchType;
1171
1172                 //
1173                 // Computed
1174                 //
1175                 bool got_default;
1176                 Label default_target;
1177                 Location loc;
1178                 
1179                 //
1180                 // The types allowed to be implicitly cast from
1181                 // on the governing type
1182                 //
1183                 static Type [] allowed_types;
1184                 
1185                 public Switch (Expression e, ArrayList sects, Location l)
1186                 {
1187                         Expr = e;
1188                         Sections = sects;
1189                         loc = l;
1190                 }
1191
1192                 public bool GotDefault {
1193                         get {
1194                                 return got_default;
1195                         }
1196                 }
1197
1198                 public Label DefaultTarget {
1199                         get {
1200                                 return default_target;
1201                         }
1202                 }
1203
1204                 //
1205                 // Determines the governing type for a switch.  The returned
1206                 // expression might be the expression from the switch, or an
1207                 // expression that includes any potential conversions to the
1208                 // integral types or to string.
1209                 //
1210                 Expression SwitchGoverningType (EmitContext ec, Type t)
1211                 {
1212                         if (t == TypeManager.int32_type ||
1213                             t == TypeManager.uint32_type ||
1214                             t == TypeManager.char_type ||
1215                             t == TypeManager.byte_type ||
1216                             t == TypeManager.sbyte_type ||
1217                             t == TypeManager.ushort_type ||
1218                             t == TypeManager.short_type ||
1219                             t == TypeManager.uint64_type ||
1220                             t == TypeManager.int64_type ||
1221                             t == TypeManager.string_type ||
1222                             t.IsSubclassOf (TypeManager.enum_type))
1223                                 return Expr;
1224
1225                         if (allowed_types == null){
1226                                 allowed_types = new Type [] {
1227                                         TypeManager.sbyte_type,
1228                                         TypeManager.byte_type,
1229                                         TypeManager.short_type,
1230                                         TypeManager.ushort_type,
1231                                         TypeManager.int32_type,
1232                                         TypeManager.uint32_type,
1233                                         TypeManager.int64_type,
1234                                         TypeManager.uint64_type,
1235                                         TypeManager.char_type,
1236                                         TypeManager.string_type
1237                                 };
1238                         }
1239
1240                         //
1241                         // Try to find a *user* defined implicit conversion.
1242                         //
1243                         // If there is no implicit conversion, or if there are multiple
1244                         // conversions, we have to report an error
1245                         //
1246                         Expression converted = null;
1247                         foreach (Type tt in allowed_types){
1248                                 Expression e;
1249                                 
1250                                 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
1251                                 if (e == null)
1252                                         continue;
1253
1254                                 if (converted != null){
1255                                         Report.Error (-12, loc, "More than one conversion to an integral " +
1256                                                       " type exists for type `" +
1257                                                       TypeManager.CSharpName (Expr.Type)+"'");
1258                                         return null;
1259                                 } else
1260                                         converted = e;
1261                         }
1262                         return converted;
1263                 }
1264
1265                 void error152 (string n)
1266                 {
1267                         Report.Error (
1268                                 152, "The label `" + n + ":' " +
1269                                 "is already present on this switch statement");
1270                 }
1271                 
1272                 //
1273                 // Performs the basic sanity checks on the switch statement
1274                 // (looks for duplicate keys and non-constant expressions).
1275                 //
1276                 // It also returns a hashtable with the keys that we will later
1277                 // use to compute the switch tables
1278                 //
1279                 bool CheckSwitch (EmitContext ec)
1280                 {
1281                         Type compare_type;
1282                         bool error = false;
1283                         Elements = new Hashtable ();
1284                                 
1285                         got_default = false;
1286
1287                         if (TypeManager.IsEnumType (SwitchType)){
1288                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
1289                         } else
1290                                 compare_type = SwitchType;
1291                         
1292                         foreach (SwitchSection ss in Sections){
1293                                 foreach (SwitchLabel sl in ss.Labels){
1294                                         if (!sl.ResolveAndReduce (ec, SwitchType)){
1295                                                 error = true;
1296                                                 continue;
1297                                         }
1298
1299                                         if (sl.Label == null){
1300                                                 if (got_default){
1301                                                         error152 ("default");
1302                                                         error = true;
1303                                                 }
1304                                                 got_default = true;
1305                                                 continue;
1306                                         }
1307                                         
1308                                         object key = sl.Converted;
1309
1310                                         if (key is Constant)
1311                                                 key = ((Constant) key).GetValue ();
1312
1313                                         if (key == null)
1314                                                 key = NullLiteral.Null;
1315                                         
1316                                         string lname = null;
1317                                         if (compare_type == TypeManager.uint64_type){
1318                                                 ulong v = (ulong) key;
1319
1320                                                 if (Elements.Contains (v))
1321                                                         lname = v.ToString ();
1322                                                 else
1323                                                         Elements.Add (v, sl);
1324                                         } else if (compare_type == TypeManager.int64_type){
1325                                                 long v = (long) key;
1326
1327                                                 if (Elements.Contains (v))
1328                                                         lname = v.ToString ();
1329                                                 else
1330                                                         Elements.Add (v, sl);
1331                                         } else if (compare_type == TypeManager.uint32_type){
1332                                                 uint v = (uint) key;
1333
1334                                                 if (Elements.Contains (v))
1335                                                         lname = v.ToString ();
1336                                                 else
1337                                                         Elements.Add (v, sl);
1338                                         } else if (compare_type == TypeManager.char_type){
1339                                                 char v = (char) key;
1340                                                 
1341                                                 if (Elements.Contains (v))
1342                                                         lname = v.ToString ();
1343                                                 else
1344                                                         Elements.Add (v, sl);
1345                                         } else if (compare_type == TypeManager.byte_type){
1346                                                 byte v = (byte) key;
1347                                                 
1348                                                 if (Elements.Contains (v))
1349                                                         lname = v.ToString ();
1350                                                 else
1351                                                         Elements.Add (v, sl);
1352                                         } else if (compare_type == TypeManager.sbyte_type){
1353                                                 sbyte v = (sbyte) key;
1354                                                 
1355                                                 if (Elements.Contains (v))
1356                                                         lname = v.ToString ();
1357                                                 else
1358                                                         Elements.Add (v, sl);
1359                                         } else if (compare_type == TypeManager.short_type){
1360                                                 short v = (short) key;
1361                                                 
1362                                                 if (Elements.Contains (v))
1363                                                         lname = v.ToString ();
1364                                                 else
1365                                                         Elements.Add (v, sl);
1366                                         } else if (compare_type == TypeManager.ushort_type){
1367                                                 ushort v = (ushort) key;
1368                                                 
1369                                                 if (Elements.Contains (v))
1370                                                         lname = v.ToString ();
1371                                                 else
1372                                                         Elements.Add (v, sl);
1373                                         } else if (compare_type == TypeManager.string_type){
1374                                                 if (key is NullLiteral){
1375                                                         if (Elements.Contains (NullLiteral.Null))
1376                                                                 lname = "null";
1377                                                         else
1378                                                                 Elements.Add (NullLiteral.Null, null);
1379                                                 } else {
1380                                                         string s = (string) key;
1381
1382                                                         if (Elements.Contains (s))
1383                                                                 lname = s;
1384                                                         else
1385                                                                 Elements.Add (s, sl);
1386                                                 }
1387                                         } else if (compare_type == TypeManager.int32_type) {
1388                                                 int v = (int) key;
1389
1390                                                 if (Elements.Contains (v))
1391                                                         lname = v.ToString ();
1392                                                 else
1393                                                         Elements.Add (v, sl);
1394                                         } else {
1395                                                 throw new Exception ("Unknown switch type!" +
1396                                                                      SwitchType + " " + compare_type);
1397                                         }
1398
1399                                         if (lname != null){
1400                                                 error152 ("case + " + lname);
1401                                                 error = true;
1402                                         }
1403                                 }
1404                         }
1405                         if (error)
1406                                 return false;
1407                         
1408                         return true;
1409                 }
1410
1411                 void EmitObjectInteger (ILGenerator ig, object k)
1412                 {
1413                         if (k is int)
1414                                 IntConstant.EmitInt (ig, (int) k);
1415                         else if (k is Constant){
1416                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
1417                         } else if (k is uint)
1418                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
1419                         else if (k is long)
1420                                 LongConstant.EmitLong (ig, (long) k);
1421                         else if (k is ulong)
1422                                 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
1423                         else if (k is char)
1424                                 IntConstant.EmitInt (ig, (int) ((char) k));
1425                         else if (k is sbyte)
1426                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
1427                         else if (k is byte)
1428                                 IntConstant.EmitInt (ig, (int) ((byte) k));
1429                         else 
1430                                 throw new Exception ("Unhandled case");
1431                 }
1432                 
1433                 //
1434                 // This simple emit switch works, but does not take advantage of the
1435                 // `switch' opcode.  The swithc opcode uses a jump table that we are not
1436                 // computing at this point
1437                 //
1438                 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
1439                 {
1440                         ILGenerator ig = ec.ig;
1441                         Label end_of_switch = ig.DefineLabel ();
1442                         Label next_test = ig.DefineLabel ();
1443                         Label null_target = ig.DefineLabel ();
1444                         bool default_found = false;
1445                         bool first_test = true;
1446                         bool pending_goto_end = false;
1447                         bool all_return = true;
1448                         bool is_string = false;
1449                         bool null_found;
1450                         
1451                         //
1452                         // Special processing for strings: we cant compare
1453                         // against null.
1454                         //
1455                         if (SwitchType == TypeManager.string_type){
1456                                 ig.Emit (OpCodes.Ldloc, val);
1457                                 is_string = true;
1458                                 
1459                                 if (Elements.Contains (NullLiteral.Null)){
1460                                         ig.Emit (OpCodes.Brfalse, null_target);
1461                                 } else
1462                                         ig.Emit (OpCodes.Brfalse, default_target);
1463
1464                                 ig.Emit (OpCodes.Ldloc, val);
1465                                 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
1466                                 ig.Emit (OpCodes.Stloc, val);
1467                         }
1468                         
1469                         foreach (SwitchSection ss in Sections){
1470                                 Label sec_begin = ig.DefineLabel ();
1471
1472                                 if (pending_goto_end)
1473                                         ig.Emit (OpCodes.Br, end_of_switch);
1474
1475                                 int label_count = ss.Labels.Count;
1476                                 null_found = false;
1477                                 foreach (SwitchLabel sl in ss.Labels){
1478                                         ig.MarkLabel (sl.ILLabel);
1479                                         
1480                                         if (!first_test){
1481                                                 ig.MarkLabel (next_test);
1482                                                 next_test = ig.DefineLabel ();
1483                                         }
1484                                         //
1485                                         // If we are the default target
1486                                         //
1487                                         if (sl.Label == null){
1488                                                 ig.MarkLabel (default_target);
1489                                                 default_found = true;
1490                                         } else {
1491                                                 object lit = sl.Converted;
1492
1493                                                 if (lit is NullLiteral){
1494                                                         null_found = true;
1495                                                         if (label_count == 1)
1496                                                                 ig.Emit (OpCodes.Br, next_test);
1497                                                         continue;
1498                                                                               
1499                                                 }
1500                                                 if (is_string){
1501                                                         StringConstant str = (StringConstant) lit;
1502
1503                                                         ig.Emit (OpCodes.Ldloc, val);
1504                                                         ig.Emit (OpCodes.Ldstr, str.Value);
1505                                                         if (label_count == 1)
1506                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
1507                                                         else
1508                                                                 ig.Emit (OpCodes.Beq, sec_begin);
1509                                                 } else {
1510                                                         ig.Emit (OpCodes.Ldloc, val);
1511                                                         EmitObjectInteger (ig, lit);
1512                                                         ig.Emit (OpCodes.Ceq);
1513                                                         if (label_count == 1)
1514                                                                 ig.Emit (OpCodes.Brfalse, next_test);
1515                                                         else
1516                                                                 ig.Emit (OpCodes.Brtrue, sec_begin);
1517                                                 }
1518                                         }
1519                                 }
1520                                 if (label_count != 1)
1521                                         ig.Emit (OpCodes.Br, next_test);
1522                                 
1523                                 if (null_found)
1524                                         ig.MarkLabel (null_target);
1525                                 ig.MarkLabel (sec_begin);
1526                                 if (ss.Block.Emit (ec))
1527                                         pending_goto_end = false;
1528                                 else {
1529                                         all_return = false;
1530                                         pending_goto_end = true;
1531                                 }
1532                                 first_test = false;
1533                         }
1534                         if (!default_found)
1535                                 ig.MarkLabel (default_target);
1536                         ig.MarkLabel (next_test);
1537                         ig.MarkLabel (end_of_switch);
1538                         
1539                         return all_return;
1540                 }
1541                 
1542                 public override bool Emit (EmitContext ec)
1543                 {
1544                         Expr = Expr.Resolve (ec);
1545                         if (Expr == null)
1546                                 return false;
1547
1548                         Expression new_expr = SwitchGoverningType (ec, Expr.Type);
1549                         if (new_expr == null){
1550                                 Report.Error (151, loc, "An integer type or string was expected for switch");
1551                                 return false;
1552                         }
1553
1554                         // Validate switch.
1555                         SwitchType = new_expr.Type;
1556
1557                         if (!CheckSwitch (ec))
1558                                 return false;
1559
1560                         // Store variable for comparission purposes
1561                         LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
1562                         new_expr.Emit (ec);
1563                         ec.ig.Emit (OpCodes.Stloc, value);
1564
1565                         ILGenerator ig = ec.ig;
1566
1567                         default_target = ig.DefineLabel ();
1568
1569                         //
1570                         // Setup the codegen context
1571                         //
1572                         Label old_end = ec.LoopEnd;
1573                         Switch old_switch = ec.Switch;
1574                         
1575                         ec.LoopEnd = ig.DefineLabel ();
1576                         ec.Switch = this;
1577
1578                         // Emit Code.
1579                         bool all_return =  SimpleSwitchEmit (ec, value);
1580
1581                         // Restore context state. 
1582                         ig.MarkLabel (ec.LoopEnd);
1583
1584                         //
1585                         // FIXME: I am emitting a nop, because the switch performs
1586                         // no analysis on whether something ever reaches the end
1587                         //
1588                         // try: b (int a) { switch (a) { default: return 0; }  }
1589                         ig.Emit (OpCodes.Nop);
1590
1591                         //
1592                         // Restore the previous context
1593                         //
1594                         ec.LoopEnd = old_end;
1595                         ec.Switch = old_switch;
1596                         
1597                         //
1598                         // Because we have a nop at the end
1599                         //
1600                         return false;
1601                 }
1602         }
1603
1604         public class Lock : Statement {
1605                 public readonly Expression Expr;
1606                 public readonly Statement Statement;
1607                 Location loc;
1608                         
1609                 public Lock (Expression expr, Statement stmt, Location l)
1610                 {
1611                         Expr = expr;
1612                         Statement = stmt;
1613                         loc = l;
1614                 }
1615
1616                 public override bool Emit (EmitContext ec)
1617                 {
1618                         Expression e = Expr.Resolve (ec);
1619                         if (e == null)
1620                                 return false;
1621
1622                         Type type = e.Type;
1623                         
1624                         if (type.IsValueType){
1625                                 Report.Error (185, loc, "lock statement requires the expression to be " +
1626                                               " a reference type (type is: `" +
1627                                               TypeManager.CSharpName (type) + "'");
1628                                 return false;
1629                         }
1630
1631                         ILGenerator ig = ec.ig;
1632                         LocalBuilder temp = ig.DeclareLocal (type);
1633                                 
1634                         e.Emit (ec);
1635                         ig.Emit (OpCodes.Dup);
1636                         ig.Emit (OpCodes.Stloc, temp);
1637                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
1638
1639                         // try
1640                         Label end = ig.BeginExceptionBlock ();
1641                         bool old_in_try = ec.InTry;
1642                         ec.InTry = true;
1643                         Label finish = ig.DefineLabel ();
1644                         Statement.Emit (ec);
1645                         ec.InTry = old_in_try;
1646                         // ig.Emit (OpCodes.Leave, finish);
1647
1648                         ig.MarkLabel (finish);
1649                         
1650                         // finally
1651                         ig.BeginFinallyBlock ();
1652                         ig.Emit (OpCodes.Ldloc, temp);
1653                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
1654                         ig.EndExceptionBlock ();
1655                         
1656                         return false;
1657                 }
1658         }
1659
1660         public class Unchecked : Statement {
1661                 public readonly Block Block;
1662                 
1663                 public Unchecked (Block b)
1664                 {
1665                         Block = b;
1666                 }
1667
1668                 public override bool Emit (EmitContext ec)
1669                 {
1670                         bool previous_state = ec.CheckState;
1671                         bool previous_state_const = ec.ConstantCheckState;
1672                         bool val;
1673                         
1674                         ec.CheckState = false;
1675                         ec.ConstantCheckState = false;
1676                         val = Block.Emit (ec);
1677                         ec.CheckState = previous_state;
1678                         ec.ConstantCheckState = previous_state_const;
1679
1680                         return val;
1681                 }
1682         }
1683
1684         public class Checked : Statement {
1685                 public readonly Block Block;
1686                 
1687                 public Checked (Block b)
1688                 {
1689                         Block = b;
1690                 }
1691
1692                 public override bool Emit (EmitContext ec)
1693                 {
1694                         bool previous_state = ec.CheckState;
1695                         bool previous_state_const = ec.ConstantCheckState;
1696                         bool val;
1697                         
1698                         ec.CheckState = true;
1699                         ec.ConstantCheckState = true;
1700                         val = Block.Emit (ec);
1701                         ec.CheckState = previous_state;
1702                         ec.ConstantCheckState = previous_state_const;
1703
1704                         return val;
1705                 }
1706         }
1707
1708         public class Unsafe : Statement {
1709                 public readonly Block Block;
1710
1711                 public Unsafe (Block b)
1712                 {
1713                         Block = b;
1714                 }
1715
1716                 public override bool Emit (EmitContext ec)
1717                 {
1718                         bool previous_state = ec.InUnsafe;
1719                         bool val;
1720                         
1721                         ec.InUnsafe = true;
1722                         val = Block.Emit (ec);
1723                         ec.InUnsafe = previous_state;
1724
1725                         return val;
1726                 }
1727         }
1728
1729         // 
1730         // Fixed statement
1731         //
1732         public class Fixed : Statement {
1733                 string    type;
1734                 ArrayList declarators;
1735                 Statement statement;
1736                 Location  loc;
1737
1738                 public Fixed (string type, ArrayList decls, Statement stmt, Location l)
1739                 {
1740                         this.type = type;
1741                         declarators = decls;
1742                         statement = stmt;
1743                         loc = l;
1744                 }
1745
1746                 public override bool Emit (EmitContext ec)
1747                 {
1748                         ILGenerator ig = ec.ig;
1749                         Type t;
1750                         
1751                         t = RootContext.LookupType (ec.DeclSpace, type, false, loc);
1752                         if (t == null)
1753                                 return false;
1754
1755                         foreach (Pair p in declarators){
1756                                 VariableInfo vi = (VariableInfo) p.First;
1757                                 Expression e = (Expression) p.Second;
1758
1759                                 //
1760                                 // The rules for the possible declarators are pretty wise,
1761                                 // but the production on the grammar is more concise.
1762                                 //
1763                                 // So we have to enforce these rules here.
1764                                 //
1765                                 // We do not resolve before doing the case 1 test,
1766                                 // because the grammar is explicit in that the token &
1767                                 // is present, so we need to test for this particular case.
1768                                 //
1769
1770                                 //
1771                                 // Case 1: & object.
1772                                 //
1773                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
1774                                         Expression child = ((Unary) e).Expr;
1775
1776                                         vi.MakePinned ();
1777                                         if (child is ParameterReference || child is LocalVariableReference){
1778                                                 Report.Error (
1779                                                         213, loc, 
1780                                                         "No need to use fixed statement for parameters or " +
1781                                                         "local variable declarations (address is already " +
1782                                                         "fixed)");
1783                                                 continue;
1784                                         }
1785                                         
1786                                         e = e.Resolve (ec);
1787                                         if (e == null)
1788                                                 continue;
1789
1790                                         child = ((Unary) e).Expr;
1791                                         
1792                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
1793                                                 continue;
1794
1795                                         //
1796                                         // Store pointer in pinned location
1797                                         //
1798                                         e.Emit (ec);
1799                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1800
1801                                         statement.Emit (ec);
1802
1803                                         // Clear the pinned variable.
1804                                         ig.Emit (OpCodes.Ldc_I4_0);
1805                                         ig.Emit (OpCodes.Conv_U);
1806                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1807
1808                                         continue;
1809                                 }
1810
1811                                 e = e.Resolve (ec);
1812                                 if (e == null)
1813                                         continue;
1814
1815                                 //
1816                                 // Case 2: Array
1817                                 //
1818                                 if (e.Type.IsArray){
1819                                         Type array_type = e.Type.GetElementType ();
1820                                         
1821                                         vi.MakePinned ();
1822                                         //
1823                                         // Provided that array_type is unmanaged,
1824                                         //
1825                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
1826                                                 continue;
1827
1828                                         //
1829                                         // and T* is implicitly convertible to the
1830                                         // pointer type given in the fixed statement.
1831                                         //
1832                                         ArrayPtr array_ptr = new ArrayPtr (e);
1833                                         
1834                                         Expression converted = Expression.ConvertImplicitRequired (
1835                                                 ec, array_ptr, vi.VariableType, loc);
1836                                         if (converted == null)
1837                                                 continue;
1838
1839                                         //
1840                                         // Store pointer in pinned location
1841                                         //
1842                                         converted.Emit (ec);
1843                                         
1844                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1845
1846                                         statement.Emit (ec);
1847                                         
1848                                         // Clear the pinned variable.
1849                                         ig.Emit (OpCodes.Ldc_I4_0);
1850                                         ig.Emit (OpCodes.Conv_U);
1851                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1852
1853                                         continue;
1854                                 }
1855
1856                                 //
1857                                 // Case 3: string
1858                                 //
1859                                 if (e.Type == TypeManager.string_type){
1860                                         LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
1861                                         TypeManager.MakePinned (pinned_string);
1862                                         
1863                                         e.Emit (ec);
1864                                         ig.Emit (OpCodes.Stloc, pinned_string);
1865
1866                                         Expression sptr = new StringPtr (pinned_string);
1867                                         Expression converted = Expression.ConvertImplicitRequired (
1868                                                 ec, sptr, vi.VariableType, loc);
1869                                         
1870                                         if (converted == null)
1871                                                 continue;
1872
1873                                         converted.Emit (ec);
1874                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1875                                         
1876                                         statement.Emit (ec);
1877
1878                                         // Clear the pinned variable
1879                                         ig.Emit (OpCodes.Ldnull);
1880                                         ig.Emit (OpCodes.Stloc, pinned_string);
1881                                 }
1882                         }
1883
1884                         return false;
1885                 }
1886         }
1887         
1888         public class Catch {
1889                 public readonly string Type;
1890                 public readonly string Name;
1891                 public readonly Block  Block;
1892                 public readonly Location Location;
1893                 
1894                 public Catch (string type, string name, Block block, Location l)
1895                 {
1896                         Type = type;
1897                         Name = name;
1898                         Block = block;
1899                         Location = l;
1900                 }
1901         }
1902
1903         public class Try : Statement {
1904                 public readonly Block Fini, Block;
1905                 public readonly ArrayList Specific;
1906                 public readonly Catch General;
1907                 
1908                 //
1909                 // specific, general and fini might all be null.
1910                 //
1911                 public Try (Block block, ArrayList specific, Catch general, Block fini)
1912                 {
1913                         if (specific == null && general == null){
1914                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
1915                         }
1916                         
1917                         this.Block = block;
1918                         this.Specific = specific;
1919                         this.General = general;
1920                         this.Fini = fini;
1921                 }
1922
1923                 public override bool Emit (EmitContext ec)
1924                 {
1925                         ILGenerator ig = ec.ig;
1926                         Label end;
1927                         Label finish = ig.DefineLabel ();;
1928                         bool returns;
1929                         
1930                         end = ig.BeginExceptionBlock ();
1931                         bool old_in_try = ec.InTry;
1932                         ec.InTry = true;
1933                         returns = Block.Emit (ec);
1934                         ec.InTry = old_in_try;
1935
1936                         //
1937                         // System.Reflection.Emit provides this automatically:
1938                         // ig.Emit (OpCodes.Leave, finish);
1939
1940                         bool old_in_catch = ec.InCatch;
1941                         ec.InCatch = true;
1942                         DeclSpace ds = ec.DeclSpace;
1943                         
1944                         foreach (Catch c in Specific){
1945                                 Type catch_type = RootContext.LookupType (ds, c.Type, false, c.Location);
1946                                 VariableInfo vi;
1947                                 
1948                                 if (catch_type == null)
1949                                         return false;
1950
1951                                 ig.BeginCatchBlock (catch_type);
1952
1953                                 if (c.Name != null){
1954                                         vi = c.Block.GetVariableInfo (c.Name);
1955                                         if (vi == null){
1956                                                 Console.WriteLine ("This should not happen! variable does not exist in this block");
1957                                                 Environment.Exit (0);
1958                                         }
1959                                 
1960                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1961                                 } else
1962                                         ig.Emit (OpCodes.Pop);
1963                                 
1964                                 c.Block.Emit (ec);
1965                         }
1966
1967                         if (General != null){
1968                                 ig.BeginCatchBlock (TypeManager.object_type);
1969                                 ig.Emit (OpCodes.Pop);
1970                                 General.Block.Emit (ec);
1971                         }
1972                         ec.InCatch = old_in_catch;
1973
1974                         ig.MarkLabel (finish);
1975                         if (Fini != null){
1976                                 ig.BeginFinallyBlock ();
1977                                 bool old_in_finally = ec.InFinally;
1978                                 ec.InFinally = true;
1979                                 Fini.Emit (ec);
1980                                 ec.InFinally = old_in_finally;
1981                         }
1982                         
1983                         ig.EndExceptionBlock ();
1984
1985                         //
1986                         // FIXME: Is this correct?
1987                         // Replace with `returns' and check test-18, maybe we can
1988                         // perform an optimization here.
1989                         //
1990                         return false;
1991                 }
1992         }
1993
1994         //
1995         // FIXME: We still do not support the expression variant of the using
1996         // statement.
1997         //
1998         public class Using : Statement {
1999                 object expression_or_block;
2000                 Statement Statement;
2001                 Location loc;
2002                 
2003                 public Using (object expression_or_block, Statement stmt, Location l)
2004                 {
2005                         this.expression_or_block = expression_or_block;
2006                         Statement = stmt;
2007                         loc = l;
2008                 }
2009
2010                 //
2011                 // Emits the code for the case of using using a local variable declaration.
2012                 //
2013                 bool EmitLocalVariableDecls (EmitContext ec, string type_name, ArrayList var_list)
2014                 {
2015                         ILGenerator ig = ec.ig;
2016                         Expression [] converted_vars;
2017                         bool need_conv = false;
2018                         Type type = RootContext.LookupType (ec.DeclSpace, type_name, false, loc);
2019                         int i = 0;
2020
2021                         if (type == null)
2022                                 return false;
2023                         
2024                         //
2025                         // The type must be an IDisposable or an implicit conversion
2026                         // must exist.
2027                         //
2028                         converted_vars = new Expression [var_list.Count];
2029                         if (!TypeManager.ImplementsInterface (type, TypeManager.idisposable_type)){
2030                                 foreach (DictionaryEntry e in var_list){
2031                                         Expression var = (Expression) e.Key;
2032
2033                                         var = var.Resolve (ec);
2034                                         if (var == null)
2035                                                 return false;
2036                                         
2037                                         converted_vars [i] = Expression.ConvertImplicit (
2038                                                 ec, var, TypeManager.idisposable_type, loc);
2039
2040                                         if (converted_vars [i] == null)
2041                                                 return false;
2042                                         i++;
2043                                 }
2044                                 need_conv = true;
2045                         }
2046                         
2047                         i = 0;
2048                         bool old_in_try = ec.InTry;
2049                         ec.InTry = true;
2050                         foreach (DictionaryEntry e in var_list){
2051                                 LocalVariableReference var = (LocalVariableReference) e.Key;
2052                                 Expression expr = (Expression) e.Value;
2053                                 Expression a;
2054
2055                                 a = new Assign (var, expr, loc);
2056                                 a.Resolve (ec);
2057                                 if (!need_conv)
2058                                         converted_vars [i] = var;
2059                                 i++;
2060                                 if (a == null)
2061                                         continue;
2062                                 ((ExpressionStatement) a).EmitStatement (ec);
2063                                 
2064                                 ig.BeginExceptionBlock ();
2065
2066                         }
2067                         Statement.Emit (ec);
2068                         ec.InTry = old_in_try;
2069
2070                         bool old_in_finally = ec.InFinally;
2071                         ec.InFinally = true;
2072                         var_list.Reverse ();
2073                         foreach (DictionaryEntry e in var_list){
2074                                 LocalVariableReference var = (LocalVariableReference) e.Key;
2075                                 Label skip = ig.DefineLabel ();
2076                                 i--;
2077                                 
2078                                 ig.BeginFinallyBlock ();
2079                                 
2080                                 var.Emit (ec);
2081                                 ig.Emit (OpCodes.Brfalse, skip);
2082                                 converted_vars [i].Emit (ec);
2083                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
2084                                 ig.MarkLabel (skip);
2085                                 ig.EndExceptionBlock ();
2086                         }
2087                         ec.InFinally = old_in_finally;
2088
2089                         return false;
2090                 }
2091
2092                 bool EmitExpression (EmitContext ec, Expression expr)
2093                 {
2094                         Type expr_type = expr.Type;
2095                         Expression conv = null;
2096                         
2097                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
2098                                 conv = Expression.ConvertImplicit (
2099                                         ec, expr, TypeManager.idisposable_type, loc);
2100
2101                                 if (conv == null)
2102                                         return false;
2103                         }
2104
2105                         //
2106                         // Make a copy of the expression and operate on that.
2107                         //
2108                         ILGenerator ig = ec.ig;
2109                         LocalBuilder local_copy = ig.DeclareLocal (expr_type);
2110                         if (conv != null)
2111                                 conv.Emit (ec);
2112                         else
2113                                 expr.Emit (ec);
2114                         ig.Emit (OpCodes.Stloc, local_copy);
2115
2116                         bool old_in_try = ec.InTry;
2117                         ec.InTry = true;
2118                         ig.BeginExceptionBlock ();
2119                         Statement.Emit (ec);
2120                         ec.InTry = old_in_try;
2121                         
2122                         Label skip = ig.DefineLabel ();
2123                         bool old_in_finally = ec.InFinally;
2124                         ig.BeginFinallyBlock ();
2125                         ig.Emit (OpCodes.Ldloc, local_copy);
2126                         ig.Emit (OpCodes.Brfalse, skip);
2127                         ig.Emit (OpCodes.Ldloc, local_copy);
2128                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
2129                         ig.MarkLabel (skip);
2130                         ec.InFinally = old_in_finally;
2131                         ig.EndExceptionBlock ();
2132
2133                         return false;
2134                 }
2135                 
2136                 public override bool Emit (EmitContext ec)
2137                 {
2138                         if (expression_or_block is DictionaryEntry){
2139                                 string t = (string) ((DictionaryEntry) expression_or_block).Key;
2140                                 ArrayList var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
2141
2142                                 return EmitLocalVariableDecls (ec, t, var_list);
2143                         } if (expression_or_block is Expression){
2144                                 Expression e = (Expression) expression_or_block;
2145
2146                                 e = e.Resolve (ec);
2147                                 if (e == null)
2148                                         return false;
2149
2150                                 return EmitExpression (ec, e);
2151                         }
2152                         return false;
2153                 }
2154         }
2155
2156         /// <summary>
2157         ///   Implementation of the foreach C# statement
2158         /// </summary>
2159         public class Foreach : Statement {
2160                 string type;
2161                 LocalVariableReference variable;
2162                 Expression expr;
2163                 Statement statement;
2164                 Location loc;
2165                 
2166                 public Foreach (string type, LocalVariableReference var, Expression expr,
2167                                 Statement stmt, Location l)
2168                 {
2169                         this.type = type;
2170                         this.variable = var;
2171                         this.expr = expr;
2172                         statement = stmt;
2173                         loc = l;
2174                 }
2175                 
2176                 //
2177                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
2178                 //
2179                 static MethodInfo FetchMethodMoveNext (Type t)
2180                 {
2181                         MemberInfo [] move_next_list;
2182                         
2183                         move_next_list = TypeContainer.FindMembers (
2184                                 t, MemberTypes.Method,
2185                                 BindingFlags.Public | BindingFlags.Instance,
2186                                 Type.FilterName, "MoveNext");
2187                         if (move_next_list == null || move_next_list.Length == 0)
2188                                 return null;
2189
2190                         foreach (MemberInfo m in move_next_list){
2191                                 MethodInfo mi = (MethodInfo) m;
2192                                 Type [] args;
2193                                 
2194                                 args = TypeManager.GetArgumentTypes (mi);
2195                                 if (args != null && args.Length == 0){
2196                                         if (mi.ReturnType == TypeManager.bool_type)
2197                                                 return mi;
2198                                 }
2199                         }
2200                         return null;
2201                 }
2202                 
2203                 //
2204                 // Retrieves a `public T get_Current ()' method from the Type `t'
2205                 //
2206                 static MethodInfo FetchMethodGetCurrent (Type t)
2207                 {
2208                         MemberInfo [] move_next_list;
2209                         
2210                         move_next_list = TypeContainer.FindMembers (
2211                                 t, MemberTypes.Method,
2212                                 BindingFlags.Public | BindingFlags.Instance,
2213                                 Type.FilterName, "get_Current");
2214                         if (move_next_list == null || move_next_list.Length == 0)
2215                                 return null;
2216
2217                         foreach (MemberInfo m in move_next_list){
2218                                 MethodInfo mi = (MethodInfo) m;
2219                                 Type [] args;
2220                                 
2221                                 args = TypeManager.GetArgumentTypes (mi);
2222                                 if (args != null && args.Length == 0)
2223                                         return mi;
2224                         }
2225                         return null;
2226                 }
2227
2228                 // 
2229                 // This struct records the helper methods used by the Foreach construct
2230                 //
2231                 class ForeachHelperMethods {
2232                         public EmitContext ec;
2233                         public MethodInfo get_enumerator;
2234                         public MethodInfo move_next;
2235                         public MethodInfo get_current;
2236
2237                         public ForeachHelperMethods (EmitContext ec)
2238                         {
2239                                 this.ec = ec;
2240                         }
2241                 }
2242                 
2243                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
2244                 {
2245                         if (m == null)
2246                                 return false;
2247                         
2248                         if (!(m is MethodInfo))
2249                                 return false;
2250                         
2251                         if (m.Name != "GetEnumerator")
2252                                 return false;
2253
2254                         MethodInfo mi = (MethodInfo) m;
2255                         Type [] args = TypeManager.GetArgumentTypes (mi);
2256                         if (args != null){
2257                                 if (args.Length != 0)
2258                                         return false;
2259                         }
2260                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
2261                         EmitContext ec = hm.ec;
2262                         
2263                         //
2264                         // Check whether GetEnumerator is accessible to us
2265                         //
2266                         MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
2267
2268                         Type declaring = mi.DeclaringType;
2269                         if (prot == MethodAttributes.Private){
2270                                 if (declaring != ec.ContainerType)
2271                                         return false;
2272                         } else if (prot == MethodAttributes.FamANDAssem){
2273                                 // If from a different assembly, false
2274                                 if (!(mi is MethodBuilder))
2275                                         return false;
2276                                 //
2277                                 // Are we being invoked from the same class, or from a derived method?
2278                                 //
2279                                 if (ec.ContainerType != declaring){
2280                                         if (!ec.ContainerType.IsSubclassOf (declaring))
2281                                                 return false;
2282                                 }
2283                         } else if (prot == MethodAttributes.FamORAssem){
2284                                 if (!(mi is MethodBuilder ||
2285                                       ec.ContainerType == declaring ||
2286                                       ec.ContainerType.IsSubclassOf (declaring)))
2287                                         return false;
2288                         } if (prot == MethodAttributes.Family){
2289                                 if (!(ec.ContainerType == declaring ||
2290                                       ec.ContainerType.IsSubclassOf (declaring)))
2291                                         return false;
2292                         }
2293
2294                         //
2295                         // Ok, we can access it, now make sure that we can do something
2296                         // with this `GetEnumerator'
2297                         //
2298                         if (mi.ReturnType == TypeManager.ienumerator_type || 
2299                             TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType)){
2300                                 hm.move_next = TypeManager.bool_movenext_void;
2301                                 hm.get_current = TypeManager.object_getcurrent_void;
2302                                 return true;
2303                         }
2304
2305                         //
2306                         // Ok, so they dont return an IEnumerable, we will have to
2307                         // find if they support the GetEnumerator pattern.
2308                         //
2309                         Type return_type = mi.ReturnType;
2310
2311                         hm.move_next = FetchMethodMoveNext (return_type);
2312                         if (hm.move_next == null)
2313                                 return false;
2314                         hm.get_current = FetchMethodGetCurrent (return_type);
2315                         if (hm.get_current == null)
2316                                 return false;
2317
2318                         return true;
2319                 }
2320                 
2321                 /// <summary>
2322                 ///   This filter is used to find the GetEnumerator method
2323                 ///   on which IEnumerator operates
2324                 /// </summary>
2325                 static MemberFilter FilterEnumerator;
2326                 
2327                 static Foreach ()
2328                 {
2329                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
2330                 }
2331
2332                 void error1579 (Type t)
2333                 {
2334                         Report.Error (1579, loc,
2335                                       "foreach statement cannot operate on variables of type `" +
2336                                       t.FullName + "' because that class does not provide a " +
2337                                       " GetEnumerator method or it is inaccessible");
2338                 }
2339
2340                 static bool TryType (Type t, ForeachHelperMethods hm)
2341                 {
2342                         MemberInfo [] mi;
2343                         
2344                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
2345                                                         BindingFlags.Public | BindingFlags.NonPublic |
2346                                                         BindingFlags.Instance,
2347                                                         FilterEnumerator, hm);
2348
2349                         if (mi == null || mi.Length == 0)
2350                                 return false;
2351
2352                         hm.get_enumerator = (MethodInfo) mi [0];
2353                         return true;    
2354                 }
2355                 
2356                 //
2357                 // Looks for a usable GetEnumerator in the Type, and if found returns
2358                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
2359                 //
2360                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
2361                 {
2362                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
2363
2364                         if (TryType (t, hm))
2365                                 return hm;
2366
2367                         //
2368                         // Now try to find the method in the interfaces
2369                         //
2370                         while (t != null){
2371                                 Type [] ifaces = t.GetInterfaces ();
2372
2373                                 foreach (Type i in ifaces){
2374                                         if (TryType (i, hm))
2375                                                 return hm;
2376                                 }
2377                                 
2378                                 //
2379                                 // Since TypeBuilder.GetInterfaces only returns the interface
2380                                 // types for this type, we have to keep looping, but once
2381                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
2382                                 // done, because it returns all the types
2383                                 //
2384                                 if ((t is TypeBuilder))
2385                                         t = t.BaseType;
2386                                 else
2387                                         break;
2388                         } 
2389
2390                         return null;
2391                 }
2392
2393                 //
2394                 // FIXME: possible optimization.
2395                 // We might be able to avoid creating `empty' if the type is the sam
2396                 //
2397                 bool EmitCollectionForeach (EmitContext ec, Type var_type, ForeachHelperMethods hm)
2398                 {
2399                         ILGenerator ig = ec.ig;
2400                         LocalBuilder enumerator, disposable;
2401                         Expression empty = new EmptyExpression ();
2402                         Expression conv;
2403
2404                         //
2405                         // FIXME: maybe we can apply the same trick we do in the
2406                         // array handling to avoid creating empty and conv in some cases.
2407                         //
2408                         // Although it is not as important in this case, as the type
2409                         // will not likely be object (what the enumerator will return).
2410                         //
2411                         conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
2412                         if (conv == null)
2413                                 return false;
2414                         
2415                         enumerator = ig.DeclareLocal (TypeManager.ienumerator_type);
2416                         disposable = ig.DeclareLocal (TypeManager.idisposable_type);
2417                         
2418                         //
2419                         // Instantiate the enumerator
2420                         //
2421                         if (expr.Type.IsValueType){
2422                                 if (expr is IMemoryLocation){
2423                                         IMemoryLocation ml = (IMemoryLocation) expr;
2424
2425                                         ml.AddressOf (ec, AddressOp.Load);
2426                                 } else
2427                                         throw new Exception ("Expr " + expr + " of type " + expr.Type +
2428                                                              " does not implement IMemoryLocation");
2429                                 ig.Emit (OpCodes.Call, hm.get_enumerator);
2430                         } else {
2431                                 expr.Emit (ec);
2432                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
2433                         }
2434                         ig.Emit (OpCodes.Stloc, enumerator);
2435
2436                         //
2437                         // Protect the code in a try/finalize block, so that
2438                         // if the beast implement IDisposable, we get rid of it
2439                         //
2440                         Label l = ig.BeginExceptionBlock ();
2441                         bool old_in_try = ec.InTry;
2442                         ec.InTry = true;
2443                         
2444                         Label end_try = ig.DefineLabel ();
2445                         
2446                         ig.MarkLabel (ec.LoopBegin);
2447                         ig.Emit (OpCodes.Ldloc, enumerator);
2448                         ig.Emit (OpCodes.Callvirt, hm.move_next);
2449                         ig.Emit (OpCodes.Brfalse, end_try);
2450                         ig.Emit (OpCodes.Ldloc, enumerator);
2451                         ig.Emit (OpCodes.Callvirt, hm.get_current);
2452                         variable.EmitAssign (ec, conv);
2453                         statement.Emit (ec);
2454                         ig.Emit (OpCodes.Br, ec.LoopBegin);
2455                         ig.MarkLabel (end_try);
2456                         ec.InTry = old_in_try;
2457                         
2458                         // The runtime provides this for us.
2459                         // ig.Emit (OpCodes.Leave, end);
2460
2461                         //
2462                         // Now the finally block
2463                         //
2464                         Label end_finally = ig.DefineLabel ();
2465                         bool old_in_finally = ec.InFinally;
2466                         ec.InFinally = true;
2467                         ig.BeginFinallyBlock ();
2468                         
2469                         ig.Emit (OpCodes.Ldloc, enumerator);
2470                         ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
2471                         ig.Emit (OpCodes.Stloc, disposable);
2472                         ig.Emit (OpCodes.Ldloc, disposable);
2473                         ig.Emit (OpCodes.Brfalse, end_finally);
2474                         ig.Emit (OpCodes.Ldloc, disposable);
2475                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
2476                         ig.MarkLabel (end_finally);
2477                         ec.InFinally = old_in_finally;
2478
2479                         // The runtime generates this anyways.
2480                         // ig.Emit (OpCodes.Endfinally);
2481
2482                         ig.EndExceptionBlock ();
2483
2484                         ig.MarkLabel (ec.LoopEnd);
2485                         return false;
2486                 }
2487
2488                 //
2489                 // FIXME: possible optimization.
2490                 // We might be able to avoid creating `empty' if the type is the sam
2491                 //
2492                 bool EmitArrayForeach (EmitContext ec, Type var_type)
2493                 {
2494                         Type array_type = expr.Type;
2495                         Type element_type = array_type.GetElementType ();
2496                         Expression conv = null;
2497                         Expression empty = new EmptyExpression (element_type);
2498                         
2499                         conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
2500                         if (conv == null)
2501                                 return false;
2502
2503                         int rank = array_type.GetArrayRank ();
2504                         ILGenerator ig = ec.ig;
2505
2506                         LocalBuilder copy = ig.DeclareLocal (array_type);
2507                         
2508                         //
2509                         // Make our copy of the array
2510                         //
2511                         expr.Emit (ec);
2512                         ig.Emit (OpCodes.Stloc, copy);
2513                         
2514                         if (rank == 1){
2515                                 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
2516
2517                                 Label loop, test;
2518                                 
2519                                 ig.Emit (OpCodes.Ldc_I4_0);
2520                                 ig.Emit (OpCodes.Stloc, counter);
2521                                 test = ig.DefineLabel ();
2522                                 ig.Emit (OpCodes.Br, test);
2523
2524                                 loop = ig.DefineLabel ();
2525                                 ig.MarkLabel (loop);
2526
2527                                 ig.Emit (OpCodes.Ldloc, copy);
2528                                 ig.Emit (OpCodes.Ldloc, counter);
2529                                 ArrayAccess.EmitLoadOpcode (ig, var_type);
2530
2531                                 variable.EmitAssign (ec, conv);
2532
2533                                 statement.Emit (ec);
2534
2535                                 ig.MarkLabel (ec.LoopBegin);
2536                                 ig.Emit (OpCodes.Ldloc, counter);
2537                                 ig.Emit (OpCodes.Ldc_I4_1);
2538                                 ig.Emit (OpCodes.Add);
2539                                 ig.Emit (OpCodes.Stloc, counter);
2540
2541                                 ig.MarkLabel (test);
2542                                 ig.Emit (OpCodes.Ldloc, counter);
2543                                 ig.Emit (OpCodes.Ldloc, copy);
2544                                 ig.Emit (OpCodes.Ldlen);
2545                                 ig.Emit (OpCodes.Conv_I4);
2546                                 ig.Emit (OpCodes.Blt, loop);
2547                         } else {
2548                                 LocalBuilder [] dim_len   = new LocalBuilder [rank];
2549                                 LocalBuilder [] dim_count = new LocalBuilder [rank];
2550                                 Label [] loop = new Label [rank];
2551                                 Label [] test = new Label [rank];
2552                                 int dim;
2553                                 
2554                                 for (dim = 0; dim < rank; dim++){
2555                                         dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
2556                                         dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
2557                                         test [dim] = ig.DefineLabel ();
2558                                         loop [dim] = ig.DefineLabel ();
2559                                 }
2560                                         
2561                                 for (dim = 0; dim < rank; dim++){
2562                                         ig.Emit (OpCodes.Ldloc, copy);
2563                                         IntLiteral.EmitInt (ig, dim);
2564                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
2565                                         ig.Emit (OpCodes.Stloc, dim_len [dim]);
2566                                 }
2567
2568                                 for (dim = 0; dim < rank; dim++){
2569                                         ig.Emit (OpCodes.Ldc_I4_0);
2570                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
2571                                         ig.Emit (OpCodes.Br, test [dim]);
2572                                         ig.MarkLabel (loop [dim]);
2573                                 }
2574
2575                                 ig.Emit (OpCodes.Ldloc, copy);
2576                                 for (dim = 0; dim < rank; dim++)
2577                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
2578
2579                                 //
2580                                 // FIXME: Maybe we can cache the computation of `get'?
2581                                 //
2582                                 Type [] args = new Type [rank];
2583                                 MethodInfo get;
2584
2585                                 for (int i = 0; i < rank; i++)
2586                                         args [i] = TypeManager.int32_type;
2587
2588                                 ModuleBuilder mb = RootContext.ModuleBuilder;
2589                                 get = mb.GetArrayMethod (
2590                                         array_type, "Get",
2591                                         CallingConventions.HasThis| CallingConventions.Standard,
2592                                         var_type, args);
2593                                 ig.Emit (OpCodes.Call, get);
2594                                 variable.EmitAssign (ec, conv);
2595                                 statement.Emit (ec);
2596                                 ig.MarkLabel (ec.LoopBegin);
2597                                 for (dim = rank - 1; dim >= 0; dim--){
2598                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
2599                                         ig.Emit (OpCodes.Ldc_I4_1);
2600                                         ig.Emit (OpCodes.Add);
2601                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
2602
2603                                         ig.MarkLabel (test [dim]);
2604                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
2605                                         ig.Emit (OpCodes.Ldloc, dim_len [dim]);
2606                                         ig.Emit (OpCodes.Blt, loop [dim]);
2607                                 }
2608                         }
2609                         ig.MarkLabel (ec.LoopEnd);
2610                         
2611                         return false;
2612                 }
2613                 
2614                 public override bool Emit (EmitContext ec)
2615                 {
2616                         Type var_type;
2617                         bool ret_val;
2618                         
2619                         expr = expr.Resolve (ec);
2620                         if (expr == null)
2621                                 return false;
2622
2623                         var_type = RootContext.LookupType (ec.DeclSpace, type, false, loc);
2624                         if (var_type == null)
2625                                 return false;
2626                         
2627                         //
2628                         // We need an instance variable.  Not sure this is the best
2629                         // way of doing this.
2630                         //
2631                         // FIXME: When we implement propertyaccess, will those turn
2632                         // out to return values in ExprClass?  I think they should.
2633                         //
2634                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
2635                               expr.eclass == ExprClass.PropertyAccess)){
2636                                 error1579 (expr.Type);
2637                                 return false;
2638                         }
2639
2640                         ILGenerator ig = ec.ig;
2641                         
2642                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
2643                         bool old_inloop = ec.InLoop;
2644                         ec.LoopBegin = ig.DefineLabel ();
2645                         ec.LoopEnd = ig.DefineLabel ();
2646                         ec.InLoop = true;
2647                         
2648                         if (expr.Type.IsArray)
2649                                 ret_val = EmitArrayForeach (ec, var_type);
2650                         else {
2651                                 ForeachHelperMethods hm;
2652                                 
2653                                 hm = ProbeCollectionType (ec, expr.Type);
2654                                 if (hm == null)
2655                                         return false;
2656
2657                                 ret_val = EmitCollectionForeach (ec, var_type, hm);
2658                         }
2659                         
2660                         ec.LoopBegin = old_begin;
2661                         ec.LoopEnd = old_end;
2662                         ec.InLoop = old_inloop;
2663
2664                         return ret_val;
2665                 }
2666         }
2667 }
2668