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