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)
83 if (!Location.IsNull (loc))
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 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, Location l)
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 if (!(expr is Constant)){
804 Error (150, "A constant value is expected");
808 object val = Expression.ConvertIntLiteral (
809 (Constant) expr, ec.Switch.SwitchType, loc);
814 sl = (SwitchLabel) ec.Switch.Elements [val];
817 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", val);
821 ec.CurrentBranching.CurrentUsageVector.Goto ();
825 protected override void DoEmit (EmitContext ec)
827 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
831 public class Throw : Statement {
834 public Throw (Expression expr, Location l)
840 public override bool Resolve (EmitContext ec)
842 ec.CurrentBranching.CurrentUsageVector.Throw ();
845 expr = expr.Resolve (ec);
849 ExprClass eclass = expr.eclass;
851 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
852 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
853 expr.Error_UnexpectedKind (ec, "value, variable, property or indexer access ", loc);
859 if ((t != TypeManager.exception_type) &&
860 !t.IsSubclassOf (TypeManager.exception_type) &&
861 !(expr is NullLiteral)) {
863 "The type caught or thrown must be derived " +
864 "from System.Exception");
871 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
876 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
882 protected override void DoEmit (EmitContext ec)
885 ec.ig.Emit (OpCodes.Rethrow);
889 ec.ig.Emit (OpCodes.Throw);
894 public class Break : Statement {
896 public Break (Location l)
903 public override bool Resolve (EmitContext ec)
905 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
906 Error (139, "No enclosing loop out of which to break or continue");
908 } else if (ec.InFinally && ec.CurrentBranching.BreakCrossesTryCatchBoundary()) {
909 Error (157, "Control cannot leave the body of a finally clause");
911 } else if (ec.CurrentBranching.InTryOrCatch (false))
912 ec.CurrentBranching.AddFinallyVector (
913 ec.CurrentBranching.CurrentUsageVector);
914 else if (ec.CurrentBranching.InLoop () || ec.CurrentBranching.InSwitch ())
915 ec.CurrentBranching.AddBreakVector (
916 ec.CurrentBranching.CurrentUsageVector);
918 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
921 ec.NeedReturnLabel ();
923 ec.CurrentBranching.CurrentUsageVector.Break ();
927 protected override void DoEmit (EmitContext ec)
929 ILGenerator ig = ec.ig;
932 ig.Emit (OpCodes.Leave, ec.LoopEnd);
934 ig.Emit (OpCodes.Br, ec.LoopEnd);
939 public class Continue : Statement {
941 public Continue (Location l)
948 public override bool Resolve (EmitContext ec)
950 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
951 Error (139, "No enclosing loop out of which to break or continue");
953 } else if (ec.InFinally) {
954 Error (157, "Control cannot leave the body of a finally clause");
956 } else if (ec.CurrentBranching.InTryOrCatch (false))
957 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
959 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
961 ec.CurrentBranching.CurrentUsageVector.Goto ();
965 protected override void DoEmit (EmitContext ec)
967 Label begin = ec.LoopBegin;
970 ec.ig.Emit (OpCodes.Leave, begin);
972 ec.ig.Emit (OpCodes.Br, begin);
977 // The information about a user-perceived local variable
979 public class LocalInfo {
980 public Expression Type;
983 // Most of the time a variable will be stored in a LocalBuilder
985 // But sometimes, it will be stored in a field (variables that have been
986 // hoisted by iterators or by anonymous methods). The context of the field will
987 // be stored in the EmitContext
990 public LocalBuilder LocalBuilder;
991 public FieldBuilder FieldBuilder;
993 public Type VariableType;
994 public readonly string Name;
995 public readonly Location Location;
996 public readonly Block Block;
998 public VariableInfo VariableInfo;
1007 CompilerGenerated = 64
1010 public enum ReadOnlyContext: byte {
1017 ReadOnlyContext ro_context;
1019 public LocalInfo (Expression type, string name, Block block, Location l)
1027 public LocalInfo (TypeContainer tc, Block block, Location l)
1029 VariableType = tc.TypeBuilder;
1034 public bool IsThisAssigned (EmitContext ec, Location loc)
1036 if (VariableInfo == null)
1037 throw new Exception ();
1039 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1042 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1045 public bool IsAssigned (EmitContext ec)
1047 if (VariableInfo == null)
1048 throw new Exception ();
1050 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1053 public bool Resolve (EmitContext ec)
1055 if (VariableType == null) {
1056 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1060 VariableType = texpr.ResolveType (ec);
1063 if (VariableType == TypeManager.void_type) {
1064 Report.Error (1547, Location,
1065 "Keyword 'void' cannot be used in this context");
1069 if (VariableType.IsAbstract && VariableType.IsSealed) {
1070 Report.Error (723, Location, "Cannot declare variable of static type `{0}'", TypeManager.CSharpName (VariableType));
1074 if (VariableType.IsPointer && !ec.InUnsafe)
1075 Expression.UnsafeError (Location);
1080 public bool IsCaptured {
1082 return (flags & Flags.Captured) != 0;
1086 flags |= Flags.Captured;
1090 public bool AddressTaken {
1092 return (flags & Flags.AddressTaken) != 0;
1096 flags |= Flags.AddressTaken;
1100 public bool CompilerGenerated {
1102 return (flags & Flags.CompilerGenerated) != 0;
1106 flags |= Flags.CompilerGenerated;
1110 public override string ToString ()
1112 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1113 Name, Type, VariableInfo, Location);
1118 return (flags & Flags.Used) != 0;
1121 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1125 public bool ReadOnly {
1127 return (flags & Flags.ReadOnly) != 0;
1131 public void SetReadOnlyContext (ReadOnlyContext context)
1133 flags |= Flags.ReadOnly;
1134 ro_context = context;
1137 public string GetReadOnlyContext ()
1140 throw new InternalErrorException ("Variable is not readonly");
1142 switch (ro_context) {
1143 case ReadOnlyContext.Fixed:
1144 return "fixed variable";
1145 case ReadOnlyContext.Foreach:
1146 return "foreach iteration variable";
1147 case ReadOnlyContext.Using:
1148 return "using variable";
1150 throw new NotImplementedException ();
1154 // Whether the variable is pinned, if Pinned the variable has been
1155 // allocated in a pinned slot with DeclareLocal.
1157 public bool Pinned {
1159 return (flags & Flags.Pinned) != 0;
1162 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1166 public bool IsThis {
1168 return (flags & Flags.IsThis) != 0;
1171 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1177 /// Block represents a C# block.
1181 /// This class is used in a number of places: either to represent
1182 /// explicit blocks that the programmer places or implicit blocks.
1184 /// Implicit blocks are used as labels or to introduce variable
1187 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1188 /// they contain extra information that is not necessary on normal blocks.
1190 public class Block : Statement {
1191 public Block Parent;
1192 public readonly Location StartLocation;
1193 public Location EndLocation = Location.Null;
1195 public readonly ToplevelBlock Toplevel;
1198 public enum Flags : ushort {
1202 VariablesInitialized = 8,
1207 HasVarargs = 256 // Used in ToplevelBlock
1209 protected Flags flags;
1211 public bool Implicit {
1212 get { return (flags & Flags.Implicit) != 0; }
1215 public bool Unchecked {
1216 get { return (flags & Flags.Unchecked) != 0; }
1217 set { flags |= Flags.Unchecked; }
1220 public bool Unsafe {
1221 get { return (flags & Flags.Unsafe) != 0; }
1222 set { flags |= Flags.Unsafe; }
1226 // The statements in this block
1228 ArrayList statements;
1232 // An array of Blocks. We keep track of children just
1233 // to generate the local variable declarations.
1235 // Statements and child statements are handled through the
1241 // Labels. (label, block) pairs.
1246 // Keeps track of (name, type) pairs
1248 Hashtable variables;
1251 // Keeps track of constants
1252 Hashtable constants;
1255 // Temporary variables.
1257 ArrayList temporary_variables;
1260 // If this is a switch section, the enclosing switch block.
1264 protected static int id;
1268 public Block (Block parent)
1269 : this (parent, (Flags) 0, Location.Null, Location.Null)
1272 public Block (Block parent, Flags flags)
1273 : this (parent, flags, Location.Null, Location.Null)
1276 public Block (Block parent, Location start, Location end)
1277 : this (parent, (Flags) 0, start, end)
1280 public Block (Block parent, Flags flags, Location start, Location end)
1283 parent.AddChild (this);
1285 this.Parent = parent;
1287 this.StartLocation = start;
1288 this.EndLocation = end;
1291 statements = new ArrayList ();
1293 if ((flags & Flags.IsToplevel) != 0)
1294 Toplevel = (ToplevelBlock) this;
1296 Toplevel = parent.Toplevel;
1298 if (parent != null && Implicit) {
1299 if (parent.known_variables == null)
1300 parent.known_variables = new Hashtable ();
1301 // share with parent
1302 known_variables = parent.known_variables;
1307 public Block CreateSwitchBlock (Location start)
1309 Block new_block = new Block (this, start, start);
1310 new_block.switch_block = this;
1315 get { return this_id; }
1318 protected Hashtable Variables {
1320 if (variables == null)
1321 variables = new Hashtable ();
1326 void AddChild (Block b)
1328 if (children == null)
1329 children = new ArrayList ();
1334 public void SetEndLocation (Location loc)
1340 /// Adds a label to the current block.
1344 /// false if the name already exists in this block. true
1348 public bool AddLabel (string name, LabeledStatement target, Location loc)
1350 if (switch_block != null)
1351 return switch_block.AddLabel (name, target, loc);
1354 while (cur != null) {
1355 if (cur.DoLookupLabel (name) != null) {
1357 140, loc, "The label `{0}' is a duplicate",
1368 while (cur != null) {
1369 if (cur.DoLookupLabel (name) != null) {
1372 "The label `{0}' shadows another label " +
1373 "by the same name in a contained scope.",
1378 if (children != null) {
1379 foreach (Block b in children) {
1380 LabeledStatement s = b.DoLookupLabel (name);
1386 "The label `{0}' shadows another " +
1387 "label by the same name in a " +
1399 labels = new Hashtable ();
1401 labels.Add (name, target);
1405 public LabeledStatement LookupLabel (string name)
1407 LabeledStatement s = DoLookupLabel (name);
1411 if (children == null)
1414 foreach (Block child in children) {
1415 if (!child.Implicit)
1418 s = child.LookupLabel (name);
1426 LabeledStatement DoLookupLabel (string name)
1428 if (switch_block != null)
1429 return switch_block.LookupLabel (name);
1432 if (labels.Contains (name))
1433 return ((LabeledStatement) labels [name]);
1438 Hashtable known_variables;
1441 // Marks a variable with name @name as being used in this or a child block.
1442 // If a variable name has been used in a child block, it's illegal to
1443 // declare a variable with the same name in the current block.
1445 void AddKnownVariable (string name, LocalInfo info)
1447 if (known_variables == null)
1448 known_variables = new Hashtable ();
1450 known_variables [name] = info;
1453 LocalInfo GetKnownVariableInfo (string name)
1455 if (known_variables == null)
1457 return (LocalInfo) known_variables [name];
1460 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1463 LocalInfo kvi = b.GetKnownVariableInfo (name);
1464 while (kvi == null) {
1470 kvi = b.GetKnownVariableInfo (name);
1476 // Is kvi.Block nested inside 'b'
1477 if (b.known_variables != kvi.Block.known_variables) {
1479 // If a variable by the same name it defined in a nested block of this
1480 // block, we violate the invariant meaning in a block.
1483 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1484 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1489 // It's ok if the definition is in a nested subblock of b, but not
1490 // nested inside this block -- a definition in a sibling block
1491 // should not affect us.
1497 // Block 'b' and kvi.Block are the same textual block.
1498 // However, different variables are extant.
1500 // Check if the variable is in scope in both blocks. We use
1501 // an indirect check that depends on AddVariable doing its
1502 // part in maintaining the invariant-meaning-in-block property.
1504 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1508 // Even though we detected the error when the name is used, we
1509 // treat it as if the variable declaration was in error.
1511 Report.SymbolRelatedToPreviousError (loc, name);
1512 Error_AlreadyDeclared (kvi.Location, name, "child");
1516 public LocalInfo AddVariable (Expression type, string name, Location l)
1518 LocalInfo vi = GetLocalInfo (name);
1520 Report.SymbolRelatedToPreviousError (vi.Location, name);
1521 if (known_variables == vi.Block.known_variables)
1522 Report.Error (128, l,
1523 "A local variable named `{0}' is already defined in this scope", name);
1525 Error_AlreadyDeclared (l, name, "parent");
1529 vi = GetKnownVariableInfo (name);
1531 Report.SymbolRelatedToPreviousError (vi.Location, name);
1532 Error_AlreadyDeclared (l, name, "child");
1537 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1539 Report.SymbolRelatedToPreviousError (p.Location, name);
1540 Error_AlreadyDeclared (l, name, "method argument");
1544 vi = new LocalInfo (type, name, this, l);
1546 Variables.Add (name, vi);
1548 for (Block b = this; b != null; b = b.Parent)
1549 b.AddKnownVariable (name, vi);
1551 if ((flags & Flags.VariablesInitialized) != 0)
1552 throw new Exception ();
1557 void Error_AlreadyDeclared (Location loc, string var, string reason)
1559 Report.Error (136, loc, "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning to `{0}', " +
1560 "which is already used in a `{1}' scope", var, reason);
1563 public bool AddConstant (Expression type, string name, Expression value, Location l)
1565 if (AddVariable (type, name, l) == null)
1568 if (constants == null)
1569 constants = new Hashtable ();
1571 constants.Add (name, value);
1575 static int next_temp_id = 0;
1577 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1579 if (temporary_variables == null)
1580 temporary_variables = new ArrayList ();
1582 int id = ++next_temp_id;
1583 string name = "$s_" + id.ToString ();
1585 LocalInfo li = new LocalInfo (te, name, this, loc);
1586 li.CompilerGenerated = true;
1587 temporary_variables.Add (li);
1591 public LocalInfo GetLocalInfo (string name)
1593 for (Block b = this; b != null; b = b.Parent) {
1594 if (b.variables != null) {
1595 LocalInfo ret = b.variables [name] as LocalInfo;
1603 public Expression GetVariableType (string name)
1605 LocalInfo vi = GetLocalInfo (name);
1606 return vi == null ? null : vi.Type;
1609 public Expression GetConstantExpression (string name)
1611 for (Block b = this; b != null; b = b.Parent) {
1612 if (b.constants != null) {
1613 Expression ret = b.constants [name] as Expression;
1622 /// True if the variable named @name is a constant
1624 public bool IsConstant (string name)
1626 Expression e = GetConstantExpression (name);
1630 public void AddStatement (Statement s)
1633 flags |= Flags.BlockUsed;
1637 get { return (flags & Flags.BlockUsed) != 0; }
1642 flags |= Flags.BlockUsed;
1645 public bool HasRet {
1646 get { return (flags & Flags.HasRet) != 0; }
1649 public bool IsDestructor {
1650 get { return (flags & Flags.IsDestructor) != 0; }
1653 public void SetDestructor ()
1655 flags |= Flags.IsDestructor;
1658 VariableMap param_map, local_map;
1660 public VariableMap ParameterMap {
1662 if ((flags & Flags.VariablesInitialized) == 0)
1663 throw new Exception ("Variables have not been initialized yet");
1669 public VariableMap LocalMap {
1671 if ((flags & Flags.VariablesInitialized) == 0)
1672 throw new Exception ("Variables have not been initialized yet");
1679 /// Emits the variable declarations and labels.
1682 /// tc: is our typecontainer (to resolve type references)
1683 /// ig: is the code generator:
1685 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1687 bool old_unsafe = ec.InUnsafe;
1689 // If some parent block was unsafe, we remain unsafe even if this block
1690 // isn't explicitly marked as such.
1691 ec.InUnsafe |= Unsafe;
1694 // Compute the VariableMap's.
1696 // Unfortunately, we don't know the type when adding variables with
1697 // AddVariable(), so we need to compute this info here.
1701 if (variables != null) {
1702 foreach (LocalInfo li in variables.Values)
1705 locals = new LocalInfo [variables.Count];
1706 variables.Values.CopyTo (locals, 0);
1708 locals = new LocalInfo [0];
1711 local_map = new VariableMap (Parent.LocalMap, locals);
1713 local_map = new VariableMap (locals);
1715 param_map = new VariableMap (ip);
1716 flags |= Flags.VariablesInitialized;
1718 bool old_check_state = ec.ConstantCheckState;
1719 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1722 // Process this block variables
1724 if (variables != null){
1725 foreach (DictionaryEntry de in variables){
1726 string name = (string) de.Key;
1727 LocalInfo vi = (LocalInfo) de.Value;
1729 if (vi.VariableType == null)
1732 Type variable_type = vi.VariableType;
1734 if (variable_type.IsPointer){
1736 // Am not really convinced that this test is required (Microsoft does it)
1737 // but the fact is that you would not be able to use the pointer variable
1740 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1745 if (constants == null)
1748 Expression cv = (Expression) constants [name];
1752 ec.CurrentBlock = this;
1753 Expression e = cv.Resolve (ec);
1755 Constant ce = e as Constant;
1757 Const.Error_ExpressionMustBeConstant (vi.Location, name);
1761 if (e.Type != variable_type){
1762 e = Const.ChangeType (vi.Location, ce, variable_type);
1767 constants.Remove (name);
1768 constants.Add (name, e);
1771 ec.ConstantCheckState = old_check_state;
1774 // Now, handle the children
1776 if (children != null){
1777 foreach (Block b in children)
1778 b.ResolveMeta (toplevel, ec, ip);
1780 ec.InUnsafe = old_unsafe;
1784 // Emits the local variable declarations for a block
1786 public void EmitMeta (EmitContext ec)
1788 ILGenerator ig = ec.ig;
1790 if (variables != null){
1791 bool have_captured_vars = ec.HaveCapturedVariables ();
1793 foreach (DictionaryEntry de in variables){
1794 LocalInfo vi = (LocalInfo) de.Value;
1796 if (have_captured_vars && ec.IsCaptured (vi))
1801 // This is needed to compile on both .NET 1.x and .NET 2.x
1802 // the later introduced `DeclareLocal (Type t, bool pinned)'
1804 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1805 else if (!vi.IsThis)
1806 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1810 if (temporary_variables != null) {
1811 AnonymousContainer am = ec.CurrentAnonymousMethod;
1812 TypeBuilder scope = null;
1813 if ((am != null) && am.IsIterator) {
1814 scope = am.Scope.ScopeTypeBuilder;
1816 throw new InternalErrorException ();
1818 foreach (LocalInfo vi in temporary_variables) {
1819 if (scope != null) {
1820 if (vi.FieldBuilder == null)
1821 vi.FieldBuilder = scope.DefineField (
1822 vi.Name, vi.VariableType, FieldAttributes.Assembly);
1824 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1828 if (children != null){
1829 foreach (Block b in children)
1834 void UsageWarning (FlowBranching.UsageVector vector)
1838 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1839 foreach (DictionaryEntry de in variables){
1840 LocalInfo vi = (LocalInfo) de.Value;
1845 name = (string) de.Key;
1847 if (vector.IsAssigned (vi.VariableInfo)){
1848 Report.Warning (219, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
1850 Report.Warning (168, vi.Location, "The variable `{0}' is declared but never used", name);
1856 bool unreachable_shown;
1859 public override bool Resolve (EmitContext ec)
1861 Block prev_block = ec.CurrentBlock;
1864 int errors = Report.Errors;
1866 ec.CurrentBlock = this;
1867 ec.StartFlowBranching (this);
1869 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1871 int statement_count = statements.Count;
1872 for (int ix = 0; ix < statement_count; ix++){
1873 Statement s = (Statement) statements [ix];
1876 // Warn if we detect unreachable code.
1880 ((Block) s).unreachable = true;
1882 if (!unreachable_shown && (RootContext.WarningLevel >= 2)) {
1884 162, loc, "Unreachable code detected");
1885 unreachable_shown = true;
1890 // Note that we're not using ResolveUnreachable() for unreachable
1891 // statements here. ResolveUnreachable() creates a temporary
1892 // flow branching and kills it afterwards. This leads to problems
1893 // if you have two unreachable statements where the first one
1894 // assigns a variable and the second one tries to access it.
1897 if (!s.Resolve (ec)) {
1899 statements [ix] = EmptyStatement.Value;
1903 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1904 statements [ix] = EmptyStatement.Value;
1906 num_statements = ix + 1;
1907 if (s is LabeledStatement)
1908 unreachable = false;
1910 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1913 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1914 ec.CurrentBranching, statement_count, num_statements);
1916 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1918 ec.CurrentBlock = prev_block;
1920 // If we're a non-static `struct' constructor which doesn't have an
1921 // initializer, then we must initialize all of the struct's fields.
1922 if ((flags & Flags.IsToplevel) != 0 &&
1923 !Toplevel.IsThisAssigned (ec) &&
1924 vector.Reachability.Throws != FlowBranching.FlowReturns.Always)
1927 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1928 foreach (LabeledStatement label in labels.Values)
1929 if (!label.HasBeenReferenced)
1930 Report.Warning (164, label.loc,
1931 "This label has not been referenced");
1934 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1936 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1937 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1938 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1939 flags |= Flags.HasRet;
1941 if (ok && (errors == Report.Errors)) {
1942 if (RootContext.WarningLevel >= 3)
1943 UsageWarning (vector);
1949 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1951 unreachable_shown = true;
1954 if (warn && (RootContext.WarningLevel >= 2))
1955 Report.Warning (162, loc, "Unreachable code detected");
1957 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1958 bool ok = Resolve (ec);
1959 ec.KillFlowBranching ();
1964 protected override void DoEmit (EmitContext ec)
1966 for (int ix = 0; ix < num_statements; ix++){
1967 Statement s = (Statement) statements [ix];
1969 // Check whether we are the last statement in a
1972 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
1973 ec.IsLastStatement = true;
1975 ec.IsLastStatement = false;
1981 public override void Emit (EmitContext ec)
1983 Block prev_block = ec.CurrentBlock;
1985 ec.CurrentBlock = this;
1987 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1988 bool is_lexical_block = !Implicit && (Parent != null);
1990 if (emit_debug_info) {
1991 if (is_lexical_block)
1994 if (variables != null) {
1995 foreach (DictionaryEntry de in variables) {
1996 string name = (string) de.Key;
1997 LocalInfo vi = (LocalInfo) de.Value;
1999 if (vi.LocalBuilder == null)
2002 ec.DefineLocalVariable (name, vi.LocalBuilder);
2007 ec.Mark (StartLocation, true);
2009 ec.Mark (EndLocation, true);
2011 if (emit_debug_info && is_lexical_block)
2014 ec.CurrentBlock = prev_block;
2018 // Returns true if we ar ea child of `b'.
2020 public bool IsChildOf (Block b)
2022 Block current = this;
2025 if (current.Parent == b)
2027 current = current.Parent;
2028 } while (current != null);
2032 public override string ToString ()
2034 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2039 // A toplevel block contains extra information, the split is done
2040 // only to separate information that would otherwise bloat the more
2041 // lightweight Block.
2043 // In particular, this was introduced when the support for Anonymous
2044 // Methods was implemented.
2046 public class ToplevelBlock : Block {
2048 // Pointer to the host of this anonymous method, or null
2049 // if we are the topmost block
2051 ToplevelBlock container;
2052 CaptureContext capture_context;
2053 FlowBranching top_level_branching;
2055 Hashtable capture_contexts;
2058 public bool HasVarargs {
2059 get { return (flags & Flags.HasVarargs) != 0; }
2060 set { flags |= Flags.HasVarargs; }
2064 // The parameters for the block.
2066 public readonly Parameters Parameters;
2068 public void RegisterCaptureContext (CaptureContext cc)
2070 if (capture_contexts == null)
2071 capture_contexts = new Hashtable ();
2072 capture_contexts [cc] = cc;
2075 public void CompleteContexts ()
2077 if (capture_contexts == null)
2080 foreach (CaptureContext cc in capture_contexts.Keys){
2085 public CaptureContext ToplevelBlockCaptureContext {
2086 get { return capture_context; }
2089 public ToplevelBlock Container {
2090 get { return container; }
2093 protected void AddChild (ToplevelBlock block)
2095 if (children == null)
2096 children = new ArrayList ();
2098 children.Add (block);
2102 // Parent is only used by anonymous blocks to link back to their
2105 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2106 this (container, (Flags) 0, parameters, start)
2110 public ToplevelBlock (Parameters parameters, Location start) :
2111 this (null, (Flags) 0, parameters, start)
2115 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2116 this (null, flags, parameters, start)
2120 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2121 base (null, flags | Flags.IsToplevel, start, Location.Null)
2123 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2124 this.container = container;
2126 if (container != null)
2127 container.AddChild (this);
2130 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2134 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2136 if (capture_context == null)
2137 capture_context = new CaptureContext (this, loc, host);
2140 public CaptureContext CaptureContext {
2141 get { return capture_context; }
2144 public FlowBranching TopLevelBranching {
2145 get { return top_level_branching; }
2149 // This is used if anonymous methods are used inside an iterator
2150 // (see 2test-22.cs for an example).
2152 // The AnonymousMethod is created while parsing - at a time when we don't
2153 // know yet that we're inside an iterator, so it's `Container' is initially
2154 // null. Later on, when resolving the iterator, we need to move the
2155 // anonymous method into that iterator.
2157 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2159 foreach (ToplevelBlock block in children) {
2160 if (block.CaptureContext == null)
2163 block.container = new_parent;
2164 block.CaptureContext.ReParent (new_parent, new_host);
2169 // Returns a `ParameterReference' for the given name, or null if there
2170 // is no such parameter
2172 public ParameterReference GetParameterReference (string name, Location loc)
2177 for (ToplevelBlock t = this; t != null; t = t.Container) {
2178 Parameters pars = t.Parameters;
2179 par = pars.GetParameterByName (name, out idx);
2181 return new ParameterReference (pars, this, idx, name, loc);
2187 // Whether the parameter named `name' is local to this block,
2188 // or false, if the parameter belongs to an encompassing block.
2190 public bool IsLocalParameter (string name)
2192 return Parameters.GetParameterByName (name) != null;
2196 // Whether the `name' is a parameter reference
2198 public bool IsParameterReference (string name)
2200 for (ToplevelBlock t = this; t != null; t = t.Container) {
2201 if (t.IsLocalParameter (name))
2207 LocalInfo this_variable = null;
2210 // Returns the "this" instance variable of this block.
2211 // See AddThisVariable() for more information.
2213 public LocalInfo ThisVariable {
2214 get { return this_variable; }
2219 // This is used by non-static `struct' constructors which do not have an
2220 // initializer - in this case, the constructor must initialize all of the
2221 // struct's fields. To do this, we add a "this" variable and use the flow
2222 // analysis code to ensure that it's been fully initialized before control
2223 // leaves the constructor.
2225 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
2227 if (this_variable == null) {
2228 this_variable = new LocalInfo (tc, this, l);
2229 this_variable.Used = true;
2230 this_variable.IsThis = true;
2232 Variables.Add ("this", this_variable);
2235 return this_variable;
2238 public bool IsThisAssigned (EmitContext ec)
2240 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2243 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2245 int errors = Report.Errors;
2247 if (top_level_branching != null)
2250 ResolveMeta (this, ec, ip);
2252 top_level_branching = ec.StartFlowBranching (this);
2254 return Report.Errors == errors;
2258 public class SwitchLabel {
2265 Label il_label_code;
2266 bool il_label_code_set;
2269 // if expr == null, then it is the default case.
2271 public SwitchLabel (Expression expr, Location l)
2277 public Expression Label {
2283 public object Converted {
2289 public Label GetILLabel (EmitContext ec)
2292 il_label = ec.ig.DefineLabel ();
2293 il_label_set = true;
2298 public Label GetILLabelCode (EmitContext ec)
2300 if (!il_label_code_set){
2301 il_label_code = ec.ig.DefineLabel ();
2302 il_label_code_set = true;
2304 return il_label_code;
2308 // Resolves the expression, reduces it to a literal if possible
2309 // and then converts it to the requested type.
2311 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2313 Expression e = label.Resolve (ec);
2318 Constant c = e as Constant;
2320 Report.Error (150, loc, "A constant value is expected");
2324 if (required_type == TypeManager.string_type) {
2325 if (c.Type == TypeManager.string_type) {
2326 converted = c.GetValue ();
2330 if (e is NullLiteral) {
2336 converted = Expression.ConvertIntLiteral (c, required_type, loc);
2337 return converted != null;
2340 public void Erorr_AlreadyOccurs ()
2343 if (converted == null)
2345 else if (converted is NullLiteral)
2348 label = converted.ToString ();
2350 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2354 public class SwitchSection {
2355 // An array of SwitchLabels.
2356 public readonly ArrayList Labels;
2357 public readonly Block Block;
2359 public SwitchSection (ArrayList labels, Block block)
2366 public class Switch : Statement {
2367 public readonly ArrayList Sections;
2368 public Expression Expr;
2371 /// Maps constants whose type type SwitchType to their SwitchLabels.
2373 public IDictionary Elements;
2376 /// The governing switch type
2378 public Type SwitchType;
2383 Label default_target;
2384 Expression new_expr;
2386 SwitchSection constant_section;
2387 SwitchSection default_section;
2390 // The types allowed to be implicitly cast from
2391 // on the governing type
2393 static Type [] allowed_types;
2395 public Switch (Expression e, ArrayList sects, Location l)
2402 public bool GotDefault {
2404 return default_section != null;
2408 public Label DefaultTarget {
2410 return default_target;
2415 // Determines the governing type for a switch. The returned
2416 // expression might be the expression from the switch, or an
2417 // expression that includes any potential conversions to the
2418 // integral types or to string.
2420 Expression SwitchGoverningType (EmitContext ec, Type t)
2422 if (t == TypeManager.byte_type ||
2423 t == TypeManager.sbyte_type ||
2424 t == TypeManager.ushort_type ||
2425 t == TypeManager.short_type ||
2426 t == TypeManager.uint32_type ||
2427 t == TypeManager.int32_type ||
2428 t == TypeManager.uint64_type ||
2429 t == TypeManager.int64_type ||
2430 t == TypeManager.char_type ||
2431 t == TypeManager.string_type ||
2432 t == TypeManager.bool_type ||
2433 t.IsSubclassOf (TypeManager.enum_type))
2436 if (allowed_types == null){
2437 allowed_types = new Type [] {
2438 TypeManager.sbyte_type,
2439 TypeManager.byte_type,
2440 TypeManager.short_type,
2441 TypeManager.ushort_type,
2442 TypeManager.int32_type,
2443 TypeManager.uint32_type,
2444 TypeManager.int64_type,
2445 TypeManager.uint64_type,
2446 TypeManager.char_type,
2447 TypeManager.string_type,
2448 TypeManager.bool_type
2453 // Try to find a *user* defined implicit conversion.
2455 // If there is no implicit conversion, or if there are multiple
2456 // conversions, we have to report an error
2458 Expression converted = null;
2459 foreach (Type tt in allowed_types){
2462 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2467 // Ignore over-worked ImplicitUserConversions that do
2468 // an implicit conversion in addition to the user conversion.
2470 if (!(e is UserCast))
2473 if (converted != null){
2474 Report.ExtraInformation (
2476 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2477 TypeManager.CSharpName (Expr.Type)));
2487 // Performs the basic sanity checks on the switch statement
2488 // (looks for duplicate keys and non-constant expressions).
2490 // It also returns a hashtable with the keys that we will later
2491 // use to compute the switch tables
2493 bool CheckSwitch (EmitContext ec)
2496 Elements = Sections.Count > 10 ?
2497 (IDictionary)new Hashtable () :
2498 (IDictionary)new ListDictionary ();
2500 foreach (SwitchSection ss in Sections){
2501 foreach (SwitchLabel sl in ss.Labels){
2502 if (sl.Label == null){
2503 if (default_section != null){
2504 sl.Erorr_AlreadyOccurs ();
2507 default_section = ss;
2511 if (!sl.ResolveAndReduce (ec, SwitchType)){
2516 object key = sl.Converted;
2518 Elements.Add (key, sl);
2520 catch (ArgumentException) {
2521 sl.Erorr_AlreadyOccurs ();
2529 void EmitObjectInteger (ILGenerator ig, object k)
2532 IntConstant.EmitInt (ig, (int) k);
2533 else if (k is Constant) {
2534 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2537 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2540 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2542 IntConstant.EmitInt (ig, (int) (long) k);
2543 ig.Emit (OpCodes.Conv_I8);
2546 LongConstant.EmitLong (ig, (long) k);
2548 else if (k is ulong)
2550 if ((ulong) k < (1L<<32))
2552 IntConstant.EmitInt (ig, (int) (long) k);
2553 ig.Emit (OpCodes.Conv_U8);
2557 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2561 IntConstant.EmitInt (ig, (int) ((char) k));
2562 else if (k is sbyte)
2563 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2565 IntConstant.EmitInt (ig, (int) ((byte) k));
2566 else if (k is short)
2567 IntConstant.EmitInt (ig, (int) ((short) k));
2568 else if (k is ushort)
2569 IntConstant.EmitInt (ig, (int) ((ushort) k));
2571 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2573 throw new Exception ("Unhandled case");
2576 // structure used to hold blocks of keys while calculating table switch
2577 class KeyBlock : IComparable
2579 public KeyBlock (long _nFirst)
2581 nFirst = nLast = _nFirst;
2585 public ArrayList rgKeys = null;
2586 // how many items are in the bucket
2587 public int Size = 1;
2590 get { return (int) (nLast - nFirst + 1); }
2592 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2594 return kbLast.nLast - kbFirst.nFirst + 1;
2596 public int CompareTo (object obj)
2598 KeyBlock kb = (KeyBlock) obj;
2599 int nLength = Length;
2600 int nLengthOther = kb.Length;
2601 if (nLengthOther == nLength)
2602 return (int) (kb.nFirst - nFirst);
2603 return nLength - nLengthOther;
2608 /// This method emits code for a lookup-based switch statement (non-string)
2609 /// Basically it groups the cases into blocks that are at least half full,
2610 /// and then spits out individual lookup opcodes for each block.
2611 /// It emits the longest blocks first, and short blocks are just
2612 /// handled with direct compares.
2614 /// <param name="ec"></param>
2615 /// <param name="val"></param>
2616 /// <returns></returns>
2617 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2619 int cElements = Elements.Count;
2620 object [] rgKeys = new object [cElements];
2621 Elements.Keys.CopyTo (rgKeys, 0);
2622 Array.Sort (rgKeys);
2624 // initialize the block list with one element per key
2625 ArrayList rgKeyBlocks = new ArrayList ();
2626 foreach (object key in rgKeys)
2627 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2630 // iteratively merge the blocks while they are at least half full
2631 // there's probably a really cool way to do this with a tree...
2632 while (rgKeyBlocks.Count > 1)
2634 ArrayList rgKeyBlocksNew = new ArrayList ();
2635 kbCurr = (KeyBlock) rgKeyBlocks [0];
2636 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2638 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2639 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2642 kbCurr.nLast = kb.nLast;
2643 kbCurr.Size += kb.Size;
2647 // start a new block
2648 rgKeyBlocksNew.Add (kbCurr);
2652 rgKeyBlocksNew.Add (kbCurr);
2653 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2655 rgKeyBlocks = rgKeyBlocksNew;
2658 // initialize the key lists
2659 foreach (KeyBlock kb in rgKeyBlocks)
2660 kb.rgKeys = new ArrayList ();
2662 // fill the key lists
2664 if (rgKeyBlocks.Count > 0) {
2665 kbCurr = (KeyBlock) rgKeyBlocks [0];
2666 foreach (object key in rgKeys)
2668 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2669 System.Convert.ToInt64 (key) > kbCurr.nLast;
2671 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2672 kbCurr.rgKeys.Add (key);
2676 // sort the blocks so we can tackle the largest ones first
2677 rgKeyBlocks.Sort ();
2679 // okay now we can start...
2680 ILGenerator ig = ec.ig;
2681 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2682 Label lblDefault = ig.DefineLabel ();
2684 Type typeKeys = null;
2685 if (rgKeys.Length > 0)
2686 typeKeys = rgKeys [0].GetType (); // used for conversions
2690 if (TypeManager.IsEnumType (SwitchType))
2691 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2693 compare_type = SwitchType;
2695 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2697 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2698 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2701 foreach (object key in kb.rgKeys)
2703 ig.Emit (OpCodes.Ldloc, val);
2704 EmitObjectInteger (ig, key);
2705 SwitchLabel sl = (SwitchLabel) Elements [key];
2706 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2711 // TODO: if all the keys in the block are the same and there are
2712 // no gaps/defaults then just use a range-check.
2713 if (compare_type == TypeManager.int64_type ||
2714 compare_type == TypeManager.uint64_type)
2716 // TODO: optimize constant/I4 cases
2718 // check block range (could be > 2^31)
2719 ig.Emit (OpCodes.Ldloc, val);
2720 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2721 ig.Emit (OpCodes.Blt, lblDefault);
2722 ig.Emit (OpCodes.Ldloc, val);
2723 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2724 ig.Emit (OpCodes.Bgt, lblDefault);
2727 ig.Emit (OpCodes.Ldloc, val);
2730 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2731 ig.Emit (OpCodes.Sub);
2733 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2738 ig.Emit (OpCodes.Ldloc, val);
2739 int nFirst = (int) kb.nFirst;
2742 IntConstant.EmitInt (ig, nFirst);
2743 ig.Emit (OpCodes.Sub);
2745 else if (nFirst < 0)
2747 IntConstant.EmitInt (ig, -nFirst);
2748 ig.Emit (OpCodes.Add);
2752 // first, build the list of labels for the switch
2754 int cJumps = kb.Length;
2755 Label [] rgLabels = new Label [cJumps];
2756 for (int iJump = 0; iJump < cJumps; iJump++)
2758 object key = kb.rgKeys [iKey];
2759 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2761 SwitchLabel sl = (SwitchLabel) Elements [key];
2762 rgLabels [iJump] = sl.GetILLabel (ec);
2766 rgLabels [iJump] = lblDefault;
2768 // emit the switch opcode
2769 ig.Emit (OpCodes.Switch, rgLabels);
2772 // mark the default for this block
2774 ig.MarkLabel (lblDefault);
2777 // TODO: find the default case and emit it here,
2778 // to prevent having to do the following jump.
2779 // make sure to mark other labels in the default section
2781 // the last default just goes to the end
2782 ig.Emit (OpCodes.Br, lblDefault);
2784 // now emit the code for the sections
2785 bool fFoundDefault = false;
2786 foreach (SwitchSection ss in Sections)
2788 foreach (SwitchLabel sl in ss.Labels)
2790 ig.MarkLabel (sl.GetILLabel (ec));
2791 ig.MarkLabel (sl.GetILLabelCode (ec));
2792 if (sl.Label == null)
2794 ig.MarkLabel (lblDefault);
2795 fFoundDefault = true;
2799 //ig.Emit (OpCodes.Br, lblEnd);
2802 if (!fFoundDefault) {
2803 ig.MarkLabel (lblDefault);
2805 ig.MarkLabel (lblEnd);
2808 // This simple emit switch works, but does not take advantage of the
2810 // TODO: remove non-string logic from here
2811 // TODO: binary search strings?
2813 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2815 ILGenerator ig = ec.ig;
2816 Label end_of_switch = ig.DefineLabel ();
2817 Label next_test = ig.DefineLabel ();
2818 Label null_target = ig.DefineLabel ();
2819 bool first_test = true;
2820 bool pending_goto_end = false;
2821 bool null_marked = false;
2824 ig.Emit (OpCodes.Ldloc, val);
2826 if (Elements.Contains (NullLiteral.Null)){
2827 ig.Emit (OpCodes.Brfalse, null_target);
2829 ig.Emit (OpCodes.Brfalse, default_target);
2831 ig.Emit (OpCodes.Ldloc, val);
2832 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2833 ig.Emit (OpCodes.Stloc, val);
2835 int section_count = Sections.Count;
2836 for (int section = 0; section < section_count; section++){
2837 SwitchSection ss = (SwitchSection) Sections [section];
2839 if (ss == default_section)
2842 Label sec_begin = ig.DefineLabel ();
2844 ig.Emit (OpCodes.Nop);
2846 if (pending_goto_end)
2847 ig.Emit (OpCodes.Br, end_of_switch);
2849 int label_count = ss.Labels.Count;
2851 for (int label = 0; label < label_count; label++){
2852 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2853 ig.MarkLabel (sl.GetILLabel (ec));
2856 ig.MarkLabel (next_test);
2857 next_test = ig.DefineLabel ();
2860 // If we are the default target
2862 if (sl.Label != null){
2863 object lit = sl.Converted;
2865 if (lit is NullLiteral){
2867 if (label_count == 1)
2868 ig.Emit (OpCodes.Br, next_test);
2872 ig.Emit (OpCodes.Ldloc, val);
2873 ig.Emit (OpCodes.Ldstr, (string)lit);
2874 if (label_count == 1)
2875 ig.Emit (OpCodes.Bne_Un, next_test);
2877 if (label+1 == label_count)
2878 ig.Emit (OpCodes.Bne_Un, next_test);
2880 ig.Emit (OpCodes.Beq, sec_begin);
2885 ig.MarkLabel (null_target);
2888 ig.MarkLabel (sec_begin);
2889 foreach (SwitchLabel sl in ss.Labels)
2890 ig.MarkLabel (sl.GetILLabelCode (ec));
2893 pending_goto_end = !ss.Block.HasRet;
2896 ig.MarkLabel (next_test);
2897 ig.MarkLabel (default_target);
2899 ig.MarkLabel (null_target);
2900 if (default_section != null)
2901 default_section.Block.Emit (ec);
2902 ig.MarkLabel (end_of_switch);
2905 SwitchSection FindSection (SwitchLabel label)
2907 foreach (SwitchSection ss in Sections){
2908 foreach (SwitchLabel sl in ss.Labels){
2917 public override bool Resolve (EmitContext ec)
2919 Expr = Expr.Resolve (ec);
2923 new_expr = SwitchGoverningType (ec, Expr.Type);
2924 if (new_expr == null){
2925 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2930 SwitchType = new_expr.Type;
2932 if (!CheckSwitch (ec))
2935 Switch old_switch = ec.Switch;
2937 ec.Switch.SwitchType = SwitchType;
2939 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2940 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2942 is_constant = new_expr is Constant;
2944 object key = ((Constant) new_expr).GetValue ();
2945 SwitchLabel label = (SwitchLabel) Elements [key];
2947 constant_section = FindSection (label);
2948 if (constant_section == null)
2949 constant_section = default_section;
2953 foreach (SwitchSection ss in Sections){
2955 ec.CurrentBranching.CreateSibling (
2956 null, FlowBranching.SiblingType.SwitchSection);
2960 if (is_constant && (ss != constant_section)) {
2961 // If we're a constant switch, we're only emitting
2962 // one single section - mark all the others as
2964 ec.CurrentBranching.CurrentUsageVector.Goto ();
2965 if (!ss.Block.ResolveUnreachable (ec, true))
2968 if (!ss.Block.Resolve (ec))
2973 if (default_section == null)
2974 ec.CurrentBranching.CreateSibling (
2975 null, FlowBranching.SiblingType.SwitchSection);
2977 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2978 ec.Switch = old_switch;
2980 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2986 protected override void DoEmit (EmitContext ec)
2988 ILGenerator ig = ec.ig;
2990 // Store variable for comparission purposes
2993 value = ig.DeclareLocal (SwitchType);
2995 ig.Emit (OpCodes.Stloc, value);
2999 default_target = ig.DefineLabel ();
3002 // Setup the codegen context
3004 Label old_end = ec.LoopEnd;
3005 Switch old_switch = ec.Switch;
3007 ec.LoopEnd = ig.DefineLabel ();
3012 if (constant_section != null)
3013 constant_section.Block.Emit (ec);
3014 } else if (SwitchType == TypeManager.string_type)
3015 SimpleSwitchEmit (ec, value);
3017 TableSwitchEmit (ec, value);
3019 // Restore context state.
3020 ig.MarkLabel (ec.LoopEnd);
3023 // Restore the previous context
3025 ec.LoopEnd = old_end;
3026 ec.Switch = old_switch;
3030 public abstract class ExceptionStatement : Statement
3032 public abstract void EmitFinally (EmitContext ec);
3034 protected bool emit_finally = true;
3035 ArrayList parent_vectors;
3037 protected void DoEmitFinally (EmitContext ec)
3040 ec.ig.BeginFinallyBlock ();
3041 else if (ec.InIterator)
3042 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3046 protected void ResolveFinally (FlowBranchingException branching)
3048 emit_finally = branching.EmitFinally;
3050 branching.Parent.StealFinallyClauses (ref parent_vectors);
3054 public class Lock : ExceptionStatement {
3056 Statement Statement;
3059 public Lock (Expression expr, Statement stmt, Location l)
3066 public override bool Resolve (EmitContext ec)
3068 expr = expr.Resolve (ec);
3072 if (expr.Type.IsValueType){
3073 Report.Error (185, loc,
3074 "`{0}' is not a reference type as required by the lock statement",
3075 TypeManager.CSharpName (expr.Type));
3079 FlowBranchingException branching = ec.StartFlowBranching (this);
3080 bool ok = Statement.Resolve (ec);
3082 ec.KillFlowBranching ();
3086 ResolveFinally (branching);
3088 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3089 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3090 // Unfortunately, System.Reflection.Emit automatically emits
3091 // a leave to the end of the finally block.
3092 // This is a problem if `returns' is true since we may jump
3093 // to a point after the end of the method.
3094 // As a workaround, emit an explicit ret here.
3095 ec.NeedReturnLabel ();
3101 protected override void DoEmit (EmitContext ec)
3103 Type type = expr.Type;
3105 ILGenerator ig = ec.ig;
3106 temp = ig.DeclareLocal (type);
3109 ig.Emit (OpCodes.Dup);
3110 ig.Emit (OpCodes.Stloc, temp);
3111 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3115 ig.BeginExceptionBlock ();
3116 Statement.Emit (ec);
3121 ig.EndExceptionBlock ();
3124 public override void EmitFinally (EmitContext ec)
3126 ILGenerator ig = ec.ig;
3127 ig.Emit (OpCodes.Ldloc, temp);
3128 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3132 public class Unchecked : Statement {
3133 public readonly Block Block;
3135 public Unchecked (Block b)
3141 public override bool Resolve (EmitContext ec)
3143 bool previous_state = ec.CheckState;
3144 bool previous_state_const = ec.ConstantCheckState;
3146 ec.CheckState = false;
3147 ec.ConstantCheckState = false;
3148 bool ret = Block.Resolve (ec);
3149 ec.CheckState = previous_state;
3150 ec.ConstantCheckState = previous_state_const;
3155 protected override void DoEmit (EmitContext ec)
3157 bool previous_state = ec.CheckState;
3158 bool previous_state_const = ec.ConstantCheckState;
3160 ec.CheckState = false;
3161 ec.ConstantCheckState = false;
3163 ec.CheckState = previous_state;
3164 ec.ConstantCheckState = previous_state_const;
3168 public class Checked : Statement {
3169 public readonly Block Block;
3171 public Checked (Block b)
3174 b.Unchecked = false;
3177 public override bool Resolve (EmitContext ec)
3179 bool previous_state = ec.CheckState;
3180 bool previous_state_const = ec.ConstantCheckState;
3182 ec.CheckState = true;
3183 ec.ConstantCheckState = true;
3184 bool ret = Block.Resolve (ec);
3185 ec.CheckState = previous_state;
3186 ec.ConstantCheckState = previous_state_const;
3191 protected override void DoEmit (EmitContext ec)
3193 bool previous_state = ec.CheckState;
3194 bool previous_state_const = ec.ConstantCheckState;
3196 ec.CheckState = true;
3197 ec.ConstantCheckState = true;
3199 ec.CheckState = previous_state;
3200 ec.ConstantCheckState = previous_state_const;
3204 public class Unsafe : Statement {
3205 public readonly Block Block;
3207 public Unsafe (Block b)
3210 Block.Unsafe = true;
3213 public override bool Resolve (EmitContext ec)
3215 bool previous_state = ec.InUnsafe;
3219 val = Block.Resolve (ec);
3220 ec.InUnsafe = previous_state;
3225 protected override void DoEmit (EmitContext ec)
3227 bool previous_state = ec.InUnsafe;
3231 ec.InUnsafe = previous_state;
3238 public class Fixed : Statement {
3240 ArrayList declarators;
3241 Statement statement;
3246 abstract class Emitter
3248 protected LocalInfo vi;
3249 protected Expression converted;
3251 protected Emitter (Expression expr, LocalInfo li)
3257 public abstract void Emit (EmitContext ec);
3258 public abstract void EmitExit (ILGenerator ig);
3261 class ExpressionEmitter: Emitter {
3262 public ExpressionEmitter (Expression converted, LocalInfo li) :
3263 base (converted, li)
3267 public override void Emit (EmitContext ec) {
3269 // Store pointer in pinned location
3271 converted.Emit (ec);
3272 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3275 public override void EmitExit (ILGenerator ig)
3277 ig.Emit (OpCodes.Ldc_I4_0);
3278 ig.Emit (OpCodes.Conv_U);
3279 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3283 class StringEmitter: Emitter {
3284 LocalBuilder pinned_string;
3287 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3293 public override void Emit (EmitContext ec)
3295 ILGenerator ig = ec.ig;
3296 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3298 converted.Emit (ec);
3299 ig.Emit (OpCodes.Stloc, pinned_string);
3301 Expression sptr = new StringPtr (pinned_string, loc);
3302 converted = Convert.ImplicitConversionRequired (
3303 ec, sptr, vi.VariableType, loc);
3305 if (converted == null)
3308 converted.Emit (ec);
3309 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3312 public override void EmitExit(ILGenerator ig)
3314 ig.Emit (OpCodes.Ldnull);
3315 ig.Emit (OpCodes.Stloc, pinned_string);
3319 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3322 declarators = decls;
3327 public override bool Resolve (EmitContext ec)
3330 Expression.UnsafeError (loc);
3334 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3338 expr_type = texpr.ResolveType (ec);
3340 CheckObsolete (expr_type);
3342 data = new Emitter [declarators.Count];
3344 if (!expr_type.IsPointer){
3345 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3350 foreach (Pair p in declarators){
3351 LocalInfo vi = (LocalInfo) p.First;
3352 Expression e = (Expression) p.Second;
3354 vi.VariableInfo.SetAssigned (ec);
3355 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3358 // The rules for the possible declarators are pretty wise,
3359 // but the production on the grammar is more concise.
3361 // So we have to enforce these rules here.
3363 // We do not resolve before doing the case 1 test,
3364 // because the grammar is explicit in that the token &
3365 // is present, so we need to test for this particular case.
3369 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3374 // Case 1: & object.
3376 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3377 Expression child = ((Unary) e).Expr;
3379 if (child is ParameterReference || child is LocalVariableReference){
3382 "No need to use fixed statement for parameters or " +
3383 "local variable declarations (address is already " +
3388 ec.InFixedInitializer = true;
3390 ec.InFixedInitializer = false;
3394 child = ((Unary) e).Expr;
3396 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3399 data [i] = new ExpressionEmitter (e, vi);
3405 ec.InFixedInitializer = true;
3407 ec.InFixedInitializer = false;
3414 if (e.Type.IsArray){
3415 Type array_type = TypeManager.GetElementType (e.Type);
3418 // Provided that array_type is unmanaged,
3420 if (!TypeManager.VerifyUnManaged (array_type, loc))
3424 // and T* is implicitly convertible to the
3425 // pointer type given in the fixed statement.
3427 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3429 Expression converted = Convert.ImplicitConversionRequired (
3430 ec, array_ptr, vi.VariableType, loc);
3431 if (converted == null)
3434 data [i] = new ExpressionEmitter (converted, vi);
3443 if (e.Type == TypeManager.string_type){
3444 data [i] = new StringEmitter (e, vi, loc);
3449 // Case 4: fixed buffer
3450 FieldExpr fe = e as FieldExpr;
3452 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3454 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3456 Expression converted = Convert.ImplicitConversionRequired (
3457 ec, fixed_buffer_ptr, vi.VariableType, loc);
3458 if (converted == null)
3461 data [i] = new ExpressionEmitter (converted, vi);
3469 // For other cases, flag a `this is already fixed expression'
3471 if (e is LocalVariableReference || e is ParameterReference ||
3472 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3474 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3478 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3482 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3484 if (!statement.Resolve (ec)) {
3485 ec.KillFlowBranching ();
3489 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3490 has_ret = reachability.IsUnreachable;
3495 protected override void DoEmit (EmitContext ec)
3497 for (int i = 0; i < data.Length; i++) {
3501 statement.Emit (ec);
3506 ILGenerator ig = ec.ig;
3509 // Clear the pinned variable
3511 for (int i = 0; i < data.Length; i++) {
3512 data [i].EmitExit (ig);
3517 public class Catch: Statement {
3518 public readonly string Name;
3519 public readonly Block Block;
3521 Expression type_expr;
3524 public Catch (Expression type, string name, Block block, Location l)
3532 public Type CatchType {
3538 public bool IsGeneral {
3540 return type_expr == null;
3544 protected override void DoEmit(EmitContext ec)
3548 public override bool Resolve (EmitContext ec)
3550 bool was_catch = ec.InCatch;
3553 if (type_expr != null) {
3554 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3558 type = te.ResolveType (ec);
3560 CheckObsolete (type);
3562 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3563 Error (155, "The type caught or thrown must be derived from System.Exception");
3569 return Block.Resolve (ec);
3572 ec.InCatch = was_catch;
3577 public class Try : ExceptionStatement {
3578 public readonly Block Fini, Block;
3579 public readonly ArrayList Specific;
3580 public readonly Catch General;
3582 bool need_exc_block;
3585 // specific, general and fini might all be null.
3587 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3589 if (specific == null && general == null){
3590 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3594 this.Specific = specific;
3595 this.General = general;
3600 public override bool Resolve (EmitContext ec)
3604 FlowBranchingException branching = ec.StartFlowBranching (this);
3606 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3608 if (!Block.Resolve (ec))
3611 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3613 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3615 Type[] prevCatches = new Type [Specific.Count];
3617 foreach (Catch c in Specific){
3618 ec.CurrentBranching.CreateSibling (
3619 c.Block, FlowBranching.SiblingType.Catch);
3621 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3623 if (c.Name != null) {
3624 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3626 throw new Exception ();
3628 vi.VariableInfo = null;
3631 if (!c.Resolve (ec))
3634 Type resolvedType = c.CatchType;
3635 for (int ii = 0; ii < last_index; ++ii) {
3636 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3637 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3642 prevCatches [last_index++] = resolvedType;
3643 need_exc_block = true;
3646 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3648 if (General != null){
3649 ec.CurrentBranching.CreateSibling (
3650 General.Block, FlowBranching.SiblingType.Catch);
3652 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3654 if (!General.Resolve (ec))
3657 need_exc_block = true;
3660 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3664 ec.CurrentBranching.CreateSibling (
3665 Fini, FlowBranching.SiblingType.Finally);
3667 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3668 bool was_finally = ec.InFinally;
3669 ec.InFinally = true;
3670 if (!Fini.Resolve (ec))
3672 ec.InFinally = was_finally;
3675 need_exc_block = true;
3678 if (ec.InIterator) {
3679 ResolveFinally (branching);
3680 need_exc_block |= emit_finally;
3682 emit_finally = Fini != null;
3684 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3686 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3688 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3690 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3691 // Unfortunately, System.Reflection.Emit automatically emits
3692 // a leave to the end of the finally block. This is a problem
3693 // if `returns' is true since we may jump to a point after the
3694 // end of the method.
3695 // As a workaround, emit an explicit ret here.
3696 ec.NeedReturnLabel ();
3702 protected override void DoEmit (EmitContext ec)
3704 ILGenerator ig = ec.ig;
3707 ig.BeginExceptionBlock ();
3710 foreach (Catch c in Specific){
3713 ig.BeginCatchBlock (c.CatchType);
3715 if (c.Name != null){
3716 vi = c.Block.GetLocalInfo (c.Name);
3718 throw new Exception ("Variable does not exist in this block");
3720 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3722 ig.Emit (OpCodes.Pop);
3727 if (General != null){
3728 ig.BeginCatchBlock (TypeManager.object_type);
3729 ig.Emit (OpCodes.Pop);
3730 General.Block.Emit (ec);
3735 ig.EndExceptionBlock ();
3738 public override void EmitFinally (EmitContext ec)
3744 public bool HasCatch
3747 return General != null || Specific.Count > 0;
3752 public class Using : ExceptionStatement {
3753 object expression_or_block;
3754 Statement Statement;
3759 Expression [] resolved_vars;
3760 Expression [] converted_vars;
3761 ExpressionStatement [] assign;
3762 LocalBuilder local_copy;
3764 public Using (object expression_or_block, Statement stmt, Location l)
3766 this.expression_or_block = expression_or_block;
3772 // Resolves for the case of using using a local variable declaration.
3774 bool ResolveLocalVariableDecls (EmitContext ec)
3778 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3782 expr_type = texpr.ResolveType (ec);
3785 // The type must be an IDisposable or an implicit conversion
3788 converted_vars = new Expression [var_list.Count];
3789 resolved_vars = new Expression [var_list.Count];
3790 assign = new ExpressionStatement [var_list.Count];
3792 bool need_conv = !TypeManager.ImplementsInterface (
3793 expr_type, TypeManager.idisposable_type);
3795 foreach (DictionaryEntry e in var_list){
3796 Expression var = (Expression) e.Key;
3798 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3802 resolved_vars [i] = var;
3809 converted_vars [i] = Convert.ImplicitConversionRequired (
3810 ec, var, TypeManager.idisposable_type, loc);
3812 if (converted_vars [i] == null)
3819 foreach (DictionaryEntry e in var_list){
3820 Expression var = resolved_vars [i];
3821 Expression new_expr = (Expression) e.Value;
3824 a = new Assign (var, new_expr, loc);
3830 converted_vars [i] = var;
3831 assign [i] = (ExpressionStatement) a;
3838 bool ResolveExpression (EmitContext ec)
3840 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3841 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3842 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3843 TypeManager.CSharpName (expr_type));
3852 // Emits the code for the case of using using a local variable declaration.
3854 void EmitLocalVariableDecls (EmitContext ec)
3856 ILGenerator ig = ec.ig;
3859 for (i = 0; i < assign.Length; i++) {
3860 assign [i].EmitStatement (ec);
3863 ig.BeginExceptionBlock ();
3865 Statement.Emit (ec);
3866 var_list.Reverse ();
3871 void EmitLocalVariableDeclFinally (EmitContext ec)
3873 ILGenerator ig = ec.ig;
3875 int i = assign.Length;
3876 for (int ii = 0; ii < var_list.Count; ++ii){
3877 Expression var = resolved_vars [--i];
3878 Label skip = ig.DefineLabel ();
3880 if (!var.Type.IsValueType) {
3882 ig.Emit (OpCodes.Brfalse, skip);
3883 converted_vars [i].Emit (ec);
3884 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3886 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3888 if (!(ml is MethodGroupExpr)) {
3890 ig.Emit (OpCodes.Box, var.Type);
3891 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3893 MethodInfo mi = null;
3895 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3896 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3903 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3907 IMemoryLocation mloc = (IMemoryLocation) var;
3909 mloc.AddressOf (ec, AddressOp.Load);
3910 ig.Emit (OpCodes.Call, mi);
3914 ig.MarkLabel (skip);
3917 ig.EndExceptionBlock ();
3919 ig.BeginFinallyBlock ();
3924 void EmitExpression (EmitContext ec)
3927 // Make a copy of the expression and operate on that.
3929 ILGenerator ig = ec.ig;
3930 local_copy = ig.DeclareLocal (expr_type);
3935 ig.Emit (OpCodes.Stloc, local_copy);
3938 ig.BeginExceptionBlock ();
3940 Statement.Emit (ec);
3944 ig.EndExceptionBlock ();
3947 void EmitExpressionFinally (EmitContext ec)
3949 ILGenerator ig = ec.ig;
3950 if (!local_copy.LocalType.IsValueType) {
3951 Label skip = ig.DefineLabel ();
3952 ig.Emit (OpCodes.Ldloc, local_copy);
3953 ig.Emit (OpCodes.Brfalse, skip);
3954 ig.Emit (OpCodes.Ldloc, local_copy);
3955 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3956 ig.MarkLabel (skip);
3958 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
3960 if (!(ml is MethodGroupExpr)) {
3961 ig.Emit (OpCodes.Ldloc, local_copy);
3962 ig.Emit (OpCodes.Box, local_copy.LocalType);
3963 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3965 MethodInfo mi = null;
3967 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3968 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3975 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3979 ig.Emit (OpCodes.Ldloca, local_copy);
3980 ig.Emit (OpCodes.Call, mi);
3985 public override bool Resolve (EmitContext ec)
3987 if (expression_or_block is DictionaryEntry){
3988 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3989 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3991 if (!ResolveLocalVariableDecls (ec))
3994 } else if (expression_or_block is Expression){
3995 expr = (Expression) expression_or_block;
3997 expr = expr.Resolve (ec);
4001 expr_type = expr.Type;
4003 if (!ResolveExpression (ec))
4007 FlowBranchingException branching = ec.StartFlowBranching (this);
4009 bool ok = Statement.Resolve (ec);
4012 ec.KillFlowBranching ();
4016 ResolveFinally (branching);
4017 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4019 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4020 // Unfortunately, System.Reflection.Emit automatically emits a leave
4021 // to the end of the finally block. This is a problem if `returns'
4022 // is true since we may jump to a point after the end of the method.
4023 // As a workaround, emit an explicit ret here.
4024 ec.NeedReturnLabel ();
4030 protected override void DoEmit (EmitContext ec)
4032 if (expression_or_block is DictionaryEntry)
4033 EmitLocalVariableDecls (ec);
4034 else if (expression_or_block is Expression)
4035 EmitExpression (ec);
4038 public override void EmitFinally (EmitContext ec)
4040 if (expression_or_block is DictionaryEntry)
4041 EmitLocalVariableDeclFinally (ec);
4042 else if (expression_or_block is Expression)
4043 EmitExpressionFinally (ec);
4048 /// Implementation of the foreach C# statement
4050 public class Foreach : Statement {
4052 Expression variable;
4054 Statement statement;
4056 CollectionForeach collection;
4058 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4059 Statement stmt, Location l)
4062 this.variable = var;
4068 public override bool Resolve (EmitContext ec)
4070 expr = expr.Resolve (ec);
4074 if (expr is NullLiteral) {
4075 Report.Error (186, loc, "Use of null is not valid in this context");
4079 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4083 Type var_type = texpr.Type;
4086 // We need an instance variable. Not sure this is the best
4087 // way of doing this.
4089 // FIXME: When we implement propertyaccess, will those turn
4090 // out to return values in ExprClass? I think they should.
4092 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4093 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4094 collection.error1579 ();
4098 if (expr.Type.IsArray) {
4099 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4100 return array.Resolve (ec);
4102 collection = new CollectionForeach (
4103 var_type, variable, expr, statement, loc);
4104 return collection.Resolve (ec);
4108 protected override void DoEmit (EmitContext ec)
4110 ILGenerator ig = ec.ig;
4112 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4113 ec.LoopBegin = ig.DefineLabel ();
4114 ec.LoopEnd = ig.DefineLabel ();
4116 if (collection != null)
4117 collection.Emit (ec);
4121 ec.LoopBegin = old_begin;
4122 ec.LoopEnd = old_end;
4125 protected class TemporaryVariable : Expression, IMemoryLocation
4129 public TemporaryVariable (Type type, Location loc)
4133 eclass = ExprClass.Value;
4136 public override Expression DoResolve (EmitContext ec)
4141 TypeExpr te = new TypeExpression (type, loc);
4142 li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
4143 if (!li.Resolve (ec))
4146 AnonymousContainer am = ec.CurrentAnonymousMethod;
4147 if ((am != null) && am.IsIterator)
4148 ec.CaptureVariable (li);
4153 public override void Emit (EmitContext ec)
4155 ILGenerator ig = ec.ig;
4157 if (li.FieldBuilder != null) {
4158 ig.Emit (OpCodes.Ldarg_0);
4159 ig.Emit (OpCodes.Ldfld, li.FieldBuilder);
4161 ig.Emit (OpCodes.Ldloc, li.LocalBuilder);
4165 public void EmitLoadAddress (EmitContext ec)
4167 ILGenerator ig = ec.ig;
4169 if (li.FieldBuilder != null) {
4170 ig.Emit (OpCodes.Ldarg_0);
4171 ig.Emit (OpCodes.Ldflda, li.FieldBuilder);
4173 ig.Emit (OpCodes.Ldloca, li.LocalBuilder);
4177 public void Store (EmitContext ec, Expression right_side)
4179 if (li.FieldBuilder != null)
4180 ec.ig.Emit (OpCodes.Ldarg_0);
4182 right_side.Emit (ec);
4183 if (li.FieldBuilder != null) {
4184 ec.ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4186 ec.ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4190 public void EmitThis (EmitContext ec)
4192 if (li.FieldBuilder != null) {
4193 ec.ig.Emit (OpCodes.Ldarg_0);
4197 public void EmitStore (ILGenerator ig)
4199 if (li.FieldBuilder != null)
4200 ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4202 ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4205 public void AddressOf (EmitContext ec, AddressOp mode)
4207 EmitLoadAddress (ec);
4211 protected class ArrayCounter : TemporaryVariable
4213 public ArrayCounter (Location loc)
4214 : base (TypeManager.int32_type, loc)
4217 public void Initialize (EmitContext ec)
4220 ec.ig.Emit (OpCodes.Ldc_I4_0);
4224 public void Increment (EmitContext ec)
4228 ec.ig.Emit (OpCodes.Ldc_I4_1);
4229 ec.ig.Emit (OpCodes.Add);
4234 protected class ArrayForeach : Statement
4236 Expression variable, expr, conv;
4237 Statement statement;
4240 TemporaryVariable[] lengths;
4241 ArrayCounter[] counter;
4244 TemporaryVariable copy;
4247 public ArrayForeach (Type var_type, Expression var,
4248 Expression expr, Statement stmt, Location l)
4250 this.var_type = var_type;
4251 this.variable = var;
4257 public override bool Resolve (EmitContext ec)
4259 array_type = expr.Type;
4260 rank = array_type.GetArrayRank ();
4262 copy = new TemporaryVariable (array_type, loc);
4265 counter = new ArrayCounter [rank];
4266 lengths = new TemporaryVariable [rank];
4268 ArrayList list = new ArrayList ();
4269 for (int i = 0; i < rank; i++) {
4270 counter [i] = new ArrayCounter (loc);
4271 counter [i].Resolve (ec);
4273 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4274 lengths [i].Resolve (ec);
4276 list.Add (counter [i]);
4279 access = new ElementAccess (copy, list, loc).Resolve (ec);
4283 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4289 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4290 ec.CurrentBranching.CreateSibling ();
4292 variable = variable.ResolveLValue (ec, conv, loc);
4293 if (variable == null)
4296 if (!statement.Resolve (ec))
4299 ec.EndFlowBranching ();
4304 protected override void DoEmit (EmitContext ec)
4306 ILGenerator ig = ec.ig;
4308 copy.Store (ec, expr);
4310 Label[] test = new Label [rank];
4311 Label[] loop = new Label [rank];
4313 for (int i = 0; i < rank; i++) {
4314 test [i] = ig.DefineLabel ();
4315 loop [i] = ig.DefineLabel ();
4317 lengths [i].EmitThis (ec);
4318 ((ArrayAccess) access).EmitGetLength (ec, i);
4319 lengths [i].EmitStore (ig);
4322 for (int i = 0; i < rank; i++) {
4323 counter [i].Initialize (ec);
4325 ig.Emit (OpCodes.Br, test [i]);
4326 ig.MarkLabel (loop [i]);
4329 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4331 statement.Emit (ec);
4333 ig.MarkLabel (ec.LoopBegin);
4335 for (int i = rank - 1; i >= 0; i--){
4336 counter [i].Increment (ec);
4338 ig.MarkLabel (test [i]);
4339 counter [i].Emit (ec);
4340 lengths [i].Emit (ec);
4341 ig.Emit (OpCodes.Blt, loop [i]);
4344 ig.MarkLabel (ec.LoopEnd);
4348 protected class CollectionForeach : ExceptionStatement
4350 Expression variable, expr;
4351 Statement statement;
4353 TemporaryVariable enumerator;
4357 MethodGroupExpr get_enumerator;
4358 PropertyExpr get_current;
4359 MethodInfo move_next;
4360 Type var_type, enumerator_type;
4363 public CollectionForeach (Type var_type, Expression var,
4364 Expression expr, Statement stmt, Location l)
4366 this.var_type = var_type;
4367 this.variable = var;
4373 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4375 Type [] args = TypeManager.GetArgumentTypes (mi);
4377 if (args.Length != 0)
4381 if (TypeManager.IsOverride (mi))
4384 // Check whether GetEnumerator is public
4385 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4388 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4390 // Apply the same optimization as MS: skip the GetEnumerator
4391 // returning an IEnumerator, and use the one returning a
4392 // CharEnumerator instead. This allows us to avoid the
4393 // try-finally block and the boxing.
4398 // Ok, we can access it, now make sure that we can do something
4399 // with this `GetEnumerator'
4402 Type return_type = mi.ReturnType;
4403 if (mi.ReturnType == TypeManager.ienumerator_type ||
4404 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4405 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4407 // If it is not an interface, lets try to find the methods ourselves.
4408 // For example, if we have:
4409 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4410 // We can avoid the iface call. This is a runtime perf boost.
4411 // even bigger if we have a ValueType, because we avoid the cost
4414 // We have to make sure that both methods exist for us to take
4415 // this path. If one of the methods does not exist, we will just
4416 // use the interface. Sadly, this complex if statement is the only
4417 // way I could do this without a goto
4420 if (return_type.IsInterface ||
4421 !FetchMoveNext (ec, return_type) ||
4422 !FetchGetCurrent (ec, return_type)) {
4423 move_next = TypeManager.bool_movenext_void;
4424 get_current = new PropertyExpr (
4425 ec, TypeManager.ienumerator_getcurrent, loc);
4430 // Ok, so they dont return an IEnumerable, we will have to
4431 // find if they support the GetEnumerator pattern.
4434 if (!FetchMoveNext (ec, return_type))
4437 if (!FetchGetCurrent (ec, return_type))
4441 enumerator_type = return_type;
4442 is_disposable = !enumerator_type.IsSealed ||
4443 TypeManager.ImplementsInterface (
4444 enumerator_type, TypeManager.idisposable_type);
4450 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4452 bool FetchMoveNext (EmitContext ec, Type t)
4454 MemberList move_next_list;
4456 move_next_list = TypeContainer.FindMembers (
4457 t, MemberTypes.Method,
4458 BindingFlags.Public | BindingFlags.Instance,
4459 Type.FilterName, "MoveNext");
4460 if (move_next_list.Count == 0)
4463 foreach (MemberInfo m in move_next_list){
4464 MethodInfo mi = (MethodInfo) m;
4467 args = TypeManager.GetArgumentTypes (mi);
4468 if ((args != null) && (args.Length == 0) &&
4469 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4479 // Retrieves a `public T get_Current ()' method from the Type `t'
4481 bool FetchGetCurrent (EmitContext ec, Type t)
4483 PropertyExpr pe = Expression.MemberLookup (
4484 ec, t, "Current", MemberTypes.Property,
4485 Expression.AllBindingFlags, loc) as PropertyExpr;
4494 // Retrieves a `public void Dispose ()' method from the Type `t'
4496 static MethodInfo FetchMethodDispose (Type t)
4498 MemberList dispose_list;
4500 dispose_list = TypeContainer.FindMembers (
4501 t, MemberTypes.Method,
4502 BindingFlags.Public | BindingFlags.Instance,
4503 Type.FilterName, "Dispose");
4504 if (dispose_list.Count == 0)
4507 foreach (MemberInfo m in dispose_list){
4508 MethodInfo mi = (MethodInfo) m;
4511 args = TypeManager.GetArgumentTypes (mi);
4512 if (args != null && args.Length == 0){
4513 if (mi.ReturnType == TypeManager.void_type)
4520 public void error1579 ()
4522 Report.Error (1579, loc,
4523 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4524 TypeManager.CSharpName (expr.Type));
4527 bool TryType (EmitContext ec, Type t)
4529 MethodGroupExpr mg = Expression.MemberLookup (
4530 ec, t, "GetEnumerator", MemberTypes.Method,
4531 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4535 foreach (MethodBase mb in mg.Methods) {
4536 if (!GetEnumeratorFilter (ec, (MethodInfo) mb))
4539 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) mb };
4540 get_enumerator = new MethodGroupExpr (mi, loc);
4542 if (t != expr.Type) {
4543 expr = Convert.ExplicitConversion (
4546 throw new InternalErrorException ();
4549 get_enumerator.InstanceExpression = expr;
4550 get_enumerator.IsBase = t != expr.Type;
4558 bool ProbeCollectionType (EmitContext ec, Type t)
4560 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4561 if (TryType (ec, tt))
4567 // Now try to find the method in the interfaces
4570 Type [] ifaces = t.GetInterfaces ();
4572 foreach (Type i in ifaces){
4573 if (TryType (ec, i))
4578 // Since TypeBuilder.GetInterfaces only returns the interface
4579 // types for this type, we have to keep looping, but once
4580 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4581 // done, because it returns all the types
4583 if ((t is TypeBuilder))
4592 public override bool Resolve (EmitContext ec)
4594 enumerator_type = TypeManager.ienumerator_type;
4595 is_disposable = true;
4597 if (!ProbeCollectionType (ec, expr.Type)) {
4602 enumerator = new TemporaryVariable (enumerator_type, loc);
4603 enumerator.Resolve (ec);
4605 init = new Invocation (get_enumerator, new ArrayList (), loc);
4606 init = init.Resolve (ec);
4610 Expression move_next_expr;
4612 MemberInfo[] mi = new MemberInfo[] { move_next };
4613 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4614 mg.InstanceExpression = enumerator;
4616 move_next_expr = new Invocation (mg, new ArrayList (), loc);
4619 get_current.InstanceExpression = enumerator;
4621 Statement block = new CollectionForeachStatement (
4622 var_type, variable, get_current, statement, loc);
4624 loop = new While (move_next_expr, block, loc);
4628 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4629 ec.CurrentBranching.CreateSibling ();
4631 FlowBranchingException branching = null;
4633 branching = ec.StartFlowBranching (this);
4635 if (!loop.Resolve (ec))
4638 if (is_disposable) {
4639 ResolveFinally (branching);
4640 ec.EndFlowBranching ();
4642 emit_finally = true;
4644 ec.EndFlowBranching ();
4649 protected override void DoEmit (EmitContext ec)
4651 ILGenerator ig = ec.ig;
4653 enumerator.Store (ec, init);
4656 // Protect the code in a try/finalize block, so that
4657 // if the beast implement IDisposable, we get rid of it
4659 if (is_disposable && emit_finally)
4660 ig.BeginExceptionBlock ();
4665 // Now the finally block
4667 if (is_disposable) {
4670 ig.EndExceptionBlock ();
4675 public override void EmitFinally (EmitContext ec)
4677 ILGenerator ig = ec.ig;
4679 if (enumerator_type.IsValueType) {
4680 enumerator.Emit (ec);
4682 MethodInfo mi = FetchMethodDispose (enumerator_type);
4684 enumerator.EmitLoadAddress (ec);
4685 ig.Emit (OpCodes.Call, mi);
4687 enumerator.Emit (ec);
4688 ig.Emit (OpCodes.Box, enumerator_type);
4689 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4692 Label call_dispose = ig.DefineLabel ();
4694 enumerator.Emit (ec);
4695 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4696 ig.Emit (OpCodes.Dup);
4697 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4698 ig.Emit (OpCodes.Pop);
4700 Label end_finally = ig.DefineLabel ();
4701 ig.Emit (OpCodes.Br, end_finally);
4703 ig.MarkLabel (call_dispose);
4704 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4705 ig.MarkLabel (end_finally);
4710 protected class CollectionForeachStatement : Statement
4713 Expression variable, current, conv;
4714 Statement statement;
4717 public CollectionForeachStatement (Type type, Expression variable,
4718 Expression current, Statement statement,
4722 this.variable = variable;
4723 this.current = current;
4724 this.statement = statement;
4728 public override bool Resolve (EmitContext ec)
4730 current = current.Resolve (ec);
4731 if (current == null)
4734 conv = Convert.ExplicitConversion (ec, current, type, loc);
4738 assign = new Assign (variable, conv, loc);
4739 if (assign.Resolve (ec) == null)
4742 if (!statement.Resolve (ec))
4748 protected override void DoEmit (EmitContext ec)
4750 assign.EmitStatement (ec);
4751 statement.Emit (ec);