2006-04-27 Jonathan Chambers <jonathan.chambers@ansys.com>
[mcs.git] / mcs / statement.cs
blobc235064f7078dff3a20aa9d3c85b0da3f209e3b5
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 //
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 // (C) 2003, 2004 Novell, Inc.
12 using System;
13 using System.Text;
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Diagnostics;
17 using System.Collections;
18 using System.Collections.Specialized;
20 namespace Mono.CSharp {
22 public abstract class Statement {
23 public Location loc;
25 /// <summary>
26 /// Resolves the statement, true means that all sub-statements
27 /// did resolve ok.
28 // </summary>
29 public virtual bool Resolve (EmitContext ec)
31 return true;
34 /// <summary>
35 /// We already know that the statement is unreachable, but we still
36 /// need to resolve it to catch errors.
37 /// </summary>
38 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
41 // This conflicts with csc's way of doing this, but IMHO it's
42 // the right thing to do.
44 // If something is unreachable, we still check whether it's
45 // correct. This means that you cannot use unassigned variables
46 // in unreachable code, for instance.
49 if (warn)
50 Report.Warning (162, 2, loc, "Unreachable code detected");
52 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
53 bool ok = Resolve (ec);
54 ec.KillFlowBranching ();
56 return ok;
59 /// <summary>
60 /// Return value indicates whether all code paths emitted return.
61 /// </summary>
62 protected abstract void DoEmit (EmitContext ec);
64 /// <summary>
65 /// Utility wrapper routine for Error, just to beautify the code
66 /// </summary>
67 public void Error (int error, string format, params object[] args)
69 Error (error, String.Format (format, args));
72 public void Error (int error, string s)
74 if (!loc.IsNull)
75 Report.Error (error, loc, s);
76 else
77 Report.Error (error, s);
80 /// <summary>
81 /// Return value indicates whether all code paths emitted return.
82 /// </summary>
83 public virtual void Emit (EmitContext ec)
85 ec.Mark (loc, true);
86 DoEmit (ec);
90 public sealed class EmptyStatement : Statement {
92 private EmptyStatement () {}
94 public static readonly EmptyStatement Value = new EmptyStatement ();
96 public override bool Resolve (EmitContext ec)
98 return true;
101 protected override void DoEmit (EmitContext ec)
106 public class If : Statement {
107 Expression expr;
108 public Statement TrueStatement;
109 public Statement FalseStatement;
111 bool is_true_ret;
113 public If (Expression expr, Statement trueStatement, Location l)
115 this.expr = expr;
116 TrueStatement = trueStatement;
117 loc = l;
120 public If (Expression expr,
121 Statement trueStatement,
122 Statement falseStatement,
123 Location l)
125 this.expr = expr;
126 TrueStatement = trueStatement;
127 FalseStatement = falseStatement;
128 loc = l;
131 public override bool Resolve (EmitContext ec)
133 bool ok = true;
135 Report.Debug (1, "START IF BLOCK", loc);
137 expr = Expression.ResolveBoolean (ec, expr, loc);
138 if (expr == null){
139 ok = false;
140 goto skip;
143 Assign ass = expr as Assign;
144 if (ass != null && ass.Source is Constant) {
145 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
149 // Dead code elimination
151 if (expr is BoolConstant){
152 bool take = ((BoolConstant) expr).Value;
154 if (take){
155 if (!TrueStatement.Resolve (ec))
156 return false;
158 if ((FalseStatement != null) &&
159 !FalseStatement.ResolveUnreachable (ec, true))
160 return false;
161 FalseStatement = null;
162 } else {
163 if (!TrueStatement.ResolveUnreachable (ec, true))
164 return false;
165 TrueStatement = null;
167 if ((FalseStatement != null) &&
168 !FalseStatement.Resolve (ec))
169 return false;
172 return true;
174 skip:
175 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
177 ok &= TrueStatement.Resolve (ec);
179 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
181 ec.CurrentBranching.CreateSibling ();
183 if (FalseStatement != null)
184 ok &= FalseStatement.Resolve (ec);
186 ec.EndFlowBranching ();
188 Report.Debug (1, "END IF BLOCK", loc);
190 return ok;
193 protected override void DoEmit (EmitContext ec)
195 ILGenerator ig = ec.ig;
196 Label false_target = ig.DefineLabel ();
197 Label end;
200 // If we're a boolean expression, Resolve() already
201 // eliminated dead code for us.
203 if (expr is BoolConstant){
204 bool take = ((BoolConstant) expr).Value;
206 if (take)
207 TrueStatement.Emit (ec);
208 else if (FalseStatement != null)
209 FalseStatement.Emit (ec);
211 return;
214 expr.EmitBranchable (ec, false_target, false);
216 TrueStatement.Emit (ec);
218 if (FalseStatement != null){
219 bool branch_emitted = false;
221 end = ig.DefineLabel ();
222 if (!is_true_ret){
223 ig.Emit (OpCodes.Br, end);
224 branch_emitted = true;
227 ig.MarkLabel (false_target);
228 FalseStatement.Emit (ec);
230 if (branch_emitted)
231 ig.MarkLabel (end);
232 } else {
233 ig.MarkLabel (false_target);
238 public class Do : Statement {
239 public Expression expr;
240 public readonly Statement EmbeddedStatement;
241 bool infinite;
243 public Do (Statement statement, Expression boolExpr, Location l)
245 expr = boolExpr;
246 EmbeddedStatement = statement;
247 loc = l;
250 public override bool Resolve (EmitContext ec)
252 bool ok = true;
254 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
256 if (!EmbeddedStatement.Resolve (ec))
257 ok = false;
259 expr = Expression.ResolveBoolean (ec, expr, loc);
260 if (expr == null)
261 ok = false;
262 else if (expr is BoolConstant){
263 bool res = ((BoolConstant) expr).Value;
265 if (res)
266 infinite = true;
269 ec.CurrentBranching.Infinite = infinite;
270 ec.EndFlowBranching ();
272 return ok;
275 protected override void DoEmit (EmitContext ec)
277 ILGenerator ig = ec.ig;
278 Label loop = ig.DefineLabel ();
279 Label old_begin = ec.LoopBegin;
280 Label old_end = ec.LoopEnd;
282 ec.LoopBegin = ig.DefineLabel ();
283 ec.LoopEnd = ig.DefineLabel ();
285 ig.MarkLabel (loop);
286 EmbeddedStatement.Emit (ec);
287 ig.MarkLabel (ec.LoopBegin);
290 // Dead code elimination
292 if (expr is BoolConstant){
293 bool res = ((BoolConstant) expr).Value;
295 if (res)
296 ec.ig.Emit (OpCodes.Br, loop);
297 } else
298 expr.EmitBranchable (ec, loop, true);
300 ig.MarkLabel (ec.LoopEnd);
302 ec.LoopBegin = old_begin;
303 ec.LoopEnd = old_end;
307 public class While : Statement {
308 public Expression expr;
309 public readonly Statement Statement;
310 bool infinite, empty;
312 public While (Expression boolExpr, Statement statement, Location l)
314 this.expr = boolExpr;
315 Statement = statement;
316 loc = l;
319 public override bool Resolve (EmitContext ec)
321 bool ok = true;
323 expr = Expression.ResolveBoolean (ec, expr, loc);
324 if (expr == null)
325 return false;
328 // Inform whether we are infinite or not
330 if (expr is BoolConstant){
331 BoolConstant bc = (BoolConstant) expr;
333 if (bc.Value == false){
334 if (!Statement.ResolveUnreachable (ec, true))
335 return false;
336 empty = true;
337 return true;
338 } else
339 infinite = true;
342 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
343 if (!infinite)
344 ec.CurrentBranching.CreateSibling ();
346 if (!Statement.Resolve (ec))
347 ok = false;
349 ec.CurrentBranching.Infinite = infinite;
350 ec.EndFlowBranching ();
352 return ok;
355 protected override void DoEmit (EmitContext ec)
357 if (empty)
358 return;
360 ILGenerator ig = ec.ig;
361 Label old_begin = ec.LoopBegin;
362 Label old_end = ec.LoopEnd;
364 ec.LoopBegin = ig.DefineLabel ();
365 ec.LoopEnd = ig.DefineLabel ();
368 // Inform whether we are infinite or not
370 if (expr is BoolConstant){
371 ig.MarkLabel (ec.LoopBegin);
372 Statement.Emit (ec);
373 ig.Emit (OpCodes.Br, ec.LoopBegin);
376 // Inform that we are infinite (ie, `we return'), only
377 // if we do not `break' inside the code.
379 ig.MarkLabel (ec.LoopEnd);
380 } else {
381 Label while_loop = ig.DefineLabel ();
383 ig.Emit (OpCodes.Br, ec.LoopBegin);
384 ig.MarkLabel (while_loop);
386 Statement.Emit (ec);
388 ig.MarkLabel (ec.LoopBegin);
390 expr.EmitBranchable (ec, while_loop, true);
392 ig.MarkLabel (ec.LoopEnd);
395 ec.LoopBegin = old_begin;
396 ec.LoopEnd = old_end;
400 public class For : Statement {
401 Expression Test;
402 readonly Statement InitStatement;
403 readonly Statement Increment;
404 public readonly Statement Statement;
405 bool infinite, empty;
407 public For (Statement initStatement,
408 Expression test,
409 Statement increment,
410 Statement statement,
411 Location l)
413 InitStatement = initStatement;
414 Test = test;
415 Increment = increment;
416 Statement = statement;
417 loc = l;
420 public override bool Resolve (EmitContext ec)
422 bool ok = true;
424 if (InitStatement != null){
425 if (!InitStatement.Resolve (ec))
426 ok = false;
429 if (Test != null){
430 Test = Expression.ResolveBoolean (ec, Test, loc);
431 if (Test == null)
432 ok = false;
433 else if (Test is BoolConstant){
434 BoolConstant bc = (BoolConstant) Test;
436 if (bc.Value == false){
437 if (!Statement.ResolveUnreachable (ec, true))
438 return false;
439 if ((Increment != null) &&
440 !Increment.ResolveUnreachable (ec, false))
441 return false;
442 empty = true;
443 return true;
444 } else
445 infinite = true;
447 } else
448 infinite = true;
450 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
451 if (!infinite)
452 ec.CurrentBranching.CreateSibling ();
454 if (!Statement.Resolve (ec))
455 ok = false;
457 if (Increment != null){
458 if (!Increment.Resolve (ec))
459 ok = false;
462 ec.CurrentBranching.Infinite = infinite;
463 ec.EndFlowBranching ();
465 return ok;
468 protected override void DoEmit (EmitContext ec)
470 if (empty)
471 return;
473 ILGenerator ig = ec.ig;
474 Label old_begin = ec.LoopBegin;
475 Label old_end = ec.LoopEnd;
476 Label loop = ig.DefineLabel ();
477 Label test = ig.DefineLabel ();
479 if (InitStatement != null && InitStatement != EmptyStatement.Value)
480 InitStatement.Emit (ec);
482 ec.LoopBegin = ig.DefineLabel ();
483 ec.LoopEnd = ig.DefineLabel ();
485 ig.Emit (OpCodes.Br, test);
486 ig.MarkLabel (loop);
487 Statement.Emit (ec);
489 ig.MarkLabel (ec.LoopBegin);
490 if (Increment != EmptyStatement.Value)
491 Increment.Emit (ec);
493 ig.MarkLabel (test);
495 // If test is null, there is no test, and we are just
496 // an infinite loop
498 if (Test != null){
500 // The Resolve code already catches the case for
501 // Test == BoolConstant (false) so we know that
502 // this is true
504 if (Test is BoolConstant)
505 ig.Emit (OpCodes.Br, loop);
506 else
507 Test.EmitBranchable (ec, loop, true);
509 } else
510 ig.Emit (OpCodes.Br, loop);
511 ig.MarkLabel (ec.LoopEnd);
513 ec.LoopBegin = old_begin;
514 ec.LoopEnd = old_end;
518 public class StatementExpression : Statement {
519 ExpressionStatement expr;
521 public StatementExpression (ExpressionStatement expr)
523 this.expr = expr;
524 loc = expr.Location;
527 public override bool Resolve (EmitContext ec)
529 if (expr != null)
530 expr = expr.ResolveStatement (ec);
531 return expr != null;
534 protected override void DoEmit (EmitContext ec)
536 expr.EmitStatement (ec);
539 public override string ToString ()
541 return "StatementExpression (" + expr + ")";
545 /// <summary>
546 /// Implements the return statement
547 /// </summary>
548 public class Return : Statement {
549 public Expression Expr;
551 public Return (Expression expr, Location l)
553 Expr = expr;
554 loc = l;
557 bool in_exc;
559 public override bool Resolve (EmitContext ec)
561 AnonymousContainer am = ec.CurrentAnonymousMethod;
562 if ((am != null) && am.IsIterator && ec.InIterator) {
563 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
564 "statement to return a value, or yield break to end the iteration");
565 return false;
568 if (ec.ReturnType == null){
569 if (Expr != null){
570 if (ec.CurrentAnonymousMethod != null){
571 Report.Error (1662, loc,
572 "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",
573 ec.CurrentAnonymousMethod.GetSignatureForError ());
575 Error (127, "A return keyword must not be followed by any expression when method returns void");
576 return false;
578 } else {
579 if (Expr == null){
580 Error (126, "An object of a type convertible to `{0}' is required " +
581 "for the return statement",
582 TypeManager.CSharpName (ec.ReturnType));
583 return false;
586 Expr = Expr.Resolve (ec);
587 if (Expr == null)
588 return false;
590 if (Expr.Type != ec.ReturnType) {
591 Expr = Convert.ImplicitConversionRequired (
592 ec, Expr, ec.ReturnType, loc);
593 if (Expr == null)
594 return false;
598 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
600 if (ec.CurrentBranching.InTryOrCatch (true)) {
601 ec.CurrentBranching.AddFinallyVector (vector);
602 in_exc = true;
603 } else if (ec.InFinally) {
604 Error (157, "Control cannot leave the body of a finally clause");
605 return false;
606 } else
607 vector.CheckOutParameters (ec.CurrentBranching);
609 if (in_exc)
610 ec.NeedReturnLabel ();
612 ec.CurrentBranching.CurrentUsageVector.Return ();
613 return true;
616 protected override void DoEmit (EmitContext ec)
618 if (Expr != null) {
619 Expr.Emit (ec);
621 if (in_exc)
622 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
625 if (in_exc)
626 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
627 else
628 ec.ig.Emit (OpCodes.Ret);
632 public class Goto : Statement {
633 string target;
634 LabeledStatement label;
636 public override bool Resolve (EmitContext ec)
638 label = ec.CurrentBranching.LookupLabel (target, loc);
639 if (label == null)
640 return false;
642 // If this is a forward goto.
643 if (!label.IsDefined)
644 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
646 ec.CurrentBranching.CurrentUsageVector.Goto ();
647 label.AddReference ();
649 return true;
652 public Goto (string label, Location l)
654 loc = l;
655 target = label;
658 public string Target {
659 get {
660 return target;
664 protected override void DoEmit (EmitContext ec)
666 Label l = label.LabelTarget (ec);
667 ec.ig.Emit (OpCodes.Br, l);
671 public class LabeledStatement : Statement {
672 bool defined;
673 bool referenced;
674 Label label;
675 ILGenerator ig;
677 FlowBranching.UsageVector vectors;
679 public LabeledStatement (Location l)
681 this.loc = l;
684 public Label LabelTarget (EmitContext ec)
686 if (defined)
687 return label;
688 ig = ec.ig;
689 label = ec.ig.DefineLabel ();
690 defined = true;
692 return label;
695 public bool IsDefined {
696 get {
697 return defined;
701 public bool HasBeenReferenced {
702 get {
703 return referenced;
707 public void AddUsageVector (FlowBranching.UsageVector vector)
709 vector = vector.Clone ();
710 vector.Next = vectors;
711 vectors = vector;
714 public override bool Resolve (EmitContext ec)
716 ec.CurrentBranching.Label (vectors);
718 return true;
721 protected override void DoEmit (EmitContext ec)
723 if (ig != null && ig != ec.ig) {
724 // TODO: location is wrong
725 Report.Error (1632, loc, "Control cannot leave the body of an anonymous method");
726 return;
728 LabelTarget (ec);
729 ec.ig.MarkLabel (label);
732 public void AddReference ()
734 referenced = true;
739 /// <summary>
740 /// `goto default' statement
741 /// </summary>
742 public class GotoDefault : Statement {
744 public GotoDefault (Location l)
746 loc = l;
749 public override bool Resolve (EmitContext ec)
751 ec.CurrentBranching.CurrentUsageVector.Goto ();
752 return true;
755 protected override void DoEmit (EmitContext ec)
757 if (ec.Switch == null){
758 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
759 return;
762 if (!ec.Switch.GotDefault){
763 Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
764 return;
766 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
770 /// <summary>
771 /// `goto case' statement
772 /// </summary>
773 public class GotoCase : Statement {
774 Expression expr;
775 SwitchLabel sl;
777 public GotoCase (Expression e, Location l)
779 expr = e;
780 loc = l;
783 public override bool Resolve (EmitContext ec)
785 if (ec.Switch == null){
786 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
787 return false;
790 expr = expr.Resolve (ec);
791 if (expr == null)
792 return false;
794 Constant c = expr as Constant;
795 if (c == null) {
796 Error (150, "A constant value is expected");
797 return false;
800 c = c.ToType (ec.Switch.SwitchType, loc);
801 if (c == null)
802 return false;
804 object val = c.GetValue ();
805 if (val == null)
806 val = SwitchLabel.NullStringCase;
808 sl = (SwitchLabel) ec.Switch.Elements [val];
810 if (sl == null){
811 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", c.GetValue () == null ? "null" : val.ToString ());
812 return false;
815 ec.CurrentBranching.CurrentUsageVector.Goto ();
816 return true;
819 protected override void DoEmit (EmitContext ec)
821 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
825 public class Throw : Statement {
826 Expression expr;
828 public Throw (Expression expr, Location l)
830 this.expr = expr;
831 loc = l;
834 public override bool Resolve (EmitContext ec)
836 ec.CurrentBranching.CurrentUsageVector.Throw ();
838 if (expr != null){
839 expr = expr.Resolve (ec);
840 if (expr == null)
841 return false;
843 ExprClass eclass = expr.eclass;
845 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
846 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
847 expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
848 return false;
851 Type t = expr.Type;
853 if ((t != TypeManager.exception_type) &&
854 !t.IsSubclassOf (TypeManager.exception_type) &&
855 !(expr is NullLiteral)) {
856 Error (155,
857 "The type caught or thrown must be derived " +
858 "from System.Exception");
859 return false;
861 return true;
864 if (!ec.InCatch) {
865 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
866 return false;
869 if (ec.InFinally) {
870 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
871 return false;
873 return true;
876 protected override void DoEmit (EmitContext ec)
878 if (expr == null)
879 ec.ig.Emit (OpCodes.Rethrow);
880 else {
881 expr.Emit (ec);
883 ec.ig.Emit (OpCodes.Throw);
888 public class Break : Statement {
890 public Break (Location l)
892 loc = l;
895 bool crossing_exc;
897 public override bool Resolve (EmitContext ec)
899 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
900 Error (139, "No enclosing loop out of which to break or continue");
901 return false;
902 } else if (ec.InFinally && ec.CurrentBranching.BreakCrossesTryCatchBoundary()) {
903 Error (157, "Control cannot leave the body of a finally clause");
904 return false;
905 } else if (ec.CurrentBranching.InTryOrCatch (false))
906 ec.CurrentBranching.AddFinallyVector (
907 ec.CurrentBranching.CurrentUsageVector);
908 else if (ec.CurrentBranching.InLoop () || ec.CurrentBranching.InSwitch ())
909 ec.CurrentBranching.AddBreakVector (
910 ec.CurrentBranching.CurrentUsageVector);
912 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
914 if (!crossing_exc)
915 ec.NeedReturnLabel ();
917 ec.CurrentBranching.CurrentUsageVector.Break ();
918 return true;
921 protected override void DoEmit (EmitContext ec)
923 ILGenerator ig = ec.ig;
925 if (crossing_exc)
926 ig.Emit (OpCodes.Leave, ec.LoopEnd);
927 else {
928 ig.Emit (OpCodes.Br, ec.LoopEnd);
933 public class Continue : Statement {
935 public Continue (Location l)
937 loc = l;
940 bool crossing_exc;
942 public override bool Resolve (EmitContext ec)
944 if (!ec.CurrentBranching.InLoop ()){
945 Error (139, "No enclosing loop out of which to break or continue");
946 return false;
947 } else if (ec.InFinally) {
948 Error (157, "Control cannot leave the body of a finally clause");
949 return false;
950 } else if (ec.CurrentBranching.InTryOrCatch (false))
951 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
953 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
955 ec.CurrentBranching.CurrentUsageVector.Goto ();
956 return true;
959 protected override void DoEmit (EmitContext ec)
961 Label begin = ec.LoopBegin;
963 if (crossing_exc)
964 ec.ig.Emit (OpCodes.Leave, begin);
965 else
966 ec.ig.Emit (OpCodes.Br, begin);
971 // The information about a user-perceived local variable
973 public class LocalInfo {
974 public Expression Type;
977 // Most of the time a variable will be stored in a LocalBuilder
979 // But sometimes, it will be stored in a field (variables that have been
980 // hoisted by iterators or by anonymous methods). The context of the field will
981 // be stored in the EmitContext
984 public LocalBuilder LocalBuilder;
985 public FieldBuilder FieldBuilder;
987 public Type VariableType;
988 public readonly string Name;
989 public readonly Location Location;
990 public readonly Block Block;
992 public VariableInfo VariableInfo;
994 enum Flags : byte {
995 Used = 1,
996 ReadOnly = 2,
997 Pinned = 4,
998 IsThis = 8,
999 Captured = 16,
1000 AddressTaken = 32,
1001 CompilerGenerated = 64
1004 public enum ReadOnlyContext: byte {
1005 Using,
1006 Foreach,
1007 Fixed
1010 Flags flags;
1011 ReadOnlyContext ro_context;
1013 public LocalInfo (Expression type, string name, Block block, Location l)
1015 Type = type;
1016 Name = name;
1017 Block = block;
1018 Location = l;
1021 public LocalInfo (DeclSpace ds, Block block, Location l)
1023 VariableType = ds.TypeBuilder;
1024 Block = block;
1025 Location = l;
1028 public bool IsThisAssigned (EmitContext ec, Location loc)
1030 if (VariableInfo == null)
1031 throw new Exception ();
1033 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1034 return true;
1036 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1039 public bool IsAssigned (EmitContext ec)
1041 if (VariableInfo == null)
1042 throw new Exception ();
1044 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1047 public bool Resolve (EmitContext ec)
1049 if (VariableType == null) {
1050 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1051 if (texpr == null)
1052 return false;
1054 VariableType = texpr.Type;
1057 if (VariableType == TypeManager.void_type) {
1058 Report.Error (1547, Location,
1059 "Keyword 'void' cannot be used in this context");
1060 return false;
1063 if (VariableType.IsAbstract && VariableType.IsSealed) {
1064 Report.Error (723, Location, "Cannot declare variable of static type `{0}'", TypeManager.CSharpName (VariableType));
1065 return false;
1068 if (VariableType.IsPointer && !ec.InUnsafe)
1069 Expression.UnsafeError (Location);
1071 return true;
1074 public bool IsCaptured {
1075 get {
1076 return (flags & Flags.Captured) != 0;
1079 set {
1080 flags |= Flags.Captured;
1084 public bool AddressTaken {
1085 get {
1086 return (flags & Flags.AddressTaken) != 0;
1089 set {
1090 flags |= Flags.AddressTaken;
1094 public bool CompilerGenerated {
1095 get {
1096 return (flags & Flags.CompilerGenerated) != 0;
1099 set {
1100 flags |= Flags.CompilerGenerated;
1104 public override string ToString ()
1106 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1107 Name, Type, VariableInfo, Location);
1110 public bool Used {
1111 get {
1112 return (flags & Flags.Used) != 0;
1114 set {
1115 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1119 public bool ReadOnly {
1120 get {
1121 return (flags & Flags.ReadOnly) != 0;
1125 public void SetReadOnlyContext (ReadOnlyContext context)
1127 flags |= Flags.ReadOnly;
1128 ro_context = context;
1131 public string GetReadOnlyContext ()
1133 if (!ReadOnly)
1134 throw new InternalErrorException ("Variable is not readonly");
1136 switch (ro_context) {
1137 case ReadOnlyContext.Fixed:
1138 return "fixed variable";
1139 case ReadOnlyContext.Foreach:
1140 return "foreach iteration variable";
1141 case ReadOnlyContext.Using:
1142 return "using variable";
1144 throw new NotImplementedException ();
1148 // Whether the variable is pinned, if Pinned the variable has been
1149 // allocated in a pinned slot with DeclareLocal.
1151 public bool Pinned {
1152 get {
1153 return (flags & Flags.Pinned) != 0;
1155 set {
1156 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1160 public bool IsThis {
1161 get {
1162 return (flags & Flags.IsThis) != 0;
1164 set {
1165 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1170 /// <summary>
1171 /// Block represents a C# block.
1172 /// </summary>
1174 /// <remarks>
1175 /// This class is used in a number of places: either to represent
1176 /// explicit blocks that the programmer places or implicit blocks.
1178 /// Implicit blocks are used as labels or to introduce variable
1179 /// declarations.
1181 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1182 /// they contain extra information that is not necessary on normal blocks.
1183 /// </remarks>
1184 public class Block : Statement {
1185 public Block Parent;
1186 public readonly Location StartLocation;
1187 public Location EndLocation = Location.Null;
1189 public readonly ToplevelBlock Toplevel;
1191 [Flags]
1192 public enum Flags : ushort {
1193 Implicit = 1,
1194 Unchecked = 2,
1195 BlockUsed = 4,
1196 VariablesInitialized = 8,
1197 HasRet = 16,
1198 IsDestructor = 32,
1199 IsToplevel = 64,
1200 Unsafe = 128,
1201 HasVarargs = 256 // Used in ToplevelBlock
1203 protected Flags flags;
1205 public bool Implicit {
1206 get { return (flags & Flags.Implicit) != 0; }
1209 public bool Unchecked {
1210 get { return (flags & Flags.Unchecked) != 0; }
1211 set { flags |= Flags.Unchecked; }
1214 public bool Unsafe {
1215 get { return (flags & Flags.Unsafe) != 0; }
1216 set { flags |= Flags.Unsafe; }
1220 // The statements in this block
1222 ArrayList statements;
1223 int num_statements;
1226 // An array of Blocks. We keep track of children just
1227 // to generate the local variable declarations.
1229 // Statements and child statements are handled through the
1230 // statements.
1232 ArrayList children;
1235 // Labels. (label, block) pairs.
1237 Hashtable labels;
1240 // Keeps track of (name, type) pairs
1242 IDictionary variables;
1245 // Keeps track of constants
1246 Hashtable constants;
1249 // Temporary variables.
1251 ArrayList temporary_variables;
1254 // If this is a switch section, the enclosing switch block.
1256 Block switch_block;
1258 protected static int id;
1260 int this_id;
1262 public Block (Block parent)
1263 : this (parent, (Flags) 0, Location.Null, Location.Null)
1266 public Block (Block parent, Flags flags)
1267 : this (parent, flags, Location.Null, Location.Null)
1270 public Block (Block parent, Location start, Location end)
1271 : this (parent, (Flags) 0, start, end)
1274 public Block (Block parent, Flags flags, Location start, Location end)
1276 if (parent != null)
1277 parent.AddChild (this);
1279 this.Parent = parent;
1280 this.flags = flags;
1281 this.StartLocation = start;
1282 this.EndLocation = end;
1283 this.loc = start;
1284 this_id = id++;
1285 statements = new ArrayList ();
1287 if ((flags & Flags.IsToplevel) != 0)
1288 Toplevel = (ToplevelBlock) this;
1289 else
1290 Toplevel = parent.Toplevel;
1292 if (parent != null && Implicit) {
1293 if (parent.known_variables == null)
1294 parent.known_variables = new Hashtable ();
1295 // share with parent
1296 known_variables = parent.known_variables;
1300 public Block CreateSwitchBlock (Location start)
1302 Block new_block = new Block (this, start, start);
1303 new_block.switch_block = this;
1304 return new_block;
1307 public int ID {
1308 get { return this_id; }
1311 protected IDictionary Variables {
1312 get {
1313 if (variables == null)
1314 variables = new ListDictionary ();
1315 return variables;
1319 void AddChild (Block b)
1321 if (children == null)
1322 children = new ArrayList ();
1324 children.Add (b);
1327 public void SetEndLocation (Location loc)
1329 EndLocation = loc;
1332 /// <summary>
1333 /// Adds a label to the current block.
1334 /// </summary>
1336 /// <returns>
1337 /// false if the name already exists in this block. true
1338 /// otherwise.
1339 /// </returns>
1341 public bool AddLabel (string name, LabeledStatement target, Location loc)
1343 if (switch_block != null)
1344 return switch_block.AddLabel (name, target, loc);
1346 Block cur = this;
1347 while (cur != null) {
1348 if (cur.DoLookupLabel (name) != null) {
1349 Report.Error (
1350 140, loc, "The label `{0}' is a duplicate",
1351 name);
1352 return false;
1355 if (!Implicit)
1356 break;
1358 cur = cur.Parent;
1361 while (cur != null) {
1362 if (cur.DoLookupLabel (name) != null) {
1363 Report.Error (
1364 158, loc,
1365 "The label `{0}' shadows another label " +
1366 "by the same name in a contained scope.",
1367 name);
1368 return false;
1371 if (children != null) {
1372 foreach (Block b in children) {
1373 LabeledStatement s = b.DoLookupLabel (name);
1374 if (s == null)
1375 continue;
1377 Report.Error (
1378 158, s.loc,
1379 "The label `{0}' shadows another " +
1380 "label by the same name in a " +
1381 "contained scope.",
1382 name);
1383 return false;
1388 cur = cur.Parent;
1391 if (labels == null)
1392 labels = new Hashtable ();
1394 labels.Add (name, target);
1395 return true;
1398 public LabeledStatement LookupLabel (string name)
1400 LabeledStatement s = DoLookupLabel (name);
1401 if (s != null)
1402 return s;
1404 if (children == null)
1405 return null;
1407 foreach (Block child in children) {
1408 if (!child.Implicit)
1409 continue;
1411 s = child.LookupLabel (name);
1412 if (s != null)
1413 return s;
1416 return null;
1419 LabeledStatement DoLookupLabel (string name)
1421 if (switch_block != null)
1422 return switch_block.LookupLabel (name);
1424 if (labels != null)
1425 if (labels.Contains (name))
1426 return ((LabeledStatement) labels [name]);
1428 return null;
1431 Hashtable known_variables;
1433 // <summary>
1434 // Marks a variable with name @name as being used in this or a child block.
1435 // If a variable name has been used in a child block, it's illegal to
1436 // declare a variable with the same name in the current block.
1437 // </summary>
1438 void AddKnownVariable (string name, LocalInfo info)
1440 if (known_variables == null)
1441 known_variables = new Hashtable ();
1443 known_variables [name] = info;
1446 LocalInfo GetKnownVariableInfo (string name)
1448 if (known_variables == null)
1449 return null;
1450 return (LocalInfo) known_variables [name];
1453 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1455 Block b = this;
1456 LocalInfo kvi = b.GetKnownVariableInfo (name);
1457 while (kvi == null) {
1458 while (b.Implicit)
1459 b = b.Parent;
1460 b = b.Parent;
1461 if (b == null)
1462 return true;
1463 kvi = b.GetKnownVariableInfo (name);
1466 if (kvi.Block == b)
1467 return true;
1469 // Is kvi.Block nested inside 'b'
1470 if (b.known_variables != kvi.Block.known_variables) {
1472 // If a variable by the same name it defined in a nested block of this
1473 // block, we violate the invariant meaning in a block.
1475 if (b == this) {
1476 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1477 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1478 return false;
1482 // It's ok if the definition is in a nested subblock of b, but not
1483 // nested inside this block -- a definition in a sibling block
1484 // should not affect us.
1486 return true;
1490 // Block 'b' and kvi.Block are the same textual block.
1491 // However, different variables are extant.
1493 // Check if the variable is in scope in both blocks. We use
1494 // an indirect check that depends on AddVariable doing its
1495 // part in maintaining the invariant-meaning-in-block property.
1497 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1498 return true;
1501 // Even though we detected the error when the name is used, we
1502 // treat it as if the variable declaration was in error.
1504 Report.SymbolRelatedToPreviousError (loc, name);
1505 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1506 return false;
1509 public LocalInfo AddVariable (Expression type, string name, Location l)
1511 LocalInfo vi = GetLocalInfo (name);
1512 if (vi != null) {
1513 Report.SymbolRelatedToPreviousError (vi.Location, name);
1514 if (known_variables == vi.Block.known_variables)
1515 Report.Error (128, l,
1516 "A local variable named `{0}' is already defined in this scope", name);
1517 else
1518 Error_AlreadyDeclared (l, name, "parent");
1519 return null;
1522 vi = GetKnownVariableInfo (name);
1523 if (vi != null) {
1524 Report.SymbolRelatedToPreviousError (vi.Location, name);
1525 Error_AlreadyDeclared (l, name, "child");
1526 return null;
1529 int idx;
1530 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1531 if (p != null) {
1532 Report.SymbolRelatedToPreviousError (p.Location, name);
1533 Error_AlreadyDeclared (l, name, "method argument");
1534 return null;
1537 vi = new LocalInfo (type, name, this, l);
1539 Variables.Add (name, vi);
1541 for (Block b = this; b != null; b = b.Parent)
1542 b.AddKnownVariable (name, vi);
1544 if ((flags & Flags.VariablesInitialized) != 0)
1545 throw new Exception ();
1547 return vi;
1550 void Error_AlreadyDeclared (Location loc, string var, string reason)
1552 Report.Error (136, loc, "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning to `{0}', " +
1553 "which is already used in a `{1}' scope", var, reason);
1556 public bool AddConstant (Expression type, string name, Expression value, Location l)
1558 if (AddVariable (type, name, l) == null)
1559 return false;
1561 if (constants == null)
1562 constants = new Hashtable ();
1564 constants.Add (name, value);
1566 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1567 Use ();
1568 return true;
1571 static int next_temp_id = 0;
1573 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1575 if (temporary_variables == null)
1576 temporary_variables = new ArrayList ();
1578 int id = ++next_temp_id;
1579 string name = "$s_" + id.ToString ();
1581 LocalInfo li = new LocalInfo (te, name, this, loc);
1582 li.CompilerGenerated = true;
1583 temporary_variables.Add (li);
1584 return li;
1587 public LocalInfo GetLocalInfo (string name)
1589 for (Block b = this; b != null; b = b.Parent) {
1590 if (b.variables != null) {
1591 LocalInfo ret = b.variables [name] as LocalInfo;
1592 if (ret != null)
1593 return ret;
1596 return null;
1599 public Expression GetVariableType (string name)
1601 LocalInfo vi = GetLocalInfo (name);
1602 return vi == null ? null : vi.Type;
1605 public Expression GetConstantExpression (string name)
1607 for (Block b = this; b != null; b = b.Parent) {
1608 if (b.constants != null) {
1609 Expression ret = b.constants [name] as Expression;
1610 if (ret != null)
1611 return ret;
1614 return null;
1617 public void AddStatement (Statement s)
1619 statements.Add (s);
1620 flags |= Flags.BlockUsed;
1623 public bool Used {
1624 get { return (flags & Flags.BlockUsed) != 0; }
1627 public void Use ()
1629 flags |= Flags.BlockUsed;
1632 public bool HasRet {
1633 get { return (flags & Flags.HasRet) != 0; }
1636 public bool IsDestructor {
1637 get { return (flags & Flags.IsDestructor) != 0; }
1640 public void SetDestructor ()
1642 flags |= Flags.IsDestructor;
1645 VariableMap param_map, local_map;
1647 public VariableMap ParameterMap {
1648 get {
1649 if ((flags & Flags.VariablesInitialized) == 0)
1650 throw new Exception ("Variables have not been initialized yet");
1652 return param_map;
1656 public VariableMap LocalMap {
1657 get {
1658 if ((flags & Flags.VariablesInitialized) == 0)
1659 throw new Exception ("Variables have not been initialized yet");
1661 return local_map;
1665 /// <summary>
1666 /// Emits the variable declarations and labels.
1667 /// </summary>
1668 /// <remarks>
1669 /// tc: is our typecontainer (to resolve type references)
1670 /// ig: is the code generator:
1671 /// </remarks>
1672 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
1674 bool old_unsafe = ec.InUnsafe;
1676 // If some parent block was unsafe, we remain unsafe even if this block
1677 // isn't explicitly marked as such.
1678 ec.InUnsafe |= Unsafe;
1681 // Compute the VariableMap's.
1683 // Unfortunately, we don't know the type when adding variables with
1684 // AddVariable(), so we need to compute this info here.
1687 LocalInfo[] locals;
1688 if (variables != null) {
1689 foreach (LocalInfo li in variables.Values)
1690 li.Resolve (ec);
1692 locals = new LocalInfo [variables.Count];
1693 variables.Values.CopyTo (locals, 0);
1694 } else
1695 locals = new LocalInfo [0];
1697 if (Parent != null)
1698 local_map = new VariableMap (Parent.LocalMap, locals);
1699 else
1700 local_map = new VariableMap (locals);
1702 param_map = new VariableMap (ip);
1703 flags |= Flags.VariablesInitialized;
1705 bool old_check_state = ec.ConstantCheckState;
1706 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1709 // Process this block variables
1711 if (variables != null){
1712 foreach (DictionaryEntry de in variables){
1713 string name = (string) de.Key;
1714 LocalInfo vi = (LocalInfo) de.Value;
1716 if (vi.VariableType == null)
1717 continue;
1719 Type variable_type = vi.VariableType;
1721 if (variable_type.IsPointer){
1723 // Am not really convinced that this test is required (Microsoft does it)
1724 // but the fact is that you would not be able to use the pointer variable
1725 // *anyways*
1727 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1728 vi.Location))
1729 continue;
1732 if (constants == null)
1733 continue;
1735 Expression cv = (Expression) constants [name];
1736 if (cv == null)
1737 continue;
1739 // Don't let 'const int Foo = Foo;' succeed.
1740 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
1741 // which in turn causes the 'must be constant' error to be triggered.
1742 constants.Remove (name);
1744 ec.CurrentBlock = this;
1745 Expression e = cv.Resolve (ec);
1746 if (e == null)
1747 continue;
1749 Constant ce = e as Constant;
1750 if (ce == null){
1751 Const.Error_ExpressionMustBeConstant (vi.Location, name);
1752 continue;
1755 e = ce.ToType (variable_type, vi.Location);
1756 if (e == null)
1757 continue;
1759 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue) {
1760 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
1761 continue;
1764 constants.Add (name, e);
1767 ec.ConstantCheckState = old_check_state;
1770 // Now, handle the children
1772 if (children != null){
1773 foreach (Block b in children)
1774 b.ResolveMeta (toplevel, ec, ip);
1776 ec.InUnsafe = old_unsafe;
1780 // Emits the local variable declarations for a block
1782 public void EmitMeta (EmitContext ec)
1784 ILGenerator ig = ec.ig;
1786 if (variables != null){
1787 bool have_captured_vars = ec.HaveCapturedVariables ();
1789 foreach (DictionaryEntry de in variables){
1790 LocalInfo vi = (LocalInfo) de.Value;
1792 if (have_captured_vars && ec.IsCaptured (vi))
1793 continue;
1795 if (vi.Pinned)
1797 // This is needed to compile on both .NET 1.x and .NET 2.x
1798 // the later introduced `DeclareLocal (Type t, bool pinned)'
1800 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1801 else if (!vi.IsThis)
1802 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1806 if (temporary_variables != null) {
1807 AnonymousContainer am = ec.CurrentAnonymousMethod;
1808 TypeBuilder scope = null;
1809 if ((am != null) && am.IsIterator) {
1810 scope = am.Scope.ScopeTypeBuilder;
1811 if (scope == null)
1812 throw new InternalErrorException ();
1814 foreach (LocalInfo vi in temporary_variables) {
1815 if (scope != null) {
1816 if (vi.FieldBuilder == null)
1817 vi.FieldBuilder = scope.DefineField (
1818 vi.Name, vi.VariableType, FieldAttributes.Assembly);
1819 } else
1820 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1824 if (children != null){
1825 foreach (Block b in children)
1826 b.EmitMeta (ec);
1830 void UsageWarning (FlowBranching.UsageVector vector)
1832 string name;
1834 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1835 foreach (DictionaryEntry de in variables){
1836 LocalInfo vi = (LocalInfo) de.Value;
1838 if (vi.Used)
1839 continue;
1841 name = (string) de.Key;
1843 // vi.VariableInfo can be null for 'catch' variables
1844 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo)){
1845 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
1846 } else {
1847 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
1853 bool unreachable_shown;
1854 bool unreachable;
1856 private void CheckPossibleMistakenEmptyStatement (Statement s)
1858 Statement body;
1860 // Some statements are wrapped by a Block. Since
1861 // others' internal could be changed, here I treat
1862 // them as possibly wrapped by Block equally.
1863 Block b = s as Block;
1864 if (b != null && b.statements.Count == 1)
1865 s = (Statement) b.statements [0];
1867 if (s is Lock)
1868 body = ((Lock) s).Statement;
1869 else if (s is For)
1870 body = ((For) s).Statement;
1871 else if (s is Foreach)
1872 body = ((Foreach) s).Statement;
1873 else if (s is While)
1874 body = ((While) s).Statement;
1875 else if (s is Using)
1876 body = ((Using) s).Statement;
1877 else if (s is Fixed)
1878 body = ((Fixed) s).Statement;
1879 else
1880 return;
1882 if (body == null || body is EmptyStatement)
1883 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
1886 public override bool Resolve (EmitContext ec)
1888 Block prev_block = ec.CurrentBlock;
1889 bool ok = true;
1891 int errors = Report.Errors;
1893 ec.CurrentBlock = this;
1894 ec.StartFlowBranching (this);
1896 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1898 int statement_count = statements.Count;
1899 for (int ix = 0; ix < statement_count; ix++){
1900 Statement s = (Statement) statements [ix];
1901 // Check possible empty statement (CS0642)
1902 if (RootContext.WarningLevel >= 3 &&
1903 ix + 1 < statement_count &&
1904 statements [ix + 1] is Block)
1905 CheckPossibleMistakenEmptyStatement (s);
1908 // Warn if we detect unreachable code.
1910 if (unreachable) {
1911 if (s is EmptyStatement)
1912 continue;
1914 if (s is Block)
1915 ((Block) s).unreachable = true;
1917 if (!unreachable_shown) {
1918 Report.Warning (162, 2, s.loc, "Unreachable code detected");
1919 unreachable_shown = true;
1924 // Note that we're not using ResolveUnreachable() for unreachable
1925 // statements here. ResolveUnreachable() creates a temporary
1926 // flow branching and kills it afterwards. This leads to problems
1927 // if you have two unreachable statements where the first one
1928 // assigns a variable and the second one tries to access it.
1931 if (!s.Resolve (ec)) {
1932 ok = false;
1933 statements [ix] = EmptyStatement.Value;
1934 continue;
1937 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1938 statements [ix] = EmptyStatement.Value;
1940 num_statements = ix + 1;
1941 if (s is LabeledStatement)
1942 unreachable = false;
1943 else
1944 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1947 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1948 ec.CurrentBranching, statement_count, num_statements);
1950 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1952 ec.CurrentBlock = prev_block;
1954 // If we're a non-static `struct' constructor which doesn't have an
1955 // initializer, then we must initialize all of the struct's fields.
1956 if ((flags & Flags.IsToplevel) != 0 &&
1957 !Toplevel.IsThisAssigned (ec) &&
1958 vector.Reachability.Throws != FlowBranching.FlowReturns.Always)
1959 ok = false;
1961 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1962 foreach (LabeledStatement label in labels.Values)
1963 if (!label.HasBeenReferenced)
1964 Report.Warning (164, 2, label.loc,
1965 "This label has not been referenced");
1968 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1970 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1971 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1972 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1973 flags |= Flags.HasRet;
1975 if (ok && (errors == Report.Errors)) {
1976 if (RootContext.WarningLevel >= 3)
1977 UsageWarning (vector);
1980 return ok;
1983 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1985 unreachable_shown = true;
1986 unreachable = true;
1988 if (warn)
1989 Report.Warning (162, 2, loc, "Unreachable code detected");
1991 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1992 bool ok = Resolve (ec);
1993 ec.KillFlowBranching ();
1995 return ok;
1998 protected override void DoEmit (EmitContext ec)
2000 for (int ix = 0; ix < num_statements; ix++){
2001 Statement s = (Statement) statements [ix];
2003 // Check whether we are the last statement in a
2004 // top-level block.
2006 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2007 ec.IsLastStatement = true;
2008 else
2009 ec.IsLastStatement = false;
2011 s.Emit (ec);
2015 public override void Emit (EmitContext ec)
2017 Block prev_block = ec.CurrentBlock;
2019 ec.CurrentBlock = this;
2021 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2022 bool is_lexical_block = !Implicit && (Parent != null);
2024 if (emit_debug_info) {
2025 if (is_lexical_block)
2026 ec.BeginScope ();
2028 if (variables != null) {
2029 foreach (DictionaryEntry de in variables) {
2030 string name = (string) de.Key;
2031 LocalInfo vi = (LocalInfo) de.Value;
2033 if (vi.LocalBuilder == null)
2034 continue;
2036 ec.DefineLocalVariable (name, vi.LocalBuilder);
2040 ec.Mark (StartLocation, true);
2041 ec.EmitScopeInitFromBlock (this);
2042 DoEmit (ec);
2043 ec.Mark (EndLocation, true);
2045 if (emit_debug_info && is_lexical_block)
2046 ec.EndScope ();
2048 ec.CurrentBlock = prev_block;
2052 // Returns true if we ar ea child of `b'.
2054 public bool IsChildOf (Block b)
2056 Block current = this;
2058 do {
2059 if (current.Parent == b)
2060 return true;
2061 current = current.Parent;
2062 } while (current != null);
2063 return false;
2066 public override string ToString ()
2068 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2073 // A toplevel block contains extra information, the split is done
2074 // only to separate information that would otherwise bloat the more
2075 // lightweight Block.
2077 // In particular, this was introduced when the support for Anonymous
2078 // Methods was implemented.
2080 public class ToplevelBlock : Block {
2082 // Pointer to the host of this anonymous method, or null
2083 // if we are the topmost block
2085 ToplevelBlock container;
2086 CaptureContext capture_context;
2087 FlowBranching top_level_branching;
2089 Hashtable capture_contexts;
2090 ArrayList children;
2092 public bool HasVarargs {
2093 get { return (flags & Flags.HasVarargs) != 0; }
2094 set { flags |= Flags.HasVarargs; }
2098 // The parameters for the block.
2100 public readonly Parameters Parameters;
2102 public void RegisterCaptureContext (CaptureContext cc)
2104 if (capture_contexts == null)
2105 capture_contexts = new Hashtable ();
2106 capture_contexts [cc] = cc;
2109 public void CompleteContexts ()
2111 if (capture_contexts == null)
2112 return;
2114 foreach (CaptureContext cc in capture_contexts.Keys){
2115 cc.LinkScopes ();
2119 public CaptureContext ToplevelBlockCaptureContext {
2120 get { return capture_context; }
2123 public ToplevelBlock Container {
2124 get { return container; }
2127 protected void AddChild (ToplevelBlock block)
2129 if (children == null)
2130 children = new ArrayList ();
2132 children.Add (block);
2136 // Parent is only used by anonymous blocks to link back to their
2137 // parents
2139 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2140 this (container, (Flags) 0, parameters, start)
2144 public ToplevelBlock (Parameters parameters, Location start) :
2145 this (null, (Flags) 0, parameters, start)
2149 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2150 this (null, flags, parameters, start)
2154 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2155 base (null, flags | Flags.IsToplevel, start, Location.Null)
2157 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2158 this.container = container;
2160 if (container != null)
2161 container.AddChild (this);
2164 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2168 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2170 if (capture_context == null)
2171 capture_context = new CaptureContext (this, loc, host);
2174 public CaptureContext CaptureContext {
2175 get { return capture_context; }
2178 public FlowBranching TopLevelBranching {
2179 get { return top_level_branching; }
2183 // This is used if anonymous methods are used inside an iterator
2184 // (see 2test-22.cs for an example).
2186 // The AnonymousMethod is created while parsing - at a time when we don't
2187 // know yet that we're inside an iterator, so it's `Container' is initially
2188 // null. Later on, when resolving the iterator, we need to move the
2189 // anonymous method into that iterator.
2191 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2193 foreach (ToplevelBlock block in children) {
2194 if (block.CaptureContext == null)
2195 continue;
2197 block.container = new_parent;
2198 block.CaptureContext.ReParent (new_parent, new_host);
2203 // Returns a `ParameterReference' for the given name, or null if there
2204 // is no such parameter
2206 public ParameterReference GetParameterReference (string name, Location loc)
2208 Parameter par;
2209 int idx;
2211 for (ToplevelBlock t = this; t != null; t = t.Container) {
2212 Parameters pars = t.Parameters;
2213 par = pars.GetParameterByName (name, out idx);
2214 if (par != null)
2215 return new ParameterReference (par, this, idx, loc);
2217 return null;
2221 // Whether the parameter named `name' is local to this block,
2222 // or false, if the parameter belongs to an encompassing block.
2224 public bool IsLocalParameter (string name)
2226 return Parameters.GetParameterByName (name) != null;
2230 // Whether the `name' is a parameter reference
2232 public bool IsParameterReference (string name)
2234 for (ToplevelBlock t = this; t != null; t = t.Container) {
2235 if (t.IsLocalParameter (name))
2236 return true;
2238 return false;
2241 LocalInfo this_variable = null;
2243 // <summary>
2244 // Returns the "this" instance variable of this block.
2245 // See AddThisVariable() for more information.
2246 // </summary>
2247 public LocalInfo ThisVariable {
2248 get { return this_variable; }
2252 // <summary>
2253 // This is used by non-static `struct' constructors which do not have an
2254 // initializer - in this case, the constructor must initialize all of the
2255 // struct's fields. To do this, we add a "this" variable and use the flow
2256 // analysis code to ensure that it's been fully initialized before control
2257 // leaves the constructor.
2258 // </summary>
2259 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2261 if (this_variable == null) {
2262 this_variable = new LocalInfo (ds, this, l);
2263 this_variable.Used = true;
2264 this_variable.IsThis = true;
2266 Variables.Add ("this", this_variable);
2269 return this_variable;
2272 public bool IsThisAssigned (EmitContext ec)
2274 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2277 public bool ResolveMeta (EmitContext ec, Parameters ip)
2279 int errors = Report.Errors;
2281 if (top_level_branching != null)
2282 return true;
2284 ResolveMeta (this, ec, ip);
2286 top_level_branching = ec.StartFlowBranching (this);
2288 return Report.Errors == errors;
2292 public class SwitchLabel {
2293 Expression label;
2294 object converted;
2295 Location loc;
2297 Label il_label;
2298 bool il_label_set;
2299 Label il_label_code;
2300 bool il_label_code_set;
2302 public static readonly object NullStringCase = new object ();
2305 // if expr == null, then it is the default case.
2307 public SwitchLabel (Expression expr, Location l)
2309 label = expr;
2310 loc = l;
2313 public Expression Label {
2314 get {
2315 return label;
2319 public object Converted {
2320 get {
2321 return converted;
2325 public Label GetILLabel (EmitContext ec)
2327 if (!il_label_set){
2328 il_label = ec.ig.DefineLabel ();
2329 il_label_set = true;
2331 return il_label;
2334 public Label GetILLabelCode (EmitContext ec)
2336 if (!il_label_code_set){
2337 il_label_code = ec.ig.DefineLabel ();
2338 il_label_code_set = true;
2340 return il_label_code;
2344 // Resolves the expression, reduces it to a literal if possible
2345 // and then converts it to the requested type.
2347 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2349 Expression e = label.Resolve (ec);
2351 if (e == null)
2352 return false;
2354 Constant c = e as Constant;
2355 if (c == null){
2356 Report.Error (150, loc, "A constant value is expected");
2357 return false;
2360 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2361 converted = NullStringCase;
2362 return true;
2365 c = c.ToType (required_type, loc);
2366 if (c == null)
2367 return false;
2369 converted = c.GetValue ();
2370 return true;
2373 public void Erorr_AlreadyOccurs ()
2375 string label;
2376 if (converted == null)
2377 label = "default";
2378 else if (converted == NullStringCase)
2379 label = "null";
2380 else
2381 label = converted.ToString ();
2383 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2387 public class SwitchSection {
2388 // An array of SwitchLabels.
2389 public readonly ArrayList Labels;
2390 public readonly Block Block;
2392 public SwitchSection (ArrayList labels, Block block)
2394 Labels = labels;
2395 Block = block;
2399 public class Switch : Statement {
2400 public readonly ArrayList Sections;
2401 public Expression Expr;
2403 /// <summary>
2404 /// Maps constants whose type type SwitchType to their SwitchLabels.
2405 /// </summary>
2406 public IDictionary Elements;
2408 /// <summary>
2409 /// The governing switch type
2410 /// </summary>
2411 public Type SwitchType;
2414 // Computed
2416 Label default_target;
2417 Expression new_expr;
2418 bool is_constant;
2419 SwitchSection constant_section;
2420 SwitchSection default_section;
2423 // The types allowed to be implicitly cast from
2424 // on the governing type
2426 static Type [] allowed_types;
2428 public Switch (Expression e, ArrayList sects, Location l)
2430 Expr = e;
2431 Sections = sects;
2432 loc = l;
2435 public bool GotDefault {
2436 get {
2437 return default_section != null;
2441 public Label DefaultTarget {
2442 get {
2443 return default_target;
2448 // Determines the governing type for a switch. The returned
2449 // expression might be the expression from the switch, or an
2450 // expression that includes any potential conversions to the
2451 // integral types or to string.
2453 Expression SwitchGoverningType (EmitContext ec, Type t)
2455 if (t == TypeManager.byte_type ||
2456 t == TypeManager.sbyte_type ||
2457 t == TypeManager.ushort_type ||
2458 t == TypeManager.short_type ||
2459 t == TypeManager.uint32_type ||
2460 t == TypeManager.int32_type ||
2461 t == TypeManager.uint64_type ||
2462 t == TypeManager.int64_type ||
2463 t == TypeManager.char_type ||
2464 t == TypeManager.string_type ||
2465 t == TypeManager.bool_type ||
2466 t.IsSubclassOf (TypeManager.enum_type))
2467 return Expr;
2469 if (allowed_types == null){
2470 allowed_types = new Type [] {
2471 TypeManager.sbyte_type,
2472 TypeManager.byte_type,
2473 TypeManager.short_type,
2474 TypeManager.ushort_type,
2475 TypeManager.int32_type,
2476 TypeManager.uint32_type,
2477 TypeManager.int64_type,
2478 TypeManager.uint64_type,
2479 TypeManager.char_type,
2480 TypeManager.string_type,
2481 TypeManager.bool_type
2486 // Try to find a *user* defined implicit conversion.
2488 // If there is no implicit conversion, or if there are multiple
2489 // conversions, we have to report an error
2491 Expression converted = null;
2492 foreach (Type tt in allowed_types){
2493 Expression e;
2495 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2496 if (e == null)
2497 continue;
2500 // Ignore over-worked ImplicitUserConversions that do
2501 // an implicit conversion in addition to the user conversion.
2503 if (!(e is UserCast))
2504 continue;
2506 if (converted != null){
2507 Report.ExtraInformation (
2508 loc,
2509 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2510 TypeManager.CSharpName (Expr.Type)));
2511 return null;
2514 converted = e;
2516 return converted;
2520 // Performs the basic sanity checks on the switch statement
2521 // (looks for duplicate keys and non-constant expressions).
2523 // It also returns a hashtable with the keys that we will later
2524 // use to compute the switch tables
2526 bool CheckSwitch (EmitContext ec)
2528 bool error = false;
2529 Elements = Sections.Count > 10 ?
2530 (IDictionary)new Hashtable () :
2531 (IDictionary)new ListDictionary ();
2533 foreach (SwitchSection ss in Sections){
2534 foreach (SwitchLabel sl in ss.Labels){
2535 if (sl.Label == null){
2536 if (default_section != null){
2537 sl.Erorr_AlreadyOccurs ();
2538 error = true;
2540 default_section = ss;
2541 continue;
2544 if (!sl.ResolveAndReduce (ec, SwitchType)){
2545 error = true;
2546 continue;
2549 object key = sl.Converted;
2550 try {
2551 Elements.Add (key, sl);
2553 catch (ArgumentException) {
2554 sl.Erorr_AlreadyOccurs ();
2555 error = true;
2559 return !error;
2562 void EmitObjectInteger (ILGenerator ig, object k)
2564 if (k is int)
2565 IntConstant.EmitInt (ig, (int) k);
2566 else if (k is Constant) {
2567 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2569 else if (k is uint)
2570 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2571 else if (k is long)
2573 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2575 IntConstant.EmitInt (ig, (int) (long) k);
2576 ig.Emit (OpCodes.Conv_I8);
2578 else
2579 LongConstant.EmitLong (ig, (long) k);
2581 else if (k is ulong)
2583 ulong ul = (ulong) k;
2584 if (ul < (1L<<32))
2586 IntConstant.EmitInt (ig, unchecked ((int) ul));
2587 ig.Emit (OpCodes.Conv_U8);
2589 else
2591 LongConstant.EmitLong (ig, unchecked ((long) ul));
2594 else if (k is char)
2595 IntConstant.EmitInt (ig, (int) ((char) k));
2596 else if (k is sbyte)
2597 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2598 else if (k is byte)
2599 IntConstant.EmitInt (ig, (int) ((byte) k));
2600 else if (k is short)
2601 IntConstant.EmitInt (ig, (int) ((short) k));
2602 else if (k is ushort)
2603 IntConstant.EmitInt (ig, (int) ((ushort) k));
2604 else if (k is bool)
2605 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2606 else
2607 throw new Exception ("Unhandled case");
2610 // structure used to hold blocks of keys while calculating table switch
2611 class KeyBlock : IComparable
2613 public KeyBlock (long _nFirst)
2615 nFirst = nLast = _nFirst;
2617 public long nFirst;
2618 public long nLast;
2619 public ArrayList rgKeys = null;
2620 // how many items are in the bucket
2621 public int Size = 1;
2622 public int Length
2624 get { return (int) (nLast - nFirst + 1); }
2626 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2628 return kbLast.nLast - kbFirst.nFirst + 1;
2630 public int CompareTo (object obj)
2632 KeyBlock kb = (KeyBlock) obj;
2633 int nLength = Length;
2634 int nLengthOther = kb.Length;
2635 if (nLengthOther == nLength)
2636 return (int) (kb.nFirst - nFirst);
2637 return nLength - nLengthOther;
2641 /// <summary>
2642 /// This method emits code for a lookup-based switch statement (non-string)
2643 /// Basically it groups the cases into blocks that are at least half full,
2644 /// and then spits out individual lookup opcodes for each block.
2645 /// It emits the longest blocks first, and short blocks are just
2646 /// handled with direct compares.
2647 /// </summary>
2648 /// <param name="ec"></param>
2649 /// <param name="val"></param>
2650 /// <returns></returns>
2651 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2653 int cElements = Elements.Count;
2654 object [] rgKeys = new object [cElements];
2655 Elements.Keys.CopyTo (rgKeys, 0);
2656 Array.Sort (rgKeys);
2658 // initialize the block list with one element per key
2659 ArrayList rgKeyBlocks = new ArrayList ();
2660 foreach (object key in rgKeys)
2661 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2663 KeyBlock kbCurr;
2664 // iteratively merge the blocks while they are at least half full
2665 // there's probably a really cool way to do this with a tree...
2666 while (rgKeyBlocks.Count > 1)
2668 ArrayList rgKeyBlocksNew = new ArrayList ();
2669 kbCurr = (KeyBlock) rgKeyBlocks [0];
2670 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2672 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2673 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2675 // merge blocks
2676 kbCurr.nLast = kb.nLast;
2677 kbCurr.Size += kb.Size;
2679 else
2681 // start a new block
2682 rgKeyBlocksNew.Add (kbCurr);
2683 kbCurr = kb;
2686 rgKeyBlocksNew.Add (kbCurr);
2687 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2688 break;
2689 rgKeyBlocks = rgKeyBlocksNew;
2692 // initialize the key lists
2693 foreach (KeyBlock kb in rgKeyBlocks)
2694 kb.rgKeys = new ArrayList ();
2696 // fill the key lists
2697 int iBlockCurr = 0;
2698 if (rgKeyBlocks.Count > 0) {
2699 kbCurr = (KeyBlock) rgKeyBlocks [0];
2700 foreach (object key in rgKeys)
2702 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2703 System.Convert.ToInt64 (key) > kbCurr.nLast;
2704 if (fNextBlock)
2705 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2706 kbCurr.rgKeys.Add (key);
2710 // sort the blocks so we can tackle the largest ones first
2711 rgKeyBlocks.Sort ();
2713 // okay now we can start...
2714 ILGenerator ig = ec.ig;
2715 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2716 Label lblDefault = ig.DefineLabel ();
2718 Type typeKeys = null;
2719 if (rgKeys.Length > 0)
2720 typeKeys = rgKeys [0].GetType (); // used for conversions
2722 Type compare_type;
2724 if (TypeManager.IsEnumType (SwitchType))
2725 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2726 else
2727 compare_type = SwitchType;
2729 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2731 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2732 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2733 if (kb.Length <= 2)
2735 foreach (object key in kb.rgKeys)
2737 ig.Emit (OpCodes.Ldloc, val);
2738 EmitObjectInteger (ig, key);
2739 SwitchLabel sl = (SwitchLabel) Elements [key];
2740 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2743 else
2745 // TODO: if all the keys in the block are the same and there are
2746 // no gaps/defaults then just use a range-check.
2747 if (compare_type == TypeManager.int64_type ||
2748 compare_type == TypeManager.uint64_type)
2750 // TODO: optimize constant/I4 cases
2752 // check block range (could be > 2^31)
2753 ig.Emit (OpCodes.Ldloc, val);
2754 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2755 ig.Emit (OpCodes.Blt, lblDefault);
2756 ig.Emit (OpCodes.Ldloc, val);
2757 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2758 ig.Emit (OpCodes.Bgt, lblDefault);
2760 // normalize range
2761 ig.Emit (OpCodes.Ldloc, val);
2762 if (kb.nFirst != 0)
2764 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2765 ig.Emit (OpCodes.Sub);
2767 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2769 else
2771 // normalize range
2772 ig.Emit (OpCodes.Ldloc, val);
2773 int nFirst = (int) kb.nFirst;
2774 if (nFirst > 0)
2776 IntConstant.EmitInt (ig, nFirst);
2777 ig.Emit (OpCodes.Sub);
2779 else if (nFirst < 0)
2781 IntConstant.EmitInt (ig, -nFirst);
2782 ig.Emit (OpCodes.Add);
2786 // first, build the list of labels for the switch
2787 int iKey = 0;
2788 int cJumps = kb.Length;
2789 Label [] rgLabels = new Label [cJumps];
2790 for (int iJump = 0; iJump < cJumps; iJump++)
2792 object key = kb.rgKeys [iKey];
2793 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2795 SwitchLabel sl = (SwitchLabel) Elements [key];
2796 rgLabels [iJump] = sl.GetILLabel (ec);
2797 iKey++;
2799 else
2800 rgLabels [iJump] = lblDefault;
2802 // emit the switch opcode
2803 ig.Emit (OpCodes.Switch, rgLabels);
2806 // mark the default for this block
2807 if (iBlock != 0)
2808 ig.MarkLabel (lblDefault);
2811 // TODO: find the default case and emit it here,
2812 // to prevent having to do the following jump.
2813 // make sure to mark other labels in the default section
2815 // the last default just goes to the end
2816 ig.Emit (OpCodes.Br, lblDefault);
2818 // now emit the code for the sections
2819 bool fFoundDefault = false;
2820 foreach (SwitchSection ss in Sections)
2822 foreach (SwitchLabel sl in ss.Labels)
2824 ig.MarkLabel (sl.GetILLabel (ec));
2825 ig.MarkLabel (sl.GetILLabelCode (ec));
2826 if (sl.Label == null)
2828 ig.MarkLabel (lblDefault);
2829 fFoundDefault = true;
2832 ss.Block.Emit (ec);
2833 //ig.Emit (OpCodes.Br, lblEnd);
2836 if (!fFoundDefault) {
2837 ig.MarkLabel (lblDefault);
2839 ig.MarkLabel (lblEnd);
2842 // This simple emit switch works, but does not take advantage of the
2843 // `switch' opcode.
2844 // TODO: remove non-string logic from here
2845 // TODO: binary search strings?
2847 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2849 ILGenerator ig = ec.ig;
2850 Label end_of_switch = ig.DefineLabel ();
2851 Label next_test = ig.DefineLabel ();
2852 Label null_target = ig.DefineLabel ();
2853 bool first_test = true;
2854 bool pending_goto_end = false;
2855 bool null_marked = false;
2856 bool null_found;
2858 ig.Emit (OpCodes.Ldloc, val);
2860 if (Elements.Contains (SwitchLabel.NullStringCase)){
2861 ig.Emit (OpCodes.Brfalse, null_target);
2862 } else
2863 ig.Emit (OpCodes.Brfalse, default_target);
2865 ig.Emit (OpCodes.Ldloc, val);
2866 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2867 ig.Emit (OpCodes.Stloc, val);
2869 int section_count = Sections.Count;
2870 for (int section = 0; section < section_count; section++){
2871 SwitchSection ss = (SwitchSection) Sections [section];
2873 if (ss == default_section)
2874 continue;
2876 Label sec_begin = ig.DefineLabel ();
2878 ig.Emit (OpCodes.Nop);
2880 if (pending_goto_end)
2881 ig.Emit (OpCodes.Br, end_of_switch);
2883 int label_count = ss.Labels.Count;
2884 null_found = false;
2885 for (int label = 0; label < label_count; label++){
2886 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2887 ig.MarkLabel (sl.GetILLabel (ec));
2889 if (!first_test){
2890 ig.MarkLabel (next_test);
2891 next_test = ig.DefineLabel ();
2894 // If we are the default target
2896 if (sl.Label != null){
2897 object lit = sl.Converted;
2899 if (lit == SwitchLabel.NullStringCase){
2900 null_found = true;
2901 if (label_count == 1)
2902 ig.Emit (OpCodes.Br, next_test);
2903 continue;
2906 ig.Emit (OpCodes.Ldloc, val);
2907 ig.Emit (OpCodes.Ldstr, (string)lit);
2908 if (label_count == 1)
2909 ig.Emit (OpCodes.Bne_Un, next_test);
2910 else {
2911 if (label+1 == label_count)
2912 ig.Emit (OpCodes.Bne_Un, next_test);
2913 else
2914 ig.Emit (OpCodes.Beq, sec_begin);
2918 if (null_found) {
2919 ig.MarkLabel (null_target);
2920 null_marked = true;
2922 ig.MarkLabel (sec_begin);
2923 foreach (SwitchLabel sl in ss.Labels)
2924 ig.MarkLabel (sl.GetILLabelCode (ec));
2926 ss.Block.Emit (ec);
2927 pending_goto_end = !ss.Block.HasRet;
2928 first_test = false;
2930 ig.MarkLabel (next_test);
2931 ig.MarkLabel (default_target);
2932 if (!null_marked)
2933 ig.MarkLabel (null_target);
2934 if (default_section != null)
2935 default_section.Block.Emit (ec);
2936 ig.MarkLabel (end_of_switch);
2939 SwitchSection FindSection (SwitchLabel label)
2941 foreach (SwitchSection ss in Sections){
2942 foreach (SwitchLabel sl in ss.Labels){
2943 if (label == sl)
2944 return ss;
2948 return null;
2951 public override bool Resolve (EmitContext ec)
2953 Expr = Expr.Resolve (ec);
2954 if (Expr == null)
2955 return false;
2957 new_expr = SwitchGoverningType (ec, Expr.Type);
2958 if (new_expr == null){
2959 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2960 return false;
2963 // Validate switch.
2964 SwitchType = new_expr.Type;
2966 if (!CheckSwitch (ec))
2967 return false;
2969 Switch old_switch = ec.Switch;
2970 ec.Switch = this;
2971 ec.Switch.SwitchType = SwitchType;
2973 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2974 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2976 is_constant = new_expr is Constant;
2977 if (is_constant) {
2978 object key = ((Constant) new_expr).GetValue ();
2979 SwitchLabel label = (SwitchLabel) Elements [key];
2981 constant_section = FindSection (label);
2982 if (constant_section == null)
2983 constant_section = default_section;
2986 bool first = true;
2987 foreach (SwitchSection ss in Sections){
2988 if (!first)
2989 ec.CurrentBranching.CreateSibling (
2990 null, FlowBranching.SiblingType.SwitchSection);
2991 else
2992 first = false;
2994 if (is_constant && (ss != constant_section)) {
2995 // If we're a constant switch, we're only emitting
2996 // one single section - mark all the others as
2997 // unreachable.
2998 ec.CurrentBranching.CurrentUsageVector.Goto ();
2999 if (!ss.Block.ResolveUnreachable (ec, true))
3000 return false;
3001 } else {
3002 if (!ss.Block.Resolve (ec))
3003 return false;
3007 if (default_section == null)
3008 ec.CurrentBranching.CreateSibling (
3009 null, FlowBranching.SiblingType.SwitchSection);
3011 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3012 ec.Switch = old_switch;
3014 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3015 reachability);
3017 return true;
3020 protected override void DoEmit (EmitContext ec)
3022 ILGenerator ig = ec.ig;
3024 // Store variable for comparission purposes
3025 LocalBuilder value;
3026 if (!is_constant) {
3027 value = ig.DeclareLocal (SwitchType);
3028 new_expr.Emit (ec);
3029 ig.Emit (OpCodes.Stloc, value);
3030 } else
3031 value = null;
3033 default_target = ig.DefineLabel ();
3036 // Setup the codegen context
3038 Label old_end = ec.LoopEnd;
3039 Switch old_switch = ec.Switch;
3041 ec.LoopEnd = ig.DefineLabel ();
3042 ec.Switch = this;
3044 // Emit Code.
3045 if (is_constant) {
3046 if (constant_section != null)
3047 constant_section.Block.Emit (ec);
3048 } else if (SwitchType == TypeManager.string_type)
3049 SimpleSwitchEmit (ec, value);
3050 else
3051 TableSwitchEmit (ec, value);
3053 // Restore context state.
3054 ig.MarkLabel (ec.LoopEnd);
3057 // Restore the previous context
3059 ec.LoopEnd = old_end;
3060 ec.Switch = old_switch;
3064 public abstract class ExceptionStatement : Statement
3066 public abstract void EmitFinally (EmitContext ec);
3068 protected bool emit_finally = true;
3069 ArrayList parent_vectors;
3071 protected void DoEmitFinally (EmitContext ec)
3073 if (emit_finally)
3074 ec.ig.BeginFinallyBlock ();
3075 else if (ec.InIterator)
3076 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3077 EmitFinally (ec);
3080 protected void ResolveFinally (FlowBranchingException branching)
3082 emit_finally = branching.EmitFinally;
3083 if (!emit_finally)
3084 branching.Parent.StealFinallyClauses (ref parent_vectors);
3088 public class Lock : ExceptionStatement {
3089 Expression expr;
3090 public Statement Statement;
3091 TemporaryVariable temp;
3093 public Lock (Expression expr, Statement stmt, Location l)
3095 this.expr = expr;
3096 Statement = stmt;
3097 loc = l;
3100 public override bool Resolve (EmitContext ec)
3102 expr = expr.Resolve (ec);
3103 if (expr == null)
3104 return false;
3106 if (expr.Type.IsValueType){
3107 Report.Error (185, loc,
3108 "`{0}' is not a reference type as required by the lock statement",
3109 TypeManager.CSharpName (expr.Type));
3110 return false;
3113 FlowBranchingException branching = ec.StartFlowBranching (this);
3114 bool ok = Statement.Resolve (ec);
3115 if (!ok) {
3116 ec.KillFlowBranching ();
3117 return false;
3120 ResolveFinally (branching);
3122 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3123 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3124 // Unfortunately, System.Reflection.Emit automatically emits
3125 // a leave to the end of the finally block.
3126 // This is a problem if `returns' is true since we may jump
3127 // to a point after the end of the method.
3128 // As a workaround, emit an explicit ret here.
3129 ec.NeedReturnLabel ();
3132 temp = new TemporaryVariable (expr.Type, loc);
3133 temp.Resolve (ec);
3135 return true;
3138 protected override void DoEmit (EmitContext ec)
3140 ILGenerator ig = ec.ig;
3142 temp.Store (ec, expr);
3143 temp.Emit (ec);
3144 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3146 // try
3147 if (emit_finally)
3148 ig.BeginExceptionBlock ();
3149 Statement.Emit (ec);
3151 // finally
3152 DoEmitFinally (ec);
3153 if (emit_finally)
3154 ig.EndExceptionBlock ();
3157 public override void EmitFinally (EmitContext ec)
3159 temp.Emit (ec);
3160 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3164 public class Unchecked : Statement {
3165 public readonly Block Block;
3167 public Unchecked (Block b)
3169 Block = b;
3170 b.Unchecked = true;
3173 public override bool Resolve (EmitContext ec)
3175 bool previous_state = ec.CheckState;
3176 bool previous_state_const = ec.ConstantCheckState;
3178 ec.CheckState = false;
3179 ec.ConstantCheckState = false;
3180 bool ret = Block.Resolve (ec);
3181 ec.CheckState = previous_state;
3182 ec.ConstantCheckState = previous_state_const;
3184 return ret;
3187 protected override void DoEmit (EmitContext ec)
3189 bool previous_state = ec.CheckState;
3190 bool previous_state_const = ec.ConstantCheckState;
3192 ec.CheckState = false;
3193 ec.ConstantCheckState = false;
3194 Block.Emit (ec);
3195 ec.CheckState = previous_state;
3196 ec.ConstantCheckState = previous_state_const;
3200 public class Checked : Statement {
3201 public readonly Block Block;
3203 public Checked (Block b)
3205 Block = b;
3206 b.Unchecked = false;
3209 public override bool Resolve (EmitContext ec)
3211 bool previous_state = ec.CheckState;
3212 bool previous_state_const = ec.ConstantCheckState;
3214 ec.CheckState = true;
3215 ec.ConstantCheckState = true;
3216 bool ret = Block.Resolve (ec);
3217 ec.CheckState = previous_state;
3218 ec.ConstantCheckState = previous_state_const;
3220 return ret;
3223 protected override void DoEmit (EmitContext ec)
3225 bool previous_state = ec.CheckState;
3226 bool previous_state_const = ec.ConstantCheckState;
3228 ec.CheckState = true;
3229 ec.ConstantCheckState = true;
3230 Block.Emit (ec);
3231 ec.CheckState = previous_state;
3232 ec.ConstantCheckState = previous_state_const;
3236 public class Unsafe : Statement {
3237 public readonly Block Block;
3239 public Unsafe (Block b)
3241 Block = b;
3242 Block.Unsafe = true;
3245 public override bool Resolve (EmitContext ec)
3247 bool previous_state = ec.InUnsafe;
3248 bool val;
3250 ec.InUnsafe = true;
3251 val = Block.Resolve (ec);
3252 ec.InUnsafe = previous_state;
3254 return val;
3257 protected override void DoEmit (EmitContext ec)
3259 bool previous_state = ec.InUnsafe;
3261 ec.InUnsafe = true;
3262 Block.Emit (ec);
3263 ec.InUnsafe = previous_state;
3268 // Fixed statement
3270 public class Fixed : Statement {
3271 Expression type;
3272 ArrayList declarators;
3273 Statement statement;
3274 Type expr_type;
3275 Emitter[] data;
3276 bool has_ret;
3278 abstract class Emitter
3280 protected LocalInfo vi;
3281 protected Expression converted;
3283 protected Emitter (Expression expr, LocalInfo li)
3285 converted = expr;
3286 vi = li;
3289 public abstract void Emit (EmitContext ec);
3290 public abstract void EmitExit (ILGenerator ig);
3293 class ExpressionEmitter : Emitter {
3294 public ExpressionEmitter (Expression converted, LocalInfo li) :
3295 base (converted, li)
3299 public override void Emit (EmitContext ec) {
3301 // Store pointer in pinned location
3303 converted.Emit (ec);
3304 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3307 public override void EmitExit (ILGenerator ig)
3309 ig.Emit (OpCodes.Ldc_I4_0);
3310 ig.Emit (OpCodes.Conv_U);
3311 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3315 class StringEmitter : Emitter {
3316 LocalBuilder pinned_string;
3317 Location loc;
3319 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3320 base (expr, li)
3322 this.loc = loc;
3325 public override void Emit (EmitContext ec)
3327 ILGenerator ig = ec.ig;
3328 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3330 converted.Emit (ec);
3331 ig.Emit (OpCodes.Stloc, pinned_string);
3333 Expression sptr = new StringPtr (pinned_string, loc);
3334 converted = Convert.ImplicitConversionRequired (
3335 ec, sptr, vi.VariableType, loc);
3337 if (converted == null)
3338 return;
3340 converted.Emit (ec);
3341 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3344 public override void EmitExit(ILGenerator ig)
3346 ig.Emit (OpCodes.Ldnull);
3347 ig.Emit (OpCodes.Stloc, pinned_string);
3351 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3353 this.type = type;
3354 declarators = decls;
3355 statement = stmt;
3356 loc = l;
3359 public Statement Statement {
3360 get { return statement; }
3363 public override bool Resolve (EmitContext ec)
3365 if (!ec.InUnsafe){
3366 Expression.UnsafeError (loc);
3367 return false;
3370 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3371 if (texpr == null)
3372 return false;
3374 expr_type = texpr.Type;
3376 data = new Emitter [declarators.Count];
3378 if (!expr_type.IsPointer){
3379 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3380 return false;
3383 int i = 0;
3384 foreach (Pair p in declarators){
3385 LocalInfo vi = (LocalInfo) p.First;
3386 Expression e = (Expression) p.Second;
3388 vi.VariableInfo.SetAssigned (ec);
3389 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3392 // The rules for the possible declarators are pretty wise,
3393 // but the production on the grammar is more concise.
3395 // So we have to enforce these rules here.
3397 // We do not resolve before doing the case 1 test,
3398 // because the grammar is explicit in that the token &
3399 // is present, so we need to test for this particular case.
3402 if (e is Cast){
3403 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3404 return false;
3408 // Case 1: & object.
3410 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3411 Expression child = ((Unary) e).Expr;
3413 if (child is ParameterReference || child is LocalVariableReference){
3414 Report.Error (
3415 213, loc,
3416 "No need to use fixed statement for parameters or " +
3417 "local variable declarations (address is already " +
3418 "fixed)");
3419 return false;
3422 ec.InFixedInitializer = true;
3423 e = e.Resolve (ec);
3424 ec.InFixedInitializer = false;
3425 if (e == null)
3426 return false;
3428 child = ((Unary) e).Expr;
3430 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3431 return false;
3433 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
3434 e.Error_ValueCannotBeConverted (e.Location, expr_type, false);
3435 return false;
3438 data [i] = new ExpressionEmitter (e, vi);
3439 i++;
3441 continue;
3444 ec.InFixedInitializer = true;
3445 e = e.Resolve (ec);
3446 ec.InFixedInitializer = false;
3447 if (e == null)
3448 return false;
3451 // Case 2: Array
3453 if (e.Type.IsArray){
3454 Type array_type = TypeManager.GetElementType (e.Type);
3457 // Provided that array_type is unmanaged,
3459 if (!TypeManager.VerifyUnManaged (array_type, loc))
3460 return false;
3463 // and T* is implicitly convertible to the
3464 // pointer type given in the fixed statement.
3466 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3468 Expression converted = Convert.ImplicitConversionRequired (
3469 ec, array_ptr, vi.VariableType, loc);
3470 if (converted == null)
3471 return false;
3473 data [i] = new ExpressionEmitter (converted, vi);
3474 i++;
3476 continue;
3480 // Case 3: string
3482 if (e.Type == TypeManager.string_type){
3483 data [i] = new StringEmitter (e, vi, loc);
3484 i++;
3485 continue;
3488 // Case 4: fixed buffer
3489 FieldExpr fe = e as FieldExpr;
3490 if (fe != null) {
3491 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3492 if (ff != null) {
3493 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3495 Expression converted = Convert.ImplicitConversionRequired (
3496 ec, fixed_buffer_ptr, vi.VariableType, loc);
3497 if (converted == null)
3498 return false;
3500 data [i] = new ExpressionEmitter (converted, vi);
3501 i++;
3503 continue;
3508 // For other cases, flag a `this is already fixed expression'
3510 if (e is LocalVariableReference || e is ParameterReference ||
3511 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3513 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3514 return false;
3517 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3518 return false;
3521 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3523 if (!statement.Resolve (ec)) {
3524 ec.KillFlowBranching ();
3525 return false;
3528 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3529 has_ret = reachability.IsUnreachable;
3531 return true;
3534 protected override void DoEmit (EmitContext ec)
3536 for (int i = 0; i < data.Length; i++) {
3537 data [i].Emit (ec);
3540 statement.Emit (ec);
3542 if (has_ret)
3543 return;
3545 ILGenerator ig = ec.ig;
3548 // Clear the pinned variable
3550 for (int i = 0; i < data.Length; i++) {
3551 data [i].EmitExit (ig);
3556 public class Catch : Statement {
3557 public readonly string Name;
3558 public readonly Block Block;
3559 public readonly Block VarBlock;
3561 Expression type_expr;
3562 Type type;
3564 public Catch (Expression type, string name, Block block, Block var_block, Location l)
3566 type_expr = type;
3567 Name = name;
3568 Block = block;
3569 VarBlock = var_block;
3570 loc = l;
3573 public Type CatchType {
3574 get {
3575 return type;
3579 public bool IsGeneral {
3580 get {
3581 return type_expr == null;
3585 protected override void DoEmit(EmitContext ec)
3589 public override bool Resolve (EmitContext ec)
3591 bool was_catch = ec.InCatch;
3592 ec.InCatch = true;
3593 try {
3594 if (type_expr != null) {
3595 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3596 if (te == null)
3597 return false;
3599 type = te.Type;
3601 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3602 Error (155, "The type caught or thrown must be derived from System.Exception");
3603 return false;
3605 } else
3606 type = null;
3608 if (!Block.Resolve (ec))
3609 return false;
3611 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
3612 // emit the "unused variable" warnings.
3613 if (VarBlock != null)
3614 return VarBlock.Resolve (ec);
3616 return true;
3618 finally {
3619 ec.InCatch = was_catch;
3624 public class Try : ExceptionStatement {
3625 public readonly Block Fini, Block;
3626 public readonly ArrayList Specific;
3627 public readonly Catch General;
3629 bool need_exc_block;
3632 // specific, general and fini might all be null.
3634 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3636 if (specific == null && general == null){
3637 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3640 this.Block = block;
3641 this.Specific = specific;
3642 this.General = general;
3643 this.Fini = fini;
3644 loc = l;
3647 public override bool Resolve (EmitContext ec)
3649 bool ok = true;
3651 FlowBranchingException branching = ec.StartFlowBranching (this);
3653 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3655 if (!Block.Resolve (ec))
3656 ok = false;
3658 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3660 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3662 Type[] prevCatches = new Type [Specific.Count];
3663 int last_index = 0;
3664 foreach (Catch c in Specific){
3665 ec.CurrentBranching.CreateSibling (
3666 c.Block, FlowBranching.SiblingType.Catch);
3668 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3670 if (c.Name != null) {
3671 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3672 if (vi == null)
3673 throw new Exception ();
3675 vi.VariableInfo = null;
3678 if (!c.Resolve (ec))
3679 return false;
3681 Type resolvedType = c.CatchType;
3682 for (int ii = 0; ii < last_index; ++ii) {
3683 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3684 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3685 return false;
3689 prevCatches [last_index++] = resolvedType;
3690 need_exc_block = true;
3693 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3695 if (General != null){
3696 if (CodeGen.Assembly.WrapNonExceptionThrows) {
3697 foreach (Catch c in Specific){
3698 if (c.CatchType == TypeManager.exception_type) {
3699 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'");
3704 ec.CurrentBranching.CreateSibling (
3705 General.Block, FlowBranching.SiblingType.Catch);
3707 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3709 if (!General.Resolve (ec))
3710 ok = false;
3712 need_exc_block = true;
3715 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3717 if (Fini != null) {
3718 if (ok)
3719 ec.CurrentBranching.CreateSibling (
3720 Fini, FlowBranching.SiblingType.Finally);
3722 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3723 bool was_finally = ec.InFinally;
3724 ec.InFinally = true;
3725 if (!Fini.Resolve (ec))
3726 ok = false;
3727 ec.InFinally = was_finally;
3729 if (!ec.InIterator)
3730 need_exc_block = true;
3733 if (ec.InIterator) {
3734 ResolveFinally (branching);
3735 need_exc_block |= emit_finally;
3736 } else
3737 emit_finally = Fini != null;
3739 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3741 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3743 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3745 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3746 // Unfortunately, System.Reflection.Emit automatically emits
3747 // a leave to the end of the finally block. This is a problem
3748 // if `returns' is true since we may jump to a point after the
3749 // end of the method.
3750 // As a workaround, emit an explicit ret here.
3751 ec.NeedReturnLabel ();
3754 return ok;
3757 protected override void DoEmit (EmitContext ec)
3759 ILGenerator ig = ec.ig;
3761 if (need_exc_block)
3762 ig.BeginExceptionBlock ();
3763 Block.Emit (ec);
3765 foreach (Catch c in Specific){
3766 LocalInfo vi;
3768 ig.BeginCatchBlock (c.CatchType);
3770 if (c.VarBlock != null)
3771 ec.EmitScopeInitFromBlock (c.VarBlock);
3772 if (c.Name != null){
3773 vi = c.Block.GetLocalInfo (c.Name);
3774 if (vi == null)
3775 throw new Exception ("Variable does not exist in this block");
3777 if (vi.IsCaptured){
3778 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
3779 ig.Emit (OpCodes.Stloc, e);
3781 ec.EmitCapturedVariableInstance (vi);
3782 ig.Emit (OpCodes.Ldloc, e);
3783 ig.Emit (OpCodes.Stfld, vi.FieldBuilder);
3784 } else
3785 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3786 } else
3787 ig.Emit (OpCodes.Pop);
3789 c.Block.Emit (ec);
3792 if (General != null){
3793 ig.BeginCatchBlock (TypeManager.object_type);
3794 ig.Emit (OpCodes.Pop);
3795 General.Block.Emit (ec);
3798 DoEmitFinally (ec);
3799 if (need_exc_block)
3800 ig.EndExceptionBlock ();
3803 public override void EmitFinally (EmitContext ec)
3805 if (Fini != null)
3806 Fini.Emit (ec);
3809 public bool HasCatch
3811 get {
3812 return General != null || Specific.Count > 0;
3817 public class Using : ExceptionStatement {
3818 object expression_or_block;
3819 public Statement Statement;
3820 ArrayList var_list;
3821 Expression expr;
3822 Type expr_type;
3823 Expression [] resolved_vars;
3824 Expression [] converted_vars;
3825 ExpressionStatement [] assign;
3826 LocalBuilder local_copy;
3828 public Using (object expression_or_block, Statement stmt, Location l)
3830 this.expression_or_block = expression_or_block;
3831 Statement = stmt;
3832 loc = l;
3836 // Resolves for the case of using using a local variable declaration.
3838 bool ResolveLocalVariableDecls (EmitContext ec)
3840 int i = 0;
3842 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3843 if (texpr == null)
3844 return false;
3846 expr_type = texpr.Type;
3849 // The type must be an IDisposable or an implicit conversion
3850 // must exist.
3852 converted_vars = new Expression [var_list.Count];
3853 resolved_vars = new Expression [var_list.Count];
3854 assign = new ExpressionStatement [var_list.Count];
3856 bool need_conv = !TypeManager.ImplementsInterface (
3857 expr_type, TypeManager.idisposable_type);
3859 foreach (DictionaryEntry e in var_list){
3860 Expression var = (Expression) e.Key;
3862 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3863 if (var == null)
3864 return false;
3866 resolved_vars [i] = var;
3868 if (!need_conv) {
3869 i++;
3870 continue;
3873 converted_vars [i] = Convert.ImplicitConversion (
3874 ec, var, TypeManager.idisposable_type, loc);
3876 if (converted_vars [i] == null) {
3877 Error_IsNotConvertibleToIDisposable ();
3878 return false;
3881 i++;
3884 i = 0;
3885 foreach (DictionaryEntry e in var_list){
3886 Expression var = resolved_vars [i];
3887 Expression new_expr = (Expression) e.Value;
3888 Expression a;
3890 a = new Assign (var, new_expr, loc);
3891 a = a.Resolve (ec);
3892 if (a == null)
3893 return false;
3895 if (!need_conv)
3896 converted_vars [i] = var;
3897 assign [i] = (ExpressionStatement) a;
3898 i++;
3901 return true;
3904 void Error_IsNotConvertibleToIDisposable ()
3906 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
3907 TypeManager.CSharpName (expr_type));
3910 bool ResolveExpression (EmitContext ec)
3912 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3913 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3914 Error_IsNotConvertibleToIDisposable ();
3915 return false;
3919 return true;
3923 // Emits the code for the case of using using a local variable declaration.
3925 void EmitLocalVariableDecls (EmitContext ec)
3927 ILGenerator ig = ec.ig;
3928 int i = 0;
3930 for (i = 0; i < assign.Length; i++) {
3931 assign [i].EmitStatement (ec);
3933 if (emit_finally)
3934 ig.BeginExceptionBlock ();
3936 Statement.Emit (ec);
3937 var_list.Reverse ();
3939 DoEmitFinally (ec);
3942 void EmitLocalVariableDeclFinally (EmitContext ec)
3944 ILGenerator ig = ec.ig;
3946 int i = assign.Length;
3947 for (int ii = 0; ii < var_list.Count; ++ii){
3948 Expression var = resolved_vars [--i];
3949 Label skip = ig.DefineLabel ();
3951 if (!var.Type.IsValueType) {
3952 var.Emit (ec);
3953 ig.Emit (OpCodes.Brfalse, skip);
3954 converted_vars [i].Emit (ec);
3955 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3956 } else {
3957 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3959 if (!(ml is MethodGroupExpr)) {
3960 var.Emit (ec);
3961 ig.Emit (OpCodes.Box, var.Type);
3962 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3963 } else {
3964 MethodInfo mi = null;
3966 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3967 if (TypeManager.GetParameterData (mk).Count == 0) {
3968 mi = mk;
3969 break;
3973 if (mi == null) {
3974 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3975 return;
3978 IMemoryLocation mloc = (IMemoryLocation) var;
3980 mloc.AddressOf (ec, AddressOp.Load);
3981 ig.Emit (OpCodes.Call, mi);
3985 ig.MarkLabel (skip);
3987 if (emit_finally) {
3988 ig.EndExceptionBlock ();
3989 if (i > 0)
3990 ig.BeginFinallyBlock ();
3995 void EmitExpression (EmitContext ec)
3998 // Make a copy of the expression and operate on that.
4000 ILGenerator ig = ec.ig;
4001 local_copy = ig.DeclareLocal (expr_type);
4003 expr.Emit (ec);
4004 ig.Emit (OpCodes.Stloc, local_copy);
4006 if (emit_finally)
4007 ig.BeginExceptionBlock ();
4009 Statement.Emit (ec);
4011 DoEmitFinally (ec);
4012 if (emit_finally)
4013 ig.EndExceptionBlock ();
4016 void EmitExpressionFinally (EmitContext ec)
4018 ILGenerator ig = ec.ig;
4019 if (!local_copy.LocalType.IsValueType) {
4020 Label skip = ig.DefineLabel ();
4021 ig.Emit (OpCodes.Ldloc, local_copy);
4022 ig.Emit (OpCodes.Brfalse, skip);
4023 ig.Emit (OpCodes.Ldloc, local_copy);
4024 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4025 ig.MarkLabel (skip);
4026 } else {
4027 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4029 if (!(ml is MethodGroupExpr)) {
4030 ig.Emit (OpCodes.Ldloc, local_copy);
4031 ig.Emit (OpCodes.Box, local_copy.LocalType);
4032 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4033 } else {
4034 MethodInfo mi = null;
4036 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4037 if (TypeManager.GetParameterData (mk).Count == 0) {
4038 mi = mk;
4039 break;
4043 if (mi == null) {
4044 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4045 return;
4048 ig.Emit (OpCodes.Ldloca, local_copy);
4049 ig.Emit (OpCodes.Call, mi);
4054 public override bool Resolve (EmitContext ec)
4056 if (expression_or_block is DictionaryEntry){
4057 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4058 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4060 if (!ResolveLocalVariableDecls (ec))
4061 return false;
4063 } else if (expression_or_block is Expression){
4064 expr = (Expression) expression_or_block;
4066 expr = expr.Resolve (ec);
4067 if (expr == null)
4068 return false;
4070 expr_type = expr.Type;
4072 if (!ResolveExpression (ec))
4073 return false;
4076 FlowBranchingException branching = ec.StartFlowBranching (this);
4078 bool ok = Statement.Resolve (ec);
4080 if (!ok) {
4081 ec.KillFlowBranching ();
4082 return false;
4085 ResolveFinally (branching);
4086 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4088 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4089 // Unfortunately, System.Reflection.Emit automatically emits a leave
4090 // to the end of the finally block. This is a problem if `returns'
4091 // is true since we may jump to a point after the end of the method.
4092 // As a workaround, emit an explicit ret here.
4093 ec.NeedReturnLabel ();
4096 return true;
4099 protected override void DoEmit (EmitContext ec)
4101 if (expression_or_block is DictionaryEntry)
4102 EmitLocalVariableDecls (ec);
4103 else if (expression_or_block is Expression)
4104 EmitExpression (ec);
4107 public override void EmitFinally (EmitContext ec)
4109 if (expression_or_block is DictionaryEntry)
4110 EmitLocalVariableDeclFinally (ec);
4111 else if (expression_or_block is Expression)
4112 EmitExpressionFinally (ec);
4116 /// <summary>
4117 /// Implementation of the foreach C# statement
4118 /// </summary>
4119 public class Foreach : Statement {
4120 Expression type;
4121 Expression variable;
4122 Expression expr;
4123 Statement statement;
4124 ArrayForeach array;
4125 CollectionForeach collection;
4127 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4128 Statement stmt, Location l)
4130 this.type = type;
4131 this.variable = var;
4132 this.expr = expr;
4133 statement = stmt;
4134 loc = l;
4137 public Statement Statement {
4138 get { return statement; }
4141 public override bool Resolve (EmitContext ec)
4143 expr = expr.Resolve (ec);
4144 if (expr == null)
4145 return false;
4147 Constant c = expr as Constant;
4148 if (c != null && c.GetValue () == null) {
4149 Report.Error (186, loc, "Use of null is not valid in this context");
4150 return false;
4153 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4154 if (texpr == null)
4155 return false;
4157 Type var_type = texpr.Type;
4159 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethod) {
4160 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4161 expr.ExprClassName);
4162 return false;
4166 // We need an instance variable. Not sure this is the best
4167 // way of doing this.
4169 // FIXME: When we implement propertyaccess, will those turn
4170 // out to return values in ExprClass? I think they should.
4172 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4173 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4174 collection.Error_Enumerator ();
4175 return false;
4178 if (expr.Type.IsArray) {
4179 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4180 return array.Resolve (ec);
4181 } else {
4182 collection = new CollectionForeach (
4183 var_type, variable, expr, statement, loc);
4184 return collection.Resolve (ec);
4188 protected override void DoEmit (EmitContext ec)
4190 ILGenerator ig = ec.ig;
4192 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4193 ec.LoopBegin = ig.DefineLabel ();
4194 ec.LoopEnd = ig.DefineLabel ();
4196 if (collection != null)
4197 collection.Emit (ec);
4198 else
4199 array.Emit (ec);
4201 ec.LoopBegin = old_begin;
4202 ec.LoopEnd = old_end;
4205 protected class ArrayCounter : TemporaryVariable
4207 public ArrayCounter (Location loc)
4208 : base (TypeManager.int32_type, loc)
4211 public void Initialize (EmitContext ec)
4213 EmitThis (ec);
4214 ec.ig.Emit (OpCodes.Ldc_I4_0);
4215 EmitStore (ec.ig);
4218 public void Increment (EmitContext ec)
4220 EmitThis (ec);
4221 Emit (ec);
4222 ec.ig.Emit (OpCodes.Ldc_I4_1);
4223 ec.ig.Emit (OpCodes.Add);
4224 EmitStore (ec.ig);
4228 protected class ArrayForeach : Statement
4230 Expression variable, expr, conv;
4231 Statement statement;
4232 Type array_type;
4233 Type var_type;
4234 TemporaryVariable[] lengths;
4235 ArrayCounter[] counter;
4236 int rank;
4238 TemporaryVariable copy;
4239 Expression access;
4241 public ArrayForeach (Type var_type, Expression var,
4242 Expression expr, Statement stmt, Location l)
4244 this.var_type = var_type;
4245 this.variable = var;
4246 this.expr = expr;
4247 statement = stmt;
4248 loc = l;
4251 public override bool Resolve (EmitContext ec)
4253 array_type = expr.Type;
4254 rank = array_type.GetArrayRank ();
4256 copy = new TemporaryVariable (array_type, loc);
4257 copy.Resolve (ec);
4259 counter = new ArrayCounter [rank];
4260 lengths = new TemporaryVariable [rank];
4262 ArrayList list = new ArrayList ();
4263 for (int i = 0; i < rank; i++) {
4264 counter [i] = new ArrayCounter (loc);
4265 counter [i].Resolve (ec);
4267 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4268 lengths [i].Resolve (ec);
4270 list.Add (counter [i]);
4273 access = new ElementAccess (copy, list).Resolve (ec);
4274 if (access == null)
4275 return false;
4277 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4278 if (conv == null)
4279 return false;
4281 bool ok = true;
4283 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4284 ec.CurrentBranching.CreateSibling ();
4286 variable = variable.ResolveLValue (ec, conv, loc);
4287 if (variable == null)
4288 ok = false;
4290 if (!statement.Resolve (ec))
4291 ok = false;
4293 ec.EndFlowBranching ();
4295 return ok;
4298 protected override void DoEmit (EmitContext ec)
4300 ILGenerator ig = ec.ig;
4302 copy.Store (ec, expr);
4304 Label[] test = new Label [rank];
4305 Label[] loop = new Label [rank];
4307 for (int i = 0; i < rank; i++) {
4308 test [i] = ig.DefineLabel ();
4309 loop [i] = ig.DefineLabel ();
4311 lengths [i].EmitThis (ec);
4312 ((ArrayAccess) access).EmitGetLength (ec, i);
4313 lengths [i].EmitStore (ig);
4316 for (int i = 0; i < rank; i++) {
4317 counter [i].Initialize (ec);
4319 ig.Emit (OpCodes.Br, test [i]);
4320 ig.MarkLabel (loop [i]);
4323 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4325 statement.Emit (ec);
4327 ig.MarkLabel (ec.LoopBegin);
4329 for (int i = rank - 1; i >= 0; i--){
4330 counter [i].Increment (ec);
4332 ig.MarkLabel (test [i]);
4333 counter [i].Emit (ec);
4334 lengths [i].Emit (ec);
4335 ig.Emit (OpCodes.Blt, loop [i]);
4338 ig.MarkLabel (ec.LoopEnd);
4342 protected class CollectionForeach : ExceptionStatement
4344 Expression variable, expr;
4345 Statement statement;
4347 TemporaryVariable enumerator;
4348 Expression init;
4349 Statement loop;
4351 MethodGroupExpr get_enumerator;
4352 PropertyExpr get_current;
4353 MethodInfo move_next;
4354 Type var_type, enumerator_type;
4355 bool is_disposable;
4356 bool enumerator_found;
4358 public CollectionForeach (Type var_type, Expression var,
4359 Expression expr, Statement stmt, Location l)
4361 this.var_type = var_type;
4362 this.variable = var;
4363 this.expr = expr;
4364 statement = stmt;
4365 loc = l;
4368 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4370 Type return_type = mi.ReturnType;
4372 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4374 // Apply the same optimization as MS: skip the GetEnumerator
4375 // returning an IEnumerator, and use the one returning a
4376 // CharEnumerator instead. This allows us to avoid the
4377 // try-finally block and the boxing.
4379 return false;
4382 // Ok, we can access it, now make sure that we can do something
4383 // with this `GetEnumerator'
4386 if (return_type == TypeManager.ienumerator_type ||
4387 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4388 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4390 // If it is not an interface, lets try to find the methods ourselves.
4391 // For example, if we have:
4392 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4393 // We can avoid the iface call. This is a runtime perf boost.
4394 // even bigger if we have a ValueType, because we avoid the cost
4395 // of boxing.
4397 // We have to make sure that both methods exist for us to take
4398 // this path. If one of the methods does not exist, we will just
4399 // use the interface. Sadly, this complex if statement is the only
4400 // way I could do this without a goto
4403 if (return_type.IsInterface ||
4404 !FetchMoveNext (return_type) ||
4405 !FetchGetCurrent (ec, return_type)) {
4406 move_next = TypeManager.bool_movenext_void;
4407 get_current = new PropertyExpr (
4408 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4409 return true;
4411 } else {
4413 // Ok, so they dont return an IEnumerable, we will have to
4414 // find if they support the GetEnumerator pattern.
4417 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
4418 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",
4419 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
4420 return false;
4424 enumerator_type = return_type;
4425 is_disposable = !enumerator_type.IsSealed ||
4426 TypeManager.ImplementsInterface (
4427 enumerator_type, TypeManager.idisposable_type);
4429 return true;
4433 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4435 bool FetchMoveNext (Type t)
4437 MemberList move_next_list;
4439 move_next_list = TypeContainer.FindMembers (
4440 t, MemberTypes.Method,
4441 BindingFlags.Public | BindingFlags.Instance,
4442 Type.FilterName, "MoveNext");
4443 if (move_next_list.Count == 0)
4444 return false;
4446 foreach (MemberInfo m in move_next_list){
4447 MethodInfo mi = (MethodInfo) m;
4449 if ((TypeManager.GetParameterData (mi).Count == 0) &&
4450 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4451 move_next = mi;
4452 return true;
4456 return false;
4460 // Retrieves a `public T get_Current ()' method from the Type `t'
4462 bool FetchGetCurrent (EmitContext ec, Type t)
4464 PropertyExpr pe = Expression.MemberLookup (
4465 ec.ContainerType, t, "Current", MemberTypes.Property,
4466 Expression.AllBindingFlags, loc) as PropertyExpr;
4467 if (pe == null)
4468 return false;
4470 get_current = pe;
4471 return true;
4475 // Retrieves a `public void Dispose ()' method from the Type `t'
4477 static MethodInfo FetchMethodDispose (Type t)
4479 MemberList dispose_list;
4481 dispose_list = TypeContainer.FindMembers (
4482 t, MemberTypes.Method,
4483 BindingFlags.Public | BindingFlags.Instance,
4484 Type.FilterName, "Dispose");
4485 if (dispose_list.Count == 0)
4486 return null;
4488 foreach (MemberInfo m in dispose_list){
4489 MethodInfo mi = (MethodInfo) m;
4491 if (TypeManager.GetParameterData (mi).Count == 0){
4492 if (mi.ReturnType == TypeManager.void_type)
4493 return mi;
4496 return null;
4499 public void Error_Enumerator ()
4501 if (enumerator_found) {
4502 return;
4505 Report.Error (1579, loc,
4506 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4507 TypeManager.CSharpName (expr.Type));
4510 bool TryType (EmitContext ec, Type t)
4512 MethodGroupExpr mg = Expression.MemberLookup (
4513 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
4514 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4515 if (mg == null)
4516 return false;
4518 foreach (MethodBase mb in mg.Methods) {
4519 if (TypeManager.GetParameterData (mb).Count != 0)
4520 continue;
4522 // Check whether GetEnumerator is public
4523 if ((mb.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4524 continue;
4526 if (TypeManager.IsOverride (mb))
4527 continue;
4529 enumerator_found = true;
4531 if (!GetEnumeratorFilter (ec, (MethodInfo) mb))
4532 continue;
4534 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) mb };
4535 get_enumerator = new MethodGroupExpr (mi, loc);
4537 if (t != expr.Type) {
4538 expr = Convert.ExplicitConversion (
4539 ec, expr, t, loc);
4540 if (expr == null)
4541 throw new InternalErrorException ();
4544 get_enumerator.InstanceExpression = expr;
4545 get_enumerator.IsBase = t != expr.Type;
4547 return true;
4550 return false;
4553 bool ProbeCollectionType (EmitContext ec, Type t)
4555 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4556 if (TryType (ec, tt))
4557 return true;
4558 tt = tt.BaseType;
4562 // Now try to find the method in the interfaces
4564 while (t != null){
4565 Type [] ifaces = t.GetInterfaces ();
4567 foreach (Type i in ifaces){
4568 if (TryType (ec, i))
4569 return true;
4573 // Since TypeBuilder.GetInterfaces only returns the interface
4574 // types for this type, we have to keep looping, but once
4575 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4576 // done, because it returns all the types
4578 if ((t is TypeBuilder))
4579 t = t.BaseType;
4580 else
4581 break;
4584 return false;
4587 public override bool Resolve (EmitContext ec)
4589 enumerator_type = TypeManager.ienumerator_type;
4590 is_disposable = true;
4592 if (!ProbeCollectionType (ec, expr.Type)) {
4593 Error_Enumerator ();
4594 return false;
4597 enumerator = new TemporaryVariable (enumerator_type, loc);
4598 enumerator.Resolve (ec);
4600 init = new Invocation (get_enumerator, new ArrayList ());
4601 init = init.Resolve (ec);
4602 if (init == null)
4603 return false;
4605 Expression move_next_expr;
4607 MemberInfo[] mi = new MemberInfo[] { move_next };
4608 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4609 mg.InstanceExpression = enumerator;
4611 move_next_expr = new Invocation (mg, new ArrayList ());
4614 get_current.InstanceExpression = enumerator;
4616 Statement block = new CollectionForeachStatement (
4617 var_type, variable, get_current, statement, loc);
4619 loop = new While (move_next_expr, block, loc);
4621 bool ok = true;
4623 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4624 ec.CurrentBranching.CreateSibling ();
4626 FlowBranchingException branching = null;
4627 if (is_disposable)
4628 branching = ec.StartFlowBranching (this);
4630 if (!loop.Resolve (ec))
4631 ok = false;
4633 if (is_disposable) {
4634 ResolveFinally (branching);
4635 ec.EndFlowBranching ();
4636 } else
4637 emit_finally = true;
4639 ec.EndFlowBranching ();
4641 return ok;
4644 protected override void DoEmit (EmitContext ec)
4646 ILGenerator ig = ec.ig;
4648 enumerator.Store (ec, init);
4651 // Protect the code in a try/finalize block, so that
4652 // if the beast implement IDisposable, we get rid of it
4654 if (is_disposable && emit_finally)
4655 ig.BeginExceptionBlock ();
4657 loop.Emit (ec);
4660 // Now the finally block
4662 if (is_disposable) {
4663 DoEmitFinally (ec);
4664 if (emit_finally)
4665 ig.EndExceptionBlock ();
4670 public override void EmitFinally (EmitContext ec)
4672 ILGenerator ig = ec.ig;
4674 if (enumerator_type.IsValueType) {
4675 MethodInfo mi = FetchMethodDispose (enumerator_type);
4676 if (mi != null) {
4677 enumerator.EmitLoadAddress (ec);
4678 ig.Emit (OpCodes.Call, mi);
4679 } else {
4680 enumerator.Emit (ec);
4681 ig.Emit (OpCodes.Box, enumerator_type);
4682 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4684 } else {
4685 Label call_dispose = ig.DefineLabel ();
4687 enumerator.Emit (ec);
4688 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4689 ig.Emit (OpCodes.Dup);
4690 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4691 ig.Emit (OpCodes.Pop);
4693 Label end_finally = ig.DefineLabel ();
4694 ig.Emit (OpCodes.Br, end_finally);
4696 ig.MarkLabel (call_dispose);
4697 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4698 ig.MarkLabel (end_finally);
4703 protected class CollectionForeachStatement : Statement
4705 Type type;
4706 Expression variable, current, conv;
4707 Statement statement;
4708 Assign assign;
4710 public CollectionForeachStatement (Type type, Expression variable,
4711 Expression current, Statement statement,
4712 Location loc)
4714 this.type = type;
4715 this.variable = variable;
4716 this.current = current;
4717 this.statement = statement;
4718 this.loc = loc;
4721 public override bool Resolve (EmitContext ec)
4723 current = current.Resolve (ec);
4724 if (current == null)
4725 return false;
4727 conv = Convert.ExplicitConversion (ec, current, type, loc);
4728 if (conv == null)
4729 return false;
4731 assign = new Assign (variable, conv, loc);
4732 if (assign.Resolve (ec) == null)
4733 return false;
4735 if (!statement.Resolve (ec))
4736 return false;
4738 return true;
4741 protected override void DoEmit (EmitContext ec)
4743 assign.EmitStatement (ec);
4744 statement.Emit (ec);