web site updates
[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                 public bool Used;
649                 public bool Assigned;
650                 public bool ReadOnly;
651                 
652                 public VariableInfo (string type, Location l)
653                 {
654                         Type = type;
655                         LocalBuilder = null;
656                         Location = l;
657                 }
658
659                 public void MakePinned ()
660                 {
661                         TypeManager.MakePinned (LocalBuilder);
662                 }                               
663         }
664                 
665         /// <summary>
666         ///   Block represents a C# block.
667         /// </summary>
668         ///
669         /// <remarks>
670         ///   This class is used in a number of places: either to represent
671         ///   explicit blocks that the programmer places or implicit blocks.
672         ///
673         ///   Implicit blocks are used as labels or to introduce variable
674         ///   declarations.
675         /// </remarks>
676         public class Block : Statement {
677                 public readonly Block  Parent;
678                 public readonly bool   Implicit;
679
680                 //
681                 // The statements in this block
682                 //
683                 StatementCollection statements;
684
685                 //
686                 // An array of Blocks.  We keep track of children just
687                 // to generate the local variable declarations.
688                 //
689                 // Statements and child statements are handled through the
690                 // statements.
691                 //
692                 ArrayList children;
693                 
694                 //
695                 // Labels.  (label, block) pairs.
696                 //
697                 Hashtable labels;
698
699                 //
700                 // Keeps track of (name, type) pairs
701                 //
702                 Hashtable variables;
703
704                 //
705                 // Keeps track of constants
706                 Hashtable constants;
707
708                 //
709                 // Maps variable names to ILGenerator.LocalBuilders
710                 //
711                 Hashtable local_builders;
712
713                 bool used = false;
714
715                 static int id;
716
717                 int this_id;
718                 
719                 public Block (Block parent)
720                 {
721                         if (parent != null)
722                                 parent.AddChild (this);
723                         
724                         this.Parent = parent;
725                         this.Implicit = false;
726
727                         this_id = id++;
728                 }
729
730                 public Block (Block parent, bool implicit_block)
731                 {
732                         if (parent != null)
733                                 parent.AddChild (this);
734                         
735                         this.Parent = parent;
736                         this.Implicit = true;
737                         this_id = id++;
738                 }
739
740                 public int ID {
741                         get {
742                                 return this_id;
743                         }
744                 }
745                 
746                 void AddChild (Block b)
747                 {
748                         if (children == null)
749                                 children = new ArrayList ();
750                         
751                         children.Add (b);
752                 }
753
754                 /// <summary>
755                 ///   Adds a label to the current block. 
756                 /// </summary>
757                 ///
758                 /// <returns>
759                 ///   false if the name already exists in this block. true
760                 ///   otherwise.
761                 /// </returns>
762                 ///
763                 public bool AddLabel (string name, LabeledStatement target)
764                 {
765                         if (labels == null)
766                                 labels = new Hashtable ();
767                         if (labels.Contains (name))
768                                 return false;
769                         
770                         labels.Add (name, target);
771                         return true;
772                 }
773
774                 public LabeledStatement LookupLabel (string name)
775                 {
776                         if (labels != null){
777                                 if (labels.Contains (name))
778                                         return ((LabeledStatement) labels [name]);
779                         }
780
781                         if (Parent != null)
782                                 return Parent.LookupLabel (name);
783
784                         return null;
785                 }
786
787                 public VariableInfo AddVariable (string type, string name, Parameters pars, Location l)
788                 {
789                         if (variables == null)
790                                 variables = new Hashtable ();
791
792                         if (GetVariableType (name) != null)
793                                 return null;
794
795                         if (pars != null) {
796                                 int idx = 0;
797                                 Parameter p = pars.GetParameterByName (name, out idx);
798                                 if (p != null) 
799                                         return null;
800                         }
801                         
802                         VariableInfo vi = new VariableInfo (type, l);
803
804                         variables.Add (name, vi);
805
806                         // Console.WriteLine ("Adding {0} to {1}", name, ID);
807                         return vi;
808                 }
809
810                 public bool AddConstant (string type, string name, Expression value, Parameters pars, Location l)
811                 {
812                         if (AddVariable (type, name, pars, l) == null)
813                                 return false;
814                         
815                         if (constants == null)
816                                 constants = new Hashtable ();
817
818                         constants.Add (name, value);
819                         return true;
820                 }
821
822                 public Hashtable Variables {
823                         get {
824                                 return variables;
825                         }
826                 }
827
828                 public VariableInfo GetVariableInfo (string name)
829                 {
830                         if (variables != null) {
831                                 object temp;
832                                 temp = variables [name];
833
834                                 if (temp != null){
835                                         return (VariableInfo) temp;
836                                 }
837                         }
838
839                         if (Parent != null)
840                                 return Parent.GetVariableInfo (name);
841
842                         return null;
843                 }
844                 
845                 public string GetVariableType (string name)
846                 {
847                         VariableInfo vi = GetVariableInfo (name);
848
849                         if (vi != null)
850                                 return vi.Type;
851
852                         return null;
853                 }
854
855                 public Expression GetConstantExpression (string name)
856                 {
857                         if (constants != null) {
858                                 object temp;
859                                 temp = constants [name];
860                                 
861                                 if (temp != null)
862                                         return (Expression) temp;
863                         }
864                         
865                         if (Parent != null)
866                                 return Parent.GetConstantExpression (name);
867
868                         return null;
869                 }
870                 
871                 /// <summary>
872                 ///   True if the variable named @name has been defined
873                 ///   in this block
874                 /// </summary>
875                 public bool IsVariableDefined (string name)
876                 {
877                         // Console.WriteLine ("Looking up {0} in {1}", name, ID);
878                         if (variables != null) {
879                                 if (variables.Contains (name))
880                                         return true;
881                         }
882                         
883                         if (Parent != null)
884                                 return Parent.IsVariableDefined (name);
885
886                         return false;
887                 }
888
889                 /// <summary>
890                 ///   True if the variable named @name is a constant
891                 ///  </summary>
892                 public bool IsConstant (string name)
893                 {
894                         Expression e = null;
895                         
896                         e = GetConstantExpression (name);
897                         
898                         return e != null;
899                 }
900                 
901                 /// <summary>
902                 ///   Use to fetch the statement associated with this label
903                 /// </summary>
904                 public Statement this [string name] {
905                         get {
906                                 return (Statement) labels [name];
907                         }
908                 }
909
910                 /// <returns>
911                 ///   A list of labels that were not used within this block
912                 /// </returns>
913                 public string [] GetUnreferenced ()
914                 {
915                         // FIXME: Implement me
916                         return null;
917                 }
918
919                 public StatementCollection Statements {
920                         get {
921                                 if (statements == null)
922                                         statements = new StatementCollection ();
923
924                                 return statements;
925                         }
926                 }
927
928                 public void AddStatement (Statement s)
929                 {
930                         if (statements == null)
931                                 statements = new StatementCollection ();
932
933                         statements.Add (s);
934                         used = true;
935                 }
936
937                 public bool Used {
938                         get {
939                                 return used;
940                         }
941                 }
942
943                 public void Use ()
944                 {
945                         used = true;
946                 }
947                 
948                 /// <summary>
949                 ///   Emits the variable declarations and labels.
950                 /// </summary>
951                 /// <remarks>
952                 ///   tc: is our typecontainer (to resolve type references)
953                 ///   ig: is the code generator:
954                 ///   toplevel: the toplevel block.  This is used for checking 
955                 ///             that no two labels with the same name are used.
956                 /// </remarks>
957                 public void EmitMeta (EmitContext ec, Block toplevel)
958                 {
959                         DeclSpace ds = ec.DeclSpace;
960                         ILGenerator ig = ec.ig;
961                                 
962                         //
963                         // Process this block variables
964                         //
965                         if (variables != null){
966                                 local_builders = new Hashtable ();
967                                 
968                                 foreach (DictionaryEntry de in variables){
969                                         string name = (string) de.Key;
970                                         VariableInfo vi = (VariableInfo) de.Value;
971                                         Type t;
972
973                                         t = RootContext.LookupType (ds, vi.Type, false, vi.Location);
974                                         if (t == null)
975                                                 continue;
976
977                                         vi.VariableType = t;
978                                         vi.LocalBuilder = ig.DeclareLocal (t);
979
980                                         if (constants == null)
981                                                 continue;
982
983                                         Expression cv = (Expression) constants [name];
984                                         if (cv == null)
985                                                 continue;
986
987                                         Expression e = cv.Resolve (ec);
988                                         if (e == null)
989                                                 continue;
990
991                                         if (!(e is Constant)){
992                                                 Report.Error (133, vi.Location,
993                                                               "The expression being assigned to `" +
994                                                               name + "' must be constant (" + e + ")");
995                                                 continue;
996                                         }
997
998                                         constants.Remove (name);
999                                         constants.Add (name, e);
1000                                 }
1001                         }
1002
1003                         //
1004                         // Now, handle the children
1005                         //
1006                         if (children != null){
1007                                 foreach (Block b in children)
1008                                         b.EmitMeta (ec, toplevel);
1009                         }
1010                 }
1011
1012                 public void UsageWarning ()
1013                 {
1014                         string name;
1015                         
1016                         if (variables != null){
1017                                 foreach (DictionaryEntry de in variables){
1018                                         VariableInfo vi = (VariableInfo) de.Value;
1019                                         
1020                                         if (vi.Used)
1021                                                 continue;
1022                                         
1023                                         name = (string) de.Key;
1024                                                 
1025                                         if (vi.Assigned){
1026                                                 Report.Warning (
1027                                                         219, vi.Location, "The variable `" + name +
1028                                                         "' is assigned but its value is never used");
1029                                         } else {
1030                                                 Report.Warning (
1031                                                         168, vi.Location, "The variable `" +
1032                                                         name +
1033                                                         "' is declared but never used");
1034                                         } 
1035                                 }
1036                         }
1037
1038                         if (children != null)
1039                                 foreach (Block b in children)
1040                                         b.UsageWarning ();
1041                 }
1042
1043 //              static int count;
1044                 
1045                 public override bool Emit (EmitContext ec)
1046                 {
1047                         bool is_ret = false;
1048                         Block prev_block = ec.CurrentBlock;
1049
1050 //                      count++;
1051                         ec.CurrentBlock = this;
1052 //                      if (count == 40)
1053 //                              throw new Exception ();
1054                         foreach (Statement s in Statements)
1055                                 is_ret = s.Emit (ec);
1056 //                      count--;
1057                         
1058                         ec.CurrentBlock = prev_block;
1059                         return is_ret;
1060                 }
1061         }
1062
1063         public class SwitchLabel {
1064                 Expression label;
1065                 object converted;
1066                 public Location loc;
1067                 public Label ILLabel;
1068                 
1069                 //
1070                 // if expr == null, then it is the default case.
1071                 //
1072                 public SwitchLabel (Expression expr, Location l)
1073                 {
1074                         label = expr;
1075                         loc = l;
1076                 }
1077
1078                 public Expression Label {
1079                         get {
1080                                 return label;
1081                         }
1082                 }
1083
1084                 public object Converted {
1085                         get {
1086                                 return converted;
1087                         }
1088                 }
1089                 
1090                 //
1091                 // Resolves the expression, reduces it to a literal if possible
1092                 // and then converts it to the requested type.
1093                 //
1094                 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1095                 {
1096                         ILLabel = ec.ig.DefineLabel ();
1097
1098                         if (label == null)
1099                                 return true;
1100                         
1101                         Expression e = label.Resolve (ec);
1102
1103                         if (e == null)
1104                                 return false;
1105
1106                         if (!(e is Constant)){
1107                                 Console.WriteLine ("Value is: " + label);
1108                                 Report.Error (150, loc, "A constant value is expected");
1109                                 return false;
1110                         }
1111
1112                         if (e is StringConstant || e is NullLiteral){
1113                                 if (required_type == TypeManager.string_type){
1114                                         converted = label;
1115                                         ILLabel = ec.ig.DefineLabel ();
1116                                         return true;
1117                                 }
1118                         }
1119
1120                         converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1121                         if (converted == null)
1122                                 return false;
1123
1124                         return true;
1125                 }
1126         }
1127
1128         public class SwitchSection {
1129                 // An array of SwitchLabels.
1130                 public readonly ArrayList Labels;
1131                 public readonly Block Block;
1132                 
1133                 public SwitchSection (ArrayList labels, Block block)
1134                 {
1135                         Labels = labels;
1136                         Block = block;
1137                 }
1138         }
1139         
1140         public class Switch : Statement {
1141                 public readonly ArrayList Sections;
1142                 public Expression Expr;
1143
1144                 /// <summary>
1145                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
1146                 /// </summary>
1147                 public Hashtable Elements;
1148
1149                 /// <summary>
1150                 ///   The governing switch type
1151                 /// </summary>
1152                 public Type SwitchType;
1153
1154                 //
1155                 // Computed
1156                 //
1157                 bool got_default;
1158                 Label default_target;
1159                 Location loc;
1160                 
1161                 //
1162                 // The types allowed to be implicitly cast from
1163                 // on the governing type
1164                 //
1165                 static Type [] allowed_types;
1166                 
1167                 public Switch (Expression e, ArrayList sects, Location l)
1168                 {
1169                         Expr = e;
1170                         Sections = sects;
1171                         loc = l;
1172                 }
1173
1174                 public bool GotDefault {
1175                         get {
1176                                 return got_default;
1177                         }
1178                 }
1179
1180                 public Label DefaultTarget {
1181                         get {
1182                                 return default_target;
1183                         }
1184                 }
1185
1186                 //
1187                 // Determines the governing type for a switch.  The returned
1188                 // expression might be the expression from the switch, or an
1189                 // expression that includes any potential conversions to the
1190                 // integral types or to string.
1191                 //
1192                 Expression SwitchGoverningType (EmitContext ec, Type t)
1193                 {
1194                         if (t == TypeManager.int32_type ||
1195                             t == TypeManager.uint32_type ||
1196                             t == TypeManager.char_type ||
1197                             t == TypeManager.byte_type ||
1198                             t == TypeManager.sbyte_type ||
1199                             t == TypeManager.ushort_type ||
1200                             t == TypeManager.short_type ||
1201                             t == TypeManager.uint64_type ||
1202                             t == TypeManager.int64_type ||
1203                             t == TypeManager.string_type ||
1204                             t.IsSubclassOf (TypeManager.enum_type))
1205                                 return Expr;
1206
1207                         if (allowed_types == null){
1208                                 allowed_types = new Type [] {
1209                                         TypeManager.sbyte_type,
1210                                         TypeManager.byte_type,
1211                                         TypeManager.short_type,
1212                                         TypeManager.ushort_type,
1213                                         TypeManager.int32_type,
1214                                         TypeManager.uint32_type,
1215                                         TypeManager.int64_type,
1216                                         TypeManager.uint64_type,
1217                                         TypeManager.char_type,
1218                                         TypeManager.string_type
1219                                 };
1220                         }
1221
1222                         //
1223                         // Try to find a *user* defined implicit conversion.
1224                         //
1225                         // If there is no implicit conversion, or if there are multiple
1226                         // conversions, we have to report an error
1227                         //
1228                         Expression converted = null;
1229                         foreach (Type tt in allowed_types){
1230                                 Expression e;
1231                                 
1232                                 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
1233                                 if (e == null)
1234                                         continue;
1235
1236                                 if (converted != null){
1237                                         Report.Error (-12, loc, "More than one conversion to an integral " +
1238                                                       " type exists for type `" +
1239                                                       TypeManager.CSharpName (Expr.Type)+"'");
1240                                         return null;
1241                                 } else
1242                                         converted = e;
1243                         }
1244                         return converted;
1245                 }
1246
1247                 void error152 (string n)
1248                 {
1249                         Report.Error (
1250                                 152, "The label `" + n + ":' " +
1251                                 "is already present on this switch statement");
1252                 }
1253                 
1254                 //
1255                 // Performs the basic sanity checks on the switch statement
1256                 // (looks for duplicate keys and non-constant expressions).
1257                 //
1258                 // It also returns a hashtable with the keys that we will later
1259                 // use to compute the switch tables
1260                 //
1261                 bool CheckSwitch (EmitContext ec)
1262                 {
1263                         Type compare_type;
1264                         bool error = false;
1265                         Elements = new Hashtable ();
1266                                 
1267                         got_default = false;
1268
1269                         if (TypeManager.IsEnumType (SwitchType)){
1270                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
1271                         } else
1272                                 compare_type = SwitchType;
1273                         
1274                         foreach (SwitchSection ss in Sections){
1275                                 foreach (SwitchLabel sl in ss.Labels){
1276                                         if (!sl.ResolveAndReduce (ec, SwitchType)){
1277                                                 error = true;
1278                                                 continue;
1279                                         }
1280
1281                                         if (sl.Label == null){
1282                                                 if (got_default){
1283                                                         error152 ("default");
1284                                                         error = true;
1285                                                 }
1286                                                 got_default = true;
1287                                                 continue;
1288                                         }
1289                                         
1290                                         object key = sl.Converted;
1291
1292                                         if (key is Constant)
1293                                                 key = ((Constant) key).GetValue ();
1294
1295                                         if (key == null)
1296                                                 key = NullLiteral.Null;
1297                                         
1298                                         string lname = null;
1299                                         if (compare_type == TypeManager.uint64_type){
1300                                                 ulong v = (ulong) key;
1301
1302                                                 if (Elements.Contains (v))
1303                                                         lname = v.ToString ();
1304                                                 else
1305                                                         Elements.Add (v, sl);
1306                                         } else if (compare_type == TypeManager.int64_type){
1307                                                 long v = (long) key;
1308
1309                                                 if (Elements.Contains (v))
1310                                                         lname = v.ToString ();
1311                                                 else
1312                                                         Elements.Add (v, sl);
1313                                         } else if (compare_type == TypeManager.uint32_type){
1314                                                 uint v = (uint) key;
1315
1316                                                 if (Elements.Contains (v))
1317                                                         lname = v.ToString ();
1318                                                 else
1319                                                         Elements.Add (v, sl);
1320                                         } else if (compare_type == TypeManager.char_type){
1321                                                 char v = (char) key;
1322                                                 
1323                                                 if (Elements.Contains (v))
1324                                                         lname = v.ToString ();
1325                                                 else
1326                                                         Elements.Add (v, sl);
1327                                         } else if (compare_type == TypeManager.byte_type){
1328                                                 byte v = (byte) key;
1329                                                 
1330                                                 if (Elements.Contains (v))
1331                                                         lname = v.ToString ();
1332                                                 else
1333                                                         Elements.Add (v, sl);
1334                                         } else if (compare_type == TypeManager.sbyte_type){
1335                                                 sbyte v = (sbyte) key;
1336                                                 
1337                                                 if (Elements.Contains (v))
1338                                                         lname = v.ToString ();
1339                                                 else
1340                                                         Elements.Add (v, sl);
1341                                         } else if (compare_type == TypeManager.short_type){
1342                                                 short v = (short) key;
1343                                                 
1344                                                 if (Elements.Contains (v))
1345                                                         lname = v.ToString ();
1346                                                 else
1347                                                         Elements.Add (v, sl);
1348                                         } else if (compare_type == TypeManager.ushort_type){
1349                                                 ushort v = (ushort) key;
1350                                                 
1351                                                 if (Elements.Contains (v))
1352                                                         lname = v.ToString ();
1353                                                 else
1354                                                         Elements.Add (v, sl);
1355                                         } else if (compare_type == TypeManager.string_type){
1356                                                 if (key is NullLiteral){
1357                                                         if (Elements.Contains (NullLiteral.Null))
1358                                                                 lname = "null";
1359                                                         else
1360                                                                 Elements.Add (NullLiteral.Null, null);
1361                                                 } else {
1362                                                         string s = (string) key;
1363
1364                                                         if (Elements.Contains (s))
1365                                                                 lname = s;
1366                                                         else
1367                                                                 Elements.Add (s, sl);
1368                                                 }
1369                                         } else if (compare_type == TypeManager.int32_type) {
1370                                                 int v = (int) key;
1371
1372                                                 if (Elements.Contains (v))
1373                                                         lname = v.ToString ();
1374                                                 else
1375                                                         Elements.Add (v, sl);
1376                                         } else {
1377                                                 throw new Exception ("Unknown switch type!" +
1378                                                                      SwitchType + " " + compare_type);
1379                                         }
1380
1381                                         if (lname != null){
1382                                                 error152 ("case + " + lname);
1383                                                 error = true;
1384                                         }
1385                                 }
1386                         }
1387                         if (error)
1388                                 return false;
1389                         
1390                         return true;
1391                 }
1392
1393                 void EmitObjectInteger (ILGenerator ig, object k)
1394                 {
1395                         if (k is int)
1396                                 IntConstant.EmitInt (ig, (int) k);
1397                         else if (k is Constant){
1398                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
1399                         } else if (k is uint)
1400                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
1401                         else if (k is long)
1402                                 LongConstant.EmitLong (ig, (long) k);
1403                         else if (k is ulong)
1404                                 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
1405                         else if (k is char)
1406                                 IntConstant.EmitInt (ig, (int) ((char) k));
1407                         else if (k is sbyte)
1408                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
1409                         else if (k is byte)
1410                                 IntConstant.EmitInt (ig, (int) ((byte) k));
1411                         else 
1412                                 throw new Exception ("Unhandled case");
1413                 }
1414                 
1415                 //
1416                 // This simple emit switch works, but does not take advantage of the
1417                 // `switch' opcode.  The swithc opcode uses a jump table that we are not
1418                 // computing at this point
1419                 //
1420                 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
1421                 {
1422                         ILGenerator ig = ec.ig;
1423                         Label end_of_switch = ig.DefineLabel ();
1424                         Label next_test = ig.DefineLabel ();
1425                         Label null_target = ig.DefineLabel ();
1426                         bool default_found = false;
1427                         bool first_test = true;
1428                         bool pending_goto_end = false;
1429                         bool all_return = true;
1430                         bool is_string = false;
1431                         bool null_found;
1432                         
1433                         //
1434                         // Special processing for strings: we cant compare
1435                         // against null.
1436                         //
1437                         if (SwitchType == TypeManager.string_type){
1438                                 ig.Emit (OpCodes.Ldloc, val);
1439                                 is_string = true;
1440                                 
1441                                 if (Elements.Contains (NullLiteral.Null)){
1442                                         ig.Emit (OpCodes.Brfalse, null_target);
1443                                 } else
1444                                         ig.Emit (OpCodes.Brfalse, default_target);
1445
1446                                 ig.Emit (OpCodes.Ldloc, val);
1447                                 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
1448                                 ig.Emit (OpCodes.Stloc, val);
1449                         }
1450                         
1451                         foreach (SwitchSection ss in Sections){
1452                                 Label sec_begin = ig.DefineLabel ();
1453
1454                                 if (pending_goto_end)
1455                                         ig.Emit (OpCodes.Br, end_of_switch);
1456
1457                                 int label_count = ss.Labels.Count;
1458                                 null_found = false;
1459                                 foreach (SwitchLabel sl in ss.Labels){
1460                                         ig.MarkLabel (sl.ILLabel);
1461                                         
1462                                         if (!first_test){
1463                                                 ig.MarkLabel (next_test);
1464                                                 next_test = ig.DefineLabel ();
1465                                         }
1466                                         //
1467                                         // If we are the default target
1468                                         //
1469                                         if (sl.Label == null){
1470                                                 ig.MarkLabel (default_target);
1471                                                 default_found = true;
1472                                         } else {
1473                                                 object lit = sl.Converted;
1474
1475                                                 if (lit is NullLiteral){
1476                                                         null_found = true;
1477                                                         if (label_count == 1)
1478                                                                 ig.Emit (OpCodes.Br, next_test);
1479                                                         continue;
1480                                                                               
1481                                                 }
1482                                                 if (is_string){
1483                                                         StringConstant str = (StringConstant) lit;
1484
1485                                                         ig.Emit (OpCodes.Ldloc, val);
1486                                                         ig.Emit (OpCodes.Ldstr, str.Value);
1487                                                         if (label_count == 1)
1488                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
1489                                                         else
1490                                                                 ig.Emit (OpCodes.Beq, sec_begin);
1491                                                 } else {
1492                                                         ig.Emit (OpCodes.Ldloc, val);
1493                                                         EmitObjectInteger (ig, lit);
1494                                                         ig.Emit (OpCodes.Ceq);
1495                                                         if (label_count == 1)
1496                                                                 ig.Emit (OpCodes.Brfalse, next_test);
1497                                                         else
1498                                                                 ig.Emit (OpCodes.Brtrue, sec_begin);
1499                                                 }
1500                                         }
1501                                 }
1502                                 if (label_count != 1)
1503                                         ig.Emit (OpCodes.Br, next_test);
1504                                 
1505                                 if (null_found)
1506                                         ig.MarkLabel (null_target);
1507                                 ig.MarkLabel (sec_begin);
1508                                 if (ss.Block.Emit (ec))
1509                                         pending_goto_end = false;
1510                                 else {
1511                                         all_return = false;
1512                                         pending_goto_end = true;
1513                                 }
1514                                 first_test = false;
1515                         }
1516                         if (!default_found)
1517                                 ig.MarkLabel (default_target);
1518                         ig.MarkLabel (next_test);
1519                         ig.MarkLabel (end_of_switch);
1520                         
1521                         return all_return;
1522                 }
1523                 
1524                 public override bool Emit (EmitContext ec)
1525                 {
1526                         Expr = Expr.Resolve (ec);
1527                         if (Expr == null)
1528                                 return false;
1529
1530                         Expression new_expr = SwitchGoverningType (ec, Expr.Type);
1531                         if (new_expr == null){
1532                                 Report.Error (151, loc, "An integer type or string was expected for switch");
1533                                 return false;
1534                         }
1535
1536                         // Validate switch.
1537                         SwitchType = new_expr.Type;
1538
1539                         if (!CheckSwitch (ec))
1540                                 return false;
1541
1542                         // Store variable for comparission purposes
1543                         LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
1544                         new_expr.Emit (ec);
1545                         ec.ig.Emit (OpCodes.Stloc, value);
1546
1547                         ILGenerator ig = ec.ig;
1548
1549                         default_target = ig.DefineLabel ();
1550
1551                         //
1552                         // Setup the codegen context
1553                         //
1554                         Label old_end = ec.LoopEnd;
1555                         Switch old_switch = ec.Switch;
1556                         
1557                         ec.LoopEnd = ig.DefineLabel ();
1558                         ec.Switch = this;
1559
1560                         // Emit Code.
1561                         bool all_return =  SimpleSwitchEmit (ec, value);
1562
1563                         // Restore context state. 
1564                         ig.MarkLabel (ec.LoopEnd);
1565
1566                         //
1567                         // FIXME: I am emitting a nop, because the switch performs
1568                         // no analysis on whether something ever reaches the end
1569                         //
1570                         // try: b (int a) { switch (a) { default: return 0; }  }
1571                         ig.Emit (OpCodes.Nop);
1572
1573                         //
1574                         // Restore the previous context
1575                         //
1576                         ec.LoopEnd = old_end;
1577                         ec.Switch = old_switch;
1578                         
1579                         //
1580                         // Because we have a nop at the end
1581                         //
1582                         return false;
1583                 }
1584         }
1585
1586         public class Lock : Statement {
1587                 public readonly Expression Expr;
1588                 public readonly Statement Statement;
1589                 Location loc;
1590                         
1591                 public Lock (Expression expr, Statement stmt, Location l)
1592                 {
1593                         Expr = expr;
1594                         Statement = stmt;
1595                         loc = l;
1596                 }
1597
1598                 public override bool Emit (EmitContext ec)
1599                 {
1600                         Expression e = Expr.Resolve (ec);
1601                         if (e == null)
1602                                 return false;
1603
1604                         Type type = e.Type;
1605                         
1606                         if (type.IsValueType){
1607                                 Report.Error (185, loc, "lock statement requires the expression to be " +
1608                                               " a reference type (type is: `" +
1609                                               TypeManager.CSharpName (type) + "'");
1610                                 return false;
1611                         }
1612
1613                         ILGenerator ig = ec.ig;
1614                         LocalBuilder temp = ig.DeclareLocal (type);
1615                                 
1616                         e.Emit (ec);
1617                         ig.Emit (OpCodes.Dup);
1618                         ig.Emit (OpCodes.Stloc, temp);
1619                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
1620
1621                         // try
1622                         Label end = ig.BeginExceptionBlock ();
1623                         bool old_in_try = ec.InTry;
1624                         ec.InTry = true;
1625                         Label finish = ig.DefineLabel ();
1626                         Statement.Emit (ec);
1627                         ec.InTry = old_in_try;
1628                         // ig.Emit (OpCodes.Leave, finish);
1629
1630                         ig.MarkLabel (finish);
1631                         
1632                         // finally
1633                         ig.BeginFinallyBlock ();
1634                         ig.Emit (OpCodes.Ldloc, temp);
1635                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
1636                         ig.EndExceptionBlock ();
1637                         
1638                         return false;
1639                 }
1640         }
1641
1642         public class Unchecked : Statement {
1643                 public readonly Block Block;
1644                 
1645                 public Unchecked (Block b)
1646                 {
1647                         Block = b;
1648                 }
1649
1650                 public override bool Emit (EmitContext ec)
1651                 {
1652                         bool previous_state = ec.CheckState;
1653                         bool previous_state_const = ec.ConstantCheckState;
1654                         bool val;
1655                         
1656                         ec.CheckState = false;
1657                         ec.ConstantCheckState = false;
1658                         val = Block.Emit (ec);
1659                         ec.CheckState = previous_state;
1660                         ec.ConstantCheckState = previous_state_const;
1661
1662                         return val;
1663                 }
1664         }
1665
1666         public class Checked : Statement {
1667                 public readonly Block Block;
1668                 
1669                 public Checked (Block b)
1670                 {
1671                         Block = b;
1672                 }
1673
1674                 public override bool Emit (EmitContext ec)
1675                 {
1676                         bool previous_state = ec.CheckState;
1677                         bool previous_state_const = ec.ConstantCheckState;
1678                         bool val;
1679                         
1680                         ec.CheckState = true;
1681                         ec.ConstantCheckState = true;
1682                         val = Block.Emit (ec);
1683                         ec.CheckState = previous_state;
1684                         ec.ConstantCheckState = previous_state_const;
1685
1686                         return val;
1687                 }
1688         }
1689
1690         public class Unsafe : Statement {
1691                 public readonly Block Block;
1692
1693                 public Unsafe (Block b)
1694                 {
1695                         Block = b;
1696                 }
1697
1698                 public override bool Emit (EmitContext ec)
1699                 {
1700                         bool previous_state = ec.InUnsafe;
1701                         bool val;
1702                         
1703                         ec.InUnsafe = true;
1704                         val = Block.Emit (ec);
1705                         ec.InUnsafe = previous_state;
1706
1707                         return val;
1708                 }
1709         }
1710
1711         // 
1712         // Fixed statement
1713         //
1714         public class Fixed : Statement {
1715                 string    type;
1716                 ArrayList declarators;
1717                 Statement statement;
1718                 Location  loc;
1719
1720                 public Fixed (string type, ArrayList decls, Statement stmt, Location l)
1721                 {
1722                         this.type = type;
1723                         declarators = decls;
1724                         statement = stmt;
1725                         loc = l;
1726                 }
1727
1728                 public override bool Emit (EmitContext ec)
1729                 {
1730                         ILGenerator ig = ec.ig;
1731                         Type t;
1732                         
1733                         t = RootContext.LookupType (ec.DeclSpace, type, false, loc);
1734                         if (t == null)
1735                                 return false;
1736
1737                         foreach (Pair p in declarators){
1738                                 VariableInfo vi = (VariableInfo) p.First;
1739                                 Expression e = (Expression) p.Second;
1740
1741                                 //
1742                                 // The rules for the possible declarators are pretty wise,
1743                                 // but the production on the grammar is more concise.
1744                                 //
1745                                 // So we have to enforce these rules here.
1746                                 //
1747                                 // We do not resolve before doing the case 1 test,
1748                                 // because the grammar is explicit in that the token &
1749                                 // is present, so we need to test for this particular case.
1750                                 //
1751
1752                                 //
1753                                 // Case 1: & object.
1754                                 //
1755                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
1756                                         Expression child = ((Unary) e).Expr;
1757
1758                                         vi.MakePinned ();
1759                                         if (child is ParameterReference || child is LocalVariableReference){
1760                                                 Report.Error (
1761                                                         213, loc, 
1762                                                         "No need to use fixed statement for parameters or " +
1763                                                         "local variable declarations (address is already " +
1764                                                         "fixed)");
1765                                                 continue;
1766                                         }
1767                                         
1768                                         e = e.Resolve (ec);
1769                                         if (e == null)
1770                                                 continue;
1771
1772                                         child = ((Unary) e).Expr;
1773                                         
1774                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
1775                                                 continue;
1776
1777                                         //
1778                                         // Store pointer in pinned location
1779                                         //
1780                                         e.Emit (ec);
1781                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1782
1783                                         statement.Emit (ec);
1784
1785                                         // Clear the pinned variable.
1786                                         ig.Emit (OpCodes.Ldc_I4_0);
1787                                         ig.Emit (OpCodes.Conv_U);
1788                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1789
1790                                         continue;
1791                                 }
1792
1793                                 e = e.Resolve (ec);
1794                                 if (e == null)
1795                                         continue;
1796
1797                                 //
1798                                 // Case 2: Array
1799                                 //
1800                                 if (e.Type.IsArray){
1801                                         Type array_type = e.Type.GetElementType ();
1802                                         
1803                                         vi.MakePinned ();
1804                                         //
1805                                         // Provided that array_type is unmanaged,
1806                                         //
1807                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
1808                                                 continue;
1809
1810                                         //
1811                                         // and T* is implicitly convertible to the
1812                                         // pointer type given in the fixed statement.
1813                                         //
1814                                         ArrayPtr array_ptr = new ArrayPtr (e);
1815                                         
1816                                         Expression converted = Expression.ConvertImplicitRequired (
1817                                                 ec, array_ptr, vi.VariableType, loc);
1818                                         if (converted == null)
1819                                                 continue;
1820
1821                                         //
1822                                         // Store pointer in pinned location
1823                                         //
1824                                         converted.Emit (ec);
1825                                         
1826                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1827
1828                                         statement.Emit (ec);
1829                                         
1830                                         // Clear the pinned variable.
1831                                         ig.Emit (OpCodes.Ldc_I4_0);
1832                                         ig.Emit (OpCodes.Conv_U);
1833                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1834
1835                                         continue;
1836                                 }
1837
1838                                 //
1839                                 // Case 3: string
1840                                 //
1841                                 if (e.Type == TypeManager.string_type){
1842                                         LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
1843                                         TypeManager.MakePinned (pinned_string);
1844                                         
1845                                         e.Emit (ec);
1846                                         ig.Emit (OpCodes.Stloc, pinned_string);
1847
1848                                         Expression sptr = new StringPtr (pinned_string);
1849                                         Expression converted = Expression.ConvertImplicitRequired (
1850                                                 ec, sptr, vi.VariableType, loc);
1851                                         
1852                                         if (converted == null)
1853                                                 continue;
1854
1855                                         converted.Emit (ec);
1856                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1857                                         
1858                                         statement.Emit (ec);
1859
1860                                         // Clear the pinned variable
1861                                         ig.Emit (OpCodes.Ldnull);
1862                                         ig.Emit (OpCodes.Stloc, pinned_string);
1863                                 }
1864                         }
1865
1866                         return false;
1867                 }
1868         }
1869         
1870         public class Catch {
1871                 public readonly string Type;
1872                 public readonly string Name;
1873                 public readonly Block  Block;
1874                 public readonly Location Location;
1875                 
1876                 public Catch (string type, string name, Block block, Location l)
1877                 {
1878                         Type = type;
1879                         Name = name;
1880                         Block = block;
1881                         Location = l;
1882                 }
1883         }
1884
1885         public class Try : Statement {
1886                 public readonly Block Fini, Block;
1887                 public readonly ArrayList Specific;
1888                 public readonly Catch General;
1889                 
1890                 //
1891                 // specific, general and fini might all be null.
1892                 //
1893                 public Try (Block block, ArrayList specific, Catch general, Block fini)
1894                 {
1895                         if (specific == null && general == null){
1896                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
1897                         }
1898                         
1899                         this.Block = block;
1900                         this.Specific = specific;
1901                         this.General = general;
1902                         this.Fini = fini;
1903                 }
1904
1905                 public override bool Emit (EmitContext ec)
1906                 {
1907                         ILGenerator ig = ec.ig;
1908                         Label end;
1909                         Label finish = ig.DefineLabel ();;
1910                         bool returns;
1911                         
1912                         end = ig.BeginExceptionBlock ();
1913                         bool old_in_try = ec.InTry;
1914                         ec.InTry = true;
1915                         returns = Block.Emit (ec);
1916                         ec.InTry = old_in_try;
1917
1918                         //
1919                         // System.Reflection.Emit provides this automatically:
1920                         // ig.Emit (OpCodes.Leave, finish);
1921
1922                         bool old_in_catch = ec.InCatch;
1923                         ec.InCatch = true;
1924                         DeclSpace ds = ec.DeclSpace;
1925                         
1926                         foreach (Catch c in Specific){
1927                                 Type catch_type = RootContext.LookupType (ds, c.Type, false, c.Location);
1928                                 VariableInfo vi;
1929                                 
1930                                 if (catch_type == null)
1931                                         return false;
1932
1933                                 ig.BeginCatchBlock (catch_type);
1934
1935                                 if (c.Name != null){
1936                                         vi = c.Block.GetVariableInfo (c.Name);
1937                                         if (vi == null){
1938                                                 Console.WriteLine ("This should not happen! variable does not exist in this block");
1939                                                 Environment.Exit (0);
1940                                         }
1941                                 
1942                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1943                                 } else
1944                                         ig.Emit (OpCodes.Pop);
1945                                 
1946                                 c.Block.Emit (ec);
1947                         }
1948
1949                         if (General != null){
1950                                 ig.BeginCatchBlock (TypeManager.object_type);
1951                                 ig.Emit (OpCodes.Pop);
1952                                 General.Block.Emit (ec);
1953                         }
1954                         ec.InCatch = old_in_catch;
1955
1956                         ig.MarkLabel (finish);
1957                         if (Fini != null){
1958                                 ig.BeginFinallyBlock ();
1959                                 bool old_in_finally = ec.InFinally;
1960                                 ec.InFinally = true;
1961                                 Fini.Emit (ec);
1962                                 ec.InFinally = old_in_finally;
1963                         }
1964                         
1965                         ig.EndExceptionBlock ();
1966
1967                         //
1968                         // FIXME: Is this correct?
1969                         // Replace with `returns' and check test-18, maybe we can
1970                         // perform an optimization here.
1971                         //
1972                         return false;
1973                 }
1974         }
1975
1976         //
1977         // FIXME: We still do not support the expression variant of the using
1978         // statement.
1979         //
1980         public class Using : Statement {
1981                 object expression_or_block;
1982                 Statement Statement;
1983                 Location loc;
1984                 
1985                 public Using (object expression_or_block, Statement stmt, Location l)
1986                 {
1987                         this.expression_or_block = expression_or_block;
1988                         Statement = stmt;
1989                         loc = l;
1990                 }
1991
1992                 //
1993                 // Emits the code for the case of using using a local variable declaration.
1994                 //
1995                 bool EmitLocalVariableDecls (EmitContext ec, string type_name, ArrayList var_list)
1996                 {
1997                         ILGenerator ig = ec.ig;
1998                         Expression [] converted_vars;
1999                         bool need_conv = false;
2000                         Type type = RootContext.LookupType (ec.DeclSpace, type_name, false, loc);
2001                         int i = 0;
2002
2003                         if (type == null)
2004                                 return false;
2005                         
2006                         //
2007                         // The type must be an IDisposable or an implicit conversion
2008                         // must exist.
2009                         //
2010                         converted_vars = new Expression [var_list.Count];
2011                         if (!TypeManager.ImplementsInterface (type, TypeManager.idisposable_type)){
2012                                 foreach (DictionaryEntry e in var_list){
2013                                         Expression var = (Expression) e.Key;
2014
2015                                         var = var.Resolve (ec);
2016                                         if (var == null)
2017                                                 return false;
2018                                         
2019                                         converted_vars [i] = Expression.ConvertImplicit (
2020                                                 ec, var, TypeManager.idisposable_type, loc);
2021
2022                                         if (converted_vars [i] == null)
2023                                                 return false;
2024                                         i++;
2025                                 }
2026                                 need_conv = true;
2027                         }
2028                         
2029                         i = 0;
2030                         bool old_in_try = ec.InTry;
2031                         ec.InTry = true;
2032                         foreach (DictionaryEntry e in var_list){
2033                                 LocalVariableReference var = (LocalVariableReference) e.Key;
2034                                 Expression expr = (Expression) e.Value;
2035                                 Expression a;
2036
2037                                 a = new Assign (var, expr, loc);
2038                                 a.Resolve (ec);
2039                                 if (!need_conv)
2040                                         converted_vars [i] = var;
2041                                 i++;
2042                                 if (a == null)
2043                                         continue;
2044                                 ((ExpressionStatement) a).EmitStatement (ec);
2045                                 
2046                                 ig.BeginExceptionBlock ();
2047
2048                         }
2049                         Statement.Emit (ec);
2050                         ec.InTry = old_in_try;
2051
2052                         bool old_in_finally = ec.InFinally;
2053                         ec.InFinally = true;
2054                         var_list.Reverse ();
2055                         foreach (DictionaryEntry e in var_list){
2056                                 LocalVariableReference var = (LocalVariableReference) e.Key;
2057                                 Label skip = ig.DefineLabel ();
2058                                 i--;
2059                                 
2060                                 ig.BeginFinallyBlock ();
2061                                 
2062                                 var.Emit (ec);
2063                                 ig.Emit (OpCodes.Brfalse, skip);
2064                                 converted_vars [i].Emit (ec);
2065                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
2066                                 ig.MarkLabel (skip);
2067                                 ig.EndExceptionBlock ();
2068                         }
2069                         ec.InFinally = old_in_finally;
2070
2071                         return false;
2072                 }
2073
2074                 bool EmitExpression (EmitContext ec, Expression expr)
2075                 {
2076                         Type expr_type = expr.Type;
2077                         Expression conv = null;
2078                         
2079                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
2080                                 conv = Expression.ConvertImplicit (
2081                                         ec, expr, TypeManager.idisposable_type, loc);
2082
2083                                 if (conv == null)
2084                                         return false;
2085                         }
2086
2087                         //
2088                         // Make a copy of the expression and operate on that.
2089                         //
2090                         ILGenerator ig = ec.ig;
2091                         LocalBuilder local_copy = ig.DeclareLocal (expr_type);
2092                         if (conv != null)
2093                                 conv.Emit (ec);
2094                         else
2095                                 expr.Emit (ec);
2096                         ig.Emit (OpCodes.Stloc, local_copy);
2097
2098                         bool old_in_try = ec.InTry;
2099                         ec.InTry = true;
2100                         ig.BeginExceptionBlock ();
2101                         Statement.Emit (ec);
2102                         ec.InTry = old_in_try;
2103                         
2104                         Label skip = ig.DefineLabel ();
2105                         bool old_in_finally = ec.InFinally;
2106                         ig.BeginFinallyBlock ();
2107                         ig.Emit (OpCodes.Ldloc, local_copy);
2108                         ig.Emit (OpCodes.Brfalse, skip);
2109                         ig.Emit (OpCodes.Ldloc, local_copy);
2110                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
2111                         ig.MarkLabel (skip);
2112                         ec.InFinally = old_in_finally;
2113                         ig.EndExceptionBlock ();
2114
2115                         return false;
2116                 }
2117                 
2118                 public override bool Emit (EmitContext ec)
2119                 {
2120                         if (expression_or_block is DictionaryEntry){
2121                                 string t = (string) ((DictionaryEntry) expression_or_block).Key;
2122                                 ArrayList var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
2123
2124                                 return EmitLocalVariableDecls (ec, t, var_list);
2125                         } if (expression_or_block is Expression){
2126                                 Expression e = (Expression) expression_or_block;
2127
2128                                 e = e.Resolve (ec);
2129                                 if (e == null)
2130                                         return false;
2131
2132                                 return EmitExpression (ec, e);
2133                         }
2134                         return false;
2135                 }
2136         }
2137
2138         /// <summary>
2139         ///   Implementation of the foreach C# statement
2140         /// </summary>
2141         public class Foreach : Statement {
2142                 string type;
2143                 LocalVariableReference variable;
2144                 Expression expr;
2145                 Statement statement;
2146                 Location loc;
2147                 
2148                 public Foreach (string type, LocalVariableReference var, Expression expr,
2149                                 Statement stmt, Location l)
2150                 {
2151                         this.type = type;
2152                         this.variable = var;
2153                         this.expr = expr;
2154                         statement = stmt;
2155                         loc = l;
2156                 }
2157                 
2158                 //
2159                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
2160                 //
2161                 static MethodInfo FetchMethodMoveNext (Type t)
2162                 {
2163                         MemberInfo [] move_next_list;
2164                         
2165                         move_next_list = TypeContainer.FindMembers (
2166                                 t, MemberTypes.Method,
2167                                 BindingFlags.Public | BindingFlags.Instance,
2168                                 Type.FilterName, "MoveNext");
2169                         if (move_next_list == null || move_next_list.Length == 0)
2170                                 return null;
2171
2172                         foreach (MemberInfo m in move_next_list){
2173                                 MethodInfo mi = (MethodInfo) m;
2174                                 Type [] args;
2175                                 
2176                                 args = TypeManager.GetArgumentTypes (mi);
2177                                 if (args != null && args.Length == 0){
2178                                         if (mi.ReturnType == TypeManager.bool_type)
2179                                                 return mi;
2180                                 }
2181                         }
2182                         return null;
2183                 }
2184                 
2185                 //
2186                 // Retrieves a `public T get_Current ()' method from the Type `t'
2187                 //
2188                 static MethodInfo FetchMethodGetCurrent (Type t)
2189                 {
2190                         MemberInfo [] move_next_list;
2191                         
2192                         move_next_list = TypeContainer.FindMembers (
2193                                 t, MemberTypes.Method,
2194                                 BindingFlags.Public | BindingFlags.Instance,
2195                                 Type.FilterName, "get_Current");
2196                         if (move_next_list == null || move_next_list.Length == 0)
2197                                 return null;
2198
2199                         foreach (MemberInfo m in move_next_list){
2200                                 MethodInfo mi = (MethodInfo) m;
2201                                 Type [] args;
2202                                 
2203                                 args = TypeManager.GetArgumentTypes (mi);
2204                                 if (args != null && args.Length == 0)
2205                                         return mi;
2206                         }
2207                         return null;
2208                 }
2209
2210                 // 
2211                 // This struct records the helper methods used by the Foreach construct
2212                 //
2213                 class ForeachHelperMethods {
2214                         public EmitContext ec;
2215                         public MethodInfo get_enumerator;
2216                         public MethodInfo move_next;
2217                         public MethodInfo get_current;
2218
2219                         public ForeachHelperMethods (EmitContext ec)
2220                         {
2221                                 this.ec = ec;
2222                         }
2223                 }
2224                 
2225                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
2226                 {
2227                         if (m == null)
2228                                 return false;
2229                         
2230                         if (!(m is MethodInfo))
2231                                 return false;
2232                         
2233                         if (m.Name != "GetEnumerator")
2234                                 return false;
2235
2236                         MethodInfo mi = (MethodInfo) m;
2237                         Type [] args = TypeManager.GetArgumentTypes (mi);
2238                         if (args != null){
2239                                 if (args.Length != 0)
2240                                         return false;
2241                         }
2242                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
2243                         EmitContext ec = hm.ec;
2244                         
2245                         //
2246                         // Check whether GetEnumerator is accessible to us
2247                         //
2248                         MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
2249
2250                         Type declaring = mi.DeclaringType;
2251                         if (prot == MethodAttributes.Private){
2252                                 if (declaring != ec.ContainerType)
2253                                         return false;
2254                         } else if (prot == MethodAttributes.FamANDAssem){
2255                                 // If from a different assembly, false
2256                                 if (!(mi is MethodBuilder))
2257                                         return false;
2258                                 //
2259                                 // Are we being invoked from the same class, or from a derived method?
2260                                 //
2261                                 if (ec.ContainerType != declaring){
2262                                         if (!ec.ContainerType.IsSubclassOf (declaring))
2263                                                 return false;
2264                                 }
2265                         } else if (prot == MethodAttributes.FamORAssem){
2266                                 if (!(mi is MethodBuilder ||
2267                                       ec.ContainerType == declaring ||
2268                                       ec.ContainerType.IsSubclassOf (declaring)))
2269                                         return false;
2270                         } if (prot == MethodAttributes.Family){
2271                                 if (!(ec.ContainerType == declaring ||
2272                                       ec.ContainerType.IsSubclassOf (declaring)))
2273                                         return false;
2274                         }
2275
2276                         //
2277                         // Ok, we can access it, now make sure that we can do something
2278                         // with this `GetEnumerator'
2279                         //
2280                         if (mi.ReturnType == TypeManager.ienumerator_type || 
2281                             TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType)){
2282                                 hm.move_next = TypeManager.bool_movenext_void;
2283                                 hm.get_current = TypeManager.object_getcurrent_void;
2284                                 return true;
2285                         }
2286
2287                         //
2288                         // Ok, so they dont return an IEnumerable, we will have to
2289                         // find if they support the GetEnumerator pattern.
2290                         //
2291                         Type return_type = mi.ReturnType;
2292
2293                         hm.move_next = FetchMethodMoveNext (return_type);
2294                         if (hm.move_next == null)
2295                                 return false;
2296                         hm.get_current = FetchMethodGetCurrent (return_type);
2297                         if (hm.get_current == null)
2298                                 return false;
2299
2300                         return true;
2301                 }
2302                 
2303                 /// <summary>
2304                 ///   This filter is used to find the GetEnumerator method
2305                 ///   on which IEnumerator operates
2306                 /// </summary>
2307                 static MemberFilter FilterEnumerator;
2308                 
2309                 static Foreach ()
2310                 {
2311                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
2312                 }
2313
2314                 void error1579 (Type t)
2315                 {
2316                         Report.Error (1579, loc,
2317                                       "foreach statement cannot operate on variables of type `" +
2318                                       t.FullName + "' because that class does not provide a " +
2319                                       " GetEnumerator method or it is inaccessible");
2320                 }
2321
2322                 static bool TryType (Type t, ForeachHelperMethods hm)
2323                 {
2324                         MemberInfo [] mi;
2325                         
2326                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
2327                                                         BindingFlags.Public | BindingFlags.NonPublic |
2328                                                         BindingFlags.Instance,
2329                                                         FilterEnumerator, hm);
2330
2331                         if (mi == null || mi.Length == 0)
2332                                 return false;
2333
2334                         hm.get_enumerator = (MethodInfo) mi [0];
2335                         return true;    
2336                 }
2337                 
2338                 //
2339                 // Looks for a usable GetEnumerator in the Type, and if found returns
2340                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
2341                 //
2342                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
2343                 {
2344                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
2345
2346                         if (TryType (t, hm))
2347                                 return hm;
2348
2349                         //
2350                         // Now try to find the method in the interfaces
2351                         //
2352                         while (t != null){
2353                                 Type [] ifaces = t.GetInterfaces ();
2354
2355                                 foreach (Type i in ifaces){
2356                                         if (TryType (i, hm))
2357                                                 return hm;
2358                                 }
2359                                 
2360                                 //
2361                                 // Since TypeBuilder.GetInterfaces only returns the interface
2362                                 // types for this type, we have to keep looping, but once
2363                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
2364                                 // done, because it returns all the types
2365                                 //
2366                                 if ((t is TypeBuilder))
2367                                         t = t.BaseType;
2368                                 else
2369                                         break;
2370                         } 
2371
2372                         return null;
2373                 }
2374
2375                 //
2376                 // FIXME: possible optimization.
2377                 // We might be able to avoid creating `empty' if the type is the sam
2378                 //
2379                 bool EmitCollectionForeach (EmitContext ec, Type var_type, ForeachHelperMethods hm)
2380                 {
2381                         ILGenerator ig = ec.ig;
2382                         LocalBuilder enumerator, disposable;
2383                         Expression empty = new EmptyExpression ();
2384                         Expression conv;
2385
2386                         //
2387                         // FIXME: maybe we can apply the same trick we do in the
2388                         // array handling to avoid creating empty and conv in some cases.
2389                         //
2390                         // Although it is not as important in this case, as the type
2391                         // will not likely be object (what the enumerator will return).
2392                         //
2393                         conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
2394                         if (conv == null)
2395                                 return false;
2396                         
2397                         enumerator = ig.DeclareLocal (TypeManager.ienumerator_type);
2398                         disposable = ig.DeclareLocal (TypeManager.idisposable_type);
2399                         
2400                         //
2401                         // Instantiate the enumerator
2402                         //
2403                         if (expr.Type.IsValueType){
2404                                 if (expr is IMemoryLocation){
2405                                         IMemoryLocation ml = (IMemoryLocation) expr;
2406
2407                                         ml.AddressOf (ec, AddressOp.Load);
2408                                 } else
2409                                         throw new Exception ("Expr " + expr + " of type " + expr.Type +
2410                                                              " does not implement IMemoryLocation");
2411                                 ig.Emit (OpCodes.Call, hm.get_enumerator);
2412                         } else {
2413                                 expr.Emit (ec);
2414                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
2415                         }
2416                         ig.Emit (OpCodes.Stloc, enumerator);
2417
2418                         //
2419                         // Protect the code in a try/finalize block, so that
2420                         // if the beast implement IDisposable, we get rid of it
2421                         //
2422                         Label l = ig.BeginExceptionBlock ();
2423                         bool old_in_try = ec.InTry;
2424                         ec.InTry = true;
2425                         
2426                         Label end_try = ig.DefineLabel ();
2427                         
2428                         ig.MarkLabel (ec.LoopBegin);
2429                         ig.Emit (OpCodes.Ldloc, enumerator);
2430                         ig.Emit (OpCodes.Callvirt, hm.move_next);
2431                         ig.Emit (OpCodes.Brfalse, end_try);
2432                         ig.Emit (OpCodes.Ldloc, enumerator);
2433                         ig.Emit (OpCodes.Callvirt, hm.get_current);
2434                         variable.EmitAssign (ec, conv);
2435                         statement.Emit (ec);
2436                         ig.Emit (OpCodes.Br, ec.LoopBegin);
2437                         ig.MarkLabel (end_try);
2438                         ec.InTry = old_in_try;
2439                         
2440                         // The runtime provides this for us.
2441                         // ig.Emit (OpCodes.Leave, end);
2442
2443                         //
2444                         // Now the finally block
2445                         //
2446                         Label end_finally = ig.DefineLabel ();
2447                         bool old_in_finally = ec.InFinally;
2448                         ec.InFinally = true;
2449                         ig.BeginFinallyBlock ();
2450                         
2451                         ig.Emit (OpCodes.Ldloc, enumerator);
2452                         ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
2453                         ig.Emit (OpCodes.Stloc, disposable);
2454                         ig.Emit (OpCodes.Ldloc, disposable);
2455                         ig.Emit (OpCodes.Brfalse, end_finally);
2456                         ig.Emit (OpCodes.Ldloc, disposable);
2457                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
2458                         ig.MarkLabel (end_finally);
2459                         ec.InFinally = old_in_finally;
2460
2461                         // The runtime generates this anyways.
2462                         // ig.Emit (OpCodes.Endfinally);
2463
2464                         ig.EndExceptionBlock ();
2465
2466                         ig.MarkLabel (ec.LoopEnd);
2467                         return false;
2468                 }
2469
2470                 //
2471                 // FIXME: possible optimization.
2472                 // We might be able to avoid creating `empty' if the type is the sam
2473                 //
2474                 bool EmitArrayForeach (EmitContext ec, Type var_type)
2475                 {
2476                         Type array_type = expr.Type;
2477                         Type element_type = array_type.GetElementType ();
2478                         Expression conv = null;
2479                         Expression empty = new EmptyExpression (element_type);
2480                         
2481                         conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
2482                         if (conv == null)
2483                                 return false;
2484
2485                         int rank = array_type.GetArrayRank ();
2486                         ILGenerator ig = ec.ig;
2487
2488                         LocalBuilder copy = ig.DeclareLocal (array_type);
2489                         
2490                         //
2491                         // Make our copy of the array
2492                         //
2493                         expr.Emit (ec);
2494                         ig.Emit (OpCodes.Stloc, copy);
2495                         
2496                         if (rank == 1){
2497                                 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
2498
2499                                 Label loop, test;
2500                                 
2501                                 ig.Emit (OpCodes.Ldc_I4_0);
2502                                 ig.Emit (OpCodes.Stloc, counter);
2503                                 test = ig.DefineLabel ();
2504                                 ig.Emit (OpCodes.Br, test);
2505
2506                                 loop = ig.DefineLabel ();
2507                                 ig.MarkLabel (loop);
2508
2509                                 ig.Emit (OpCodes.Ldloc, copy);
2510                                 ig.Emit (OpCodes.Ldloc, counter);
2511                                 ArrayAccess.EmitLoadOpcode (ig, var_type);
2512
2513                                 variable.EmitAssign (ec, conv);
2514
2515                                 statement.Emit (ec);
2516
2517                                 ig.MarkLabel (ec.LoopBegin);
2518                                 ig.Emit (OpCodes.Ldloc, counter);
2519                                 ig.Emit (OpCodes.Ldc_I4_1);
2520                                 ig.Emit (OpCodes.Add);
2521                                 ig.Emit (OpCodes.Stloc, counter);
2522
2523                                 ig.MarkLabel (test);
2524                                 ig.Emit (OpCodes.Ldloc, counter);
2525                                 ig.Emit (OpCodes.Ldloc, copy);
2526                                 ig.Emit (OpCodes.Ldlen);
2527                                 ig.Emit (OpCodes.Conv_I4);
2528                                 ig.Emit (OpCodes.Blt, loop);
2529                         } else {
2530                                 LocalBuilder [] dim_len   = new LocalBuilder [rank];
2531                                 LocalBuilder [] dim_count = new LocalBuilder [rank];
2532                                 Label [] loop = new Label [rank];
2533                                 Label [] test = new Label [rank];
2534                                 int dim;
2535                                 
2536                                 for (dim = 0; dim < rank; dim++){
2537                                         dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
2538                                         dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
2539                                         test [dim] = ig.DefineLabel ();
2540                                         loop [dim] = ig.DefineLabel ();
2541                                 }
2542                                         
2543                                 for (dim = 0; dim < rank; dim++){
2544                                         ig.Emit (OpCodes.Ldloc, copy);
2545                                         IntLiteral.EmitInt (ig, dim);
2546                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
2547                                         ig.Emit (OpCodes.Stloc, dim_len [dim]);
2548                                 }
2549
2550                                 for (dim = 0; dim < rank; dim++){
2551                                         ig.Emit (OpCodes.Ldc_I4_0);
2552                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
2553                                         ig.Emit (OpCodes.Br, test [dim]);
2554                                         ig.MarkLabel (loop [dim]);
2555                                 }
2556
2557                                 ig.Emit (OpCodes.Ldloc, copy);
2558                                 for (dim = 0; dim < rank; dim++)
2559                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
2560
2561                                 //
2562                                 // FIXME: Maybe we can cache the computation of `get'?
2563                                 //
2564                                 Type [] args = new Type [rank];
2565                                 MethodInfo get;
2566
2567                                 for (int i = 0; i < rank; i++)
2568                                         args [i] = TypeManager.int32_type;
2569
2570                                 ModuleBuilder mb = RootContext.ModuleBuilder;
2571                                 get = mb.GetArrayMethod (
2572                                         array_type, "Get",
2573                                         CallingConventions.HasThis| CallingConventions.Standard,
2574                                         var_type, args);
2575                                 ig.Emit (OpCodes.Call, get);
2576                                 variable.EmitAssign (ec, conv);
2577                                 statement.Emit (ec);
2578                                 ig.MarkLabel (ec.LoopBegin);
2579                                 for (dim = rank - 1; dim >= 0; dim--){
2580                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
2581                                         ig.Emit (OpCodes.Ldc_I4_1);
2582                                         ig.Emit (OpCodes.Add);
2583                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
2584
2585                                         ig.MarkLabel (test [dim]);
2586                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
2587                                         ig.Emit (OpCodes.Ldloc, dim_len [dim]);
2588                                         ig.Emit (OpCodes.Blt, loop [dim]);
2589                                 }
2590                         }
2591                         ig.MarkLabel (ec.LoopEnd);
2592                         
2593                         return false;
2594                 }
2595                 
2596                 public override bool Emit (EmitContext ec)
2597                 {
2598                         Type var_type;
2599                         bool ret_val;
2600                         
2601                         expr = expr.Resolve (ec);
2602                         if (expr == null)
2603                                 return false;
2604
2605                         var_type = RootContext.LookupType (ec.DeclSpace, type, false, loc);
2606                         if (var_type == null)
2607                                 return false;
2608                         
2609                         //
2610                         // We need an instance variable.  Not sure this is the best
2611                         // way of doing this.
2612                         //
2613                         // FIXME: When we implement propertyaccess, will those turn
2614                         // out to return values in ExprClass?  I think they should.
2615                         //
2616                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
2617                               expr.eclass == ExprClass.PropertyAccess)){
2618                                 error1579 (expr.Type);
2619                                 return false;
2620                         }
2621
2622                         ILGenerator ig = ec.ig;
2623                         
2624                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
2625                         bool old_inloop = ec.InLoop;
2626                         ec.LoopBegin = ig.DefineLabel ();
2627                         ec.LoopEnd = ig.DefineLabel ();
2628                         ec.InLoop = true;
2629                         
2630                         if (expr.Type.IsArray)
2631                                 ret_val = EmitArrayForeach (ec, var_type);
2632                         else {
2633                                 ForeachHelperMethods hm;
2634                                 
2635                                 hm = ProbeCollectionType (ec, expr.Type);
2636                                 if (hm == null)
2637                                         return false;
2638
2639                                 ret_val = EmitCollectionForeach (ec, var_type, hm);
2640                         }
2641                         
2642                         ec.LoopBegin = old_begin;
2643                         ec.LoopEnd = old_end;
2644                         ec.InLoop = old_inloop;
2645
2646                         return ret_val;
2647                 }
2648         }
2649 }
2650