2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@ximian.com)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 // (C) 2003, 2004 Novell, Inc.
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 {
26 /// Resolves the statement, true means that all sub-statements
29 public virtual bool Resolve (EmitContext ec)
35 /// We already know that the statement is unreachable, but we still
36 /// need to resolve it to catch errors.
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 && (RootContext.WarningLevel >= 2))
50 Report.Warning (162, loc, "Unreachable code detected");
52 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
53 bool ok = Resolve (ec);
54 ec.KillFlowBranching ();
60 /// Return value indicates whether all code paths emitted return.
62 protected abstract void DoEmit (EmitContext ec);
65 /// Utility wrapper routine for Error, just to beautify the code
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)
75 Report.Error (error, loc, s);
77 Report.Error (error, s);
81 /// Return value indicates whether all code paths emitted return.
83 public virtual void Emit (EmitContext 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)
101 protected override void DoEmit (EmitContext ec)
106 public class If : Statement {
108 public Statement TrueStatement;
109 public Statement FalseStatement;
113 public If (Expression expr, Statement trueStatement, Location l)
116 TrueStatement = trueStatement;
120 public If (Expression expr,
121 Statement trueStatement,
122 Statement falseStatement,
126 TrueStatement = trueStatement;
127 FalseStatement = falseStatement;
131 public override bool Resolve (EmitContext ec)
135 Report.Debug (1, "START IF BLOCK", loc);
137 expr = Expression.ResolveBoolean (ec, expr, loc);
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;
155 if (!TrueStatement.Resolve (ec))
158 if ((FalseStatement != null) &&
159 !FalseStatement.ResolveUnreachable (ec, true))
161 FalseStatement = null;
163 if (!TrueStatement.ResolveUnreachable (ec, true))
165 TrueStatement = null;
167 if ((FalseStatement != null) &&
168 !FalseStatement.Resolve (ec))
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);
193 protected override void DoEmit (EmitContext ec)
195 ILGenerator ig = ec.ig;
196 Label false_target = ig.DefineLabel ();
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;
207 TrueStatement.Emit (ec);
208 else if (FalseStatement != null)
209 FalseStatement.Emit (ec);
214 expr.EmitBranchable (ec, false_target, false);
216 TrueStatement.Emit (ec);
218 if (FalseStatement != null){
219 bool branch_emitted = false;
221 end = ig.DefineLabel ();
223 ig.Emit (OpCodes.Br, end);
224 branch_emitted = true;
227 ig.MarkLabel (false_target);
228 FalseStatement.Emit (ec);
233 ig.MarkLabel (false_target);
238 public class Do : Statement {
239 public Expression expr;
240 public readonly Statement EmbeddedStatement;
243 public Do (Statement statement, Expression boolExpr, Location l)
246 EmbeddedStatement = statement;
250 public override bool Resolve (EmitContext ec)
254 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
256 if (!EmbeddedStatement.Resolve (ec))
259 expr = Expression.ResolveBoolean (ec, expr, loc);
262 else if (expr is BoolConstant){
263 bool res = ((BoolConstant) expr).Value;
269 ec.CurrentBranching.Infinite = infinite;
270 ec.EndFlowBranching ();
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 ();
286 EmbeddedStatement.Emit (ec);
287 ig.MarkLabel (ec.LoopBegin);
290 // Dead code elimination
292 if (expr is BoolConstant){
293 bool res = ((BoolConstant) expr).Value;
296 ec.ig.Emit (OpCodes.Br, loop);
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;
319 public override bool Resolve (EmitContext ec)
323 expr = Expression.ResolveBoolean (ec, expr, loc);
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))
342 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
344 ec.CurrentBranching.CreateSibling ();
346 if (!Statement.Resolve (ec))
349 ec.CurrentBranching.Infinite = infinite;
350 ec.EndFlowBranching ();
355 protected override void DoEmit (EmitContext ec)
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);
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);
381 Label while_loop = ig.DefineLabel ();
383 ig.Emit (OpCodes.Br, ec.LoopBegin);
384 ig.MarkLabel (while_loop);
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 {
402 readonly Statement InitStatement;
403 readonly Statement Increment;
404 public readonly Statement Statement;
405 bool infinite, empty;
407 public For (Statement initStatement,
413 InitStatement = initStatement;
415 Increment = increment;
416 Statement = statement;
420 public override bool Resolve (EmitContext ec)
424 if (InitStatement != null){
425 if (!InitStatement.Resolve (ec))
430 Test = Expression.ResolveBoolean (ec, Test, loc);
433 else if (Test is BoolConstant){
434 BoolConstant bc = (BoolConstant) Test;
436 if (bc.Value == false){
437 if (!Statement.ResolveUnreachable (ec, true))
439 if ((Increment != null) &&
440 !Increment.ResolveUnreachable (ec, false))
450 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
452 ec.CurrentBranching.CreateSibling ();
454 if (!Statement.Resolve (ec))
457 if (Increment != null){
458 if (!Increment.Resolve (ec))
462 ec.CurrentBranching.Infinite = infinite;
463 ec.EndFlowBranching ();
468 protected override void DoEmit (EmitContext ec)
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);
489 ig.MarkLabel (ec.LoopBegin);
490 if (Increment != EmptyStatement.Value)
495 // If test is null, there is no test, and we are just
500 // The Resolve code already catches the case for
501 // Test == BoolConstant (false) so we know that
504 if (Test is BoolConstant)
505 ig.Emit (OpCodes.Br, loop);
507 Test.EmitBranchable (ec, loop, true);
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)
527 public override bool Resolve (EmitContext ec)
530 expr = expr.ResolveStatement (ec);
534 protected override void DoEmit (EmitContext ec)
536 expr.EmitStatement (ec);
539 public override string ToString ()
541 return "StatementExpression (" + expr + ")";
546 /// Implements the return statement
548 public class Return : Statement {
549 public Expression Expr;
551 public Return (Expression expr, Location l)
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");
568 if (ec.ReturnType == 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");
580 Error (126, "An object of a type convertible to `{0}' is required " +
581 "for the return statement",
582 TypeManager.CSharpName (ec.ReturnType));
586 Expr = Expr.Resolve (ec);
590 if (Expr.Type != ec.ReturnType) {
591 Expr = Convert.ImplicitConversionRequired (
592 ec, Expr, ec.ReturnType, loc);
598 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
600 if (ec.CurrentBranching.InTryOrCatch (true)) {
601 ec.CurrentBranching.AddFinallyVector (vector);
603 } else if (ec.InFinally) {
604 Error (157, "Control cannot leave the body of a finally clause");
607 vector.CheckOutParameters (ec.CurrentBranching);
610 ec.NeedReturnLabel ();
612 ec.CurrentBranching.CurrentUsageVector.Return ();
616 protected override void DoEmit (EmitContext ec)
622 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
626 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
628 ec.ig.Emit (OpCodes.Ret);
632 public class Goto : Statement {
634 LabeledStatement label;
636 public override bool Resolve (EmitContext ec)
638 label = ec.CurrentBranching.LookupLabel (target, loc);
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 ();
652 public Goto (string label, Location l)
658 public string 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 {
677 FlowBranching.UsageVector vectors;
679 public LabeledStatement (string label_name, Location l)
684 public Label LabelTarget (EmitContext ec)
689 label = ec.ig.DefineLabel ();
695 public bool IsDefined {
701 public bool HasBeenReferenced {
707 public void AddUsageVector (FlowBranching.UsageVector vector)
709 vector = vector.Clone ();
710 vector.Next = vectors;
714 public override bool Resolve (EmitContext ec)
716 ec.CurrentBranching.Label (vectors);
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");
729 ec.ig.MarkLabel (label);
732 public void AddReference ()
740 /// `goto default' statement
742 public class GotoDefault : Statement {
744 public GotoDefault (Location l)
749 public override bool Resolve (EmitContext ec)
751 ec.CurrentBranching.CurrentUsageVector.Goto ();
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");
762 if (!ec.Switch.GotDefault){
763 Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
766 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
771 /// `goto case' statement
773 public class GotoCase : Statement {
777 public GotoCase (Expression e, Location 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");
790 expr = expr.Resolve (ec);
794 Constant c = expr as Constant;
796 Error (150, "A constant value is expected");
800 c = c.ToType (ec.Switch.SwitchType, loc);
804 object val = c.GetValue ();
806 val = SwitchLabel.NullStringCase;
808 sl = (SwitchLabel) ec.Switch.Elements [val];
811 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", c.GetValue () == null ? "null" : val);
815 ec.CurrentBranching.CurrentUsageVector.Goto ();
819 protected override void DoEmit (EmitContext ec)
821 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
825 public class Throw : Statement {
828 public Throw (Expression expr, Location l)
834 public override bool Resolve (EmitContext ec)
836 ec.CurrentBranching.CurrentUsageVector.Throw ();
839 expr = expr.Resolve (ec);
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, "value, variable, property or indexer access ", loc);
853 if ((t != TypeManager.exception_type) &&
854 !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
855 !(expr is NullLiteral)) {
857 "The type caught or thrown must be derived " +
858 "from System.Exception");
865 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
870 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
876 protected override void DoEmit (EmitContext ec)
879 ec.ig.Emit (OpCodes.Rethrow);
883 ec.ig.Emit (OpCodes.Throw);
888 public class Break : Statement {
890 public Break (Location l)
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");
902 } else if (ec.InFinally && ec.CurrentBranching.BreakCrossesTryCatchBoundary()) {
903 Error (157, "Control cannot leave the body of a finally clause");
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 ();
915 ec.NeedReturnLabel ();
917 ec.CurrentBranching.CurrentUsageVector.Break ();
921 protected override void DoEmit (EmitContext ec)
923 ILGenerator ig = ec.ig;
926 ig.Emit (OpCodes.Leave, ec.LoopEnd);
928 ig.Emit (OpCodes.Br, ec.LoopEnd);
933 public class Continue : Statement {
935 public Continue (Location l)
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");
947 } else if (ec.InFinally) {
948 Error (157, "Control cannot leave the body of a finally clause");
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 ();
959 protected override void DoEmit (EmitContext ec)
961 Label begin = ec.LoopBegin;
964 ec.ig.Emit (OpCodes.Leave, begin);
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;
1001 CompilerGenerated = 64
1004 public enum ReadOnlyContext: byte {
1011 ReadOnlyContext ro_context;
1013 public LocalInfo (Expression type, string name, Block block, Location l)
1021 public LocalInfo (TypeContainer tc, Block block, Location l)
1023 VariableType = tc.TypeBuilder;
1028 public bool IsThisAssigned (EmitContext ec, Location loc)
1030 if (VariableInfo == null)
1031 throw new Exception ();
1033 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
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);
1054 VariableType = texpr.ResolveType (ec);
1057 if (VariableType == TypeManager.void_type) {
1058 Report.Error (1547, Location,
1059 "Keyword 'void' cannot be used in this context");
1063 if (VariableType.IsAbstract && VariableType.IsSealed) {
1064 Report.Error (723, Location, "Cannot declare variable of static type `{0}'", TypeManager.CSharpName (VariableType));
1068 if (VariableType.IsPointer && !ec.InUnsafe)
1069 Expression.UnsafeError (Location);
1074 public bool IsCaptured {
1076 return (flags & Flags.Captured) != 0;
1080 flags |= Flags.Captured;
1084 public bool AddressTaken {
1086 return (flags & Flags.AddressTaken) != 0;
1090 flags |= Flags.AddressTaken;
1094 public bool CompilerGenerated {
1096 return (flags & Flags.CompilerGenerated) != 0;
1100 flags |= Flags.CompilerGenerated;
1104 public override string ToString ()
1106 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1107 Name, Type, VariableInfo, Location);
1112 return (flags & Flags.Used) != 0;
1115 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1119 public bool ReadOnly {
1121 return (flags & Flags.ReadOnly) != 0;
1125 public void SetReadOnlyContext (ReadOnlyContext context)
1127 flags |= Flags.ReadOnly;
1128 ro_context = context;
1131 public string GetReadOnlyContext ()
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 {
1153 return (flags & Flags.Pinned) != 0;
1156 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1160 public bool IsThis {
1162 return (flags & Flags.IsThis) != 0;
1165 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1171 /// Block represents a C# block.
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
1181 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1182 /// they contain extra information that is not necessary on normal blocks.
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;
1192 public enum Flags : ushort {
1196 VariablesInitialized = 8,
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;
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
1235 // Labels. (label, block) pairs.
1240 // Keeps track of (name, type) pairs
1242 Hashtable 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.
1258 protected static int 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)
1277 parent.AddChild (this);
1279 this.Parent = parent;
1281 this.StartLocation = start;
1282 this.EndLocation = end;
1285 statements = new ArrayList ();
1287 if ((flags & Flags.IsToplevel) != 0)
1288 Toplevel = (ToplevelBlock) this;
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;
1301 public Block CreateSwitchBlock (Location start)
1303 Block new_block = new Block (this, start, start);
1304 new_block.switch_block = this;
1309 get { return this_id; }
1312 protected Hashtable Variables {
1314 if (variables == null)
1315 variables = new Hashtable ();
1320 void AddChild (Block b)
1322 if (children == null)
1323 children = new ArrayList ();
1328 public void SetEndLocation (Location loc)
1334 /// Adds a label to the current block.
1338 /// false if the name already exists in this block. true
1342 public bool AddLabel (string name, LabeledStatement target, Location loc)
1344 if (switch_block != null)
1345 return switch_block.AddLabel (name, target, loc);
1348 while (cur != null) {
1349 if (cur.DoLookupLabel (name) != null) {
1351 140, loc, "The label `{0}' is a duplicate",
1362 while (cur != null) {
1363 if (cur.DoLookupLabel (name) != null) {
1366 "The label `{0}' shadows another label " +
1367 "by the same name in a contained scope.",
1372 if (children != null) {
1373 foreach (Block b in children) {
1374 LabeledStatement s = b.DoLookupLabel (name);
1380 "The label `{0}' shadows another " +
1381 "label by the same name in a " +
1393 labels = new Hashtable ();
1395 labels.Add (name, target);
1399 public LabeledStatement LookupLabel (string name)
1401 LabeledStatement s = DoLookupLabel (name);
1405 if (children == null)
1408 foreach (Block child in children) {
1409 if (!child.Implicit)
1412 s = child.LookupLabel (name);
1420 LabeledStatement DoLookupLabel (string name)
1422 if (switch_block != null)
1423 return switch_block.LookupLabel (name);
1426 if (labels.Contains (name))
1427 return ((LabeledStatement) labels [name]);
1432 Hashtable known_variables;
1435 // Marks a variable with name @name as being used in this or a child block.
1436 // If a variable name has been used in a child block, it's illegal to
1437 // declare a variable with the same name in the current block.
1439 void AddKnownVariable (string name, LocalInfo info)
1441 if (known_variables == null)
1442 known_variables = new Hashtable ();
1444 known_variables [name] = info;
1447 LocalInfo GetKnownVariableInfo (string name)
1449 if (known_variables == null)
1451 return (LocalInfo) known_variables [name];
1454 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1457 LocalInfo kvi = b.GetKnownVariableInfo (name);
1458 while (kvi == null) {
1464 kvi = b.GetKnownVariableInfo (name);
1470 // Is kvi.Block nested inside 'b'
1471 if (b.known_variables != kvi.Block.known_variables) {
1473 // If a variable by the same name it defined in a nested block of this
1474 // block, we violate the invariant meaning in a block.
1477 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1478 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1483 // It's ok if the definition is in a nested subblock of b, but not
1484 // nested inside this block -- a definition in a sibling block
1485 // should not affect us.
1491 // Block 'b' and kvi.Block are the same textual block.
1492 // However, different variables are extant.
1494 // Check if the variable is in scope in both blocks. We use
1495 // an indirect check that depends on AddVariable doing its
1496 // part in maintaining the invariant-meaning-in-block property.
1498 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1502 // Even though we detected the error when the name is used, we
1503 // treat it as if the variable declaration was in error.
1505 Report.SymbolRelatedToPreviousError (loc, name);
1506 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1510 public LocalInfo AddVariable (Expression type, string name, Location l)
1512 LocalInfo vi = GetLocalInfo (name);
1514 Report.SymbolRelatedToPreviousError (vi.Location, name);
1515 if (known_variables == vi.Block.known_variables)
1516 Report.Error (128, l,
1517 "A local variable named `{0}' is already defined in this scope", name);
1519 Error_AlreadyDeclared (l, name, "parent");
1523 vi = GetKnownVariableInfo (name);
1525 Report.SymbolRelatedToPreviousError (vi.Location, name);
1526 Error_AlreadyDeclared (l, name, "child");
1531 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1533 Report.SymbolRelatedToPreviousError (p.Location, name);
1534 Error_AlreadyDeclared (l, name, "method argument");
1538 vi = new LocalInfo (type, name, this, l);
1540 Variables.Add (name, vi);
1542 for (Block b = this; b != null; b = b.Parent)
1543 b.AddKnownVariable (name, vi);
1545 if ((flags & Flags.VariablesInitialized) != 0)
1546 throw new Exception ();
1551 void Error_AlreadyDeclared (Location loc, string var, string reason)
1553 Report.Error (136, loc, "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning to `{0}', " +
1554 "which is already used in a `{1}' scope", var, reason);
1557 public bool AddConstant (Expression type, string name, Expression value, Location l)
1559 if (AddVariable (type, name, l) == null)
1562 if (constants == null)
1563 constants = new Hashtable ();
1565 constants.Add (name, value);
1569 static int next_temp_id = 0;
1571 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1573 if (temporary_variables == null)
1574 temporary_variables = new ArrayList ();
1576 int id = ++next_temp_id;
1577 string name = "$s_" + id.ToString ();
1579 LocalInfo li = new LocalInfo (te, name, this, loc);
1580 li.CompilerGenerated = true;
1581 temporary_variables.Add (li);
1585 public LocalInfo GetLocalInfo (string name)
1587 for (Block b = this; b != null; b = b.Parent) {
1588 if (b.variables != null) {
1589 LocalInfo ret = b.variables [name] as LocalInfo;
1597 public Expression GetVariableType (string name)
1599 LocalInfo vi = GetLocalInfo (name);
1600 return vi == null ? null : vi.Type;
1603 public Expression GetConstantExpression (string name)
1605 for (Block b = this; b != null; b = b.Parent) {
1606 if (b.constants != null) {
1607 Expression ret = b.constants [name] as Expression;
1616 /// True if the variable named @name is a constant
1618 public bool IsConstant (string name)
1620 Expression e = GetConstantExpression (name);
1624 public void AddStatement (Statement s)
1627 flags |= Flags.BlockUsed;
1631 get { return (flags & Flags.BlockUsed) != 0; }
1636 flags |= Flags.BlockUsed;
1639 public bool HasRet {
1640 get { return (flags & Flags.HasRet) != 0; }
1643 public bool IsDestructor {
1644 get { return (flags & Flags.IsDestructor) != 0; }
1647 public void SetDestructor ()
1649 flags |= Flags.IsDestructor;
1652 VariableMap param_map, local_map;
1654 public VariableMap ParameterMap {
1656 if ((flags & Flags.VariablesInitialized) == 0)
1657 throw new Exception ("Variables have not been initialized yet");
1663 public VariableMap LocalMap {
1665 if ((flags & Flags.VariablesInitialized) == 0)
1666 throw new Exception ("Variables have not been initialized yet");
1673 /// Emits the variable declarations and labels.
1676 /// tc: is our typecontainer (to resolve type references)
1677 /// ig: is the code generator:
1679 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1681 bool old_unsafe = ec.InUnsafe;
1683 // If some parent block was unsafe, we remain unsafe even if this block
1684 // isn't explicitly marked as such.
1685 ec.InUnsafe |= Unsafe;
1688 // Compute the VariableMap's.
1690 // Unfortunately, we don't know the type when adding variables with
1691 // AddVariable(), so we need to compute this info here.
1695 if (variables != null) {
1696 foreach (LocalInfo li in variables.Values)
1699 locals = new LocalInfo [variables.Count];
1700 variables.Values.CopyTo (locals, 0);
1702 locals = new LocalInfo [0];
1705 local_map = new VariableMap (Parent.LocalMap, locals);
1707 local_map = new VariableMap (locals);
1709 param_map = new VariableMap (ip);
1710 flags |= Flags.VariablesInitialized;
1712 bool old_check_state = ec.ConstantCheckState;
1713 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1716 // Process this block variables
1718 if (variables != null){
1719 foreach (DictionaryEntry de in variables){
1720 string name = (string) de.Key;
1721 LocalInfo vi = (LocalInfo) de.Value;
1723 if (vi.VariableType == null)
1726 Type variable_type = vi.VariableType;
1728 if (variable_type.IsPointer){
1730 // Am not really convinced that this test is required (Microsoft does it)
1731 // but the fact is that you would not be able to use the pointer variable
1734 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1739 if (constants == null)
1742 Expression cv = (Expression) constants [name];
1746 ec.CurrentBlock = this;
1747 Expression e = cv.Resolve (ec);
1749 Constant ce = e as Constant;
1751 Const.Error_ExpressionMustBeConstant (vi.Location, name);
1755 e = ce.ToType (variable_type, vi.Location);
1759 constants.Remove (name);
1760 constants.Add (name, e);
1763 ec.ConstantCheckState = old_check_state;
1766 // Now, handle the children
1768 if (children != null){
1769 foreach (Block b in children)
1770 b.ResolveMeta (toplevel, ec, ip);
1772 ec.InUnsafe = old_unsafe;
1776 // Emits the local variable declarations for a block
1778 public void EmitMeta (EmitContext ec)
1780 ILGenerator ig = ec.ig;
1782 if (variables != null){
1783 bool have_captured_vars = ec.HaveCapturedVariables ();
1785 foreach (DictionaryEntry de in variables){
1786 LocalInfo vi = (LocalInfo) de.Value;
1788 if (have_captured_vars && ec.IsCaptured (vi))
1793 // This is needed to compile on both .NET 1.x and .NET 2.x
1794 // the later introduced `DeclareLocal (Type t, bool pinned)'
1796 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1797 else if (!vi.IsThis)
1798 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1802 if (temporary_variables != null) {
1803 AnonymousContainer am = ec.CurrentAnonymousMethod;
1804 TypeBuilder scope = null;
1805 if ((am != null) && am.IsIterator) {
1806 scope = am.Scope.ScopeTypeBuilder;
1808 throw new InternalErrorException ();
1810 foreach (LocalInfo vi in temporary_variables) {
1811 if (scope != null) {
1812 if (vi.FieldBuilder == null)
1813 vi.FieldBuilder = scope.DefineField (
1814 vi.Name, vi.VariableType, FieldAttributes.Assembly);
1816 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1820 if (children != null){
1821 foreach (Block b in children)
1826 void UsageWarning (FlowBranching.UsageVector vector)
1830 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1831 foreach (DictionaryEntry de in variables){
1832 LocalInfo vi = (LocalInfo) de.Value;
1837 name = (string) de.Key;
1839 if (vector.IsAssigned (vi.VariableInfo)){
1840 Report.Warning (219, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
1842 Report.Warning (168, vi.Location, "The variable `{0}' is declared but never used", name);
1848 bool unreachable_shown;
1851 private void CheckPossibleMistakenEmptyStatement (Statement s)
1855 // Some statements are wrapped by a Block. Since
1856 // others' internal could be changed, here I treat
1857 // them as possibly wrapped by Block equally.
1858 Block b = s as Block;
1859 if (b != null && b.statements.Count == 1)
1860 s = (Statement) b.statements [0];
1863 body = ((Lock) s).Statement;
1865 body = ((For) s).Statement;
1866 else if (s is Foreach)
1867 body = ((Foreach) s).Statement;
1868 else if (s is While)
1869 body = ((While) s).Statement;
1870 else if (s is Using)
1871 body = ((Using) s).Statement;
1872 else if (s is Fixed)
1873 body = ((Fixed) s).Statement;
1877 if (body == null || body is EmptyStatement)
1878 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
1881 public override bool Resolve (EmitContext ec)
1883 Block prev_block = ec.CurrentBlock;
1886 int errors = Report.Errors;
1888 ec.CurrentBlock = this;
1889 ec.StartFlowBranching (this);
1891 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1894 // This flag is used to notate nested statements as unreachable from the beginning of this block.
1895 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
1896 // from the beginning of the function. The outer Resolve() that detected the unreachability is
1897 // responsible for handling the situation.
1899 int statement_count = statements.Count;
1900 for (int ix = 0; ix < statement_count; ix++){
1901 Statement s = (Statement) statements [ix];
1902 // Check possible empty statement (CS0642)
1903 if (RootContext.WarningLevel >= 3 &&
1904 ix + 1 < statement_count &&
1905 statements [ix + 1] is Block)
1906 CheckPossibleMistakenEmptyStatement (s);
1910 ((Block) s).unreachable = true;
1912 if (!unreachable_shown && (RootContext.WarningLevel >= 2)) {
1914 162, s.loc, "Unreachable code detected");
1915 unreachable_shown = true;
1919 if (!s.Resolve (ec)) {
1921 statements [ix] = EmptyStatement.Value;
1925 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1926 statements [ix] = EmptyStatement.Value;
1928 num_statements = ix + 1;
1929 if (s is LabeledStatement)
1930 unreachable = false;
1932 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1935 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1936 ec.CurrentBranching, statement_count, num_statements);
1938 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1940 ec.CurrentBlock = prev_block;
1942 // If we're a non-static `struct' constructor which doesn't have an
1943 // initializer, then we must initialize all of the struct's fields.
1944 if ((flags & Flags.IsToplevel) != 0 &&
1945 !Toplevel.IsThisAssigned (ec) &&
1946 vector.Reachability.Throws != FlowBranching.FlowReturns.Always)
1949 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1950 foreach (LabeledStatement label in labels.Values)
1951 if (!label.HasBeenReferenced)
1952 Report.Warning (164, label.loc,
1953 "This label has not been referenced");
1956 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1958 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1959 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1960 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1961 flags |= Flags.HasRet;
1963 if (ok && (errors == Report.Errors)) {
1964 if (RootContext.WarningLevel >= 3)
1965 UsageWarning (vector);
1971 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1973 unreachable_shown = true;
1976 if (warn && (RootContext.WarningLevel >= 2))
1977 Report.Warning (162, loc, "Unreachable code detected");
1979 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1980 bool ok = Resolve (ec);
1981 ec.KillFlowBranching ();
1986 protected override void DoEmit (EmitContext ec)
1988 for (int ix = 0; ix < num_statements; ix++){
1989 Statement s = (Statement) statements [ix];
1991 // Check whether we are the last statement in a
1994 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
1995 ec.IsLastStatement = true;
1997 ec.IsLastStatement = false;
2003 public override void Emit (EmitContext ec)
2005 Block prev_block = ec.CurrentBlock;
2007 ec.CurrentBlock = this;
2009 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2010 bool is_lexical_block = !Implicit && (Parent != null);
2012 if (emit_debug_info) {
2013 if (is_lexical_block)
2016 if (variables != null) {
2017 foreach (DictionaryEntry de in variables) {
2018 string name = (string) de.Key;
2019 LocalInfo vi = (LocalInfo) de.Value;
2021 if (vi.LocalBuilder == null)
2024 ec.DefineLocalVariable (name, vi.LocalBuilder);
2029 ec.Mark (StartLocation, true);
2031 ec.Mark (EndLocation, true);
2033 if (emit_debug_info && is_lexical_block)
2036 ec.CurrentBlock = prev_block;
2040 // Returns true if we ar ea child of `b'.
2042 public bool IsChildOf (Block b)
2044 Block current = this;
2047 if (current.Parent == b)
2049 current = current.Parent;
2050 } while (current != null);
2054 public override string ToString ()
2056 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2061 // A toplevel block contains extra information, the split is done
2062 // only to separate information that would otherwise bloat the more
2063 // lightweight Block.
2065 // In particular, this was introduced when the support for Anonymous
2066 // Methods was implemented.
2068 public class ToplevelBlock : Block {
2070 // Pointer to the host of this anonymous method, or null
2071 // if we are the topmost block
2073 ToplevelBlock container;
2074 CaptureContext capture_context;
2075 FlowBranching top_level_branching;
2077 Hashtable capture_contexts;
2080 public bool HasVarargs {
2081 get { return (flags & Flags.HasVarargs) != 0; }
2082 set { flags |= Flags.HasVarargs; }
2086 // The parameters for the block.
2088 Parameters parameters;
2089 public Parameters Parameters {
2090 get { return parameters; }
2093 public void RegisterCaptureContext (CaptureContext cc)
2095 if (capture_contexts == null)
2096 capture_contexts = new Hashtable ();
2097 capture_contexts [cc] = cc;
2100 public void CompleteContexts ()
2102 if (capture_contexts == null)
2105 foreach (CaptureContext cc in capture_contexts.Keys){
2110 public CaptureContext ToplevelBlockCaptureContext {
2111 get { return capture_context; }
2114 public ToplevelBlock Container {
2115 get { return container; }
2118 protected void AddChild (ToplevelBlock block)
2120 if (children == null)
2121 children = new ArrayList ();
2123 children.Add (block);
2127 // Parent is only used by anonymous blocks to link back to their
2130 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2131 this (container, (Flags) 0, parameters, start)
2135 public ToplevelBlock (Parameters parameters, Location start) :
2136 this (null, (Flags) 0, parameters, start)
2140 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2141 this (null, flags, parameters, start)
2145 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2146 base (null, flags | Flags.IsToplevel, start, Location.Null)
2148 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2149 this.container = container;
2151 if (container != null)
2152 container.AddChild (this);
2155 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2159 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2161 if (capture_context == null)
2162 capture_context = new CaptureContext (this, loc, host);
2165 public CaptureContext CaptureContext {
2166 get { return capture_context; }
2169 public FlowBranching TopLevelBranching {
2170 get { return top_level_branching; }
2174 // This is used if anonymous methods are used inside an iterator
2175 // (see 2test-22.cs for an example).
2177 // The AnonymousMethod is created while parsing - at a time when we don't
2178 // know yet that we're inside an iterator, so it's `Container' is initially
2179 // null. Later on, when resolving the iterator, we need to move the
2180 // anonymous method into that iterator.
2182 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2184 foreach (ToplevelBlock block in children) {
2185 if (block.CaptureContext == null)
2188 block.container = new_parent;
2189 block.CaptureContext.ReParent (new_parent, new_host);
2194 // Returns a `ParameterReference' for the given name, or null if there
2195 // is no such parameter
2197 public ParameterReference GetParameterReference (string name, Location loc)
2202 for (ToplevelBlock t = this; t != null; t = t.Container) {
2203 Parameters pars = t.Parameters;
2204 par = pars.GetParameterByName (name, out idx);
2206 return new ParameterReference (pars, this, idx, name, loc);
2212 // Whether the parameter named `name' is local to this block,
2213 // or false, if the parameter belongs to an encompassing block.
2215 public bool IsLocalParameter (string name)
2217 return Parameters.GetParameterByName (name) != null;
2221 // Whether the `name' is a parameter reference
2223 public bool IsParameterReference (string name)
2225 for (ToplevelBlock t = this; t != null; t = t.Container) {
2226 if (t.IsLocalParameter (name))
2232 LocalInfo this_variable = null;
2235 // Returns the "this" instance variable of this block.
2236 // See AddThisVariable() for more information.
2238 public LocalInfo ThisVariable {
2239 get { return this_variable; }
2244 // This is used by non-static `struct' constructors which do not have an
2245 // initializer - in this case, the constructor must initialize all of the
2246 // struct's fields. To do this, we add a "this" variable and use the flow
2247 // analysis code to ensure that it's been fully initialized before control
2248 // leaves the constructor.
2250 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
2252 if (this_variable == null) {
2253 this_variable = new LocalInfo (tc, this, l);
2254 this_variable.Used = true;
2255 this_variable.IsThis = true;
2257 Variables.Add ("this", this_variable);
2260 return this_variable;
2263 public bool IsThisAssigned (EmitContext ec)
2265 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2268 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2270 int errors = Report.Errors;
2272 if (top_level_branching != null)
2276 parameters = ip.Parameters;
2278 ResolveMeta (this, ec, ip);
2280 top_level_branching = ec.StartFlowBranching (this);
2282 return Report.Errors == errors;
2286 public class SwitchLabel {
2293 Label il_label_code;
2294 bool il_label_code_set;
2296 public static readonly object NullStringCase = new object ();
2299 // if expr == null, then it is the default case.
2301 public SwitchLabel (Expression expr, Location l)
2307 public Expression Label {
2313 public object Converted {
2319 public Label GetILLabel (EmitContext ec)
2322 il_label = ec.ig.DefineLabel ();
2323 il_label_set = true;
2328 public Label GetILLabelCode (EmitContext ec)
2330 if (!il_label_code_set){
2331 il_label_code = ec.ig.DefineLabel ();
2332 il_label_code_set = true;
2334 return il_label_code;
2338 // Resolves the expression, reduces it to a literal if possible
2339 // and then converts it to the requested type.
2341 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2343 Expression e = label.Resolve (ec);
2348 Constant c = e as Constant;
2350 Report.Error (150, loc, "A constant value is expected");
2354 if (required_type == TypeManager.string_type && e is NullLiteral) {
2355 converted = NullStringCase;
2359 c = c.ToType (required_type, loc);
2363 converted = c.GetValue ();
2367 public void Erorr_AlreadyOccurs ()
2370 if (converted == null)
2372 else if (converted is NullLiteral)
2375 label = converted.ToString ();
2377 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2381 public class SwitchSection {
2382 // An array of SwitchLabels.
2383 public readonly ArrayList Labels;
2384 public readonly Block Block;
2386 public SwitchSection (ArrayList labels, Block block)
2393 public class Switch : Statement {
2394 public readonly ArrayList Sections;
2395 public Expression Expr;
2398 /// Maps constants whose type type SwitchType to their SwitchLabels.
2400 public IDictionary Elements;
2403 /// The governing switch type
2405 public Type SwitchType;
2410 Label default_target;
2411 Expression new_expr;
2413 SwitchSection constant_section;
2414 SwitchSection default_section;
2417 // The types allowed to be implicitly cast from
2418 // on the governing type
2420 static Type [] allowed_types;
2422 public Switch (Expression e, ArrayList sects, Location l)
2429 public bool GotDefault {
2431 return default_section != null;
2435 public Label DefaultTarget {
2437 return default_target;
2442 // Determines the governing type for a switch. The returned
2443 // expression might be the expression from the switch, or an
2444 // expression that includes any potential conversions to the
2445 // integral types or to string.
2447 Expression SwitchGoverningType (EmitContext ec, Type t)
2449 if (t == TypeManager.byte_type ||
2450 t == TypeManager.sbyte_type ||
2451 t == TypeManager.ushort_type ||
2452 t == TypeManager.short_type ||
2453 t == TypeManager.uint32_type ||
2454 t == TypeManager.int32_type ||
2455 t == TypeManager.uint64_type ||
2456 t == TypeManager.int64_type ||
2457 t == TypeManager.char_type ||
2458 t == TypeManager.string_type ||
2459 t == TypeManager.bool_type ||
2460 t.IsSubclassOf (TypeManager.enum_type))
2463 if (allowed_types == null){
2464 allowed_types = new Type [] {
2465 TypeManager.sbyte_type,
2466 TypeManager.byte_type,
2467 TypeManager.short_type,
2468 TypeManager.ushort_type,
2469 TypeManager.int32_type,
2470 TypeManager.uint32_type,
2471 TypeManager.int64_type,
2472 TypeManager.uint64_type,
2473 TypeManager.char_type,
2474 TypeManager.string_type,
2475 TypeManager.bool_type
2480 // Try to find a *user* defined implicit conversion.
2482 // If there is no implicit conversion, or if there are multiple
2483 // conversions, we have to report an error
2485 Expression converted = null;
2486 foreach (Type tt in allowed_types){
2489 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2494 // Ignore over-worked ImplicitUserConversions that do
2495 // an implicit conversion in addition to the user conversion.
2497 if (!(e is UserCast))
2500 if (converted != null){
2501 Report.ExtraInformation (
2503 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2504 TypeManager.CSharpName (Expr.Type)));
2514 // Performs the basic sanity checks on the switch statement
2515 // (looks for duplicate keys and non-constant expressions).
2517 // It also returns a hashtable with the keys that we will later
2518 // use to compute the switch tables
2520 bool CheckSwitch (EmitContext ec)
2523 Elements = Sections.Count > 10 ?
2524 (IDictionary)new Hashtable () :
2525 (IDictionary)new ListDictionary ();
2527 foreach (SwitchSection ss in Sections){
2528 foreach (SwitchLabel sl in ss.Labels){
2529 if (sl.Label == null){
2530 if (default_section != null){
2531 sl.Erorr_AlreadyOccurs ();
2534 default_section = ss;
2538 if (!sl.ResolveAndReduce (ec, SwitchType)){
2543 object key = sl.Converted;
2545 Elements.Add (key, sl);
2547 catch (ArgumentException) {
2548 sl.Erorr_AlreadyOccurs ();
2556 void EmitObjectInteger (ILGenerator ig, object k)
2559 IntConstant.EmitInt (ig, (int) k);
2560 else if (k is Constant) {
2561 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2564 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2567 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2569 IntConstant.EmitInt (ig, (int) (long) k);
2570 ig.Emit (OpCodes.Conv_I8);
2573 LongConstant.EmitLong (ig, (long) k);
2575 else if (k is ulong)
2577 if ((ulong) k < (1L<<32))
2579 IntConstant.EmitInt (ig, (int) (long) k);
2580 ig.Emit (OpCodes.Conv_U8);
2584 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2588 IntConstant.EmitInt (ig, (int) ((char) k));
2589 else if (k is sbyte)
2590 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2592 IntConstant.EmitInt (ig, (int) ((byte) k));
2593 else if (k is short)
2594 IntConstant.EmitInt (ig, (int) ((short) k));
2595 else if (k is ushort)
2596 IntConstant.EmitInt (ig, (int) ((ushort) k));
2598 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2600 throw new Exception ("Unhandled case");
2603 // structure used to hold blocks of keys while calculating table switch
2604 class KeyBlock : IComparable
2606 public KeyBlock (long _nFirst)
2608 nFirst = nLast = _nFirst;
2612 public ArrayList rgKeys = null;
2613 // how many items are in the bucket
2614 public int Size = 1;
2617 get { return (int) (nLast - nFirst + 1); }
2619 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2621 return kbLast.nLast - kbFirst.nFirst + 1;
2623 public int CompareTo (object obj)
2625 KeyBlock kb = (KeyBlock) obj;
2626 int nLength = Length;
2627 int nLengthOther = kb.Length;
2628 if (nLengthOther == nLength)
2629 return (int) (kb.nFirst - nFirst);
2630 return nLength - nLengthOther;
2635 /// This method emits code for a lookup-based switch statement (non-string)
2636 /// Basically it groups the cases into blocks that are at least half full,
2637 /// and then spits out individual lookup opcodes for each block.
2638 /// It emits the longest blocks first, and short blocks are just
2639 /// handled with direct compares.
2641 /// <param name="ec"></param>
2642 /// <param name="val"></param>
2643 /// <returns></returns>
2644 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2646 int cElements = Elements.Count;
2647 object [] rgKeys = new object [cElements];
2648 Elements.Keys.CopyTo (rgKeys, 0);
2649 Array.Sort (rgKeys);
2651 // initialize the block list with one element per key
2652 ArrayList rgKeyBlocks = new ArrayList ();
2653 foreach (object key in rgKeys)
2654 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2657 // iteratively merge the blocks while they are at least half full
2658 // there's probably a really cool way to do this with a tree...
2659 while (rgKeyBlocks.Count > 1)
2661 ArrayList rgKeyBlocksNew = new ArrayList ();
2662 kbCurr = (KeyBlock) rgKeyBlocks [0];
2663 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2665 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2666 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2669 kbCurr.nLast = kb.nLast;
2670 kbCurr.Size += kb.Size;
2674 // start a new block
2675 rgKeyBlocksNew.Add (kbCurr);
2679 rgKeyBlocksNew.Add (kbCurr);
2680 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2682 rgKeyBlocks = rgKeyBlocksNew;
2685 // initialize the key lists
2686 foreach (KeyBlock kb in rgKeyBlocks)
2687 kb.rgKeys = new ArrayList ();
2689 // fill the key lists
2691 if (rgKeyBlocks.Count > 0) {
2692 kbCurr = (KeyBlock) rgKeyBlocks [0];
2693 foreach (object key in rgKeys)
2695 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2696 System.Convert.ToInt64 (key) > kbCurr.nLast;
2698 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2699 kbCurr.rgKeys.Add (key);
2703 // sort the blocks so we can tackle the largest ones first
2704 rgKeyBlocks.Sort ();
2706 // okay now we can start...
2707 ILGenerator ig = ec.ig;
2708 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2709 Label lblDefault = ig.DefineLabel ();
2711 Type typeKeys = null;
2712 if (rgKeys.Length > 0)
2713 typeKeys = rgKeys [0].GetType (); // used for conversions
2717 if (TypeManager.IsEnumType (SwitchType))
2718 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2720 compare_type = SwitchType;
2722 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2724 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2725 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2728 foreach (object key in kb.rgKeys)
2730 ig.Emit (OpCodes.Ldloc, val);
2731 EmitObjectInteger (ig, key);
2732 SwitchLabel sl = (SwitchLabel) Elements [key];
2733 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2738 // TODO: if all the keys in the block are the same and there are
2739 // no gaps/defaults then just use a range-check.
2740 if (compare_type == TypeManager.int64_type ||
2741 compare_type == TypeManager.uint64_type)
2743 // TODO: optimize constant/I4 cases
2745 // check block range (could be > 2^31)
2746 ig.Emit (OpCodes.Ldloc, val);
2747 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2748 ig.Emit (OpCodes.Blt, lblDefault);
2749 ig.Emit (OpCodes.Ldloc, val);
2750 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2751 ig.Emit (OpCodes.Bgt, lblDefault);
2754 ig.Emit (OpCodes.Ldloc, val);
2757 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2758 ig.Emit (OpCodes.Sub);
2760 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2765 ig.Emit (OpCodes.Ldloc, val);
2766 int nFirst = (int) kb.nFirst;
2769 IntConstant.EmitInt (ig, nFirst);
2770 ig.Emit (OpCodes.Sub);
2772 else if (nFirst < 0)
2774 IntConstant.EmitInt (ig, -nFirst);
2775 ig.Emit (OpCodes.Add);
2779 // first, build the list of labels for the switch
2781 int cJumps = kb.Length;
2782 Label [] rgLabels = new Label [cJumps];
2783 for (int iJump = 0; iJump < cJumps; iJump++)
2785 object key = kb.rgKeys [iKey];
2786 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2788 SwitchLabel sl = (SwitchLabel) Elements [key];
2789 rgLabels [iJump] = sl.GetILLabel (ec);
2793 rgLabels [iJump] = lblDefault;
2795 // emit the switch opcode
2796 ig.Emit (OpCodes.Switch, rgLabels);
2799 // mark the default for this block
2801 ig.MarkLabel (lblDefault);
2804 // TODO: find the default case and emit it here,
2805 // to prevent having to do the following jump.
2806 // make sure to mark other labels in the default section
2808 // the last default just goes to the end
2809 ig.Emit (OpCodes.Br, lblDefault);
2811 // now emit the code for the sections
2812 bool fFoundDefault = false;
2813 foreach (SwitchSection ss in Sections)
2815 foreach (SwitchLabel sl in ss.Labels)
2817 ig.MarkLabel (sl.GetILLabel (ec));
2818 ig.MarkLabel (sl.GetILLabelCode (ec));
2819 if (sl.Label == null)
2821 ig.MarkLabel (lblDefault);
2822 fFoundDefault = true;
2826 //ig.Emit (OpCodes.Br, lblEnd);
2829 if (!fFoundDefault) {
2830 ig.MarkLabel (lblDefault);
2832 ig.MarkLabel (lblEnd);
2835 // This simple emit switch works, but does not take advantage of the
2837 // TODO: remove non-string logic from here
2838 // TODO: binary search strings?
2840 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2842 ILGenerator ig = ec.ig;
2843 Label end_of_switch = ig.DefineLabel ();
2844 Label next_test = ig.DefineLabel ();
2845 Label null_target = ig.DefineLabel ();
2846 bool first_test = true;
2847 bool pending_goto_end = false;
2848 bool null_marked = false;
2851 ig.Emit (OpCodes.Ldloc, val);
2853 if (Elements.Contains (SwitchLabel.NullStringCase)){
2854 ig.Emit (OpCodes.Brfalse, null_target);
2856 ig.Emit (OpCodes.Brfalse, default_target);
2858 ig.Emit (OpCodes.Ldloc, val);
2859 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2860 ig.Emit (OpCodes.Stloc, val);
2862 int section_count = Sections.Count;
2863 for (int section = 0; section < section_count; section++){
2864 SwitchSection ss = (SwitchSection) Sections [section];
2866 if (ss == default_section)
2869 Label sec_begin = ig.DefineLabel ();
2871 ig.Emit (OpCodes.Nop);
2873 if (pending_goto_end)
2874 ig.Emit (OpCodes.Br, end_of_switch);
2876 int label_count = ss.Labels.Count;
2878 for (int label = 0; label < label_count; label++){
2879 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2880 ig.MarkLabel (sl.GetILLabel (ec));
2883 ig.MarkLabel (next_test);
2884 next_test = ig.DefineLabel ();
2887 // If we are the default target
2889 if (sl.Label != null){
2890 object lit = sl.Converted;
2892 if (lit == SwitchLabel.NullStringCase){
2894 if (label_count == 1)
2895 ig.Emit (OpCodes.Br, next_test);
2899 ig.Emit (OpCodes.Ldloc, val);
2900 ig.Emit (OpCodes.Ldstr, (string)lit);
2901 if (label_count == 1)
2902 ig.Emit (OpCodes.Bne_Un, next_test);
2904 if (label+1 == label_count)
2905 ig.Emit (OpCodes.Bne_Un, next_test);
2907 ig.Emit (OpCodes.Beq, sec_begin);
2912 ig.MarkLabel (null_target);
2915 ig.MarkLabel (sec_begin);
2916 foreach (SwitchLabel sl in ss.Labels)
2917 ig.MarkLabel (sl.GetILLabelCode (ec));
2920 pending_goto_end = !ss.Block.HasRet;
2923 ig.MarkLabel (next_test);
2924 ig.MarkLabel (default_target);
2926 ig.MarkLabel (null_target);
2927 if (default_section != null)
2928 default_section.Block.Emit (ec);
2929 ig.MarkLabel (end_of_switch);
2932 SwitchSection FindSection (SwitchLabel label)
2934 foreach (SwitchSection ss in Sections){
2935 foreach (SwitchLabel sl in ss.Labels){
2944 public override bool Resolve (EmitContext ec)
2946 Expr = Expr.Resolve (ec);
2950 new_expr = SwitchGoverningType (ec, Expr.Type);
2951 if (new_expr == null){
2952 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2957 SwitchType = new_expr.Type;
2959 if (!CheckSwitch (ec))
2962 Switch old_switch = ec.Switch;
2964 ec.Switch.SwitchType = SwitchType;
2966 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2967 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2969 is_constant = new_expr is Constant;
2971 object key = ((Constant) new_expr).GetValue ();
2972 SwitchLabel label = (SwitchLabel) Elements [key];
2974 constant_section = FindSection (label);
2975 if (constant_section == null)
2976 constant_section = default_section;
2980 foreach (SwitchSection ss in Sections){
2982 ec.CurrentBranching.CreateSibling (
2983 null, FlowBranching.SiblingType.SwitchSection);
2987 if (is_constant && (ss != constant_section)) {
2988 // If we're a constant switch, we're only emitting
2989 // one single section - mark all the others as
2991 ec.CurrentBranching.CurrentUsageVector.Goto ();
2992 if (!ss.Block.ResolveUnreachable (ec, true))
2995 if (!ss.Block.Resolve (ec))
3000 if (default_section == null)
3001 ec.CurrentBranching.CreateSibling (
3002 null, FlowBranching.SiblingType.SwitchSection);
3004 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3005 ec.Switch = old_switch;
3007 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3013 protected override void DoEmit (EmitContext ec)
3015 ILGenerator ig = ec.ig;
3017 // Store variable for comparission purposes
3020 value = ig.DeclareLocal (SwitchType);
3022 ig.Emit (OpCodes.Stloc, value);
3026 default_target = ig.DefineLabel ();
3029 // Setup the codegen context
3031 Label old_end = ec.LoopEnd;
3032 Switch old_switch = ec.Switch;
3034 ec.LoopEnd = ig.DefineLabel ();
3039 if (constant_section != null)
3040 constant_section.Block.Emit (ec);
3041 } else if (SwitchType == TypeManager.string_type)
3042 SimpleSwitchEmit (ec, value);
3044 TableSwitchEmit (ec, value);
3046 // Restore context state.
3047 ig.MarkLabel (ec.LoopEnd);
3050 // Restore the previous context
3052 ec.LoopEnd = old_end;
3053 ec.Switch = old_switch;
3057 public abstract class ExceptionStatement : Statement
3059 public abstract void EmitFinally (EmitContext ec);
3061 protected bool emit_finally = true;
3062 ArrayList parent_vectors;
3064 protected void DoEmitFinally (EmitContext ec)
3067 ec.ig.BeginFinallyBlock ();
3068 else if (ec.InIterator)
3069 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3073 protected void ResolveFinally (FlowBranchingException branching)
3075 emit_finally = branching.EmitFinally;
3077 branching.Parent.StealFinallyClauses (ref parent_vectors);
3081 public class Lock : ExceptionStatement {
3083 public Statement Statement;
3084 TemporaryVariable temp;
3086 public Lock (Expression expr, Statement stmt, Location l)
3093 public override bool Resolve (EmitContext ec)
3095 expr = expr.Resolve (ec);
3099 if (expr.Type.IsValueType){
3100 Report.Error (185, loc,
3101 "`{0}' is not a reference type as required by the lock statement",
3102 TypeManager.CSharpName (expr.Type));
3106 FlowBranchingException branching = ec.StartFlowBranching (this);
3107 bool ok = Statement.Resolve (ec);
3109 ec.KillFlowBranching ();
3113 ResolveFinally (branching);
3115 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3116 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3117 // Unfortunately, System.Reflection.Emit automatically emits
3118 // a leave to the end of the finally block.
3119 // This is a problem if `returns' is true since we may jump
3120 // to a point after the end of the method.
3121 // As a workaround, emit an explicit ret here.
3122 ec.NeedReturnLabel ();
3125 temp = new TemporaryVariable (expr.Type, loc);
3131 protected override void DoEmit (EmitContext ec)
3133 ILGenerator ig = ec.ig;
3135 temp.Store (ec, expr);
3137 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3141 ig.BeginExceptionBlock ();
3142 Statement.Emit (ec);
3147 ig.EndExceptionBlock ();
3150 public override void EmitFinally (EmitContext ec)
3153 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3157 public class Unchecked : Statement {
3158 public readonly Block Block;
3160 public Unchecked (Block b)
3166 public override bool Resolve (EmitContext ec)
3168 bool previous_state = ec.CheckState;
3169 bool previous_state_const = ec.ConstantCheckState;
3171 ec.CheckState = false;
3172 ec.ConstantCheckState = false;
3173 bool ret = Block.Resolve (ec);
3174 ec.CheckState = previous_state;
3175 ec.ConstantCheckState = previous_state_const;
3180 protected override void DoEmit (EmitContext ec)
3182 bool previous_state = ec.CheckState;
3183 bool previous_state_const = ec.ConstantCheckState;
3185 ec.CheckState = false;
3186 ec.ConstantCheckState = false;
3188 ec.CheckState = previous_state;
3189 ec.ConstantCheckState = previous_state_const;
3193 public class Checked : Statement {
3194 public readonly Block Block;
3196 public Checked (Block b)
3199 b.Unchecked = false;
3202 public override bool Resolve (EmitContext ec)
3204 bool previous_state = ec.CheckState;
3205 bool previous_state_const = ec.ConstantCheckState;
3207 ec.CheckState = true;
3208 ec.ConstantCheckState = true;
3209 bool ret = Block.Resolve (ec);
3210 ec.CheckState = previous_state;
3211 ec.ConstantCheckState = previous_state_const;
3216 protected override void DoEmit (EmitContext ec)
3218 bool previous_state = ec.CheckState;
3219 bool previous_state_const = ec.ConstantCheckState;
3221 ec.CheckState = true;
3222 ec.ConstantCheckState = true;
3224 ec.CheckState = previous_state;
3225 ec.ConstantCheckState = previous_state_const;
3229 public class Unsafe : Statement {
3230 public readonly Block Block;
3232 public Unsafe (Block b)
3235 Block.Unsafe = true;
3238 public override bool Resolve (EmitContext ec)
3240 bool previous_state = ec.InUnsafe;
3244 val = Block.Resolve (ec);
3245 ec.InUnsafe = previous_state;
3250 protected override void DoEmit (EmitContext ec)
3252 bool previous_state = ec.InUnsafe;
3256 ec.InUnsafe = previous_state;
3263 public class Fixed : Statement {
3265 ArrayList declarators;
3266 Statement statement;
3271 abstract class Emitter
3273 protected LocalInfo vi;
3274 protected Expression converted;
3276 protected Emitter (Expression expr, LocalInfo li)
3282 public abstract void Emit (EmitContext ec);
3283 public abstract void EmitExit (ILGenerator ig);
3286 class ExpressionEmitter: Emitter {
3287 public ExpressionEmitter (Expression converted, LocalInfo li) :
3288 base (converted, li)
3292 public override void Emit (EmitContext ec) {
3294 // Store pointer in pinned location
3296 converted.Emit (ec);
3297 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3300 public override void EmitExit (ILGenerator ig)
3302 ig.Emit (OpCodes.Ldc_I4_0);
3303 ig.Emit (OpCodes.Conv_U);
3304 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3308 class StringEmitter: Emitter {
3309 LocalBuilder pinned_string;
3312 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3318 public override void Emit (EmitContext ec)
3320 ILGenerator ig = ec.ig;
3321 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3323 converted.Emit (ec);
3324 ig.Emit (OpCodes.Stloc, pinned_string);
3326 Expression sptr = new StringPtr (pinned_string, loc);
3327 converted = Convert.ImplicitConversionRequired (
3328 ec, sptr, vi.VariableType, loc);
3330 if (converted == null)
3333 converted.Emit (ec);
3334 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3337 public override void EmitExit(ILGenerator ig)
3339 ig.Emit (OpCodes.Ldnull);
3340 ig.Emit (OpCodes.Stloc, pinned_string);
3344 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3347 declarators = decls;
3352 public Statement Statement {
3353 get { return statement; }
3356 public override bool Resolve (EmitContext ec)
3359 Expression.UnsafeError (loc);
3363 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3367 expr_type = texpr.ResolveType (ec);
3369 data = new Emitter [declarators.Count];
3371 if (!expr_type.IsPointer){
3372 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3377 foreach (Pair p in declarators){
3378 LocalInfo vi = (LocalInfo) p.First;
3379 Expression e = (Expression) p.Second;
3381 vi.VariableInfo.SetAssigned (ec);
3382 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3385 // The rules for the possible declarators are pretty wise,
3386 // but the production on the grammar is more concise.
3388 // So we have to enforce these rules here.
3390 // We do not resolve before doing the case 1 test,
3391 // because the grammar is explicit in that the token &
3392 // is present, so we need to test for this particular case.
3396 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3401 // Case 1: & object.
3403 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3404 Expression child = ((Unary) e).Expr;
3406 if (child is ParameterReference || child is LocalVariableReference){
3409 "No need to use fixed statement for parameters or " +
3410 "local variable declarations (address is already " +
3415 ec.InFixedInitializer = true;
3417 ec.InFixedInitializer = false;
3421 child = ((Unary) e).Expr;
3423 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3426 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
3427 Convert.Error_CannotImplicitConversion (e.Location, e.Type, expr_type);
3431 data [i] = new ExpressionEmitter (e, vi);
3437 ec.InFixedInitializer = true;
3439 ec.InFixedInitializer = false;
3446 if (e.Type.IsArray){
3447 Type array_type = TypeManager.GetElementType (e.Type);
3450 // Provided that array_type is unmanaged,
3452 if (!TypeManager.VerifyUnManaged (array_type, loc))
3456 // and T* is implicitly convertible to the
3457 // pointer type given in the fixed statement.
3459 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3461 Expression converted = Convert.ImplicitConversionRequired (
3462 ec, array_ptr, vi.VariableType, loc);
3463 if (converted == null)
3466 data [i] = new ExpressionEmitter (converted, vi);
3475 if (e.Type == TypeManager.string_type){
3476 data [i] = new StringEmitter (e, vi, loc);
3481 // Case 4: fixed buffer
3482 FieldExpr fe = e as FieldExpr;
3484 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3486 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3488 Expression converted = Convert.ImplicitConversionRequired (
3489 ec, fixed_buffer_ptr, vi.VariableType, loc);
3490 if (converted == null)
3493 data [i] = new ExpressionEmitter (converted, vi);
3501 // For other cases, flag a `this is already fixed expression'
3503 if (e is LocalVariableReference || e is ParameterReference ||
3504 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3506 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3510 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3514 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3516 if (!statement.Resolve (ec)) {
3517 ec.KillFlowBranching ();
3521 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3522 has_ret = reachability.IsUnreachable;
3527 protected override void DoEmit (EmitContext ec)
3529 for (int i = 0; i < data.Length; i++) {
3533 statement.Emit (ec);
3538 ILGenerator ig = ec.ig;
3541 // Clear the pinned variable
3543 for (int i = 0; i < data.Length; i++) {
3544 data [i].EmitExit (ig);
3549 public class Catch: Statement {
3550 public readonly string Name;
3551 public readonly Block Block;
3553 Expression type_expr;
3556 public Catch (Expression type, string name, Block block, Location l)
3564 public Type CatchType {
3570 public bool IsGeneral {
3572 return type_expr == null;
3576 protected override void DoEmit(EmitContext ec)
3580 public override bool Resolve (EmitContext ec)
3582 bool was_catch = ec.InCatch;
3585 if (type_expr != null) {
3586 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3590 type = te.ResolveType (ec);
3592 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3593 Error (155, "The type caught or thrown must be derived from System.Exception");
3599 return Block.Resolve (ec);
3602 ec.InCatch = was_catch;
3607 public class Try : ExceptionStatement {
3608 public readonly Block Fini, Block;
3609 public readonly ArrayList Specific;
3610 public readonly Catch General;
3612 bool need_exc_block;
3615 // specific, general and fini might all be null.
3617 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3619 if (specific == null && general == null){
3620 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3624 this.Specific = specific;
3625 this.General = general;
3630 public override bool Resolve (EmitContext ec)
3634 FlowBranchingException branching = ec.StartFlowBranching (this);
3636 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3638 if (!Block.Resolve (ec))
3641 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3643 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3645 Type[] prevCatches = new Type [Specific.Count];
3647 foreach (Catch c in Specific){
3648 ec.CurrentBranching.CreateSibling (
3649 c.Block, FlowBranching.SiblingType.Catch);
3651 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3653 if (c.Name != null) {
3654 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3656 throw new Exception ();
3658 vi.VariableInfo = null;
3661 if (!c.Resolve (ec))
3664 Type resolvedType = c.CatchType;
3665 for (int ii = 0; ii < last_index; ++ii) {
3666 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3667 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3672 prevCatches [last_index++] = resolvedType;
3673 need_exc_block = true;
3676 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3678 if (General != null){
3679 ec.CurrentBranching.CreateSibling (
3680 General.Block, FlowBranching.SiblingType.Catch);
3682 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3684 if (!General.Resolve (ec))
3687 need_exc_block = true;
3690 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3694 ec.CurrentBranching.CreateSibling (
3695 Fini, FlowBranching.SiblingType.Finally);
3697 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3698 bool was_finally = ec.InFinally;
3699 ec.InFinally = true;
3700 if (!Fini.Resolve (ec))
3702 ec.InFinally = was_finally;
3705 need_exc_block = true;
3708 if (ec.InIterator) {
3709 ResolveFinally (branching);
3710 need_exc_block |= emit_finally;
3712 emit_finally = Fini != null;
3714 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3716 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3718 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3720 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3721 // Unfortunately, System.Reflection.Emit automatically emits
3722 // a leave to the end of the finally block. This is a problem
3723 // if `returns' is true since we may jump to a point after the
3724 // end of the method.
3725 // As a workaround, emit an explicit ret here.
3726 ec.NeedReturnLabel ();
3732 protected override void DoEmit (EmitContext ec)
3734 ILGenerator ig = ec.ig;
3737 ig.BeginExceptionBlock ();
3740 foreach (Catch c in Specific){
3743 ig.BeginCatchBlock (c.CatchType);
3745 if (c.Name != null){
3746 vi = c.Block.GetLocalInfo (c.Name);
3748 throw new Exception ("Variable does not exist in this block");
3750 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3752 ec.EmitCapturedVariableInstance (vi);
3753 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
3754 ig.Emit (OpCodes.Stfld, vi.FieldBuilder);
3757 ig.Emit (OpCodes.Pop);
3762 if (General != null){
3763 ig.BeginCatchBlock (TypeManager.object_type);
3764 ig.Emit (OpCodes.Pop);
3765 General.Block.Emit (ec);
3770 ig.EndExceptionBlock ();
3773 public override void EmitFinally (EmitContext ec)
3779 public bool HasCatch
3782 return General != null || Specific.Count > 0;
3787 public class Using : ExceptionStatement {
3788 object expression_or_block;
3789 public Statement Statement;
3793 Expression [] resolved_vars;
3794 Expression [] converted_vars;
3795 ExpressionStatement [] assign;
3796 LocalBuilder local_copy;
3798 public Using (object expression_or_block, Statement stmt, Location l)
3800 this.expression_or_block = expression_or_block;
3806 // Resolves for the case of using using a local variable declaration.
3808 bool ResolveLocalVariableDecls (EmitContext ec)
3812 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3816 expr_type = texpr.ResolveType (ec);
3819 // The type must be an IDisposable or an implicit conversion
3822 converted_vars = new Expression [var_list.Count];
3823 resolved_vars = new Expression [var_list.Count];
3824 assign = new ExpressionStatement [var_list.Count];
3826 bool need_conv = !TypeManager.ImplementsInterface (
3827 expr_type, TypeManager.idisposable_type);
3829 foreach (DictionaryEntry e in var_list){
3830 Expression var = (Expression) e.Key;
3832 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3836 resolved_vars [i] = var;
3843 converted_vars [i] = Convert.ImplicitConversion (
3844 ec, var, TypeManager.idisposable_type, loc);
3846 if (converted_vars [i] == null) {
3847 Error_IsNotConvertibleToIDisposable ();
3855 foreach (DictionaryEntry e in var_list){
3856 Expression var = resolved_vars [i];
3857 Expression new_expr = (Expression) e.Value;
3860 a = new Assign (var, new_expr, loc);
3866 converted_vars [i] = var;
3867 assign [i] = (ExpressionStatement) a;
3874 void Error_IsNotConvertibleToIDisposable ()
3876 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
3877 TypeManager.CSharpName (expr_type));
3880 bool ResolveExpression (EmitContext ec)
3882 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3883 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3884 Error_IsNotConvertibleToIDisposable ();
3893 // Emits the code for the case of using using a local variable declaration.
3895 void EmitLocalVariableDecls (EmitContext ec)
3897 ILGenerator ig = ec.ig;
3900 for (i = 0; i < assign.Length; i++) {
3901 assign [i].EmitStatement (ec);
3904 ig.BeginExceptionBlock ();
3906 Statement.Emit (ec);
3908 var_list.Reverse ();
3913 void EmitLocalVariableDeclFinally (EmitContext ec)
3915 ILGenerator ig = ec.ig;
3917 int i = assign.Length;
3918 for (int ii = 0; ii < var_list.Count; ++ii){
3919 Expression var = resolved_vars [--i];
3920 Label skip = ig.DefineLabel ();
3922 ig.BeginFinallyBlock ();
3924 if (!var.Type.IsValueType) {
3926 ig.Emit (OpCodes.Brfalse, skip);
3927 converted_vars [i].Emit (ec);
3928 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3930 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3932 if (!(ml is MethodGroupExpr)) {
3934 ig.Emit (OpCodes.Box, var.Type);
3935 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3937 MethodInfo mi = null;
3939 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3940 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3947 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3951 IMemoryLocation mloc = (IMemoryLocation) var;
3953 mloc.AddressOf (ec, AddressOp.Load);
3954 ig.Emit (OpCodes.Call, mi);
3958 ig.MarkLabel (skip);
3961 ig.EndExceptionBlock ();
3963 ig.BeginFinallyBlock ();
3968 void EmitExpression (EmitContext ec)
3971 // Make a copy of the expression and operate on that.
3973 ILGenerator ig = ec.ig;
3974 local_copy = ig.DeclareLocal (expr_type);
3977 ig.Emit (OpCodes.Stloc, local_copy);
3980 ig.BeginExceptionBlock ();
3982 Statement.Emit (ec);
3986 ig.EndExceptionBlock ();
3989 void EmitExpressionFinally (EmitContext ec)
3991 ILGenerator ig = ec.ig;
3992 if (!local_copy.LocalType.IsValueType) {
3993 Label skip = ig.DefineLabel ();
3994 ig.Emit (OpCodes.Ldloc, local_copy);
3995 ig.Emit (OpCodes.Brfalse, skip);
3996 ig.Emit (OpCodes.Ldloc, local_copy);
3997 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3998 ig.MarkLabel (skip);
4000 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4002 if (!(ml is MethodGroupExpr)) {
4003 ig.Emit (OpCodes.Ldloc, local_copy);
4004 ig.Emit (OpCodes.Box, local_copy.LocalType);
4005 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4007 MethodInfo mi = null;
4009 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4010 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4017 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4021 ig.Emit (OpCodes.Ldloca, local_copy);
4022 ig.Emit (OpCodes.Call, mi);
4027 public override bool Resolve (EmitContext ec)
4029 if (expression_or_block is DictionaryEntry){
4030 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4031 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4033 if (!ResolveLocalVariableDecls (ec))
4036 } else if (expression_or_block is Expression){
4037 expr = (Expression) expression_or_block;
4039 expr = expr.Resolve (ec);
4043 expr_type = expr.Type;
4045 if (!ResolveExpression (ec))
4049 FlowBranchingException branching = ec.StartFlowBranching (this);
4051 bool ok = Statement.Resolve (ec);
4054 ec.KillFlowBranching ();
4058 ResolveFinally (branching);
4059 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4061 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4062 // Unfortunately, System.Reflection.Emit automatically emits a leave
4063 // to the end of the finally block. This is a problem if `returns'
4064 // is true since we may jump to a point after the end of the method.
4065 // As a workaround, emit an explicit ret here.
4066 ec.NeedReturnLabel ();
4072 protected override void DoEmit (EmitContext ec)
4074 if (expression_or_block is DictionaryEntry)
4075 EmitLocalVariableDecls (ec);
4076 else if (expression_or_block is Expression)
4077 EmitExpression (ec);
4080 public override void EmitFinally (EmitContext ec)
4082 if (expression_or_block is DictionaryEntry)
4083 EmitLocalVariableDeclFinally (ec);
4084 else if (expression_or_block is Expression)
4085 EmitExpressionFinally (ec);
4090 /// Implementation of the foreach C# statement
4092 public class Foreach : Statement {
4094 Expression variable;
4096 Statement statement;
4098 CollectionForeach collection;
4100 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4101 Statement stmt, Location l)
4104 this.variable = var;
4110 public Statement Statement {
4111 get { return statement; }
4114 public override bool Resolve (EmitContext ec)
4116 expr = expr.Resolve (ec);
4120 if (expr is NullLiteral) {
4121 Report.Error (186, loc, "Use of null is not valid in this context");
4125 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4129 Type var_type = texpr.Type;
4131 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethod) {
4132 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4133 expr.ExprClassName);
4138 // We need an instance variable. Not sure this is the best
4139 // way of doing this.
4141 // FIXME: When we implement propertyaccess, will those turn
4142 // out to return values in ExprClass? I think they should.
4144 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4145 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4146 collection.Error_Enumerator ();
4150 if (expr.Type.IsArray) {
4151 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4152 return array.Resolve (ec);
4154 collection = new CollectionForeach (
4155 var_type, variable, expr, statement, loc);
4156 return collection.Resolve (ec);
4160 protected override void DoEmit (EmitContext ec)
4162 ILGenerator ig = ec.ig;
4164 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4165 ec.LoopBegin = ig.DefineLabel ();
4166 ec.LoopEnd = ig.DefineLabel ();
4168 if (collection != null)
4169 collection.Emit (ec);
4173 ec.LoopBegin = old_begin;
4174 ec.LoopEnd = old_end;
4177 protected class ArrayCounter : TemporaryVariable
4179 public ArrayCounter (Location loc)
4180 : base (TypeManager.int32_type, loc)
4183 public void Initialize (EmitContext ec)
4186 ec.ig.Emit (OpCodes.Ldc_I4_0);
4190 public void Increment (EmitContext ec)
4194 ec.ig.Emit (OpCodes.Ldc_I4_1);
4195 ec.ig.Emit (OpCodes.Add);
4200 protected class ArrayForeach : Statement
4202 Expression variable, expr, conv;
4203 Statement statement;
4206 TemporaryVariable[] lengths;
4207 ArrayCounter[] counter;
4210 TemporaryVariable copy;
4213 public ArrayForeach (Type var_type, Expression var,
4214 Expression expr, Statement stmt, Location l)
4216 this.var_type = var_type;
4217 this.variable = var;
4223 public override bool Resolve (EmitContext ec)
4225 array_type = expr.Type;
4226 rank = array_type.GetArrayRank ();
4228 copy = new TemporaryVariable (array_type, loc);
4231 counter = new ArrayCounter [rank];
4232 lengths = new TemporaryVariable [rank];
4234 ArrayList list = new ArrayList ();
4235 for (int i = 0; i < rank; i++) {
4236 counter [i] = new ArrayCounter (loc);
4237 counter [i].Resolve (ec);
4239 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4240 lengths [i].Resolve (ec);
4242 list.Add (counter [i]);
4245 access = new ElementAccess (copy, list).Resolve (ec);
4249 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4255 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4256 ec.CurrentBranching.CreateSibling ();
4258 variable = variable.ResolveLValue (ec, conv, loc);
4259 if (variable == null)
4262 if (!statement.Resolve (ec))
4265 ec.EndFlowBranching ();
4270 protected override void DoEmit (EmitContext ec)
4272 ILGenerator ig = ec.ig;
4274 copy.Store (ec, expr);
4276 Label[] test = new Label [rank];
4277 Label[] loop = new Label [rank];
4279 for (int i = 0; i < rank; i++) {
4280 test [i] = ig.DefineLabel ();
4281 loop [i] = ig.DefineLabel ();
4283 lengths [i].EmitThis (ec);
4284 ((ArrayAccess) access).EmitGetLength (ec, i);
4285 lengths [i].EmitStore (ig);
4288 for (int i = 0; i < rank; i++) {
4289 counter [i].Initialize (ec);
4291 ig.Emit (OpCodes.Br, test [i]);
4292 ig.MarkLabel (loop [i]);
4295 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4297 statement.Emit (ec);
4299 ig.MarkLabel (ec.LoopBegin);
4301 for (int i = rank - 1; i >= 0; i--){
4302 counter [i].Increment (ec);
4304 ig.MarkLabel (test [i]);
4305 counter [i].Emit (ec);
4306 lengths [i].Emit (ec);
4307 ig.Emit (OpCodes.Blt, loop [i]);
4310 ig.MarkLabel (ec.LoopEnd);
4314 protected class CollectionForeach : ExceptionStatement
4316 Expression variable, expr;
4317 Statement statement;
4319 TemporaryVariable enumerator;
4323 MethodGroupExpr get_enumerator;
4324 PropertyExpr get_current;
4325 MethodInfo move_next;
4326 Type var_type, enumerator_type;
4328 bool enumerator_found;
4330 public CollectionForeach (Type var_type, Expression var,
4331 Expression expr, Statement stmt, Location l)
4333 this.var_type = var_type;
4334 this.variable = var;
4340 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4342 Type return_type = mi.ReturnType;
4344 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4346 // Apply the same optimization as MS: skip the GetEnumerator
4347 // returning an IEnumerator, and use the one returning a
4348 // CharEnumerator instead. This allows us to avoid the
4349 // try-finally block and the boxing.
4354 // Ok, we can access it, now make sure that we can do something
4355 // with this `GetEnumerator'
4358 if (return_type == TypeManager.ienumerator_type ||
4359 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4360 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4362 // If it is not an interface, lets try to find the methods ourselves.
4363 // For example, if we have:
4364 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4365 // We can avoid the iface call. This is a runtime perf boost.
4366 // even bigger if we have a ValueType, because we avoid the cost
4369 // We have to make sure that both methods exist for us to take
4370 // this path. If one of the methods does not exist, we will just
4371 // use the interface. Sadly, this complex if statement is the only
4372 // way I could do this without a goto
4375 if (return_type.IsInterface && return_type.IsGenericType) {
4376 enumerator_type = return_type;
4377 if (!FetchGetCurrent (ec, return_type))
4378 get_current = new PropertyExpr (
4379 ec, TypeManager.ienumerator_getcurrent, loc);
4380 if (!FetchMoveNext (ec, return_type))
4381 move_next = TypeManager.bool_movenext_void;
4385 if (return_type.IsInterface ||
4386 !FetchMoveNext (ec, return_type) ||
4387 !FetchGetCurrent (ec, return_type)) {
4388 enumerator_type = return_type;
4389 move_next = TypeManager.bool_movenext_void;
4390 get_current = new PropertyExpr (
4391 ec, TypeManager.ienumerator_getcurrent, loc);
4396 // Ok, so they dont return an IEnumerable, we will have to
4397 // find if they support the GetEnumerator pattern.
4400 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (ec, return_type) || !FetchGetCurrent (ec, return_type)) {
4401 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",
4402 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
4407 enumerator_type = return_type;
4408 is_disposable = !enumerator_type.IsSealed ||
4409 TypeManager.ImplementsInterface (
4410 enumerator_type, TypeManager.idisposable_type);
4416 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4418 bool FetchMoveNext (EmitContext ec, Type t)
4420 MemberList move_next_list;
4422 move_next_list = TypeContainer.FindMembers (
4423 t, MemberTypes.Method,
4424 Expression.AllBindingFlags,
4425 Type.FilterName, "MoveNext");
4426 if (move_next_list.Count == 0)
4430 foreach (MemberInfo m in move_next_list){
4431 MethodInfo mi = (MethodInfo) m;
4434 args = TypeManager.GetArgumentTypes (mi);
4435 if ((args != null) && (args.Length == 0) &&
4436 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4448 // Retrieves a `public T get_Current ()' method from the Type `t'
4450 bool FetchGetCurrent (EmitContext ec, Type t)
4452 PropertyExpr pe = Expression.MemberLookup (
4453 ec, t, "Current", MemberTypes.Property,
4454 Expression.AllBindingFlags, loc) as PropertyExpr;
4463 // Retrieves a `public void Dispose ()' method from the Type `t'
4465 static MethodInfo FetchMethodDispose (Type t)
4467 MemberList dispose_list;
4469 dispose_list = TypeContainer.FindMembers (
4470 t, MemberTypes.Method,
4471 BindingFlags.Public | BindingFlags.Instance,
4472 Type.FilterName, "Dispose");
4473 if (dispose_list.Count == 0)
4476 foreach (MemberInfo m in dispose_list){
4477 MethodInfo mi = (MethodInfo) m;
4480 args = TypeManager.GetArgumentTypes (mi);
4481 if (args != null && args.Length == 0){
4482 if (mi.ReturnType == TypeManager.void_type)
4489 public void Error_Enumerator ()
4491 if (enumerator_found) {
4495 Report.Error (1579, loc,
4496 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4497 TypeManager.CSharpName (expr.Type));
4500 bool TryType (EmitContext ec, Type t)
4502 MethodGroupExpr mg = Expression.MemberLookup (
4503 ec, t, "GetEnumerator", MemberTypes.Method,
4504 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4508 MethodBase result = null;
4509 MethodInfo tmp_move_next = null;
4510 PropertyExpr tmp_get_cur = null;
4511 Type tmp_enumerator_type = enumerator_type;
4512 foreach (MethodInfo mi in mg.Methods) {
4513 Type [] args = TypeManager.GetArgumentTypes (mi);
4514 if (args != null && args.Length != 0)
4517 // Check whether GetEnumerator is public
4518 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4521 if (TypeManager.IsOverride (mi))
4524 enumerator_found = true;
4526 if (!GetEnumeratorFilter (ec, mi)) {
4531 tmp_move_next = move_next;
4532 tmp_get_cur = get_current;
4533 tmp_enumerator_type = enumerator_type;
4534 if (mi.DeclaringType == t)
4538 if (result != null) {
4539 move_next = tmp_move_next;
4540 get_current = tmp_get_cur;
4541 enumerator_type = tmp_enumerator_type;
4542 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
4543 get_enumerator = new MethodGroupExpr (mi, loc);
4545 if (t != expr.Type) {
4546 expr = Convert.ExplicitConversion (
4549 throw new InternalErrorException ();
4552 get_enumerator.InstanceExpression = expr;
4553 get_enumerator.IsBase = t != expr.Type;
4561 bool ProbeCollectionType (EmitContext ec, Type t)
4563 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4564 if (TryType (ec, tt))
4570 // Now try to find the method in the interfaces
4573 Type [] ifaces = t.GetInterfaces ();
4575 foreach (Type i in ifaces){
4576 if (TryType (ec, i))
4581 // Since TypeBuilder.GetInterfaces only returns the interface
4582 // types for this type, we have to keep looping, but once
4583 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4584 // done, because it returns all the types
4586 if ((t is TypeBuilder))
4595 public override bool Resolve (EmitContext ec)
4597 enumerator_type = TypeManager.ienumerator_type;
4598 is_disposable = true;
4600 if (!ProbeCollectionType (ec, expr.Type)) {
4601 Error_Enumerator ();
4605 enumerator = new TemporaryVariable (enumerator_type, loc);
4606 enumerator.Resolve (ec);
4608 init = new Invocation (get_enumerator, new ArrayList ());
4609 init = init.Resolve (ec);
4613 Expression move_next_expr;
4615 MemberInfo[] mi = new MemberInfo[] { move_next };
4616 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4617 mg.InstanceExpression = enumerator;
4619 move_next_expr = new Invocation (mg, new ArrayList ());
4622 get_current.InstanceExpression = enumerator;
4624 Statement block = new CollectionForeachStatement (
4625 var_type, variable, get_current, statement, loc);
4627 loop = new While (move_next_expr, block, loc);
4631 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4632 ec.CurrentBranching.CreateSibling ();
4634 FlowBranchingException branching = null;
4636 branching = ec.StartFlowBranching (this);
4638 if (!loop.Resolve (ec))
4641 if (is_disposable) {
4642 ResolveFinally (branching);
4643 ec.EndFlowBranching ();
4645 emit_finally = true;
4647 ec.EndFlowBranching ();
4652 protected override void DoEmit (EmitContext ec)
4654 ILGenerator ig = ec.ig;
4656 enumerator.Store (ec, init);
4659 // Protect the code in a try/finalize block, so that
4660 // if the beast implement IDisposable, we get rid of it
4662 if (is_disposable && emit_finally)
4663 ig.BeginExceptionBlock ();
4668 // Now the finally block
4670 if (is_disposable) {
4673 ig.EndExceptionBlock ();
4678 public override void EmitFinally (EmitContext ec)
4680 ILGenerator ig = ec.ig;
4682 if (enumerator_type.IsValueType) {
4683 enumerator.Emit (ec);
4685 MethodInfo mi = FetchMethodDispose (enumerator_type);
4687 enumerator.EmitLoadAddress (ec);
4688 ig.Emit (OpCodes.Call, mi);
4690 enumerator.Emit (ec);
4691 ig.Emit (OpCodes.Box, enumerator_type);
4692 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4695 Label call_dispose = ig.DefineLabel ();
4697 enumerator.Emit (ec);
4698 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4699 ig.Emit (OpCodes.Dup);
4700 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4701 ig.Emit (OpCodes.Pop);
4703 Label end_finally = ig.DefineLabel ();
4704 ig.Emit (OpCodes.Br, end_finally);
4706 ig.MarkLabel (call_dispose);
4707 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4708 ig.MarkLabel (end_finally);
4713 protected class CollectionForeachStatement : Statement
4716 Expression variable, current, conv;
4717 Statement statement;
4720 public CollectionForeachStatement (Type type, Expression variable,
4721 Expression current, Statement statement,
4725 this.variable = variable;
4726 this.current = current;
4727 this.statement = statement;
4731 public override bool Resolve (EmitContext ec)
4733 current = current.Resolve (ec);
4734 if (current == null)
4737 conv = Convert.ExplicitConversion (ec, current, type, loc);
4741 assign = new Assign (variable, conv, loc);
4742 if (assign.Resolve (ec) == null)
4745 if (!statement.Resolve (ec))
4751 protected override void DoEmit (EmitContext ec)
4753 assign.EmitStatement (ec);
4754 statement.Emit (ec);