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