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 ();
59 protected void CheckObsolete (Type type)
61 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
62 if (obsolete_attr == null)
65 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
69 /// Return value indicates whether all code paths emitted return.
71 protected abstract void DoEmit (EmitContext ec);
74 /// Utility wrapper routine for Error, just to beautify the code
76 public void Error (int error, string format, params object[] args)
78 Error (error, String.Format (format, args));
81 public void Error (int error, string s)
84 Report.Error (error, loc, s);
86 Report.Error (error, s);
90 /// Return value indicates whether all code paths emitted return.
92 public virtual void Emit (EmitContext ec)
99 public sealed class EmptyStatement : Statement {
101 private EmptyStatement () {}
103 public static readonly EmptyStatement Value = new EmptyStatement ();
105 public override bool Resolve (EmitContext ec)
110 protected override void DoEmit (EmitContext ec)
115 public class If : Statement {
117 public Statement TrueStatement;
118 public Statement FalseStatement;
122 public If (Expression expr, Statement trueStatement, Location l)
125 TrueStatement = trueStatement;
129 public If (Expression expr,
130 Statement trueStatement,
131 Statement falseStatement,
135 TrueStatement = trueStatement;
136 FalseStatement = falseStatement;
140 public override bool Resolve (EmitContext ec)
144 Report.Debug (1, "START IF BLOCK", loc);
146 expr = Expression.ResolveBoolean (ec, expr, loc);
152 Assign ass = expr as Assign;
153 if (ass != null && ass.Source is Constant) {
154 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
158 // Dead code elimination
160 if (expr is BoolConstant){
161 bool take = ((BoolConstant) expr).Value;
164 if (!TrueStatement.Resolve (ec))
167 if ((FalseStatement != null) &&
168 !FalseStatement.ResolveUnreachable (ec, true))
170 FalseStatement = null;
172 if (!TrueStatement.ResolveUnreachable (ec, true))
174 TrueStatement = null;
176 if ((FalseStatement != null) &&
177 !FalseStatement.Resolve (ec))
184 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
186 ok &= TrueStatement.Resolve (ec);
188 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
190 ec.CurrentBranching.CreateSibling ();
192 if (FalseStatement != null)
193 ok &= FalseStatement.Resolve (ec);
195 ec.EndFlowBranching ();
197 Report.Debug (1, "END IF BLOCK", loc);
202 protected override void DoEmit (EmitContext ec)
204 ILGenerator ig = ec.ig;
205 Label false_target = ig.DefineLabel ();
209 // If we're a boolean expression, Resolve() already
210 // eliminated dead code for us.
212 if (expr is BoolConstant){
213 bool take = ((BoolConstant) expr).Value;
216 TrueStatement.Emit (ec);
217 else if (FalseStatement != null)
218 FalseStatement.Emit (ec);
223 expr.EmitBranchable (ec, false_target, false);
225 TrueStatement.Emit (ec);
227 if (FalseStatement != null){
228 bool branch_emitted = false;
230 end = ig.DefineLabel ();
232 ig.Emit (OpCodes.Br, end);
233 branch_emitted = true;
236 ig.MarkLabel (false_target);
237 FalseStatement.Emit (ec);
242 ig.MarkLabel (false_target);
247 public class Do : Statement {
248 public Expression expr;
249 public readonly Statement EmbeddedStatement;
252 public Do (Statement statement, Expression boolExpr, Location l)
255 EmbeddedStatement = statement;
259 public override bool Resolve (EmitContext ec)
263 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
265 if (!EmbeddedStatement.Resolve (ec))
268 expr = Expression.ResolveBoolean (ec, expr, loc);
271 else if (expr is BoolConstant){
272 bool res = ((BoolConstant) expr).Value;
278 ec.CurrentBranching.Infinite = infinite;
279 ec.EndFlowBranching ();
284 protected override void DoEmit (EmitContext ec)
286 ILGenerator ig = ec.ig;
287 Label loop = ig.DefineLabel ();
288 Label old_begin = ec.LoopBegin;
289 Label old_end = ec.LoopEnd;
291 ec.LoopBegin = ig.DefineLabel ();
292 ec.LoopEnd = ig.DefineLabel ();
295 EmbeddedStatement.Emit (ec);
296 ig.MarkLabel (ec.LoopBegin);
299 // Dead code elimination
301 if (expr is BoolConstant){
302 bool res = ((BoolConstant) expr).Value;
305 ec.ig.Emit (OpCodes.Br, loop);
307 expr.EmitBranchable (ec, loop, true);
309 ig.MarkLabel (ec.LoopEnd);
311 ec.LoopBegin = old_begin;
312 ec.LoopEnd = old_end;
316 public class While : Statement {
317 public Expression expr;
318 public readonly Statement Statement;
319 bool infinite, empty;
321 public While (Expression boolExpr, Statement statement, Location l)
323 this.expr = boolExpr;
324 Statement = statement;
328 public override bool Resolve (EmitContext ec)
332 expr = Expression.ResolveBoolean (ec, expr, loc);
337 // Inform whether we are infinite or not
339 if (expr is BoolConstant){
340 BoolConstant bc = (BoolConstant) expr;
342 if (bc.Value == false){
343 if (!Statement.ResolveUnreachable (ec, true))
351 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
353 ec.CurrentBranching.CreateSibling ();
355 if (!Statement.Resolve (ec))
358 ec.CurrentBranching.Infinite = infinite;
359 ec.EndFlowBranching ();
364 protected override void DoEmit (EmitContext ec)
369 ILGenerator ig = ec.ig;
370 Label old_begin = ec.LoopBegin;
371 Label old_end = ec.LoopEnd;
373 ec.LoopBegin = ig.DefineLabel ();
374 ec.LoopEnd = ig.DefineLabel ();
377 // Inform whether we are infinite or not
379 if (expr is BoolConstant){
380 ig.MarkLabel (ec.LoopBegin);
382 ig.Emit (OpCodes.Br, ec.LoopBegin);
385 // Inform that we are infinite (ie, `we return'), only
386 // if we do not `break' inside the code.
388 ig.MarkLabel (ec.LoopEnd);
390 Label while_loop = ig.DefineLabel ();
392 ig.Emit (OpCodes.Br, ec.LoopBegin);
393 ig.MarkLabel (while_loop);
397 ig.MarkLabel (ec.LoopBegin);
399 expr.EmitBranchable (ec, while_loop, true);
401 ig.MarkLabel (ec.LoopEnd);
404 ec.LoopBegin = old_begin;
405 ec.LoopEnd = old_end;
409 public class For : Statement {
411 readonly Statement InitStatement;
412 readonly Statement Increment;
413 public readonly Statement Statement;
414 bool infinite, empty;
416 public For (Statement initStatement,
422 InitStatement = initStatement;
424 Increment = increment;
425 Statement = statement;
429 public override bool Resolve (EmitContext ec)
433 if (InitStatement != null){
434 if (!InitStatement.Resolve (ec))
439 Test = Expression.ResolveBoolean (ec, Test, loc);
442 else if (Test is BoolConstant){
443 BoolConstant bc = (BoolConstant) Test;
445 if (bc.Value == false){
446 if (!Statement.ResolveUnreachable (ec, true))
448 if ((Increment != null) &&
449 !Increment.ResolveUnreachable (ec, false))
459 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
461 ec.CurrentBranching.CreateSibling ();
463 if (!Statement.Resolve (ec))
466 if (Increment != null){
467 if (!Increment.Resolve (ec))
471 ec.CurrentBranching.Infinite = infinite;
472 ec.EndFlowBranching ();
477 protected override void DoEmit (EmitContext ec)
482 ILGenerator ig = ec.ig;
483 Label old_begin = ec.LoopBegin;
484 Label old_end = ec.LoopEnd;
485 Label loop = ig.DefineLabel ();
486 Label test = ig.DefineLabel ();
488 if (InitStatement != null && InitStatement != EmptyStatement.Value)
489 InitStatement.Emit (ec);
491 ec.LoopBegin = ig.DefineLabel ();
492 ec.LoopEnd = ig.DefineLabel ();
494 ig.Emit (OpCodes.Br, test);
498 ig.MarkLabel (ec.LoopBegin);
499 if (Increment != EmptyStatement.Value)
504 // If test is null, there is no test, and we are just
509 // The Resolve code already catches the case for
510 // Test == BoolConstant (false) so we know that
513 if (Test is BoolConstant)
514 ig.Emit (OpCodes.Br, loop);
516 Test.EmitBranchable (ec, loop, true);
519 ig.Emit (OpCodes.Br, loop);
520 ig.MarkLabel (ec.LoopEnd);
522 ec.LoopBegin = old_begin;
523 ec.LoopEnd = old_end;
527 public class StatementExpression : Statement {
528 ExpressionStatement expr;
530 public StatementExpression (ExpressionStatement expr)
536 public override bool Resolve (EmitContext ec)
539 expr = expr.ResolveStatement (ec);
543 protected override void DoEmit (EmitContext ec)
545 expr.EmitStatement (ec);
548 public override string ToString ()
550 return "StatementExpression (" + expr + ")";
555 /// Implements the return statement
557 public class Return : Statement {
558 public Expression Expr;
560 public Return (Expression expr, Location l)
568 public override bool Resolve (EmitContext ec)
570 AnonymousContainer am = ec.CurrentAnonymousMethod;
571 if ((am != null) && am.IsIterator && ec.InIterator) {
572 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
573 "statement to return a value, or yield break to end the iteration");
577 if (ec.ReturnType == null){
579 if (ec.CurrentAnonymousMethod != null){
580 Report.Error (1662, loc,
581 "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",
582 ec.CurrentAnonymousMethod.GetSignatureForError ());
584 Error (127, "A return keyword must not be followed by any expression when method returns void");
589 Error (126, "An object of a type convertible to `{0}' is required " +
590 "for the return statement",
591 TypeManager.CSharpName (ec.ReturnType));
595 Expr = Expr.Resolve (ec);
599 if (Expr.Type != ec.ReturnType) {
600 Expr = Convert.ImplicitConversionRequired (
601 ec, Expr, ec.ReturnType, loc);
607 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
609 if (ec.CurrentBranching.InTryOrCatch (true)) {
610 ec.CurrentBranching.AddFinallyVector (vector);
612 } else if (ec.InFinally) {
613 Error (157, "Control cannot leave the body of a finally clause");
616 vector.CheckOutParameters (ec.CurrentBranching);
619 ec.NeedReturnLabel ();
621 ec.CurrentBranching.CurrentUsageVector.Return ();
625 protected override void DoEmit (EmitContext ec)
631 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
635 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
637 ec.ig.Emit (OpCodes.Ret);
641 public class Goto : Statement {
643 LabeledStatement label;
645 public override bool Resolve (EmitContext ec)
647 label = ec.CurrentBranching.LookupLabel (target, loc);
651 // If this is a forward goto.
652 if (!label.IsDefined)
653 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
655 ec.CurrentBranching.CurrentUsageVector.Goto ();
656 label.AddReference ();
661 public Goto (string label, Location l)
667 public string Target {
673 protected override void DoEmit (EmitContext ec)
675 Label l = label.LabelTarget (ec);
676 ec.ig.Emit (OpCodes.Br, l);
680 public class LabeledStatement : Statement {
686 FlowBranching.UsageVector vectors;
688 public LabeledStatement (string label_name, Location l)
693 public Label LabelTarget (EmitContext ec)
698 label = ec.ig.DefineLabel ();
704 public bool IsDefined {
710 public bool HasBeenReferenced {
716 public void AddUsageVector (FlowBranching.UsageVector vector)
718 vector = vector.Clone ();
719 vector.Next = vectors;
723 public override bool Resolve (EmitContext ec)
725 ec.CurrentBranching.Label (vectors);
730 protected override void DoEmit (EmitContext ec)
732 if (ig != null && ig != ec.ig) {
733 // TODO: location is wrong
734 Report.Error (1632, loc, "Control cannot leave the body of an anonymous method");
738 ec.ig.MarkLabel (label);
741 public void AddReference ()
749 /// `goto default' statement
751 public class GotoDefault : Statement {
753 public GotoDefault (Location l)
758 public override bool Resolve (EmitContext ec)
760 ec.CurrentBranching.CurrentUsageVector.Goto ();
764 protected override void DoEmit (EmitContext ec)
766 if (ec.Switch == null){
767 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
771 if (!ec.Switch.GotDefault){
772 Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
775 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
780 /// `goto case' statement
782 public class GotoCase : Statement {
786 public GotoCase (Expression e, Location l)
792 public override bool Resolve (EmitContext ec)
794 if (ec.Switch == null){
795 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
799 expr = expr.Resolve (ec);
803 Constant c = expr as Constant;
805 Error (150, "A constant value is expected");
809 c = c.ToType (ec.Switch.SwitchType, loc);
813 object val = c.GetValue ();
817 sl = (SwitchLabel) ec.Switch.Elements [val];
820 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", c.GetValue () == null ? "null" : val);
824 ec.CurrentBranching.CurrentUsageVector.Goto ();
828 protected override void DoEmit (EmitContext ec)
830 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
834 public class Throw : Statement {
837 public Throw (Expression expr, Location l)
843 public override bool Resolve (EmitContext ec)
845 ec.CurrentBranching.CurrentUsageVector.Throw ();
848 expr = expr.Resolve (ec);
852 ExprClass eclass = expr.eclass;
854 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
855 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
856 expr.Error_UnexpectedKind (ec, "value, variable, property or indexer access ", loc);
862 if ((t != TypeManager.exception_type) &&
863 !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
864 !(expr is NullLiteral)) {
866 "The type caught or thrown must be derived " +
867 "from System.Exception");
874 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
879 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
885 protected override void DoEmit (EmitContext ec)
888 ec.ig.Emit (OpCodes.Rethrow);
892 ec.ig.Emit (OpCodes.Throw);
897 public class Break : Statement {
899 public Break (Location l)
906 public override bool Resolve (EmitContext ec)
908 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
909 Error (139, "No enclosing loop out of which to break or continue");
911 } else if (ec.InFinally && ec.CurrentBranching.BreakCrossesTryCatchBoundary()) {
912 Error (157, "Control cannot leave the body of a finally clause");
914 } else if (ec.CurrentBranching.InTryOrCatch (false))
915 ec.CurrentBranching.AddFinallyVector (
916 ec.CurrentBranching.CurrentUsageVector);
917 else if (ec.CurrentBranching.InLoop () || ec.CurrentBranching.InSwitch ())
918 ec.CurrentBranching.AddBreakVector (
919 ec.CurrentBranching.CurrentUsageVector);
921 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
924 ec.NeedReturnLabel ();
926 ec.CurrentBranching.CurrentUsageVector.Break ();
930 protected override void DoEmit (EmitContext ec)
932 ILGenerator ig = ec.ig;
935 ig.Emit (OpCodes.Leave, ec.LoopEnd);
937 ig.Emit (OpCodes.Br, ec.LoopEnd);
942 public class Continue : Statement {
944 public Continue (Location l)
951 public override bool Resolve (EmitContext ec)
953 if (!ec.CurrentBranching.InLoop ()){
954 Error (139, "No enclosing loop out of which to break or continue");
956 } else if (ec.InFinally) {
957 Error (157, "Control cannot leave the body of a finally clause");
959 } else if (ec.CurrentBranching.InTryOrCatch (false))
960 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
962 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
964 ec.CurrentBranching.CurrentUsageVector.Goto ();
968 protected override void DoEmit (EmitContext ec)
970 Label begin = ec.LoopBegin;
973 ec.ig.Emit (OpCodes.Leave, begin);
975 ec.ig.Emit (OpCodes.Br, begin);
980 // The information about a user-perceived local variable
982 public class LocalInfo {
983 public Expression Type;
986 // Most of the time a variable will be stored in a LocalBuilder
988 // But sometimes, it will be stored in a field (variables that have been
989 // hoisted by iterators or by anonymous methods). The context of the field will
990 // be stored in the EmitContext
993 public LocalBuilder LocalBuilder;
994 public FieldBuilder FieldBuilder;
996 public Type VariableType;
997 public readonly string Name;
998 public readonly Location Location;
999 public readonly Block Block;
1001 public VariableInfo VariableInfo;
1010 CompilerGenerated = 64
1013 public enum ReadOnlyContext: byte {
1020 ReadOnlyContext ro_context;
1022 public LocalInfo (Expression type, string name, Block block, Location l)
1030 public LocalInfo (TypeContainer tc, Block block, Location l)
1032 VariableType = tc.TypeBuilder;
1037 public bool IsThisAssigned (EmitContext ec, Location loc)
1039 if (VariableInfo == null)
1040 throw new Exception ();
1042 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1045 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1048 public bool IsAssigned (EmitContext ec)
1050 if (VariableInfo == null)
1051 throw new Exception ();
1053 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1056 public bool Resolve (EmitContext ec)
1058 if (VariableType == null) {
1059 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
1063 VariableType = texpr.Type;
1066 if (VariableType == TypeManager.void_type) {
1067 Report.Error (1547, Location,
1068 "Keyword 'void' cannot be used in this context");
1072 if (VariableType.IsAbstract && VariableType.IsSealed) {
1073 Report.Error (723, Location, "Cannot declare variable of static type `{0}'", TypeManager.CSharpName (VariableType));
1077 if (VariableType.IsPointer && !ec.InUnsafe)
1078 Expression.UnsafeError (Location);
1083 public bool IsCaptured {
1085 return (flags & Flags.Captured) != 0;
1089 flags |= Flags.Captured;
1093 public bool AddressTaken {
1095 return (flags & Flags.AddressTaken) != 0;
1099 flags |= Flags.AddressTaken;
1103 public bool CompilerGenerated {
1105 return (flags & Flags.CompilerGenerated) != 0;
1109 flags |= Flags.CompilerGenerated;
1113 public override string ToString ()
1115 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1116 Name, Type, VariableInfo, Location);
1121 return (flags & Flags.Used) != 0;
1124 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1128 public bool ReadOnly {
1130 return (flags & Flags.ReadOnly) != 0;
1134 public void SetReadOnlyContext (ReadOnlyContext context)
1136 flags |= Flags.ReadOnly;
1137 ro_context = context;
1140 public string GetReadOnlyContext ()
1143 throw new InternalErrorException ("Variable is not readonly");
1145 switch (ro_context) {
1146 case ReadOnlyContext.Fixed:
1147 return "fixed variable";
1148 case ReadOnlyContext.Foreach:
1149 return "foreach iteration variable";
1150 case ReadOnlyContext.Using:
1151 return "using variable";
1153 throw new NotImplementedException ();
1157 // Whether the variable is pinned, if Pinned the variable has been
1158 // allocated in a pinned slot with DeclareLocal.
1160 public bool Pinned {
1162 return (flags & Flags.Pinned) != 0;
1165 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1169 public bool IsThis {
1171 return (flags & Flags.IsThis) != 0;
1174 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1180 /// Block represents a C# block.
1184 /// This class is used in a number of places: either to represent
1185 /// explicit blocks that the programmer places or implicit blocks.
1187 /// Implicit blocks are used as labels or to introduce variable
1190 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1191 /// they contain extra information that is not necessary on normal blocks.
1193 public class Block : Statement {
1194 public Block Parent;
1195 public readonly Location StartLocation;
1196 public Location EndLocation = Location.Null;
1198 public readonly ToplevelBlock Toplevel;
1201 public enum Flags : ushort {
1205 VariablesInitialized = 8,
1210 HasVarargs = 256 // Used in ToplevelBlock
1212 protected Flags flags;
1214 public bool Implicit {
1215 get { return (flags & Flags.Implicit) != 0; }
1218 public bool Unchecked {
1219 get { return (flags & Flags.Unchecked) != 0; }
1220 set { flags |= Flags.Unchecked; }
1223 public bool Unsafe {
1224 get { return (flags & Flags.Unsafe) != 0; }
1225 set { flags |= Flags.Unsafe; }
1229 // The statements in this block
1231 ArrayList statements;
1235 // An array of Blocks. We keep track of children just
1236 // to generate the local variable declarations.
1238 // Statements and child statements are handled through the
1244 // Labels. (label, block) pairs.
1249 // Keeps track of (name, type) pairs
1251 Hashtable variables;
1254 // Keeps track of constants
1255 Hashtable constants;
1258 // Temporary variables.
1260 ArrayList temporary_variables;
1263 // If this is a switch section, the enclosing switch block.
1267 protected static int id;
1271 public Block (Block parent)
1272 : this (parent, (Flags) 0, Location.Null, Location.Null)
1275 public Block (Block parent, Flags flags)
1276 : this (parent, flags, Location.Null, Location.Null)
1279 public Block (Block parent, Location start, Location end)
1280 : this (parent, (Flags) 0, start, end)
1283 public Block (Block parent, Flags flags, Location start, Location end)
1286 parent.AddChild (this);
1288 this.Parent = parent;
1290 this.StartLocation = start;
1291 this.EndLocation = end;
1294 statements = new ArrayList ();
1296 if ((flags & Flags.IsToplevel) != 0)
1297 Toplevel = (ToplevelBlock) this;
1299 Toplevel = parent.Toplevel;
1301 if (parent != null && Implicit) {
1302 if (parent.known_variables == null)
1303 parent.known_variables = new Hashtable ();
1304 // share with parent
1305 known_variables = parent.known_variables;
1310 public Block CreateSwitchBlock (Location start)
1312 Block new_block = new Block (this, start, start);
1313 new_block.switch_block = this;
1318 get { return this_id; }
1321 protected Hashtable Variables {
1323 if (variables == null)
1324 variables = new Hashtable ();
1329 void AddChild (Block b)
1331 if (children == null)
1332 children = new ArrayList ();
1337 public void SetEndLocation (Location loc)
1343 /// Adds a label to the current block.
1347 /// false if the name already exists in this block. true
1351 public bool AddLabel (string name, LabeledStatement target, Location loc)
1353 if (switch_block != null)
1354 return switch_block.AddLabel (name, target, loc);
1357 while (cur != null) {
1358 if (cur.DoLookupLabel (name) != null) {
1360 140, loc, "The label `{0}' is a duplicate",
1371 while (cur != null) {
1372 if (cur.DoLookupLabel (name) != null) {
1375 "The label `{0}' shadows another label " +
1376 "by the same name in a contained scope.",
1381 if (children != null) {
1382 foreach (Block b in children) {
1383 LabeledStatement s = b.DoLookupLabel (name);
1389 "The label `{0}' shadows another " +
1390 "label by the same name in a " +
1402 labels = new Hashtable ();
1404 labels.Add (name, target);
1408 public LabeledStatement LookupLabel (string name)
1410 LabeledStatement s = DoLookupLabel (name);
1414 if (children == null)
1417 foreach (Block child in children) {
1418 if (!child.Implicit)
1421 s = child.LookupLabel (name);
1429 LabeledStatement DoLookupLabel (string name)
1431 if (switch_block != null)
1432 return switch_block.LookupLabel (name);
1435 if (labels.Contains (name))
1436 return ((LabeledStatement) labels [name]);
1441 Hashtable known_variables;
1444 // Marks a variable with name @name as being used in this or a child block.
1445 // If a variable name has been used in a child block, it's illegal to
1446 // declare a variable with the same name in the current block.
1448 void AddKnownVariable (string name, LocalInfo info)
1450 if (known_variables == null)
1451 known_variables = new Hashtable ();
1453 known_variables [name] = info;
1456 LocalInfo GetKnownVariableInfo (string name)
1458 if (known_variables == null)
1460 return (LocalInfo) known_variables [name];
1463 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1466 LocalInfo kvi = b.GetKnownVariableInfo (name);
1467 while (kvi == null) {
1473 kvi = b.GetKnownVariableInfo (name);
1479 // Is kvi.Block nested inside 'b'
1480 if (b.known_variables != kvi.Block.known_variables) {
1482 // If a variable by the same name it defined in a nested block of this
1483 // block, we violate the invariant meaning in a block.
1486 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1487 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1492 // It's ok if the definition is in a nested subblock of b, but not
1493 // nested inside this block -- a definition in a sibling block
1494 // should not affect us.
1500 // Block 'b' and kvi.Block are the same textual block.
1501 // However, different variables are extant.
1503 // Check if the variable is in scope in both blocks. We use
1504 // an indirect check that depends on AddVariable doing its
1505 // part in maintaining the invariant-meaning-in-block property.
1507 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1511 // Even though we detected the error when the name is used, we
1512 // treat it as if the variable declaration was in error.
1514 Report.SymbolRelatedToPreviousError (loc, name);
1515 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1519 public LocalInfo AddVariable (Expression type, string name, Location l)
1521 LocalInfo vi = GetLocalInfo (name);
1523 Report.SymbolRelatedToPreviousError (vi.Location, name);
1524 if (known_variables == vi.Block.known_variables)
1525 Report.Error (128, l,
1526 "A local variable named `{0}' is already defined in this scope", name);
1528 Error_AlreadyDeclared (l, name, "parent");
1532 vi = GetKnownVariableInfo (name);
1534 Report.SymbolRelatedToPreviousError (vi.Location, name);
1535 Error_AlreadyDeclared (l, name, "child");
1540 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1542 Report.SymbolRelatedToPreviousError (p.Location, name);
1543 Error_AlreadyDeclared (l, name, "method argument");
1547 vi = new LocalInfo (type, name, this, l);
1549 Variables.Add (name, vi);
1551 for (Block b = this; b != null; b = b.Parent)
1552 b.AddKnownVariable (name, vi);
1554 if ((flags & Flags.VariablesInitialized) != 0)
1555 throw new Exception ();
1560 void Error_AlreadyDeclared (Location loc, string var, string reason)
1562 Report.Error (136, loc, "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning to `{0}', " +
1563 "which is already used in a `{1}' scope", var, reason);
1566 public bool AddConstant (Expression type, string name, Expression value, Location l)
1568 if (AddVariable (type, name, l) == null)
1571 if (constants == null)
1572 constants = new Hashtable ();
1574 constants.Add (name, value);
1578 static int next_temp_id = 0;
1580 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1582 if (temporary_variables == null)
1583 temporary_variables = new ArrayList ();
1585 int id = ++next_temp_id;
1586 string name = "$s_" + id.ToString ();
1588 LocalInfo li = new LocalInfo (te, name, this, loc);
1589 li.CompilerGenerated = true;
1590 temporary_variables.Add (li);
1594 public LocalInfo GetLocalInfo (string name)
1596 for (Block b = this; b != null; b = b.Parent) {
1597 if (b.variables != null) {
1598 LocalInfo ret = b.variables [name] as LocalInfo;
1606 public Expression GetVariableType (string name)
1608 LocalInfo vi = GetLocalInfo (name);
1609 return vi == null ? null : vi.Type;
1612 public Expression GetConstantExpression (string name)
1614 for (Block b = this; b != null; b = b.Parent) {
1615 if (b.constants != null) {
1616 Expression ret = b.constants [name] as Expression;
1625 /// True if the variable named @name is a constant
1627 public bool IsConstant (string name)
1629 Expression e = GetConstantExpression (name);
1633 public void AddStatement (Statement s)
1636 flags |= Flags.BlockUsed;
1640 get { return (flags & Flags.BlockUsed) != 0; }
1645 flags |= Flags.BlockUsed;
1648 public bool HasRet {
1649 get { return (flags & Flags.HasRet) != 0; }
1652 public bool IsDestructor {
1653 get { return (flags & Flags.IsDestructor) != 0; }
1656 public void SetDestructor ()
1658 flags |= Flags.IsDestructor;
1661 VariableMap param_map, local_map;
1663 public VariableMap ParameterMap {
1665 if ((flags & Flags.VariablesInitialized) == 0)
1666 throw new Exception ("Variables have not been initialized yet");
1672 public VariableMap LocalMap {
1674 if ((flags & Flags.VariablesInitialized) == 0)
1675 throw new Exception ("Variables have not been initialized yet");
1682 /// Emits the variable declarations and labels.
1685 /// tc: is our typecontainer (to resolve type references)
1686 /// ig: is the code generator:
1688 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1690 bool old_unsafe = ec.InUnsafe;
1692 // If some parent block was unsafe, we remain unsafe even if this block
1693 // isn't explicitly marked as such.
1694 ec.InUnsafe |= Unsafe;
1697 // Compute the VariableMap's.
1699 // Unfortunately, we don't know the type when adding variables with
1700 // AddVariable(), so we need to compute this info here.
1704 if (variables != null) {
1705 foreach (LocalInfo li in variables.Values)
1708 locals = new LocalInfo [variables.Count];
1709 variables.Values.CopyTo (locals, 0);
1711 locals = new LocalInfo [0];
1714 local_map = new VariableMap (Parent.LocalMap, locals);
1716 local_map = new VariableMap (locals);
1718 param_map = new VariableMap (ip);
1719 flags |= Flags.VariablesInitialized;
1721 bool old_check_state = ec.ConstantCheckState;
1722 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1725 // Process this block variables
1727 if (variables != null){
1728 foreach (DictionaryEntry de in variables){
1729 string name = (string) de.Key;
1730 LocalInfo vi = (LocalInfo) de.Value;
1732 if (vi.VariableType == null)
1735 Type variable_type = vi.VariableType;
1737 if (variable_type.IsPointer){
1739 // Am not really convinced that this test is required (Microsoft does it)
1740 // but the fact is that you would not be able to use the pointer variable
1743 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1748 if (constants == null)
1751 Expression cv = (Expression) constants [name];
1755 ec.CurrentBlock = this;
1756 Expression e = cv.Resolve (ec);
1758 Constant ce = e as Constant;
1760 Const.Error_ExpressionMustBeConstant (vi.Location, name);
1764 e = ce.ToType (variable_type, vi.Location);
1768 constants.Remove (name);
1769 constants.Add (name, e);
1772 ec.ConstantCheckState = old_check_state;
1775 // Now, handle the children
1777 if (children != null){
1778 foreach (Block b in children)
1779 b.ResolveMeta (toplevel, ec, ip);
1781 ec.InUnsafe = old_unsafe;
1785 // Emits the local variable declarations for a block
1787 public void EmitMeta (EmitContext ec)
1789 ILGenerator ig = ec.ig;
1791 if (variables != null){
1792 bool have_captured_vars = ec.HaveCapturedVariables ();
1794 foreach (DictionaryEntry de in variables){
1795 LocalInfo vi = (LocalInfo) de.Value;
1797 if (have_captured_vars && ec.IsCaptured (vi))
1802 // This is needed to compile on both .NET 1.x and .NET 2.x
1803 // the later introduced `DeclareLocal (Type t, bool pinned)'
1805 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1806 else if (!vi.IsThis)
1807 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1811 if (temporary_variables != null) {
1812 AnonymousContainer am = ec.CurrentAnonymousMethod;
1813 TypeBuilder scope = null;
1814 if ((am != null) && am.IsIterator) {
1815 scope = am.Scope.ScopeTypeBuilder;
1817 throw new InternalErrorException ();
1819 foreach (LocalInfo vi in temporary_variables) {
1820 if (scope != null) {
1821 if (vi.FieldBuilder == null)
1822 vi.FieldBuilder = scope.DefineField (
1823 vi.Name, vi.VariableType, FieldAttributes.Assembly);
1825 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1829 if (children != null){
1830 foreach (Block b in children)
1835 void UsageWarning (FlowBranching.UsageVector vector)
1839 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1840 foreach (DictionaryEntry de in variables){
1841 LocalInfo vi = (LocalInfo) de.Value;
1846 name = (string) de.Key;
1848 if (vector.IsAssigned (vi.VariableInfo)){
1849 Report.Warning (219, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
1851 Report.Warning (168, vi.Location, "The variable `{0}' is declared but never used", name);
1857 bool unreachable_shown;
1860 private void CheckPossibleMistakenEmptyStatement (Statement s)
1864 // Some statements are wrapped by a Block. Since
1865 // others' internal could be changed, here I treat
1866 // them as possibly wrapped by Block equally.
1867 Block b = s as Block;
1868 if (b != null && b.statements.Count == 1)
1869 s = (Statement) b.statements [0];
1872 body = ((Lock) s).Statement;
1874 body = ((For) s).Statement;
1875 else if (s is Foreach)
1876 body = ((Foreach) s).Statement;
1877 else if (s is While)
1878 body = ((While) s).Statement;
1879 else if (s is Using)
1880 body = ((Using) s).Statement;
1881 else if (s is Fixed)
1882 body = ((Fixed) s).Statement;
1886 if (body == null || body is EmptyStatement)
1887 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
1890 public override bool Resolve (EmitContext ec)
1892 Block prev_block = ec.CurrentBlock;
1895 int errors = Report.Errors;
1897 ec.CurrentBlock = this;
1898 ec.StartFlowBranching (this);
1900 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1903 // This flag is used to notate nested statements as unreachable from the beginning of this block.
1904 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
1905 // from the beginning of the function. The outer Resolve() that detected the unreachability is
1906 // responsible for handling the situation.
1908 int statement_count = statements.Count;
1909 for (int ix = 0; ix < statement_count; ix++){
1910 Statement s = (Statement) statements [ix];
1911 // Check possible empty statement (CS0642)
1912 if (RootContext.WarningLevel >= 3 &&
1913 ix + 1 < statement_count &&
1914 statements [ix + 1] is Block)
1915 CheckPossibleMistakenEmptyStatement (s);
1919 ((Block) s).unreachable = true;
1921 if (!unreachable_shown && (RootContext.WarningLevel >= 2)) {
1923 162, loc, "Unreachable code detected");
1924 unreachable_shown = true;
1928 if (!s.Resolve (ec)) {
1930 statements [ix] = EmptyStatement.Value;
1934 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1935 statements [ix] = EmptyStatement.Value;
1937 num_statements = ix + 1;
1938 if (s is LabeledStatement)
1939 unreachable = false;
1941 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1944 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1945 ec.CurrentBranching, statement_count, num_statements);
1947 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1949 ec.CurrentBlock = prev_block;
1951 // If we're a non-static `struct' constructor which doesn't have an
1952 // initializer, then we must initialize all of the struct's fields.
1953 if ((flags & Flags.IsToplevel) != 0 &&
1954 !Toplevel.IsThisAssigned (ec) &&
1955 vector.Reachability.Throws != FlowBranching.FlowReturns.Always)
1958 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1959 foreach (LabeledStatement label in labels.Values)
1960 if (!label.HasBeenReferenced)
1961 Report.Warning (164, label.loc,
1962 "This label has not been referenced");
1965 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1967 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1968 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1969 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1970 flags |= Flags.HasRet;
1972 if (ok && (errors == Report.Errors)) {
1973 if (RootContext.WarningLevel >= 3)
1974 UsageWarning (vector);
1980 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1982 unreachable_shown = true;
1985 if (warn && (RootContext.WarningLevel >= 2))
1986 Report.Warning (162, loc, "Unreachable code detected");
1988 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1989 bool ok = Resolve (ec);
1990 ec.KillFlowBranching ();
1995 protected override void DoEmit (EmitContext ec)
1997 for (int ix = 0; ix < num_statements; ix++){
1998 Statement s = (Statement) statements [ix];
2000 // Check whether we are the last statement in a
2003 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2004 ec.IsLastStatement = true;
2006 ec.IsLastStatement = false;
2012 public override void Emit (EmitContext ec)
2014 Block prev_block = ec.CurrentBlock;
2016 ec.CurrentBlock = this;
2018 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2019 bool is_lexical_block = !Implicit && (Parent != null);
2021 if (emit_debug_info) {
2022 if (is_lexical_block)
2025 if (variables != null) {
2026 foreach (DictionaryEntry de in variables) {
2027 string name = (string) de.Key;
2028 LocalInfo vi = (LocalInfo) de.Value;
2030 if (vi.LocalBuilder == null)
2033 ec.DefineLocalVariable (name, vi.LocalBuilder);
2038 ec.Mark (StartLocation, true);
2040 ec.Mark (EndLocation, true);
2042 if (emit_debug_info && is_lexical_block)
2045 ec.CurrentBlock = prev_block;
2049 // Returns true if we ar ea child of `b'.
2051 public bool IsChildOf (Block b)
2053 Block current = this;
2056 if (current.Parent == b)
2058 current = current.Parent;
2059 } while (current != null);
2063 public override string ToString ()
2065 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2070 // A toplevel block contains extra information, the split is done
2071 // only to separate information that would otherwise bloat the more
2072 // lightweight Block.
2074 // In particular, this was introduced when the support for Anonymous
2075 // Methods was implemented.
2077 public class ToplevelBlock : Block {
2079 // Pointer to the host of this anonymous method, or null
2080 // if we are the topmost block
2082 ToplevelBlock container;
2083 CaptureContext capture_context;
2084 FlowBranching top_level_branching;
2086 Hashtable capture_contexts;
2089 public bool HasVarargs {
2090 get { return (flags & Flags.HasVarargs) != 0; }
2091 set { flags |= Flags.HasVarargs; }
2095 // The parameters for the block.
2097 Parameters parameters;
2098 public Parameters Parameters {
2099 get { return parameters; }
2102 public void RegisterCaptureContext (CaptureContext cc)
2104 if (capture_contexts == null)
2105 capture_contexts = new Hashtable ();
2106 capture_contexts [cc] = cc;
2109 public void CompleteContexts ()
2111 if (capture_contexts == null)
2114 foreach (CaptureContext cc in capture_contexts.Keys){
2119 public CaptureContext ToplevelBlockCaptureContext {
2120 get { return capture_context; }
2123 public ToplevelBlock Container {
2124 get { return container; }
2127 protected void AddChild (ToplevelBlock block)
2129 if (children == null)
2130 children = new ArrayList ();
2132 children.Add (block);
2136 // Parent is only used by anonymous blocks to link back to their
2139 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2140 this (container, (Flags) 0, parameters, start)
2144 public ToplevelBlock (Parameters parameters, Location start) :
2145 this (null, (Flags) 0, parameters, start)
2149 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2150 this (null, flags, parameters, start)
2154 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2155 base (null, flags | Flags.IsToplevel, start, Location.Null)
2157 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2158 this.container = container;
2160 if (container != null)
2161 container.AddChild (this);
2164 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2168 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2170 if (capture_context == null)
2171 capture_context = new CaptureContext (this, loc, host);
2174 public CaptureContext CaptureContext {
2175 get { return capture_context; }
2178 public FlowBranching TopLevelBranching {
2179 get { return top_level_branching; }
2183 // This is used if anonymous methods are used inside an iterator
2184 // (see 2test-22.cs for an example).
2186 // The AnonymousMethod is created while parsing - at a time when we don't
2187 // know yet that we're inside an iterator, so it's `Container' is initially
2188 // null. Later on, when resolving the iterator, we need to move the
2189 // anonymous method into that iterator.
2191 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2193 foreach (ToplevelBlock block in children) {
2194 if (block.CaptureContext == null)
2197 block.container = new_parent;
2198 block.CaptureContext.ReParent (new_parent, new_host);
2203 // Returns a `ParameterReference' for the given name, or null if there
2204 // is no such parameter
2206 public ParameterReference GetParameterReference (string name, Location loc)
2211 for (ToplevelBlock t = this; t != null; t = t.Container) {
2212 Parameters pars = t.Parameters;
2213 par = pars.GetParameterByName (name, out idx);
2215 return new ParameterReference (pars, this, idx, name, loc);
2221 // Whether the parameter named `name' is local to this block,
2222 // or false, if the parameter belongs to an encompassing block.
2224 public bool IsLocalParameter (string name)
2226 return Parameters.GetParameterByName (name) != null;
2230 // Whether the `name' is a parameter reference
2232 public bool IsParameterReference (string name)
2234 for (ToplevelBlock t = this; t != null; t = t.Container) {
2235 if (t.IsLocalParameter (name))
2241 LocalInfo this_variable = null;
2244 // Returns the "this" instance variable of this block.
2245 // See AddThisVariable() for more information.
2247 public LocalInfo ThisVariable {
2248 get { return this_variable; }
2253 // This is used by non-static `struct' constructors which do not have an
2254 // initializer - in this case, the constructor must initialize all of the
2255 // struct's fields. To do this, we add a "this" variable and use the flow
2256 // analysis code to ensure that it's been fully initialized before control
2257 // leaves the constructor.
2259 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
2261 if (this_variable == null) {
2262 this_variable = new LocalInfo (tc, this, l);
2263 this_variable.Used = true;
2264 this_variable.IsThis = true;
2266 Variables.Add ("this", this_variable);
2269 return this_variable;
2272 public bool IsThisAssigned (EmitContext ec)
2274 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2277 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2279 int errors = Report.Errors;
2281 if (top_level_branching != null)
2285 parameters = ip.Parameters;
2287 ResolveMeta (this, ec, ip);
2289 top_level_branching = ec.StartFlowBranching (this);
2291 return Report.Errors == errors;
2295 public class SwitchLabel {
2302 Label il_label_code;
2303 bool il_label_code_set;
2306 // if expr == null, then it is the default case.
2308 public SwitchLabel (Expression expr, Location l)
2314 public Expression Label {
2320 public object Converted {
2326 public Label GetILLabel (EmitContext ec)
2329 il_label = ec.ig.DefineLabel ();
2330 il_label_set = true;
2335 public Label GetILLabelCode (EmitContext ec)
2337 if (!il_label_code_set){
2338 il_label_code = ec.ig.DefineLabel ();
2339 il_label_code_set = true;
2341 return il_label_code;
2345 // Resolves the expression, reduces it to a literal if possible
2346 // and then converts it to the requested type.
2348 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2350 Expression e = label.Resolve (ec);
2355 Constant c = e as Constant;
2357 Report.Error (150, loc, "A constant value is expected");
2361 if (required_type == TypeManager.string_type && e is NullLiteral) {
2366 c = c.ToType (required_type, loc);
2370 converted = c.GetValue ();
2374 public void Erorr_AlreadyOccurs ()
2377 if (converted == null)
2379 else if (converted is NullLiteral)
2382 label = converted.ToString ();
2384 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2388 public class SwitchSection {
2389 // An array of SwitchLabels.
2390 public readonly ArrayList Labels;
2391 public readonly Block Block;
2393 public SwitchSection (ArrayList labels, Block block)
2400 public class Switch : Statement {
2401 public readonly ArrayList Sections;
2402 public Expression Expr;
2405 /// Maps constants whose type type SwitchType to their SwitchLabels.
2407 public IDictionary Elements;
2410 /// The governing switch type
2412 public Type SwitchType;
2417 Label default_target;
2418 Expression new_expr;
2420 SwitchSection constant_section;
2421 SwitchSection default_section;
2424 // The types allowed to be implicitly cast from
2425 // on the governing type
2427 static Type [] allowed_types;
2429 public Switch (Expression e, ArrayList sects, Location l)
2436 public bool GotDefault {
2438 return default_section != null;
2442 public Label DefaultTarget {
2444 return default_target;
2449 // Determines the governing type for a switch. The returned
2450 // expression might be the expression from the switch, or an
2451 // expression that includes any potential conversions to the
2452 // integral types or to string.
2454 Expression SwitchGoverningType (EmitContext ec, Type t)
2456 if (t == TypeManager.byte_type ||
2457 t == TypeManager.sbyte_type ||
2458 t == TypeManager.ushort_type ||
2459 t == TypeManager.short_type ||
2460 t == TypeManager.uint32_type ||
2461 t == TypeManager.int32_type ||
2462 t == TypeManager.uint64_type ||
2463 t == TypeManager.int64_type ||
2464 t == TypeManager.char_type ||
2465 t == TypeManager.string_type ||
2466 t == TypeManager.bool_type ||
2467 t.IsSubclassOf (TypeManager.enum_type))
2470 if (allowed_types == null){
2471 allowed_types = new Type [] {
2472 TypeManager.sbyte_type,
2473 TypeManager.byte_type,
2474 TypeManager.short_type,
2475 TypeManager.ushort_type,
2476 TypeManager.int32_type,
2477 TypeManager.uint32_type,
2478 TypeManager.int64_type,
2479 TypeManager.uint64_type,
2480 TypeManager.char_type,
2481 TypeManager.string_type,
2482 TypeManager.bool_type
2487 // Try to find a *user* defined implicit conversion.
2489 // If there is no implicit conversion, or if there are multiple
2490 // conversions, we have to report an error
2492 Expression converted = null;
2493 foreach (Type tt in allowed_types){
2496 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2501 // Ignore over-worked ImplicitUserConversions that do
2502 // an implicit conversion in addition to the user conversion.
2504 if (!(e is UserCast))
2507 if (converted != null){
2508 Report.ExtraInformation (
2510 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2511 TypeManager.CSharpName (Expr.Type)));
2521 // Performs the basic sanity checks on the switch statement
2522 // (looks for duplicate keys and non-constant expressions).
2524 // It also returns a hashtable with the keys that we will later
2525 // use to compute the switch tables
2527 bool CheckSwitch (EmitContext ec)
2530 Elements = Sections.Count > 10 ?
2531 (IDictionary)new Hashtable () :
2532 (IDictionary)new ListDictionary ();
2534 foreach (SwitchSection ss in Sections){
2535 foreach (SwitchLabel sl in ss.Labels){
2536 if (sl.Label == null){
2537 if (default_section != null){
2538 sl.Erorr_AlreadyOccurs ();
2541 default_section = ss;
2545 if (!sl.ResolveAndReduce (ec, SwitchType)){
2550 object key = sl.Converted;
2552 Elements.Add (key, sl);
2554 catch (ArgumentException) {
2555 sl.Erorr_AlreadyOccurs ();
2563 void EmitObjectInteger (ILGenerator ig, object k)
2566 IntConstant.EmitInt (ig, (int) k);
2567 else if (k is Constant) {
2568 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2571 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2574 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2576 IntConstant.EmitInt (ig, (int) (long) k);
2577 ig.Emit (OpCodes.Conv_I8);
2580 LongConstant.EmitLong (ig, (long) k);
2582 else if (k is ulong)
2584 if ((ulong) k < (1L<<32))
2586 IntConstant.EmitInt (ig, (int) (long) k);
2587 ig.Emit (OpCodes.Conv_U8);
2591 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2595 IntConstant.EmitInt (ig, (int) ((char) k));
2596 else if (k is sbyte)
2597 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2599 IntConstant.EmitInt (ig, (int) ((byte) k));
2600 else if (k is short)
2601 IntConstant.EmitInt (ig, (int) ((short) k));
2602 else if (k is ushort)
2603 IntConstant.EmitInt (ig, (int) ((ushort) k));
2605 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2607 throw new Exception ("Unhandled case");
2610 // structure used to hold blocks of keys while calculating table switch
2611 class KeyBlock : IComparable
2613 public KeyBlock (long _nFirst)
2615 nFirst = nLast = _nFirst;
2619 public ArrayList rgKeys = null;
2620 // how many items are in the bucket
2621 public int Size = 1;
2624 get { return (int) (nLast - nFirst + 1); }
2626 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2628 return kbLast.nLast - kbFirst.nFirst + 1;
2630 public int CompareTo (object obj)
2632 KeyBlock kb = (KeyBlock) obj;
2633 int nLength = Length;
2634 int nLengthOther = kb.Length;
2635 if (nLengthOther == nLength)
2636 return (int) (kb.nFirst - nFirst);
2637 return nLength - nLengthOther;
2642 /// This method emits code for a lookup-based switch statement (non-string)
2643 /// Basically it groups the cases into blocks that are at least half full,
2644 /// and then spits out individual lookup opcodes for each block.
2645 /// It emits the longest blocks first, and short blocks are just
2646 /// handled with direct compares.
2648 /// <param name="ec"></param>
2649 /// <param name="val"></param>
2650 /// <returns></returns>
2651 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2653 int cElements = Elements.Count;
2654 object [] rgKeys = new object [cElements];
2655 Elements.Keys.CopyTo (rgKeys, 0);
2656 Array.Sort (rgKeys);
2658 // initialize the block list with one element per key
2659 ArrayList rgKeyBlocks = new ArrayList ();
2660 foreach (object key in rgKeys)
2661 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2664 // iteratively merge the blocks while they are at least half full
2665 // there's probably a really cool way to do this with a tree...
2666 while (rgKeyBlocks.Count > 1)
2668 ArrayList rgKeyBlocksNew = new ArrayList ();
2669 kbCurr = (KeyBlock) rgKeyBlocks [0];
2670 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2672 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2673 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2676 kbCurr.nLast = kb.nLast;
2677 kbCurr.Size += kb.Size;
2681 // start a new block
2682 rgKeyBlocksNew.Add (kbCurr);
2686 rgKeyBlocksNew.Add (kbCurr);
2687 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2689 rgKeyBlocks = rgKeyBlocksNew;
2692 // initialize the key lists
2693 foreach (KeyBlock kb in rgKeyBlocks)
2694 kb.rgKeys = new ArrayList ();
2696 // fill the key lists
2698 if (rgKeyBlocks.Count > 0) {
2699 kbCurr = (KeyBlock) rgKeyBlocks [0];
2700 foreach (object key in rgKeys)
2702 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2703 System.Convert.ToInt64 (key) > kbCurr.nLast;
2705 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2706 kbCurr.rgKeys.Add (key);
2710 // sort the blocks so we can tackle the largest ones first
2711 rgKeyBlocks.Sort ();
2713 // okay now we can start...
2714 ILGenerator ig = ec.ig;
2715 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2716 Label lblDefault = ig.DefineLabel ();
2718 Type typeKeys = null;
2719 if (rgKeys.Length > 0)
2720 typeKeys = rgKeys [0].GetType (); // used for conversions
2724 if (TypeManager.IsEnumType (SwitchType))
2725 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2727 compare_type = SwitchType;
2729 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2731 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2732 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2735 foreach (object key in kb.rgKeys)
2737 ig.Emit (OpCodes.Ldloc, val);
2738 EmitObjectInteger (ig, key);
2739 SwitchLabel sl = (SwitchLabel) Elements [key];
2740 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2745 // TODO: if all the keys in the block are the same and there are
2746 // no gaps/defaults then just use a range-check.
2747 if (compare_type == TypeManager.int64_type ||
2748 compare_type == TypeManager.uint64_type)
2750 // TODO: optimize constant/I4 cases
2752 // check block range (could be > 2^31)
2753 ig.Emit (OpCodes.Ldloc, val);
2754 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2755 ig.Emit (OpCodes.Blt, lblDefault);
2756 ig.Emit (OpCodes.Ldloc, val);
2757 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2758 ig.Emit (OpCodes.Bgt, lblDefault);
2761 ig.Emit (OpCodes.Ldloc, val);
2764 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2765 ig.Emit (OpCodes.Sub);
2767 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2772 ig.Emit (OpCodes.Ldloc, val);
2773 int nFirst = (int) kb.nFirst;
2776 IntConstant.EmitInt (ig, nFirst);
2777 ig.Emit (OpCodes.Sub);
2779 else if (nFirst < 0)
2781 IntConstant.EmitInt (ig, -nFirst);
2782 ig.Emit (OpCodes.Add);
2786 // first, build the list of labels for the switch
2788 int cJumps = kb.Length;
2789 Label [] rgLabels = new Label [cJumps];
2790 for (int iJump = 0; iJump < cJumps; iJump++)
2792 object key = kb.rgKeys [iKey];
2793 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2795 SwitchLabel sl = (SwitchLabel) Elements [key];
2796 rgLabels [iJump] = sl.GetILLabel (ec);
2800 rgLabels [iJump] = lblDefault;
2802 // emit the switch opcode
2803 ig.Emit (OpCodes.Switch, rgLabels);
2806 // mark the default for this block
2808 ig.MarkLabel (lblDefault);
2811 // TODO: find the default case and emit it here,
2812 // to prevent having to do the following jump.
2813 // make sure to mark other labels in the default section
2815 // the last default just goes to the end
2816 ig.Emit (OpCodes.Br, lblDefault);
2818 // now emit the code for the sections
2819 bool fFoundDefault = false;
2820 foreach (SwitchSection ss in Sections)
2822 foreach (SwitchLabel sl in ss.Labels)
2824 ig.MarkLabel (sl.GetILLabel (ec));
2825 ig.MarkLabel (sl.GetILLabelCode (ec));
2826 if (sl.Label == null)
2828 ig.MarkLabel (lblDefault);
2829 fFoundDefault = true;
2833 //ig.Emit (OpCodes.Br, lblEnd);
2836 if (!fFoundDefault) {
2837 ig.MarkLabel (lblDefault);
2839 ig.MarkLabel (lblEnd);
2842 // This simple emit switch works, but does not take advantage of the
2844 // TODO: remove non-string logic from here
2845 // TODO: binary search strings?
2847 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2849 ILGenerator ig = ec.ig;
2850 Label end_of_switch = ig.DefineLabel ();
2851 Label next_test = ig.DefineLabel ();
2852 Label null_target = ig.DefineLabel ();
2853 bool first_test = true;
2854 bool pending_goto_end = false;
2855 bool null_marked = false;
2858 ig.Emit (OpCodes.Ldloc, val);
2860 if (Elements.Contains (NullLiteral.Null)){
2861 ig.Emit (OpCodes.Brfalse, null_target);
2863 ig.Emit (OpCodes.Brfalse, default_target);
2865 ig.Emit (OpCodes.Ldloc, val);
2866 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2867 ig.Emit (OpCodes.Stloc, val);
2869 int section_count = Sections.Count;
2870 for (int section = 0; section < section_count; section++){
2871 SwitchSection ss = (SwitchSection) Sections [section];
2873 if (ss == default_section)
2876 Label sec_begin = ig.DefineLabel ();
2878 ig.Emit (OpCodes.Nop);
2880 if (pending_goto_end)
2881 ig.Emit (OpCodes.Br, end_of_switch);
2883 int label_count = ss.Labels.Count;
2885 for (int label = 0; label < label_count; label++){
2886 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2887 ig.MarkLabel (sl.GetILLabel (ec));
2890 ig.MarkLabel (next_test);
2891 next_test = ig.DefineLabel ();
2894 // If we are the default target
2896 if (sl.Label != null){
2897 object lit = sl.Converted;
2899 if (lit is NullLiteral){
2901 if (label_count == 1)
2902 ig.Emit (OpCodes.Br, next_test);
2906 ig.Emit (OpCodes.Ldloc, val);
2907 ig.Emit (OpCodes.Ldstr, (string)lit);
2908 if (label_count == 1)
2909 ig.Emit (OpCodes.Bne_Un, next_test);
2911 if (label+1 == label_count)
2912 ig.Emit (OpCodes.Bne_Un, next_test);
2914 ig.Emit (OpCodes.Beq, sec_begin);
2919 ig.MarkLabel (null_target);
2922 ig.MarkLabel (sec_begin);
2923 foreach (SwitchLabel sl in ss.Labels)
2924 ig.MarkLabel (sl.GetILLabelCode (ec));
2927 pending_goto_end = !ss.Block.HasRet;
2930 ig.MarkLabel (next_test);
2931 ig.MarkLabel (default_target);
2933 ig.MarkLabel (null_target);
2934 if (default_section != null)
2935 default_section.Block.Emit (ec);
2936 ig.MarkLabel (end_of_switch);
2939 SwitchSection FindSection (SwitchLabel label)
2941 foreach (SwitchSection ss in Sections){
2942 foreach (SwitchLabel sl in ss.Labels){
2951 public override bool Resolve (EmitContext ec)
2953 Expr = Expr.Resolve (ec);
2957 new_expr = SwitchGoverningType (ec, Expr.Type);
2958 if (new_expr == null){
2959 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2964 SwitchType = new_expr.Type;
2966 if (!CheckSwitch (ec))
2969 Switch old_switch = ec.Switch;
2971 ec.Switch.SwitchType = SwitchType;
2973 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2974 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2976 is_constant = new_expr is Constant;
2978 object key = ((Constant) new_expr).GetValue ();
2979 SwitchLabel label = (SwitchLabel) Elements [key];
2981 constant_section = FindSection (label);
2982 if (constant_section == null)
2983 constant_section = default_section;
2987 foreach (SwitchSection ss in Sections){
2989 ec.CurrentBranching.CreateSibling (
2990 null, FlowBranching.SiblingType.SwitchSection);
2994 if (is_constant && (ss != constant_section)) {
2995 // If we're a constant switch, we're only emitting
2996 // one single section - mark all the others as
2998 ec.CurrentBranching.CurrentUsageVector.Goto ();
2999 if (!ss.Block.ResolveUnreachable (ec, true))
3002 if (!ss.Block.Resolve (ec))
3007 if (default_section == null)
3008 ec.CurrentBranching.CreateSibling (
3009 null, FlowBranching.SiblingType.SwitchSection);
3011 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3012 ec.Switch = old_switch;
3014 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3020 protected override void DoEmit (EmitContext ec)
3022 ILGenerator ig = ec.ig;
3024 // Store variable for comparission purposes
3027 value = ig.DeclareLocal (SwitchType);
3029 ig.Emit (OpCodes.Stloc, value);
3033 default_target = ig.DefineLabel ();
3036 // Setup the codegen context
3038 Label old_end = ec.LoopEnd;
3039 Switch old_switch = ec.Switch;
3041 ec.LoopEnd = ig.DefineLabel ();
3046 if (constant_section != null)
3047 constant_section.Block.Emit (ec);
3048 } else if (SwitchType == TypeManager.string_type)
3049 SimpleSwitchEmit (ec, value);
3051 TableSwitchEmit (ec, value);
3053 // Restore context state.
3054 ig.MarkLabel (ec.LoopEnd);
3057 // Restore the previous context
3059 ec.LoopEnd = old_end;
3060 ec.Switch = old_switch;
3064 public abstract class ExceptionStatement : Statement
3066 public abstract void EmitFinally (EmitContext ec);
3068 protected bool emit_finally = true;
3069 ArrayList parent_vectors;
3071 protected void DoEmitFinally (EmitContext ec)
3074 ec.ig.BeginFinallyBlock ();
3075 else if (ec.InIterator)
3076 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3080 protected void ResolveFinally (FlowBranchingException branching)
3082 emit_finally = branching.EmitFinally;
3084 branching.Parent.StealFinallyClauses (ref parent_vectors);
3088 public class Lock : ExceptionStatement {
3090 public Statement Statement;
3093 public Lock (Expression expr, Statement stmt, Location l)
3100 public override bool Resolve (EmitContext ec)
3102 expr = expr.Resolve (ec);
3106 if (expr.Type.IsValueType){
3107 Report.Error (185, loc,
3108 "`{0}' is not a reference type as required by the lock statement",
3109 TypeManager.CSharpName (expr.Type));
3113 FlowBranchingException branching = ec.StartFlowBranching (this);
3114 bool ok = Statement.Resolve (ec);
3116 ec.KillFlowBranching ();
3120 ResolveFinally (branching);
3122 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3123 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3124 // Unfortunately, System.Reflection.Emit automatically emits
3125 // a leave to the end of the finally block.
3126 // This is a problem if `returns' is true since we may jump
3127 // to a point after the end of the method.
3128 // As a workaround, emit an explicit ret here.
3129 ec.NeedReturnLabel ();
3135 protected override void DoEmit (EmitContext ec)
3137 Type type = expr.Type;
3139 ILGenerator ig = ec.ig;
3140 temp = ig.DeclareLocal (type);
3143 ig.Emit (OpCodes.Dup);
3144 ig.Emit (OpCodes.Stloc, temp);
3145 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3149 ig.BeginExceptionBlock ();
3150 Statement.Emit (ec);
3155 ig.EndExceptionBlock ();
3158 public override void EmitFinally (EmitContext ec)
3160 ILGenerator ig = ec.ig;
3161 ig.Emit (OpCodes.Ldloc, temp);
3162 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3166 public class Unchecked : Statement {
3167 public readonly Block Block;
3169 public Unchecked (Block b)
3175 public override bool Resolve (EmitContext ec)
3177 bool previous_state = ec.CheckState;
3178 bool previous_state_const = ec.ConstantCheckState;
3180 ec.CheckState = false;
3181 ec.ConstantCheckState = false;
3182 bool ret = Block.Resolve (ec);
3183 ec.CheckState = previous_state;
3184 ec.ConstantCheckState = previous_state_const;
3189 protected override void DoEmit (EmitContext ec)
3191 bool previous_state = ec.CheckState;
3192 bool previous_state_const = ec.ConstantCheckState;
3194 ec.CheckState = false;
3195 ec.ConstantCheckState = false;
3197 ec.CheckState = previous_state;
3198 ec.ConstantCheckState = previous_state_const;
3202 public class Checked : Statement {
3203 public readonly Block Block;
3205 public Checked (Block b)
3208 b.Unchecked = false;
3211 public override bool Resolve (EmitContext ec)
3213 bool previous_state = ec.CheckState;
3214 bool previous_state_const = ec.ConstantCheckState;
3216 ec.CheckState = true;
3217 ec.ConstantCheckState = true;
3218 bool ret = Block.Resolve (ec);
3219 ec.CheckState = previous_state;
3220 ec.ConstantCheckState = previous_state_const;
3225 protected override void DoEmit (EmitContext ec)
3227 bool previous_state = ec.CheckState;
3228 bool previous_state_const = ec.ConstantCheckState;
3230 ec.CheckState = true;
3231 ec.ConstantCheckState = true;
3233 ec.CheckState = previous_state;
3234 ec.ConstantCheckState = previous_state_const;
3238 public class Unsafe : Statement {
3239 public readonly Block Block;
3241 public Unsafe (Block b)
3244 Block.Unsafe = true;
3247 public override bool Resolve (EmitContext ec)
3249 bool previous_state = ec.InUnsafe;
3253 val = Block.Resolve (ec);
3254 ec.InUnsafe = previous_state;
3259 protected override void DoEmit (EmitContext ec)
3261 bool previous_state = ec.InUnsafe;
3265 ec.InUnsafe = previous_state;
3272 public class Fixed : Statement {
3274 ArrayList declarators;
3275 Statement statement;
3280 abstract class Emitter
3282 protected LocalInfo vi;
3283 protected Expression converted;
3285 protected Emitter (Expression expr, LocalInfo li)
3291 public abstract void Emit (EmitContext ec);
3292 public abstract void EmitExit (ILGenerator ig);
3295 class ExpressionEmitter: Emitter {
3296 public ExpressionEmitter (Expression converted, LocalInfo li) :
3297 base (converted, li)
3301 public override void Emit (EmitContext ec) {
3303 // Store pointer in pinned location
3305 converted.Emit (ec);
3306 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3309 public override void EmitExit (ILGenerator ig)
3311 ig.Emit (OpCodes.Ldc_I4_0);
3312 ig.Emit (OpCodes.Conv_U);
3313 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3317 class StringEmitter: Emitter {
3318 LocalBuilder pinned_string;
3321 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3327 public override void Emit (EmitContext ec)
3329 ILGenerator ig = ec.ig;
3330 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3332 converted.Emit (ec);
3333 ig.Emit (OpCodes.Stloc, pinned_string);
3335 Expression sptr = new StringPtr (pinned_string, loc);
3336 converted = Convert.ImplicitConversionRequired (
3337 ec, sptr, vi.VariableType, loc);
3339 if (converted == null)
3342 converted.Emit (ec);
3343 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3346 public override void EmitExit(ILGenerator ig)
3348 ig.Emit (OpCodes.Ldnull);
3349 ig.Emit (OpCodes.Stloc, pinned_string);
3353 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3356 declarators = decls;
3361 public Statement Statement {
3362 get { return statement; }
3365 public override bool Resolve (EmitContext ec)
3368 Expression.UnsafeError (loc);
3372 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3376 expr_type = texpr.Type;
3378 CheckObsolete (expr_type);
3380 data = new Emitter [declarators.Count];
3382 if (!expr_type.IsPointer){
3383 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3388 foreach (Pair p in declarators){
3389 LocalInfo vi = (LocalInfo) p.First;
3390 Expression e = (Expression) p.Second;
3392 vi.VariableInfo.SetAssigned (ec);
3393 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3396 // The rules for the possible declarators are pretty wise,
3397 // but the production on the grammar is more concise.
3399 // So we have to enforce these rules here.
3401 // We do not resolve before doing the case 1 test,
3402 // because the grammar is explicit in that the token &
3403 // is present, so we need to test for this particular case.
3407 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3412 // Case 1: & object.
3414 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3415 Expression child = ((Unary) e).Expr;
3417 if (child is ParameterReference || child is LocalVariableReference){
3420 "No need to use fixed statement for parameters or " +
3421 "local variable declarations (address is already " +
3426 ec.InFixedInitializer = true;
3428 ec.InFixedInitializer = false;
3432 child = ((Unary) e).Expr;
3434 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3437 data [i] = new ExpressionEmitter (e, vi);
3443 ec.InFixedInitializer = true;
3445 ec.InFixedInitializer = false;
3452 if (e.Type.IsArray){
3453 Type array_type = TypeManager.GetElementType (e.Type);
3456 // Provided that array_type is unmanaged,
3458 if (!TypeManager.VerifyUnManaged (array_type, loc))
3462 // and T* is implicitly convertible to the
3463 // pointer type given in the fixed statement.
3465 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3467 Expression converted = Convert.ImplicitConversionRequired (
3468 ec, array_ptr, vi.VariableType, loc);
3469 if (converted == null)
3472 data [i] = new ExpressionEmitter (converted, vi);
3481 if (e.Type == TypeManager.string_type){
3482 data [i] = new StringEmitter (e, vi, loc);
3487 // Case 4: fixed buffer
3488 FieldExpr fe = e as FieldExpr;
3490 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3492 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3494 Expression converted = Convert.ImplicitConversionRequired (
3495 ec, fixed_buffer_ptr, vi.VariableType, loc);
3496 if (converted == null)
3499 data [i] = new ExpressionEmitter (converted, vi);
3507 // For other cases, flag a `this is already fixed expression'
3509 if (e is LocalVariableReference || e is ParameterReference ||
3510 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3512 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3516 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3520 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3522 if (!statement.Resolve (ec)) {
3523 ec.KillFlowBranching ();
3527 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3528 has_ret = reachability.IsUnreachable;
3533 protected override void DoEmit (EmitContext ec)
3535 for (int i = 0; i < data.Length; i++) {
3539 statement.Emit (ec);
3544 ILGenerator ig = ec.ig;
3547 // Clear the pinned variable
3549 for (int i = 0; i < data.Length; i++) {
3550 data [i].EmitExit (ig);
3555 public class Catch: Statement {
3556 public readonly string Name;
3557 public readonly Block Block;
3559 Expression type_expr;
3562 public Catch (Expression type, string name, Block block, Location l)
3570 public Type CatchType {
3576 public bool IsGeneral {
3578 return type_expr == null;
3582 protected override void DoEmit(EmitContext ec)
3586 public override bool Resolve (EmitContext ec)
3588 bool was_catch = ec.InCatch;
3591 if (type_expr != null) {
3592 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3596 type = te.ResolveType (ec);
3598 CheckObsolete (type);
3600 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3601 Error (155, "The type caught or thrown must be derived from System.Exception");
3607 return Block.Resolve (ec);
3610 ec.InCatch = was_catch;
3615 public class Try : ExceptionStatement {
3616 public readonly Block Fini, Block;
3617 public readonly ArrayList Specific;
3618 public readonly Catch General;
3620 bool need_exc_block;
3623 // specific, general and fini might all be null.
3625 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3627 if (specific == null && general == null){
3628 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3632 this.Specific = specific;
3633 this.General = general;
3638 public override bool Resolve (EmitContext ec)
3642 FlowBranchingException branching = ec.StartFlowBranching (this);
3644 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3646 if (!Block.Resolve (ec))
3649 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3651 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3653 Type[] prevCatches = new Type [Specific.Count];
3655 foreach (Catch c in Specific){
3656 ec.CurrentBranching.CreateSibling (
3657 c.Block, FlowBranching.SiblingType.Catch);
3659 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3661 if (c.Name != null) {
3662 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3664 throw new Exception ();
3666 vi.VariableInfo = null;
3669 if (!c.Resolve (ec))
3672 Type resolvedType = c.CatchType;
3673 for (int ii = 0; ii < last_index; ++ii) {
3674 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3675 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3680 prevCatches [last_index++] = resolvedType;
3681 need_exc_block = true;
3684 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3686 if (General != null){
3687 ec.CurrentBranching.CreateSibling (
3688 General.Block, FlowBranching.SiblingType.Catch);
3690 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3692 if (!General.Resolve (ec))
3695 need_exc_block = true;
3698 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3702 ec.CurrentBranching.CreateSibling (
3703 Fini, FlowBranching.SiblingType.Finally);
3705 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3706 bool was_finally = ec.InFinally;
3707 ec.InFinally = true;
3708 if (!Fini.Resolve (ec))
3710 ec.InFinally = was_finally;
3713 need_exc_block = true;
3716 if (ec.InIterator) {
3717 ResolveFinally (branching);
3718 need_exc_block |= emit_finally;
3720 emit_finally = Fini != null;
3722 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3724 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3726 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3728 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3729 // Unfortunately, System.Reflection.Emit automatically emits
3730 // a leave to the end of the finally block. This is a problem
3731 // if `returns' is true since we may jump to a point after the
3732 // end of the method.
3733 // As a workaround, emit an explicit ret here.
3734 ec.NeedReturnLabel ();
3740 protected override void DoEmit (EmitContext ec)
3742 ILGenerator ig = ec.ig;
3745 ig.BeginExceptionBlock ();
3748 foreach (Catch c in Specific){
3751 ig.BeginCatchBlock (c.CatchType);
3753 if (c.Name != null){
3754 vi = c.Block.GetLocalInfo (c.Name);
3756 throw new Exception ("Variable does not exist in this block");
3758 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3760 ec.EmitCapturedVariableInstance (vi);
3761 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
3762 ig.Emit (OpCodes.Stfld, vi.FieldBuilder);
3765 ig.Emit (OpCodes.Pop);
3770 if (General != null){
3771 ig.BeginCatchBlock (TypeManager.object_type);
3772 ig.Emit (OpCodes.Pop);
3773 General.Block.Emit (ec);
3778 ig.EndExceptionBlock ();
3781 public override void EmitFinally (EmitContext ec)
3787 public bool HasCatch
3790 return General != null || Specific.Count > 0;
3795 public class Using : ExceptionStatement {
3796 object expression_or_block;
3797 public Statement Statement;
3802 Expression [] resolved_vars;
3803 Expression [] converted_vars;
3804 ExpressionStatement [] assign;
3805 LocalBuilder local_copy;
3807 public Using (object expression_or_block, Statement stmt, Location l)
3809 this.expression_or_block = expression_or_block;
3815 // Resolves for the case of using using a local variable declaration.
3817 bool ResolveLocalVariableDecls (EmitContext ec)
3821 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3825 expr_type = texpr.Type;
3828 // The type must be an IDisposable or an implicit conversion
3831 converted_vars = new Expression [var_list.Count];
3832 resolved_vars = new Expression [var_list.Count];
3833 assign = new ExpressionStatement [var_list.Count];
3835 bool need_conv = !TypeManager.ImplementsInterface (
3836 expr_type, TypeManager.idisposable_type);
3838 foreach (DictionaryEntry e in var_list){
3839 Expression var = (Expression) e.Key;
3841 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3845 resolved_vars [i] = var;
3852 converted_vars [i] = Convert.ImplicitConversionRequired (
3853 ec, var, TypeManager.idisposable_type, loc);
3855 if (converted_vars [i] == null)
3862 foreach (DictionaryEntry e in var_list){
3863 Expression var = resolved_vars [i];
3864 Expression new_expr = (Expression) e.Value;
3867 a = new Assign (var, new_expr, loc);
3873 converted_vars [i] = var;
3874 assign [i] = (ExpressionStatement) a;
3881 bool ResolveExpression (EmitContext ec)
3883 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3884 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3885 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3886 TypeManager.CSharpName (expr_type));
3895 // Emits the code for the case of using using a local variable declaration.
3897 void EmitLocalVariableDecls (EmitContext ec)
3899 ILGenerator ig = ec.ig;
3902 for (i = 0; i < assign.Length; i++) {
3903 assign [i].EmitStatement (ec);
3906 ig.BeginExceptionBlock ();
3908 Statement.Emit (ec);
3910 var_list.Reverse ();
3915 void EmitLocalVariableDeclFinally (EmitContext ec)
3917 ILGenerator ig = ec.ig;
3919 int i = assign.Length;
3920 for (int ii = 0; ii < var_list.Count; ++ii){
3921 Expression var = resolved_vars [--i];
3922 Label skip = ig.DefineLabel ();
3924 ig.BeginFinallyBlock ();
3926 if (!var.Type.IsValueType) {
3928 ig.Emit (OpCodes.Brfalse, skip);
3929 converted_vars [i].Emit (ec);
3930 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3932 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3934 if (!(ml is MethodGroupExpr)) {
3936 ig.Emit (OpCodes.Box, var.Type);
3937 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3939 MethodInfo mi = null;
3941 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3942 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3949 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3953 IMemoryLocation mloc = (IMemoryLocation) var;
3955 mloc.AddressOf (ec, AddressOp.Load);
3956 ig.Emit (OpCodes.Call, mi);
3960 ig.MarkLabel (skip);
3963 ig.EndExceptionBlock ();
3965 ig.BeginFinallyBlock ();
3970 void EmitExpression (EmitContext ec)
3973 // Make a copy of the expression and operate on that.
3975 ILGenerator ig = ec.ig;
3976 local_copy = ig.DeclareLocal (expr_type);
3981 ig.Emit (OpCodes.Stloc, local_copy);
3984 ig.BeginExceptionBlock ();
3986 Statement.Emit (ec);
3990 ig.EndExceptionBlock ();
3993 void EmitExpressionFinally (EmitContext ec)
3995 ILGenerator ig = ec.ig;
3996 if (!local_copy.LocalType.IsValueType) {
3997 Label skip = ig.DefineLabel ();
3998 ig.Emit (OpCodes.Ldloc, local_copy);
3999 ig.Emit (OpCodes.Brfalse, skip);
4000 ig.Emit (OpCodes.Ldloc, local_copy);
4001 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4002 ig.MarkLabel (skip);
4004 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4006 if (!(ml is MethodGroupExpr)) {
4007 ig.Emit (OpCodes.Ldloc, local_copy);
4008 ig.Emit (OpCodes.Box, local_copy.LocalType);
4009 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4011 MethodInfo mi = null;
4013 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4014 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4021 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4025 ig.Emit (OpCodes.Ldloca, local_copy);
4026 ig.Emit (OpCodes.Call, mi);
4031 public override bool Resolve (EmitContext ec)
4033 if (expression_or_block is DictionaryEntry){
4034 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4035 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4037 if (!ResolveLocalVariableDecls (ec))
4040 } else if (expression_or_block is Expression){
4041 expr = (Expression) expression_or_block;
4043 expr = expr.Resolve (ec);
4047 expr_type = expr.Type;
4049 if (!ResolveExpression (ec))
4053 FlowBranchingException branching = ec.StartFlowBranching (this);
4055 bool ok = Statement.Resolve (ec);
4058 ec.KillFlowBranching ();
4062 ResolveFinally (branching);
4063 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4065 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4066 // Unfortunately, System.Reflection.Emit automatically emits a leave
4067 // to the end of the finally block. This is a problem if `returns'
4068 // is true since we may jump to a point after the end of the method.
4069 // As a workaround, emit an explicit ret here.
4070 ec.NeedReturnLabel ();
4076 protected override void DoEmit (EmitContext ec)
4078 if (expression_or_block is DictionaryEntry)
4079 EmitLocalVariableDecls (ec);
4080 else if (expression_or_block is Expression)
4081 EmitExpression (ec);
4084 public override void EmitFinally (EmitContext ec)
4086 if (expression_or_block is DictionaryEntry)
4087 EmitLocalVariableDeclFinally (ec);
4088 else if (expression_or_block is Expression)
4089 EmitExpressionFinally (ec);
4094 /// Implementation of the foreach C# statement
4096 public class Foreach : Statement {
4098 Expression variable;
4100 Statement statement;
4102 CollectionForeach collection;
4104 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4105 Statement stmt, Location l)
4108 this.variable = var;
4114 public Statement Statement {
4115 get { return statement; }
4118 public override bool Resolve (EmitContext ec)
4120 expr = expr.Resolve (ec);
4124 if (expr is NullLiteral) {
4125 Report.Error (186, loc, "Use of null is not valid in this context");
4129 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4133 Type var_type = texpr.Type;
4136 // We need an instance variable. Not sure this is the best
4137 // way of doing this.
4139 // FIXME: When we implement propertyaccess, will those turn
4140 // out to return values in ExprClass? I think they should.
4142 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4143 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4144 collection.error1579 ();
4148 if (expr.Type.IsArray) {
4149 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4150 return array.Resolve (ec);
4152 collection = new CollectionForeach (
4153 var_type, variable, expr, statement, loc);
4154 return collection.Resolve (ec);
4158 protected override void DoEmit (EmitContext ec)
4160 ILGenerator ig = ec.ig;
4162 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4163 ec.LoopBegin = ig.DefineLabel ();
4164 ec.LoopEnd = ig.DefineLabel ();
4166 if (collection != null)
4167 collection.Emit (ec);
4171 ec.LoopBegin = old_begin;
4172 ec.LoopEnd = old_end;
4175 protected class TemporaryVariable : Expression, IMemoryLocation
4179 public TemporaryVariable (Type type, Location loc)
4183 eclass = ExprClass.Value;
4186 public override Expression DoResolve (EmitContext ec)
4191 TypeExpr te = new TypeExpression (type, loc);
4192 li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
4193 if (!li.Resolve (ec))
4196 AnonymousContainer am = ec.CurrentAnonymousMethod;
4197 if ((am != null) && am.IsIterator)
4198 ec.CaptureVariable (li);
4203 public override void Emit (EmitContext ec)
4205 ILGenerator ig = ec.ig;
4207 if (li.FieldBuilder != null) {
4208 ig.Emit (OpCodes.Ldarg_0);
4209 ig.Emit (OpCodes.Ldfld, li.FieldBuilder);
4211 ig.Emit (OpCodes.Ldloc, li.LocalBuilder);
4215 public void EmitLoadAddress (EmitContext ec)
4217 ILGenerator ig = ec.ig;
4219 if (li.FieldBuilder != null) {
4220 ig.Emit (OpCodes.Ldarg_0);
4221 ig.Emit (OpCodes.Ldflda, li.FieldBuilder);
4223 ig.Emit (OpCodes.Ldloca, li.LocalBuilder);
4227 public void Store (EmitContext ec, Expression right_side)
4229 if (li.FieldBuilder != null)
4230 ec.ig.Emit (OpCodes.Ldarg_0);
4232 right_side.Emit (ec);
4233 if (li.FieldBuilder != null) {
4234 ec.ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4236 ec.ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4240 public void EmitThis (EmitContext ec)
4242 if (li.FieldBuilder != null) {
4243 ec.ig.Emit (OpCodes.Ldarg_0);
4247 public void EmitStore (ILGenerator ig)
4249 if (li.FieldBuilder != null)
4250 ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4252 ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4255 public void AddressOf (EmitContext ec, AddressOp mode)
4257 EmitLoadAddress (ec);
4261 protected class ArrayCounter : TemporaryVariable
4263 public ArrayCounter (Location loc)
4264 : base (TypeManager.int32_type, loc)
4267 public void Initialize (EmitContext ec)
4270 ec.ig.Emit (OpCodes.Ldc_I4_0);
4274 public void Increment (EmitContext ec)
4278 ec.ig.Emit (OpCodes.Ldc_I4_1);
4279 ec.ig.Emit (OpCodes.Add);
4284 protected class ArrayForeach : Statement
4286 Expression variable, expr, conv;
4287 Statement statement;
4290 TemporaryVariable[] lengths;
4291 ArrayCounter[] counter;
4294 TemporaryVariable copy;
4297 public ArrayForeach (Type var_type, Expression var,
4298 Expression expr, Statement stmt, Location l)
4300 this.var_type = var_type;
4301 this.variable = var;
4307 public override bool Resolve (EmitContext ec)
4309 array_type = expr.Type;
4310 rank = array_type.GetArrayRank ();
4312 copy = new TemporaryVariable (array_type, loc);
4315 counter = new ArrayCounter [rank];
4316 lengths = new TemporaryVariable [rank];
4318 ArrayList list = new ArrayList ();
4319 for (int i = 0; i < rank; i++) {
4320 counter [i] = new ArrayCounter (loc);
4321 counter [i].Resolve (ec);
4323 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4324 lengths [i].Resolve (ec);
4326 list.Add (counter [i]);
4329 access = new ElementAccess (copy, list).Resolve (ec);
4333 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4339 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4340 ec.CurrentBranching.CreateSibling ();
4342 variable = variable.ResolveLValue (ec, conv, loc);
4343 if (variable == null)
4346 if (!statement.Resolve (ec))
4349 ec.EndFlowBranching ();
4354 protected override void DoEmit (EmitContext ec)
4356 ILGenerator ig = ec.ig;
4358 copy.Store (ec, expr);
4360 Label[] test = new Label [rank];
4361 Label[] loop = new Label [rank];
4363 for (int i = 0; i < rank; i++) {
4364 test [i] = ig.DefineLabel ();
4365 loop [i] = ig.DefineLabel ();
4367 lengths [i].EmitThis (ec);
4368 ((ArrayAccess) access).EmitGetLength (ec, i);
4369 lengths [i].EmitStore (ig);
4372 for (int i = 0; i < rank; i++) {
4373 counter [i].Initialize (ec);
4375 ig.Emit (OpCodes.Br, test [i]);
4376 ig.MarkLabel (loop [i]);
4379 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4381 statement.Emit (ec);
4383 ig.MarkLabel (ec.LoopBegin);
4385 for (int i = rank - 1; i >= 0; i--){
4386 counter [i].Increment (ec);
4388 ig.MarkLabel (test [i]);
4389 counter [i].Emit (ec);
4390 lengths [i].Emit (ec);
4391 ig.Emit (OpCodes.Blt, loop [i]);
4394 ig.MarkLabel (ec.LoopEnd);
4398 protected class CollectionForeach : ExceptionStatement
4400 Expression variable, expr;
4401 Statement statement;
4403 TemporaryVariable enumerator;
4407 MethodGroupExpr get_enumerator;
4408 PropertyExpr get_current;
4409 MethodInfo move_next;
4410 Type var_type, enumerator_type;
4413 public CollectionForeach (Type var_type, Expression var,
4414 Expression expr, Statement stmt, Location l)
4416 this.var_type = var_type;
4417 this.variable = var;
4423 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4425 Type [] args = TypeManager.GetArgumentTypes (mi);
4427 if (args.Length != 0)
4431 if (TypeManager.IsOverride (mi))
4434 // Check whether GetEnumerator is public
4435 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4438 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4440 // Apply the same optimization as MS: skip the GetEnumerator
4441 // returning an IEnumerator, and use the one returning a
4442 // CharEnumerator instead. This allows us to avoid the
4443 // try-finally block and the boxing.
4448 // Ok, we can access it, now make sure that we can do something
4449 // with this `GetEnumerator'
4452 Type return_type = mi.ReturnType;
4453 if (mi.ReturnType == TypeManager.ienumerator_type ||
4454 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4455 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4457 // If it is not an interface, lets try to find the methods ourselves.
4458 // For example, if we have:
4459 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4460 // We can avoid the iface call. This is a runtime perf boost.
4461 // even bigger if we have a ValueType, because we avoid the cost
4464 // We have to make sure that both methods exist for us to take
4465 // this path. If one of the methods does not exist, we will just
4466 // use the interface. Sadly, this complex if statement is the only
4467 // way I could do this without a goto
4470 if (return_type.IsInterface && return_type.IsGenericType) {
4471 enumerator_type = return_type;
4472 if (!FetchGetCurrent (ec, return_type))
4473 get_current = new PropertyExpr (
4474 ec, TypeManager.ienumerator_getcurrent, loc);
4475 if (!FetchMoveNext (ec, return_type))
4476 move_next = TypeManager.bool_movenext_void;
4480 if (return_type.IsInterface ||
4481 !FetchMoveNext (ec, return_type) ||
4482 !FetchGetCurrent (ec, return_type)) {
4483 enumerator_type = return_type;
4484 move_next = TypeManager.bool_movenext_void;
4485 get_current = new PropertyExpr (
4486 ec, TypeManager.ienumerator_getcurrent, loc);
4491 // Ok, so they dont return an IEnumerable, we will have to
4492 // find if they support the GetEnumerator pattern.
4495 if (!FetchMoveNext (ec, return_type))
4498 if (!FetchGetCurrent (ec, return_type))
4502 enumerator_type = return_type;
4503 is_disposable = !enumerator_type.IsSealed ||
4504 TypeManager.ImplementsInterface (
4505 enumerator_type, TypeManager.idisposable_type);
4511 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4513 bool FetchMoveNext (EmitContext ec, Type t)
4515 MemberList move_next_list;
4517 move_next_list = TypeContainer.FindMembers (
4518 t, MemberTypes.Method,
4519 Expression.AllBindingFlags,
4520 Type.FilterName, "MoveNext");
4521 if (move_next_list.Count == 0)
4525 foreach (MemberInfo m in move_next_list){
4526 MethodInfo mi = (MethodInfo) m;
4529 args = TypeManager.GetArgumentTypes (mi);
4530 if ((args != null) && (args.Length == 0) &&
4531 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4543 // Retrieves a `public T get_Current ()' method from the Type `t'
4545 bool FetchGetCurrent (EmitContext ec, Type t)
4547 PropertyExpr pe = Expression.MemberLookup (
4548 ec, t, "Current", MemberTypes.Property,
4549 Expression.AllBindingFlags, loc) as PropertyExpr;
4558 // Retrieves a `public void Dispose ()' method from the Type `t'
4560 static MethodInfo FetchMethodDispose (Type t)
4562 MemberList dispose_list;
4564 dispose_list = TypeContainer.FindMembers (
4565 t, MemberTypes.Method,
4566 BindingFlags.Public | BindingFlags.Instance,
4567 Type.FilterName, "Dispose");
4568 if (dispose_list.Count == 0)
4571 foreach (MemberInfo m in dispose_list){
4572 MethodInfo mi = (MethodInfo) m;
4575 args = TypeManager.GetArgumentTypes (mi);
4576 if (args != null && args.Length == 0){
4577 if (mi.ReturnType == TypeManager.void_type)
4584 public void error1579 ()
4586 Report.Error (1579, loc,
4587 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4588 TypeManager.CSharpName (expr.Type));
4591 bool TryType (EmitContext ec, Type t)
4593 MethodGroupExpr mg = Expression.MemberLookup (
4594 ec, t, "GetEnumerator", MemberTypes.Method,
4595 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4599 MethodBase result = null;
4600 MethodInfo tmp_move_next = null;
4601 PropertyExpr tmp_get_cur = null;
4602 Type tmp_enumerator_type = enumerator_type;
4603 foreach (MethodInfo mi in mg.Methods) {
4604 if (!GetEnumeratorFilter (ec, mi)) {
4609 tmp_move_next = move_next;
4610 tmp_get_cur = get_current;
4611 tmp_enumerator_type = enumerator_type;
4612 if (mi.DeclaringType == t)
4616 if (result != null) {
4617 move_next = tmp_move_next;
4618 get_current = tmp_get_cur;
4619 enumerator_type = tmp_enumerator_type;
4620 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
4621 get_enumerator = new MethodGroupExpr (mi, loc);
4623 if (t != expr.Type) {
4624 expr = Convert.ExplicitConversion (
4627 throw new InternalErrorException ();
4630 get_enumerator.InstanceExpression = expr;
4631 get_enumerator.IsBase = t != expr.Type;
4639 bool ProbeCollectionType (EmitContext ec, Type t)
4641 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4642 if (TryType (ec, tt))
4648 // Now try to find the method in the interfaces
4651 Type [] ifaces = t.GetInterfaces ();
4653 foreach (Type i in ifaces){
4654 if (TryType (ec, i))
4659 // Since TypeBuilder.GetInterfaces only returns the interface
4660 // types for this type, we have to keep looping, but once
4661 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4662 // done, because it returns all the types
4664 if ((t is TypeBuilder))
4673 public override bool Resolve (EmitContext ec)
4675 enumerator_type = TypeManager.ienumerator_type;
4676 is_disposable = true;
4678 if (!ProbeCollectionType (ec, expr.Type)) {
4683 enumerator = new TemporaryVariable (enumerator_type, loc);
4684 enumerator.Resolve (ec);
4686 init = new Invocation (get_enumerator, new ArrayList ());
4687 init = init.Resolve (ec);
4691 Expression move_next_expr;
4693 MemberInfo[] mi = new MemberInfo[] { move_next };
4694 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4695 mg.InstanceExpression = enumerator;
4697 move_next_expr = new Invocation (mg, new ArrayList ());
4700 get_current.InstanceExpression = enumerator;
4702 Statement block = new CollectionForeachStatement (
4703 var_type, variable, get_current, statement, loc);
4705 loop = new While (move_next_expr, block, loc);
4709 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4710 ec.CurrentBranching.CreateSibling ();
4712 FlowBranchingException branching = null;
4714 branching = ec.StartFlowBranching (this);
4716 if (!loop.Resolve (ec))
4719 if (is_disposable) {
4720 ResolveFinally (branching);
4721 ec.EndFlowBranching ();
4723 emit_finally = true;
4725 ec.EndFlowBranching ();
4730 protected override void DoEmit (EmitContext ec)
4732 ILGenerator ig = ec.ig;
4734 enumerator.Store (ec, init);
4737 // Protect the code in a try/finalize block, so that
4738 // if the beast implement IDisposable, we get rid of it
4740 if (is_disposable && emit_finally)
4741 ig.BeginExceptionBlock ();
4746 // Now the finally block
4748 if (is_disposable) {
4751 ig.EndExceptionBlock ();
4756 public override void EmitFinally (EmitContext ec)
4758 ILGenerator ig = ec.ig;
4760 if (enumerator_type.IsValueType) {
4761 enumerator.Emit (ec);
4763 MethodInfo mi = FetchMethodDispose (enumerator_type);
4765 enumerator.EmitLoadAddress (ec);
4766 ig.Emit (OpCodes.Call, mi);
4768 enumerator.Emit (ec);
4769 ig.Emit (OpCodes.Box, enumerator_type);
4770 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4773 Label call_dispose = ig.DefineLabel ();
4775 enumerator.Emit (ec);
4776 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4777 ig.Emit (OpCodes.Dup);
4778 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4779 ig.Emit (OpCodes.Pop);
4781 Label end_finally = ig.DefineLabel ();
4782 ig.Emit (OpCodes.Br, end_finally);
4784 ig.MarkLabel (call_dispose);
4785 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4786 ig.MarkLabel (end_finally);
4791 protected class CollectionForeachStatement : Statement
4794 Expression variable, current, conv;
4795 Statement statement;
4798 public CollectionForeachStatement (Type type, Expression variable,
4799 Expression current, Statement statement,
4803 this.variable = variable;
4804 this.current = current;
4805 this.statement = statement;
4809 public override bool Resolve (EmitContext ec)
4811 current = current.Resolve (ec);
4812 if (current == null)
4815 conv = Convert.ExplicitConversion (ec, current, type, loc);
4819 assign = new Assign (variable, conv, loc);
4820 if (assign.Resolve (ec) == null)
4823 if (!statement.Resolve (ec))
4829 protected override void DoEmit (EmitContext ec)
4831 assign.EmitStatement (ec);
4832 statement.Emit (ec);