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