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)
1462 LocalInfo kvi = GetKnownVariableInfo (name);
1463 if (kvi == null || kvi.Block == this)
1466 if (known_variables != kvi.Block.known_variables) {
1467 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1468 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1473 // this block and kvi.Block are the same textual block.
1474 // However, different variables are extant.
1476 // Check if the variable is in scope in both blocks. We use
1477 // an indirect check that depends on AddVariable doing its
1478 // part in maintaining the invariant-meaning-in-block property.
1480 if (e is LocalVariableReference || (e is Constant && GetLocalInfo (name) != null))
1483 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1484 Error_AlreadyDeclared (loc, name, "parent or current");
1488 public LocalInfo AddVariable (Expression type, string name, Location l)
1490 LocalInfo vi = GetLocalInfo (name);
1492 Report.SymbolRelatedToPreviousError (vi.Location, name);
1493 if (known_variables == vi.Block.known_variables)
1494 Report.Error (128, l,
1495 "A local variable named `{0}' is already defined in this scope", name);
1497 Error_AlreadyDeclared (l, name, "parent");
1501 vi = GetKnownVariableInfo (name);
1503 Report.SymbolRelatedToPreviousError (vi.Location, name);
1504 Error_AlreadyDeclared (l, name, "child");
1509 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1511 Report.SymbolRelatedToPreviousError (p.Location, name);
1512 Error_AlreadyDeclared (l, name, "method argument");
1516 vi = new LocalInfo (type, name, this, l);
1518 Variables.Add (name, vi);
1520 for (Block b = this; b != null; b = b.Parent)
1521 b.AddKnownVariable (name, vi);
1523 if ((flags & Flags.VariablesInitialized) != 0)
1524 throw new Exception ();
1529 void Error_AlreadyDeclared (Location loc, string var, string reason)
1531 Report.Error (136, loc, "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning to `{0}', " +
1532 "which is already used in a `{1}' scope", var, reason);
1535 public bool AddConstant (Expression type, string name, Expression value, Location l)
1537 if (AddVariable (type, name, l) == null)
1540 if (constants == null)
1541 constants = new Hashtable ();
1543 constants.Add (name, value);
1547 static int next_temp_id = 0;
1549 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1551 if (temporary_variables == null)
1552 temporary_variables = new ArrayList ();
1554 int id = ++next_temp_id;
1555 string name = "$s_" + id.ToString ();
1557 LocalInfo li = new LocalInfo (te, name, this, loc);
1558 li.CompilerGenerated = true;
1559 temporary_variables.Add (li);
1563 public LocalInfo GetLocalInfo (string name)
1565 for (Block b = this; b != null; b = b.Parent) {
1566 if (b.variables != null) {
1567 LocalInfo ret = b.variables [name] as LocalInfo;
1575 public Expression GetVariableType (string name)
1577 LocalInfo vi = GetLocalInfo (name);
1578 return vi == null ? null : vi.Type;
1581 public Expression GetConstantExpression (string name)
1583 for (Block b = this; b != null; b = b.Parent) {
1584 if (b.constants != null) {
1585 Expression ret = b.constants [name] as Expression;
1594 /// True if the variable named @name is a constant
1596 public bool IsConstant (string name)
1598 Expression e = GetConstantExpression (name);
1602 public void AddStatement (Statement s)
1605 flags |= Flags.BlockUsed;
1609 get { return (flags & Flags.BlockUsed) != 0; }
1614 flags |= Flags.BlockUsed;
1617 public bool HasRet {
1618 get { return (flags & Flags.HasRet) != 0; }
1621 public bool IsDestructor {
1622 get { return (flags & Flags.IsDestructor) != 0; }
1625 public void SetDestructor ()
1627 flags |= Flags.IsDestructor;
1630 VariableMap param_map, local_map;
1632 public VariableMap ParameterMap {
1634 if ((flags & Flags.VariablesInitialized) == 0)
1635 throw new Exception ("Variables have not been initialized yet");
1641 public VariableMap LocalMap {
1643 if ((flags & Flags.VariablesInitialized) == 0)
1644 throw new Exception ("Variables have not been initialized yet");
1651 /// Emits the variable declarations and labels.
1654 /// tc: is our typecontainer (to resolve type references)
1655 /// ig: is the code generator:
1657 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1659 bool old_unsafe = ec.InUnsafe;
1661 // If some parent block was unsafe, we remain unsafe even if this block
1662 // isn't explicitly marked as such.
1663 ec.InUnsafe |= Unsafe;
1666 // Compute the VariableMap's.
1668 // Unfortunately, we don't know the type when adding variables with
1669 // AddVariable(), so we need to compute this info here.
1673 if (variables != null) {
1674 foreach (LocalInfo li in variables.Values)
1677 locals = new LocalInfo [variables.Count];
1678 variables.Values.CopyTo (locals, 0);
1680 locals = new LocalInfo [0];
1683 local_map = new VariableMap (Parent.LocalMap, locals);
1685 local_map = new VariableMap (locals);
1687 param_map = new VariableMap (ip);
1688 flags |= Flags.VariablesInitialized;
1690 bool old_check_state = ec.ConstantCheckState;
1691 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1694 // Process this block variables
1696 if (variables != null){
1697 foreach (DictionaryEntry de in variables){
1698 string name = (string) de.Key;
1699 LocalInfo vi = (LocalInfo) de.Value;
1701 if (vi.VariableType == null)
1704 Type variable_type = vi.VariableType;
1706 if (variable_type.IsPointer){
1708 // Am not really convinced that this test is required (Microsoft does it)
1709 // but the fact is that you would not be able to use the pointer variable
1712 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1717 if (constants == null)
1720 Expression cv = (Expression) constants [name];
1724 ec.CurrentBlock = this;
1725 Expression e = cv.Resolve (ec);
1727 Constant ce = e as Constant;
1729 Const.Error_ExpressionMustBeConstant (vi.Location, name);
1733 if (e.Type != variable_type){
1734 e = Const.ChangeType (vi.Location, ce, variable_type);
1739 constants.Remove (name);
1740 constants.Add (name, e);
1743 ec.ConstantCheckState = old_check_state;
1746 // Now, handle the children
1748 if (children != null){
1749 foreach (Block b in children)
1750 b.ResolveMeta (toplevel, ec, ip);
1752 ec.InUnsafe = old_unsafe;
1756 // Emits the local variable declarations for a block
1758 public void EmitMeta (EmitContext ec)
1760 ILGenerator ig = ec.ig;
1762 if (variables != null){
1763 bool have_captured_vars = ec.HaveCapturedVariables ();
1765 foreach (DictionaryEntry de in variables){
1766 LocalInfo vi = (LocalInfo) de.Value;
1768 if (have_captured_vars && ec.IsCaptured (vi))
1773 // This is needed to compile on both .NET 1.x and .NET 2.x
1774 // the later introduced `DeclareLocal (Type t, bool pinned)'
1776 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1777 else if (!vi.IsThis)
1778 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1782 if (temporary_variables != null) {
1783 AnonymousContainer am = ec.CurrentAnonymousMethod;
1784 TypeBuilder scope = null;
1785 if ((am != null) && am.IsIterator) {
1786 scope = am.Scope.ScopeTypeBuilder;
1788 throw new InternalErrorException ();
1790 foreach (LocalInfo vi in temporary_variables) {
1791 if (scope != null) {
1792 if (vi.FieldBuilder == null)
1793 vi.FieldBuilder = scope.DefineField (
1794 vi.Name, vi.VariableType, FieldAttributes.Assembly);
1796 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1800 if (children != null){
1801 foreach (Block b in children)
1806 void UsageWarning (FlowBranching.UsageVector vector)
1810 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1811 foreach (DictionaryEntry de in variables){
1812 LocalInfo vi = (LocalInfo) de.Value;
1817 name = (string) de.Key;
1819 if (vector.IsAssigned (vi.VariableInfo)){
1820 Report.Warning (219, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
1822 Report.Warning (168, vi.Location, "The variable `{0}' is declared but never used", name);
1828 bool unreachable_shown;
1831 public override bool Resolve (EmitContext ec)
1833 Block prev_block = ec.CurrentBlock;
1836 int errors = Report.Errors;
1838 ec.CurrentBlock = this;
1839 ec.StartFlowBranching (this);
1841 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1843 int statement_count = statements.Count;
1844 for (int ix = 0; ix < statement_count; ix++){
1845 Statement s = (Statement) statements [ix];
1848 // Warn if we detect unreachable code.
1852 ((Block) s).unreachable = true;
1854 if (!unreachable_shown && (RootContext.WarningLevel >= 2)) {
1856 162, loc, "Unreachable code detected");
1857 unreachable_shown = true;
1862 // Note that we're not using ResolveUnreachable() for unreachable
1863 // statements here. ResolveUnreachable() creates a temporary
1864 // flow branching and kills it afterwards. This leads to problems
1865 // if you have two unreachable statements where the first one
1866 // assigns a variable and the second one tries to access it.
1869 if (!s.Resolve (ec)) {
1871 statements [ix] = EmptyStatement.Value;
1875 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1876 statements [ix] = EmptyStatement.Value;
1878 num_statements = ix + 1;
1879 if (s is LabeledStatement)
1880 unreachable = false;
1882 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1885 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1886 ec.CurrentBranching, statement_count, num_statements);
1888 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1890 ec.CurrentBlock = prev_block;
1892 // If we're a non-static `struct' constructor which doesn't have an
1893 // initializer, then we must initialize all of the struct's fields.
1894 if ((flags & Flags.IsToplevel) != 0 &&
1895 !Toplevel.IsThisAssigned (ec) &&
1896 vector.Reachability.Throws != FlowBranching.FlowReturns.Always)
1899 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1900 foreach (LabeledStatement label in labels.Values)
1901 if (!label.HasBeenReferenced)
1902 Report.Warning (164, label.loc,
1903 "This label has not been referenced");
1906 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1908 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1909 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1910 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1911 flags |= Flags.HasRet;
1913 if (ok && (errors == Report.Errors)) {
1914 if (RootContext.WarningLevel >= 3)
1915 UsageWarning (vector);
1921 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1923 unreachable_shown = true;
1926 if (warn && (RootContext.WarningLevel >= 2))
1927 Report.Warning (162, loc, "Unreachable code detected");
1929 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1930 bool ok = Resolve (ec);
1931 ec.KillFlowBranching ();
1936 protected override void DoEmit (EmitContext ec)
1938 for (int ix = 0; ix < num_statements; ix++){
1939 Statement s = (Statement) statements [ix];
1941 // Check whether we are the last statement in a
1944 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
1945 ec.IsLastStatement = true;
1947 ec.IsLastStatement = false;
1953 public override void Emit (EmitContext ec)
1955 Block prev_block = ec.CurrentBlock;
1957 ec.CurrentBlock = this;
1959 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1960 bool is_lexical_block = !Implicit && (Parent != null);
1962 if (emit_debug_info) {
1963 if (is_lexical_block)
1966 if (variables != null) {
1967 foreach (DictionaryEntry de in variables) {
1968 string name = (string) de.Key;
1969 LocalInfo vi = (LocalInfo) de.Value;
1971 if (vi.LocalBuilder == null)
1974 ec.DefineLocalVariable (name, vi.LocalBuilder);
1979 ec.Mark (StartLocation, true);
1981 ec.Mark (EndLocation, true);
1983 if (emit_debug_info && is_lexical_block)
1986 ec.CurrentBlock = prev_block;
1990 // Returns true if we ar ea child of `b'.
1992 public bool IsChildOf (Block b)
1994 Block current = this;
1997 if (current.Parent == b)
1999 current = current.Parent;
2000 } while (current != null);
2004 public override string ToString ()
2006 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2011 // A toplevel block contains extra information, the split is done
2012 // only to separate information that would otherwise bloat the more
2013 // lightweight Block.
2015 // In particular, this was introduced when the support for Anonymous
2016 // Methods was implemented.
2018 public class ToplevelBlock : Block {
2020 // Pointer to the host of this anonymous method, or null
2021 // if we are the topmost block
2023 ToplevelBlock container;
2024 CaptureContext capture_context;
2025 FlowBranching top_level_branching;
2027 Hashtable capture_contexts;
2030 public bool HasVarargs {
2031 get { return (flags & Flags.HasVarargs) != 0; }
2032 set { flags |= Flags.HasVarargs; }
2036 // The parameters for the block.
2038 public readonly Parameters Parameters;
2040 public void RegisterCaptureContext (CaptureContext cc)
2042 if (capture_contexts == null)
2043 capture_contexts = new Hashtable ();
2044 capture_contexts [cc] = cc;
2047 public void CompleteContexts ()
2049 if (capture_contexts == null)
2052 foreach (CaptureContext cc in capture_contexts.Keys){
2057 public CaptureContext ToplevelBlockCaptureContext {
2058 get { return capture_context; }
2061 public ToplevelBlock Container {
2062 get { return container; }
2065 protected void AddChild (ToplevelBlock block)
2067 if (children == null)
2068 children = new ArrayList ();
2070 children.Add (block);
2074 // Parent is only used by anonymous blocks to link back to their
2077 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2078 this (container, (Flags) 0, parameters, start)
2082 public ToplevelBlock (Parameters parameters, Location start) :
2083 this (null, (Flags) 0, parameters, start)
2087 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2088 this (null, flags, parameters, start)
2092 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2093 base (null, flags | Flags.IsToplevel, start, Location.Null)
2095 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2096 this.container = container;
2098 if (container != null)
2099 container.AddChild (this);
2102 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2106 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2108 if (capture_context == null)
2109 capture_context = new CaptureContext (this, loc, host);
2112 public CaptureContext CaptureContext {
2113 get { return capture_context; }
2116 public FlowBranching TopLevelBranching {
2117 get { return top_level_branching; }
2121 // This is used if anonymous methods are used inside an iterator
2122 // (see 2test-22.cs for an example).
2124 // The AnonymousMethod is created while parsing - at a time when we don't
2125 // know yet that we're inside an iterator, so it's `Container' is initially
2126 // null. Later on, when resolving the iterator, we need to move the
2127 // anonymous method into that iterator.
2129 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2131 foreach (ToplevelBlock block in children) {
2132 if (block.CaptureContext == null)
2135 block.container = new_parent;
2136 block.CaptureContext.ReParent (new_parent, new_host);
2141 // Returns a `ParameterReference' for the given name, or null if there
2142 // is no such parameter
2144 public ParameterReference GetParameterReference (string name, Location loc)
2149 for (ToplevelBlock t = this; t != null; t = t.Container) {
2150 Parameters pars = t.Parameters;
2151 par = pars.GetParameterByName (name, out idx);
2153 return new ParameterReference (pars, this, idx, name, loc);
2159 // Whether the parameter named `name' is local to this block,
2160 // or false, if the parameter belongs to an encompassing block.
2162 public bool IsLocalParameter (string name)
2164 return Parameters.GetParameterByName (name) != null;
2168 // Whether the `name' is a parameter reference
2170 public bool IsParameterReference (string name)
2172 for (ToplevelBlock t = this; t != null; t = t.Container) {
2173 if (t.IsLocalParameter (name))
2179 LocalInfo this_variable = null;
2182 // Returns the "this" instance variable of this block.
2183 // See AddThisVariable() for more information.
2185 public LocalInfo ThisVariable {
2186 get { return this_variable; }
2191 // This is used by non-static `struct' constructors which do not have an
2192 // initializer - in this case, the constructor must initialize all of the
2193 // struct's fields. To do this, we add a "this" variable and use the flow
2194 // analysis code to ensure that it's been fully initialized before control
2195 // leaves the constructor.
2197 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
2199 if (this_variable == null) {
2200 this_variable = new LocalInfo (tc, this, l);
2201 this_variable.Used = true;
2202 this_variable.IsThis = true;
2204 Variables.Add ("this", this_variable);
2207 return this_variable;
2210 public bool IsThisAssigned (EmitContext ec)
2212 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2215 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2217 int errors = Report.Errors;
2219 if (top_level_branching != null)
2222 ResolveMeta (this, ec, ip);
2224 top_level_branching = ec.StartFlowBranching (this);
2226 return Report.Errors == errors;
2230 public class SwitchLabel {
2237 Label il_label_code;
2238 bool il_label_code_set;
2241 // if expr == null, then it is the default case.
2243 public SwitchLabel (Expression expr, Location l)
2249 public Expression Label {
2255 public object Converted {
2261 public Label GetILLabel (EmitContext ec)
2264 il_label = ec.ig.DefineLabel ();
2265 il_label_set = true;
2270 public Label GetILLabelCode (EmitContext ec)
2272 if (!il_label_code_set){
2273 il_label_code = ec.ig.DefineLabel ();
2274 il_label_code_set = true;
2276 return il_label_code;
2280 // Resolves the expression, reduces it to a literal if possible
2281 // and then converts it to the requested type.
2283 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2285 Expression e = label.Resolve (ec);
2290 Constant c = e as Constant;
2292 Report.Error (150, loc, "A constant value is expected");
2296 if (required_type == TypeManager.string_type) {
2297 if (c.Type == TypeManager.string_type) {
2298 converted = c.GetValue ();
2302 if (e is NullLiteral) {
2308 converted = Expression.ConvertIntLiteral (c, required_type, loc);
2309 return converted != null;
2312 public void Erorr_AlreadyOccurs ()
2315 if (converted == null)
2317 else if (converted is NullLiteral)
2320 label = converted.ToString ();
2322 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2326 public class SwitchSection {
2327 // An array of SwitchLabels.
2328 public readonly ArrayList Labels;
2329 public readonly Block Block;
2331 public SwitchSection (ArrayList labels, Block block)
2338 public class Switch : Statement {
2339 public readonly ArrayList Sections;
2340 public Expression Expr;
2343 /// Maps constants whose type type SwitchType to their SwitchLabels.
2345 public IDictionary Elements;
2348 /// The governing switch type
2350 public Type SwitchType;
2355 Label default_target;
2356 Expression new_expr;
2358 SwitchSection constant_section;
2359 SwitchSection default_section;
2362 // The types allowed to be implicitly cast from
2363 // on the governing type
2365 static Type [] allowed_types;
2367 public Switch (Expression e, ArrayList sects, Location l)
2374 public bool GotDefault {
2376 return default_section != null;
2380 public Label DefaultTarget {
2382 return default_target;
2387 // Determines the governing type for a switch. The returned
2388 // expression might be the expression from the switch, or an
2389 // expression that includes any potential conversions to the
2390 // integral types or to string.
2392 Expression SwitchGoverningType (EmitContext ec, Type t)
2394 if (t == TypeManager.byte_type ||
2395 t == TypeManager.sbyte_type ||
2396 t == TypeManager.ushort_type ||
2397 t == TypeManager.short_type ||
2398 t == TypeManager.uint32_type ||
2399 t == TypeManager.int32_type ||
2400 t == TypeManager.uint64_type ||
2401 t == TypeManager.int64_type ||
2402 t == TypeManager.char_type ||
2403 t == TypeManager.string_type ||
2404 t == TypeManager.bool_type ||
2405 t.IsSubclassOf (TypeManager.enum_type))
2408 if (allowed_types == null){
2409 allowed_types = new Type [] {
2410 TypeManager.sbyte_type,
2411 TypeManager.byte_type,
2412 TypeManager.short_type,
2413 TypeManager.ushort_type,
2414 TypeManager.int32_type,
2415 TypeManager.uint32_type,
2416 TypeManager.int64_type,
2417 TypeManager.uint64_type,
2418 TypeManager.char_type,
2419 TypeManager.string_type,
2420 TypeManager.bool_type
2425 // Try to find a *user* defined implicit conversion.
2427 // If there is no implicit conversion, or if there are multiple
2428 // conversions, we have to report an error
2430 Expression converted = null;
2431 foreach (Type tt in allowed_types){
2434 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2439 // Ignore over-worked ImplicitUserConversions that do
2440 // an implicit conversion in addition to the user conversion.
2442 if (!(e is UserCast))
2445 if (converted != null){
2446 Report.ExtraInformation (
2448 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2449 TypeManager.CSharpName (Expr.Type)));
2459 // Performs the basic sanity checks on the switch statement
2460 // (looks for duplicate keys and non-constant expressions).
2462 // It also returns a hashtable with the keys that we will later
2463 // use to compute the switch tables
2465 bool CheckSwitch (EmitContext ec)
2468 Elements = Sections.Count > 10 ?
2469 (IDictionary)new Hashtable () :
2470 (IDictionary)new ListDictionary ();
2472 foreach (SwitchSection ss in Sections){
2473 foreach (SwitchLabel sl in ss.Labels){
2474 if (sl.Label == null){
2475 if (default_section != null){
2476 sl.Erorr_AlreadyOccurs ();
2479 default_section = ss;
2483 if (!sl.ResolveAndReduce (ec, SwitchType)){
2488 object key = sl.Converted;
2490 Elements.Add (key, sl);
2492 catch (ArgumentException) {
2493 sl.Erorr_AlreadyOccurs ();
2501 void EmitObjectInteger (ILGenerator ig, object k)
2504 IntConstant.EmitInt (ig, (int) k);
2505 else if (k is Constant) {
2506 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2509 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2512 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2514 IntConstant.EmitInt (ig, (int) (long) k);
2515 ig.Emit (OpCodes.Conv_I8);
2518 LongConstant.EmitLong (ig, (long) k);
2520 else if (k is ulong)
2522 if ((ulong) k < (1L<<32))
2524 IntConstant.EmitInt (ig, (int) (long) k);
2525 ig.Emit (OpCodes.Conv_U8);
2529 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2533 IntConstant.EmitInt (ig, (int) ((char) k));
2534 else if (k is sbyte)
2535 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2537 IntConstant.EmitInt (ig, (int) ((byte) k));
2538 else if (k is short)
2539 IntConstant.EmitInt (ig, (int) ((short) k));
2540 else if (k is ushort)
2541 IntConstant.EmitInt (ig, (int) ((ushort) k));
2543 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2545 throw new Exception ("Unhandled case");
2548 // structure used to hold blocks of keys while calculating table switch
2549 class KeyBlock : IComparable
2551 public KeyBlock (long _nFirst)
2553 nFirst = nLast = _nFirst;
2557 public ArrayList rgKeys = null;
2558 // how many items are in the bucket
2559 public int Size = 1;
2562 get { return (int) (nLast - nFirst + 1); }
2564 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2566 return kbLast.nLast - kbFirst.nFirst + 1;
2568 public int CompareTo (object obj)
2570 KeyBlock kb = (KeyBlock) obj;
2571 int nLength = Length;
2572 int nLengthOther = kb.Length;
2573 if (nLengthOther == nLength)
2574 return (int) (kb.nFirst - nFirst);
2575 return nLength - nLengthOther;
2580 /// This method emits code for a lookup-based switch statement (non-string)
2581 /// Basically it groups the cases into blocks that are at least half full,
2582 /// and then spits out individual lookup opcodes for each block.
2583 /// It emits the longest blocks first, and short blocks are just
2584 /// handled with direct compares.
2586 /// <param name="ec"></param>
2587 /// <param name="val"></param>
2588 /// <returns></returns>
2589 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2591 int cElements = Elements.Count;
2592 object [] rgKeys = new object [cElements];
2593 Elements.Keys.CopyTo (rgKeys, 0);
2594 Array.Sort (rgKeys);
2596 // initialize the block list with one element per key
2597 ArrayList rgKeyBlocks = new ArrayList ();
2598 foreach (object key in rgKeys)
2599 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2602 // iteratively merge the blocks while they are at least half full
2603 // there's probably a really cool way to do this with a tree...
2604 while (rgKeyBlocks.Count > 1)
2606 ArrayList rgKeyBlocksNew = new ArrayList ();
2607 kbCurr = (KeyBlock) rgKeyBlocks [0];
2608 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2610 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2611 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2614 kbCurr.nLast = kb.nLast;
2615 kbCurr.Size += kb.Size;
2619 // start a new block
2620 rgKeyBlocksNew.Add (kbCurr);
2624 rgKeyBlocksNew.Add (kbCurr);
2625 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2627 rgKeyBlocks = rgKeyBlocksNew;
2630 // initialize the key lists
2631 foreach (KeyBlock kb in rgKeyBlocks)
2632 kb.rgKeys = new ArrayList ();
2634 // fill the key lists
2636 if (rgKeyBlocks.Count > 0) {
2637 kbCurr = (KeyBlock) rgKeyBlocks [0];
2638 foreach (object key in rgKeys)
2640 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2641 System.Convert.ToInt64 (key) > kbCurr.nLast;
2643 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2644 kbCurr.rgKeys.Add (key);
2648 // sort the blocks so we can tackle the largest ones first
2649 rgKeyBlocks.Sort ();
2651 // okay now we can start...
2652 ILGenerator ig = ec.ig;
2653 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2654 Label lblDefault = ig.DefineLabel ();
2656 Type typeKeys = null;
2657 if (rgKeys.Length > 0)
2658 typeKeys = rgKeys [0].GetType (); // used for conversions
2662 if (TypeManager.IsEnumType (SwitchType))
2663 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2665 compare_type = SwitchType;
2667 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2669 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2670 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2673 foreach (object key in kb.rgKeys)
2675 ig.Emit (OpCodes.Ldloc, val);
2676 EmitObjectInteger (ig, key);
2677 SwitchLabel sl = (SwitchLabel) Elements [key];
2678 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2683 // TODO: if all the keys in the block are the same and there are
2684 // no gaps/defaults then just use a range-check.
2685 if (compare_type == TypeManager.int64_type ||
2686 compare_type == TypeManager.uint64_type)
2688 // TODO: optimize constant/I4 cases
2690 // check block range (could be > 2^31)
2691 ig.Emit (OpCodes.Ldloc, val);
2692 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2693 ig.Emit (OpCodes.Blt, lblDefault);
2694 ig.Emit (OpCodes.Ldloc, val);
2695 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2696 ig.Emit (OpCodes.Bgt, lblDefault);
2699 ig.Emit (OpCodes.Ldloc, val);
2702 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2703 ig.Emit (OpCodes.Sub);
2705 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2710 ig.Emit (OpCodes.Ldloc, val);
2711 int nFirst = (int) kb.nFirst;
2714 IntConstant.EmitInt (ig, nFirst);
2715 ig.Emit (OpCodes.Sub);
2717 else if (nFirst < 0)
2719 IntConstant.EmitInt (ig, -nFirst);
2720 ig.Emit (OpCodes.Add);
2724 // first, build the list of labels for the switch
2726 int cJumps = kb.Length;
2727 Label [] rgLabels = new Label [cJumps];
2728 for (int iJump = 0; iJump < cJumps; iJump++)
2730 object key = kb.rgKeys [iKey];
2731 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2733 SwitchLabel sl = (SwitchLabel) Elements [key];
2734 rgLabels [iJump] = sl.GetILLabel (ec);
2738 rgLabels [iJump] = lblDefault;
2740 // emit the switch opcode
2741 ig.Emit (OpCodes.Switch, rgLabels);
2744 // mark the default for this block
2746 ig.MarkLabel (lblDefault);
2749 // TODO: find the default case and emit it here,
2750 // to prevent having to do the following jump.
2751 // make sure to mark other labels in the default section
2753 // the last default just goes to the end
2754 ig.Emit (OpCodes.Br, lblDefault);
2756 // now emit the code for the sections
2757 bool fFoundDefault = false;
2758 foreach (SwitchSection ss in Sections)
2760 foreach (SwitchLabel sl in ss.Labels)
2762 ig.MarkLabel (sl.GetILLabel (ec));
2763 ig.MarkLabel (sl.GetILLabelCode (ec));
2764 if (sl.Label == null)
2766 ig.MarkLabel (lblDefault);
2767 fFoundDefault = true;
2771 //ig.Emit (OpCodes.Br, lblEnd);
2774 if (!fFoundDefault) {
2775 ig.MarkLabel (lblDefault);
2777 ig.MarkLabel (lblEnd);
2780 // This simple emit switch works, but does not take advantage of the
2782 // TODO: remove non-string logic from here
2783 // TODO: binary search strings?
2785 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2787 ILGenerator ig = ec.ig;
2788 Label end_of_switch = ig.DefineLabel ();
2789 Label next_test = ig.DefineLabel ();
2790 Label null_target = ig.DefineLabel ();
2791 bool first_test = true;
2792 bool pending_goto_end = false;
2793 bool null_marked = false;
2796 ig.Emit (OpCodes.Ldloc, val);
2798 if (Elements.Contains (NullLiteral.Null)){
2799 ig.Emit (OpCodes.Brfalse, null_target);
2801 ig.Emit (OpCodes.Brfalse, default_target);
2803 ig.Emit (OpCodes.Ldloc, val);
2804 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2805 ig.Emit (OpCodes.Stloc, val);
2807 int section_count = Sections.Count;
2808 for (int section = 0; section < section_count; section++){
2809 SwitchSection ss = (SwitchSection) Sections [section];
2811 if (ss == default_section)
2814 Label sec_begin = ig.DefineLabel ();
2816 ig.Emit (OpCodes.Nop);
2818 if (pending_goto_end)
2819 ig.Emit (OpCodes.Br, end_of_switch);
2821 int label_count = ss.Labels.Count;
2823 for (int label = 0; label < label_count; label++){
2824 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2825 ig.MarkLabel (sl.GetILLabel (ec));
2828 ig.MarkLabel (next_test);
2829 next_test = ig.DefineLabel ();
2832 // If we are the default target
2834 if (sl.Label != null){
2835 object lit = sl.Converted;
2837 if (lit is NullLiteral){
2839 if (label_count == 1)
2840 ig.Emit (OpCodes.Br, next_test);
2844 ig.Emit (OpCodes.Ldloc, val);
2845 ig.Emit (OpCodes.Ldstr, (string)lit);
2846 if (label_count == 1)
2847 ig.Emit (OpCodes.Bne_Un, next_test);
2849 if (label+1 == label_count)
2850 ig.Emit (OpCodes.Bne_Un, next_test);
2852 ig.Emit (OpCodes.Beq, sec_begin);
2857 ig.MarkLabel (null_target);
2860 ig.MarkLabel (sec_begin);
2861 foreach (SwitchLabel sl in ss.Labels)
2862 ig.MarkLabel (sl.GetILLabelCode (ec));
2865 pending_goto_end = !ss.Block.HasRet;
2868 ig.MarkLabel (next_test);
2869 ig.MarkLabel (default_target);
2871 ig.MarkLabel (null_target);
2872 if (default_section != null)
2873 default_section.Block.Emit (ec);
2874 ig.MarkLabel (end_of_switch);
2877 SwitchSection FindSection (SwitchLabel label)
2879 foreach (SwitchSection ss in Sections){
2880 foreach (SwitchLabel sl in ss.Labels){
2889 public override bool Resolve (EmitContext ec)
2891 Expr = Expr.Resolve (ec);
2895 new_expr = SwitchGoverningType (ec, Expr.Type);
2896 if (new_expr == null){
2897 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2902 SwitchType = new_expr.Type;
2904 if (!CheckSwitch (ec))
2907 Switch old_switch = ec.Switch;
2909 ec.Switch.SwitchType = SwitchType;
2911 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2912 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2914 is_constant = new_expr is Constant;
2916 object key = ((Constant) new_expr).GetValue ();
2917 SwitchLabel label = (SwitchLabel) Elements [key];
2919 constant_section = FindSection (label);
2920 if (constant_section == null)
2921 constant_section = default_section;
2925 foreach (SwitchSection ss in Sections){
2927 ec.CurrentBranching.CreateSibling (
2928 null, FlowBranching.SiblingType.SwitchSection);
2932 if (is_constant && (ss != constant_section)) {
2933 // If we're a constant switch, we're only emitting
2934 // one single section - mark all the others as
2936 ec.CurrentBranching.CurrentUsageVector.Goto ();
2937 if (!ss.Block.ResolveUnreachable (ec, true))
2940 if (!ss.Block.Resolve (ec))
2945 if (default_section == null)
2946 ec.CurrentBranching.CreateSibling (
2947 null, FlowBranching.SiblingType.SwitchSection);
2949 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2950 ec.Switch = old_switch;
2952 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2958 protected override void DoEmit (EmitContext ec)
2960 ILGenerator ig = ec.ig;
2962 // Store variable for comparission purposes
2965 value = ig.DeclareLocal (SwitchType);
2967 ig.Emit (OpCodes.Stloc, value);
2971 default_target = ig.DefineLabel ();
2974 // Setup the codegen context
2976 Label old_end = ec.LoopEnd;
2977 Switch old_switch = ec.Switch;
2979 ec.LoopEnd = ig.DefineLabel ();
2984 if (constant_section != null)
2985 constant_section.Block.Emit (ec);
2986 } else if (SwitchType == TypeManager.string_type)
2987 SimpleSwitchEmit (ec, value);
2989 TableSwitchEmit (ec, value);
2991 // Restore context state.
2992 ig.MarkLabel (ec.LoopEnd);
2995 // Restore the previous context
2997 ec.LoopEnd = old_end;
2998 ec.Switch = old_switch;
3002 public abstract class ExceptionStatement : Statement
3004 public abstract void EmitFinally (EmitContext ec);
3006 protected bool emit_finally = true;
3007 ArrayList parent_vectors;
3009 protected void DoEmitFinally (EmitContext ec)
3012 ec.ig.BeginFinallyBlock ();
3013 else if (ec.InIterator)
3014 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3018 protected void ResolveFinally (FlowBranchingException branching)
3020 emit_finally = branching.EmitFinally;
3022 branching.Parent.StealFinallyClauses (ref parent_vectors);
3026 public class Lock : ExceptionStatement {
3028 Statement Statement;
3031 public Lock (Expression expr, Statement stmt, Location l)
3038 public override bool Resolve (EmitContext ec)
3040 expr = expr.Resolve (ec);
3044 if (expr.Type.IsValueType){
3045 Report.Error (185, loc,
3046 "`{0}' is not a reference type as required by the lock statement",
3047 TypeManager.CSharpName (expr.Type));
3051 FlowBranchingException branching = ec.StartFlowBranching (this);
3052 bool ok = Statement.Resolve (ec);
3054 ec.KillFlowBranching ();
3058 ResolveFinally (branching);
3060 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3061 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3062 // Unfortunately, System.Reflection.Emit automatically emits
3063 // a leave to the end of the finally block.
3064 // This is a problem if `returns' is true since we may jump
3065 // to a point after the end of the method.
3066 // As a workaround, emit an explicit ret here.
3067 ec.NeedReturnLabel ();
3073 protected override void DoEmit (EmitContext ec)
3075 Type type = expr.Type;
3077 ILGenerator ig = ec.ig;
3078 temp = ig.DeclareLocal (type);
3081 ig.Emit (OpCodes.Dup);
3082 ig.Emit (OpCodes.Stloc, temp);
3083 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3087 ig.BeginExceptionBlock ();
3088 Statement.Emit (ec);
3093 ig.EndExceptionBlock ();
3096 public override void EmitFinally (EmitContext ec)
3098 ILGenerator ig = ec.ig;
3099 ig.Emit (OpCodes.Ldloc, temp);
3100 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3104 public class Unchecked : Statement {
3105 public readonly Block Block;
3107 public Unchecked (Block b)
3113 public override bool Resolve (EmitContext ec)
3115 bool previous_state = ec.CheckState;
3116 bool previous_state_const = ec.ConstantCheckState;
3118 ec.CheckState = false;
3119 ec.ConstantCheckState = false;
3120 bool ret = Block.Resolve (ec);
3121 ec.CheckState = previous_state;
3122 ec.ConstantCheckState = previous_state_const;
3127 protected override void DoEmit (EmitContext ec)
3129 bool previous_state = ec.CheckState;
3130 bool previous_state_const = ec.ConstantCheckState;
3132 ec.CheckState = false;
3133 ec.ConstantCheckState = false;
3135 ec.CheckState = previous_state;
3136 ec.ConstantCheckState = previous_state_const;
3140 public class Checked : Statement {
3141 public readonly Block Block;
3143 public Checked (Block b)
3146 b.Unchecked = false;
3149 public override bool Resolve (EmitContext ec)
3151 bool previous_state = ec.CheckState;
3152 bool previous_state_const = ec.ConstantCheckState;
3154 ec.CheckState = true;
3155 ec.ConstantCheckState = true;
3156 bool ret = Block.Resolve (ec);
3157 ec.CheckState = previous_state;
3158 ec.ConstantCheckState = previous_state_const;
3163 protected override void DoEmit (EmitContext ec)
3165 bool previous_state = ec.CheckState;
3166 bool previous_state_const = ec.ConstantCheckState;
3168 ec.CheckState = true;
3169 ec.ConstantCheckState = true;
3171 ec.CheckState = previous_state;
3172 ec.ConstantCheckState = previous_state_const;
3176 public class Unsafe : Statement {
3177 public readonly Block Block;
3179 public Unsafe (Block b)
3182 Block.Unsafe = true;
3185 public override bool Resolve (EmitContext ec)
3187 bool previous_state = ec.InUnsafe;
3191 val = Block.Resolve (ec);
3192 ec.InUnsafe = previous_state;
3197 protected override void DoEmit (EmitContext ec)
3199 bool previous_state = ec.InUnsafe;
3203 ec.InUnsafe = previous_state;
3210 public class Fixed : Statement {
3212 ArrayList declarators;
3213 Statement statement;
3218 abstract class Emitter
3220 protected LocalInfo vi;
3221 protected Expression converted;
3223 protected Emitter (Expression expr, LocalInfo li)
3229 public abstract void Emit (EmitContext ec);
3230 public abstract void EmitExit (ILGenerator ig);
3233 class ExpressionEmitter: Emitter {
3234 public ExpressionEmitter (Expression converted, LocalInfo li) :
3235 base (converted, li)
3239 public override void Emit (EmitContext ec) {
3241 // Store pointer in pinned location
3243 converted.Emit (ec);
3244 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3247 public override void EmitExit (ILGenerator ig)
3249 ig.Emit (OpCodes.Ldc_I4_0);
3250 ig.Emit (OpCodes.Conv_U);
3251 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3255 class StringEmitter: Emitter {
3256 LocalBuilder pinned_string;
3259 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3265 public override void Emit (EmitContext ec)
3267 ILGenerator ig = ec.ig;
3268 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3270 converted.Emit (ec);
3271 ig.Emit (OpCodes.Stloc, pinned_string);
3273 Expression sptr = new StringPtr (pinned_string, loc);
3274 converted = Convert.ImplicitConversionRequired (
3275 ec, sptr, vi.VariableType, loc);
3277 if (converted == null)
3280 converted.Emit (ec);
3281 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3284 public override void EmitExit(ILGenerator ig)
3286 ig.Emit (OpCodes.Ldnull);
3287 ig.Emit (OpCodes.Stloc, pinned_string);
3291 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3294 declarators = decls;
3299 public override bool Resolve (EmitContext ec)
3302 Expression.UnsafeError (loc);
3306 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3310 expr_type = texpr.ResolveType (ec);
3312 CheckObsolete (expr_type);
3314 data = new Emitter [declarators.Count];
3316 if (!expr_type.IsPointer){
3317 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3322 foreach (Pair p in declarators){
3323 LocalInfo vi = (LocalInfo) p.First;
3324 Expression e = (Expression) p.Second;
3326 vi.VariableInfo.SetAssigned (ec);
3327 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3330 // The rules for the possible declarators are pretty wise,
3331 // but the production on the grammar is more concise.
3333 // So we have to enforce these rules here.
3335 // We do not resolve before doing the case 1 test,
3336 // because the grammar is explicit in that the token &
3337 // is present, so we need to test for this particular case.
3341 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3346 // Case 1: & object.
3348 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3349 Expression child = ((Unary) e).Expr;
3351 if (child is ParameterReference || child is LocalVariableReference){
3354 "No need to use fixed statement for parameters or " +
3355 "local variable declarations (address is already " +
3360 ec.InFixedInitializer = true;
3362 ec.InFixedInitializer = false;
3366 child = ((Unary) e).Expr;
3368 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3371 data [i] = new ExpressionEmitter (e, vi);
3377 ec.InFixedInitializer = true;
3379 ec.InFixedInitializer = false;
3386 if (e.Type.IsArray){
3387 Type array_type = TypeManager.GetElementType (e.Type);
3390 // Provided that array_type is unmanaged,
3392 if (!TypeManager.VerifyUnManaged (array_type, loc))
3396 // and T* is implicitly convertible to the
3397 // pointer type given in the fixed statement.
3399 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3401 Expression converted = Convert.ImplicitConversionRequired (
3402 ec, array_ptr, vi.VariableType, loc);
3403 if (converted == null)
3406 data [i] = new ExpressionEmitter (converted, vi);
3415 if (e.Type == TypeManager.string_type){
3416 data [i] = new StringEmitter (e, vi, loc);
3421 // Case 4: fixed buffer
3422 FieldExpr fe = e as FieldExpr;
3424 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3426 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3428 Expression converted = Convert.ImplicitConversionRequired (
3429 ec, fixed_buffer_ptr, vi.VariableType, loc);
3430 if (converted == null)
3433 data [i] = new ExpressionEmitter (converted, vi);
3441 // For other cases, flag a `this is already fixed expression'
3443 if (e is LocalVariableReference || e is ParameterReference ||
3444 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3446 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3450 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3454 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3456 if (!statement.Resolve (ec)) {
3457 ec.KillFlowBranching ();
3461 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3462 has_ret = reachability.IsUnreachable;
3467 protected override void DoEmit (EmitContext ec)
3469 for (int i = 0; i < data.Length; i++) {
3473 statement.Emit (ec);
3478 ILGenerator ig = ec.ig;
3481 // Clear the pinned variable
3483 for (int i = 0; i < data.Length; i++) {
3484 data [i].EmitExit (ig);
3489 public class Catch: Statement {
3490 public readonly string Name;
3491 public readonly Block Block;
3493 Expression type_expr;
3496 public Catch (Expression type, string name, Block block, Location l)
3504 public Type CatchType {
3510 public bool IsGeneral {
3512 return type_expr == null;
3516 protected override void DoEmit(EmitContext ec)
3520 public override bool Resolve (EmitContext ec)
3522 bool was_catch = ec.InCatch;
3525 if (type_expr != null) {
3526 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3530 type = te.ResolveType (ec);
3532 CheckObsolete (type);
3534 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3535 Error (155, "The type caught or thrown must be derived from System.Exception");
3541 return Block.Resolve (ec);
3544 ec.InCatch = was_catch;
3549 public class Try : ExceptionStatement {
3550 public readonly Block Fini, Block;
3551 public readonly ArrayList Specific;
3552 public readonly Catch General;
3554 bool need_exc_block;
3557 // specific, general and fini might all be null.
3559 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3561 if (specific == null && general == null){
3562 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3566 this.Specific = specific;
3567 this.General = general;
3572 public override bool Resolve (EmitContext ec)
3576 FlowBranchingException branching = ec.StartFlowBranching (this);
3578 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3580 if (!Block.Resolve (ec))
3583 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3585 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3587 Type[] prevCatches = new Type [Specific.Count];
3589 foreach (Catch c in Specific){
3590 ec.CurrentBranching.CreateSibling (
3591 c.Block, FlowBranching.SiblingType.Catch);
3593 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3595 if (c.Name != null) {
3596 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3598 throw new Exception ();
3600 vi.VariableInfo = null;
3603 if (!c.Resolve (ec))
3606 Type resolvedType = c.CatchType;
3607 for (int ii = 0; ii < last_index; ++ii) {
3608 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3609 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3614 prevCatches [last_index++] = resolvedType;
3615 need_exc_block = true;
3618 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3620 if (General != null){
3621 ec.CurrentBranching.CreateSibling (
3622 General.Block, FlowBranching.SiblingType.Catch);
3624 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3626 if (!General.Resolve (ec))
3629 need_exc_block = true;
3632 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3636 ec.CurrentBranching.CreateSibling (
3637 Fini, FlowBranching.SiblingType.Finally);
3639 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3640 bool was_finally = ec.InFinally;
3641 ec.InFinally = true;
3642 if (!Fini.Resolve (ec))
3644 ec.InFinally = was_finally;
3647 need_exc_block = true;
3650 if (ec.InIterator) {
3651 ResolveFinally (branching);
3652 need_exc_block |= emit_finally;
3654 emit_finally = Fini != null;
3656 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3658 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3660 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3662 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3663 // Unfortunately, System.Reflection.Emit automatically emits
3664 // a leave to the end of the finally block. This is a problem
3665 // if `returns' is true since we may jump to a point after the
3666 // end of the method.
3667 // As a workaround, emit an explicit ret here.
3668 ec.NeedReturnLabel ();
3674 protected override void DoEmit (EmitContext ec)
3676 ILGenerator ig = ec.ig;
3679 ig.BeginExceptionBlock ();
3682 foreach (Catch c in Specific){
3685 ig.BeginCatchBlock (c.CatchType);
3687 if (c.Name != null){
3688 vi = c.Block.GetLocalInfo (c.Name);
3690 throw new Exception ("Variable does not exist in this block");
3692 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3694 ig.Emit (OpCodes.Pop);
3699 if (General != null){
3700 ig.BeginCatchBlock (TypeManager.object_type);
3701 ig.Emit (OpCodes.Pop);
3702 General.Block.Emit (ec);
3707 ig.EndExceptionBlock ();
3710 public override void EmitFinally (EmitContext ec)
3716 public bool HasCatch
3719 return General != null || Specific.Count > 0;
3724 public class Using : ExceptionStatement {
3725 object expression_or_block;
3726 Statement Statement;
3731 Expression [] resolved_vars;
3732 Expression [] converted_vars;
3733 ExpressionStatement [] assign;
3734 LocalBuilder local_copy;
3736 public Using (object expression_or_block, Statement stmt, Location l)
3738 this.expression_or_block = expression_or_block;
3744 // Resolves for the case of using using a local variable declaration.
3746 bool ResolveLocalVariableDecls (EmitContext ec)
3750 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3754 expr_type = texpr.ResolveType (ec);
3757 // The type must be an IDisposable or an implicit conversion
3760 converted_vars = new Expression [var_list.Count];
3761 resolved_vars = new Expression [var_list.Count];
3762 assign = new ExpressionStatement [var_list.Count];
3764 bool need_conv = !TypeManager.ImplementsInterface (
3765 expr_type, TypeManager.idisposable_type);
3767 foreach (DictionaryEntry e in var_list){
3768 Expression var = (Expression) e.Key;
3770 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3774 resolved_vars [i] = var;
3781 converted_vars [i] = Convert.ImplicitConversionRequired (
3782 ec, var, TypeManager.idisposable_type, loc);
3784 if (converted_vars [i] == null)
3791 foreach (DictionaryEntry e in var_list){
3792 Expression var = resolved_vars [i];
3793 Expression new_expr = (Expression) e.Value;
3796 a = new Assign (var, new_expr, loc);
3802 converted_vars [i] = var;
3803 assign [i] = (ExpressionStatement) a;
3810 bool ResolveExpression (EmitContext ec)
3812 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3813 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3814 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3815 TypeManager.CSharpName (expr_type));
3824 // Emits the code for the case of using using a local variable declaration.
3826 void EmitLocalVariableDecls (EmitContext ec)
3828 ILGenerator ig = ec.ig;
3831 for (i = 0; i < assign.Length; i++) {
3832 assign [i].EmitStatement (ec);
3835 ig.BeginExceptionBlock ();
3837 Statement.Emit (ec);
3838 var_list.Reverse ();
3843 void EmitLocalVariableDeclFinally (EmitContext ec)
3845 ILGenerator ig = ec.ig;
3847 int i = assign.Length;
3848 for (int ii = 0; ii < var_list.Count; ++ii){
3849 Expression var = resolved_vars [--i];
3850 Label skip = ig.DefineLabel ();
3852 if (!var.Type.IsValueType) {
3854 ig.Emit (OpCodes.Brfalse, skip);
3855 converted_vars [i].Emit (ec);
3856 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3858 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3860 if (!(ml is MethodGroupExpr)) {
3862 ig.Emit (OpCodes.Box, var.Type);
3863 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3865 MethodInfo mi = null;
3867 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3868 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3875 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3879 IMemoryLocation mloc = (IMemoryLocation) var;
3881 mloc.AddressOf (ec, AddressOp.Load);
3882 ig.Emit (OpCodes.Call, mi);
3886 ig.MarkLabel (skip);
3889 ig.EndExceptionBlock ();
3891 ig.BeginFinallyBlock ();
3896 void EmitExpression (EmitContext ec)
3899 // Make a copy of the expression and operate on that.
3901 ILGenerator ig = ec.ig;
3902 local_copy = ig.DeclareLocal (expr_type);
3907 ig.Emit (OpCodes.Stloc, local_copy);
3910 ig.BeginExceptionBlock ();
3912 Statement.Emit (ec);
3916 ig.EndExceptionBlock ();
3919 void EmitExpressionFinally (EmitContext ec)
3921 ILGenerator ig = ec.ig;
3922 if (!local_copy.LocalType.IsValueType) {
3923 Label skip = ig.DefineLabel ();
3924 ig.Emit (OpCodes.Ldloc, local_copy);
3925 ig.Emit (OpCodes.Brfalse, skip);
3926 ig.Emit (OpCodes.Ldloc, local_copy);
3927 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3928 ig.MarkLabel (skip);
3930 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
3932 if (!(ml is MethodGroupExpr)) {
3933 ig.Emit (OpCodes.Ldloc, local_copy);
3934 ig.Emit (OpCodes.Box, local_copy.LocalType);
3935 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3937 MethodInfo mi = null;
3939 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3940 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3947 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3951 ig.Emit (OpCodes.Ldloca, local_copy);
3952 ig.Emit (OpCodes.Call, mi);
3957 public override bool Resolve (EmitContext ec)
3959 if (expression_or_block is DictionaryEntry){
3960 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3961 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3963 if (!ResolveLocalVariableDecls (ec))
3966 } else if (expression_or_block is Expression){
3967 expr = (Expression) expression_or_block;
3969 expr = expr.Resolve (ec);
3973 expr_type = expr.Type;
3975 if (!ResolveExpression (ec))
3979 FlowBranchingException branching = ec.StartFlowBranching (this);
3981 bool ok = Statement.Resolve (ec);
3984 ec.KillFlowBranching ();
3988 ResolveFinally (branching);
3989 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3991 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3992 // Unfortunately, System.Reflection.Emit automatically emits a leave
3993 // to the end of the finally block. This is a problem if `returns'
3994 // is true since we may jump to a point after the end of the method.
3995 // As a workaround, emit an explicit ret here.
3996 ec.NeedReturnLabel ();
4002 protected override void DoEmit (EmitContext ec)
4004 if (expression_or_block is DictionaryEntry)
4005 EmitLocalVariableDecls (ec);
4006 else if (expression_or_block is Expression)
4007 EmitExpression (ec);
4010 public override void EmitFinally (EmitContext ec)
4012 if (expression_or_block is DictionaryEntry)
4013 EmitLocalVariableDeclFinally (ec);
4014 else if (expression_or_block is Expression)
4015 EmitExpressionFinally (ec);
4020 /// Implementation of the foreach C# statement
4022 public class Foreach : Statement {
4024 Expression variable;
4026 Statement statement;
4028 CollectionForeach collection;
4030 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4031 Statement stmt, Location l)
4034 this.variable = var;
4040 public override bool Resolve (EmitContext ec)
4042 expr = expr.Resolve (ec);
4046 if (expr is NullLiteral) {
4047 Report.Error (186, loc, "Use of null is not valid in this context");
4051 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4055 Type var_type = texpr.Type;
4058 // We need an instance variable. Not sure this is the best
4059 // way of doing this.
4061 // FIXME: When we implement propertyaccess, will those turn
4062 // out to return values in ExprClass? I think they should.
4064 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4065 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4066 collection.error1579 ();
4070 if (expr.Type.IsArray) {
4071 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4072 return array.Resolve (ec);
4074 collection = new CollectionForeach (
4075 var_type, variable, expr, statement, loc);
4076 return collection.Resolve (ec);
4080 protected override void DoEmit (EmitContext ec)
4082 ILGenerator ig = ec.ig;
4084 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4085 ec.LoopBegin = ig.DefineLabel ();
4086 ec.LoopEnd = ig.DefineLabel ();
4088 if (collection != null)
4089 collection.Emit (ec);
4093 ec.LoopBegin = old_begin;
4094 ec.LoopEnd = old_end;
4097 protected class TemporaryVariable : Expression, IMemoryLocation
4101 public TemporaryVariable (Type type, Location loc)
4105 eclass = ExprClass.Value;
4108 public override Expression DoResolve (EmitContext ec)
4113 TypeExpr te = new TypeExpression (type, loc);
4114 li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
4115 if (!li.Resolve (ec))
4118 AnonymousContainer am = ec.CurrentAnonymousMethod;
4119 if ((am != null) && am.IsIterator)
4120 ec.CaptureVariable (li);
4125 public override void Emit (EmitContext ec)
4127 ILGenerator ig = ec.ig;
4129 if (li.FieldBuilder != null) {
4130 ig.Emit (OpCodes.Ldarg_0);
4131 ig.Emit (OpCodes.Ldfld, li.FieldBuilder);
4133 ig.Emit (OpCodes.Ldloc, li.LocalBuilder);
4137 public void EmitLoadAddress (EmitContext ec)
4139 ILGenerator ig = ec.ig;
4141 if (li.FieldBuilder != null) {
4142 ig.Emit (OpCodes.Ldarg_0);
4143 ig.Emit (OpCodes.Ldflda, li.FieldBuilder);
4145 ig.Emit (OpCodes.Ldloca, li.LocalBuilder);
4149 public void Store (EmitContext ec, Expression right_side)
4151 if (li.FieldBuilder != null)
4152 ec.ig.Emit (OpCodes.Ldarg_0);
4154 right_side.Emit (ec);
4155 if (li.FieldBuilder != null) {
4156 ec.ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4158 ec.ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4162 public void EmitThis (EmitContext ec)
4164 if (li.FieldBuilder != null) {
4165 ec.ig.Emit (OpCodes.Ldarg_0);
4169 public void EmitStore (ILGenerator ig)
4171 if (li.FieldBuilder != null)
4172 ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4174 ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4177 public void AddressOf (EmitContext ec, AddressOp mode)
4179 EmitLoadAddress (ec);
4183 protected class ArrayCounter : TemporaryVariable
4185 public ArrayCounter (Location loc)
4186 : base (TypeManager.int32_type, loc)
4189 public void Initialize (EmitContext ec)
4192 ec.ig.Emit (OpCodes.Ldc_I4_0);
4196 public void Increment (EmitContext ec)
4200 ec.ig.Emit (OpCodes.Ldc_I4_1);
4201 ec.ig.Emit (OpCodes.Add);
4206 protected class ArrayForeach : Statement
4208 Expression variable, expr, conv;
4209 Statement statement;
4212 TemporaryVariable[] lengths;
4213 ArrayCounter[] counter;
4216 TemporaryVariable copy;
4219 public ArrayForeach (Type var_type, Expression var,
4220 Expression expr, Statement stmt, Location l)
4222 this.var_type = var_type;
4223 this.variable = var;
4229 public override bool Resolve (EmitContext ec)
4231 array_type = expr.Type;
4232 rank = array_type.GetArrayRank ();
4234 copy = new TemporaryVariable (array_type, loc);
4237 counter = new ArrayCounter [rank];
4238 lengths = new TemporaryVariable [rank];
4240 ArrayList list = new ArrayList ();
4241 for (int i = 0; i < rank; i++) {
4242 counter [i] = new ArrayCounter (loc);
4243 counter [i].Resolve (ec);
4245 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4246 lengths [i].Resolve (ec);
4248 list.Add (counter [i]);
4251 access = new ElementAccess (copy, list, loc).Resolve (ec);
4255 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4261 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4262 ec.CurrentBranching.CreateSibling ();
4264 variable = variable.ResolveLValue (ec, conv, loc);
4265 if (variable == null)
4268 if (!statement.Resolve (ec))
4271 ec.EndFlowBranching ();
4276 protected override void DoEmit (EmitContext ec)
4278 ILGenerator ig = ec.ig;
4280 copy.Store (ec, expr);
4282 Label[] test = new Label [rank];
4283 Label[] loop = new Label [rank];
4285 for (int i = 0; i < rank; i++) {
4286 test [i] = ig.DefineLabel ();
4287 loop [i] = ig.DefineLabel ();
4289 lengths [i].EmitThis (ec);
4290 ((ArrayAccess) access).EmitGetLength (ec, i);
4291 lengths [i].EmitStore (ig);
4294 for (int i = 0; i < rank; i++) {
4295 counter [i].Initialize (ec);
4297 ig.Emit (OpCodes.Br, test [i]);
4298 ig.MarkLabel (loop [i]);
4301 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4303 statement.Emit (ec);
4305 ig.MarkLabel (ec.LoopBegin);
4307 for (int i = rank - 1; i >= 0; i--){
4308 counter [i].Increment (ec);
4310 ig.MarkLabel (test [i]);
4311 counter [i].Emit (ec);
4312 lengths [i].Emit (ec);
4313 ig.Emit (OpCodes.Blt, loop [i]);
4316 ig.MarkLabel (ec.LoopEnd);
4320 protected class CollectionForeach : ExceptionStatement
4322 Expression variable, expr;
4323 Statement statement;
4325 TemporaryVariable enumerator;
4329 MethodGroupExpr get_enumerator;
4330 PropertyExpr get_current;
4331 MethodInfo move_next;
4332 Type var_type, enumerator_type;
4335 public CollectionForeach (Type var_type, Expression var,
4336 Expression expr, Statement stmt, Location l)
4338 this.var_type = var_type;
4339 this.variable = var;
4345 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4347 Type [] args = TypeManager.GetArgumentTypes (mi);
4349 if (args.Length != 0)
4353 if (TypeManager.IsOverride (mi))
4356 // Check whether GetEnumerator is public
4357 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4360 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4362 // Apply the same optimization as MS: skip the GetEnumerator
4363 // returning an IEnumerator, and use the one returning a
4364 // CharEnumerator instead. This allows us to avoid the
4365 // try-finally block and the boxing.
4370 // Ok, we can access it, now make sure that we can do something
4371 // with this `GetEnumerator'
4374 Type return_type = mi.ReturnType;
4375 if (mi.ReturnType == TypeManager.ienumerator_type ||
4376 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4377 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4379 // If it is not an interface, lets try to find the methods ourselves.
4380 // For example, if we have:
4381 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4382 // We can avoid the iface call. This is a runtime perf boost.
4383 // even bigger if we have a ValueType, because we avoid the cost
4386 // We have to make sure that both methods exist for us to take
4387 // this path. If one of the methods does not exist, we will just
4388 // use the interface. Sadly, this complex if statement is the only
4389 // way I could do this without a goto
4392 if (return_type.IsInterface ||
4393 !FetchMoveNext (ec, return_type) ||
4394 !FetchGetCurrent (ec, return_type)) {
4395 move_next = TypeManager.bool_movenext_void;
4396 get_current = new PropertyExpr (
4397 ec, TypeManager.ienumerator_getcurrent, loc);
4402 // Ok, so they dont return an IEnumerable, we will have to
4403 // find if they support the GetEnumerator pattern.
4406 if (!FetchMoveNext (ec, return_type))
4409 if (!FetchGetCurrent (ec, return_type))
4413 enumerator_type = return_type;
4414 is_disposable = !enumerator_type.IsSealed ||
4415 TypeManager.ImplementsInterface (
4416 enumerator_type, TypeManager.idisposable_type);
4422 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4424 bool FetchMoveNext (EmitContext ec, Type t)
4426 MemberList move_next_list;
4428 move_next_list = TypeContainer.FindMembers (
4429 t, MemberTypes.Method,
4430 BindingFlags.Public | BindingFlags.Instance,
4431 Type.FilterName, "MoveNext");
4432 if (move_next_list.Count == 0)
4435 foreach (MemberInfo m in move_next_list){
4436 MethodInfo mi = (MethodInfo) m;
4439 args = TypeManager.GetArgumentTypes (mi);
4440 if ((args != null) && (args.Length == 0) &&
4441 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4451 // Retrieves a `public T get_Current ()' method from the Type `t'
4453 bool FetchGetCurrent (EmitContext ec, Type t)
4455 PropertyExpr pe = Expression.MemberLookup (
4456 ec, t, "Current", MemberTypes.Property,
4457 Expression.AllBindingFlags, loc) as PropertyExpr;
4466 // Retrieves a `public void Dispose ()' method from the Type `t'
4468 static MethodInfo FetchMethodDispose (Type t)
4470 MemberList dispose_list;
4472 dispose_list = TypeContainer.FindMembers (
4473 t, MemberTypes.Method,
4474 BindingFlags.Public | BindingFlags.Instance,
4475 Type.FilterName, "Dispose");
4476 if (dispose_list.Count == 0)
4479 foreach (MemberInfo m in dispose_list){
4480 MethodInfo mi = (MethodInfo) m;
4483 args = TypeManager.GetArgumentTypes (mi);
4484 if (args != null && args.Length == 0){
4485 if (mi.ReturnType == TypeManager.void_type)
4492 public void error1579 ()
4494 Report.Error (1579, loc,
4495 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4496 TypeManager.CSharpName (expr.Type));
4499 bool TryType (EmitContext ec, Type t)
4501 MethodGroupExpr mg = Expression.MemberLookup (
4502 ec, t, "GetEnumerator", MemberTypes.Method,
4503 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4507 foreach (MethodBase mb in mg.Methods) {
4508 if (!GetEnumeratorFilter (ec, (MethodInfo) mb))
4511 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) mb };
4512 get_enumerator = new MethodGroupExpr (mi, loc);
4514 if (t != expr.Type) {
4515 expr = Convert.ExplicitConversion (
4518 throw new InternalErrorException ();
4521 get_enumerator.InstanceExpression = expr;
4522 get_enumerator.IsBase = t != expr.Type;
4530 bool ProbeCollectionType (EmitContext ec, Type t)
4532 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4533 if (TryType (ec, tt))
4539 // Now try to find the method in the interfaces
4542 Type [] ifaces = t.GetInterfaces ();
4544 foreach (Type i in ifaces){
4545 if (TryType (ec, i))
4550 // Since TypeBuilder.GetInterfaces only returns the interface
4551 // types for this type, we have to keep looping, but once
4552 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4553 // done, because it returns all the types
4555 if ((t is TypeBuilder))
4564 public override bool Resolve (EmitContext ec)
4566 enumerator_type = TypeManager.ienumerator_type;
4567 is_disposable = true;
4569 if (!ProbeCollectionType (ec, expr.Type)) {
4574 enumerator = new TemporaryVariable (enumerator_type, loc);
4575 enumerator.Resolve (ec);
4577 init = new Invocation (get_enumerator, new ArrayList (), loc);
4578 init = init.Resolve (ec);
4582 Expression move_next_expr;
4584 MemberInfo[] mi = new MemberInfo[] { move_next };
4585 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4586 mg.InstanceExpression = enumerator;
4588 move_next_expr = new Invocation (mg, new ArrayList (), loc);
4591 get_current.InstanceExpression = enumerator;
4593 Statement block = new CollectionForeachStatement (
4594 var_type, variable, get_current, statement, loc);
4596 loop = new While (move_next_expr, block, loc);
4600 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4601 ec.CurrentBranching.CreateSibling ();
4603 FlowBranchingException branching = null;
4605 branching = ec.StartFlowBranching (this);
4607 if (!loop.Resolve (ec))
4610 if (is_disposable) {
4611 ResolveFinally (branching);
4612 ec.EndFlowBranching ();
4614 emit_finally = true;
4616 ec.EndFlowBranching ();
4621 protected override void DoEmit (EmitContext ec)
4623 ILGenerator ig = ec.ig;
4625 enumerator.Store (ec, init);
4628 // Protect the code in a try/finalize block, so that
4629 // if the beast implement IDisposable, we get rid of it
4631 if (is_disposable && emit_finally)
4632 ig.BeginExceptionBlock ();
4637 // Now the finally block
4639 if (is_disposable) {
4642 ig.EndExceptionBlock ();
4647 public override void EmitFinally (EmitContext ec)
4649 ILGenerator ig = ec.ig;
4651 if (enumerator_type.IsValueType) {
4652 enumerator.Emit (ec);
4654 MethodInfo mi = FetchMethodDispose (enumerator_type);
4656 enumerator.EmitLoadAddress (ec);
4657 ig.Emit (OpCodes.Call, mi);
4659 enumerator.Emit (ec);
4660 ig.Emit (OpCodes.Box, enumerator_type);
4661 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4664 Label call_dispose = ig.DefineLabel ();
4666 enumerator.Emit (ec);
4667 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4668 ig.Emit (OpCodes.Dup);
4669 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4670 ig.Emit (OpCodes.Pop);
4672 Label end_finally = ig.DefineLabel ();
4673 ig.Emit (OpCodes.Br, end_finally);
4675 ig.MarkLabel (call_dispose);
4676 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4677 ig.MarkLabel (end_finally);
4682 protected class CollectionForeachStatement : Statement
4685 Expression variable, current, conv;
4686 Statement statement;
4689 public CollectionForeachStatement (Type type, Expression variable,
4690 Expression current, Statement statement,
4694 this.variable = variable;
4695 this.current = current;
4696 this.statement = statement;
4700 public override bool Resolve (EmitContext ec)
4702 current = current.Resolve (ec);
4703 if (current == null)
4706 conv = Convert.ExplicitConversion (ec, current, type, loc);
4710 assign = new Assign (variable, conv, loc);
4711 if (assign.Resolve (ec) == null)
4714 if (!statement.Resolve (ec))
4720 protected override void DoEmit (EmitContext ec)
4722 assign.EmitStatement (ec);
4723 statement.Emit (ec);