2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@ximian.com)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 // (C) 2003, 2004 Novell, Inc.
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Diagnostics;
17 using System.Collections;
18 using System.Collections.Specialized;
20 namespace Mono.CSharp {
22 public abstract class Statement {
26 /// Resolves the statement, true means that all sub-statements
29 public virtual bool Resolve (EmitContext ec)
35 /// We already know that the statement is unreachable, but we still
36 /// need to resolve it to catch errors.
38 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
41 // This conflicts with csc's way of doing this, but IMHO it's
42 // the right thing to do.
44 // If something is unreachable, we still check whether it's
45 // correct. This means that you cannot use unassigned variables
46 // in unreachable code, for instance.
49 if (warn && (RootContext.WarningLevel >= 2))
50 Report.Warning (162, loc, "Unreachable code detected");
52 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
53 bool ok = Resolve (ec);
54 ec.KillFlowBranching ();
59 protected void CheckObsolete (Type type)
61 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
62 if (obsolete_attr == null)
65 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
69 /// Return value indicates whether all code paths emitted return.
71 protected abstract void DoEmit (EmitContext ec);
74 /// Utility wrapper routine for Error, just to beautify the code
76 public void Error (int error, string format, params object[] args)
78 Error (error, String.Format (format, args));
81 public void Error (int error, string s)
84 Report.Error (error, loc, s);
86 Report.Error (error, s);
90 /// Return value indicates whether all code paths emitted return.
92 public virtual void Emit (EmitContext ec)
99 public sealed class EmptyStatement : Statement {
101 private EmptyStatement () {}
103 public static readonly EmptyStatement Value = new EmptyStatement ();
105 public override bool Resolve (EmitContext ec)
110 protected override void DoEmit (EmitContext ec)
115 public class If : Statement {
117 public Statement TrueStatement;
118 public Statement FalseStatement;
122 public If (Expression expr, Statement trueStatement, Location l)
125 TrueStatement = trueStatement;
129 public If (Expression expr,
130 Statement trueStatement,
131 Statement falseStatement,
135 TrueStatement = trueStatement;
136 FalseStatement = falseStatement;
140 public override bool Resolve (EmitContext ec)
144 Report.Debug (1, "START IF BLOCK", loc);
146 expr = Expression.ResolveBoolean (ec, expr, loc);
152 Assign ass = expr as Assign;
153 if (ass != null && ass.Source is Constant) {
154 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
158 // Dead code elimination
160 if (expr is BoolConstant){
161 bool take = ((BoolConstant) expr).Value;
164 if (!TrueStatement.Resolve (ec))
167 if ((FalseStatement != null) &&
168 !FalseStatement.ResolveUnreachable (ec, true))
170 FalseStatement = null;
172 if (!TrueStatement.ResolveUnreachable (ec, true))
174 TrueStatement = null;
176 if ((FalseStatement != null) &&
177 !FalseStatement.Resolve (ec))
184 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
186 ok &= TrueStatement.Resolve (ec);
188 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
190 ec.CurrentBranching.CreateSibling ();
192 if (FalseStatement != null)
193 ok &= FalseStatement.Resolve (ec);
195 ec.EndFlowBranching ();
197 Report.Debug (1, "END IF BLOCK", loc);
202 protected override void DoEmit (EmitContext ec)
204 ILGenerator ig = ec.ig;
205 Label false_target = ig.DefineLabel ();
209 // If we're a boolean expression, Resolve() already
210 // eliminated dead code for us.
212 if (expr is BoolConstant){
213 bool take = ((BoolConstant) expr).Value;
216 TrueStatement.Emit (ec);
217 else if (FalseStatement != null)
218 FalseStatement.Emit (ec);
223 expr.EmitBranchable (ec, false_target, false);
225 TrueStatement.Emit (ec);
227 if (FalseStatement != null){
228 bool branch_emitted = false;
230 end = ig.DefineLabel ();
232 ig.Emit (OpCodes.Br, end);
233 branch_emitted = true;
236 ig.MarkLabel (false_target);
237 FalseStatement.Emit (ec);
242 ig.MarkLabel (false_target);
247 public class Do : Statement {
248 public Expression expr;
249 public readonly Statement EmbeddedStatement;
252 public Do (Statement statement, Expression boolExpr, Location l)
255 EmbeddedStatement = statement;
259 public override bool Resolve (EmitContext ec)
263 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
265 if (!EmbeddedStatement.Resolve (ec))
268 expr = Expression.ResolveBoolean (ec, expr, loc);
271 else if (expr is BoolConstant){
272 bool res = ((BoolConstant) expr).Value;
278 ec.CurrentBranching.Infinite = infinite;
279 ec.EndFlowBranching ();
284 protected override void DoEmit (EmitContext ec)
286 ILGenerator ig = ec.ig;
287 Label loop = ig.DefineLabel ();
288 Label old_begin = ec.LoopBegin;
289 Label old_end = ec.LoopEnd;
291 ec.LoopBegin = ig.DefineLabel ();
292 ec.LoopEnd = ig.DefineLabel ();
295 EmbeddedStatement.Emit (ec);
296 ig.MarkLabel (ec.LoopBegin);
299 // Dead code elimination
301 if (expr is BoolConstant){
302 bool res = ((BoolConstant) expr).Value;
305 ec.ig.Emit (OpCodes.Br, loop);
307 expr.EmitBranchable (ec, loop, true);
309 ig.MarkLabel (ec.LoopEnd);
311 ec.LoopBegin = old_begin;
312 ec.LoopEnd = old_end;
316 public class While : Statement {
317 public Expression expr;
318 public readonly Statement Statement;
319 bool infinite, empty;
321 public While (Expression boolExpr, Statement statement, Location l)
323 this.expr = boolExpr;
324 Statement = statement;
328 public override bool Resolve (EmitContext ec)
332 expr = Expression.ResolveBoolean (ec, expr, loc);
337 // Inform whether we are infinite or not
339 if (expr is BoolConstant){
340 BoolConstant bc = (BoolConstant) expr;
342 if (bc.Value == false){
343 if (!Statement.ResolveUnreachable (ec, true))
351 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
353 ec.CurrentBranching.CreateSibling ();
355 if (!Statement.Resolve (ec))
358 ec.CurrentBranching.Infinite = infinite;
359 ec.EndFlowBranching ();
364 protected override void DoEmit (EmitContext ec)
369 ILGenerator ig = ec.ig;
370 Label old_begin = ec.LoopBegin;
371 Label old_end = ec.LoopEnd;
373 ec.LoopBegin = ig.DefineLabel ();
374 ec.LoopEnd = ig.DefineLabel ();
377 // Inform whether we are infinite or not
379 if (expr is BoolConstant){
380 ig.MarkLabel (ec.LoopBegin);
382 ig.Emit (OpCodes.Br, ec.LoopBegin);
385 // Inform that we are infinite (ie, `we return'), only
386 // if we do not `break' inside the code.
388 ig.MarkLabel (ec.LoopEnd);
390 Label while_loop = ig.DefineLabel ();
392 ig.Emit (OpCodes.Br, ec.LoopBegin);
393 ig.MarkLabel (while_loop);
397 ig.MarkLabel (ec.LoopBegin);
399 expr.EmitBranchable (ec, while_loop, true);
401 ig.MarkLabel (ec.LoopEnd);
404 ec.LoopBegin = old_begin;
405 ec.LoopEnd = old_end;
409 public class For : Statement {
411 readonly Statement InitStatement;
412 readonly Statement Increment;
413 readonly Statement Statement;
414 bool infinite, empty;
416 public For (Statement initStatement,
422 InitStatement = initStatement;
424 Increment = increment;
425 Statement = statement;
429 public override bool Resolve (EmitContext ec)
433 if (InitStatement != null){
434 if (!InitStatement.Resolve (ec))
439 Test = Expression.ResolveBoolean (ec, Test, loc);
442 else if (Test is BoolConstant){
443 BoolConstant bc = (BoolConstant) Test;
445 if (bc.Value == false){
446 if (!Statement.ResolveUnreachable (ec, true))
448 if ((Increment != null) &&
449 !Increment.ResolveUnreachable (ec, false))
459 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
461 ec.CurrentBranching.CreateSibling ();
463 if (!Statement.Resolve (ec))
466 if (Increment != null){
467 if (!Increment.Resolve (ec))
471 ec.CurrentBranching.Infinite = infinite;
472 ec.EndFlowBranching ();
477 protected override void DoEmit (EmitContext ec)
482 ILGenerator ig = ec.ig;
483 Label old_begin = ec.LoopBegin;
484 Label old_end = ec.LoopEnd;
485 Label loop = ig.DefineLabel ();
486 Label test = ig.DefineLabel ();
488 if (InitStatement != null && InitStatement != EmptyStatement.Value)
489 InitStatement.Emit (ec);
491 ec.LoopBegin = ig.DefineLabel ();
492 ec.LoopEnd = ig.DefineLabel ();
494 ig.Emit (OpCodes.Br, test);
498 ig.MarkLabel (ec.LoopBegin);
499 if (Increment != EmptyStatement.Value)
504 // If test is null, there is no test, and we are just
509 // The Resolve code already catches the case for
510 // Test == BoolConstant (false) so we know that
513 if (Test is BoolConstant)
514 ig.Emit (OpCodes.Br, loop);
516 Test.EmitBranchable (ec, loop, true);
519 ig.Emit (OpCodes.Br, loop);
520 ig.MarkLabel (ec.LoopEnd);
522 ec.LoopBegin = old_begin;
523 ec.LoopEnd = old_end;
527 public class StatementExpression : Statement {
528 ExpressionStatement expr;
530 public StatementExpression (ExpressionStatement expr)
536 public override bool Resolve (EmitContext ec)
539 expr = expr.ResolveStatement (ec);
543 protected override void DoEmit (EmitContext ec)
545 expr.EmitStatement (ec);
548 public override string ToString ()
550 return "StatementExpression (" + expr + ")";
555 /// Implements the return statement
557 public class Return : Statement {
558 public Expression Expr;
560 public Return (Expression expr, Location l)
568 public override bool Resolve (EmitContext ec)
570 AnonymousContainer am = ec.CurrentAnonymousMethod;
571 if ((am != null) && am.IsIterator && ec.InIterator) {
572 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
573 "statement to return a value, or yield break to end the iteration");
577 if (ec.ReturnType == null){
579 if (ec.CurrentAnonymousMethod != null){
580 Report.Error (1662, loc,
581 "Cannot convert anonymous method block to delegate type `{0}' because some of the return types in the block are not implicitly convertible to the delegate return type",
582 ec.CurrentAnonymousMethod.GetSignatureForError ());
584 Error (127, "A return keyword must not be followed by any expression when method returns void");
589 Error (126, "An object of a type convertible to `{0}' is required " +
590 "for the return statement",
591 TypeManager.CSharpName (ec.ReturnType));
595 Expr = Expr.Resolve (ec);
599 if (Expr.Type != ec.ReturnType) {
600 Expr = Convert.ImplicitConversionRequired (
601 ec, Expr, ec.ReturnType, loc);
607 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
609 if (ec.CurrentBranching.InTryOrCatch (true)) {
610 ec.CurrentBranching.AddFinallyVector (vector);
612 } else if (ec.InFinally) {
613 Error (157, "Control cannot leave the body of a finally clause");
616 vector.CheckOutParameters (ec.CurrentBranching);
619 ec.NeedReturnLabel ();
621 ec.CurrentBranching.CurrentUsageVector.Return ();
625 protected override void DoEmit (EmitContext ec)
631 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
635 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
637 ec.ig.Emit (OpCodes.Ret);
641 public class Goto : Statement {
643 LabeledStatement label;
645 public override bool Resolve (EmitContext ec)
647 label = ec.CurrentBranching.LookupLabel (target, loc);
651 // If this is a forward goto.
652 if (!label.IsDefined)
653 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
655 ec.CurrentBranching.CurrentUsageVector.Goto ();
656 label.AddReference ();
661 public Goto (string label, Location l)
667 public string Target {
673 protected override void DoEmit (EmitContext ec)
675 Label l = label.LabelTarget (ec);
676 ec.ig.Emit (OpCodes.Br, l);
680 public class LabeledStatement : Statement {
686 FlowBranching.UsageVector vectors;
688 public LabeledStatement (string label_name, Location l)
693 public Label LabelTarget (EmitContext ec)
698 label = ec.ig.DefineLabel ();
704 public bool IsDefined {
710 public bool HasBeenReferenced {
716 public void AddUsageVector (FlowBranching.UsageVector vector)
718 vector = vector.Clone ();
719 vector.Next = vectors;
723 public override bool Resolve (EmitContext ec)
725 ec.CurrentBranching.Label (vectors);
730 protected override void DoEmit (EmitContext ec)
732 if (ig != null && ig != ec.ig) {
733 // TODO: location is wrong
734 Report.Error (1632, loc, "Control cannot leave the body of an anonymous method");
738 ec.ig.MarkLabel (label);
741 public void AddReference ()
749 /// `goto default' statement
751 public class GotoDefault : Statement {
753 public GotoDefault (Location l)
758 public override bool Resolve (EmitContext ec)
760 ec.CurrentBranching.CurrentUsageVector.Goto ();
764 protected override void DoEmit (EmitContext ec)
766 if (ec.Switch == null){
767 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
771 if (!ec.Switch.GotDefault){
772 Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
775 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
780 /// `goto case' statement
782 public class GotoCase : Statement {
786 public GotoCase (Expression e, Location l)
792 public override bool Resolve (EmitContext ec)
794 if (ec.Switch == null){
795 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
799 expr = expr.Resolve (ec);
803 Constant c = expr as Constant;
805 Error (150, "A constant value is expected");
809 c = c.ToType (ec.Switch.SwitchType, loc);
813 object val = c.GetValue ();
817 sl = (SwitchLabel) ec.Switch.Elements [val];
820 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", c.GetValue () == null ? "null" : val);
824 ec.CurrentBranching.CurrentUsageVector.Goto ();
828 protected override void DoEmit (EmitContext ec)
830 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
834 public class Throw : Statement {
837 public Throw (Expression expr, Location l)
843 public override bool Resolve (EmitContext ec)
845 ec.CurrentBranching.CurrentUsageVector.Throw ();
848 expr = expr.Resolve (ec);
852 ExprClass eclass = expr.eclass;
854 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
855 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
856 expr.Error_UnexpectedKind (ec, "value, variable, property or indexer access ", loc);
862 if ((t != TypeManager.exception_type) &&
863 !t.IsSubclassOf (TypeManager.exception_type) &&
864 !(expr is NullLiteral)) {
866 "The type caught or thrown must be derived " +
867 "from System.Exception");
874 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
879 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
885 protected override void DoEmit (EmitContext ec)
888 ec.ig.Emit (OpCodes.Rethrow);
892 ec.ig.Emit (OpCodes.Throw);
897 public class Break : Statement {
899 public Break (Location l)
906 public override bool Resolve (EmitContext ec)
908 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
909 Error (139, "No enclosing loop out of which to break or continue");
911 } else if (ec.InFinally && ec.CurrentBranching.BreakCrossesTryCatchBoundary()) {
912 Error (157, "Control cannot leave the body of a finally clause");
914 } else if (ec.CurrentBranching.InTryOrCatch (false))
915 ec.CurrentBranching.AddFinallyVector (
916 ec.CurrentBranching.CurrentUsageVector);
917 else if (ec.CurrentBranching.InLoop () || ec.CurrentBranching.InSwitch ())
918 ec.CurrentBranching.AddBreakVector (
919 ec.CurrentBranching.CurrentUsageVector);
921 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
924 ec.NeedReturnLabel ();
926 ec.CurrentBranching.CurrentUsageVector.Break ();
930 protected override void DoEmit (EmitContext ec)
932 ILGenerator ig = ec.ig;
935 ig.Emit (OpCodes.Leave, ec.LoopEnd);
937 ig.Emit (OpCodes.Br, ec.LoopEnd);
942 public class Continue : Statement {
944 public Continue (Location l)
951 public override bool Resolve (EmitContext ec)
953 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
954 Error (139, "No enclosing loop out of which to break or continue");
956 } else if (ec.InFinally) {
957 Error (157, "Control cannot leave the body of a finally clause");
959 } else if (ec.CurrentBranching.InTryOrCatch (false))
960 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
962 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
964 ec.CurrentBranching.CurrentUsageVector.Goto ();
968 protected override void DoEmit (EmitContext ec)
970 Label begin = ec.LoopBegin;
973 ec.ig.Emit (OpCodes.Leave, begin);
975 ec.ig.Emit (OpCodes.Br, begin);
980 // The information about a user-perceived local variable
982 public class LocalInfo {
983 public Expression Type;
986 // Most of the time a variable will be stored in a LocalBuilder
988 // But sometimes, it will be stored in a field (variables that have been
989 // hoisted by iterators or by anonymous methods). The context of the field will
990 // be stored in the EmitContext
993 public LocalBuilder LocalBuilder;
994 public FieldBuilder FieldBuilder;
996 public Type VariableType;
997 public readonly string Name;
998 public readonly Location Location;
999 public readonly Block Block;
1001 public VariableInfo VariableInfo;
1010 CompilerGenerated = 64
1013 public enum ReadOnlyContext: byte {
1020 ReadOnlyContext ro_context;
1022 public LocalInfo (Expression type, string name, Block block, Location l)
1030 public LocalInfo (TypeContainer tc, Block block, Location l)
1032 VariableType = tc.TypeBuilder;
1037 public bool IsThisAssigned (EmitContext ec, Location loc)
1039 if (VariableInfo == null)
1040 throw new Exception ();
1042 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1045 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1048 public bool IsAssigned (EmitContext ec)
1050 if (VariableInfo == null)
1051 throw new Exception ();
1053 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1056 public bool Resolve (EmitContext ec)
1058 if (VariableType == null) {
1059 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1063 VariableType = texpr.ResolveType (ec);
1066 if (VariableType == TypeManager.void_type) {
1067 Report.Error (1547, Location,
1068 "Keyword 'void' cannot be used in this context");
1072 if (VariableType.IsAbstract && VariableType.IsSealed) {
1073 Report.Error (723, Location, "Cannot declare variable of static type `{0}'", TypeManager.CSharpName (VariableType));
1077 if (VariableType.IsPointer && !ec.InUnsafe)
1078 Expression.UnsafeError (Location);
1083 public bool IsCaptured {
1085 return (flags & Flags.Captured) != 0;
1089 flags |= Flags.Captured;
1093 public bool AddressTaken {
1095 return (flags & Flags.AddressTaken) != 0;
1099 flags |= Flags.AddressTaken;
1103 public bool CompilerGenerated {
1105 return (flags & Flags.CompilerGenerated) != 0;
1109 flags |= Flags.CompilerGenerated;
1113 public override string ToString ()
1115 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1116 Name, Type, VariableInfo, Location);
1121 return (flags & Flags.Used) != 0;
1124 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1128 public bool ReadOnly {
1130 return (flags & Flags.ReadOnly) != 0;
1134 public void SetReadOnlyContext (ReadOnlyContext context)
1136 flags |= Flags.ReadOnly;
1137 ro_context = context;
1140 public string GetReadOnlyContext ()
1143 throw new InternalErrorException ("Variable is not readonly");
1145 switch (ro_context) {
1146 case ReadOnlyContext.Fixed:
1147 return "fixed variable";
1148 case ReadOnlyContext.Foreach:
1149 return "foreach iteration variable";
1150 case ReadOnlyContext.Using:
1151 return "using variable";
1153 throw new NotImplementedException ();
1157 // Whether the variable is pinned, if Pinned the variable has been
1158 // allocated in a pinned slot with DeclareLocal.
1160 public bool Pinned {
1162 return (flags & Flags.Pinned) != 0;
1165 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1169 public bool IsThis {
1171 return (flags & Flags.IsThis) != 0;
1174 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1180 /// Block represents a C# block.
1184 /// This class is used in a number of places: either to represent
1185 /// explicit blocks that the programmer places or implicit blocks.
1187 /// Implicit blocks are used as labels or to introduce variable
1190 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1191 /// they contain extra information that is not necessary on normal blocks.
1193 public class Block : Statement {
1194 public Block Parent;
1195 public readonly Location StartLocation;
1196 public Location EndLocation = Location.Null;
1198 public readonly ToplevelBlock Toplevel;
1201 public enum Flags : ushort {
1205 VariablesInitialized = 8,
1210 HasVarargs = 256 // Used in ToplevelBlock
1212 protected Flags flags;
1214 public bool Implicit {
1215 get { return (flags & Flags.Implicit) != 0; }
1218 public bool Unchecked {
1219 get { return (flags & Flags.Unchecked) != 0; }
1220 set { flags |= Flags.Unchecked; }
1223 public bool Unsafe {
1224 get { return (flags & Flags.Unsafe) != 0; }
1225 set { flags |= Flags.Unsafe; }
1229 // The statements in this block
1231 ArrayList statements;
1235 // An array of Blocks. We keep track of children just
1236 // to generate the local variable declarations.
1238 // Statements and child statements are handled through the
1244 // Labels. (label, block) pairs.
1249 // Keeps track of (name, type) pairs
1251 Hashtable variables;
1254 // Keeps track of constants
1255 Hashtable constants;
1258 // Temporary variables.
1260 ArrayList temporary_variables;
1263 // If this is a switch section, the enclosing switch block.
1267 protected static int id;
1271 public Block (Block parent)
1272 : this (parent, (Flags) 0, Location.Null, Location.Null)
1275 public Block (Block parent, Flags flags)
1276 : this (parent, flags, Location.Null, Location.Null)
1279 public Block (Block parent, Location start, Location end)
1280 : this (parent, (Flags) 0, start, end)
1283 public Block (Block parent, Flags flags, Location start, Location end)
1286 parent.AddChild (this);
1288 this.Parent = parent;
1290 this.StartLocation = start;
1291 this.EndLocation = end;
1294 statements = new ArrayList ();
1296 if ((flags & Flags.IsToplevel) != 0)
1297 Toplevel = (ToplevelBlock) this;
1299 Toplevel = parent.Toplevel;
1301 if (parent != null && Implicit) {
1302 if (parent.known_variables == null)
1303 parent.known_variables = new Hashtable ();
1304 // share with parent
1305 known_variables = parent.known_variables;
1310 public Block CreateSwitchBlock (Location start)
1312 Block new_block = new Block (this, start, start);
1313 new_block.switch_block = this;
1318 get { return this_id; }
1321 protected Hashtable Variables {
1323 if (variables == null)
1324 variables = new Hashtable ();
1329 void AddChild (Block b)
1331 if (children == null)
1332 children = new ArrayList ();
1337 public void SetEndLocation (Location loc)
1343 /// Adds a label to the current block.
1347 /// false if the name already exists in this block. true
1351 public bool AddLabel (string name, LabeledStatement target, Location loc)
1353 if (switch_block != null)
1354 return switch_block.AddLabel (name, target, loc);
1357 while (cur != null) {
1358 if (cur.DoLookupLabel (name) != null) {
1360 140, loc, "The label `{0}' is a duplicate",
1371 while (cur != null) {
1372 if (cur.DoLookupLabel (name) != null) {
1375 "The label `{0}' shadows another label " +
1376 "by the same name in a contained scope.",
1381 if (children != null) {
1382 foreach (Block b in children) {
1383 LabeledStatement s = b.DoLookupLabel (name);
1389 "The label `{0}' shadows another " +
1390 "label by the same name in a " +
1402 labels = new Hashtable ();
1404 labels.Add (name, target);
1408 public LabeledStatement LookupLabel (string name)
1410 LabeledStatement s = DoLookupLabel (name);
1414 if (children == null)
1417 foreach (Block child in children) {
1418 if (!child.Implicit)
1421 s = child.LookupLabel (name);
1429 LabeledStatement DoLookupLabel (string name)
1431 if (switch_block != null)
1432 return switch_block.LookupLabel (name);
1435 if (labels.Contains (name))
1436 return ((LabeledStatement) labels [name]);
1441 Hashtable known_variables;
1444 // Marks a variable with name @name as being used in this or a child block.
1445 // If a variable name has been used in a child block, it's illegal to
1446 // declare a variable with the same name in the current block.
1448 void AddKnownVariable (string name, LocalInfo info)
1450 if (known_variables == null)
1451 known_variables = new Hashtable ();
1453 known_variables [name] = info;
1456 LocalInfo GetKnownVariableInfo (string name)
1458 if (known_variables == null)
1460 return (LocalInfo) known_variables [name];
1463 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1466 LocalInfo kvi = b.GetKnownVariableInfo (name);
1467 while (kvi == null) {
1473 kvi = b.GetKnownVariableInfo (name);
1479 // Is kvi.Block nested inside 'b'
1480 if (b.known_variables != kvi.Block.known_variables) {
1482 // If a variable by the same name it defined in a nested block of this
1483 // block, we violate the invariant meaning in a block.
1486 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1487 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1492 // It's ok if the definition is in a nested subblock of b, but not
1493 // nested inside this block -- a definition in a sibling block
1494 // should not affect us.
1500 // Block 'b' and kvi.Block are the same textual block.
1501 // However, different variables are extant.
1503 // Check if the variable is in scope in both blocks. We use
1504 // an indirect check that depends on AddVariable doing its
1505 // part in maintaining the invariant-meaning-in-block property.
1507 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1511 // Even though we detected the error when the name is used, we
1512 // treat it as if the variable declaration was in error.
1514 Report.SymbolRelatedToPreviousError (loc, name);
1515 Error_AlreadyDeclared (kvi.Location, name, "child");
1519 public LocalInfo AddVariable (Expression type, string name, Location l)
1521 LocalInfo vi = GetLocalInfo (name);
1523 Report.SymbolRelatedToPreviousError (vi.Location, name);
1524 if (known_variables == vi.Block.known_variables)
1525 Report.Error (128, l,
1526 "A local variable named `{0}' is already defined in this scope", name);
1528 Error_AlreadyDeclared (l, name, "parent");
1532 vi = GetKnownVariableInfo (name);
1534 Report.SymbolRelatedToPreviousError (vi.Location, name);
1535 Error_AlreadyDeclared (l, name, "child");
1540 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1542 Report.SymbolRelatedToPreviousError (p.Location, name);
1543 Error_AlreadyDeclared (l, name, "method argument");
1547 vi = new LocalInfo (type, name, this, l);
1549 Variables.Add (name, vi);
1551 for (Block b = this; b != null; b = b.Parent)
1552 b.AddKnownVariable (name, vi);
1554 if ((flags & Flags.VariablesInitialized) != 0)
1555 throw new Exception ();
1560 void Error_AlreadyDeclared (Location loc, string var, string reason)
1562 Report.Error (136, loc, "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning to `{0}', " +
1563 "which is already used in a `{1}' scope", var, reason);
1566 public bool AddConstant (Expression type, string name, Expression value, Location l)
1568 if (AddVariable (type, name, l) == null)
1571 if (constants == null)
1572 constants = new Hashtable ();
1574 constants.Add (name, value);
1578 static int next_temp_id = 0;
1580 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1582 if (temporary_variables == null)
1583 temporary_variables = new ArrayList ();
1585 int id = ++next_temp_id;
1586 string name = "$s_" + id.ToString ();
1588 LocalInfo li = new LocalInfo (te, name, this, loc);
1589 li.CompilerGenerated = true;
1590 temporary_variables.Add (li);
1594 public LocalInfo GetLocalInfo (string name)
1596 for (Block b = this; b != null; b = b.Parent) {
1597 if (b.variables != null) {
1598 LocalInfo ret = b.variables [name] as LocalInfo;
1606 public Expression GetVariableType (string name)
1608 LocalInfo vi = GetLocalInfo (name);
1609 return vi == null ? null : vi.Type;
1612 public Expression GetConstantExpression (string name)
1614 for (Block b = this; b != null; b = b.Parent) {
1615 if (b.constants != null) {
1616 Expression ret = b.constants [name] as Expression;
1625 /// True if the variable named @name is a constant
1627 public bool IsConstant (string name)
1629 Expression e = GetConstantExpression (name);
1633 public void AddStatement (Statement s)
1636 flags |= Flags.BlockUsed;
1640 get { return (flags & Flags.BlockUsed) != 0; }
1645 flags |= Flags.BlockUsed;
1648 public bool HasRet {
1649 get { return (flags & Flags.HasRet) != 0; }
1652 public bool IsDestructor {
1653 get { return (flags & Flags.IsDestructor) != 0; }
1656 public void SetDestructor ()
1658 flags |= Flags.IsDestructor;
1661 VariableMap param_map, local_map;
1663 public VariableMap ParameterMap {
1665 if ((flags & Flags.VariablesInitialized) == 0)
1666 throw new Exception ("Variables have not been initialized yet");
1672 public VariableMap LocalMap {
1674 if ((flags & Flags.VariablesInitialized) == 0)
1675 throw new Exception ("Variables have not been initialized yet");
1682 /// Emits the variable declarations and labels.
1685 /// tc: is our typecontainer (to resolve type references)
1686 /// ig: is the code generator:
1688 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1690 bool old_unsafe = ec.InUnsafe;
1692 // If some parent block was unsafe, we remain unsafe even if this block
1693 // isn't explicitly marked as such.
1694 ec.InUnsafe |= Unsafe;
1697 // Compute the VariableMap's.
1699 // Unfortunately, we don't know the type when adding variables with
1700 // AddVariable(), so we need to compute this info here.
1704 if (variables != null) {
1705 foreach (LocalInfo li in variables.Values)
1708 locals = new LocalInfo [variables.Count];
1709 variables.Values.CopyTo (locals, 0);
1711 locals = new LocalInfo [0];
1714 local_map = new VariableMap (Parent.LocalMap, locals);
1716 local_map = new VariableMap (locals);
1718 param_map = new VariableMap (ip);
1719 flags |= Flags.VariablesInitialized;
1721 bool old_check_state = ec.ConstantCheckState;
1722 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1725 // Process this block variables
1727 if (variables != null){
1728 foreach (DictionaryEntry de in variables){
1729 string name = (string) de.Key;
1730 LocalInfo vi = (LocalInfo) de.Value;
1732 if (vi.VariableType == null)
1735 Type variable_type = vi.VariableType;
1737 if (variable_type.IsPointer){
1739 // Am not really convinced that this test is required (Microsoft does it)
1740 // but the fact is that you would not be able to use the pointer variable
1743 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1748 if (constants == null)
1751 Expression cv = (Expression) constants [name];
1755 ec.CurrentBlock = this;
1756 Expression e = cv.Resolve (ec);
1758 Constant ce = e as Constant;
1760 Const.Error_ExpressionMustBeConstant (vi.Location, name);
1764 e = ce.ToType (variable_type, vi.Location);
1768 constants.Remove (name);
1769 constants.Add (name, e);
1772 ec.ConstantCheckState = old_check_state;
1775 // Now, handle the children
1777 if (children != null){
1778 foreach (Block b in children)
1779 b.ResolveMeta (toplevel, ec, ip);
1781 ec.InUnsafe = old_unsafe;
1785 // Emits the local variable declarations for a block
1787 public void EmitMeta (EmitContext ec)
1789 ILGenerator ig = ec.ig;
1791 if (variables != null){
1792 bool have_captured_vars = ec.HaveCapturedVariables ();
1794 foreach (DictionaryEntry de in variables){
1795 LocalInfo vi = (LocalInfo) de.Value;
1797 if (have_captured_vars && ec.IsCaptured (vi))
1802 // This is needed to compile on both .NET 1.x and .NET 2.x
1803 // the later introduced `DeclareLocal (Type t, bool pinned)'
1805 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1806 else if (!vi.IsThis)
1807 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1811 if (temporary_variables != null) {
1812 AnonymousContainer am = ec.CurrentAnonymousMethod;
1813 TypeBuilder scope = null;
1814 if ((am != null) && am.IsIterator) {
1815 scope = am.Scope.ScopeTypeBuilder;
1817 throw new InternalErrorException ();
1819 foreach (LocalInfo vi in temporary_variables) {
1820 if (scope != null) {
1821 if (vi.FieldBuilder == null)
1822 vi.FieldBuilder = scope.DefineField (
1823 vi.Name, vi.VariableType, FieldAttributes.Assembly);
1825 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1829 if (children != null){
1830 foreach (Block b in children)
1835 void UsageWarning (FlowBranching.UsageVector vector)
1839 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1840 foreach (DictionaryEntry de in variables){
1841 LocalInfo vi = (LocalInfo) de.Value;
1846 name = (string) de.Key;
1848 if (vector.IsAssigned (vi.VariableInfo)){
1849 Report.Warning (219, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
1851 Report.Warning (168, vi.Location, "The variable `{0}' is declared but never used", name);
1857 bool unreachable_shown;
1860 public override bool Resolve (EmitContext ec)
1862 Block prev_block = ec.CurrentBlock;
1865 int errors = Report.Errors;
1867 ec.CurrentBlock = this;
1868 ec.StartFlowBranching (this);
1870 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1872 int statement_count = statements.Count;
1873 for (int ix = 0; ix < statement_count; ix++){
1874 Statement s = (Statement) statements [ix];
1877 // Warn if we detect unreachable code.
1881 ((Block) s).unreachable = true;
1883 if (!unreachable_shown && (RootContext.WarningLevel >= 2)) {
1885 162, loc, "Unreachable code detected");
1886 unreachable_shown = true;
1891 // Note that we're not using ResolveUnreachable() for unreachable
1892 // statements here. ResolveUnreachable() creates a temporary
1893 // flow branching and kills it afterwards. This leads to problems
1894 // if you have two unreachable statements where the first one
1895 // assigns a variable and the second one tries to access it.
1898 if (!s.Resolve (ec)) {
1900 statements [ix] = EmptyStatement.Value;
1904 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1905 statements [ix] = EmptyStatement.Value;
1907 num_statements = ix + 1;
1908 if (s is LabeledStatement)
1909 unreachable = false;
1911 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1914 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1915 ec.CurrentBranching, statement_count, num_statements);
1917 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1919 ec.CurrentBlock = prev_block;
1921 // If we're a non-static `struct' constructor which doesn't have an
1922 // initializer, then we must initialize all of the struct's fields.
1923 if ((flags & Flags.IsToplevel) != 0 &&
1924 !Toplevel.IsThisAssigned (ec) &&
1925 vector.Reachability.Throws != FlowBranching.FlowReturns.Always)
1928 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1929 foreach (LabeledStatement label in labels.Values)
1930 if (!label.HasBeenReferenced)
1931 Report.Warning (164, label.loc,
1932 "This label has not been referenced");
1935 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1937 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1938 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1939 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1940 flags |= Flags.HasRet;
1942 if (ok && (errors == Report.Errors)) {
1943 if (RootContext.WarningLevel >= 3)
1944 UsageWarning (vector);
1950 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1952 unreachable_shown = true;
1955 if (warn && (RootContext.WarningLevel >= 2))
1956 Report.Warning (162, loc, "Unreachable code detected");
1958 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1959 bool ok = Resolve (ec);
1960 ec.KillFlowBranching ();
1965 protected override void DoEmit (EmitContext ec)
1967 for (int ix = 0; ix < num_statements; ix++){
1968 Statement s = (Statement) statements [ix];
1970 // Check whether we are the last statement in a
1973 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
1974 ec.IsLastStatement = true;
1976 ec.IsLastStatement = false;
1982 public override void Emit (EmitContext ec)
1984 Block prev_block = ec.CurrentBlock;
1986 ec.CurrentBlock = this;
1988 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1989 bool is_lexical_block = !Implicit && (Parent != null);
1991 if (emit_debug_info) {
1992 if (is_lexical_block)
1995 if (variables != null) {
1996 foreach (DictionaryEntry de in variables) {
1997 string name = (string) de.Key;
1998 LocalInfo vi = (LocalInfo) de.Value;
2000 if (vi.LocalBuilder == null)
2003 ec.DefineLocalVariable (name, vi.LocalBuilder);
2008 ec.Mark (StartLocation, true);
2010 ec.Mark (EndLocation, true);
2012 if (emit_debug_info && is_lexical_block)
2015 ec.CurrentBlock = prev_block;
2019 // Returns true if we ar ea child of `b'.
2021 public bool IsChildOf (Block b)
2023 Block current = this;
2026 if (current.Parent == b)
2028 current = current.Parent;
2029 } while (current != null);
2033 public override string ToString ()
2035 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2040 // A toplevel block contains extra information, the split is done
2041 // only to separate information that would otherwise bloat the more
2042 // lightweight Block.
2044 // In particular, this was introduced when the support for Anonymous
2045 // Methods was implemented.
2047 public class ToplevelBlock : Block {
2049 // Pointer to the host of this anonymous method, or null
2050 // if we are the topmost block
2052 ToplevelBlock container;
2053 CaptureContext capture_context;
2054 FlowBranching top_level_branching;
2056 Hashtable capture_contexts;
2059 public bool HasVarargs {
2060 get { return (flags & Flags.HasVarargs) != 0; }
2061 set { flags |= Flags.HasVarargs; }
2065 // The parameters for the block.
2067 public readonly Parameters Parameters;
2069 public void RegisterCaptureContext (CaptureContext cc)
2071 if (capture_contexts == null)
2072 capture_contexts = new Hashtable ();
2073 capture_contexts [cc] = cc;
2076 public void CompleteContexts ()
2078 if (capture_contexts == null)
2081 foreach (CaptureContext cc in capture_contexts.Keys){
2086 public CaptureContext ToplevelBlockCaptureContext {
2087 get { return capture_context; }
2090 public ToplevelBlock Container {
2091 get { return container; }
2094 protected void AddChild (ToplevelBlock block)
2096 if (children == null)
2097 children = new ArrayList ();
2099 children.Add (block);
2103 // Parent is only used by anonymous blocks to link back to their
2106 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2107 this (container, (Flags) 0, parameters, start)
2111 public ToplevelBlock (Parameters parameters, Location start) :
2112 this (null, (Flags) 0, parameters, start)
2116 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2117 this (null, flags, parameters, start)
2121 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2122 base (null, flags | Flags.IsToplevel, start, Location.Null)
2124 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2125 this.container = container;
2127 if (container != null)
2128 container.AddChild (this);
2131 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2135 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2137 if (capture_context == null)
2138 capture_context = new CaptureContext (this, loc, host);
2141 public CaptureContext CaptureContext {
2142 get { return capture_context; }
2145 public FlowBranching TopLevelBranching {
2146 get { return top_level_branching; }
2150 // This is used if anonymous methods are used inside an iterator
2151 // (see 2test-22.cs for an example).
2153 // The AnonymousMethod is created while parsing - at a time when we don't
2154 // know yet that we're inside an iterator, so it's `Container' is initially
2155 // null. Later on, when resolving the iterator, we need to move the
2156 // anonymous method into that iterator.
2158 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2160 foreach (ToplevelBlock block in children) {
2161 if (block.CaptureContext == null)
2164 block.container = new_parent;
2165 block.CaptureContext.ReParent (new_parent, new_host);
2170 // Returns a `ParameterReference' for the given name, or null if there
2171 // is no such parameter
2173 public ParameterReference GetParameterReference (string name, Location loc)
2178 for (ToplevelBlock t = this; t != null; t = t.Container) {
2179 Parameters pars = t.Parameters;
2180 par = pars.GetParameterByName (name, out idx);
2182 return new ParameterReference (pars, this, idx, name, loc);
2188 // Whether the parameter named `name' is local to this block,
2189 // or false, if the parameter belongs to an encompassing block.
2191 public bool IsLocalParameter (string name)
2193 return Parameters.GetParameterByName (name) != null;
2197 // Whether the `name' is a parameter reference
2199 public bool IsParameterReference (string name)
2201 for (ToplevelBlock t = this; t != null; t = t.Container) {
2202 if (t.IsLocalParameter (name))
2208 LocalInfo this_variable = null;
2211 // Returns the "this" instance variable of this block.
2212 // See AddThisVariable() for more information.
2214 public LocalInfo ThisVariable {
2215 get { return this_variable; }
2220 // This is used by non-static `struct' constructors which do not have an
2221 // initializer - in this case, the constructor must initialize all of the
2222 // struct's fields. To do this, we add a "this" variable and use the flow
2223 // analysis code to ensure that it's been fully initialized before control
2224 // leaves the constructor.
2226 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
2228 if (this_variable == null) {
2229 this_variable = new LocalInfo (tc, this, l);
2230 this_variable.Used = true;
2231 this_variable.IsThis = true;
2233 Variables.Add ("this", this_variable);
2236 return this_variable;
2239 public bool IsThisAssigned (EmitContext ec)
2241 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2244 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2246 int errors = Report.Errors;
2248 if (top_level_branching != null)
2251 ResolveMeta (this, ec, ip);
2253 top_level_branching = ec.StartFlowBranching (this);
2255 return Report.Errors == errors;
2259 public class SwitchLabel {
2266 Label il_label_code;
2267 bool il_label_code_set;
2270 // if expr == null, then it is the default case.
2272 public SwitchLabel (Expression expr, Location l)
2278 public Expression Label {
2284 public object Converted {
2290 public Label GetILLabel (EmitContext ec)
2293 il_label = ec.ig.DefineLabel ();
2294 il_label_set = true;
2299 public Label GetILLabelCode (EmitContext ec)
2301 if (!il_label_code_set){
2302 il_label_code = ec.ig.DefineLabel ();
2303 il_label_code_set = true;
2305 return il_label_code;
2309 // Resolves the expression, reduces it to a literal if possible
2310 // and then converts it to the requested type.
2312 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2314 Expression e = label.Resolve (ec);
2319 Constant c = e as Constant;
2321 Report.Error (150, loc, "A constant value is expected");
2325 if (required_type == TypeManager.string_type && e is NullLiteral) {
2330 c = c.ToType (required_type, loc);
2334 converted = c.GetValue ();
2338 public void Erorr_AlreadyOccurs ()
2341 if (converted == null)
2343 else if (converted is NullLiteral)
2346 label = converted.ToString ();
2348 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2352 public class SwitchSection {
2353 // An array of SwitchLabels.
2354 public readonly ArrayList Labels;
2355 public readonly Block Block;
2357 public SwitchSection (ArrayList labels, Block block)
2364 public class Switch : Statement {
2365 public readonly ArrayList Sections;
2366 public Expression Expr;
2369 /// Maps constants whose type type SwitchType to their SwitchLabels.
2371 public IDictionary Elements;
2374 /// The governing switch type
2376 public Type SwitchType;
2381 Label default_target;
2382 Expression new_expr;
2384 SwitchSection constant_section;
2385 SwitchSection default_section;
2388 // The types allowed to be implicitly cast from
2389 // on the governing type
2391 static Type [] allowed_types;
2393 public Switch (Expression e, ArrayList sects, Location l)
2400 public bool GotDefault {
2402 return default_section != null;
2406 public Label DefaultTarget {
2408 return default_target;
2413 // Determines the governing type for a switch. The returned
2414 // expression might be the expression from the switch, or an
2415 // expression that includes any potential conversions to the
2416 // integral types or to string.
2418 Expression SwitchGoverningType (EmitContext ec, Type t)
2420 if (t == TypeManager.byte_type ||
2421 t == TypeManager.sbyte_type ||
2422 t == TypeManager.ushort_type ||
2423 t == TypeManager.short_type ||
2424 t == TypeManager.uint32_type ||
2425 t == TypeManager.int32_type ||
2426 t == TypeManager.uint64_type ||
2427 t == TypeManager.int64_type ||
2428 t == TypeManager.char_type ||
2429 t == TypeManager.string_type ||
2430 t == TypeManager.bool_type ||
2431 t.IsSubclassOf (TypeManager.enum_type))
2434 if (allowed_types == null){
2435 allowed_types = new Type [] {
2436 TypeManager.sbyte_type,
2437 TypeManager.byte_type,
2438 TypeManager.short_type,
2439 TypeManager.ushort_type,
2440 TypeManager.int32_type,
2441 TypeManager.uint32_type,
2442 TypeManager.int64_type,
2443 TypeManager.uint64_type,
2444 TypeManager.char_type,
2445 TypeManager.string_type,
2446 TypeManager.bool_type
2451 // Try to find a *user* defined implicit conversion.
2453 // If there is no implicit conversion, or if there are multiple
2454 // conversions, we have to report an error
2456 Expression converted = null;
2457 foreach (Type tt in allowed_types){
2460 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2465 // Ignore over-worked ImplicitUserConversions that do
2466 // an implicit conversion in addition to the user conversion.
2468 if (!(e is UserCast))
2471 if (converted != null){
2472 Report.ExtraInformation (
2474 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2475 TypeManager.CSharpName (Expr.Type)));
2485 // Performs the basic sanity checks on the switch statement
2486 // (looks for duplicate keys and non-constant expressions).
2488 // It also returns a hashtable with the keys that we will later
2489 // use to compute the switch tables
2491 bool CheckSwitch (EmitContext ec)
2494 Elements = Sections.Count > 10 ?
2495 (IDictionary)new Hashtable () :
2496 (IDictionary)new ListDictionary ();
2498 foreach (SwitchSection ss in Sections){
2499 foreach (SwitchLabel sl in ss.Labels){
2500 if (sl.Label == null){
2501 if (default_section != null){
2502 sl.Erorr_AlreadyOccurs ();
2505 default_section = ss;
2509 if (!sl.ResolveAndReduce (ec, SwitchType)){
2514 object key = sl.Converted;
2516 Elements.Add (key, sl);
2518 catch (ArgumentException) {
2519 sl.Erorr_AlreadyOccurs ();
2527 void EmitObjectInteger (ILGenerator ig, object k)
2530 IntConstant.EmitInt (ig, (int) k);
2531 else if (k is Constant) {
2532 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2535 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2538 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2540 IntConstant.EmitInt (ig, (int) (long) k);
2541 ig.Emit (OpCodes.Conv_I8);
2544 LongConstant.EmitLong (ig, (long) k);
2546 else if (k is ulong)
2548 if ((ulong) k < (1L<<32))
2550 IntConstant.EmitInt (ig, (int) (long) k);
2551 ig.Emit (OpCodes.Conv_U8);
2555 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2559 IntConstant.EmitInt (ig, (int) ((char) k));
2560 else if (k is sbyte)
2561 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2563 IntConstant.EmitInt (ig, (int) ((byte) k));
2564 else if (k is short)
2565 IntConstant.EmitInt (ig, (int) ((short) k));
2566 else if (k is ushort)
2567 IntConstant.EmitInt (ig, (int) ((ushort) k));
2569 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2571 throw new Exception ("Unhandled case");
2574 // structure used to hold blocks of keys while calculating table switch
2575 class KeyBlock : IComparable
2577 public KeyBlock (long _nFirst)
2579 nFirst = nLast = _nFirst;
2583 public ArrayList rgKeys = null;
2584 // how many items are in the bucket
2585 public int Size = 1;
2588 get { return (int) (nLast - nFirst + 1); }
2590 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2592 return kbLast.nLast - kbFirst.nFirst + 1;
2594 public int CompareTo (object obj)
2596 KeyBlock kb = (KeyBlock) obj;
2597 int nLength = Length;
2598 int nLengthOther = kb.Length;
2599 if (nLengthOther == nLength)
2600 return (int) (kb.nFirst - nFirst);
2601 return nLength - nLengthOther;
2606 /// This method emits code for a lookup-based switch statement (non-string)
2607 /// Basically it groups the cases into blocks that are at least half full,
2608 /// and then spits out individual lookup opcodes for each block.
2609 /// It emits the longest blocks first, and short blocks are just
2610 /// handled with direct compares.
2612 /// <param name="ec"></param>
2613 /// <param name="val"></param>
2614 /// <returns></returns>
2615 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2617 int cElements = Elements.Count;
2618 object [] rgKeys = new object [cElements];
2619 Elements.Keys.CopyTo (rgKeys, 0);
2620 Array.Sort (rgKeys);
2622 // initialize the block list with one element per key
2623 ArrayList rgKeyBlocks = new ArrayList ();
2624 foreach (object key in rgKeys)
2625 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2628 // iteratively merge the blocks while they are at least half full
2629 // there's probably a really cool way to do this with a tree...
2630 while (rgKeyBlocks.Count > 1)
2632 ArrayList rgKeyBlocksNew = new ArrayList ();
2633 kbCurr = (KeyBlock) rgKeyBlocks [0];
2634 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2636 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2637 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2640 kbCurr.nLast = kb.nLast;
2641 kbCurr.Size += kb.Size;
2645 // start a new block
2646 rgKeyBlocksNew.Add (kbCurr);
2650 rgKeyBlocksNew.Add (kbCurr);
2651 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2653 rgKeyBlocks = rgKeyBlocksNew;
2656 // initialize the key lists
2657 foreach (KeyBlock kb in rgKeyBlocks)
2658 kb.rgKeys = new ArrayList ();
2660 // fill the key lists
2662 if (rgKeyBlocks.Count > 0) {
2663 kbCurr = (KeyBlock) rgKeyBlocks [0];
2664 foreach (object key in rgKeys)
2666 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2667 System.Convert.ToInt64 (key) > kbCurr.nLast;
2669 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2670 kbCurr.rgKeys.Add (key);
2674 // sort the blocks so we can tackle the largest ones first
2675 rgKeyBlocks.Sort ();
2677 // okay now we can start...
2678 ILGenerator ig = ec.ig;
2679 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2680 Label lblDefault = ig.DefineLabel ();
2682 Type typeKeys = null;
2683 if (rgKeys.Length > 0)
2684 typeKeys = rgKeys [0].GetType (); // used for conversions
2688 if (TypeManager.IsEnumType (SwitchType))
2689 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2691 compare_type = SwitchType;
2693 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2695 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2696 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2699 foreach (object key in kb.rgKeys)
2701 ig.Emit (OpCodes.Ldloc, val);
2702 EmitObjectInteger (ig, key);
2703 SwitchLabel sl = (SwitchLabel) Elements [key];
2704 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2709 // TODO: if all the keys in the block are the same and there are
2710 // no gaps/defaults then just use a range-check.
2711 if (compare_type == TypeManager.int64_type ||
2712 compare_type == TypeManager.uint64_type)
2714 // TODO: optimize constant/I4 cases
2716 // check block range (could be > 2^31)
2717 ig.Emit (OpCodes.Ldloc, val);
2718 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2719 ig.Emit (OpCodes.Blt, lblDefault);
2720 ig.Emit (OpCodes.Ldloc, val);
2721 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2722 ig.Emit (OpCodes.Bgt, lblDefault);
2725 ig.Emit (OpCodes.Ldloc, val);
2728 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2729 ig.Emit (OpCodes.Sub);
2731 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2736 ig.Emit (OpCodes.Ldloc, val);
2737 int nFirst = (int) kb.nFirst;
2740 IntConstant.EmitInt (ig, nFirst);
2741 ig.Emit (OpCodes.Sub);
2743 else if (nFirst < 0)
2745 IntConstant.EmitInt (ig, -nFirst);
2746 ig.Emit (OpCodes.Add);
2750 // first, build the list of labels for the switch
2752 int cJumps = kb.Length;
2753 Label [] rgLabels = new Label [cJumps];
2754 for (int iJump = 0; iJump < cJumps; iJump++)
2756 object key = kb.rgKeys [iKey];
2757 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2759 SwitchLabel sl = (SwitchLabel) Elements [key];
2760 rgLabels [iJump] = sl.GetILLabel (ec);
2764 rgLabels [iJump] = lblDefault;
2766 // emit the switch opcode
2767 ig.Emit (OpCodes.Switch, rgLabels);
2770 // mark the default for this block
2772 ig.MarkLabel (lblDefault);
2775 // TODO: find the default case and emit it here,
2776 // to prevent having to do the following jump.
2777 // make sure to mark other labels in the default section
2779 // the last default just goes to the end
2780 ig.Emit (OpCodes.Br, lblDefault);
2782 // now emit the code for the sections
2783 bool fFoundDefault = false;
2784 foreach (SwitchSection ss in Sections)
2786 foreach (SwitchLabel sl in ss.Labels)
2788 ig.MarkLabel (sl.GetILLabel (ec));
2789 ig.MarkLabel (sl.GetILLabelCode (ec));
2790 if (sl.Label == null)
2792 ig.MarkLabel (lblDefault);
2793 fFoundDefault = true;
2797 //ig.Emit (OpCodes.Br, lblEnd);
2800 if (!fFoundDefault) {
2801 ig.MarkLabel (lblDefault);
2803 ig.MarkLabel (lblEnd);
2806 // This simple emit switch works, but does not take advantage of the
2808 // TODO: remove non-string logic from here
2809 // TODO: binary search strings?
2811 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2813 ILGenerator ig = ec.ig;
2814 Label end_of_switch = ig.DefineLabel ();
2815 Label next_test = ig.DefineLabel ();
2816 Label null_target = ig.DefineLabel ();
2817 bool first_test = true;
2818 bool pending_goto_end = false;
2819 bool null_marked = false;
2822 ig.Emit (OpCodes.Ldloc, val);
2824 if (Elements.Contains (NullLiteral.Null)){
2825 ig.Emit (OpCodes.Brfalse, null_target);
2827 ig.Emit (OpCodes.Brfalse, default_target);
2829 ig.Emit (OpCodes.Ldloc, val);
2830 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2831 ig.Emit (OpCodes.Stloc, val);
2833 int section_count = Sections.Count;
2834 for (int section = 0; section < section_count; section++){
2835 SwitchSection ss = (SwitchSection) Sections [section];
2837 if (ss == default_section)
2840 Label sec_begin = ig.DefineLabel ();
2842 ig.Emit (OpCodes.Nop);
2844 if (pending_goto_end)
2845 ig.Emit (OpCodes.Br, end_of_switch);
2847 int label_count = ss.Labels.Count;
2849 for (int label = 0; label < label_count; label++){
2850 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2851 ig.MarkLabel (sl.GetILLabel (ec));
2854 ig.MarkLabel (next_test);
2855 next_test = ig.DefineLabel ();
2858 // If we are the default target
2860 if (sl.Label != null){
2861 object lit = sl.Converted;
2863 if (lit is NullLiteral){
2865 if (label_count == 1)
2866 ig.Emit (OpCodes.Br, next_test);
2870 ig.Emit (OpCodes.Ldloc, val);
2871 ig.Emit (OpCodes.Ldstr, (string)lit);
2872 if (label_count == 1)
2873 ig.Emit (OpCodes.Bne_Un, next_test);
2875 if (label+1 == label_count)
2876 ig.Emit (OpCodes.Bne_Un, next_test);
2878 ig.Emit (OpCodes.Beq, sec_begin);
2883 ig.MarkLabel (null_target);
2886 ig.MarkLabel (sec_begin);
2887 foreach (SwitchLabel sl in ss.Labels)
2888 ig.MarkLabel (sl.GetILLabelCode (ec));
2891 pending_goto_end = !ss.Block.HasRet;
2894 ig.MarkLabel (next_test);
2895 ig.MarkLabel (default_target);
2897 ig.MarkLabel (null_target);
2898 if (default_section != null)
2899 default_section.Block.Emit (ec);
2900 ig.MarkLabel (end_of_switch);
2903 SwitchSection FindSection (SwitchLabel label)
2905 foreach (SwitchSection ss in Sections){
2906 foreach (SwitchLabel sl in ss.Labels){
2915 public override bool Resolve (EmitContext ec)
2917 Expr = Expr.Resolve (ec);
2921 new_expr = SwitchGoverningType (ec, Expr.Type);
2922 if (new_expr == null){
2923 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2928 SwitchType = new_expr.Type;
2930 if (!CheckSwitch (ec))
2933 Switch old_switch = ec.Switch;
2935 ec.Switch.SwitchType = SwitchType;
2937 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2938 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2940 is_constant = new_expr is Constant;
2942 object key = ((Constant) new_expr).GetValue ();
2943 SwitchLabel label = (SwitchLabel) Elements [key];
2945 constant_section = FindSection (label);
2946 if (constant_section == null)
2947 constant_section = default_section;
2951 foreach (SwitchSection ss in Sections){
2953 ec.CurrentBranching.CreateSibling (
2954 null, FlowBranching.SiblingType.SwitchSection);
2958 if (is_constant && (ss != constant_section)) {
2959 // If we're a constant switch, we're only emitting
2960 // one single section - mark all the others as
2962 ec.CurrentBranching.CurrentUsageVector.Goto ();
2963 if (!ss.Block.ResolveUnreachable (ec, true))
2966 if (!ss.Block.Resolve (ec))
2971 if (default_section == null)
2972 ec.CurrentBranching.CreateSibling (
2973 null, FlowBranching.SiblingType.SwitchSection);
2975 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2976 ec.Switch = old_switch;
2978 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2984 protected override void DoEmit (EmitContext ec)
2986 ILGenerator ig = ec.ig;
2988 // Store variable for comparission purposes
2991 value = ig.DeclareLocal (SwitchType);
2993 ig.Emit (OpCodes.Stloc, value);
2997 default_target = ig.DefineLabel ();
3000 // Setup the codegen context
3002 Label old_end = ec.LoopEnd;
3003 Switch old_switch = ec.Switch;
3005 ec.LoopEnd = ig.DefineLabel ();
3010 if (constant_section != null)
3011 constant_section.Block.Emit (ec);
3012 } else if (SwitchType == TypeManager.string_type)
3013 SimpleSwitchEmit (ec, value);
3015 TableSwitchEmit (ec, value);
3017 // Restore context state.
3018 ig.MarkLabel (ec.LoopEnd);
3021 // Restore the previous context
3023 ec.LoopEnd = old_end;
3024 ec.Switch = old_switch;
3028 public abstract class ExceptionStatement : Statement
3030 public abstract void EmitFinally (EmitContext ec);
3032 protected bool emit_finally = true;
3033 ArrayList parent_vectors;
3035 protected void DoEmitFinally (EmitContext ec)
3038 ec.ig.BeginFinallyBlock ();
3039 else if (ec.InIterator)
3040 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3044 protected void ResolveFinally (FlowBranchingException branching)
3046 emit_finally = branching.EmitFinally;
3048 branching.Parent.StealFinallyClauses (ref parent_vectors);
3052 public class Lock : ExceptionStatement {
3054 Statement Statement;
3057 public Lock (Expression expr, Statement stmt, Location l)
3064 public override bool Resolve (EmitContext ec)
3066 expr = expr.Resolve (ec);
3070 if (expr.Type.IsValueType){
3071 Report.Error (185, loc,
3072 "`{0}' is not a reference type as required by the lock statement",
3073 TypeManager.CSharpName (expr.Type));
3077 FlowBranchingException branching = ec.StartFlowBranching (this);
3078 bool ok = Statement.Resolve (ec);
3080 ec.KillFlowBranching ();
3084 ResolveFinally (branching);
3086 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3087 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3088 // Unfortunately, System.Reflection.Emit automatically emits
3089 // a leave to the end of the finally block.
3090 // This is a problem if `returns' is true since we may jump
3091 // to a point after the end of the method.
3092 // As a workaround, emit an explicit ret here.
3093 ec.NeedReturnLabel ();
3099 protected override void DoEmit (EmitContext ec)
3101 Type type = expr.Type;
3103 ILGenerator ig = ec.ig;
3104 temp = ig.DeclareLocal (type);
3107 ig.Emit (OpCodes.Dup);
3108 ig.Emit (OpCodes.Stloc, temp);
3109 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3113 ig.BeginExceptionBlock ();
3114 Statement.Emit (ec);
3119 ig.EndExceptionBlock ();
3122 public override void EmitFinally (EmitContext ec)
3124 ILGenerator ig = ec.ig;
3125 ig.Emit (OpCodes.Ldloc, temp);
3126 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3130 public class Unchecked : Statement {
3131 public readonly Block Block;
3133 public Unchecked (Block b)
3139 public override bool Resolve (EmitContext ec)
3141 bool previous_state = ec.CheckState;
3142 bool previous_state_const = ec.ConstantCheckState;
3144 ec.CheckState = false;
3145 ec.ConstantCheckState = false;
3146 bool ret = Block.Resolve (ec);
3147 ec.CheckState = previous_state;
3148 ec.ConstantCheckState = previous_state_const;
3153 protected override void DoEmit (EmitContext ec)
3155 bool previous_state = ec.CheckState;
3156 bool previous_state_const = ec.ConstantCheckState;
3158 ec.CheckState = false;
3159 ec.ConstantCheckState = false;
3161 ec.CheckState = previous_state;
3162 ec.ConstantCheckState = previous_state_const;
3166 public class Checked : Statement {
3167 public readonly Block Block;
3169 public Checked (Block b)
3172 b.Unchecked = false;
3175 public override bool Resolve (EmitContext ec)
3177 bool previous_state = ec.CheckState;
3178 bool previous_state_const = ec.ConstantCheckState;
3180 ec.CheckState = true;
3181 ec.ConstantCheckState = true;
3182 bool ret = Block.Resolve (ec);
3183 ec.CheckState = previous_state;
3184 ec.ConstantCheckState = previous_state_const;
3189 protected override void DoEmit (EmitContext ec)
3191 bool previous_state = ec.CheckState;
3192 bool previous_state_const = ec.ConstantCheckState;
3194 ec.CheckState = true;
3195 ec.ConstantCheckState = true;
3197 ec.CheckState = previous_state;
3198 ec.ConstantCheckState = previous_state_const;
3202 public class Unsafe : Statement {
3203 public readonly Block Block;
3205 public Unsafe (Block b)
3208 Block.Unsafe = true;
3211 public override bool Resolve (EmitContext ec)
3213 bool previous_state = ec.InUnsafe;
3217 val = Block.Resolve (ec);
3218 ec.InUnsafe = previous_state;
3223 protected override void DoEmit (EmitContext ec)
3225 bool previous_state = ec.InUnsafe;
3229 ec.InUnsafe = previous_state;
3236 public class Fixed : Statement {
3238 ArrayList declarators;
3239 Statement statement;
3244 abstract class Emitter
3246 protected LocalInfo vi;
3247 protected Expression converted;
3249 protected Emitter (Expression expr, LocalInfo li)
3255 public abstract void Emit (EmitContext ec);
3256 public abstract void EmitExit (ILGenerator ig);
3259 class ExpressionEmitter: Emitter {
3260 public ExpressionEmitter (Expression converted, LocalInfo li) :
3261 base (converted, li)
3265 public override void Emit (EmitContext ec) {
3267 // Store pointer in pinned location
3269 converted.Emit (ec);
3270 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3273 public override void EmitExit (ILGenerator ig)
3275 ig.Emit (OpCodes.Ldc_I4_0);
3276 ig.Emit (OpCodes.Conv_U);
3277 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3281 class StringEmitter: Emitter {
3282 LocalBuilder pinned_string;
3285 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3291 public override void Emit (EmitContext ec)
3293 ILGenerator ig = ec.ig;
3294 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3296 converted.Emit (ec);
3297 ig.Emit (OpCodes.Stloc, pinned_string);
3299 Expression sptr = new StringPtr (pinned_string, loc);
3300 converted = Convert.ImplicitConversionRequired (
3301 ec, sptr, vi.VariableType, loc);
3303 if (converted == null)
3306 converted.Emit (ec);
3307 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3310 public override void EmitExit(ILGenerator ig)
3312 ig.Emit (OpCodes.Ldnull);
3313 ig.Emit (OpCodes.Stloc, pinned_string);
3317 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3320 declarators = decls;
3325 public override bool Resolve (EmitContext ec)
3328 Expression.UnsafeError (loc);
3332 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3336 expr_type = texpr.ResolveType (ec);
3338 CheckObsolete (expr_type);
3340 data = new Emitter [declarators.Count];
3342 if (!expr_type.IsPointer){
3343 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3348 foreach (Pair p in declarators){
3349 LocalInfo vi = (LocalInfo) p.First;
3350 Expression e = (Expression) p.Second;
3352 vi.VariableInfo.SetAssigned (ec);
3353 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3356 // The rules for the possible declarators are pretty wise,
3357 // but the production on the grammar is more concise.
3359 // So we have to enforce these rules here.
3361 // We do not resolve before doing the case 1 test,
3362 // because the grammar is explicit in that the token &
3363 // is present, so we need to test for this particular case.
3367 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3372 // Case 1: & object.
3374 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3375 Expression child = ((Unary) e).Expr;
3377 if (child is ParameterReference || child is LocalVariableReference){
3380 "No need to use fixed statement for parameters or " +
3381 "local variable declarations (address is already " +
3386 ec.InFixedInitializer = true;
3388 ec.InFixedInitializer = false;
3392 child = ((Unary) e).Expr;
3394 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3397 data [i] = new ExpressionEmitter (e, vi);
3403 ec.InFixedInitializer = true;
3405 ec.InFixedInitializer = false;
3412 if (e.Type.IsArray){
3413 Type array_type = TypeManager.GetElementType (e.Type);
3416 // Provided that array_type is unmanaged,
3418 if (!TypeManager.VerifyUnManaged (array_type, loc))
3422 // and T* is implicitly convertible to the
3423 // pointer type given in the fixed statement.
3425 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3427 Expression converted = Convert.ImplicitConversionRequired (
3428 ec, array_ptr, vi.VariableType, loc);
3429 if (converted == null)
3432 data [i] = new ExpressionEmitter (converted, vi);
3441 if (e.Type == TypeManager.string_type){
3442 data [i] = new StringEmitter (e, vi, loc);
3447 // Case 4: fixed buffer
3448 FieldExpr fe = e as FieldExpr;
3450 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3452 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3454 Expression converted = Convert.ImplicitConversionRequired (
3455 ec, fixed_buffer_ptr, vi.VariableType, loc);
3456 if (converted == null)
3459 data [i] = new ExpressionEmitter (converted, vi);
3467 // For other cases, flag a `this is already fixed expression'
3469 if (e is LocalVariableReference || e is ParameterReference ||
3470 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3472 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3476 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3480 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3482 if (!statement.Resolve (ec)) {
3483 ec.KillFlowBranching ();
3487 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3488 has_ret = reachability.IsUnreachable;
3493 protected override void DoEmit (EmitContext ec)
3495 for (int i = 0; i < data.Length; i++) {
3499 statement.Emit (ec);
3504 ILGenerator ig = ec.ig;
3507 // Clear the pinned variable
3509 for (int i = 0; i < data.Length; i++) {
3510 data [i].EmitExit (ig);
3515 public class Catch: Statement {
3516 public readonly string Name;
3517 public readonly Block Block;
3519 Expression type_expr;
3522 public Catch (Expression type, string name, Block block, Location l)
3530 public Type CatchType {
3536 public bool IsGeneral {
3538 return type_expr == null;
3542 protected override void DoEmit(EmitContext ec)
3546 public override bool Resolve (EmitContext ec)
3548 bool was_catch = ec.InCatch;
3551 if (type_expr != null) {
3552 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3556 type = te.ResolveType (ec);
3558 CheckObsolete (type);
3560 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3561 Error (155, "The type caught or thrown must be derived from System.Exception");
3567 return Block.Resolve (ec);
3570 ec.InCatch = was_catch;
3575 public class Try : ExceptionStatement {
3576 public readonly Block Fini, Block;
3577 public readonly ArrayList Specific;
3578 public readonly Catch General;
3580 bool need_exc_block;
3583 // specific, general and fini might all be null.
3585 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3587 if (specific == null && general == null){
3588 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3592 this.Specific = specific;
3593 this.General = general;
3598 public override bool Resolve (EmitContext ec)
3602 FlowBranchingException branching = ec.StartFlowBranching (this);
3604 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3606 if (!Block.Resolve (ec))
3609 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3611 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3613 Type[] prevCatches = new Type [Specific.Count];
3615 foreach (Catch c in Specific){
3616 ec.CurrentBranching.CreateSibling (
3617 c.Block, FlowBranching.SiblingType.Catch);
3619 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3621 if (c.Name != null) {
3622 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3624 throw new Exception ();
3626 vi.VariableInfo = null;
3629 if (!c.Resolve (ec))
3632 Type resolvedType = c.CatchType;
3633 for (int ii = 0; ii < last_index; ++ii) {
3634 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3635 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3640 prevCatches [last_index++] = resolvedType;
3641 need_exc_block = true;
3644 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3646 if (General != null){
3647 ec.CurrentBranching.CreateSibling (
3648 General.Block, FlowBranching.SiblingType.Catch);
3650 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3652 if (!General.Resolve (ec))
3655 need_exc_block = true;
3658 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3662 ec.CurrentBranching.CreateSibling (
3663 Fini, FlowBranching.SiblingType.Finally);
3665 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3666 bool was_finally = ec.InFinally;
3667 ec.InFinally = true;
3668 if (!Fini.Resolve (ec))
3670 ec.InFinally = was_finally;
3673 need_exc_block = true;
3676 if (ec.InIterator) {
3677 ResolveFinally (branching);
3678 need_exc_block |= emit_finally;
3680 emit_finally = Fini != null;
3682 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3684 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3686 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3688 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3689 // Unfortunately, System.Reflection.Emit automatically emits
3690 // a leave to the end of the finally block. This is a problem
3691 // if `returns' is true since we may jump to a point after the
3692 // end of the method.
3693 // As a workaround, emit an explicit ret here.
3694 ec.NeedReturnLabel ();
3700 protected override void DoEmit (EmitContext ec)
3702 ILGenerator ig = ec.ig;
3705 ig.BeginExceptionBlock ();
3708 foreach (Catch c in Specific){
3711 ig.BeginCatchBlock (c.CatchType);
3713 if (c.Name != null){
3714 vi = c.Block.GetLocalInfo (c.Name);
3716 throw new Exception ("Variable does not exist in this block");
3718 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3720 ec.EmitCapturedVariableInstance (vi);
3721 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
3722 ig.Emit (OpCodes.Stfld, vi.FieldBuilder);
3725 ig.Emit (OpCodes.Pop);
3730 if (General != null){
3731 ig.BeginCatchBlock (TypeManager.object_type);
3732 ig.Emit (OpCodes.Pop);
3733 General.Block.Emit (ec);
3738 ig.EndExceptionBlock ();
3741 public override void EmitFinally (EmitContext ec)
3747 public bool HasCatch
3750 return General != null || Specific.Count > 0;
3755 public class Using : ExceptionStatement {
3756 object expression_or_block;
3757 Statement Statement;
3762 Expression [] resolved_vars;
3763 Expression [] converted_vars;
3764 ExpressionStatement [] assign;
3765 LocalBuilder local_copy;
3767 public Using (object expression_or_block, Statement stmt, Location l)
3769 this.expression_or_block = expression_or_block;
3775 // Resolves for the case of using using a local variable declaration.
3777 bool ResolveLocalVariableDecls (EmitContext ec)
3781 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3785 expr_type = texpr.ResolveType (ec);
3788 // The type must be an IDisposable or an implicit conversion
3791 converted_vars = new Expression [var_list.Count];
3792 resolved_vars = new Expression [var_list.Count];
3793 assign = new ExpressionStatement [var_list.Count];
3795 bool need_conv = !TypeManager.ImplementsInterface (
3796 expr_type, TypeManager.idisposable_type);
3798 foreach (DictionaryEntry e in var_list){
3799 Expression var = (Expression) e.Key;
3801 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3805 resolved_vars [i] = var;
3812 converted_vars [i] = Convert.ImplicitConversionRequired (
3813 ec, var, TypeManager.idisposable_type, loc);
3815 if (converted_vars [i] == null)
3822 foreach (DictionaryEntry e in var_list){
3823 Expression var = resolved_vars [i];
3824 Expression new_expr = (Expression) e.Value;
3827 a = new Assign (var, new_expr, loc);
3833 converted_vars [i] = var;
3834 assign [i] = (ExpressionStatement) a;
3841 bool ResolveExpression (EmitContext ec)
3843 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3844 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3845 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3846 TypeManager.CSharpName (expr_type));
3855 // Emits the code for the case of using using a local variable declaration.
3857 void EmitLocalVariableDecls (EmitContext ec)
3859 ILGenerator ig = ec.ig;
3862 for (i = 0; i < assign.Length; i++) {
3863 assign [i].EmitStatement (ec);
3866 ig.BeginExceptionBlock ();
3868 Statement.Emit (ec);
3869 var_list.Reverse ();
3874 void EmitLocalVariableDeclFinally (EmitContext ec)
3876 ILGenerator ig = ec.ig;
3878 int i = assign.Length;
3879 for (int ii = 0; ii < var_list.Count; ++ii){
3880 Expression var = resolved_vars [--i];
3881 Label skip = ig.DefineLabel ();
3883 if (!var.Type.IsValueType) {
3885 ig.Emit (OpCodes.Brfalse, skip);
3886 converted_vars [i].Emit (ec);
3887 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3889 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3891 if (!(ml is MethodGroupExpr)) {
3893 ig.Emit (OpCodes.Box, var.Type);
3894 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3896 MethodInfo mi = null;
3898 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3899 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3906 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3910 IMemoryLocation mloc = (IMemoryLocation) var;
3912 mloc.AddressOf (ec, AddressOp.Load);
3913 ig.Emit (OpCodes.Call, mi);
3917 ig.MarkLabel (skip);
3920 ig.EndExceptionBlock ();
3922 ig.BeginFinallyBlock ();
3927 void EmitExpression (EmitContext ec)
3930 // Make a copy of the expression and operate on that.
3932 ILGenerator ig = ec.ig;
3933 local_copy = ig.DeclareLocal (expr_type);
3938 ig.Emit (OpCodes.Stloc, local_copy);
3941 ig.BeginExceptionBlock ();
3943 Statement.Emit (ec);
3947 ig.EndExceptionBlock ();
3950 void EmitExpressionFinally (EmitContext ec)
3952 ILGenerator ig = ec.ig;
3953 if (!local_copy.LocalType.IsValueType) {
3954 Label skip = ig.DefineLabel ();
3955 ig.Emit (OpCodes.Ldloc, local_copy);
3956 ig.Emit (OpCodes.Brfalse, skip);
3957 ig.Emit (OpCodes.Ldloc, local_copy);
3958 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3959 ig.MarkLabel (skip);
3961 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
3963 if (!(ml is MethodGroupExpr)) {
3964 ig.Emit (OpCodes.Ldloc, local_copy);
3965 ig.Emit (OpCodes.Box, local_copy.LocalType);
3966 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3968 MethodInfo mi = null;
3970 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3971 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3978 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3982 ig.Emit (OpCodes.Ldloca, local_copy);
3983 ig.Emit (OpCodes.Call, mi);
3988 public override bool Resolve (EmitContext ec)
3990 if (expression_or_block is DictionaryEntry){
3991 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3992 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3994 if (!ResolveLocalVariableDecls (ec))
3997 } else if (expression_or_block is Expression){
3998 expr = (Expression) expression_or_block;
4000 expr = expr.Resolve (ec);
4004 expr_type = expr.Type;
4006 if (!ResolveExpression (ec))
4010 FlowBranchingException branching = ec.StartFlowBranching (this);
4012 bool ok = Statement.Resolve (ec);
4015 ec.KillFlowBranching ();
4019 ResolveFinally (branching);
4020 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4022 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4023 // Unfortunately, System.Reflection.Emit automatically emits a leave
4024 // to the end of the finally block. This is a problem if `returns'
4025 // is true since we may jump to a point after the end of the method.
4026 // As a workaround, emit an explicit ret here.
4027 ec.NeedReturnLabel ();
4033 protected override void DoEmit (EmitContext ec)
4035 if (expression_or_block is DictionaryEntry)
4036 EmitLocalVariableDecls (ec);
4037 else if (expression_or_block is Expression)
4038 EmitExpression (ec);
4041 public override void EmitFinally (EmitContext ec)
4043 if (expression_or_block is DictionaryEntry)
4044 EmitLocalVariableDeclFinally (ec);
4045 else if (expression_or_block is Expression)
4046 EmitExpressionFinally (ec);
4051 /// Implementation of the foreach C# statement
4053 public class Foreach : Statement {
4055 Expression variable;
4057 Statement statement;
4059 CollectionForeach collection;
4061 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4062 Statement stmt, Location l)
4065 this.variable = var;
4071 public override bool Resolve (EmitContext ec)
4073 expr = expr.Resolve (ec);
4077 if (expr is NullLiteral) {
4078 Report.Error (186, loc, "Use of null is not valid in this context");
4082 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4086 Type var_type = texpr.Type;
4089 // We need an instance variable. Not sure this is the best
4090 // way of doing this.
4092 // FIXME: When we implement propertyaccess, will those turn
4093 // out to return values in ExprClass? I think they should.
4095 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4096 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4097 collection.error1579 ();
4101 if (expr.Type.IsArray) {
4102 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4103 return array.Resolve (ec);
4105 collection = new CollectionForeach (
4106 var_type, variable, expr, statement, loc);
4107 return collection.Resolve (ec);
4111 protected override void DoEmit (EmitContext ec)
4113 ILGenerator ig = ec.ig;
4115 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4116 ec.LoopBegin = ig.DefineLabel ();
4117 ec.LoopEnd = ig.DefineLabel ();
4119 if (collection != null)
4120 collection.Emit (ec);
4124 ec.LoopBegin = old_begin;
4125 ec.LoopEnd = old_end;
4128 protected class TemporaryVariable : Expression, IMemoryLocation
4132 public TemporaryVariable (Type type, Location loc)
4136 eclass = ExprClass.Value;
4139 public override Expression DoResolve (EmitContext ec)
4144 TypeExpr te = new TypeExpression (type, loc);
4145 li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
4146 if (!li.Resolve (ec))
4149 AnonymousContainer am = ec.CurrentAnonymousMethod;
4150 if ((am != null) && am.IsIterator)
4151 ec.CaptureVariable (li);
4156 public override void Emit (EmitContext ec)
4158 ILGenerator ig = ec.ig;
4160 if (li.FieldBuilder != null) {
4161 ig.Emit (OpCodes.Ldarg_0);
4162 ig.Emit (OpCodes.Ldfld, li.FieldBuilder);
4164 ig.Emit (OpCodes.Ldloc, li.LocalBuilder);
4168 public void EmitLoadAddress (EmitContext ec)
4170 ILGenerator ig = ec.ig;
4172 if (li.FieldBuilder != null) {
4173 ig.Emit (OpCodes.Ldarg_0);
4174 ig.Emit (OpCodes.Ldflda, li.FieldBuilder);
4176 ig.Emit (OpCodes.Ldloca, li.LocalBuilder);
4180 public void Store (EmitContext ec, Expression right_side)
4182 if (li.FieldBuilder != null)
4183 ec.ig.Emit (OpCodes.Ldarg_0);
4185 right_side.Emit (ec);
4186 if (li.FieldBuilder != null) {
4187 ec.ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4189 ec.ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4193 public void EmitThis (EmitContext ec)
4195 if (li.FieldBuilder != null) {
4196 ec.ig.Emit (OpCodes.Ldarg_0);
4200 public void EmitStore (ILGenerator ig)
4202 if (li.FieldBuilder != null)
4203 ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4205 ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4208 public void AddressOf (EmitContext ec, AddressOp mode)
4210 EmitLoadAddress (ec);
4214 protected class ArrayCounter : TemporaryVariable
4216 public ArrayCounter (Location loc)
4217 : base (TypeManager.int32_type, loc)
4220 public void Initialize (EmitContext ec)
4223 ec.ig.Emit (OpCodes.Ldc_I4_0);
4227 public void Increment (EmitContext ec)
4231 ec.ig.Emit (OpCodes.Ldc_I4_1);
4232 ec.ig.Emit (OpCodes.Add);
4237 protected class ArrayForeach : Statement
4239 Expression variable, expr, conv;
4240 Statement statement;
4243 TemporaryVariable[] lengths;
4244 ArrayCounter[] counter;
4247 TemporaryVariable copy;
4250 public ArrayForeach (Type var_type, Expression var,
4251 Expression expr, Statement stmt, Location l)
4253 this.var_type = var_type;
4254 this.variable = var;
4260 public override bool Resolve (EmitContext ec)
4262 array_type = expr.Type;
4263 rank = array_type.GetArrayRank ();
4265 copy = new TemporaryVariable (array_type, loc);
4268 counter = new ArrayCounter [rank];
4269 lengths = new TemporaryVariable [rank];
4271 ArrayList list = new ArrayList ();
4272 for (int i = 0; i < rank; i++) {
4273 counter [i] = new ArrayCounter (loc);
4274 counter [i].Resolve (ec);
4276 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4277 lengths [i].Resolve (ec);
4279 list.Add (counter [i]);
4282 access = new ElementAccess (copy, list).Resolve (ec);
4286 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4292 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4293 ec.CurrentBranching.CreateSibling ();
4295 variable = variable.ResolveLValue (ec, conv, loc);
4296 if (variable == null)
4299 if (!statement.Resolve (ec))
4302 ec.EndFlowBranching ();
4307 protected override void DoEmit (EmitContext ec)
4309 ILGenerator ig = ec.ig;
4311 copy.Store (ec, expr);
4313 Label[] test = new Label [rank];
4314 Label[] loop = new Label [rank];
4316 for (int i = 0; i < rank; i++) {
4317 test [i] = ig.DefineLabel ();
4318 loop [i] = ig.DefineLabel ();
4320 lengths [i].EmitThis (ec);
4321 ((ArrayAccess) access).EmitGetLength (ec, i);
4322 lengths [i].EmitStore (ig);
4325 for (int i = 0; i < rank; i++) {
4326 counter [i].Initialize (ec);
4328 ig.Emit (OpCodes.Br, test [i]);
4329 ig.MarkLabel (loop [i]);
4332 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4334 statement.Emit (ec);
4336 ig.MarkLabel (ec.LoopBegin);
4338 for (int i = rank - 1; i >= 0; i--){
4339 counter [i].Increment (ec);
4341 ig.MarkLabel (test [i]);
4342 counter [i].Emit (ec);
4343 lengths [i].Emit (ec);
4344 ig.Emit (OpCodes.Blt, loop [i]);
4347 ig.MarkLabel (ec.LoopEnd);
4351 protected class CollectionForeach : ExceptionStatement
4353 Expression variable, expr;
4354 Statement statement;
4356 TemporaryVariable enumerator;
4360 MethodGroupExpr get_enumerator;
4361 PropertyExpr get_current;
4362 MethodInfo move_next;
4363 Type var_type, enumerator_type;
4366 public CollectionForeach (Type var_type, Expression var,
4367 Expression expr, Statement stmt, Location l)
4369 this.var_type = var_type;
4370 this.variable = var;
4376 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4378 Type [] args = TypeManager.GetArgumentTypes (mi);
4380 if (args.Length != 0)
4384 if (TypeManager.IsOverride (mi))
4387 // Check whether GetEnumerator is public
4388 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4391 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4393 // Apply the same optimization as MS: skip the GetEnumerator
4394 // returning an IEnumerator, and use the one returning a
4395 // CharEnumerator instead. This allows us to avoid the
4396 // try-finally block and the boxing.
4401 // Ok, we can access it, now make sure that we can do something
4402 // with this `GetEnumerator'
4405 Type return_type = mi.ReturnType;
4406 if (mi.ReturnType == TypeManager.ienumerator_type ||
4407 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4408 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4410 // If it is not an interface, lets try to find the methods ourselves.
4411 // For example, if we have:
4412 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4413 // We can avoid the iface call. This is a runtime perf boost.
4414 // even bigger if we have a ValueType, because we avoid the cost
4417 // We have to make sure that both methods exist for us to take
4418 // this path. If one of the methods does not exist, we will just
4419 // use the interface. Sadly, this complex if statement is the only
4420 // way I could do this without a goto
4423 if (return_type.IsInterface ||
4424 !FetchMoveNext (ec, return_type) ||
4425 !FetchGetCurrent (ec, return_type)) {
4426 move_next = TypeManager.bool_movenext_void;
4427 get_current = new PropertyExpr (
4428 ec, TypeManager.ienumerator_getcurrent, loc);
4433 // Ok, so they dont return an IEnumerable, we will have to
4434 // find if they support the GetEnumerator pattern.
4437 if (!FetchMoveNext (ec, return_type))
4440 if (!FetchGetCurrent (ec, return_type))
4444 enumerator_type = return_type;
4445 is_disposable = !enumerator_type.IsSealed ||
4446 TypeManager.ImplementsInterface (
4447 enumerator_type, TypeManager.idisposable_type);
4453 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4455 bool FetchMoveNext (EmitContext ec, Type t)
4457 MemberList move_next_list;
4459 move_next_list = TypeContainer.FindMembers (
4460 t, MemberTypes.Method,
4461 BindingFlags.Public | BindingFlags.Instance,
4462 Type.FilterName, "MoveNext");
4463 if (move_next_list.Count == 0)
4466 foreach (MemberInfo m in move_next_list){
4467 MethodInfo mi = (MethodInfo) m;
4470 args = TypeManager.GetArgumentTypes (mi);
4471 if ((args != null) && (args.Length == 0) &&
4472 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4482 // Retrieves a `public T get_Current ()' method from the Type `t'
4484 bool FetchGetCurrent (EmitContext ec, Type t)
4486 PropertyExpr pe = Expression.MemberLookup (
4487 ec, t, "Current", MemberTypes.Property,
4488 Expression.AllBindingFlags, loc) as PropertyExpr;
4497 // Retrieves a `public void Dispose ()' method from the Type `t'
4499 static MethodInfo FetchMethodDispose (Type t)
4501 MemberList dispose_list;
4503 dispose_list = TypeContainer.FindMembers (
4504 t, MemberTypes.Method,
4505 BindingFlags.Public | BindingFlags.Instance,
4506 Type.FilterName, "Dispose");
4507 if (dispose_list.Count == 0)
4510 foreach (MemberInfo m in dispose_list){
4511 MethodInfo mi = (MethodInfo) m;
4514 args = TypeManager.GetArgumentTypes (mi);
4515 if (args != null && args.Length == 0){
4516 if (mi.ReturnType == TypeManager.void_type)
4523 public void error1579 ()
4525 Report.Error (1579, loc,
4526 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4527 TypeManager.CSharpName (expr.Type));
4530 bool TryType (EmitContext ec, Type t)
4532 MethodGroupExpr mg = Expression.MemberLookup (
4533 ec, t, "GetEnumerator", MemberTypes.Method,
4534 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4538 foreach (MethodBase mb in mg.Methods) {
4539 if (!GetEnumeratorFilter (ec, (MethodInfo) mb))
4542 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) mb };
4543 get_enumerator = new MethodGroupExpr (mi, loc);
4545 if (t != expr.Type) {
4546 expr = Convert.ExplicitConversion (
4549 throw new InternalErrorException ();
4552 get_enumerator.InstanceExpression = expr;
4553 get_enumerator.IsBase = t != expr.Type;
4561 bool ProbeCollectionType (EmitContext ec, Type t)
4563 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4564 if (TryType (ec, tt))
4570 // Now try to find the method in the interfaces
4573 Type [] ifaces = t.GetInterfaces ();
4575 foreach (Type i in ifaces){
4576 if (TryType (ec, i))
4581 // Since TypeBuilder.GetInterfaces only returns the interface
4582 // types for this type, we have to keep looping, but once
4583 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4584 // done, because it returns all the types
4586 if ((t is TypeBuilder))
4595 public override bool Resolve (EmitContext ec)
4597 enumerator_type = TypeManager.ienumerator_type;
4598 is_disposable = true;
4600 if (!ProbeCollectionType (ec, expr.Type)) {
4605 enumerator = new TemporaryVariable (enumerator_type, loc);
4606 enumerator.Resolve (ec);
4608 init = new Invocation (get_enumerator, new ArrayList ());
4609 init = init.Resolve (ec);
4613 Expression move_next_expr;
4615 MemberInfo[] mi = new MemberInfo[] { move_next };
4616 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4617 mg.InstanceExpression = enumerator;
4619 move_next_expr = new Invocation (mg, new ArrayList ());
4622 get_current.InstanceExpression = enumerator;
4624 Statement block = new CollectionForeachStatement (
4625 var_type, variable, get_current, statement, loc);
4627 loop = new While (move_next_expr, block, loc);
4631 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4632 ec.CurrentBranching.CreateSibling ();
4634 FlowBranchingException branching = null;
4636 branching = ec.StartFlowBranching (this);
4638 if (!loop.Resolve (ec))
4641 if (is_disposable) {
4642 ResolveFinally (branching);
4643 ec.EndFlowBranching ();
4645 emit_finally = true;
4647 ec.EndFlowBranching ();
4652 protected override void DoEmit (EmitContext ec)
4654 ILGenerator ig = ec.ig;
4656 enumerator.Store (ec, init);
4659 // Protect the code in a try/finalize block, so that
4660 // if the beast implement IDisposable, we get rid of it
4662 if (is_disposable && emit_finally)
4663 ig.BeginExceptionBlock ();
4668 // Now the finally block
4670 if (is_disposable) {
4673 ig.EndExceptionBlock ();
4678 public override void EmitFinally (EmitContext ec)
4680 ILGenerator ig = ec.ig;
4682 if (enumerator_type.IsValueType) {
4683 enumerator.Emit (ec);
4685 MethodInfo mi = FetchMethodDispose (enumerator_type);
4687 enumerator.EmitLoadAddress (ec);
4688 ig.Emit (OpCodes.Call, mi);
4690 enumerator.Emit (ec);
4691 ig.Emit (OpCodes.Box, enumerator_type);
4692 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4695 Label call_dispose = ig.DefineLabel ();
4697 enumerator.Emit (ec);
4698 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4699 ig.Emit (OpCodes.Dup);
4700 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4701 ig.Emit (OpCodes.Pop);
4703 Label end_finally = ig.DefineLabel ();
4704 ig.Emit (OpCodes.Br, end_finally);
4706 ig.MarkLabel (call_dispose);
4707 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4708 ig.MarkLabel (end_finally);
4713 protected class CollectionForeachStatement : Statement
4716 Expression variable, current, conv;
4717 Statement statement;
4720 public CollectionForeachStatement (Type type, Expression variable,
4721 Expression current, Statement statement,
4725 this.variable = variable;
4726 this.current = current;
4727 this.statement = statement;
4731 public override bool Resolve (EmitContext ec)
4733 current = current.Resolve (ec);
4734 if (current == null)
4737 conv = Convert.ExplicitConversion (ec, current, type, loc);
4741 assign = new Assign (variable, conv, loc);
4742 if (assign.Resolve (ec) == null)
4745 if (!statement.Resolve (ec))
4751 protected override void DoEmit (EmitContext ec)
4753 assign.EmitStatement (ec);
4754 statement.Emit (ec);