2007-06-20 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / mcs / statement.cs
1 //
2 // statement.cs: Statement representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Martin Baulig (martin@ximian.com)
7 //   Marek Safar (marek.safar@seznam.cz)
8 //
9 // (C) 2001, 2002, 2003 Ximian, Inc.
10 // (C) 2003, 2004 Novell, Inc.
11 //
12
13 using System;
14 using System.Text;
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Diagnostics;
18 using System.Collections;
19 using System.Collections.Specialized;
20
21 namespace Mono.CSharp {
22         
23         public abstract class Statement {
24                 public Location loc;
25                 
26                 /// <summary>
27                 ///   Resolves the statement, true means that all sub-statements
28                 ///   did resolve ok.
29                 //  </summary>
30                 public virtual bool Resolve (EmitContext ec)
31                 {
32                         return true;
33                 }
34
35                 /// <summary>
36                 ///   We already know that the statement is unreachable, but we still
37                 ///   need to resolve it to catch errors.
38                 /// </summary>
39                 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
40                 {
41                         //
42                         // This conflicts with csc's way of doing this, but IMHO it's
43                         // the right thing to do.
44                         //
45                         // If something is unreachable, we still check whether it's
46                         // correct.  This means that you cannot use unassigned variables
47                         // in unreachable code, for instance.
48                         //
49
50                         if (warn)
51                                 Report.Warning (162, 2, loc, "Unreachable code detected");
52
53                         ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
54                         bool ok = Resolve (ec);
55                         ec.KillFlowBranching ();
56
57                         return ok;
58                 }
59                                 
60                 /// <summary>
61                 ///   Return value indicates whether all code paths emitted return.
62                 /// </summary>
63                 protected abstract void DoEmit (EmitContext ec);
64
65                 /// <summary>
66                 ///   Utility wrapper routine for Error, just to beautify the code
67                 /// </summary>
68                 public void Error (int error, string format, params object[] args)
69                 {
70                         Error (error, String.Format (format, args));
71                 }
72
73                 public void Error (int error, string s)
74                 {
75                         if (!loc.IsNull)
76                                 Report.Error (error, loc, s);
77                         else
78                                 Report.Error (error, s);
79                 }
80
81                 /// <summary>
82                 ///   Return value indicates whether all code paths emitted return.
83                 /// </summary>
84                 public virtual void Emit (EmitContext ec)
85                 {
86                         ec.Mark (loc, true);
87                         DoEmit (ec);
88                 }
89
90                 //
91                 // This routine must be overrided in derived classes and make copies
92                 // of all the data that might be modified if resolved
93                 // 
94                 protected virtual void CloneTo (CloneContext clonectx, Statement target)
95                 {
96                         throw new Exception (String.Format ("Statement.CloneTo not implemented for {0}", this.GetType ()));
97                 }
98                 
99                 public Statement Clone (CloneContext clonectx)
100                 {
101                         Statement s = (Statement) this.MemberwiseClone ();
102                         CloneTo (clonectx, s);
103                         return s;
104                 }
105
106                 public Statement PerformClone ()
107                 {
108                         CloneContext clonectx = new CloneContext ();
109
110                         return Clone (clonectx);
111                 }
112
113         }
114
115         //
116         // This class is used during the Statement.Clone operation
117         // to remap objects that have been cloned.
118         //
119         // Since blocks are cloned by Block.Clone, we need a way for
120         // expressions that must reference the block to be cloned
121         // pointing to the new cloned block.
122         //
123         public class CloneContext {
124                 Hashtable block_map = new Hashtable ();
125                 Hashtable variable_map;
126                 
127                 public void AddBlockMap (Block from, Block to)
128                 {
129                         if (block_map.Contains (from))
130                                 return;
131                         block_map [from] = to;
132                 }
133                 
134                 public Block LookupBlock (Block from)
135                 {
136                         Block result = (Block) block_map [from];
137
138                         if (result == null){
139                                 result = (Block) from.Clone (this);
140                                 block_map [from] = result;
141                         }
142
143                         return result;
144                 }
145
146                 public void AddVariableMap (LocalInfo from, LocalInfo to)
147                 {
148                         if (variable_map == null)
149                                 variable_map = new Hashtable ();
150                         
151                         if (variable_map.Contains (from))
152                                 return;
153                         variable_map [from] = to;
154                 }
155                 
156                 public LocalInfo LookupVariable (LocalInfo from)
157                 {
158                         LocalInfo result = (LocalInfo) variable_map [from];
159
160                         if (result == null)
161                                 throw new Exception ("LookupVariable: looking up a variable that has not been registered yet");
162
163                         return result;
164                 }
165         }
166         
167         public sealed class EmptyStatement : Statement {
168                 
169                 private EmptyStatement () {}
170                 
171                 public static readonly EmptyStatement Value = new EmptyStatement ();
172                 
173                 public override bool Resolve (EmitContext ec)
174                 {
175                         return true;
176                 }
177
178                 public override bool ResolveUnreachable (EmitContext ec, bool warn)
179                 {
180                         return true;
181                 }
182
183                 protected override void DoEmit (EmitContext ec)
184                 {
185                 }
186         }
187         
188         public class If : Statement {
189                 Expression expr;
190                 public Statement TrueStatement;
191                 public Statement FalseStatement;
192
193                 bool is_true_ret;
194                 
195                 public If (Expression expr, Statement trueStatement, Location l)
196                 {
197                         this.expr = expr;
198                         TrueStatement = trueStatement;
199                         loc = l;
200                 }
201
202                 public If (Expression expr,
203                            Statement trueStatement,
204                            Statement falseStatement,
205                            Location l)
206                 {
207                         this.expr = expr;
208                         TrueStatement = trueStatement;
209                         FalseStatement = falseStatement;
210                         loc = l;
211                 }
212
213                 public override bool Resolve (EmitContext ec)
214                 {
215                         bool ok = true;
216
217                         Report.Debug (1, "START IF BLOCK", loc);
218
219                         expr = Expression.ResolveBoolean (ec, expr, loc);
220                         if (expr == null){
221                                 ok = false;
222                                 goto skip;
223                         }
224
225                         Assign ass = expr as Assign;
226                         if (ass != null && ass.Source is Constant) {
227                                 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
228                         }
229
230                         //
231                         // Dead code elimination
232                         //
233                         if (expr is BoolConstant){
234                                 bool take = ((BoolConstant) expr).Value;
235
236                                 if (take){
237                                         if (!TrueStatement.Resolve (ec))
238                                                 return false;
239
240                                         if ((FalseStatement != null) &&
241                                             !FalseStatement.ResolveUnreachable (ec, true))
242                                                 return false;
243                                         FalseStatement = null;
244                                 } else {
245                                         if (!TrueStatement.ResolveUnreachable (ec, true))
246                                                 return false;
247                                         TrueStatement = null;
248
249                                         if ((FalseStatement != null) &&
250                                             !FalseStatement.Resolve (ec))
251                                                 return false;
252                                 }
253
254                                 return true;
255                         }
256                 skip:
257                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
258                         
259                         ok &= TrueStatement.Resolve (ec);
260
261                         is_true_ret = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
262
263                         ec.CurrentBranching.CreateSibling ();
264
265                         if (FalseStatement != null)
266                                 ok &= FalseStatement.Resolve (ec);
267                                         
268                         ec.EndFlowBranching ();
269
270                         Report.Debug (1, "END IF BLOCK", loc);
271
272                         return ok;
273                 }
274                 
275                 protected override void DoEmit (EmitContext ec)
276                 {
277                         ILGenerator ig = ec.ig;
278                         Label false_target = ig.DefineLabel ();
279                         Label end;
280
281                         //
282                         // If we're a boolean expression, Resolve() already
283                         // eliminated dead code for us.
284                         //
285                         if (expr is BoolConstant){
286                                 bool take = ((BoolConstant) expr).Value;
287
288                                 if (take)
289                                         TrueStatement.Emit (ec);
290                                 else if (FalseStatement != null)
291                                         FalseStatement.Emit (ec);
292
293                                 return;
294                         }
295                         
296                         expr.EmitBranchable (ec, false_target, false);
297                         
298                         TrueStatement.Emit (ec);
299
300                         if (FalseStatement != null){
301                                 bool branch_emitted = false;
302                                 
303                                 end = ig.DefineLabel ();
304                                 if (!is_true_ret){
305                                         ig.Emit (OpCodes.Br, end);
306                                         branch_emitted = true;
307                                 }
308
309                                 ig.MarkLabel (false_target);
310                                 FalseStatement.Emit (ec);
311
312                                 if (branch_emitted)
313                                         ig.MarkLabel (end);
314                         } else {
315                                 ig.MarkLabel (false_target);
316                         }
317                 }
318
319                 protected override void CloneTo (CloneContext clonectx, Statement t)
320                 {
321                         If target = (If) t;
322
323                         target.expr = expr.Clone (clonectx);
324                         target.TrueStatement = TrueStatement.Clone (clonectx);
325                         if (FalseStatement != null)
326                                 target.FalseStatement = FalseStatement.Clone (clonectx);
327                 }
328         }
329
330         public class Do : Statement {
331                 public Expression expr;
332                 public Statement  EmbeddedStatement;
333                 bool infinite;
334                 
335                 public Do (Statement statement, Expression boolExpr, Location l)
336                 {
337                         expr = boolExpr;
338                         EmbeddedStatement = statement;
339                         loc = l;
340                 }
341
342                 public override bool Resolve (EmitContext ec)
343                 {
344                         bool ok = true;
345
346                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
347
348                         bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
349
350                         ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
351                         if (!EmbeddedStatement.Resolve (ec))
352                                 ok = false;
353                         ec.EndFlowBranching ();
354
355                         if (ec.CurrentBranching.CurrentUsageVector.IsUnreachable && !was_unreachable)
356                                 Report.Warning (162, 2, expr.Location, "Unreachable code detected");
357
358                         expr = Expression.ResolveBoolean (ec, expr, loc);
359                         if (expr == null)
360                                 ok = false;
361                         else if (expr is BoolConstant){
362                                 bool res = ((BoolConstant) expr).Value;
363
364                                 if (res)
365                                         infinite = true;
366                         }
367                         if (infinite)
368                                 ec.CurrentBranching.CurrentUsageVector.Goto ();
369
370                         ec.EndFlowBranching ();
371
372                         return ok;
373                 }
374                 
375                 protected override void DoEmit (EmitContext ec)
376                 {
377                         ILGenerator ig = ec.ig;
378                         Label loop = ig.DefineLabel ();
379                         Label old_begin = ec.LoopBegin;
380                         Label old_end = ec.LoopEnd;
381                         
382                         ec.LoopBegin = ig.DefineLabel ();
383                         ec.LoopEnd = ig.DefineLabel ();
384                                 
385                         ig.MarkLabel (loop);
386                         EmbeddedStatement.Emit (ec);
387                         ig.MarkLabel (ec.LoopBegin);
388
389                         //
390                         // Dead code elimination
391                         //
392                         if (expr is BoolConstant){
393                                 bool res = ((BoolConstant) expr).Value;
394
395                                 if (res)
396                                         ec.ig.Emit (OpCodes.Br, loop); 
397                         } else
398                                 expr.EmitBranchable (ec, loop, true);
399                         
400                         ig.MarkLabel (ec.LoopEnd);
401
402                         ec.LoopBegin = old_begin;
403                         ec.LoopEnd = old_end;
404                 }
405
406                 protected override void CloneTo (CloneContext clonectx, Statement t)
407                 {
408                         Do target = (Do) t;
409
410                         target.EmbeddedStatement = EmbeddedStatement.Clone (clonectx);
411                         target.expr = expr.Clone (clonectx);
412                 }
413         }
414
415         public class While : Statement {
416                 public Expression expr;
417                 public Statement Statement;
418                 bool infinite, empty;
419                 
420                 public While (Expression boolExpr, Statement statement, Location l)
421                 {
422                         this.expr = boolExpr;
423                         Statement = statement;
424                         loc = l;
425                 }
426
427                 public override bool Resolve (EmitContext ec)
428                 {
429                         bool ok = true;
430
431                         expr = Expression.ResolveBoolean (ec, expr, loc);
432                         if (expr == null)
433                                 return false;
434
435                         //
436                         // Inform whether we are infinite or not
437                         //
438                         if (expr is BoolConstant){
439                                 BoolConstant bc = (BoolConstant) expr;
440
441                                 if (bc.Value == false){
442                                         if (!Statement.ResolveUnreachable (ec, true))
443                                                 return false;
444                                         empty = true;
445                                         return true;
446                                 } else
447                                         infinite = true;
448                         }
449
450                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
451                         if (!infinite)
452                                 ec.CurrentBranching.CreateSibling ();
453
454                         ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
455                         if (!Statement.Resolve (ec))
456                                 ok = false;
457                         ec.EndFlowBranching ();
458
459                         // There's no direct control flow from the end of the embedded statement to the end of the loop
460                         ec.CurrentBranching.CurrentUsageVector.Goto ();
461
462                         ec.EndFlowBranching ();
463
464                         return ok;
465                 }
466                 
467                 protected override void DoEmit (EmitContext ec)
468                 {
469                         if (empty)
470                                 return;
471
472                         ILGenerator ig = ec.ig;
473                         Label old_begin = ec.LoopBegin;
474                         Label old_end = ec.LoopEnd;
475                         
476                         ec.LoopBegin = ig.DefineLabel ();
477                         ec.LoopEnd = ig.DefineLabel ();
478
479                         //
480                         // Inform whether we are infinite or not
481                         //
482                         if (expr is BoolConstant){
483                                 ig.MarkLabel (ec.LoopBegin);
484                                 Statement.Emit (ec);
485                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
486                                         
487                                 //
488                                 // Inform that we are infinite (ie, `we return'), only
489                                 // if we do not `break' inside the code.
490                                 //
491                                 ig.MarkLabel (ec.LoopEnd);
492                         } else {
493                                 Label while_loop = ig.DefineLabel ();
494
495                                 ig.Emit (OpCodes.Br, ec.LoopBegin);
496                                 ig.MarkLabel (while_loop);
497
498                                 Statement.Emit (ec);
499                         
500                                 ig.MarkLabel (ec.LoopBegin);
501
502                                 expr.EmitBranchable (ec, while_loop, true);
503                                 
504                                 ig.MarkLabel (ec.LoopEnd);
505                         }       
506
507                         ec.LoopBegin = old_begin;
508                         ec.LoopEnd = old_end;
509                 }
510
511                 protected override void CloneTo (CloneContext clonectx, Statement t)
512                 {
513                         While target = (While) t;
514
515                         target.expr = expr.Clone (clonectx);
516                         target.Statement = Statement.Clone (clonectx);
517                 }
518         }
519
520         public class For : Statement {
521                 Expression Test;
522                 Statement InitStatement;
523                 Statement Increment;
524                 public Statement Statement;
525                 bool infinite, empty;
526                 
527                 public For (Statement initStatement,
528                             Expression test,
529                             Statement increment,
530                             Statement statement,
531                             Location l)
532                 {
533                         InitStatement = initStatement;
534                         Test = test;
535                         Increment = increment;
536                         Statement = statement;
537                         loc = l;
538                 }
539
540                 public override bool Resolve (EmitContext ec)
541                 {
542                         bool ok = true;
543
544                         if (InitStatement != null){
545                                 if (!InitStatement.Resolve (ec))
546                                         ok = false;
547                         }
548
549                         if (Test != null){
550                                 Test = Expression.ResolveBoolean (ec, Test, loc);
551                                 if (Test == null)
552                                         ok = false;
553                                 else if (Test is BoolConstant){
554                                         BoolConstant bc = (BoolConstant) Test;
555
556                                         if (bc.Value == false){
557                                                 if (!Statement.ResolveUnreachable (ec, true))
558                                                         return false;
559                                                 if ((Increment != null) &&
560                                                     !Increment.ResolveUnreachable (ec, false))
561                                                         return false;
562                                                 empty = true;
563                                                 return true;
564                                         } else
565                                                 infinite = true;
566                                 }
567                         } else
568                                 infinite = true;
569
570                         ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
571                         if (!infinite)
572                                 ec.CurrentBranching.CreateSibling ();
573
574                         bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
575
576                         ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
577                         if (!Statement.Resolve (ec))
578                                 ok = false;
579                         ec.EndFlowBranching ();
580
581                         if (Increment != null){
582                                 if (ec.CurrentBranching.CurrentUsageVector.IsUnreachable) {
583                                         if (!Increment.ResolveUnreachable (ec, !was_unreachable))
584                                                 ok = false;
585                                 } else {
586                                         if (!Increment.Resolve (ec))
587                                                 ok = false;
588                                 }
589                         }
590
591                         // There's no direct control flow from the end of the embedded statement to the end of the loop
592                         ec.CurrentBranching.CurrentUsageVector.Goto ();
593
594                         ec.EndFlowBranching ();
595
596                         return ok;
597                 }
598                 
599                 protected override void DoEmit (EmitContext ec)
600                 {
601                         if (empty)
602                                 return;
603
604                         ILGenerator ig = ec.ig;
605                         Label old_begin = ec.LoopBegin;
606                         Label old_end = ec.LoopEnd;
607                         Label loop = ig.DefineLabel ();
608                         Label test = ig.DefineLabel ();
609                         
610                         if (InitStatement != null && InitStatement != EmptyStatement.Value)
611                                 InitStatement.Emit (ec);
612
613                         ec.LoopBegin = ig.DefineLabel ();
614                         ec.LoopEnd = ig.DefineLabel ();
615
616                         ig.Emit (OpCodes.Br, test);
617                         ig.MarkLabel (loop);
618                         Statement.Emit (ec);
619
620                         ig.MarkLabel (ec.LoopBegin);
621                         if (Increment != EmptyStatement.Value)
622                                 Increment.Emit (ec);
623
624                         ig.MarkLabel (test);
625                         //
626                         // If test is null, there is no test, and we are just
627                         // an infinite loop
628                         //
629                         if (Test != null){
630                                 //
631                                 // The Resolve code already catches the case for
632                                 // Test == BoolConstant (false) so we know that
633                                 // this is true
634                                 //
635                                 if (Test is BoolConstant)
636                                         ig.Emit (OpCodes.Br, loop);
637                                 else
638                                         Test.EmitBranchable (ec, loop, true);
639                                 
640                         } else
641                                 ig.Emit (OpCodes.Br, loop);
642                         ig.MarkLabel (ec.LoopEnd);
643
644                         ec.LoopBegin = old_begin;
645                         ec.LoopEnd = old_end;
646                 }
647
648                 protected override void CloneTo (CloneContext clonectx, Statement t)
649                 {
650                         For target = (For) t;
651
652                         if (InitStatement != null)
653                                 target.InitStatement = InitStatement.Clone (clonectx);
654                         if (Test != null)
655                                 target.Test = Test.Clone (clonectx);
656                         if (Increment != null)
657                                 target.Increment = Increment.Clone (clonectx);
658                         target.Statement = Statement.Clone (clonectx);
659                 }
660         }
661         
662         public class StatementExpression : Statement {
663                 ExpressionStatement expr;
664                 
665                 public StatementExpression (ExpressionStatement expr)
666                 {
667                         this.expr = expr;
668                         loc = expr.Location;
669                 }
670
671                 public override bool Resolve (EmitContext ec)
672                 {
673                         if (expr != null)
674                                 expr = expr.ResolveStatement (ec);
675                         return expr != null;
676                 }
677                 
678                 protected override void DoEmit (EmitContext ec)
679                 {
680                         expr.EmitStatement (ec);
681                 }
682
683                 public override string ToString ()
684                 {
685                         return "StatementExpression (" + expr + ")";
686                 }
687
688                 protected override void CloneTo (CloneContext clonectx, Statement t)
689                 {
690                         StatementExpression target = (StatementExpression) t;
691
692                         target.expr = (ExpressionStatement) expr.Clone (clonectx);
693                 }
694         }
695
696         /// <summary>
697         ///   Implements the return statement
698         /// </summary>
699         public class Return : Statement {
700                 public Expression Expr;
701                 
702                 public Return (Expression expr, Location l)
703                 {
704                         Expr = expr;
705                         loc = l;
706                 }
707
708                 bool unwind_protect;
709
710                 public override bool Resolve (EmitContext ec)
711                 {
712                         AnonymousContainer am = ec.CurrentAnonymousMethod;
713                         if ((am != null) && am.IsIterator && ec.InIterator) {
714                                 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
715                                               "statement to return a value, or yield break to end the iteration");
716                                 return false;
717                         }
718
719                         if (ec.ReturnType == null){
720                                 if (Expr != null){
721                                         if (am != null){
722                                                 Report.Error (1662, loc,
723                                                         "Cannot convert anonymous method block to delegate type `{0}' because some of the return types in the block are not implicitly convertible to the delegate return type",
724                                                         am.GetSignatureForError ());
725                                         }
726                                         Error (127, "A return keyword must not be followed by any expression when method returns void");
727                                         return false;
728                                 }
729                         } else {
730                                 if (Expr == null){
731                                         Error (126, "An object of a type convertible to `{0}' is required " +
732                                                "for the return statement",
733                                                TypeManager.CSharpName (ec.ReturnType));
734                                         return false;
735                                 }
736
737                                 Expr = Expr.Resolve (ec);
738                                 if (Expr == null)
739                                         return false;
740
741                                 if (Expr.Type != ec.ReturnType) {
742                                         if (ec.InferReturnType) {
743                                                 ec.ReturnType = Expr.Type;
744                                         } else {
745                                                 Expr = Convert.ImplicitConversionRequired (
746                                                         ec, Expr, ec.ReturnType, loc);
747                                                 if (Expr == null)
748                                                         return false;
749                                         }
750                                 }
751                         }
752
753                         int errors = Report.Errors;
754                         unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
755                         if (unwind_protect)
756                                 ec.NeedReturnLabel ();
757                         ec.CurrentBranching.CurrentUsageVector.Goto ();
758                         return errors == Report.Errors;
759                 }
760                 
761                 protected override void DoEmit (EmitContext ec)
762                 {
763                         if (Expr != null) {
764                                 Expr.Emit (ec);
765
766                                 if (unwind_protect)
767                                         ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
768                         }
769
770                         if (unwind_protect)
771                                 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
772                         else
773                                 ec.ig.Emit (OpCodes.Ret);
774                 }
775
776                 protected override void CloneTo (CloneContext clonectx, Statement t)
777                 {
778                         Return target = (Return) t;
779
780                         target.Expr = Expr.Clone (clonectx);
781                 }
782         }
783
784         public class Goto : Statement {
785                 string target;
786                 LabeledStatement label;
787                 bool unwind_protect;
788                 
789                 public override bool Resolve (EmitContext ec)
790                 {
791                         int errors = Report.Errors;
792                         unwind_protect = ec.CurrentBranching.AddGotoOrigin (ec.CurrentBranching.CurrentUsageVector, this);
793                         ec.CurrentBranching.CurrentUsageVector.Goto ();
794                         return errors == Report.Errors;
795                 }
796                 
797                 public Goto (string label, Location l)
798                 {
799                         loc = l;
800                         target = label;
801                 }
802
803                 public string Target {
804                         get { return target; }
805                 }
806
807                 public void SetResolvedTarget (LabeledStatement label)
808                 {
809                         this.label = label;
810                         label.AddReference ();
811                 }
812
813                 protected override void DoEmit (EmitContext ec)
814                 {
815                         if (label == null)
816                                 throw new InternalErrorException ("goto emitted before target resolved");
817                         Label l = label.LabelTarget (ec);
818                         ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
819                 }
820         }
821
822         public class LabeledStatement : Statement {
823                 string name;
824                 bool defined;
825                 bool referenced;
826                 Label label;
827                 ILGenerator ig;
828
829                 FlowBranching.UsageVector vectors;
830                 
831                 public LabeledStatement (string name, Location l)
832                 {
833                         this.name = name;
834                         this.loc = l;
835                 }
836
837                 public Label LabelTarget (EmitContext ec)
838                 {
839                         if (defined)
840                                 return label;
841                         ig = ec.ig;
842                         label = ec.ig.DefineLabel ();
843                         defined = true;
844
845                         return label;
846                 }
847
848                 public string Name {
849                         get { return name; }
850                 }
851
852                 public bool IsDefined {
853                         get { return defined; }
854                 }
855
856                 public bool HasBeenReferenced {
857                         get { return referenced; }
858                 }
859
860                 public FlowBranching.UsageVector JumpOrigins {
861                         get { return vectors; }
862                 }
863
864                 public void AddUsageVector (FlowBranching.UsageVector vector)
865                 {
866                         vector = vector.Clone ();
867                         vector.Next = vectors;
868                         vectors = vector;
869                 }
870
871                 public override bool Resolve (EmitContext ec)
872                 {
873                         // this flow-branching will be terminated when the surrounding block ends
874                         ec.StartFlowBranching (this);
875                         return true;
876                 }
877
878                 protected override void DoEmit (EmitContext ec)
879                 {
880                         if (ig != null && ig != ec.ig)
881                                 throw new InternalErrorException ("cannot happen");
882                         LabelTarget (ec);
883                         ec.ig.MarkLabel (label);
884                 }
885
886                 public void AddReference ()
887                 {
888                         referenced = true;
889                 }
890         }
891         
892
893         /// <summary>
894         ///   `goto default' statement
895         /// </summary>
896         public class GotoDefault : Statement {
897                 
898                 public GotoDefault (Location l)
899                 {
900                         loc = l;
901                 }
902
903                 public override bool Resolve (EmitContext ec)
904                 {
905                         ec.CurrentBranching.CurrentUsageVector.Goto ();
906                         return true;
907                 }
908
909                 protected override void DoEmit (EmitContext ec)
910                 {
911                         if (ec.Switch == null){
912                                 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
913                                 return;
914                         }
915
916                         if (!ec.Switch.GotDefault){
917                                 FlowBranchingBlock.Error_UnknownLabel (loc, "default");
918                                 return;
919                         }
920                         ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
921                 }
922         }
923
924         /// <summary>
925         ///   `goto case' statement
926         /// </summary>
927         public class GotoCase : Statement {
928                 Expression expr;
929                 SwitchLabel sl;
930                 
931                 public GotoCase (Expression e, Location l)
932                 {
933                         expr = e;
934                         loc = l;
935                 }
936
937                 public override bool Resolve (EmitContext ec)
938                 {
939                         if (ec.Switch == null){
940                                 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
941                                 return false;
942                         }
943
944                         expr = expr.Resolve (ec);
945                         if (expr == null)
946                                 return false;
947
948                         Constant c = expr as Constant;
949                         if (c == null) {
950                                 Error (150, "A constant value is expected");
951                                 return false;
952                         }
953
954                         Type type = ec.Switch.SwitchType;
955                         if (!Convert.ImplicitStandardConversionExists (c, type))
956                                 Report.Warning (469, 2, loc, "The `goto case' value is not implicitly " +
957                                                 "convertible to type `{0}'", TypeManager.CSharpName (type));
958
959                         bool fail = false;
960                         object val = c.GetValue ();
961                         if ((val != null) && (c.Type != type) && (c.Type != TypeManager.object_type))
962                                 val = TypeManager.ChangeType (val, type, out fail);
963
964                         if (fail) {
965                                 Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
966                                               c.GetSignatureForError (), TypeManager.CSharpName (type));
967                                 return false;
968                         }
969
970                         if (val == null)
971                                 val = SwitchLabel.NullStringCase;
972                                         
973                         sl = (SwitchLabel) ec.Switch.Elements [val];
974
975                         if (sl == null){
976                                 FlowBranchingBlock.Error_UnknownLabel (loc, "case " + 
977                                         (c.GetValue () == null ? "null" : val.ToString ()));
978                                 return false;
979                         }
980
981                         ec.CurrentBranching.CurrentUsageVector.Goto ();
982                         return true;
983                 }
984
985                 protected override void DoEmit (EmitContext ec)
986                 {
987                         ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
988                 }
989
990                 protected override void CloneTo (CloneContext clonectx, Statement t)
991                 {
992                         GotoCase target = (GotoCase) t;
993
994                         target.expr = expr.Clone (clonectx);
995                         target.sl = sl.Clone (clonectx);
996                 }
997         }
998         
999         public class Throw : Statement {
1000                 Expression expr;
1001                 
1002                 public Throw (Expression expr, Location l)
1003                 {
1004                         this.expr = expr;
1005                         loc = l;
1006                 }
1007
1008                 public override bool Resolve (EmitContext ec)
1009                 {
1010                         ec.CurrentBranching.CurrentUsageVector.Goto ();
1011
1012                         if (expr != null){
1013                                 expr = expr.Resolve (ec);
1014                                 if (expr == null)
1015                                         return false;
1016
1017                                 ExprClass eclass = expr.eclass;
1018
1019                                 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
1020                                         eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
1021                                         expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
1022                                         return false;
1023                                 }
1024
1025                                 Type t = expr.Type;
1026                                 
1027                                 if ((t != TypeManager.exception_type) &&
1028                                     !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
1029                                     !(expr is NullLiteral)) {
1030                                         Error (155,
1031                                                 "The type caught or thrown must be derived " +
1032                                                 "from System.Exception");
1033                                         return false;
1034                                 }
1035                                 return true;
1036                         }
1037
1038                         if (!ec.InCatch) {
1039                                 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
1040                                 return false;
1041                         }
1042
1043                         if (ec.InFinally) {
1044                                 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
1045                                 return false;
1046                         }
1047                         return true;
1048                 }
1049                         
1050                 protected override void DoEmit (EmitContext ec)
1051                 {
1052                         if (expr == null)
1053                                 ec.ig.Emit (OpCodes.Rethrow);
1054                         else {
1055                                 expr.Emit (ec);
1056
1057                                 ec.ig.Emit (OpCodes.Throw);
1058                         }
1059                 }
1060
1061                 protected override void CloneTo (CloneContext clonectx, Statement t)
1062                 {
1063                         Throw target = (Throw) t;
1064
1065                         target.expr = expr.Clone (clonectx);
1066                 }
1067         }
1068
1069         public class Break : Statement {
1070                 
1071                 public Break (Location l)
1072                 {
1073                         loc = l;
1074                 }
1075
1076                 bool unwind_protect;
1077
1078                 public override bool Resolve (EmitContext ec)
1079                 {
1080                         int errors = Report.Errors;
1081                         unwind_protect = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1082                         ec.CurrentBranching.CurrentUsageVector.Goto ();
1083                         return errors == Report.Errors;
1084                 }
1085
1086                 protected override void DoEmit (EmitContext ec)
1087                 {
1088                         ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
1089                 }
1090         }
1091
1092         public class Continue : Statement {
1093                 
1094                 public Continue (Location l)
1095                 {
1096                         loc = l;
1097                 }
1098
1099                 bool unwind_protect;
1100
1101                 public override bool Resolve (EmitContext ec)
1102                 {
1103                         int errors = Report.Errors;
1104                         unwind_protect = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1105                         ec.CurrentBranching.CurrentUsageVector.Goto ();
1106                         return errors == Report.Errors;
1107                 }
1108
1109                 protected override void DoEmit (EmitContext ec)
1110                 {
1111                         ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
1112                 }
1113         }
1114
1115         public abstract class Variable
1116         {
1117                 public abstract Type Type {
1118                         get;
1119                 }
1120
1121                 public abstract bool HasInstance {
1122                         get;
1123                 }
1124
1125                 public abstract bool NeedsTemporary {
1126                         get;
1127                 }
1128
1129                 public abstract void EmitInstance (EmitContext ec);
1130
1131                 public abstract void Emit (EmitContext ec);
1132
1133                 public abstract void EmitAssign (EmitContext ec);
1134
1135                 public abstract void EmitAddressOf (EmitContext ec);
1136         }
1137
1138         public interface IKnownVariable {
1139                 Block Block { get; }
1140                 Location Location { get; }
1141         }
1142
1143         //
1144         // The information about a user-perceived local variable
1145         //
1146         public class LocalInfo : IKnownVariable {
1147                 public Expression Type;
1148
1149                 public Type VariableType;
1150                 public readonly string Name;
1151                 public readonly Location Location;
1152                 public readonly Block Block;
1153
1154                 public VariableInfo VariableInfo;
1155
1156                 Variable var;
1157                 public Variable Variable {
1158                         get { return var; }
1159                 }
1160
1161                 [Flags]
1162                 enum Flags : byte {
1163                         Used = 1,
1164                         ReadOnly = 2,
1165                         Pinned = 4,
1166                         IsThis = 8,
1167                         Captured = 16,
1168                         AddressTaken = 32,
1169                         CompilerGenerated = 64,
1170                         IsConstant = 128
1171                 }
1172
1173                 public enum ReadOnlyContext: byte {
1174                         Using,
1175                         Foreach,
1176                         Fixed
1177                 }
1178
1179                 Flags flags;
1180                 ReadOnlyContext ro_context;
1181                 LocalBuilder builder;
1182                 
1183                 public LocalInfo (Expression type, string name, Block block, Location l)
1184                 {
1185                         Type = type;
1186                         Name = name;
1187                         Block = block;
1188                         Location = l;
1189                 }
1190
1191                 public LocalInfo (DeclSpace ds, Block block, Location l)
1192                 {
1193                         VariableType = ds.IsGeneric ? ds.CurrentType : ds.TypeBuilder;
1194                         Block = block;
1195                         Location = l;
1196                 }
1197
1198                 public void ResolveVariable (EmitContext ec)
1199                 {
1200                         Block theblock = Block;
1201                         if (theblock.ScopeInfo != null)
1202                                 var = theblock.ScopeInfo.GetCapturedVariable (this);
1203
1204                         if (var == null) {
1205                                 if (Pinned)
1206                                         //
1207                                         // This is needed to compile on both .NET 1.x and .NET 2.x
1208                                         // the later introduced `DeclareLocal (Type t, bool pinned)'
1209                                         //
1210                                         builder = TypeManager.DeclareLocalPinned (ec.ig, VariableType);
1211                                 else
1212                                         builder = ec.ig.DeclareLocal (VariableType);
1213
1214                                 var = new LocalVariable (this, builder);
1215                         }
1216                 }
1217
1218                 public void EmitSymbolInfo (EmitContext ec, string name)
1219                 {
1220                         if (builder != null)
1221                                 ec.DefineLocalVariable (name, builder);
1222                 }
1223
1224                 public bool IsThisAssigned (EmitContext ec)
1225                 {
1226                         if (VariableInfo == null)
1227                                 throw new Exception ();
1228
1229                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1230                                 return true;
1231
1232                         return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, ec.loc);
1233                 }
1234
1235                 public bool IsAssigned (EmitContext ec)
1236                 {
1237                         if (VariableInfo == null)
1238                                 throw new Exception ();
1239
1240                         return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1241                 }
1242
1243                 public bool Resolve (EmitContext ec)
1244                 {
1245                         if (VariableType == null) {
1246                                 TypeExpr texpr = Type.ResolveAsContextualType (ec, false);
1247                                 if (texpr == null)
1248                                         return false;
1249                                 
1250                                 VariableType = texpr.Type;
1251                         }
1252
1253                         if (TypeManager.IsGenericParameter (VariableType))
1254                                 return true;
1255
1256                         if (VariableType == TypeManager.void_type) {
1257                                 Expression.Error_VoidInvalidInTheContext (Location);
1258                                 return false;
1259                         }
1260
1261                         if (VariableType.IsAbstract && VariableType.IsSealed) {
1262                                 FieldBase.Error_VariableOfStaticClass (Location, Name, VariableType);
1263                                 return false;
1264                         }
1265
1266                         if (VariableType.IsPointer && !ec.InUnsafe)
1267                                 Expression.UnsafeError (Location);
1268
1269                         return true;
1270                 }
1271
1272                 public bool IsCaptured {
1273                         get { return (flags & Flags.Captured) != 0; }
1274                         set { flags |= Flags.Captured; }
1275                 }
1276
1277                 public bool IsConstant {
1278                         get { return (flags & Flags.IsConstant) != 0; }
1279                         set { flags |= Flags.IsConstant; }
1280                 }
1281
1282                 public bool AddressTaken {
1283                         get { return (flags & Flags.AddressTaken) != 0; }
1284                         set { flags |= Flags.AddressTaken; }
1285                 }
1286
1287                 public bool CompilerGenerated {
1288                         get { return (flags & Flags.CompilerGenerated) != 0; }
1289                         set { flags |= Flags.CompilerGenerated; }
1290                 }
1291
1292                 public override string ToString ()
1293                 {
1294                         return String.Format ("LocalInfo ({0},{1},{2},{3})",
1295                                               Name, Type, VariableInfo, Location);
1296                 }
1297
1298                 public bool Used {
1299                         get { return (flags & Flags.Used) != 0; }
1300                         set { flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used)); }
1301                 }
1302
1303                 public bool ReadOnly {
1304                         get { return (flags & Flags.ReadOnly) != 0; }
1305                 }
1306
1307                 public void SetReadOnlyContext (ReadOnlyContext context)
1308                 {
1309                         flags |= Flags.ReadOnly;
1310                         ro_context = context;
1311                 }
1312
1313                 public string GetReadOnlyContext ()
1314                 {
1315                         if (!ReadOnly)
1316                                 throw new InternalErrorException ("Variable is not readonly");
1317
1318                         switch (ro_context) {
1319                                 case ReadOnlyContext.Fixed:
1320                                         return "fixed variable";
1321                                 case ReadOnlyContext.Foreach:
1322                                         return "foreach iteration variable";
1323                                 case ReadOnlyContext.Using:
1324                                         return "using variable";
1325                         }
1326                         throw new NotImplementedException ();
1327                 }
1328
1329                 //
1330                 // Whether the variable is pinned, if Pinned the variable has been 
1331                 // allocated in a pinned slot with DeclareLocal.
1332                 //
1333                 public bool Pinned {
1334                         get { return (flags & Flags.Pinned) != 0; }
1335                         set { flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned); }
1336                 }
1337
1338                 public bool IsThis {
1339                         get { return (flags & Flags.IsThis) != 0; }
1340                         set { flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis); }
1341                 }
1342
1343                 Block IKnownVariable.Block {
1344                         get { return Block; }
1345                 }
1346
1347                 Location IKnownVariable.Location {
1348                         get { return Location; }
1349                 }
1350
1351                 protected class LocalVariable : Variable
1352                 {
1353                         public readonly LocalInfo LocalInfo;
1354                         LocalBuilder builder;
1355
1356                         public LocalVariable (LocalInfo local, LocalBuilder builder)
1357                         {
1358                                 this.LocalInfo = local;
1359                                 this.builder = builder;
1360                         }
1361
1362                         public override Type Type {
1363                                 get { return LocalInfo.VariableType; }
1364                         }
1365
1366                         public override bool HasInstance {
1367                                 get { return false; }
1368                         }
1369
1370                         public override bool NeedsTemporary {
1371                                 get { return false; }
1372                         }
1373
1374                         public override void EmitInstance (EmitContext ec)
1375                         {
1376                                 // Do nothing.
1377                         }
1378
1379                         public override void Emit (EmitContext ec)
1380                         {
1381                                 ec.ig.Emit (OpCodes.Ldloc, builder);
1382                         }
1383
1384                         public override void EmitAssign (EmitContext ec)
1385                         {
1386                                 ec.ig.Emit (OpCodes.Stloc, builder);
1387                         }
1388
1389                         public override void EmitAddressOf (EmitContext ec)
1390                         {
1391                                 ec.ig.Emit (OpCodes.Ldloca, builder);
1392                         }
1393                 }
1394
1395                 public LocalInfo Clone (CloneContext clonectx)
1396                 {
1397                         // Only this kind is created by the parser.
1398                         return new LocalInfo (Type.Clone (clonectx), Name, clonectx.LookupBlock (Block), Location);
1399                 }
1400         }
1401
1402         /// <summary>
1403         ///   Block represents a C# block.
1404         /// </summary>
1405         ///
1406         /// <remarks>
1407         ///   This class is used in a number of places: either to represent
1408         ///   explicit blocks that the programmer places or implicit blocks.
1409         ///
1410         ///   Implicit blocks are used as labels or to introduce variable
1411         ///   declarations.
1412         ///
1413         ///   Top-level blocks derive from Block, and they are called ToplevelBlock
1414         ///   they contain extra information that is not necessary on normal blocks.
1415         /// </remarks>
1416         public class Block : Statement {
1417                 public Block    Parent;
1418                 public readonly Location  StartLocation;
1419                 public Location EndLocation = Location.Null;
1420
1421                 public ExplicitBlock Explicit;
1422                 public ToplevelBlock Toplevel;
1423
1424                 [Flags]
1425                 public enum Flags : byte {
1426                         Unchecked = 1,
1427                         BlockUsed = 2,
1428                         VariablesInitialized = 4,
1429                         HasRet = 8,
1430                         IsDestructor = 16,
1431                         Unsafe = 32,
1432                         HasVarargs = 64, // Used in ToplevelBlock
1433                         IsIterator = 128
1434                 }
1435                 protected Flags flags;
1436
1437                 public bool Unchecked {
1438                         get { return (flags & Flags.Unchecked) != 0; }
1439                         set { flags |= Flags.Unchecked; }
1440                 }
1441
1442                 public bool Unsafe {
1443                         get { return (flags & Flags.Unsafe) != 0; }
1444                         set { flags |= Flags.Unsafe; }
1445                 }
1446
1447                 //
1448                 // The statements in this block
1449                 //
1450                 protected ArrayList statements;
1451                 protected int current_statement;
1452                 int num_statements;
1453
1454                 //
1455                 // An array of Blocks.  We keep track of children just
1456                 // to generate the local variable declarations.
1457                 //
1458                 // Statements and child statements are handled through the
1459                 // statements.
1460                 //
1461                 ArrayList children;
1462
1463                 //
1464                 // Labels.  (label, block) pairs.
1465                 //
1466                 Hashtable labels;
1467
1468                 //
1469                 // Keeps track of (name, type) pairs
1470                 //
1471                 IDictionary variables;
1472
1473                 //
1474                 // Keeps track of constants
1475                 Hashtable constants;
1476
1477                 //
1478                 // Temporary variables.
1479                 //
1480                 ArrayList temporary_variables;
1481                 
1482                 //
1483                 // If this is a switch section, the enclosing switch block.
1484                 //
1485                 Block switch_block;
1486
1487                 ExpressionStatement scope_init;
1488
1489                 ArrayList anonymous_children;
1490
1491                 protected static int id;
1492
1493                 int this_id;
1494                 
1495                 public Block (Block parent)
1496                         : this (parent, (Flags) 0, Location.Null, Location.Null)
1497                 { }
1498
1499                 public Block (Block parent, Flags flags)
1500                         : this (parent, flags, Location.Null, Location.Null)
1501                 { }
1502
1503                 public Block (Block parent, Location start, Location end)
1504                         : this (parent, (Flags) 0, start, end)
1505                 { }
1506
1507                 public Block (Block parent, Flags flags, Location start, Location end)
1508                 {
1509                         if (parent != null) {
1510                                 parent.AddChild (this);
1511
1512                                 // the appropriate constructors will fixup these fields
1513                                 Toplevel = parent.Toplevel;
1514                                 Explicit = parent.Explicit;
1515                         }
1516                         
1517                         this.Parent = parent;
1518                         this.flags = flags;
1519                         this.StartLocation = start;
1520                         this.EndLocation = end;
1521                         this.loc = start;
1522                         this_id = id++;
1523                         statements = new ArrayList ();
1524                 }
1525
1526                 public Block CreateSwitchBlock (Location start)
1527                 {
1528                         // FIXME: should this be implicit?
1529                         Block new_block = new ExplicitBlock (this, start, start);
1530                         new_block.switch_block = this;
1531                         return new_block;
1532                 }
1533
1534                 public int ID {
1535                         get { return this_id; }
1536                 }
1537
1538                 public IDictionary Variables {
1539                         get {
1540                                 if (variables == null)
1541                                         variables = new ListDictionary ();
1542                                 return variables;
1543                         }
1544                 }
1545
1546                 void AddChild (Block b)
1547                 {
1548                         if (children == null)
1549                                 children = new ArrayList ();
1550                         
1551                         children.Add (b);
1552                 }
1553
1554                 public void SetEndLocation (Location loc)
1555                 {
1556                         EndLocation = loc;
1557                 }
1558
1559                 protected static void Error_158 (string name, Location loc)
1560                 {
1561                         Report.Error (158, loc, "The label `{0}' shadows another label " +
1562                                       "by the same name in a contained scope", name);
1563                 }
1564
1565                 /// <summary>
1566                 ///   Adds a label to the current block. 
1567                 /// </summary>
1568                 ///
1569                 /// <returns>
1570                 ///   false if the name already exists in this block. true
1571                 ///   otherwise.
1572                 /// </returns>
1573                 ///
1574                 public bool AddLabel (LabeledStatement target)
1575                 {
1576                         if (switch_block != null)
1577                                 return switch_block.AddLabel (target);
1578
1579                         string name = target.Name;
1580
1581                         Block cur = this;
1582                         while (cur != null) {
1583                                 LabeledStatement s = cur.DoLookupLabel (name);
1584                                 if (s != null) {
1585                                         Report.SymbolRelatedToPreviousError (s.loc, s.Name);
1586                                         Report.Error (140, target.loc, "The label `{0}' is a duplicate", name);
1587                                         return false;
1588                                 }
1589
1590                                 if (this == Explicit)
1591                                         break;
1592
1593                                 cur = cur.Parent;
1594                         }
1595
1596                         while (cur != null) {
1597                                 if (cur.DoLookupLabel (name) != null) {
1598                                         Error_158 (name, target.loc);
1599                                         return false;
1600                                 }
1601
1602                                 if (children != null) {
1603                                         foreach (Block b in children) {
1604                                                 LabeledStatement s = b.DoLookupLabel (name);
1605                                                 if (s == null)
1606                                                         continue;
1607
1608                                                 Report.SymbolRelatedToPreviousError (s.loc, s.Name);
1609                                                 Error_158 (name, target.loc);
1610                                                 return false;
1611                                         }
1612                                 }
1613
1614                                 cur = cur.Parent;
1615                         }
1616
1617                         Toplevel.CheckError158 (name, target.loc);
1618
1619                         if (labels == null)
1620                                 labels = new Hashtable ();
1621
1622                         labels.Add (name, target);
1623                         return true;
1624                 }
1625
1626                 public LabeledStatement LookupLabel (string name)
1627                 {
1628                         LabeledStatement s = DoLookupLabel (name);
1629                         if (s != null)
1630                                 return s;
1631
1632                         if (children == null)
1633                                 return null;
1634
1635                         foreach (Block child in children) {
1636                                 if (Explicit != child.Explicit)
1637                                         continue;
1638
1639                                 s = child.LookupLabel (name);
1640                                 if (s != null)
1641                                         return s;
1642                         }
1643
1644                         return null;
1645                 }
1646
1647                 LabeledStatement DoLookupLabel (string name)
1648                 {
1649                         if (switch_block != null)
1650                                 return switch_block.LookupLabel (name);
1651
1652                         if (labels != null)
1653                                 if (labels.Contains (name))
1654                                         return ((LabeledStatement) labels [name]);
1655
1656                         return null;
1657                 }
1658
1659                 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1660                 {
1661                         Block b = this;
1662                         IKnownVariable kvi = b.Explicit.GetKnownVariable (name);
1663                         while (kvi == null) {
1664                                 b = b.Explicit.Parent;
1665                                 if (b == null)
1666                                         return true;
1667                                 kvi = b.Explicit.GetKnownVariable (name);
1668                         }
1669
1670                         if (kvi.Block == b)
1671                                 return true;
1672
1673                         // Is kvi.Block nested inside 'b'
1674                         if (b.Explicit != kvi.Block.Explicit) {
1675                                 //
1676                                 // If a variable by the same name it defined in a nested block of this
1677                                 // block, we violate the invariant meaning in a block.
1678                                 //
1679                                 if (b == this) {
1680                                         Report.SymbolRelatedToPreviousError (kvi.Location, name);
1681                                         Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1682                                         return false;
1683                                 }
1684
1685                                 //
1686                                 // It's ok if the definition is in a nested subblock of b, but not
1687                                 // nested inside this block -- a definition in a sibling block
1688                                 // should not affect us.
1689                                 //
1690                                 return true;
1691                         }
1692
1693                         //
1694                         // Block 'b' and kvi.Block are the same textual block.
1695                         // However, different variables are extant.
1696                         //
1697                         // Check if the variable is in scope in both blocks.  We use
1698                         // an indirect check that depends on AddVariable doing its
1699                         // part in maintaining the invariant-meaning-in-block property.
1700                         //
1701                         if (e is VariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1702                                 return true;
1703
1704                         //
1705                         // Even though we detected the error when the name is used, we
1706                         // treat it as if the variable declaration was in error.
1707                         //
1708                         Report.SymbolRelatedToPreviousError (loc, name);
1709                         Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1710                         return false;
1711                 }
1712
1713                 public LocalInfo AddVariable (Expression type, string name, Location l)
1714                 {
1715                         LocalInfo vi = GetLocalInfo (name);
1716                         if (vi != null) {
1717                                 Report.SymbolRelatedToPreviousError (vi.Location, name);
1718                                 if (Explicit == vi.Block.Explicit)
1719                                         Report.Error (128, l,
1720                                                 "A local variable named `{0}' is already defined in this scope", name);
1721                                 else
1722                                         Error_AlreadyDeclared (l, name, "parent");
1723                                 return null;
1724                         }
1725
1726                         ToplevelParameterInfo pi = Toplevel.GetParameterInfo (name);
1727                         if (pi != null) {
1728                                 Report.SymbolRelatedToPreviousError (pi.Location, name);
1729                                 Error_AlreadyDeclared (loc, name,
1730                                         pi.Block == Toplevel ? "method argument" : "parent or current");
1731                         }
1732
1733                         IKnownVariable kvi = Explicit.GetKnownVariable (name);
1734                         if (kvi != null) {
1735                                 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1736                                 Error_AlreadyDeclared (l, name, "child");
1737                                 return null;
1738                         }
1739
1740                         vi = new LocalInfo (type, name, this, l);
1741                         Variables.Add (name, vi);
1742                         Explicit.AddKnownVariable (name, vi);
1743
1744                         if ((flags & Flags.VariablesInitialized) != 0)
1745                                 throw new InternalErrorException ("block has already been resolved");
1746
1747                         return vi;
1748                 }
1749
1750                 protected static void Error_AlreadyDeclared (Location loc, string var, string reason)
1751                 {
1752                         Report.Error (136, loc, "A local variable named `{0}' cannot be declared " +
1753                                       "in this scope because it would give a different meaning " +
1754                                       "to `{0}', which is already used in a `{1}' scope " +
1755                                       "to denote something else", var, reason);
1756                 }
1757
1758                 public bool AddConstant (Expression type, string name, Expression value, Location l)
1759                 {
1760                         if (AddVariable (type, name, l) == null)
1761                                 return false;
1762                         
1763                         if (constants == null)
1764                                 constants = new Hashtable ();
1765
1766                         constants.Add (name, value);
1767
1768                         // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1769                         Use ();
1770                         return true;
1771                 }
1772
1773                 static int next_temp_id = 0;
1774
1775                 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1776                 {
1777                         Report.Debug (64, "ADD TEMPORARY", this, Toplevel, loc);
1778
1779                         if (temporary_variables == null)
1780                                 temporary_variables = new ArrayList ();
1781
1782                         int id = ++next_temp_id;
1783                         string name = "$s_" + id.ToString ();
1784
1785                         LocalInfo li = new LocalInfo (te, name, this, loc);
1786                         li.CompilerGenerated = true;
1787                         temporary_variables.Add (li);
1788                         return li;
1789                 }
1790
1791                 public LocalInfo GetLocalInfo (string name)
1792                 {
1793                         for (Block b = this; b != null; b = b.Parent) {
1794                                 if (b.variables != null) {
1795                                         LocalInfo ret = b.variables [name] as LocalInfo;
1796                                         if (ret != null)
1797                                                 return ret;
1798                                 }
1799                         }
1800                         return null;
1801                 }
1802
1803                 public Expression GetVariableType (string name)
1804                 {
1805                         LocalInfo vi = GetLocalInfo (name);
1806                         return vi == null ? null : vi.Type;
1807                 }
1808
1809                 public Expression GetConstantExpression (string name)
1810                 {
1811                         for (Block b = this; b != null; b = b.Parent) {
1812                                 if (b.constants != null) {
1813                                         Expression ret = b.constants [name] as Expression;
1814                                         if (ret != null)
1815                                                 return ret;
1816                                 }
1817                         }
1818                         return null;
1819                 }
1820                 
1821                 public void AddStatement (Statement s)
1822                 {
1823                         statements.Add (s);
1824                         flags |= Flags.BlockUsed;
1825                 }
1826                 
1827                 public void InsertStatementAfterCurrent (Statement statement)
1828                 {
1829                         statements.Insert (current_statement + 1, statement);
1830                         flags |= Flags.BlockUsed;
1831                 }
1832
1833                 public bool Used {
1834                         get { return (flags & Flags.BlockUsed) != 0; }
1835                 }
1836
1837                 public void Use ()
1838                 {
1839                         flags |= Flags.BlockUsed;
1840                 }
1841
1842                 public bool HasRet {
1843                         get { return (flags & Flags.HasRet) != 0; }
1844                 }
1845
1846                 public bool IsDestructor {
1847                         get { return (flags & Flags.IsDestructor) != 0; }
1848                 }
1849
1850                 public void SetDestructor ()
1851                 {
1852                         flags |= Flags.IsDestructor;
1853                 }
1854
1855                 int assignable_slots;
1856                 public int AssignableSlots {
1857                         get {
1858                                 if ((flags & Flags.VariablesInitialized) == 0)
1859                                         throw new Exception ("Variables have not been initialized yet");
1860                                 return assignable_slots;
1861                         }
1862                 }
1863
1864                 protected ScopeInfo scope_info;
1865
1866                 public ScopeInfo ScopeInfo {
1867                         get { return scope_info; }
1868                 }
1869
1870                 public ScopeInfo CreateScopeInfo ()
1871                 {
1872                         if (scope_info == null)
1873                                 scope_info = ScopeInfo.CreateScope (this);
1874
1875                         return scope_info;
1876                 }
1877
1878                 public ArrayList AnonymousChildren {
1879                         get { return anonymous_children; }
1880                 }
1881
1882                 public void AddAnonymousChild (ToplevelBlock b)
1883                 {
1884                         if (anonymous_children == null)
1885                                 anonymous_children = new ArrayList ();
1886
1887                         anonymous_children.Add (b);
1888                 }
1889
1890                 void DoResolveConstants (EmitContext ec)
1891                 {
1892                         if (constants == null)
1893                                 return;
1894
1895                         if (variables == null)
1896                                 throw new InternalErrorException ("cannot happen");
1897
1898                         foreach (DictionaryEntry de in variables) {
1899                                 string name = (string) de.Key;
1900                                 LocalInfo vi = (LocalInfo) de.Value;
1901                                 Type variable_type = vi.VariableType;
1902
1903                                 if (variable_type == null)
1904                                         continue;
1905
1906                                 Expression cv = (Expression) constants [name];
1907                                 if (cv == null)
1908                                         continue;
1909
1910                                 // Don't let 'const int Foo = Foo;' succeed.
1911                                 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
1912                                 // which in turn causes the 'must be constant' error to be triggered.
1913                                 constants.Remove (name);
1914
1915                                 if (!Const.IsConstantTypeValid (variable_type)) {
1916                                         Const.Error_InvalidConstantType (variable_type, loc);
1917                                         continue;
1918                                 }
1919
1920                                 ec.CurrentBlock = this;
1921                                 Expression e;
1922                                 using (ec.With (EmitContext.Flags.ConstantCheckState, (flags & Flags.Unchecked) == 0)) {
1923                                         e = cv.Resolve (ec);
1924                                 }
1925                                 if (e == null)
1926                                         continue;
1927
1928                                 Constant ce = e as Constant;
1929                                 if (ce == null) {
1930                                         Const.Error_ExpressionMustBeConstant (vi.Location, name);
1931                                         continue;
1932                                 }
1933
1934                                 e = ce.ConvertImplicitly (variable_type);
1935                                 if (e == null) {
1936                                         if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue)
1937                                                 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
1938                                         else
1939                                                 ce.Error_ValueCannotBeConverted (null, vi.Location, variable_type, false);
1940                                         continue;
1941                                 }
1942
1943                                 constants.Add (name, e);
1944                                 vi.IsConstant = true;
1945                         }
1946                 }
1947
1948                 protected void ResolveMeta (EmitContext ec, int offset)
1949                 {
1950                         Report.Debug (64, "BLOCK RESOLVE META", this, Parent);
1951
1952                         // If some parent block was unsafe, we remain unsafe even if this block
1953                         // isn't explicitly marked as such.
1954                         using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
1955                                 flags |= Flags.VariablesInitialized;
1956
1957                                 if (variables != null) {
1958                                         foreach (LocalInfo li in variables.Values) {
1959                                                 if (!li.Resolve (ec))
1960                                                         continue;
1961                                                 li.VariableInfo = new VariableInfo (li, offset);
1962                                                 offset += li.VariableInfo.Length;
1963                                         }
1964                                 }
1965                                 assignable_slots = offset;
1966
1967                                 DoResolveConstants (ec);
1968
1969                                 if (children == null)
1970                                         return;
1971                                 foreach (Block b in children)
1972                                         b.ResolveMeta (ec, offset);
1973                         }
1974                 }
1975
1976                 //
1977                 // Emits the local variable declarations for a block
1978                 //
1979                 public virtual void EmitMeta (EmitContext ec)
1980                 {
1981                         Report.Debug (64, "BLOCK EMIT META", this, Parent, Toplevel, ScopeInfo, ec);
1982                         if (ScopeInfo != null) {
1983                                 scope_init = ScopeInfo.GetScopeInitializer (ec);
1984                                 Report.Debug (64, "BLOCK EMIT META #1", this, Toplevel, ScopeInfo,
1985                                               ec, scope_init);
1986                         }
1987
1988                         if (variables != null){
1989                                 foreach (LocalInfo vi in variables.Values)
1990                                         vi.ResolveVariable (ec);
1991                         }
1992
1993                         if (temporary_variables != null) {
1994                                 foreach (LocalInfo vi in temporary_variables)
1995                                         vi.ResolveVariable (ec);
1996                         }
1997
1998                         if (children != null){
1999                                 foreach (Block b in children)
2000                                         b.EmitMeta (ec);
2001                         }
2002                 }
2003
2004                 void UsageWarning (FlowBranching.UsageVector vector)
2005                 {
2006                         string name;
2007
2008                         if ((variables != null) && (RootContext.WarningLevel >= 3)) {
2009                                 foreach (DictionaryEntry de in variables){
2010                                         LocalInfo vi = (LocalInfo) de.Value;
2011
2012                                         if (vi.Used)
2013                                                 continue;
2014
2015                                         name = (string) de.Key;
2016
2017                                         // vi.VariableInfo can be null for 'catch' variables
2018                                         if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
2019                                                 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
2020                                         } else {
2021                                                 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
2022                                         }
2023                                 }
2024                         }
2025                 }
2026
2027                 bool unreachable_shown;
2028                 bool unreachable;
2029
2030                 private void CheckPossibleMistakenEmptyStatement (Statement s)
2031                 {
2032                         Statement body;
2033
2034                         // Some statements are wrapped by a Block. Since
2035                         // others' internal could be changed, here I treat
2036                         // them as possibly wrapped by Block equally.
2037                         Block b = s as Block;
2038                         if (b != null && b.statements.Count == 1)
2039                                 s = (Statement) b.statements [0];
2040
2041                         if (s is Lock)
2042                                 body = ((Lock) s).Statement;
2043                         else if (s is For)
2044                                 body = ((For) s).Statement;
2045                         else if (s is Foreach)
2046                                 body = ((Foreach) s).Statement;
2047                         else if (s is While)
2048                                 body = ((While) s).Statement;
2049                         else if (s is Using)
2050                                 body = ((Using) s).Statement;
2051                         else if (s is Fixed)
2052                                 body = ((Fixed) s).Statement;
2053                         else
2054                                 return;
2055
2056                         if (body == null || body is EmptyStatement)
2057                                 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
2058                 }
2059
2060                 public override bool Resolve (EmitContext ec)
2061                 {
2062                         Block prev_block = ec.CurrentBlock;
2063                         bool ok = true;
2064
2065                         int errors = Report.Errors;
2066
2067                         ec.CurrentBlock = this;
2068                         ec.StartFlowBranching (this);
2069
2070                         Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
2071
2072                         //
2073                         // This flag is used to notate nested statements as unreachable from the beginning of this block.
2074                         // For the purposes of this resolution, it doesn't matter that the whole block is unreachable 
2075                         // from the beginning of the function.  The outer Resolve() that detected the unreachability is
2076                         // responsible for handling the situation.
2077                         //
2078                         for (current_statement = 0; current_statement < statements.Count; current_statement++) {
2079                                 Statement s = (Statement) statements [current_statement];
2080                                 // Check possible empty statement (CS0642)
2081                                 if (RootContext.WarningLevel >= 3 &&
2082                                         current_statement + 1 < statements.Count &&
2083                                                 statements [current_statement + 1] is Block)
2084                                         CheckPossibleMistakenEmptyStatement (s);
2085
2086                                 //
2087                                 // Warn if we detect unreachable code.
2088                                 //
2089                                 if (unreachable) {
2090                                         if (s is EmptyStatement)
2091                                                 continue;
2092
2093                                         if (s is Block)
2094                                                 ((Block) s).unreachable = true;
2095
2096                                         if (!unreachable_shown && !(s is LabeledStatement)) {
2097                                                 Report.Warning (162, 2, s.loc, "Unreachable code detected");
2098                                                 unreachable_shown = true;
2099                                         }
2100                                 }
2101
2102                                 //
2103                                 // Note that we're not using ResolveUnreachable() for unreachable
2104                                 // statements here.  ResolveUnreachable() creates a temporary
2105                                 // flow branching and kills it afterwards.  This leads to problems
2106                                 // if you have two unreachable statements where the first one
2107                                 // assigns a variable and the second one tries to access it.
2108                                 //
2109
2110                                 if (!s.Resolve (ec)) {
2111                                         ok = false;
2112                                         statements [current_statement] = EmptyStatement.Value;
2113                                         continue;
2114                                 }
2115
2116                                 if (unreachable && !(s is LabeledStatement) && !(s is Block))
2117                                         statements [current_statement] = EmptyStatement.Value;
2118
2119                                 num_statements = current_statement + 1;
2120
2121                                 unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
2122                                 if (unreachable && s is LabeledStatement)
2123                                         throw new InternalErrorException ("should not happen");
2124                         }
2125
2126                         Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
2127                                       ec.CurrentBranching, statements.Count, num_statements);
2128
2129                         if (!ok)
2130                                 return false;
2131
2132                         while (ec.CurrentBranching is FlowBranchingLabeled)
2133                                 ec.EndFlowBranching ();
2134
2135                         FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
2136
2137                         ec.CurrentBlock = prev_block;
2138
2139                         // If we're a non-static `struct' constructor which doesn't have an
2140                         // initializer, then we must initialize all of the struct's fields.
2141                         if (this == Toplevel && !Toplevel.IsThisAssigned (ec) && !vector.IsUnreachable)
2142                                 ok = false;
2143
2144                         if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2145                                 foreach (LabeledStatement label in labels.Values)
2146                                         if (!label.HasBeenReferenced)
2147                                                 Report.Warning (164, 2, label.loc,
2148                                                                 "This label has not been referenced");
2149                         }
2150
2151                         Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2152
2153                         if (vector.IsUnreachable)
2154                                 flags |= Flags.HasRet;
2155
2156                         if (ok && (errors == Report.Errors)) {
2157                                 if (RootContext.WarningLevel >= 3)
2158                                         UsageWarning (vector);
2159                         }
2160
2161                         return ok;
2162                 }
2163
2164                 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2165                 {
2166                         unreachable_shown = true;
2167                         unreachable = true;
2168
2169                         if (warn)
2170                                 Report.Warning (162, 2, loc, "Unreachable code detected");
2171
2172                         ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2173                         bool ok = Resolve (ec);
2174                         ec.KillFlowBranching ();
2175
2176                         return ok;
2177                 }
2178                 
2179                 protected override void DoEmit (EmitContext ec)
2180                 {
2181                         for (int ix = 0; ix < num_statements; ix++){
2182                                 Statement s = (Statement) statements [ix];
2183                                 s.Emit (ec);
2184                         }
2185                 }
2186
2187                 public override void Emit (EmitContext ec)
2188                 {
2189                         Block prev_block = ec.CurrentBlock;
2190
2191                         ec.CurrentBlock = this;
2192
2193                         bool emit_debug_info = (CodeGen.SymbolWriter != null);
2194                         bool is_lexical_block = this == Explicit && Parent != null;
2195
2196                         if (emit_debug_info) {
2197                                 if (is_lexical_block)
2198                                         ec.BeginScope ();
2199                         }
2200                         ec.Mark (StartLocation, true);
2201                         if (scope_init != null)
2202                                 scope_init.EmitStatement (ec);
2203                         DoEmit (ec);
2204                         ec.Mark (EndLocation, true); 
2205
2206                         if (emit_debug_info) {
2207                                 if (is_lexical_block)
2208                                         ec.EndScope ();
2209
2210                                 if (variables != null) {
2211                                         foreach (DictionaryEntry de in variables) {
2212                                                 string name = (string) de.Key;
2213                                                 LocalInfo vi = (LocalInfo) de.Value;
2214
2215                                                 vi.EmitSymbolInfo (ec, name);
2216                                         }
2217                                 }
2218                         }
2219
2220                         ec.CurrentBlock = prev_block;
2221                 }
2222
2223                 public override string ToString ()
2224                 {
2225                         return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2226                 }
2227
2228                 protected override void CloneTo (CloneContext clonectx, Statement t)
2229                 {
2230                         Block target = (Block) t;
2231
2232                         clonectx.AddBlockMap (this, target);
2233
2234                         target.Toplevel = (ToplevelBlock) clonectx.LookupBlock (Toplevel);
2235                         target.Explicit = (ExplicitBlock) clonectx.LookupBlock (Explicit);
2236                         if (Parent != null)
2237                                 target.Parent = clonectx.LookupBlock (Parent);
2238                         
2239                         target.statements = new ArrayList ();
2240                         if (target.children != null){
2241                                 target.children = new ArrayList ();
2242                                 foreach (Block b in children){
2243                                         Block newblock = (Block) b.Clone (clonectx);
2244
2245                                         target.children.Add (newblock);
2246                                 }
2247                                 
2248                         }
2249
2250                         foreach (Statement s in statements)
2251                                 target.statements.Add (s.Clone (clonectx));
2252
2253                         if (variables != null){
2254                                 target.variables = new Hashtable ();
2255
2256                                 foreach (DictionaryEntry de in variables){
2257                                         LocalInfo newlocal = ((LocalInfo) de.Value).Clone (clonectx);
2258                                         target.variables [de.Key] = newlocal;
2259                                         clonectx.AddVariableMap ((LocalInfo) de.Value, newlocal);
2260                                 }
2261                         }
2262
2263                         //
2264                         // TODO: labels, switch_block, constants (?), anonymous_children
2265                         //
2266                 }
2267         }
2268
2269         public class ExplicitBlock : Block {
2270                 public ExplicitBlock (Block parent, Location start, Location end)
2271                         : this (parent, (Flags) 0, start, end)
2272                 {
2273                 }
2274
2275                 public ExplicitBlock (Block parent, Flags flags, Location start, Location end)
2276                         : base (parent, flags, start, end)
2277                 {
2278                         this.Explicit = this;
2279                 }
2280
2281                 Hashtable known_variables;
2282
2283                 // <summary>
2284                 //   Marks a variable with name @name as being used in this or a child block.
2285                 //   If a variable name has been used in a child block, it's illegal to
2286                 //   declare a variable with the same name in the current block.
2287                 // </summary>
2288                 internal void AddKnownVariable (string name, IKnownVariable info)
2289                 {
2290                         if (known_variables == null)
2291                                 known_variables = new Hashtable ();
2292
2293                         known_variables [name] = info;
2294
2295                         if (Parent != null)
2296                                 Parent.Explicit.AddKnownVariable (name, info);
2297                 }
2298
2299                 internal IKnownVariable GetKnownVariable (string name)
2300                 {
2301                         return known_variables == null ? null : (IKnownVariable) known_variables [name];
2302                 }
2303
2304                 protected override void CloneTo (CloneContext clonectx, Statement t)
2305                 {
2306                         ExplicitBlock target = (ExplicitBlock) t;
2307                         target.known_variables = null;
2308                         base.CloneTo (clonectx, t);
2309                 }
2310         }
2311
2312         public class ToplevelParameterInfo : IKnownVariable {
2313                 public readonly ToplevelBlock Block;
2314                 public readonly int Index;
2315                 public VariableInfo VariableInfo;
2316
2317                 Block IKnownVariable.Block {
2318                         get { return Block; }
2319                 }
2320                 public Parameter Parameter {
2321                         get { return Block.Parameters [Index]; }
2322                 }
2323                 public Location Location {
2324                         get { return Parameter.Location; }
2325                 }
2326
2327                 public ToplevelParameterInfo (ToplevelBlock block, int idx)
2328                 {
2329                         this.Block = block;
2330                         this.Index = idx;
2331                 }
2332         }
2333
2334         //
2335         // A toplevel block contains extra information, the split is done
2336         // only to separate information that would otherwise bloat the more
2337         // lightweight Block.
2338         //
2339         // In particular, this was introduced when the support for Anonymous
2340         // Methods was implemented. 
2341         // 
2342         public class ToplevelBlock : ExplicitBlock {
2343                 GenericMethod generic;
2344                 FlowBranchingToplevel top_level_branching;
2345                 AnonymousContainer anonymous_container;
2346                 RootScopeInfo root_scope;
2347
2348                 public bool HasVarargs {
2349                         get { return (flags & Flags.HasVarargs) != 0; }
2350                         set { flags |= Flags.HasVarargs; }
2351                 }
2352
2353                 public bool IsIterator {
2354                         get { return (flags & Flags.IsIterator) != 0; }
2355                 }
2356
2357                 //
2358                 // The parameters for the block.
2359                 //
2360                 Parameters parameters;
2361                 public Parameters Parameters {
2362                         get { return parameters; }
2363                 }
2364
2365                 public bool CompleteContexts (EmitContext ec)
2366                 {
2367                         Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS", this, Parent, root_scope);
2368
2369                         if (root_scope != null)
2370                                 root_scope.LinkScopes ();
2371
2372                         if (Parent == null && root_scope != null) {
2373                                 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS #1", this, root_scope);
2374
2375                                 if (root_scope.DefineType () == null)
2376                                         return false;
2377                                 if (!root_scope.ResolveType ())
2378                                         return false;
2379                                 if (!root_scope.ResolveMembers ())
2380                                         return false;
2381                                 if (!root_scope.DefineMembers ())
2382                                         return false;
2383                         }
2384
2385                         return true;
2386                 }
2387
2388                 public GenericMethod GenericMethod {
2389                         get { return generic; }
2390                 }
2391
2392                 public ToplevelBlock Container {
2393                         get { return Parent == null ? null : Parent.Toplevel; }
2394                 }
2395
2396                 public AnonymousContainer AnonymousContainer {
2397                         get { return anonymous_container; }
2398                         set { anonymous_container = value; }
2399                 }
2400
2401                 public ToplevelBlock (Block parent, Parameters parameters, Location start) :
2402                         this (parent, (Flags) 0, parameters, start)
2403                 {
2404                 }
2405
2406                 public ToplevelBlock (Block parent, Parameters parameters, GenericMethod generic, Location start) :
2407                         this (parent, parameters, start)
2408                 {
2409                         this.generic = generic;
2410                 }
2411                 
2412                 public ToplevelBlock (Parameters parameters, Location start) :
2413                         this (null, (Flags) 0, parameters, start)
2414                 {
2415                 }
2416
2417                 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2418                         this (null, flags, parameters, start)
2419                 {
2420                 }
2421
2422                 // We use 'Parent' to hook up to the containing block, but don't want to register the current block as a child.
2423                 // So, we use a two-stage setup -- first pass a null parent to the base constructor, and then override 'Parent'.
2424                 public ToplevelBlock (Block parent, Flags flags, Parameters parameters, Location start) :
2425                         base (null, flags, start, Location.Null)
2426                 {
2427                         this.Toplevel = this;
2428
2429                         this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2430                         this.Parent = parent;
2431                         if (parent != null)
2432                                 parent.AddAnonymousChild (this);
2433
2434                         if (this.parameters.Count != 0)
2435                                 ProcessParameters ();
2436                 }
2437
2438                 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2439                 {
2440                 }
2441
2442                 protected override void CloneTo (CloneContext clonectx, Statement t)
2443                 {
2444                         ToplevelBlock target = (ToplevelBlock) t;
2445                         base.CloneTo (clonectx, t);
2446
2447                         if (parameters.Count != 0)
2448                                 target.parameter_info = new ToplevelParameterInfo [parameters.Count];
2449                         for (int i = 0; i < parameters.Count; ++i)
2450                                 target.parameter_info [i] = new ToplevelParameterInfo (target, i);
2451                 }
2452
2453                 public bool CheckError158 (string name, Location loc)
2454                 {
2455                         if (AnonymousChildren != null) {
2456                                 foreach (ToplevelBlock child in AnonymousChildren) {
2457                                         if (!child.CheckError158 (name, loc))
2458                                                 return false;
2459                                 }
2460                         }
2461
2462                         for (ToplevelBlock c = Container; c != null; c = c.Container) {
2463                                 if (!c.DoCheckError158 (name, loc))
2464                                         return false;
2465                         }
2466
2467                         return true;
2468                 }
2469
2470                 ToplevelParameterInfo [] parameter_info;
2471                 void ProcessParameters ()
2472                 {
2473                         int n = parameters.Count;
2474                         parameter_info = new ToplevelParameterInfo [n];
2475                         for (int i = 0; i < n; ++i) {
2476                                 parameter_info [i] = new ToplevelParameterInfo (this, i);
2477
2478                                 string name = parameters [i].Name;
2479
2480                                 LocalInfo vi = GetLocalInfo (name);
2481                                 if (vi != null) {
2482                                         Report.SymbolRelatedToPreviousError (vi.Location, name);
2483                                         Error_AlreadyDeclared (loc, name, "parent or current");
2484                                         continue;
2485                                 }
2486
2487                                 ToplevelParameterInfo pi = Parent == null ? null : Parent.Toplevel.GetParameterInfo (name);
2488                                 if (pi != null) {
2489                                         Report.SymbolRelatedToPreviousError (pi.Location, name);
2490                                         Error_AlreadyDeclared (loc, name, "parent or current");
2491                                         continue;
2492                                 }
2493
2494                                 AddKnownVariable (name, parameter_info [i]);
2495                         }
2496
2497                         // mark this block as "used" so that we create local declarations in a sub-block
2498                         // FIXME: This appears to uncover a lot of bugs
2499                         //this.Use ();
2500                 }
2501
2502                 bool DoCheckError158 (string name, Location loc)
2503                 {
2504                         LabeledStatement s = LookupLabel (name);
2505                         if (s != null) {
2506                                 Report.SymbolRelatedToPreviousError (s.loc, s.Name);
2507                                 Error_158 (name, loc);
2508                                 return false;
2509                         }
2510
2511                         return true;
2512                 }
2513
2514                 public RootScopeInfo CreateRootScope (TypeContainer host)
2515                 {
2516                         if (root_scope != null)
2517                                 return root_scope;
2518
2519                         if (Container == null)
2520                                 root_scope = new RootScopeInfo (
2521                                         this, host, generic, StartLocation);
2522
2523                         if (scope_info != null)
2524                                 throw new InternalErrorException ();
2525
2526                         scope_info = root_scope;
2527                         return root_scope;
2528                 }
2529
2530                 public void CreateIteratorHost (RootScopeInfo root)
2531                 {
2532                         Report.Debug (64, "CREATE ITERATOR HOST", this, root, Parent, root_scope);
2533
2534                         if (Parent != null || root_scope != null)
2535                                 throw new InternalErrorException ();
2536
2537                         scope_info = root_scope = root;
2538                 }
2539
2540                 public RootScopeInfo RootScope {
2541                         get {
2542                                 if (root_scope != null)
2543                                         return root_scope;
2544                                 else if (Container != null)
2545                                         return Container.RootScope;
2546                                 else
2547                                         return null;
2548                         }
2549                 }
2550
2551                 public FlowBranchingToplevel TopLevelBranching {
2552                         get { return top_level_branching; }
2553                 }
2554
2555                 //
2556                 // This is used if anonymous methods are used inside an iterator
2557                 // (see 2test-22.cs for an example).
2558                 //
2559                 // The AnonymousMethod is created while parsing - at a time when we don't
2560                 // know yet that we're inside an iterator, so it's `Container' is initially
2561                 // null.  Later on, when resolving the iterator, we need to move the
2562                 // anonymous method into that iterator.
2563                 //
2564                 public void ReParent (ToplevelBlock new_parent)
2565                 {
2566                         if ((flags & Flags.VariablesInitialized) != 0)
2567                                 throw new InternalErrorException ("block has already been resolved");
2568
2569                         Parent = new_parent;
2570                 }
2571
2572                 //
2573                 // Returns a `ParameterReference' for the given name, or null if there
2574                 // is no such parameter
2575                 //
2576                 public ParameterReference GetParameterReference (string name, Location loc)
2577                 {
2578                         ToplevelParameterInfo p = GetParameterInfo (name);
2579                         return p == null ? null : new ParameterReference (this, p, loc);
2580                 }
2581
2582                 public ToplevelParameterInfo GetParameterInfo (string name)
2583                 {
2584                         int idx;
2585                         for (ToplevelBlock t = this; t != null; t = t.Container) {
2586                                 Parameter par = t.Parameters.GetParameterByName (name, out idx);
2587                                 if (par != null)
2588                                         return t.parameter_info [idx];
2589                         }
2590                         return null;
2591                 }
2592
2593                 //
2594                 // Whether the parameter named `name' is local to this block, 
2595                 // or false, if the parameter belongs to an encompassing block.
2596                 //
2597                 public bool IsLocalParameter (string name)
2598                 {
2599                         return Parameters.GetParameterByName (name) != null;
2600                 }
2601                 
2602                 //
2603                 // Whether the `name' is a parameter reference
2604                 //
2605                 public bool IsParameterReference (string name)
2606                 {
2607                         for (ToplevelBlock t = this; t != null; t = t.Container) {
2608                                 if (t.IsLocalParameter (name))
2609                                         return true;
2610                         }
2611                         return false;
2612                 }
2613
2614                 LocalInfo this_variable = null;
2615
2616                 // <summary>
2617                 //   Returns the "this" instance variable of this block.
2618                 //   See AddThisVariable() for more information.
2619                 // </summary>
2620                 public LocalInfo ThisVariable {
2621                         get { return this_variable; }
2622                 }
2623
2624
2625                 // <summary>
2626                 //   This is used by non-static `struct' constructors which do not have an
2627                 //   initializer - in this case, the constructor must initialize all of the
2628                 //   struct's fields.  To do this, we add a "this" variable and use the flow
2629                 //   analysis code to ensure that it's been fully initialized before control
2630                 //   leaves the constructor.
2631                 // </summary>
2632                 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2633                 {
2634                         if (this_variable == null) {
2635                                 this_variable = new LocalInfo (ds, this, l);
2636                                 this_variable.Used = true;
2637                                 this_variable.IsThis = true;
2638
2639                                 Variables.Add ("this", this_variable);
2640                         }
2641
2642                         return this_variable;
2643                 }
2644
2645                 public bool IsThisAssigned (EmitContext ec)
2646                 {
2647                         return this_variable == null || this_variable.IsThisAssigned (ec);
2648                 }
2649
2650                 public bool ResolveMeta (EmitContext ec, Parameters ip)
2651                 {
2652                         int errors = Report.Errors;
2653                         int orig_count = parameters.Count;
2654
2655                         if (top_level_branching != null)
2656                                 return true;
2657
2658                         if (ip != null)
2659                                 parameters = ip;
2660
2661                         // Assert: orig_count != parameter.Count => orig_count == 0
2662                         if (orig_count != 0 && orig_count != parameters.Count)
2663                                 throw new InternalErrorException ("parameter information mismatch");
2664
2665                         int offset = Parent == null ? 0 : Parent.AssignableSlots;
2666
2667                         for (int i = 0; i < orig_count; ++i) {
2668                                 Parameter.Modifier mod = parameters.ParameterModifier (i);
2669
2670                                 if ((mod & Parameter.Modifier.OUT) != Parameter.Modifier.OUT)
2671                                         continue;
2672
2673                                 VariableInfo vi = new VariableInfo (ip, i, offset);
2674                                 parameter_info [i].VariableInfo = vi;
2675                                 offset += vi.Length;
2676                         }
2677
2678                         ResolveMeta (ec, offset);
2679
2680                         top_level_branching = ec.StartFlowBranching (this);
2681
2682                         return Report.Errors == errors;
2683                 }
2684
2685                 // <summary>
2686                 //   Check whether all `out' parameters have been assigned.
2687                 // </summary>
2688                 public void CheckOutParameters (FlowBranching.UsageVector vector, Location loc)
2689                 {
2690                         if (vector.IsUnreachable)
2691                                 return;
2692
2693                         int n = parameter_info == null ? 0 : parameter_info.Length;
2694
2695                         for (int i = 0; i < n; i++) {
2696                                 VariableInfo var = parameter_info [i].VariableInfo;
2697
2698                                 if (var == null)
2699                                         continue;
2700
2701                                 if (vector.IsAssigned (var, false))
2702                                         continue;
2703
2704                                 Report.Error (177, loc, "The out parameter `{0}' must be assigned to before control leaves the current method",
2705                                         var.Name);
2706                         }
2707                 }
2708
2709                 public override void EmitMeta (EmitContext ec)
2710                 {
2711                         base.EmitMeta (ec);
2712                         parameters.ResolveVariable (this);
2713                 }
2714
2715                 public void MakeIterator (Iterator iterator)
2716                 {
2717                         flags |= Flags.IsIterator;
2718
2719                         Block block = new ExplicitBlock (this, StartLocation, EndLocation);
2720                         foreach (Statement stmt in statements)
2721                                 block.AddStatement (stmt);
2722                         statements = new ArrayList ();
2723                         statements.Add (new MoveNextStatement (iterator, block));
2724                 }
2725
2726                 protected class MoveNextStatement : Statement {
2727                         Iterator iterator;
2728                         Block block;
2729
2730                         public MoveNextStatement (Iterator iterator, Block block)
2731                         {
2732                                 this.iterator = iterator;
2733                                 this.block = block;
2734                                 this.loc = iterator.Location;
2735                         }
2736
2737                         public override bool Resolve (EmitContext ec)
2738                         {
2739                                 return block.Resolve (ec);
2740                         }
2741
2742                         protected override void DoEmit (EmitContext ec)
2743                         {
2744                                 iterator.EmitMoveNext (ec, block);
2745                         }
2746                 }
2747
2748                 public override string ToString ()
2749                 {
2750                         return String.Format ("{0} ({1}:{2}{3}:{4})", GetType (), ID, StartLocation,
2751                                               root_scope, anonymous_container != null ?
2752                                               anonymous_container.Scope : null);
2753                 }
2754         }
2755         
2756         public class SwitchLabel {
2757                 Expression label;
2758                 object converted;
2759                 Location loc;
2760
2761                 Label il_label;
2762                 bool  il_label_set;
2763                 Label il_label_code;
2764                 bool  il_label_code_set;
2765
2766                 public static readonly object NullStringCase = new object ();
2767
2768                 //
2769                 // if expr == null, then it is the default case.
2770                 //
2771                 public SwitchLabel (Expression expr, Location l)
2772                 {
2773                         label = expr;
2774                         loc = l;
2775                 }
2776
2777                 public Expression Label {
2778                         get {
2779                                 return label;
2780                         }
2781                 }
2782
2783                 public object Converted {
2784                         get {
2785                                 return converted;
2786                         }
2787                 }
2788
2789                 public Label GetILLabel (EmitContext ec)
2790                 {
2791                         if (!il_label_set){
2792                                 il_label = ec.ig.DefineLabel ();
2793                                 il_label_set = true;
2794                         }
2795                         return il_label;
2796                 }
2797
2798                 public Label GetILLabelCode (EmitContext ec)
2799                 {
2800                         if (!il_label_code_set){
2801                                 il_label_code = ec.ig.DefineLabel ();
2802                                 il_label_code_set = true;
2803                         }
2804                         return il_label_code;
2805                 }                               
2806                 
2807                 //
2808                 // Resolves the expression, reduces it to a literal if possible
2809                 // and then converts it to the requested type.
2810                 //
2811                 public bool ResolveAndReduce (EmitContext ec, Type required_type, bool allow_nullable)
2812                 {       
2813                         Expression e = label.Resolve (ec);
2814
2815                         if (e == null)
2816                                 return false;
2817
2818                         Constant c = e as Constant;
2819                         if (c == null){
2820                                 Report.Error (150, loc, "A constant value is expected");
2821                                 return false;
2822                         }
2823
2824                         if (required_type == TypeManager.string_type && c.GetValue () == null) {
2825                                 converted = NullStringCase;
2826                                 return true;
2827                         }
2828
2829                         if (allow_nullable && c.GetValue () == null) {
2830                                 converted = NullStringCase;
2831                                 return true;
2832                         }
2833
2834                         c = c.ImplicitConversionRequired (required_type, loc);
2835                         if (c == null)
2836                                 return false;
2837
2838                         converted = c.GetValue ();
2839                         return true;
2840                 }
2841
2842                 public void Erorr_AlreadyOccurs (Type switchType, SwitchLabel collisionWith)
2843                 {
2844                         string label;
2845                         if (converted == null)
2846                                 label = "default";
2847                         else if (converted == NullStringCase)
2848                                 label = "null";
2849                         else if (TypeManager.IsEnumType (switchType)) 
2850                                 label = TypeManager.CSharpEnumValue (switchType, converted);
2851                         else
2852                                 label = converted.ToString ();
2853                         
2854                         Report.SymbolRelatedToPreviousError (collisionWith.loc, null);
2855                         Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2856                 }
2857
2858                 public SwitchLabel Clone (CloneContext clonectx)
2859                 {
2860                         return new SwitchLabel (label.Clone (clonectx), loc);
2861                 }
2862         }
2863
2864         public class SwitchSection {
2865                 // An array of SwitchLabels.
2866                 public readonly ArrayList Labels;
2867                 public readonly Block Block;
2868                 
2869                 public SwitchSection (ArrayList labels, Block block)
2870                 {
2871                         Labels = labels;
2872                         Block = block;
2873                 }
2874
2875                 public SwitchSection Clone (CloneContext clonectx)
2876                 {
2877                         ArrayList cloned_labels = new ArrayList ();
2878
2879                         foreach (SwitchLabel sl in cloned_labels)
2880                                 cloned_labels.Add (sl.Clone (clonectx));
2881                         
2882                         return new SwitchSection (cloned_labels, clonectx.LookupBlock (Block));
2883                 }
2884         }
2885         
2886         public class Switch : Statement {
2887                 public ArrayList Sections;
2888                 public Expression Expr;
2889
2890                 /// <summary>
2891                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
2892                 /// </summary>
2893                 public IDictionary Elements;
2894
2895                 /// <summary>
2896                 ///   The governing switch type
2897                 /// </summary>
2898                 public Type SwitchType;
2899
2900                 //
2901                 // Computed
2902                 //
2903                 Label default_target;
2904                 Label null_target;
2905                 Expression new_expr;
2906                 bool is_constant;
2907                 SwitchSection constant_section;
2908                 SwitchSection default_section;
2909
2910 #if GMCS_SOURCE
2911                 //
2912                 // Nullable Types support for GMCS.
2913                 //
2914                 Nullable.Unwrap unwrap;
2915
2916                 protected bool HaveUnwrap {
2917                         get { return unwrap != null; }
2918                 }
2919 #else
2920                 protected bool HaveUnwrap {
2921                         get { return false; }
2922                 }
2923 #endif
2924
2925                 //
2926                 // The types allowed to be implicitly cast from
2927                 // on the governing type
2928                 //
2929                 static Type [] allowed_types;
2930                 
2931                 public Switch (Expression e, ArrayList sects, Location l)
2932                 {
2933                         Expr = e;
2934                         Sections = sects;
2935                         loc = l;
2936                 }
2937
2938                 public bool GotDefault {
2939                         get {
2940                                 return default_section != null;
2941                         }
2942                 }
2943
2944                 public Label DefaultTarget {
2945                         get {
2946                                 return default_target;
2947                         }
2948                 }
2949
2950                 //
2951                 // Determines the governing type for a switch.  The returned
2952                 // expression might be the expression from the switch, or an
2953                 // expression that includes any potential conversions to the
2954                 // integral types or to string.
2955                 //
2956                 Expression SwitchGoverningType (EmitContext ec, Expression expr)
2957                 {
2958                         Type t = TypeManager.DropGenericTypeArguments (expr.Type);
2959
2960                         if (t == TypeManager.byte_type ||
2961                             t == TypeManager.sbyte_type ||
2962                             t == TypeManager.ushort_type ||
2963                             t == TypeManager.short_type ||
2964                             t == TypeManager.uint32_type ||
2965                             t == TypeManager.int32_type ||
2966                             t == TypeManager.uint64_type ||
2967                             t == TypeManager.int64_type ||
2968                             t == TypeManager.char_type ||
2969                             t == TypeManager.string_type ||
2970                             t == TypeManager.bool_type ||
2971                             t.IsSubclassOf (TypeManager.enum_type))
2972                                 return expr;
2973
2974                         if (allowed_types == null){
2975                                 allowed_types = new Type [] {
2976                                         TypeManager.sbyte_type,
2977                                         TypeManager.byte_type,
2978                                         TypeManager.short_type,
2979                                         TypeManager.ushort_type,
2980                                         TypeManager.int32_type,
2981                                         TypeManager.uint32_type,
2982                                         TypeManager.int64_type,
2983                                         TypeManager.uint64_type,
2984                                         TypeManager.char_type,
2985                                         TypeManager.string_type,
2986                                         TypeManager.bool_type
2987                                 };
2988                         }
2989
2990                         //
2991                         // Try to find a *user* defined implicit conversion.
2992                         //
2993                         // If there is no implicit conversion, or if there are multiple
2994                         // conversions, we have to report an error
2995                         //
2996                         Expression converted = null;
2997                         foreach (Type tt in allowed_types){
2998                                 Expression e;
2999                                 
3000                                 e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
3001                                 if (e == null)
3002                                         continue;
3003
3004                                 //
3005                                 // Ignore over-worked ImplicitUserConversions that do
3006                                 // an implicit conversion in addition to the user conversion.
3007                                 // 
3008                                 if (!(e is UserCast))
3009                                         continue;
3010
3011                                 if (converted != null){
3012                                         Report.ExtraInformation (
3013                                                 loc,
3014                                                 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
3015                                                                TypeManager.CSharpName (expr.Type)));
3016                                         return null;
3017                                 }
3018
3019                                 converted = e;
3020                         }
3021                         return converted;
3022                 }
3023
3024                 //
3025                 // Performs the basic sanity checks on the switch statement
3026                 // (looks for duplicate keys and non-constant expressions).
3027                 //
3028                 // It also returns a hashtable with the keys that we will later
3029                 // use to compute the switch tables
3030                 //
3031                 bool CheckSwitch (EmitContext ec)
3032                 {
3033                         bool error = false;
3034                         Elements = Sections.Count > 10 ? 
3035                                 (IDictionary)new Hashtable () : 
3036                                 (IDictionary)new ListDictionary ();
3037                                 
3038                         foreach (SwitchSection ss in Sections){
3039                                 foreach (SwitchLabel sl in ss.Labels){
3040                                         if (sl.Label == null){
3041                                                 if (default_section != null){
3042                                                         sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)default_section.Labels [0]);
3043                                                         error = true;
3044                                                 }
3045                                                 default_section = ss;
3046                                                 continue;
3047                                         }
3048
3049                                         if (!sl.ResolveAndReduce (ec, SwitchType, HaveUnwrap)) {
3050                                                 error = true;
3051                                                 continue;
3052                                         }
3053                                         
3054                                         object key = sl.Converted;
3055                                         try {
3056                                                 Elements.Add (key, sl);
3057                                         } catch (ArgumentException) {
3058                                                 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)Elements [key]);
3059                                                 error = true;
3060                                         }
3061                                 }
3062                         }
3063                         return !error;
3064                 }
3065
3066                 void EmitObjectInteger (ILGenerator ig, object k)
3067                 {
3068                         if (k is int)
3069                                 IntConstant.EmitInt (ig, (int) k);
3070                         else if (k is Constant) {
3071                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3072                         } 
3073                         else if (k is uint)
3074                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3075                         else if (k is long)
3076                         {
3077                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3078                                 {
3079                                         IntConstant.EmitInt (ig, (int) (long) k);
3080                                         ig.Emit (OpCodes.Conv_I8);
3081                                 }
3082                                 else
3083                                         LongConstant.EmitLong (ig, (long) k);
3084                         }
3085                         else if (k is ulong)
3086                         {
3087                                 ulong ul = (ulong) k;
3088                                 if (ul < (1L<<32))
3089                                 {
3090                                         IntConstant.EmitInt (ig, unchecked ((int) ul));
3091                                         ig.Emit (OpCodes.Conv_U8);
3092                                 }
3093                                 else
3094                                 {
3095                                         LongConstant.EmitLong (ig, unchecked ((long) ul));
3096                                 }
3097                         }
3098                         else if (k is char)
3099                                 IntConstant.EmitInt (ig, (int) ((char) k));
3100                         else if (k is sbyte)
3101                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3102                         else if (k is byte)
3103                                 IntConstant.EmitInt (ig, (int) ((byte) k));
3104                         else if (k is short)
3105                                 IntConstant.EmitInt (ig, (int) ((short) k));
3106                         else if (k is ushort)
3107                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
3108                         else if (k is bool)
3109                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3110                         else
3111                                 throw new Exception ("Unhandled case");
3112                 }
3113                 
3114                 // structure used to hold blocks of keys while calculating table switch
3115                 class KeyBlock : IComparable
3116                 {
3117                         public KeyBlock (long _nFirst)
3118                         {
3119                                 nFirst = nLast = _nFirst;
3120                         }
3121                         public long nFirst;
3122                         public long nLast;
3123                         public ArrayList rgKeys = null;
3124                         // how many items are in the bucket
3125                         public int Size = 1;
3126                         public int Length
3127                         {
3128                                 get { return (int) (nLast - nFirst + 1); }
3129                         }
3130                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3131                         {
3132                                 return kbLast.nLast - kbFirst.nFirst + 1;
3133                         }
3134                         public int CompareTo (object obj)
3135                         {
3136                                 KeyBlock kb = (KeyBlock) obj;
3137                                 int nLength = Length;
3138                                 int nLengthOther = kb.Length;
3139                                 if (nLengthOther == nLength)
3140                                         return (int) (kb.nFirst - nFirst);
3141                                 return nLength - nLengthOther;
3142                         }
3143                 }
3144
3145                 /// <summary>
3146                 /// This method emits code for a lookup-based switch statement (non-string)
3147                 /// Basically it groups the cases into blocks that are at least half full,
3148                 /// and then spits out individual lookup opcodes for each block.
3149                 /// It emits the longest blocks first, and short blocks are just
3150                 /// handled with direct compares.
3151                 /// </summary>
3152                 /// <param name="ec"></param>
3153                 /// <param name="val"></param>
3154                 /// <returns></returns>
3155                 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
3156                 {
3157                         int cElements = Elements.Count;
3158                         object [] rgKeys = new object [cElements];
3159                         Elements.Keys.CopyTo (rgKeys, 0);
3160                         Array.Sort (rgKeys);
3161
3162                         // initialize the block list with one element per key
3163                         ArrayList rgKeyBlocks = new ArrayList ();
3164                         foreach (object key in rgKeys)
3165                                 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
3166
3167                         KeyBlock kbCurr;
3168                         // iteratively merge the blocks while they are at least half full
3169                         // there's probably a really cool way to do this with a tree...
3170                         while (rgKeyBlocks.Count > 1)
3171                         {
3172                                 ArrayList rgKeyBlocksNew = new ArrayList ();
3173                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
3174                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3175                                 {
3176                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3177                                         if ((kbCurr.Size + kb.Size) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
3178                                         {
3179                                                 // merge blocks
3180                                                 kbCurr.nLast = kb.nLast;
3181                                                 kbCurr.Size += kb.Size;
3182                                         }
3183                                         else
3184                                         {
3185                                                 // start a new block
3186                                                 rgKeyBlocksNew.Add (kbCurr);
3187                                                 kbCurr = kb;
3188                                         }
3189                                 }
3190                                 rgKeyBlocksNew.Add (kbCurr);
3191                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3192                                         break;
3193                                 rgKeyBlocks = rgKeyBlocksNew;
3194                         }
3195
3196                         // initialize the key lists
3197                         foreach (KeyBlock kb in rgKeyBlocks)
3198                                 kb.rgKeys = new ArrayList ();
3199
3200                         // fill the key lists
3201                         int iBlockCurr = 0;
3202                         if (rgKeyBlocks.Count > 0) {
3203                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
3204                                 foreach (object key in rgKeys)
3205                                 {
3206                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
3207                                                 System.Convert.ToInt64 (key) > kbCurr.nLast;
3208                                         if (fNextBlock)
3209                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3210                                         kbCurr.rgKeys.Add (key);
3211                                 }
3212                         }
3213
3214                         // sort the blocks so we can tackle the largest ones first
3215                         rgKeyBlocks.Sort ();
3216
3217                         // okay now we can start...
3218                         ILGenerator ig = ec.ig;
3219                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
3220                         Label lblDefault = ig.DefineLabel ();
3221
3222                         Type typeKeys = null;
3223                         if (rgKeys.Length > 0)
3224                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
3225
3226                         Type compare_type;
3227                         
3228                         if (TypeManager.IsEnumType (SwitchType))
3229                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3230                         else
3231                                 compare_type = SwitchType;
3232                         
3233                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3234                         {
3235                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3236                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3237                                 if (kb.Length <= 2)
3238                                 {
3239                                         foreach (object key in kb.rgKeys)
3240                                         {
3241                                                 ig.Emit (OpCodes.Ldloc, val);
3242                                                 EmitObjectInteger (ig, key);
3243                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
3244                                                 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
3245                                         }
3246                                 }
3247                                 else
3248                                 {
3249                                         // TODO: if all the keys in the block are the same and there are
3250                                         //       no gaps/defaults then just use a range-check.
3251                                         if (compare_type == TypeManager.int64_type ||
3252                                                 compare_type == TypeManager.uint64_type)
3253                                         {
3254                                                 // TODO: optimize constant/I4 cases
3255
3256                                                 // check block range (could be > 2^31)
3257                                                 ig.Emit (OpCodes.Ldloc, val);
3258                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3259                                                 ig.Emit (OpCodes.Blt, lblDefault);
3260                                                 ig.Emit (OpCodes.Ldloc, val);
3261                                                 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
3262                                                 ig.Emit (OpCodes.Bgt, lblDefault);
3263
3264                                                 // normalize range
3265                                                 ig.Emit (OpCodes.Ldloc, val);
3266                                                 if (kb.nFirst != 0)
3267                                                 {
3268                                                         EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3269                                                         ig.Emit (OpCodes.Sub);
3270                                                 }
3271                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
3272                                         }
3273                                         else
3274                                         {
3275                                                 // normalize range
3276                                                 ig.Emit (OpCodes.Ldloc, val);
3277                                                 int nFirst = (int) kb.nFirst;
3278                                                 if (nFirst > 0)
3279                                                 {
3280                                                         IntConstant.EmitInt (ig, nFirst);
3281                                                         ig.Emit (OpCodes.Sub);
3282                                                 }
3283                                                 else if (nFirst < 0)
3284                                                 {
3285                                                         IntConstant.EmitInt (ig, -nFirst);
3286                                                         ig.Emit (OpCodes.Add);
3287                                                 }
3288                                         }
3289
3290                                         // first, build the list of labels for the switch
3291                                         int iKey = 0;
3292                                         int cJumps = kb.Length;
3293                                         Label [] rgLabels = new Label [cJumps];
3294                                         for (int iJump = 0; iJump < cJumps; iJump++)
3295                                         {
3296                                                 object key = kb.rgKeys [iKey];
3297                                                 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
3298                                                 {
3299                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
3300                                                         rgLabels [iJump] = sl.GetILLabel (ec);
3301                                                         iKey++;
3302                                                 }
3303                                                 else
3304                                                         rgLabels [iJump] = lblDefault;
3305                                         }
3306                                         // emit the switch opcode
3307                                         ig.Emit (OpCodes.Switch, rgLabels);
3308                                 }
3309
3310                                 // mark the default for this block
3311                                 if (iBlock != 0)
3312                                         ig.MarkLabel (lblDefault);
3313                         }
3314
3315                         // TODO: find the default case and emit it here,
3316                         //       to prevent having to do the following jump.
3317                         //       make sure to mark other labels in the default section
3318
3319                         // the last default just goes to the end
3320                         ig.Emit (OpCodes.Br, lblDefault);
3321
3322                         // now emit the code for the sections
3323                         bool fFoundDefault = false;
3324                         bool fFoundNull = false;
3325                         foreach (SwitchSection ss in Sections)
3326                         {
3327                                 foreach (SwitchLabel sl in ss.Labels)
3328                                         if (sl.Converted == SwitchLabel.NullStringCase)
3329                                                 fFoundNull = true;
3330                         }
3331
3332                         foreach (SwitchSection ss in Sections)
3333                         {
3334                                 foreach (SwitchLabel sl in ss.Labels)
3335                                 {
3336                                         ig.MarkLabel (sl.GetILLabel (ec));
3337                                         ig.MarkLabel (sl.GetILLabelCode (ec));
3338                                         if (sl.Converted == SwitchLabel.NullStringCase)
3339                                                 ig.MarkLabel (null_target);
3340                                         else if (sl.Label == null) {
3341                                                 ig.MarkLabel (lblDefault);
3342                                                 fFoundDefault = true;
3343                                                 if (!fFoundNull)
3344                                                         ig.MarkLabel (null_target);
3345                                         }
3346                                 }
3347                                 ss.Block.Emit (ec);
3348                         }
3349                         
3350                         if (!fFoundDefault) {
3351                                 ig.MarkLabel (lblDefault);
3352                                 if (HaveUnwrap && !fFoundNull) {
3353                                         ig.MarkLabel (null_target);
3354                                 }
3355                         }
3356                         
3357                         ig.MarkLabel (lblEnd);
3358                 }
3359                 //
3360                 // This simple emit switch works, but does not take advantage of the
3361                 // `switch' opcode. 
3362                 // TODO: remove non-string logic from here
3363                 // TODO: binary search strings?
3364                 //
3365                 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3366                 {
3367                         ILGenerator ig = ec.ig;
3368                         Label end_of_switch = ig.DefineLabel ();
3369                         Label next_test = ig.DefineLabel ();
3370                         bool first_test = true;
3371                         bool pending_goto_end = false;
3372                         bool null_marked = false;
3373                         bool null_found;
3374                         int section_count = Sections.Count;
3375
3376                         // TODO: implement switch optimization for string by using Hashtable
3377                         //if (SwitchType == TypeManager.string_type && section_count > 7)
3378                         //      Console.WriteLine ("Switch optimization possible " + loc);
3379
3380                         ig.Emit (OpCodes.Ldloc, val);
3381                         
3382                         if (Elements.Contains (SwitchLabel.NullStringCase)){
3383                                 ig.Emit (OpCodes.Brfalse, null_target);
3384                         } else
3385                                 ig.Emit (OpCodes.Brfalse, default_target);
3386                         
3387                         ig.Emit (OpCodes.Ldloc, val);
3388                         ig.Emit (OpCodes.Call, TypeManager.string_isinterned_string);
3389                         ig.Emit (OpCodes.Stloc, val);
3390
3391                         for (int section = 0; section < section_count; section++){
3392                                 SwitchSection ss = (SwitchSection) Sections [section];
3393
3394                                 if (ss == default_section)
3395                                         continue;
3396
3397                                 Label sec_begin = ig.DefineLabel ();
3398
3399                                 ig.Emit (OpCodes.Nop);
3400
3401                                 if (pending_goto_end)
3402                                         ig.Emit (OpCodes.Br, end_of_switch);
3403
3404                                 int label_count = ss.Labels.Count;
3405                                 null_found = false;
3406                                 for (int label = 0; label < label_count; label++){
3407                                         SwitchLabel sl = (SwitchLabel) ss.Labels [label];
3408                                         ig.MarkLabel (sl.GetILLabel (ec));
3409                                         
3410                                         if (!first_test){
3411                                                 ig.MarkLabel (next_test);
3412                                                 next_test = ig.DefineLabel ();
3413                                         }
3414                                         //
3415                                         // If we are the default target
3416                                         //
3417                                         if (sl.Label != null){
3418                                                 object lit = sl.Converted;
3419
3420                                                 if (lit == SwitchLabel.NullStringCase){
3421                                                         null_found = true;
3422                                                         if (label + 1 == label_count)
3423                                                                 ig.Emit (OpCodes.Br, next_test);
3424                                                         continue;
3425                                                 }
3426                                                 
3427                                                 ig.Emit (OpCodes.Ldloc, val);
3428                                                 ig.Emit (OpCodes.Ldstr, (string)lit);
3429                                                 if (label_count == 1)
3430                                                         ig.Emit (OpCodes.Bne_Un, next_test);
3431                                                 else {
3432                                                         if (label+1 == label_count)
3433                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
3434                                                         else
3435                                                                 ig.Emit (OpCodes.Beq, sec_begin);
3436                                                 }
3437                                         }
3438                                 }
3439                                 if (null_found) {
3440                                         ig.MarkLabel (null_target);
3441                                         null_marked = true;
3442                                 }
3443                                 ig.MarkLabel (sec_begin);
3444                                 foreach (SwitchLabel sl in ss.Labels)
3445                                         ig.MarkLabel (sl.GetILLabelCode (ec));
3446
3447                                 ss.Block.Emit (ec);
3448                                 pending_goto_end = !ss.Block.HasRet;
3449                                 first_test = false;
3450                         }
3451                         ig.MarkLabel (next_test);
3452                         ig.MarkLabel (default_target);
3453                         if (!null_marked)
3454                                 ig.MarkLabel (null_target);
3455                         if (default_section != null)
3456                                 default_section.Block.Emit (ec);
3457                         ig.MarkLabel (end_of_switch);
3458                 }
3459
3460                 SwitchSection FindSection (SwitchLabel label)
3461                 {
3462                         foreach (SwitchSection ss in Sections){
3463                                 foreach (SwitchLabel sl in ss.Labels){
3464                                         if (label == sl)
3465                                                 return ss;
3466                                 }
3467                         }
3468
3469                         return null;
3470                 }
3471
3472                 public override bool Resolve (EmitContext ec)
3473                 {
3474                         Expr = Expr.Resolve (ec);
3475                         if (Expr == null)
3476                                 return false;
3477
3478                         new_expr = SwitchGoverningType (ec, Expr);
3479
3480 #if GMCS_SOURCE
3481                         if ((new_expr == null) && TypeManager.IsNullableType (Expr.Type)) {
3482                                 unwrap = Nullable.Unwrap.Create (Expr, ec);
3483                                 if (unwrap == null)
3484                                         return false;
3485
3486                                 new_expr = SwitchGoverningType (ec, unwrap);
3487                         }
3488 #endif
3489
3490                         if (new_expr == null){
3491                                 Report.Error (151, loc, "A value of an integral type or string expected for switch");
3492                                 return false;
3493                         }
3494
3495                         // Validate switch.
3496                         SwitchType = new_expr.Type;
3497
3498                         if (RootContext.Version == LanguageVersion.ISO_1 && SwitchType == TypeManager.bool_type) {
3499                                 Report.FeatureIsNotISO1 (loc, "switch expression of boolean type");
3500                                 return false;
3501                         }
3502
3503                         if (!CheckSwitch (ec))
3504                                 return false;
3505
3506                         if (HaveUnwrap)
3507                                 Elements.Remove (SwitchLabel.NullStringCase);
3508
3509                         Switch old_switch = ec.Switch;
3510                         ec.Switch = this;
3511                         ec.Switch.SwitchType = SwitchType;
3512
3513                         Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3514                         ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3515
3516                         is_constant = new_expr is Constant;
3517                         if (is_constant) {
3518                                 object key = ((Constant) new_expr).GetValue ();
3519                                 SwitchLabel label = (SwitchLabel) Elements [key];
3520
3521                                 constant_section = FindSection (label);
3522                                 if (constant_section == null)
3523                                         constant_section = default_section;
3524                         }
3525
3526                         bool first = true;
3527                         foreach (SwitchSection ss in Sections){
3528                                 if (!first)
3529                                         ec.CurrentBranching.CreateSibling (
3530                                                 null, FlowBranching.SiblingType.SwitchSection);
3531                                 else
3532                                         first = false;
3533
3534                                 if (is_constant && (ss != constant_section)) {
3535                                         // If we're a constant switch, we're only emitting
3536                                         // one single section - mark all the others as
3537                                         // unreachable.
3538                                         ec.CurrentBranching.CurrentUsageVector.Goto ();
3539                                         if (!ss.Block.ResolveUnreachable (ec, true))
3540                                                 return false;
3541                                 } else {
3542                                         if (!ss.Block.Resolve (ec))
3543                                                 return false;
3544                                 }
3545                         }
3546
3547                         if (default_section == null)
3548                                 ec.CurrentBranching.CreateSibling (
3549                                         null, FlowBranching.SiblingType.SwitchSection);
3550
3551                         ec.EndFlowBranching ();
3552                         ec.Switch = old_switch;
3553
3554                         Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching);
3555
3556                         return true;
3557                 }
3558                 
3559                 protected override void DoEmit (EmitContext ec)
3560                 {
3561                         ILGenerator ig = ec.ig;
3562
3563                         default_target = ig.DefineLabel ();
3564                         null_target = ig.DefineLabel ();
3565
3566                         // Store variable for comparission purposes
3567                         LocalBuilder value;
3568                         if (HaveUnwrap) {
3569                                 value = ig.DeclareLocal (SwitchType);
3570 #if GMCS_SOURCE
3571                                 unwrap.EmitCheck (ec);
3572                                 ig.Emit (OpCodes.Brfalse, null_target);
3573                                 new_expr.Emit (ec);
3574                                 ig.Emit (OpCodes.Stloc, value);
3575 #endif
3576                         } else if (!is_constant) {
3577                                 value = ig.DeclareLocal (SwitchType);
3578                                 new_expr.Emit (ec);
3579                                 ig.Emit (OpCodes.Stloc, value);
3580                         } else
3581                                 value = null;
3582
3583                         //
3584                         // Setup the codegen context
3585                         //
3586                         Label old_end = ec.LoopEnd;
3587                         Switch old_switch = ec.Switch;
3588                         
3589                         ec.LoopEnd = ig.DefineLabel ();
3590                         ec.Switch = this;
3591
3592                         // Emit Code.
3593                         if (is_constant) {
3594                                 if (constant_section != null)
3595                                         constant_section.Block.Emit (ec);
3596                         } else if (SwitchType == TypeManager.string_type)
3597                                 SimpleSwitchEmit (ec, value);
3598                         else
3599                                 TableSwitchEmit (ec, value);
3600
3601                         // Restore context state. 
3602                         ig.MarkLabel (ec.LoopEnd);
3603
3604                         //
3605                         // Restore the previous context
3606                         //
3607                         ec.LoopEnd = old_end;
3608                         ec.Switch = old_switch;
3609                 }
3610
3611                 protected override void CloneTo (CloneContext clonectx, Statement t)
3612                 {
3613                         Switch target = (Switch) t;
3614
3615                         target.Expr = Expr.Clone (clonectx);
3616                         target.Sections = new ArrayList ();
3617                         foreach (SwitchSection ss in Sections){
3618                                 target.Sections.Add (ss.Clone (clonectx));
3619                         }
3620                 }
3621         }
3622
3623         public abstract class ExceptionStatement : Statement
3624         {
3625                 public abstract void EmitFinally (EmitContext ec);
3626
3627                 protected bool emit_finally = true;
3628                 ArrayList parent_vectors;
3629
3630                 protected void DoEmitFinally (EmitContext ec)
3631                 {
3632                         if (emit_finally)
3633                                 ec.ig.BeginFinallyBlock ();
3634                         else if (ec.InIterator)
3635                                 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3636                         EmitFinally (ec);
3637                 }
3638
3639                 protected void ResolveFinally (FlowBranchingException branching)
3640                 {
3641                         emit_finally = branching.EmitFinally;
3642                         if (!emit_finally)
3643                                 branching.Parent.StealFinallyClauses (ref parent_vectors);
3644                 }
3645         }
3646
3647         public class Lock : ExceptionStatement {
3648                 Expression expr;
3649                 public Statement Statement;
3650                 TemporaryVariable temp;
3651                         
3652                 public Lock (Expression expr, Statement stmt, Location l)
3653                 {
3654                         this.expr = expr;
3655                         Statement = stmt;
3656                         loc = l;
3657                 }
3658
3659                 public override bool Resolve (EmitContext ec)
3660                 {
3661                         expr = expr.Resolve (ec);
3662                         if (expr == null)
3663                                 return false;
3664
3665                         if (expr.Type.IsValueType){
3666                                 Report.Error (185, loc,
3667                                               "`{0}' is not a reference type as required by the lock statement",
3668                                               TypeManager.CSharpName (expr.Type));
3669                                 return false;
3670                         }
3671
3672                         FlowBranchingException branching = ec.StartFlowBranching (this);
3673                         bool ok = Statement.Resolve (ec);
3674
3675                         ResolveFinally (branching);
3676
3677                         ec.EndFlowBranching ();
3678
3679                         // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
3680                         // So, ensure there's some IL code after the finally block.
3681                         ec.NeedReturnLabel ();
3682
3683                         // Avoid creating libraries that reference the internal
3684                         // mcs NullType:
3685                         Type t = expr.Type;
3686                         if (t == TypeManager.null_type)
3687                                 t = TypeManager.object_type;
3688                         
3689                         temp = new TemporaryVariable (t, loc);
3690                         temp.Resolve (ec);
3691                         
3692                         return ok;
3693                 }
3694                 
3695                 protected override void DoEmit (EmitContext ec)
3696                 {
3697                         ILGenerator ig = ec.ig;
3698
3699                         temp.Store (ec, expr);
3700                         temp.Emit (ec);
3701                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3702
3703                         // try
3704                         if (emit_finally)
3705                                 ig.BeginExceptionBlock ();
3706                         Statement.Emit (ec);
3707                         
3708                         // finally
3709                         DoEmitFinally (ec);
3710                         if (emit_finally)
3711                                 ig.EndExceptionBlock ();
3712                 }
3713
3714                 public override void EmitFinally (EmitContext ec)
3715                 {
3716                         temp.Emit (ec);
3717                         ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3718                 }
3719                 
3720                 protected override void CloneTo (CloneContext clonectx, Statement t)
3721                 {
3722                         Lock target = (Lock) t;
3723
3724                         target.expr = expr.Clone (clonectx);
3725                         target.Statement = Statement.Clone (clonectx);
3726                 }
3727         }
3728
3729         public class Unchecked : Statement {
3730                 public Block Block;
3731                 
3732                 public Unchecked (Block b)
3733                 {
3734                         Block = b;
3735                         b.Unchecked = true;
3736                 }
3737
3738                 public override bool Resolve (EmitContext ec)
3739                 {
3740                         using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3741                                 return Block.Resolve (ec);
3742                 }
3743                 
3744                 protected override void DoEmit (EmitContext ec)
3745                 {
3746                         using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3747                                 Block.Emit (ec);
3748                 }
3749
3750                 protected override void CloneTo (CloneContext clonectx, Statement t)
3751                 {
3752                         Unchecked target = (Unchecked) t;
3753
3754                         target.Block = clonectx.LookupBlock (Block);
3755                 }
3756         }
3757
3758         public class Checked : Statement {
3759                 public Block Block;
3760                 
3761                 public Checked (Block b)
3762                 {
3763                         Block = b;
3764                         b.Unchecked = false;
3765                 }
3766
3767                 public override bool Resolve (EmitContext ec)
3768                 {
3769                         using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3770                                 return Block.Resolve (ec);
3771                 }
3772
3773                 protected override void DoEmit (EmitContext ec)
3774                 {
3775                         using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3776                                 Block.Emit (ec);
3777                 }
3778
3779                 protected override void CloneTo (CloneContext clonectx, Statement t)
3780                 {
3781                         Checked target = (Checked) t;
3782
3783                         target.Block = clonectx.LookupBlock (Block);
3784                 }
3785         }
3786
3787         public class Unsafe : Statement {
3788                 public Block Block;
3789
3790                 public Unsafe (Block b)
3791                 {
3792                         Block = b;
3793                         Block.Unsafe = true;
3794                 }
3795
3796                 public override bool Resolve (EmitContext ec)
3797                 {
3798                         using (ec.With (EmitContext.Flags.InUnsafe, true))
3799                                 return Block.Resolve (ec);
3800                 }
3801                 
3802                 protected override void DoEmit (EmitContext ec)
3803                 {
3804                         using (ec.With (EmitContext.Flags.InUnsafe, true))
3805                                 Block.Emit (ec);
3806                 }
3807                 protected override void CloneTo (CloneContext clonectx, Statement t)
3808                 {
3809                         Unsafe target = (Unsafe) t;
3810
3811                         target.Block = clonectx.LookupBlock (Block);
3812                 }
3813         }
3814
3815         // 
3816         // Fixed statement
3817         //
3818         public class Fixed : Statement {
3819                 Expression type;
3820                 ArrayList declarators;
3821                 Statement statement;
3822                 Type expr_type;
3823                 Emitter[] data;
3824                 bool has_ret;
3825
3826                 abstract class Emitter
3827                 {
3828                         protected LocalInfo vi;
3829                         protected Expression converted;
3830
3831                         protected Emitter (Expression expr, LocalInfo li)
3832                         {
3833                                 converted = expr;
3834                                 vi = li;
3835                         }
3836
3837                         public abstract void Emit (EmitContext ec);
3838                         public abstract void EmitExit (EmitContext ec);
3839                 }
3840
3841                 class ExpressionEmitter : Emitter {
3842                         public ExpressionEmitter (Expression converted, LocalInfo li) :
3843                                 base (converted, li)
3844                         {
3845                         }
3846
3847                         public override void Emit (EmitContext ec) {
3848                                 //
3849                                 // Store pointer in pinned location
3850                                 //
3851                                 converted.Emit (ec);
3852                                 vi.Variable.EmitAssign (ec);
3853                         }
3854
3855                         public override void EmitExit (EmitContext ec)
3856                         {
3857                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
3858                                 ec.ig.Emit (OpCodes.Conv_U);
3859                                 vi.Variable.EmitAssign (ec);
3860                         }
3861                 }
3862
3863                 class StringEmitter : Emitter {
3864                         LocalBuilder pinned_string;
3865                         Location loc;
3866
3867                         public StringEmitter (Expression expr, LocalInfo li, Location loc):
3868                                 base (expr, li)
3869                         {
3870                                 this.loc = loc;
3871                         }
3872
3873                         public override void Emit (EmitContext ec)
3874                         {
3875                                 ILGenerator ig = ec.ig;
3876                                 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3877                                         
3878                                 converted.Emit (ec);
3879                                 ig.Emit (OpCodes.Stloc, pinned_string);
3880
3881                                 Expression sptr = new StringPtr (pinned_string, loc);
3882                                 converted = Convert.ImplicitConversionRequired (
3883                                         ec, sptr, vi.VariableType, loc);
3884                                         
3885                                 if (converted == null)
3886                                         return;
3887
3888                                 converted.Emit (ec);
3889                                 vi.Variable.EmitAssign (ec);
3890                         }
3891
3892                         public override void EmitExit (EmitContext ec)
3893                         {
3894                                 ec.ig.Emit (OpCodes.Ldnull);
3895                                 ec.ig.Emit (OpCodes.Stloc, pinned_string);
3896                         }
3897                 }
3898
3899                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3900                 {
3901                         this.type = type;
3902                         declarators = decls;
3903                         statement = stmt;
3904                         loc = l;
3905                 }
3906
3907                 public Statement Statement {
3908                         get { return statement; }
3909                 }
3910
3911                 public override bool Resolve (EmitContext ec)
3912                 {
3913                         if (!ec.InUnsafe){
3914                                 Expression.UnsafeError (loc);
3915                                 return false;
3916                         }
3917                         
3918                         TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3919                         if (texpr == null)
3920                                 return false;
3921
3922                         expr_type = texpr.Type;
3923
3924                         data = new Emitter [declarators.Count];
3925
3926                         if (!expr_type.IsPointer){
3927                                 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3928                                 return false;
3929                         }
3930                         
3931                         int i = 0;
3932                         foreach (Pair p in declarators){
3933                                 LocalInfo vi = (LocalInfo) p.First;
3934                                 Expression e = (Expression) p.Second;
3935                                 
3936                                 vi.VariableInfo.SetAssigned (ec);
3937                                 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3938
3939                                 //
3940                                 // The rules for the possible declarators are pretty wise,
3941                                 // but the production on the grammar is more concise.
3942                                 //
3943                                 // So we have to enforce these rules here.
3944                                 //
3945                                 // We do not resolve before doing the case 1 test,
3946                                 // because the grammar is explicit in that the token &
3947                                 // is present, so we need to test for this particular case.
3948                                 //
3949
3950                                 if (e is Cast){
3951                                         Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3952                                         return false;
3953                                 }
3954                                 
3955                                 //
3956                                 // Case 1: & object.
3957                                 //
3958                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3959                                         Expression child = ((Unary) e).Expr;
3960
3961                                         if (child is ParameterReference || child is LocalVariableReference){
3962                                                 Report.Error (
3963                                                         213, loc, 
3964                                                         "No need to use fixed statement for parameters or " +
3965                                                         "local variable declarations (address is already " +
3966                                                         "fixed)");
3967                                                 return false;
3968                                         }
3969
3970                                         ec.InFixedInitializer = true;
3971                                         e = e.Resolve (ec);
3972                                         ec.InFixedInitializer = false;
3973                                         if (e == null)
3974                                                 return false;
3975
3976                                         child = ((Unary) e).Expr;
3977                                         
3978                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
3979                                                 return false;
3980
3981                                         if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
3982                                                 e.Error_ValueCannotBeConverted (ec, e.Location, expr_type, false);
3983                                                 return false;
3984                                         }
3985
3986                                         data [i] = new ExpressionEmitter (e, vi);
3987                                         i++;
3988
3989                                         continue;
3990                                 }
3991
3992                                 ec.InFixedInitializer = true;
3993                                 e = e.Resolve (ec);
3994                                 ec.InFixedInitializer = false;
3995                                 if (e == null)
3996                                         return false;
3997
3998                                 //
3999                                 // Case 2: Array
4000                                 //
4001                                 if (e.Type.IsArray){
4002                                         Type array_type = TypeManager.GetElementType (e.Type);
4003                                         
4004                                         //
4005                                         // Provided that array_type is unmanaged,
4006                                         //
4007                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
4008                                                 return false;
4009
4010                                         //
4011                                         // and T* is implicitly convertible to the
4012                                         // pointer type given in the fixed statement.
4013                                         //
4014                                         ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
4015                                         
4016                                         Expression converted = Convert.ImplicitConversionRequired (
4017                                                 ec, array_ptr, vi.VariableType, loc);
4018                                         if (converted == null)
4019                                                 return false;
4020
4021                                         data [i] = new ExpressionEmitter (converted, vi);
4022                                         i++;
4023
4024                                         continue;
4025                                 }
4026
4027                                 //
4028                                 // Case 3: string
4029                                 //
4030                                 if (e.Type == TypeManager.string_type){
4031                                         data [i] = new StringEmitter (e, vi, loc);
4032                                         i++;
4033                                         continue;
4034                                 }
4035
4036                                 // Case 4: fixed buffer
4037                                 FieldExpr fe = e as FieldExpr;
4038                                 if (fe != null) {
4039                                         IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
4040                                         if (ff != null) {
4041                                                 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
4042                                         
4043                                                 Expression converted = Convert.ImplicitConversionRequired (
4044                                                         ec, fixed_buffer_ptr, vi.VariableType, loc);
4045                                                 if (converted == null)
4046                                                         return false;
4047
4048                                                 data [i] = new ExpressionEmitter (converted, vi);
4049                                                 i++;
4050
4051                                                 continue;
4052                                         }
4053                                 }
4054
4055                                 //
4056                                 // For other cases, flag a `this is already fixed expression'
4057                                 //
4058                                 if (e is LocalVariableReference || e is ParameterReference ||
4059                                     Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
4060                                     
4061                                         Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
4062                                         return false;
4063                                 }
4064
4065                                 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
4066                                 return false;
4067                         }
4068
4069                         ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
4070                         bool ok = statement.Resolve (ec);
4071                         bool flow_unreachable = ec.EndFlowBranching ();
4072                         has_ret = flow_unreachable;
4073
4074                         return ok;
4075                 }
4076                 
4077                 protected override void DoEmit (EmitContext ec)
4078                 {
4079                         for (int i = 0; i < data.Length; i++) {
4080                                 data [i].Emit (ec);
4081                         }
4082
4083                         statement.Emit (ec);
4084
4085                         if (has_ret)
4086                                 return;
4087
4088                         //
4089                         // Clear the pinned variable
4090                         //
4091                         for (int i = 0; i < data.Length; i++) {
4092                                 data [i].EmitExit (ec);
4093                         }
4094                 }
4095
4096                 protected override void CloneTo (CloneContext clonectx, Statement t)
4097                 {
4098                         Fixed target = (Fixed) t;
4099
4100                         target.type = type.Clone (clonectx);
4101                         target.declarators = new ArrayList ();
4102                         foreach (LocalInfo var in declarators)
4103                                 target.declarators.Add (clonectx.LookupVariable (var));
4104                         target.statement = statement.Clone (clonectx);
4105                 }
4106         }
4107         
4108         public class Catch : Statement {
4109                 public readonly string Name;
4110                 public Block  Block;
4111                 public Block  VarBlock;
4112
4113                 Expression type_expr;
4114                 Type type;
4115                 
4116                 public Catch (Expression type, string name, Block block, Block var_block, Location l)
4117                 {
4118                         type_expr = type;
4119                         Name = name;
4120                         Block = block;
4121                         VarBlock = var_block;
4122                         loc = l;
4123                 }
4124
4125                 public Type CatchType {
4126                         get {
4127                                 return type;
4128                         }
4129                 }
4130
4131                 public bool IsGeneral {
4132                         get {
4133                                 return type_expr == null;
4134                         }
4135                 }
4136
4137                 protected override void DoEmit(EmitContext ec)
4138                 {
4139                         ILGenerator ig = ec.ig;
4140
4141                         if (CatchType != null)
4142                                 ig.BeginCatchBlock (CatchType);
4143                         else
4144                                 ig.BeginCatchBlock (TypeManager.object_type);
4145
4146                         if (VarBlock != null)
4147                                 VarBlock.Emit (ec);
4148
4149                         if (Name != null) {
4150                                 LocalInfo vi = Block.GetLocalInfo (Name);
4151                                 if (vi == null)
4152                                         throw new Exception ("Variable does not exist in this block");
4153
4154                                 if (vi.Variable.NeedsTemporary) {
4155                                         LocalBuilder e = ig.DeclareLocal (vi.VariableType);
4156                                         ig.Emit (OpCodes.Stloc, e);
4157
4158                                         vi.Variable.EmitInstance (ec);
4159                                         ig.Emit (OpCodes.Ldloc, e);
4160                                         vi.Variable.EmitAssign (ec);
4161                                 } else
4162                                         vi.Variable.EmitAssign (ec);
4163                         } else
4164                                 ig.Emit (OpCodes.Pop);
4165
4166                         Block.Emit (ec);
4167                 }
4168
4169                 public override bool Resolve (EmitContext ec)
4170                 {
4171                         using (ec.With (EmitContext.Flags.InCatch, true)) {
4172                                 if (type_expr != null) {
4173                                         TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
4174                                         if (te == null)
4175                                                 return false;
4176
4177                                         type = te.Type;
4178
4179                                         if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4180                                                 Error (155, "The type caught or thrown must be derived from System.Exception");
4181                                                 return false;
4182                                         }
4183                                 } else
4184                                         type = null;
4185
4186                                 if (!Block.Resolve (ec))
4187                                         return false;
4188
4189                                 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
4190                                 // emit the "unused variable" warnings.
4191                                 if (VarBlock != null)
4192                                         return VarBlock.Resolve (ec);
4193
4194                                 return true;
4195                         }
4196                 }
4197
4198                 protected override void CloneTo (CloneContext clonectx, Statement t)
4199                 {
4200                         Catch target = (Catch) t;
4201
4202                         target.type_expr = type_expr.Clone (clonectx);
4203                         target.Block = clonectx.LookupBlock (Block);
4204                         target.VarBlock = clonectx.LookupBlock (VarBlock);
4205                 }
4206         }
4207
4208         public class Try : ExceptionStatement {
4209                 public Block Fini, Block;
4210                 public ArrayList Specific;
4211                 public Catch General;
4212
4213                 bool need_exc_block;
4214                 
4215                 //
4216                 // specific, general and fini might all be null.
4217                 //
4218                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4219                 {
4220                         if (specific == null && general == null){
4221                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4222                         }
4223                         
4224                         this.Block = block;
4225                         this.Specific = specific;
4226                         this.General = general;
4227                         this.Fini = fini;
4228                         loc = l;
4229                 }
4230
4231                 public override bool Resolve (EmitContext ec)
4232                 {
4233                         bool ok = true;
4234                         
4235                         FlowBranchingException branching = ec.StartFlowBranching (this);
4236
4237                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4238
4239                         if (!Block.Resolve (ec))
4240                                 ok = false;
4241
4242                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4243
4244                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
4245
4246                         Type[] prevCatches = new Type [Specific.Count];
4247                         int last_index = 0;
4248                         foreach (Catch c in Specific){
4249                                 ec.CurrentBranching.CreateSibling (
4250                                         c.Block, FlowBranching.SiblingType.Catch);
4251
4252                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4253
4254                                 if (c.Name != null) {
4255                                         LocalInfo vi = c.Block.GetLocalInfo (c.Name);
4256                                         if (vi == null)
4257                                                 throw new Exception ();
4258
4259                                         vi.VariableInfo = null;
4260                                 }
4261
4262                                 if (!c.Resolve (ec))
4263                                         return false;
4264
4265                                 Type resolvedType = c.CatchType;
4266                                 for (int ii = 0; ii < last_index; ++ii) {
4267                                         if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
4268                                                 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
4269                                                 return false;
4270                                         }
4271                                 }
4272
4273                                 prevCatches [last_index++] = resolvedType;
4274                                 need_exc_block = true;
4275                         }
4276
4277                         Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4278
4279                         if (General != null){
4280                                 if (CodeGen.Assembly.WrapNonExceptionThrows) {
4281                                         foreach (Catch c in Specific){
4282                                                 if (c.CatchType == TypeManager.exception_type) {
4283                                                         Report.Warning (1058, 1, c.loc, "A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a `System.Runtime.CompilerServices.RuntimeWrappedException'");
4284                                                 }
4285                                         }
4286                                 }
4287
4288                                 ec.CurrentBranching.CreateSibling (
4289                                         General.Block, FlowBranching.SiblingType.Catch);
4290
4291                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4292
4293                                 if (!General.Resolve (ec))
4294                                         ok = false;
4295
4296                                 need_exc_block = true;
4297                         }
4298
4299                         Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4300
4301                         if (Fini != null) {
4302                                 if (ok)
4303                                         ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
4304
4305                                 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4306                                 using (ec.With (EmitContext.Flags.InFinally, true)) {
4307                                         if (!Fini.Resolve (ec))
4308                                                 ok = false;
4309                                 }
4310
4311                                 if (!ec.InIterator)
4312                                         need_exc_block = true;
4313                         }
4314
4315                         if (ec.InIterator) {
4316                                 ResolveFinally (branching);
4317                                 need_exc_block |= emit_finally;
4318                         } else
4319                                 emit_finally = Fini != null;
4320
4321                         ec.EndFlowBranching ();
4322
4323                         // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4324                         // So, ensure there's some IL code after the finally block.
4325                         ec.NeedReturnLabel ();
4326
4327                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4328
4329                         Report.Debug (1, "END OF TRY", ec.CurrentBranching, vector, f_vector);
4330
4331                         return ok;
4332                 }
4333                 
4334                 protected override void DoEmit (EmitContext ec)
4335                 {
4336                         ILGenerator ig = ec.ig;
4337
4338                         if (need_exc_block)
4339                                 ig.BeginExceptionBlock ();
4340                         Block.Emit (ec);
4341
4342                         foreach (Catch c in Specific)
4343                                 c.Emit (ec);
4344
4345                         if (General != null)
4346                                 General.Emit (ec);
4347
4348                         DoEmitFinally (ec);
4349                         if (need_exc_block)
4350                                 ig.EndExceptionBlock ();
4351                 }
4352
4353                 public override void EmitFinally (EmitContext ec)
4354                 {
4355                         if (Fini != null)
4356                                 Fini.Emit (ec);
4357                 }
4358
4359                 public bool HasCatch
4360                 {
4361                         get {
4362                                 return General != null || Specific.Count > 0;
4363                         }
4364                 }
4365
4366                 protected override void CloneTo (CloneContext clonectx, Statement t)
4367                 {
4368                         Try target = (Try) t;
4369
4370                         target.Block = clonectx.LookupBlock (Block);
4371                         if (Fini != null)
4372                                 target.Fini = clonectx.LookupBlock (Fini);
4373                         if (General != null)
4374                                 target.General = (Catch) General.Clone (clonectx);
4375                         if (Specific != null){
4376                                 target.Specific = new ArrayList ();
4377                                 foreach (Catch c in Specific)
4378                                         target.Specific.Add (c.Clone (clonectx));
4379                         }
4380                 }
4381         }
4382
4383         public class Using : ExceptionStatement {
4384                 object expression_or_block;
4385                 public Statement Statement;
4386                 ArrayList var_list;
4387                 Expression expr;
4388                 Type expr_type;
4389                 Expression [] resolved_vars;
4390                 Expression [] converted_vars;
4391                 Expression [] assign;
4392                 TemporaryVariable local_copy;
4393                 
4394                 public Using (object expression_or_block, Statement stmt, Location l)
4395                 {
4396                         this.expression_or_block = expression_or_block;
4397                         Statement = stmt;
4398                         loc = l;
4399                 }
4400
4401                 //
4402                 // Resolves for the case of using using a local variable declaration.
4403                 //
4404                 bool ResolveLocalVariableDecls (EmitContext ec)
4405                 {
4406                         resolved_vars = new Expression[var_list.Count];
4407                         assign = new Expression [var_list.Count];
4408                         converted_vars = new Expression[var_list.Count];
4409
4410                         for (int i = 0; i < assign.Length; ++i) {
4411                                 DictionaryEntry e = (DictionaryEntry) var_list [i];
4412                                 Expression var = (Expression) e.Key;
4413                                 Expression new_expr = (Expression) e.Value;
4414
4415                                 Expression a = new Assign (var, new_expr, loc);
4416                                 a = a.Resolve (ec);
4417                                 if (a == null)
4418                                         return false;
4419
4420                                 resolved_vars [i] = var;
4421                                 assign [i] = a;
4422
4423                                 if (TypeManager.ImplementsInterface (a.Type, TypeManager.idisposable_type)) {
4424                                         converted_vars [i] = var;
4425                                         continue;
4426                                 }
4427
4428                                 a = Convert.ImplicitConversion (ec, a, TypeManager.idisposable_type, var.Location);
4429                                 if (a == null) {
4430                                         Error_IsNotConvertibleToIDisposable (var);
4431                                         return false;
4432                                 }
4433
4434                                 converted_vars [i] = a;
4435                         }
4436
4437                         return true;
4438                 }
4439
4440                 static void Error_IsNotConvertibleToIDisposable (Expression expr)
4441                 {
4442                         Report.SymbolRelatedToPreviousError (expr.Type);
4443                         Report.Error (1674, expr.Location, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
4444                                 expr.GetSignatureForError ());
4445                 }
4446
4447                 bool ResolveExpression (EmitContext ec)
4448                 {
4449                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4450                                 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
4451                                         Error_IsNotConvertibleToIDisposable (expr);
4452                                         return false;
4453                                 }
4454                         }
4455
4456                         local_copy = new TemporaryVariable (expr_type, loc);
4457                         local_copy.Resolve (ec);
4458
4459                         return true;
4460                 }
4461                 
4462                 //
4463                 // Emits the code for the case of using using a local variable declaration.
4464                 //
4465                 void EmitLocalVariableDecls (EmitContext ec)
4466                 {
4467                         ILGenerator ig = ec.ig;
4468                         int i = 0;
4469
4470                         for (i = 0; i < assign.Length; i++) {
4471                                 assign [i].Emit (ec);
4472
4473                                 if (emit_finally)
4474                                         ig.BeginExceptionBlock ();
4475                         }
4476                         Statement.Emit (ec);
4477
4478                         var_list.Reverse ();
4479
4480                         DoEmitFinally (ec);
4481                 }
4482
4483                 void EmitLocalVariableDeclFinally (EmitContext ec)
4484                 {
4485                         ILGenerator ig = ec.ig;
4486
4487                         int i = assign.Length;
4488                         for (int ii = 0; ii < var_list.Count; ++ii){
4489                                 Expression var = resolved_vars [--i];
4490                                 Label skip = ig.DefineLabel ();
4491
4492                                 if (emit_finally)
4493                                         ig.BeginFinallyBlock ();
4494                                 
4495                                 if (!var.Type.IsValueType) {
4496                                         var.Emit (ec);
4497                                         ig.Emit (OpCodes.Brfalse, skip);
4498                                         converted_vars [i].Emit (ec);
4499                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4500                                 } else {
4501                                         Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4502
4503                                         if (!(ml is MethodGroupExpr)) {
4504                                                 var.Emit (ec);
4505                                                 ig.Emit (OpCodes.Box, var.Type);
4506                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4507                                         } else {
4508                                                 MethodInfo mi = null;
4509
4510                                                 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4511                                                         if (TypeManager.GetParameterData (mk).Count == 0) {
4512                                                                 mi = mk;
4513                                                                 break;
4514                                                         }
4515                                                 }
4516
4517                                                 if (mi == null) {
4518                                                         Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4519                                                         return;
4520                                                 }
4521
4522                                                 IMemoryLocation mloc = (IMemoryLocation) var;
4523
4524                                                 mloc.AddressOf (ec, AddressOp.Load);
4525                                                 ig.Emit (OpCodes.Call, mi);
4526                                         }
4527                                 }
4528
4529                                 ig.MarkLabel (skip);
4530
4531                                 if (emit_finally) {
4532                                         ig.EndExceptionBlock ();
4533                                         if (i > 0)
4534                                                 ig.BeginFinallyBlock ();
4535                                 }
4536                         }
4537                 }
4538
4539                 void EmitExpression (EmitContext ec)
4540                 {
4541                         //
4542                         // Make a copy of the expression and operate on that.
4543                         //
4544                         ILGenerator ig = ec.ig;
4545
4546                         local_copy.Store (ec, expr);
4547
4548                         if (emit_finally)
4549                                 ig.BeginExceptionBlock ();
4550
4551                         Statement.Emit (ec);
4552                         
4553                         DoEmitFinally (ec);
4554                         if (emit_finally)
4555                                 ig.EndExceptionBlock ();
4556                 }
4557
4558                 void EmitExpressionFinally (EmitContext ec)
4559                 {
4560                         ILGenerator ig = ec.ig;
4561                         if (!expr_type.IsValueType) {
4562                                 Label skip = ig.DefineLabel ();
4563                                 local_copy.Emit (ec);
4564                                 ig.Emit (OpCodes.Brfalse, skip);
4565                                 local_copy.Emit (ec);
4566                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4567                                 ig.MarkLabel (skip);
4568                         } else {
4569                                 Expression ml = Expression.MemberLookup (
4570                                         ec.ContainerType, TypeManager.idisposable_type, expr_type,
4571                                         "Dispose", Location.Null);
4572
4573                                 if (!(ml is MethodGroupExpr)) {
4574                                         local_copy.Emit (ec);
4575                                         ig.Emit (OpCodes.Box, expr_type);
4576                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4577                                 } else {
4578                                         MethodInfo mi = null;
4579
4580                                         foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4581                                                 if (TypeManager.GetParameterData (mk).Count == 0) {
4582                                                         mi = mk;
4583                                                         break;
4584                                                 }
4585                                         }
4586
4587                                         if (mi == null) {
4588                                                 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4589                                                 return;
4590                                         }
4591
4592                                         local_copy.AddressOf (ec, AddressOp.Load);
4593                                         ig.Emit (OpCodes.Call, mi);
4594                                 }
4595                         }
4596                 }
4597                 
4598                 public override bool Resolve (EmitContext ec)
4599                 {
4600                         if (expression_or_block is DictionaryEntry){
4601                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4602                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4603
4604                                 if (!ResolveLocalVariableDecls (ec))
4605                                         return false;
4606
4607                         } else if (expression_or_block is Expression){
4608                                 expr = (Expression) expression_or_block;
4609
4610                                 expr = expr.Resolve (ec);
4611                                 if (expr == null)
4612                                         return false;
4613
4614                                 expr_type = expr.Type;
4615
4616                                 if (!ResolveExpression (ec))
4617                                         return false;
4618                         }
4619
4620                         FlowBranchingException branching = ec.StartFlowBranching (this);
4621
4622                         bool ok = Statement.Resolve (ec);
4623
4624                         ResolveFinally (branching);
4625
4626                         ec.EndFlowBranching ();
4627
4628                         // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4629                         // So, ensure there's some IL code after the finally block.
4630                         ec.NeedReturnLabel ();
4631
4632                         return ok;
4633                 }
4634                 
4635                 protected override void DoEmit (EmitContext ec)
4636                 {
4637                         if (expression_or_block is DictionaryEntry)
4638                                 EmitLocalVariableDecls (ec);
4639                         else if (expression_or_block is Expression)
4640                                 EmitExpression (ec);
4641                 }
4642
4643                 public override void EmitFinally (EmitContext ec)
4644                 {
4645                         if (expression_or_block is DictionaryEntry)
4646                                 EmitLocalVariableDeclFinally (ec);
4647                         else if (expression_or_block is Expression)
4648                                 EmitExpressionFinally (ec);
4649                 }
4650
4651                 protected override void CloneTo (CloneContext clonectx, Statement t)
4652                 {
4653                         Using target = (Using) t;
4654
4655                         if (expression_or_block is Expression)
4656                                 target.expression_or_block = ((Expression) expression_or_block).Clone (clonectx);
4657                         else
4658                                 target.expression_or_block = ((Statement) expression_or_block).Clone (clonectx);
4659                         
4660                         target.Statement = Statement.Clone (clonectx);
4661                 }
4662         }
4663
4664         /// <summary>
4665         ///   Implementation of the foreach C# statement
4666         /// </summary>
4667         public class Foreach : Statement {
4668                 Expression type;
4669                 Expression variable;
4670                 Expression expr;
4671                 Statement statement;
4672                 ArrayForeach array;
4673                 CollectionForeach collection;
4674                 
4675                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4676                                 Statement stmt, Location l)
4677                 {
4678                         this.type = type;
4679                         this.variable = var;
4680                         this.expr = expr;
4681                         statement = stmt;
4682                         loc = l;
4683                 }
4684
4685                 public Statement Statement {
4686                         get { return statement; }
4687                 }
4688
4689                 public override bool Resolve (EmitContext ec)
4690                 {
4691                         expr = expr.Resolve (ec);
4692                         if (expr == null)
4693                                 return false;
4694
4695                         if (expr.Type == TypeManager.null_type) {
4696                                 Report.Error (186, loc, "Use of null is not valid in this context");
4697                                 return false;
4698                         }
4699
4700                         if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
4701                                 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4702                                         expr.ExprClassName);
4703                                 return false;
4704                         }
4705
4706                         //
4707                         // We need an instance variable.  Not sure this is the best
4708                         // way of doing this.
4709                         //
4710                         // FIXME: When we implement propertyaccess, will those turn
4711                         // out to return values in ExprClass?  I think they should.
4712                         //
4713                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4714                               expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4715                                 collection.Error_Enumerator ();
4716                                 return false;
4717                         }
4718
4719                         if (expr.Type.IsArray) {
4720                                 array = new ArrayForeach (type, variable, expr, statement, loc);
4721                                 return array.Resolve (ec);
4722                         }
4723                         
4724                         collection = new CollectionForeach (type, variable, expr, statement, loc);
4725                         return collection.Resolve (ec);
4726                 }
4727
4728                 protected override void DoEmit (EmitContext ec)
4729                 {
4730                         ILGenerator ig = ec.ig;
4731                         
4732                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4733                         ec.LoopBegin = ig.DefineLabel ();
4734                         ec.LoopEnd = ig.DefineLabel ();
4735
4736                         if (collection != null)
4737                                 collection.Emit (ec);
4738                         else
4739                                 array.Emit (ec);
4740                         
4741                         ec.LoopBegin = old_begin;
4742                         ec.LoopEnd = old_end;
4743                 }
4744
4745                 protected class ArrayCounter : TemporaryVariable
4746                 {
4747                         public ArrayCounter (Location loc)
4748                                 : base (TypeManager.int32_type, loc)
4749                         { }
4750
4751                         public void Initialize (EmitContext ec)
4752                         {
4753                                 EmitThis (ec);
4754                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
4755                                 EmitStore (ec);
4756                         }
4757
4758                         public void Increment (EmitContext ec)
4759                         {
4760                                 EmitThis (ec);
4761                                 Emit (ec);
4762                                 ec.ig.Emit (OpCodes.Ldc_I4_1);
4763                                 ec.ig.Emit (OpCodes.Add);
4764                                 EmitStore (ec);
4765                         }
4766                 }
4767
4768                 protected class ArrayForeach : Statement
4769                 {
4770                         Expression variable, expr, conv;
4771                         Statement statement;
4772                         Type array_type;
4773                         Expression var_type;
4774                         TemporaryVariable[] lengths;
4775                         ArrayCounter[] counter;
4776                         int rank;
4777
4778                         TemporaryVariable copy;
4779                         Expression access;
4780
4781                         public ArrayForeach (Expression var_type, Expression var,
4782                                              Expression expr, Statement stmt, Location l)
4783                         {
4784                                 this.var_type = var_type;
4785                                 this.variable = var;
4786                                 this.expr = expr;
4787                                 statement = stmt;
4788                                 loc = l;
4789                         }
4790
4791                         public override bool Resolve (EmitContext ec)
4792                         {
4793                                 array_type = expr.Type;
4794                                 rank = array_type.GetArrayRank ();
4795
4796                                 copy = new TemporaryVariable (array_type, loc);
4797                                 copy.Resolve (ec);
4798
4799                                 counter = new ArrayCounter [rank];
4800                                 lengths = new TemporaryVariable [rank];
4801
4802                                 ArrayList list = new ArrayList ();
4803                                 for (int i = 0; i < rank; i++) {
4804                                         counter [i] = new ArrayCounter (loc);
4805                                         counter [i].Resolve (ec);
4806
4807                                         lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4808                                         lengths [i].Resolve (ec);
4809
4810                                         list.Add (counter [i]);
4811                                 }
4812
4813                                 access = new ElementAccess (copy, list).Resolve (ec);
4814                                 if (access == null)
4815                                         return false;
4816
4817                                 VarExpr ve = var_type as VarExpr;
4818                                 if (ve != null) {
4819                                         // Infer implicitly typed local variable from foreach array type
4820                                         var_type = new TypeExpression (access.Type, ve.Location);
4821                                 }
4822
4823                                 var_type = var_type.ResolveAsTypeTerminal (ec, false);
4824                                 if (var_type == null)
4825                                         return false;
4826
4827                                 conv = Convert.ExplicitConversion (ec, access, var_type.Type, loc);
4828                                 if (conv == null)
4829                                         return false;
4830
4831                                 bool ok = true;
4832
4833                                 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4834                                 ec.CurrentBranching.CreateSibling ();
4835
4836                                 variable = variable.ResolveLValue (ec, conv, loc);
4837                                 if (variable == null)
4838                                         ok = false;
4839
4840                                 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4841                                 if (!statement.Resolve (ec))
4842                                         ok = false;
4843                                 ec.EndFlowBranching ();
4844
4845                                 // There's no direct control flow from the end of the embedded statement to the end of the loop
4846                                 ec.CurrentBranching.CurrentUsageVector.Goto ();
4847
4848                                 ec.EndFlowBranching ();
4849
4850                                 return ok;
4851                         }
4852
4853                         protected override void DoEmit (EmitContext ec)
4854                         {
4855                                 ILGenerator ig = ec.ig;
4856
4857                                 copy.Store (ec, expr);
4858
4859                                 Label[] test = new Label [rank];
4860                                 Label[] loop = new Label [rank];
4861
4862                                 for (int i = 0; i < rank; i++) {
4863                                         test [i] = ig.DefineLabel ();
4864                                         loop [i] = ig.DefineLabel ();
4865
4866                                         lengths [i].EmitThis (ec);
4867                                         ((ArrayAccess) access).EmitGetLength (ec, i);
4868                                         lengths [i].EmitStore (ec);
4869                                 }
4870
4871                                 for (int i = 0; i < rank; i++) {
4872                                         counter [i].Initialize (ec);
4873
4874                                         ig.Emit (OpCodes.Br, test [i]);
4875                                         ig.MarkLabel (loop [i]);
4876                                 }
4877
4878                                 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4879
4880                                 statement.Emit (ec);
4881
4882                                 ig.MarkLabel (ec.LoopBegin);
4883
4884                                 for (int i = rank - 1; i >= 0; i--){
4885                                         counter [i].Increment (ec);
4886
4887                                         ig.MarkLabel (test [i]);
4888                                         counter [i].Emit (ec);
4889                                         lengths [i].Emit (ec);
4890                                         ig.Emit (OpCodes.Blt, loop [i]);
4891                                 }
4892
4893                                 ig.MarkLabel (ec.LoopEnd);
4894                         }
4895                 }
4896
4897                 protected class CollectionForeach : ExceptionStatement
4898                 {
4899                         Expression variable, expr;
4900                         Statement statement;
4901
4902                         TemporaryVariable enumerator;
4903                         Expression init;
4904                         Statement loop;
4905
4906                         MethodGroupExpr get_enumerator;
4907                         PropertyExpr get_current;
4908                         MethodInfo move_next;
4909                         Expression var_type;
4910                         Type enumerator_type;
4911                         bool is_disposable;
4912                         bool enumerator_found;
4913
4914                         public CollectionForeach (Expression var_type, Expression var,
4915                                                   Expression expr, Statement stmt, Location l)
4916                         {
4917                                 this.var_type = var_type;
4918                                 this.variable = var;
4919                                 this.expr = expr;
4920                                 statement = stmt;
4921                                 loc = l;
4922                         }
4923
4924                         bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4925                         {
4926                                 Type return_type = mi.ReturnType;
4927
4928                                 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4929                                         //
4930                                         // Apply the same optimization as MS: skip the GetEnumerator
4931                                         // returning an IEnumerator, and use the one returning a 
4932                                         // CharEnumerator instead. This allows us to avoid the 
4933                                         // try-finally block and the boxing.
4934                                         //
4935                                         return false;
4936
4937                                 //
4938                                 // Ok, we can access it, now make sure that we can do something
4939                                 // with this `GetEnumerator'
4940                                 //
4941
4942                                 if (return_type == TypeManager.ienumerator_type ||
4943                                     TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4944                                     (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4945                                         //
4946                                         // If it is not an interface, lets try to find the methods ourselves.
4947                                         // For example, if we have:
4948                                         // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4949                                         // We can avoid the iface call. This is a runtime perf boost.
4950                                         // even bigger if we have a ValueType, because we avoid the cost
4951                                         // of boxing.
4952                                         //
4953                                         // We have to make sure that both methods exist for us to take
4954                                         // this path. If one of the methods does not exist, we will just
4955                                         // use the interface. Sadly, this complex if statement is the only
4956                                         // way I could do this without a goto
4957                                         //
4958
4959 #if GMCS_SOURCE
4960                                         //
4961                                         // Prefer a generic enumerator over a non-generic one.
4962                                         //
4963                                         if (return_type.IsInterface && return_type.IsGenericType) {
4964                                                 enumerator_type = return_type;
4965                                                 if (!FetchGetCurrent (ec, return_type))
4966                                                         get_current = new PropertyExpr (
4967                                                                 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4968                                                 if (!FetchMoveNext (return_type))
4969                                                         move_next = TypeManager.bool_movenext_void;
4970                                                 return true;
4971                                         }
4972 #endif
4973
4974                                         if (return_type.IsInterface ||
4975                                             !FetchMoveNext (return_type) ||
4976                                             !FetchGetCurrent (ec, return_type)) {
4977                                                 enumerator_type = return_type;
4978                                                 move_next = TypeManager.bool_movenext_void;
4979                                                 get_current = new PropertyExpr (
4980                                                         ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4981                                                 return true;
4982                                         }
4983                                 } else {
4984                                         //
4985                                         // Ok, so they dont return an IEnumerable, we will have to
4986                                         // find if they support the GetEnumerator pattern.
4987                                         //
4988
4989                                         if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
4990                                                 Report.Error (202, loc, "foreach statement requires that the return type `{0}' of `{1}' must have a suitable public MoveNext method and public Current property",
4991                                                         TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
4992                                                 return false;
4993                                         }
4994                                 }
4995
4996                                 enumerator_type = return_type;
4997                                 is_disposable = !enumerator_type.IsSealed ||
4998                                         TypeManager.ImplementsInterface (
4999                                                 enumerator_type, TypeManager.idisposable_type);
5000
5001                                 return true;
5002                         }
5003
5004                         //
5005                         // Retrieves a `public bool MoveNext ()' method from the Type `t'
5006                         //
5007                         bool FetchMoveNext (Type t)
5008                         {
5009                                 MemberList move_next_list;
5010
5011                                 move_next_list = TypeContainer.FindMembers (
5012                                         t, MemberTypes.Method,
5013                                         BindingFlags.Public | BindingFlags.Instance,
5014                                         Type.FilterName, "MoveNext");
5015                                 if (move_next_list.Count == 0)
5016                                         return false;
5017
5018                                 foreach (MemberInfo m in move_next_list){
5019                                         MethodInfo mi = (MethodInfo) m;
5020                                 
5021                                         if ((TypeManager.GetParameterData (mi).Count == 0) &&
5022                                             TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
5023                                                 move_next = mi;
5024                                                 return true;
5025                                         }
5026                                 }
5027
5028                                 return false;
5029                         }
5030                 
5031                         //
5032                         // Retrieves a `public T get_Current ()' method from the Type `t'
5033                         //
5034                         bool FetchGetCurrent (EmitContext ec, Type t)
5035                         {
5036                                 PropertyExpr pe = Expression.MemberLookup (
5037                                         ec.ContainerType, t, "Current", MemberTypes.Property,
5038                                         Expression.AllBindingFlags, loc) as PropertyExpr;
5039                                 if (pe == null)
5040                                         return false;
5041
5042                                 get_current = pe;
5043                                 return true;
5044                         }
5045
5046                         // 
5047                         // Retrieves a `public void Dispose ()' method from the Type `t'
5048                         //
5049                         static MethodInfo FetchMethodDispose (Type t)
5050                         {
5051                                 MemberList dispose_list;
5052
5053                                 dispose_list = TypeContainer.FindMembers (
5054                                         t, MemberTypes.Method,
5055                                         BindingFlags.Public | BindingFlags.Instance,
5056                                         Type.FilterName, "Dispose");
5057                                 if (dispose_list.Count == 0)
5058                                         return null;
5059
5060                                 foreach (MemberInfo m in dispose_list){
5061                                         MethodInfo mi = (MethodInfo) m;
5062
5063                                         if (TypeManager.GetParameterData (mi).Count == 0){
5064                                                 if (mi.ReturnType == TypeManager.void_type)
5065                                                         return mi;
5066                                         }
5067                                 }
5068                                 return null;
5069                         }
5070
5071                         public void Error_Enumerator ()
5072                         {
5073                                 if (enumerator_found) {
5074                                         return;
5075                                 }
5076
5077                             Report.Error (1579, loc,
5078                                         "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
5079                                         TypeManager.CSharpName (expr.Type));
5080                         }
5081
5082                         public static bool IsOverride (MethodInfo m)
5083                         {
5084                                 m = (MethodInfo) TypeManager.DropGenericMethodArguments (m);
5085
5086                                 if (!m.IsVirtual || ((m.Attributes & MethodAttributes.NewSlot) != 0))
5087                                         return false;
5088                                 if (m is MethodBuilder)
5089                                         return true;
5090
5091                                 MethodInfo base_method = m.GetBaseDefinition ();
5092                                 return base_method != m;
5093                         }
5094
5095                         bool TryType (EmitContext ec, Type t)
5096                         {
5097                                 MethodGroupExpr mg = Expression.MemberLookup (
5098                                         ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
5099                                         Expression.AllBindingFlags, loc) as MethodGroupExpr;
5100                                 if (mg == null)
5101                                         return false;
5102
5103                                 MethodInfo result = null;
5104                                 MethodInfo tmp_move_next = null;
5105                                 PropertyExpr tmp_get_cur = null;
5106                                 Type tmp_enumerator_type = enumerator_type;
5107                                 foreach (MethodInfo mi in mg.Methods) {
5108                                         if (TypeManager.GetParameterData (mi).Count != 0)
5109                                                 continue;
5110                         
5111                                         // Check whether GetEnumerator is public
5112                                         if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
5113                                                 continue;
5114
5115                                         if (IsOverride (mi))
5116                                                 continue;
5117
5118                                         enumerator_found = true;
5119
5120                                         if (!GetEnumeratorFilter (ec, mi))
5121                                                 continue;
5122
5123                                         if (result != null) {
5124                                                 if (TypeManager.IsGenericType (result.ReturnType)) {
5125                                                         if (!TypeManager.IsGenericType (mi.ReturnType))
5126                                                                 continue;
5127
5128                                                         MethodBase mb = TypeManager.DropGenericMethodArguments (mi);
5129                                                         Report.SymbolRelatedToPreviousError (t);
5130                                                         Report.Error(1640, loc, "foreach statement cannot operate on variables of type `{0}' " +
5131                                                                      "because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
5132                                                                      TypeManager.CSharpName (t), TypeManager.CSharpSignature (mb));
5133                                                         return false;
5134                                                 }
5135
5136                                                 // Always prefer generics enumerators
5137                                                 if (!TypeManager.IsGenericType (mi.ReturnType)) {
5138                                                         if (TypeManager.ImplementsInterface (mi.DeclaringType, result.DeclaringType) ||
5139                                                             TypeManager.ImplementsInterface (result.DeclaringType, mi.DeclaringType))
5140                                                                 continue;
5141
5142                                                         Report.SymbolRelatedToPreviousError (result);
5143                                                         Report.SymbolRelatedToPreviousError (mi);
5144                                                         Report.Warning (278, 2, loc, "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
5145                                                                         TypeManager.CSharpName (t), "enumerable", TypeManager.CSharpSignature (result), TypeManager.CSharpSignature (mi));
5146                                                         return false;
5147                                                 }
5148                                         }
5149                                         result = mi;
5150                                         tmp_move_next = move_next;
5151                                         tmp_get_cur = get_current;
5152                                         tmp_enumerator_type = enumerator_type;
5153                                         if (mi.DeclaringType == t)
5154                                                 break;
5155                                 }
5156
5157                                 if (result != null) {
5158                                         move_next = tmp_move_next;
5159                                         get_current = tmp_get_cur;
5160                                         enumerator_type = tmp_enumerator_type;
5161                                         MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
5162                                         get_enumerator = new MethodGroupExpr (mi, loc);
5163
5164                                         if (t != expr.Type) {
5165                                                 expr = Convert.ExplicitConversion (
5166                                                         ec, expr, t, loc);
5167                                                 if (expr == null)
5168                                                         throw new InternalErrorException ();
5169                                         }
5170
5171                                         get_enumerator.InstanceExpression = expr;
5172                                         get_enumerator.IsBase = t != expr.Type;
5173
5174                                         return true;
5175                                 }
5176
5177                                 return false;
5178                         }               
5179
5180                         bool ProbeCollectionType (EmitContext ec, Type t)
5181                         {
5182                                 int errors = Report.Errors;
5183                                 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
5184                                         if (TryType (ec, tt))
5185                                                 return true;
5186                                         tt = tt.BaseType;
5187                                 }
5188
5189                                 if (Report.Errors > errors)
5190                                         return false;
5191
5192                                 //
5193                                 // Now try to find the method in the interfaces
5194                                 //
5195                                 Type [] ifaces = TypeManager.GetInterfaces (t);
5196                                 foreach (Type i in ifaces){
5197                                         if (TryType (ec, i))
5198                                                 return true;
5199                                 }
5200
5201                                 return false;
5202                         }
5203
5204                         public override bool Resolve (EmitContext ec)
5205                         {
5206                                 enumerator_type = TypeManager.ienumerator_type;
5207                                 is_disposable = true;
5208
5209                                 if (!ProbeCollectionType (ec, expr.Type)) {
5210                                         Error_Enumerator ();
5211                                         return false;
5212                                 }
5213
5214                                 VarExpr ve = var_type as VarExpr;
5215                                 if (ve != null) {
5216                                         // Infer implicitly typed local variable from foreach enumerable type
5217                                         var_type = new TypeExpression (get_current.PropertyInfo.PropertyType, var_type.Location);
5218                                 }
5219
5220                                 var_type = var_type.ResolveAsTypeTerminal (ec, false);
5221                                 if (var_type == null)
5222                                         return false;
5223                                                                 
5224                                 enumerator = new TemporaryVariable (enumerator_type, loc);
5225                                 enumerator.Resolve (ec);
5226
5227                                 init = new Invocation (get_enumerator, new ArrayList ());
5228                                 init = init.Resolve (ec);
5229                                 if (init == null)
5230                                         return false;
5231
5232                                 Expression move_next_expr;
5233                                 {
5234                                         MemberInfo[] mi = new MemberInfo[] { move_next };
5235                                         MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
5236                                         mg.InstanceExpression = enumerator;
5237
5238                                         move_next_expr = new Invocation (mg, new ArrayList ());
5239                                 }
5240
5241                                 get_current.InstanceExpression = enumerator;
5242
5243                                 Statement block = new CollectionForeachStatement (
5244                                         var_type.Type, variable, get_current, statement, loc);
5245
5246                                 loop = new While (move_next_expr, block, loc);
5247
5248                                 bool ok = true;
5249
5250                                 FlowBranchingException branching = null;
5251                                 if (is_disposable)
5252                                         branching = ec.StartFlowBranching (this);
5253
5254                                 if (!loop.Resolve (ec))
5255                                         ok = false;
5256
5257                                 if (is_disposable) {
5258                                         ResolveFinally (branching);
5259                                         ec.EndFlowBranching ();
5260                                 } else
5261                                         emit_finally = true;
5262
5263                                 return ok;
5264                         }
5265
5266                         protected override void DoEmit (EmitContext ec)
5267                         {
5268                                 ILGenerator ig = ec.ig;
5269
5270                                 enumerator.Store (ec, init);
5271
5272                                 //
5273                                 // Protect the code in a try/finalize block, so that
5274                                 // if the beast implement IDisposable, we get rid of it
5275                                 //
5276                                 if (is_disposable && emit_finally)
5277                                         ig.BeginExceptionBlock ();
5278                         
5279                                 loop.Emit (ec);
5280
5281                                 //
5282                                 // Now the finally block
5283                                 //
5284                                 if (is_disposable) {
5285                                         DoEmitFinally (ec);
5286                                         if (emit_finally)
5287                                                 ig.EndExceptionBlock ();
5288                                 }
5289                         }
5290
5291
5292                         public override void EmitFinally (EmitContext ec)
5293                         {
5294                                 ILGenerator ig = ec.ig;
5295
5296                                 if (enumerator_type.IsValueType) {
5297                                         MethodInfo mi = FetchMethodDispose (enumerator_type);
5298                                         if (mi != null) {
5299                                                 enumerator.EmitLoadAddress (ec);
5300                                                 ig.Emit (OpCodes.Call, mi);
5301                                         } else {
5302                                                 enumerator.Emit (ec);
5303                                                 ig.Emit (OpCodes.Box, enumerator_type);
5304                                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5305                                         }
5306                                 } else {
5307                                         Label call_dispose = ig.DefineLabel ();
5308
5309                                         enumerator.Emit (ec);
5310                                         ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5311                                         ig.Emit (OpCodes.Dup);
5312                                         ig.Emit (OpCodes.Brtrue_S, call_dispose);
5313                                         ig.Emit (OpCodes.Pop);
5314
5315                                         Label end_finally = ig.DefineLabel ();
5316                                         ig.Emit (OpCodes.Br, end_finally);
5317
5318                                         ig.MarkLabel (call_dispose);
5319                                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5320                                         ig.MarkLabel (end_finally);
5321                                 }
5322                         }
5323                 }
5324
5325                 protected class CollectionForeachStatement : Statement
5326                 {
5327                         Type type;
5328                         Expression variable, current, conv;
5329                         Statement statement;
5330                         Assign assign;
5331
5332                         public CollectionForeachStatement (Type type, Expression variable,
5333                                                            Expression current, Statement statement,
5334                                                            Location loc)
5335                         {
5336                                 this.type = type;
5337                                 this.variable = variable;
5338                                 this.current = current;
5339                                 this.statement = statement;
5340                                 this.loc = loc;
5341                         }
5342
5343                         public override bool Resolve (EmitContext ec)
5344                         {
5345                                 current = current.Resolve (ec);
5346                                 if (current == null)
5347                                         return false;
5348
5349                                 conv = Convert.ExplicitConversion (ec, current, type, loc);
5350                                 if (conv == null)
5351                                         return false;
5352
5353                                 assign = new Assign (variable, conv, loc);
5354                                 if (assign.Resolve (ec) == null)
5355                                         return false;
5356
5357                                 if (!statement.Resolve (ec))
5358                                         return false;
5359
5360                                 return true;
5361                         }
5362
5363                         protected override void DoEmit (EmitContext ec)
5364                         {
5365                                 assign.EmitStatement (ec);
5366                                 statement.Emit (ec);
5367                         }
5368                 }
5369
5370                 protected override void CloneTo (CloneContext clonectx, Statement t)
5371                 {
5372                         Foreach target = (Foreach) t;
5373
5374                         target.type = type.Clone (clonectx);
5375                         target.variable = variable.Clone (clonectx);
5376                         target.expr = expr.Clone (clonectx);
5377                         target.statement = statement.Clone (clonectx);
5378                 }
5379         }
5380 }