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;
18 namespace Mono.CSharp {
20 using System.Collections;
22 public abstract class Statement {
26 /// Resolves the statement, true means that all sub-statements
29 public virtual bool Resolve (EmitContext ec)
35 /// We already know that the statement is unreachable, but we still
36 /// need to resolve it to catch errors.
38 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
41 // This conflicts with csc's way of doing this, but IMHO it's
42 // the right thing to do.
44 // If something is unreachable, we still check whether it's
45 // correct. This means that you cannot use unassigned variables
46 // in unreachable code, for instance.
49 if (warn && (RootContext.WarningLevel >= 2))
50 Report.Warning (162, loc, "Unreachable code detected");
52 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
53 bool ok = Resolve (ec);
54 ec.KillFlowBranching ();
59 protected void CheckObsolete (Type type)
61 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
62 if (obsolete_attr == null)
65 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
69 /// Return value indicates whether all code paths emitted return.
71 protected abstract void DoEmit (EmitContext ec);
74 /// Utility wrapper routine for Error, just to beautify the code
76 public void Error (int error, string format, params object[] args)
78 Error (error, String.Format (format, args));
81 public void Error (int error, string s)
83 if (!Location.IsNull (loc))
84 Report.Error (error, loc, s);
86 Report.Error (error, s);
90 /// Return value indicates whether all code paths emitted return.
92 public virtual void Emit (EmitContext ec)
99 public sealed class EmptyStatement : Statement {
101 private EmptyStatement () {}
103 public static readonly EmptyStatement Value = new EmptyStatement ();
105 public override bool Resolve (EmitContext ec)
110 protected override void DoEmit (EmitContext ec)
115 public class If : Statement {
117 public Statement TrueStatement;
118 public Statement FalseStatement;
122 public If (Expression expr, Statement trueStatement, Location l)
125 TrueStatement = trueStatement;
129 public If (Expression expr,
130 Statement trueStatement,
131 Statement falseStatement,
135 TrueStatement = trueStatement;
136 FalseStatement = falseStatement;
140 public override bool Resolve (EmitContext ec)
144 Report.Debug (1, "START IF BLOCK", loc);
146 expr = Expression.ResolveBoolean (ec, expr, loc);
152 Assign ass = expr as Assign;
153 if (ass != null && ass.Source is Constant) {
154 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
158 // Dead code elimination
160 if (expr is BoolConstant){
161 bool take = ((BoolConstant) expr).Value;
164 if (!TrueStatement.Resolve (ec))
167 if ((FalseStatement != null) &&
168 !FalseStatement.ResolveUnreachable (ec, true))
170 FalseStatement = null;
172 if (!TrueStatement.ResolveUnreachable (ec, true))
174 TrueStatement = null;
176 if ((FalseStatement != null) &&
177 !FalseStatement.Resolve (ec))
184 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
186 ok &= TrueStatement.Resolve (ec);
188 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
190 ec.CurrentBranching.CreateSibling ();
192 if (FalseStatement != null)
193 ok &= FalseStatement.Resolve (ec);
195 ec.EndFlowBranching ();
197 Report.Debug (1, "END IF BLOCK", loc);
202 protected override void DoEmit (EmitContext ec)
204 ILGenerator ig = ec.ig;
205 Label false_target = ig.DefineLabel ();
209 // If we're a boolean expression, Resolve() already
210 // eliminated dead code for us.
212 if (expr is BoolConstant){
213 bool take = ((BoolConstant) expr).Value;
216 TrueStatement.Emit (ec);
217 else if (FalseStatement != null)
218 FalseStatement.Emit (ec);
223 expr.EmitBranchable (ec, false_target, false);
225 TrueStatement.Emit (ec);
227 if (FalseStatement != null){
228 bool branch_emitted = false;
230 end = ig.DefineLabel ();
232 ig.Emit (OpCodes.Br, end);
233 branch_emitted = true;
236 ig.MarkLabel (false_target);
237 FalseStatement.Emit (ec);
242 ig.MarkLabel (false_target);
247 public class Do : Statement {
248 public Expression expr;
249 public readonly Statement EmbeddedStatement;
252 public Do (Statement statement, Expression boolExpr, Location l)
255 EmbeddedStatement = statement;
259 public override bool Resolve (EmitContext ec)
263 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
265 if (!EmbeddedStatement.Resolve (ec))
268 expr = Expression.ResolveBoolean (ec, expr, loc);
271 else if (expr is BoolConstant){
272 bool res = ((BoolConstant) expr).Value;
278 ec.CurrentBranching.Infinite = infinite;
279 ec.EndFlowBranching ();
284 protected override void DoEmit (EmitContext ec)
286 ILGenerator ig = ec.ig;
287 Label loop = ig.DefineLabel ();
288 Label old_begin = ec.LoopBegin;
289 Label old_end = ec.LoopEnd;
291 ec.LoopBegin = ig.DefineLabel ();
292 ec.LoopEnd = ig.DefineLabel ();
295 EmbeddedStatement.Emit (ec);
296 ig.MarkLabel (ec.LoopBegin);
299 // Dead code elimination
301 if (expr is BoolConstant){
302 bool res = ((BoolConstant) expr).Value;
305 ec.ig.Emit (OpCodes.Br, loop);
307 expr.EmitBranchable (ec, loop, true);
309 ig.MarkLabel (ec.LoopEnd);
311 ec.LoopBegin = old_begin;
312 ec.LoopEnd = old_end;
316 public class While : Statement {
317 public Expression expr;
318 public readonly Statement Statement;
319 bool infinite, empty;
321 public While (Expression boolExpr, Statement statement, Location l)
323 this.expr = boolExpr;
324 Statement = statement;
328 public override bool Resolve (EmitContext ec)
332 expr = Expression.ResolveBoolean (ec, expr, loc);
337 // Inform whether we are infinite or not
339 if (expr is BoolConstant){
340 BoolConstant bc = (BoolConstant) expr;
342 if (bc.Value == false){
343 if (!Statement.ResolveUnreachable (ec, true))
351 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
353 ec.CurrentBranching.CreateSibling ();
355 if (!Statement.Resolve (ec))
358 ec.CurrentBranching.Infinite = infinite;
359 ec.EndFlowBranching ();
364 protected override void DoEmit (EmitContext ec)
369 ILGenerator ig = ec.ig;
370 Label old_begin = ec.LoopBegin;
371 Label old_end = ec.LoopEnd;
373 ec.LoopBegin = ig.DefineLabel ();
374 ec.LoopEnd = ig.DefineLabel ();
377 // Inform whether we are infinite or not
379 if (expr is BoolConstant){
380 ig.MarkLabel (ec.LoopBegin);
382 ig.Emit (OpCodes.Br, ec.LoopBegin);
385 // Inform that we are infinite (ie, `we return'), only
386 // if we do not `break' inside the code.
388 ig.MarkLabel (ec.LoopEnd);
390 Label while_loop = ig.DefineLabel ();
392 ig.Emit (OpCodes.Br, ec.LoopBegin);
393 ig.MarkLabel (while_loop);
397 ig.MarkLabel (ec.LoopBegin);
399 expr.EmitBranchable (ec, while_loop, true);
401 ig.MarkLabel (ec.LoopEnd);
404 ec.LoopBegin = old_begin;
405 ec.LoopEnd = old_end;
409 public class For : Statement {
411 readonly Statement InitStatement;
412 readonly Statement Increment;
413 readonly Statement Statement;
414 bool infinite, empty;
416 public For (Statement initStatement,
422 InitStatement = initStatement;
424 Increment = increment;
425 Statement = statement;
429 public override bool Resolve (EmitContext ec)
433 if (InitStatement != null){
434 if (!InitStatement.Resolve (ec))
439 Test = Expression.ResolveBoolean (ec, Test, loc);
442 else if (Test is BoolConstant){
443 BoolConstant bc = (BoolConstant) Test;
445 if (bc.Value == false){
446 if (!Statement.ResolveUnreachable (ec, true))
448 if ((Increment != null) &&
449 !Increment.ResolveUnreachable (ec, false))
459 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
461 ec.CurrentBranching.CreateSibling ();
463 if (!Statement.Resolve (ec))
466 if (Increment != null){
467 if (!Increment.Resolve (ec))
471 ec.CurrentBranching.Infinite = infinite;
472 ec.EndFlowBranching ();
477 protected override void DoEmit (EmitContext ec)
482 ILGenerator ig = ec.ig;
483 Label old_begin = ec.LoopBegin;
484 Label old_end = ec.LoopEnd;
485 Label loop = ig.DefineLabel ();
486 Label test = ig.DefineLabel ();
488 if (InitStatement != null && InitStatement != EmptyStatement.Value)
489 InitStatement.Emit (ec);
491 ec.LoopBegin = ig.DefineLabel ();
492 ec.LoopEnd = ig.DefineLabel ();
494 ig.Emit (OpCodes.Br, test);
498 ig.MarkLabel (ec.LoopBegin);
499 if (Increment != EmptyStatement.Value)
504 // If test is null, there is no test, and we are just
509 // The Resolve code already catches the case for
510 // Test == BoolConstant (false) so we know that
513 if (Test is BoolConstant)
514 ig.Emit (OpCodes.Br, loop);
516 Test.EmitBranchable (ec, loop, true);
519 ig.Emit (OpCodes.Br, loop);
520 ig.MarkLabel (ec.LoopEnd);
522 ec.LoopBegin = old_begin;
523 ec.LoopEnd = old_end;
527 public class StatementExpression : Statement {
528 ExpressionStatement expr;
530 public StatementExpression (ExpressionStatement expr, Location l)
536 public override bool Resolve (EmitContext ec)
539 expr = expr.ResolveStatement (ec);
543 protected override void DoEmit (EmitContext ec)
545 expr.EmitStatement (ec);
548 public override string ToString ()
550 return "StatementExpression (" + expr + ")";
555 /// Implements the return statement
557 public class Return : Statement {
558 public Expression Expr;
560 public Return (Expression expr, Location l)
568 public override bool Resolve (EmitContext ec)
570 if (ec.ReturnType == null){
572 if (ec.CurrentAnonymousMethod != null){
573 Report.Error (1662, loc, String.Format (
574 "Anonymous method could not be converted to delegate " +
575 "since the return value does not match the delegate value"));
577 Error (127, "Return with a value not allowed here");
582 Error (126, "An object of type `{0}' is expected " +
583 "for the return statement",
584 TypeManager.CSharpName (ec.ReturnType));
589 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
590 "statement to return a value, or yield break to end the iteration");
594 Expr = Expr.Resolve (ec);
598 if (Expr.Type != ec.ReturnType) {
599 Expr = Convert.ImplicitConversionRequired (
600 ec, Expr, ec.ReturnType, loc);
607 Error (-206, "Return statement not allowed inside iterators");
611 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
613 if (ec.CurrentBranching.InTryOrCatch (true)) {
614 ec.CurrentBranching.AddFinallyVector (vector);
616 } else if (ec.InFinally) {
617 Error (157, "Control can not leave the body of the finally block");
620 vector.CheckOutParameters (ec.CurrentBranching);
623 ec.NeedReturnLabel ();
625 ec.CurrentBranching.CurrentUsageVector.Return ();
629 protected override void DoEmit (EmitContext ec)
635 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
639 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
641 ec.ig.Emit (OpCodes.Ret);
645 public class Goto : Statement {
647 LabeledStatement label;
649 public override bool Resolve (EmitContext ec)
651 label = ec.CurrentBranching.LookupLabel (target, loc);
655 // If this is a forward goto.
656 if (!label.IsDefined)
657 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
659 ec.CurrentBranching.CurrentUsageVector.Goto ();
660 label.AddReference ();
665 public Goto (string label, Location l)
671 public string Target {
677 protected override void DoEmit (EmitContext ec)
679 Label l = label.LabelTarget (ec);
680 ec.ig.Emit (OpCodes.Br, l);
684 public class LabeledStatement : Statement {
685 public readonly Location Location;
691 FlowBranching.UsageVector vectors;
693 public LabeledStatement (string label_name, Location l)
698 public Label LabelTarget (EmitContext ec)
703 label = ec.ig.DefineLabel ();
709 public bool IsDefined {
715 public bool HasBeenReferenced {
721 public void AddUsageVector (FlowBranching.UsageVector vector)
723 vector = vector.Clone ();
724 vector.Next = vectors;
728 public override bool Resolve (EmitContext ec)
730 ec.CurrentBranching.Label (vectors);
735 protected override void DoEmit (EmitContext ec)
737 if (ig != null && ig != ec.ig) {
738 Report.Error (1632, "Control cannot leave body of anonymous method");
742 ec.ig.MarkLabel (label);
745 public void AddReference ()
753 /// `goto default' statement
755 public class GotoDefault : Statement {
757 public GotoDefault (Location l)
762 public override bool Resolve (EmitContext ec)
764 ec.CurrentBranching.CurrentUsageVector.Goto ();
768 protected override void DoEmit (EmitContext ec)
770 if (ec.Switch == null){
771 Report.Error (153, loc, "goto default is only valid in a switch statement");
775 if (!ec.Switch.GotDefault){
776 Report.Error (159, loc, "No default target on switch statement");
779 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
784 /// `goto case' statement
786 public class GotoCase : Statement {
790 public GotoCase (Expression e, Location l)
796 public override bool Resolve (EmitContext ec)
798 if (ec.Switch == null){
799 Report.Error (153, loc, "goto case is only valid in a switch statement");
803 expr = expr.Resolve (ec);
807 if (!(expr is Constant)){
808 Report.Error (159, loc, "Target expression for goto case is not constant");
812 object val = Expression.ConvertIntLiteral (
813 (Constant) expr, ec.Switch.SwitchType, loc);
818 sl = (SwitchLabel) ec.Switch.Elements [val];
823 "No such label 'case " + val + "': for the goto case");
827 ec.CurrentBranching.CurrentUsageVector.Goto ();
831 protected override void DoEmit (EmitContext ec)
833 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
837 public class Throw : Statement {
840 public Throw (Expression expr, Location l)
846 public override bool Resolve (EmitContext ec)
848 ec.CurrentBranching.CurrentUsageVector.Throw ();
851 expr = expr.Resolve (ec);
855 ExprClass eclass = expr.eclass;
857 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
858 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
859 expr.Error_UnexpectedKind ("value, variable, property or indexer access ", loc);
865 if ((t != TypeManager.exception_type) &&
866 !t.IsSubclassOf (TypeManager.exception_type) &&
867 !(expr is NullLiteral)) {
869 "The type caught or thrown must be derived " +
870 "from System.Exception");
877 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
882 Error (724, "A throw statement with no argument is only allowed in a catch clause nested inside of the innermost catch clause");
888 protected override void DoEmit (EmitContext ec)
891 ec.ig.Emit (OpCodes.Rethrow);
895 ec.ig.Emit (OpCodes.Throw);
900 public class Break : Statement {
902 public Break (Location l)
909 public override bool Resolve (EmitContext ec)
911 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
912 Error (139, "No enclosing loop or switch to continue to");
914 } else if (ec.InFinally && ec.CurrentBranching.BreakCrossesTryCatchBoundary()) {
915 Error (157, "Control can not leave the body of the finally block");
917 } else if (ec.CurrentBranching.InTryOrCatch (false))
918 ec.CurrentBranching.AddFinallyVector (
919 ec.CurrentBranching.CurrentUsageVector);
920 else if (ec.CurrentBranching.InLoop () || ec.CurrentBranching.InSwitch ())
921 ec.CurrentBranching.AddBreakVector (
922 ec.CurrentBranching.CurrentUsageVector);
924 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
927 ec.NeedReturnLabel ();
929 ec.CurrentBranching.CurrentUsageVector.Break ();
933 protected override void DoEmit (EmitContext ec)
935 ILGenerator ig = ec.ig;
938 ig.Emit (OpCodes.Leave, ec.LoopEnd);
940 ig.Emit (OpCodes.Br, ec.LoopEnd);
945 public class Continue : Statement {
947 public Continue (Location l)
954 public override bool Resolve (EmitContext ec)
956 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
957 Error (139, "No enclosing loop to continue to");
959 } else if (ec.InFinally) {
960 Error (157, "Control can not leave the body of the finally block");
962 } else if (ec.CurrentBranching.InTryOrCatch (false))
963 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
965 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
967 ec.CurrentBranching.CurrentUsageVector.Goto ();
971 protected override void DoEmit (EmitContext ec)
973 Label begin = ec.LoopBegin;
976 ec.ig.Emit (OpCodes.Leave, begin);
978 ec.ig.Emit (OpCodes.Br, begin);
983 // The information about a user-perceived local variable
985 public class LocalInfo {
986 public Expression Type;
989 // Most of the time a variable will be stored in a LocalBuilder
991 // But sometimes, it will be stored in a field (variables that have been
992 // hoisted by iterators or by anonymous methods). The context of the field will
993 // be stored in the EmitContext
996 public LocalBuilder LocalBuilder;
997 public FieldBuilder FieldBuilder;
999 public Type VariableType;
1000 public readonly string Name;
1001 public readonly Location Location;
1002 public readonly Block Block;
1004 public VariableInfo VariableInfo;
1013 CompilerGenerated = 64
1016 public enum ReadOnlyContext: byte {
1023 ReadOnlyContext ro_context;
1025 public LocalInfo (Expression type, string name, Block block, Location l)
1033 public LocalInfo (TypeContainer tc, Block block, Location l)
1035 VariableType = tc.TypeBuilder;
1040 public bool IsThisAssigned (EmitContext ec, Location loc)
1042 if (VariableInfo == null)
1043 throw new Exception ();
1045 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1048 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1051 public bool IsAssigned (EmitContext ec)
1053 if (VariableInfo == null)
1054 throw new Exception ();
1056 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1059 public bool Resolve (EmitContext ec)
1061 if (VariableType == null) {
1062 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1066 VariableType = texpr.ResolveType (ec);
1069 if (VariableType == TypeManager.void_type) {
1070 Report.Error (1547, Location,
1071 "Keyword 'void' cannot be used in this context");
1075 if (VariableType.IsAbstract && VariableType.IsSealed) {
1076 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1079 // TODO: breaks the build
1080 // if (VariableType.IsPointer && !ec.InUnsafe)
1081 // Expression.UnsafeError (Location);
1087 // Whether the variable is Fixed (because its Pinned or its a value type)
1089 public bool IsFixed {
1091 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1098 public bool IsCaptured {
1100 return (flags & Flags.Captured) != 0;
1104 flags |= Flags.Captured;
1108 public bool AddressTaken {
1110 return (flags & Flags.AddressTaken) != 0;
1114 flags |= Flags.AddressTaken;
1118 public bool CompilerGenerated {
1120 return (flags & Flags.CompilerGenerated) != 0;
1124 flags |= Flags.CompilerGenerated;
1128 public override string ToString ()
1130 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1131 Name, Type, VariableInfo, Location);
1136 return (flags & Flags.Used) != 0;
1139 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1143 public bool ReadOnly {
1145 return (flags & Flags.ReadOnly) != 0;
1149 public void SetReadOnlyContext (ReadOnlyContext context)
1151 flags |= Flags.ReadOnly;
1152 ro_context = context;
1155 public string GetReadOnlyContext ()
1158 throw new InternalErrorException ("Variable is not readonly");
1160 switch (ro_context) {
1161 case ReadOnlyContext.Fixed:
1162 return "fixed variable";
1163 case ReadOnlyContext.Foreach:
1164 return "foreach iteration variable";
1165 case ReadOnlyContext.Using:
1166 return "using variable";
1168 throw new NotImplementedException ();
1172 // Whether the variable is pinned, if Pinned the variable has been
1173 // allocated in a pinned slot with DeclareLocal.
1175 public bool Pinned {
1177 return (flags & Flags.Pinned) != 0;
1180 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1184 public bool IsThis {
1186 return (flags & Flags.IsThis) != 0;
1189 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1195 /// Block represents a C# block.
1199 /// This class is used in a number of places: either to represent
1200 /// explicit blocks that the programmer places or implicit blocks.
1202 /// Implicit blocks are used as labels or to introduce variable
1205 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1206 /// they contain extra information that is not necessary on normal blocks.
1208 public class Block : Statement {
1209 public Block Parent;
1210 public readonly Location StartLocation;
1211 public Location EndLocation = Location.Null;
1213 public readonly ToplevelBlock Toplevel;
1220 VariablesInitialized = 8,
1229 public bool Implicit {
1231 return (flags & Flags.Implicit) != 0;
1235 public bool Unchecked {
1237 return (flags & Flags.Unchecked) != 0;
1240 flags |= Flags.Unchecked;
1244 public bool Unsafe {
1246 return (flags & Flags.Unsafe) != 0;
1249 flags |= Flags.Unsafe;
1253 public bool HasVarargs {
1256 return Parent.HasVarargs;
1258 return (flags & Flags.HasVarargs) != 0;
1261 flags |= Flags.HasVarargs;
1266 // The statements in this block
1268 ArrayList statements;
1272 // An array of Blocks. We keep track of children just
1273 // to generate the local variable declarations.
1275 // Statements and child statements are handled through the
1281 // Labels. (label, block) pairs.
1286 // Keeps track of (name, type) pairs
1288 Hashtable variables;
1291 // Keeps track of constants
1292 Hashtable constants;
1295 // Temporary variables.
1297 ArrayList temporary_variables;
1300 // If this is a switch section, the enclosing switch block.
1304 protected static int id;
1308 public Block (Block parent)
1309 : this (parent, (Flags) 0, Location.Null, Location.Null)
1312 public Block (Block parent, Flags flags)
1313 : this (parent, flags, Location.Null, Location.Null)
1316 public Block (Block parent, Location start, Location end)
1317 : this (parent, (Flags) 0, start, end)
1320 public Block (Block parent, Flags flags, Location start, Location end)
1323 parent.AddChild (this);
1325 this.Parent = parent;
1327 this.StartLocation = start;
1328 this.EndLocation = end;
1331 statements = new ArrayList ();
1333 if ((flags & Flags.IsToplevel) != 0)
1334 Toplevel = (ToplevelBlock) this;
1336 Toplevel = parent.Toplevel;
1338 if (parent != null && Implicit) {
1339 if (parent.known_variables == null)
1340 parent.known_variables = new Hashtable ();
1341 // share with parent
1342 known_variables = parent.known_variables;
1347 public Block CreateSwitchBlock (Location start)
1349 Block new_block = new Block (this, start, start);
1350 new_block.switch_block = this;
1360 void AddChild (Block b)
1362 if (children == null)
1363 children = new ArrayList ();
1368 public void SetEndLocation (Location loc)
1374 /// Adds a label to the current block.
1378 /// false if the name already exists in this block. true
1382 public bool AddLabel (string name, LabeledStatement target, Location loc)
1384 if (switch_block != null)
1385 return switch_block.AddLabel (name, target, loc);
1388 while (cur != null) {
1389 if (cur.DoLookupLabel (name) != null) {
1391 140, loc, "The label '{0}' is a duplicate",
1402 while (cur != null) {
1403 if (cur.DoLookupLabel (name) != null) {
1406 "The label '{0}' shadows another label " +
1407 "by the same name in a containing scope.",
1412 if (children != null) {
1413 foreach (Block b in children) {
1414 LabeledStatement s = b.DoLookupLabel (name);
1420 "The label '{0}' shadows another " +
1421 "label by the same name in a " +
1422 "containing scope.",
1433 labels = new Hashtable ();
1435 labels.Add (name, target);
1439 public LabeledStatement LookupLabel (string name)
1441 LabeledStatement s = DoLookupLabel (name);
1445 if (children == null)
1448 foreach (Block child in children) {
1449 if (!child.Implicit)
1452 s = child.LookupLabel (name);
1460 LabeledStatement DoLookupLabel (string name)
1462 if (switch_block != null)
1463 return switch_block.LookupLabel (name);
1466 if (labels.Contains (name))
1467 return ((LabeledStatement) labels [name]);
1472 LocalInfo this_variable = null;
1475 // Returns the "this" instance variable of this block.
1476 // See AddThisVariable() for more information.
1478 public LocalInfo ThisVariable {
1480 for (Block b = this; b != null; b = b.Parent) {
1481 if (b.this_variable != null)
1482 return b.this_variable;
1489 Hashtable known_variables;
1492 // Marks a variable with name @name as being used in this or a child block.
1493 // If a variable name has been used in a child block, it's illegal to
1494 // declare a variable with the same name in the current block.
1496 void AddKnownVariable (string name, LocalInfo info)
1498 if (known_variables == null)
1499 known_variables = new Hashtable ();
1501 known_variables [name] = info;
1504 LocalInfo GetKnownVariableInfo (string name)
1506 if (known_variables == null)
1508 return (LocalInfo) known_variables [name];
1511 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1513 LocalInfo kvi = GetKnownVariableInfo (name);
1514 if (kvi == null || kvi.Block == this)
1517 if (known_variables != kvi.Block.known_variables) {
1518 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1519 Report.Error (135, loc, "'{0}' has a different meaning in a child block", name);
1524 // this block and kvi.Block are the same textual block.
1525 // However, different variables are extant.
1527 // Check if the variable is in scope in both blocks. We use
1528 // an indirect check that depends on AddVariable doing its
1529 // part in maintaining the invariant-meaning-in-block property.
1531 if (e is LocalVariableReference || (e is Constant && GetLocalInfo (name) != null))
1534 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1535 Report.Error (136, loc, "'{0}' has a different meaning later in the block", name);
1540 // This is used by non-static `struct' constructors which do not have an
1541 // initializer - in this case, the constructor must initialize all of the
1542 // struct's fields. To do this, we add a "this" variable and use the flow
1543 // analysis code to ensure that it's been fully initialized before control
1544 // leaves the constructor.
1546 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1548 if (this_variable != null)
1549 return this_variable;
1551 if (variables == null)
1552 variables = new Hashtable ();
1554 this_variable = new LocalInfo (tc, this, l);
1555 this_variable.Used = true;
1556 this_variable.IsThis = true;
1558 variables.Add ("this", this_variable);
1560 return this_variable;
1563 public LocalInfo AddVariable (Expression type, string name, Location l)
1565 if (variables == null)
1566 variables = new Hashtable ();
1568 LocalInfo vi = GetLocalInfo (name);
1570 Report.SymbolRelatedToPreviousError (vi.Location, name);
1571 if (known_variables == vi.Block.known_variables)
1572 Report.Error (128, l,
1573 "A local variable '{0}' is already declared in this scope", name);
1575 Report.Error (136, l,
1576 "'{0}' hides the declaration of local variable '{0}' in a parent scope", name);
1580 vi = GetKnownVariableInfo (name);
1582 Report.SymbolRelatedToPreviousError (vi.Location, name);
1583 Report.Error (136, l,
1584 "A child block already has a declaration of local variable '{0}':" +
1585 " allowing this declaration would violate 'invariant meaning in a block'",
1591 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1593 Report.SymbolRelatedToPreviousError (p.Location, name);
1594 Report.Error (136, l, "'{0}' hides a method parameter", name);
1598 vi = new LocalInfo (type, name, this, l);
1600 variables.Add (name, vi);
1602 for (Block b = this; b != null; b = b.Parent)
1603 b.AddKnownVariable (name, vi);
1605 if ((flags & Flags.VariablesInitialized) != 0)
1606 throw new Exception ();
1608 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1612 public bool AddConstant (Expression type, string name, Expression value, Location l)
1614 if (AddVariable (type, name, l) == null)
1617 if (constants == null)
1618 constants = new Hashtable ();
1620 constants.Add (name, value);
1624 static int next_temp_id = 0;
1626 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1628 if (temporary_variables == null)
1629 temporary_variables = new ArrayList ();
1631 int id = ++next_temp_id;
1632 string name = "$s_" + id.ToString ();
1634 LocalInfo li = new LocalInfo (te, name, this, loc);
1635 li.CompilerGenerated = true;
1636 temporary_variables.Add (li);
1640 public Hashtable Variables {
1646 public LocalInfo GetLocalInfo (string name)
1648 for (Block b = this; b != null; b = b.Parent) {
1649 if (b.variables != null) {
1650 LocalInfo ret = b.variables [name] as LocalInfo;
1658 public Expression GetVariableType (string name)
1660 LocalInfo vi = GetLocalInfo (name);
1668 public Expression GetConstantExpression (string name)
1670 for (Block b = this; b != null; b = b.Parent) {
1671 if (b.constants != null) {
1672 Expression ret = b.constants [name] as Expression;
1681 /// True if the variable named @name is a constant
1683 public bool IsConstant (string name)
1685 Expression e = null;
1687 e = GetConstantExpression (name);
1693 /// A list of labels that were not used within this block
1695 public string [] GetUnreferenced ()
1697 // FIXME: Implement me
1701 public void AddStatement (Statement s)
1704 flags |= Flags.BlockUsed;
1709 return (flags & Flags.BlockUsed) != 0;
1715 flags |= Flags.BlockUsed;
1718 public bool HasRet {
1720 return (flags & Flags.HasRet) != 0;
1724 public bool IsDestructor {
1726 return (flags & Flags.IsDestructor) != 0;
1730 public void SetDestructor ()
1732 flags |= Flags.IsDestructor;
1735 VariableMap param_map, local_map;
1737 public VariableMap ParameterMap {
1739 if ((flags & Flags.VariablesInitialized) == 0)
1740 throw new Exception ("Variables have not been initialized yet");
1746 public VariableMap LocalMap {
1748 if ((flags & Flags.VariablesInitialized) == 0)
1749 throw new Exception ("Variables have not been initialized yet");
1756 /// Emits the variable declarations and labels.
1759 /// tc: is our typecontainer (to resolve type references)
1760 /// ig: is the code generator:
1762 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1764 bool old_unsafe = ec.InUnsafe;
1766 // If some parent block was unsafe, we remain unsafe even if this block
1767 // isn't explicitly marked as such.
1768 ec.InUnsafe |= Unsafe;
1771 // Compute the VariableMap's.
1773 // Unfortunately, we don't know the type when adding variables with
1774 // AddVariable(), so we need to compute this info here.
1778 if (variables != null) {
1779 foreach (LocalInfo li in variables.Values)
1782 locals = new LocalInfo [variables.Count];
1783 variables.Values.CopyTo (locals, 0);
1785 locals = new LocalInfo [0];
1788 local_map = new VariableMap (Parent.LocalMap, locals);
1790 local_map = new VariableMap (locals);
1792 param_map = new VariableMap (ip);
1793 flags |= Flags.VariablesInitialized;
1795 bool old_check_state = ec.ConstantCheckState;
1796 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1799 // Process this block variables
1801 if (variables != null){
1802 foreach (DictionaryEntry de in variables){
1803 string name = (string) de.Key;
1804 LocalInfo vi = (LocalInfo) de.Value;
1806 if (vi.VariableType == null)
1809 Type variable_type = vi.VariableType;
1811 if (variable_type.IsPointer){
1813 // Am not really convinced that this test is required (Microsoft does it)
1814 // but the fact is that you would not be able to use the pointer variable
1817 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1824 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1827 // This is needed to compile on both .NET 1.x and .NET 2.x
1828 // the later introduced `DeclareLocal (Type t, bool pinned)'
1830 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1831 else if (!vi.IsThis)
1832 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1835 if (constants == null)
1838 Expression cv = (Expression) constants [name];
1842 ec.CurrentBlock = this;
1843 Expression e = cv.Resolve (ec);
1845 Constant ce = e as Constant;
1847 Report.Error (133, vi.Location,
1848 "The expression being assigned to '{0}' must be constant", name);
1852 if (e.Type != variable_type){
1853 e = Const.ChangeType (vi.Location, ce, variable_type);
1858 constants.Remove (name);
1859 constants.Add (name, e);
1862 ec.ConstantCheckState = old_check_state;
1865 // Now, handle the children
1867 if (children != null){
1868 foreach (Block b in children)
1869 b.ResolveMeta (toplevel, ec, ip);
1871 ec.InUnsafe = old_unsafe;
1875 // Emits the local variable declarations for a block
1877 public void EmitMeta (EmitContext ec)
1879 ILGenerator ig = ec.ig;
1881 if (variables != null){
1882 bool have_captured_vars = ec.HaveCapturedVariables ();
1883 bool remap_locals = ec.RemapToProxy;
1885 foreach (DictionaryEntry de in variables){
1886 LocalInfo vi = (LocalInfo) de.Value;
1888 if (have_captured_vars && ec.IsCaptured (vi))
1892 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1896 // This is needed to compile on both .NET 1.x and .NET 2.x
1897 // the later introduced `DeclareLocal (Type t, bool pinned)'
1899 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1900 else if (!vi.IsThis)
1901 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1906 if (temporary_variables != null) {
1907 foreach (LocalInfo vi in temporary_variables) {
1908 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1912 if (children != null){
1913 foreach (Block b in children)
1918 void UsageWarning (FlowBranching.UsageVector vector)
1922 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1923 foreach (DictionaryEntry de in variables){
1924 LocalInfo vi = (LocalInfo) de.Value;
1929 name = (string) de.Key;
1931 if (vector.IsAssigned (vi.VariableInfo)){
1932 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1934 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1940 bool unreachable_shown;
1943 public override bool Resolve (EmitContext ec)
1945 Block prev_block = ec.CurrentBlock;
1948 int errors = Report.Errors;
1950 ec.CurrentBlock = this;
1951 ec.StartFlowBranching (this);
1953 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1955 int statement_count = statements.Count;
1956 for (int ix = 0; ix < statement_count; ix++){
1957 Statement s = (Statement) statements [ix];
1960 // Warn if we detect unreachable code.
1964 ((Block) s).unreachable = true;
1966 if (!unreachable_shown && (RootContext.WarningLevel >= 2)) {
1968 162, loc, "Unreachable code detected");
1969 unreachable_shown = true;
1974 // Note that we're not using ResolveUnreachable() for unreachable
1975 // statements here. ResolveUnreachable() creates a temporary
1976 // flow branching and kills it afterwards. This leads to problems
1977 // if you have two unreachable statements where the first one
1978 // assigns a variable and the second one tries to access it.
1981 if (!s.Resolve (ec)) {
1983 statements [ix] = EmptyStatement.Value;
1987 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1988 statements [ix] = EmptyStatement.Value;
1990 num_statements = ix + 1;
1991 if (s is LabeledStatement)
1992 unreachable = false;
1994 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1997 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1998 ec.CurrentBranching, statement_count, num_statements);
2001 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
2003 ec.CurrentBlock = prev_block;
2005 // If we're a non-static `struct' constructor which doesn't have an
2006 // initializer, then we must initialize all of the struct's fields.
2007 if ((this_variable != null) &&
2008 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
2009 !this_variable.IsThisAssigned (ec, loc))
2012 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2013 foreach (LabeledStatement label in labels.Values)
2014 if (!label.HasBeenReferenced)
2015 Report.Warning (164, label.Location,
2016 "This label has not been referenced");
2019 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2021 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2022 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2023 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2024 flags |= Flags.HasRet;
2026 if (ok && (errors == Report.Errors)) {
2027 if (RootContext.WarningLevel >= 3)
2028 UsageWarning (vector);
2034 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2036 unreachable_shown = true;
2039 if (warn && (RootContext.WarningLevel >= 2))
2040 Report.Warning (162, loc, "Unreachable code detected");
2042 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2043 bool ok = Resolve (ec);
2044 ec.KillFlowBranching ();
2049 protected override void DoEmit (EmitContext ec)
2051 for (int ix = 0; ix < num_statements; ix++){
2052 Statement s = (Statement) statements [ix];
2054 // Check whether we are the last statement in a
2057 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2058 ec.IsLastStatement = true;
2060 ec.IsLastStatement = false;
2066 public override void Emit (EmitContext ec)
2068 Block prev_block = ec.CurrentBlock;
2070 ec.CurrentBlock = this;
2072 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2073 bool is_lexical_block = !Implicit && (Parent != null);
2075 if (emit_debug_info) {
2076 if (is_lexical_block)
2079 if (variables != null) {
2080 foreach (DictionaryEntry de in variables) {
2081 string name = (string) de.Key;
2082 LocalInfo vi = (LocalInfo) de.Value;
2084 if (vi.LocalBuilder == null)
2087 ec.DefineLocalVariable (name, vi.LocalBuilder);
2092 ec.Mark (StartLocation, true);
2094 ec.Mark (EndLocation, true);
2096 if (emit_debug_info && is_lexical_block)
2099 ec.CurrentBlock = prev_block;
2103 // Returns true if we ar ea child of `b'.
2105 public bool IsChildOf (Block b)
2107 Block current = this;
2110 if (current.Parent == b)
2112 current = current.Parent;
2113 } while (current != null);
2117 public override string ToString ()
2119 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2124 // A toplevel block contains extra information, the split is done
2125 // only to separate information that would otherwise bloat the more
2126 // lightweight Block.
2128 // In particular, this was introduced when the support for Anonymous
2129 // Methods was implemented.
2131 public class ToplevelBlock : Block {
2133 // Pointer to the host of this anonymous method, or null
2134 // if we are the topmost block
2136 public ToplevelBlock Container;
2137 CaptureContext capture_context;
2138 FlowBranching top_level_branching;
2140 Hashtable capture_contexts;
2143 // The parameters for the block.
2145 public readonly Parameters Parameters;
2147 public void RegisterCaptureContext (CaptureContext cc)
2149 if (capture_contexts == null)
2150 capture_contexts = new Hashtable ();
2151 capture_contexts [cc] = cc;
2154 public void CompleteContexts ()
2156 if (capture_contexts == null)
2159 foreach (CaptureContext cc in capture_contexts.Keys){
2164 public CaptureContext ToplevelBlockCaptureContext {
2166 return capture_context;
2171 // Parent is only used by anonymous blocks to link back to their
2174 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2175 this (container, (Flags) 0, parameters, start)
2179 public ToplevelBlock (Parameters parameters, Location start) :
2180 this (null, (Flags) 0, parameters, start)
2184 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2185 this (null, flags, parameters, start)
2189 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2190 base (null, flags | Flags.IsToplevel, start, Location.Null)
2192 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2193 Container = container;
2196 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2200 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2202 if (capture_context == null)
2203 capture_context = new CaptureContext (this, loc, host);
2206 public CaptureContext CaptureContext {
2208 return capture_context;
2212 public FlowBranching TopLevelBranching {
2214 return top_level_branching;
2219 // Returns a `ParameterReference' for the given name, or null if there
2220 // is no such parameter
2222 public ParameterReference GetParameterReference (string name, Location loc)
2227 for (ToplevelBlock t = this; t != null; t = t.Container) {
2228 Parameters pars = t.Parameters;
2229 par = pars.GetParameterByName (name, out idx);
2231 return new ParameterReference (pars, this, idx, name, loc);
2237 // Whether the parameter named `name' is local to this block,
2238 // or false, if the parameter belongs to an encompassing block.
2240 public bool IsLocalParameter (string name)
2242 return Parameters.GetParameterByName (name) != null;
2246 // Whether the `name' is a parameter reference
2248 public bool IsParameterReference (string name)
2250 for (ToplevelBlock t = this; t != null; t = t.Container) {
2251 if (t.IsLocalParameter (name))
2257 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2259 int errors = Report.Errors;
2261 if (top_level_branching != null)
2264 ResolveMeta (this, ec, ip);
2266 top_level_branching = ec.StartFlowBranching (this);
2268 return Report.Errors == errors;
2272 public class SwitchLabel {
2275 public Location loc;
2279 Label il_label_code;
2280 bool il_label_code_set;
2283 // if expr == null, then it is the default case.
2285 public SwitchLabel (Expression expr, Location l)
2291 public Expression Label {
2297 public object Converted {
2303 public Label GetILLabel (EmitContext ec)
2306 il_label = ec.ig.DefineLabel ();
2307 il_label_set = true;
2312 public Label GetILLabelCode (EmitContext ec)
2314 if (!il_label_code_set){
2315 il_label_code = ec.ig.DefineLabel ();
2316 il_label_code_set = true;
2318 return il_label_code;
2322 // Resolves the expression, reduces it to a literal if possible
2323 // and then converts it to the requested type.
2325 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2330 Expression e = label.Resolve (ec);
2335 if (!(e is Constant)){
2336 Report.Error (150, loc, "A constant value is expected, got: " + e);
2340 if (e is StringConstant || e is NullLiteral){
2341 if (required_type == TypeManager.string_type){
2347 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2348 if (converted == null)
2355 public class SwitchSection {
2356 // An array of SwitchLabels.
2357 public readonly ArrayList Labels;
2358 public readonly Block Block;
2360 public SwitchSection (ArrayList labels, Block block)
2367 public class Switch : Statement {
2368 public readonly ArrayList Sections;
2369 public Expression Expr;
2372 /// Maps constants whose type type SwitchType to their SwitchLabels.
2374 public Hashtable Elements;
2377 /// The governing switch type
2379 public Type SwitchType;
2384 Label default_target;
2385 Expression new_expr;
2387 SwitchSection constant_section;
2388 SwitchSection default_section;
2391 // The types allowed to be implicitly cast from
2392 // on the governing type
2394 static Type [] allowed_types;
2396 public Switch (Expression e, ArrayList sects, Location l)
2403 public bool GotDefault {
2405 return default_section != null;
2409 public Label DefaultTarget {
2411 return default_target;
2416 // Determines the governing type for a switch. The returned
2417 // expression might be the expression from the switch, or an
2418 // expression that includes any potential conversions to the
2419 // integral types or to string.
2421 Expression SwitchGoverningType (EmitContext ec, Type t)
2423 if (t == TypeManager.int32_type ||
2424 t == TypeManager.uint32_type ||
2425 t == TypeManager.char_type ||
2426 t == TypeManager.byte_type ||
2427 t == TypeManager.sbyte_type ||
2428 t == TypeManager.ushort_type ||
2429 t == TypeManager.short_type ||
2430 t == TypeManager.uint64_type ||
2431 t == TypeManager.int64_type ||
2432 t == TypeManager.string_type ||
2433 t == TypeManager.bool_type ||
2434 t.IsSubclassOf (TypeManager.enum_type))
2437 if (allowed_types == null){
2438 allowed_types = new Type [] {
2439 TypeManager.int32_type,
2440 TypeManager.uint32_type,
2441 TypeManager.sbyte_type,
2442 TypeManager.byte_type,
2443 TypeManager.short_type,
2444 TypeManager.ushort_type,
2445 TypeManager.int64_type,
2446 TypeManager.uint64_type,
2447 TypeManager.char_type,
2448 TypeManager.bool_type,
2449 TypeManager.string_type
2454 // Try to find a *user* defined implicit conversion.
2456 // If there is no implicit conversion, or if there are multiple
2457 // conversions, we have to report an error
2459 Expression converted = null;
2460 foreach (Type tt in allowed_types){
2463 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2468 // Ignore over-worked ImplicitUserConversions that do
2469 // an implicit conversion in addition to the user conversion.
2472 UserCast ue = e as UserCast;
2474 if (ue.Source != Expr)
2478 if (converted != null){
2479 Report.ExtraInformation (
2481 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2482 TypeManager.CSharpName (Expr.Type)));
2491 static string Error152 {
2493 return "The label '{0}:' already occurs in this switch statement";
2498 // Performs the basic sanity checks on the switch statement
2499 // (looks for duplicate keys and non-constant expressions).
2501 // It also returns a hashtable with the keys that we will later
2502 // use to compute the switch tables
2504 bool CheckSwitch (EmitContext ec)
2508 Elements = new Hashtable ();
2510 if (TypeManager.IsEnumType (SwitchType)){
2511 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2513 compare_type = SwitchType;
2515 foreach (SwitchSection ss in Sections){
2516 foreach (SwitchLabel sl in ss.Labels){
2517 if (!sl.ResolveAndReduce (ec, SwitchType)){
2522 if (sl.Label == null){
2523 if (default_section != null){
2524 Report.Error (152, sl.loc, Error152, "default");
2527 default_section = ss;
2531 object key = sl.Converted;
2533 if (key is Constant)
2534 key = ((Constant) key).GetValue ();
2537 key = NullLiteral.Null;
2539 string lname = null;
2540 if (compare_type == TypeManager.uint64_type){
2541 ulong v = (ulong) key;
2543 if (Elements.Contains (v))
2544 lname = v.ToString ();
2546 Elements.Add (v, sl);
2547 } else if (compare_type == TypeManager.int64_type){
2548 long v = (long) key;
2550 if (Elements.Contains (v))
2551 lname = v.ToString ();
2553 Elements.Add (v, sl);
2554 } else if (compare_type == TypeManager.uint32_type){
2555 uint v = (uint) key;
2557 if (Elements.Contains (v))
2558 lname = v.ToString ();
2560 Elements.Add (v, sl);
2561 } else if (compare_type == TypeManager.char_type){
2562 char v = (char) key;
2564 if (Elements.Contains (v))
2565 lname = v.ToString ();
2567 Elements.Add (v, sl);
2568 } else if (compare_type == TypeManager.byte_type){
2569 byte v = (byte) key;
2571 if (Elements.Contains (v))
2572 lname = v.ToString ();
2574 Elements.Add (v, sl);
2575 } else if (compare_type == TypeManager.sbyte_type){
2576 sbyte v = (sbyte) key;
2578 if (Elements.Contains (v))
2579 lname = v.ToString ();
2581 Elements.Add (v, sl);
2582 } else if (compare_type == TypeManager.short_type){
2583 short v = (short) key;
2585 if (Elements.Contains (v))
2586 lname = v.ToString ();
2588 Elements.Add (v, sl);
2589 } else if (compare_type == TypeManager.ushort_type){
2590 ushort v = (ushort) key;
2592 if (Elements.Contains (v))
2593 lname = v.ToString ();
2595 Elements.Add (v, sl);
2596 } else if (compare_type == TypeManager.string_type){
2597 if (key is NullLiteral){
2598 if (Elements.Contains (NullLiteral.Null))
2601 Elements.Add (NullLiteral.Null, null);
2603 string s = (string) key;
2605 if (Elements.Contains (s))
2608 Elements.Add (s, sl);
2610 } else if (compare_type == TypeManager.int32_type) {
2613 if (Elements.Contains (v))
2614 lname = v.ToString ();
2616 Elements.Add (v, sl);
2617 } else if (compare_type == TypeManager.bool_type) {
2618 bool v = (bool) key;
2620 if (Elements.Contains (v))
2621 lname = v.ToString ();
2623 Elements.Add (v, sl);
2627 throw new Exception ("Unknown switch type!" +
2628 SwitchType + " " + compare_type);
2631 if (lname != null) {
2632 Report.Error (152, sl.loc, Error152, "case " + lname);
2643 void EmitObjectInteger (ILGenerator ig, object k)
2646 IntConstant.EmitInt (ig, (int) k);
2647 else if (k is Constant) {
2648 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2651 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2654 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2656 IntConstant.EmitInt (ig, (int) (long) k);
2657 ig.Emit (OpCodes.Conv_I8);
2660 LongConstant.EmitLong (ig, (long) k);
2662 else if (k is ulong)
2664 if ((ulong) k < (1L<<32))
2666 IntConstant.EmitInt (ig, (int) (long) k);
2667 ig.Emit (OpCodes.Conv_U8);
2671 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2675 IntConstant.EmitInt (ig, (int) ((char) k));
2676 else if (k is sbyte)
2677 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2679 IntConstant.EmitInt (ig, (int) ((byte) k));
2680 else if (k is short)
2681 IntConstant.EmitInt (ig, (int) ((short) k));
2682 else if (k is ushort)
2683 IntConstant.EmitInt (ig, (int) ((ushort) k));
2685 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2687 throw new Exception ("Unhandled case");
2690 // structure used to hold blocks of keys while calculating table switch
2691 class KeyBlock : IComparable
2693 public KeyBlock (long _nFirst)
2695 nFirst = nLast = _nFirst;
2699 public ArrayList rgKeys = null;
2700 // how many items are in the bucket
2701 public int Size = 1;
2704 get { return (int) (nLast - nFirst + 1); }
2706 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2708 return kbLast.nLast - kbFirst.nFirst + 1;
2710 public int CompareTo (object obj)
2712 KeyBlock kb = (KeyBlock) obj;
2713 int nLength = Length;
2714 int nLengthOther = kb.Length;
2715 if (nLengthOther == nLength)
2716 return (int) (kb.nFirst - nFirst);
2717 return nLength - nLengthOther;
2722 /// This method emits code for a lookup-based switch statement (non-string)
2723 /// Basically it groups the cases into blocks that are at least half full,
2724 /// and then spits out individual lookup opcodes for each block.
2725 /// It emits the longest blocks first, and short blocks are just
2726 /// handled with direct compares.
2728 /// <param name="ec"></param>
2729 /// <param name="val"></param>
2730 /// <returns></returns>
2731 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2733 int cElements = Elements.Count;
2734 object [] rgKeys = new object [cElements];
2735 Elements.Keys.CopyTo (rgKeys, 0);
2736 Array.Sort (rgKeys);
2738 // initialize the block list with one element per key
2739 ArrayList rgKeyBlocks = new ArrayList ();
2740 foreach (object key in rgKeys)
2741 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2744 // iteratively merge the blocks while they are at least half full
2745 // there's probably a really cool way to do this with a tree...
2746 while (rgKeyBlocks.Count > 1)
2748 ArrayList rgKeyBlocksNew = new ArrayList ();
2749 kbCurr = (KeyBlock) rgKeyBlocks [0];
2750 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2752 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2753 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2756 kbCurr.nLast = kb.nLast;
2757 kbCurr.Size += kb.Size;
2761 // start a new block
2762 rgKeyBlocksNew.Add (kbCurr);
2766 rgKeyBlocksNew.Add (kbCurr);
2767 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2769 rgKeyBlocks = rgKeyBlocksNew;
2772 // initialize the key lists
2773 foreach (KeyBlock kb in rgKeyBlocks)
2774 kb.rgKeys = new ArrayList ();
2776 // fill the key lists
2778 if (rgKeyBlocks.Count > 0) {
2779 kbCurr = (KeyBlock) rgKeyBlocks [0];
2780 foreach (object key in rgKeys)
2782 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2783 System.Convert.ToInt64 (key) > kbCurr.nLast;
2785 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2786 kbCurr.rgKeys.Add (key);
2790 // sort the blocks so we can tackle the largest ones first
2791 rgKeyBlocks.Sort ();
2793 // okay now we can start...
2794 ILGenerator ig = ec.ig;
2795 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2796 Label lblDefault = ig.DefineLabel ();
2798 Type typeKeys = null;
2799 if (rgKeys.Length > 0)
2800 typeKeys = rgKeys [0].GetType (); // used for conversions
2804 if (TypeManager.IsEnumType (SwitchType))
2805 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2807 compare_type = SwitchType;
2809 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2811 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2812 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2815 foreach (object key in kb.rgKeys)
2817 ig.Emit (OpCodes.Ldloc, val);
2818 EmitObjectInteger (ig, key);
2819 SwitchLabel sl = (SwitchLabel) Elements [key];
2820 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2825 // TODO: if all the keys in the block are the same and there are
2826 // no gaps/defaults then just use a range-check.
2827 if (compare_type == TypeManager.int64_type ||
2828 compare_type == TypeManager.uint64_type)
2830 // TODO: optimize constant/I4 cases
2832 // check block range (could be > 2^31)
2833 ig.Emit (OpCodes.Ldloc, val);
2834 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2835 ig.Emit (OpCodes.Blt, lblDefault);
2836 ig.Emit (OpCodes.Ldloc, val);
2837 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2838 ig.Emit (OpCodes.Bgt, lblDefault);
2841 ig.Emit (OpCodes.Ldloc, val);
2844 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2845 ig.Emit (OpCodes.Sub);
2847 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2852 ig.Emit (OpCodes.Ldloc, val);
2853 int nFirst = (int) kb.nFirst;
2856 IntConstant.EmitInt (ig, nFirst);
2857 ig.Emit (OpCodes.Sub);
2859 else if (nFirst < 0)
2861 IntConstant.EmitInt (ig, -nFirst);
2862 ig.Emit (OpCodes.Add);
2866 // first, build the list of labels for the switch
2868 int cJumps = kb.Length;
2869 Label [] rgLabels = new Label [cJumps];
2870 for (int iJump = 0; iJump < cJumps; iJump++)
2872 object key = kb.rgKeys [iKey];
2873 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2875 SwitchLabel sl = (SwitchLabel) Elements [key];
2876 rgLabels [iJump] = sl.GetILLabel (ec);
2880 rgLabels [iJump] = lblDefault;
2882 // emit the switch opcode
2883 ig.Emit (OpCodes.Switch, rgLabels);
2886 // mark the default for this block
2888 ig.MarkLabel (lblDefault);
2891 // TODO: find the default case and emit it here,
2892 // to prevent having to do the following jump.
2893 // make sure to mark other labels in the default section
2895 // the last default just goes to the end
2896 ig.Emit (OpCodes.Br, lblDefault);
2898 // now emit the code for the sections
2899 bool fFoundDefault = false;
2900 foreach (SwitchSection ss in Sections)
2902 foreach (SwitchLabel sl in ss.Labels)
2904 ig.MarkLabel (sl.GetILLabel (ec));
2905 ig.MarkLabel (sl.GetILLabelCode (ec));
2906 if (sl.Label == null)
2908 ig.MarkLabel (lblDefault);
2909 fFoundDefault = true;
2913 //ig.Emit (OpCodes.Br, lblEnd);
2916 if (!fFoundDefault) {
2917 ig.MarkLabel (lblDefault);
2919 ig.MarkLabel (lblEnd);
2922 // This simple emit switch works, but does not take advantage of the
2924 // TODO: remove non-string logic from here
2925 // TODO: binary search strings?
2927 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2929 ILGenerator ig = ec.ig;
2930 Label end_of_switch = ig.DefineLabel ();
2931 Label next_test = ig.DefineLabel ();
2932 Label null_target = ig.DefineLabel ();
2933 bool first_test = true;
2934 bool pending_goto_end = false;
2935 bool null_marked = false;
2938 ig.Emit (OpCodes.Ldloc, val);
2940 if (Elements.Contains (NullLiteral.Null)){
2941 ig.Emit (OpCodes.Brfalse, null_target);
2943 ig.Emit (OpCodes.Brfalse, default_target);
2945 ig.Emit (OpCodes.Ldloc, val);
2946 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2947 ig.Emit (OpCodes.Stloc, val);
2949 int section_count = Sections.Count;
2950 for (int section = 0; section < section_count; section++){
2951 SwitchSection ss = (SwitchSection) Sections [section];
2953 if (ss == default_section)
2956 Label sec_begin = ig.DefineLabel ();
2958 ig.Emit (OpCodes.Nop);
2960 if (pending_goto_end)
2961 ig.Emit (OpCodes.Br, end_of_switch);
2963 int label_count = ss.Labels.Count;
2965 for (int label = 0; label < label_count; label++){
2966 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2967 ig.MarkLabel (sl.GetILLabel (ec));
2970 ig.MarkLabel (next_test);
2971 next_test = ig.DefineLabel ();
2974 // If we are the default target
2976 if (sl.Label != null){
2977 object lit = sl.Converted;
2979 if (lit is NullLiteral){
2981 if (label_count == 1)
2982 ig.Emit (OpCodes.Br, next_test);
2986 StringConstant str = (StringConstant) lit;
2988 ig.Emit (OpCodes.Ldloc, val);
2989 ig.Emit (OpCodes.Ldstr, str.Value);
2990 if (label_count == 1)
2991 ig.Emit (OpCodes.Bne_Un, next_test);
2993 if (label+1 == label_count)
2994 ig.Emit (OpCodes.Bne_Un, next_test);
2996 ig.Emit (OpCodes.Beq, sec_begin);
3001 ig.MarkLabel (null_target);
3004 ig.MarkLabel (sec_begin);
3005 foreach (SwitchLabel sl in ss.Labels)
3006 ig.MarkLabel (sl.GetILLabelCode (ec));
3009 pending_goto_end = !ss.Block.HasRet;
3012 ig.MarkLabel (next_test);
3013 ig.MarkLabel (default_target);
3015 ig.MarkLabel (null_target);
3016 if (default_section != null)
3017 default_section.Block.Emit (ec);
3018 ig.MarkLabel (end_of_switch);
3021 SwitchSection FindSection (SwitchLabel label)
3023 foreach (SwitchSection ss in Sections){
3024 foreach (SwitchLabel sl in ss.Labels){
3033 public override bool Resolve (EmitContext ec)
3035 Expr = Expr.Resolve (ec);
3039 new_expr = SwitchGoverningType (ec, Expr.Type);
3040 if (new_expr == null){
3041 Report.Error (151, loc, "An integer type or string was expected for switch");
3046 SwitchType = new_expr.Type;
3048 if (!CheckSwitch (ec))
3051 Switch old_switch = ec.Switch;
3053 ec.Switch.SwitchType = SwitchType;
3055 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3056 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3058 is_constant = new_expr is Constant;
3060 object key = ((Constant) new_expr).GetValue ();
3061 SwitchLabel label = (SwitchLabel) Elements [key];
3063 constant_section = FindSection (label);
3064 if (constant_section == null)
3065 constant_section = default_section;
3069 foreach (SwitchSection ss in Sections){
3071 ec.CurrentBranching.CreateSibling (
3072 null, FlowBranching.SiblingType.SwitchSection);
3076 if (is_constant && (ss != constant_section)) {
3077 // If we're a constant switch, we're only emitting
3078 // one single section - mark all the others as
3080 ec.CurrentBranching.CurrentUsageVector.Goto ();
3081 if (!ss.Block.ResolveUnreachable (ec, true))
3084 if (!ss.Block.Resolve (ec))
3089 if (default_section == null)
3090 ec.CurrentBranching.CreateSibling (
3091 null, FlowBranching.SiblingType.SwitchSection);
3093 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3094 ec.Switch = old_switch;
3096 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3102 protected override void DoEmit (EmitContext ec)
3104 ILGenerator ig = ec.ig;
3106 // Store variable for comparission purposes
3109 value = ig.DeclareLocal (SwitchType);
3111 ig.Emit (OpCodes.Stloc, value);
3115 default_target = ig.DefineLabel ();
3118 // Setup the codegen context
3120 Label old_end = ec.LoopEnd;
3121 Switch old_switch = ec.Switch;
3123 ec.LoopEnd = ig.DefineLabel ();
3128 if (constant_section != null)
3129 constant_section.Block.Emit (ec);
3130 } else if (SwitchType == TypeManager.string_type)
3131 SimpleSwitchEmit (ec, value);
3133 TableSwitchEmit (ec, value);
3135 // Restore context state.
3136 ig.MarkLabel (ec.LoopEnd);
3139 // Restore the previous context
3141 ec.LoopEnd = old_end;
3142 ec.Switch = old_switch;
3146 public abstract class ExceptionStatement : Statement
3148 public abstract void EmitFinally (EmitContext ec);
3150 protected bool emit_finally = true;
3151 ArrayList parent_vectors;
3153 protected void DoEmitFinally (EmitContext ec)
3156 ec.ig.BeginFinallyBlock ();
3157 else if (ec.InIterator)
3158 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3162 protected void ResolveFinally (FlowBranchingException branching)
3164 emit_finally = branching.EmitFinally;
3166 branching.Parent.StealFinallyClauses (ref parent_vectors);
3170 public class Lock : ExceptionStatement {
3172 Statement Statement;
3175 public Lock (Expression expr, Statement stmt, Location l)
3182 public override bool Resolve (EmitContext ec)
3184 expr = expr.Resolve (ec);
3188 if (expr.Type.IsValueType){
3189 Error (185, "lock statement requires the expression to be " +
3190 " a reference type (type is: `{0}'",
3191 TypeManager.CSharpName (expr.Type));
3195 FlowBranchingException branching = ec.StartFlowBranching (this);
3196 bool ok = Statement.Resolve (ec);
3198 ec.KillFlowBranching ();
3202 ResolveFinally (branching);
3204 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3205 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3206 // Unfortunately, System.Reflection.Emit automatically emits
3207 // a leave to the end of the finally block.
3208 // This is a problem if `returns' is true since we may jump
3209 // to a point after the end of the method.
3210 // As a workaround, emit an explicit ret here.
3211 ec.NeedReturnLabel ();
3217 protected override void DoEmit (EmitContext ec)
3219 Type type = expr.Type;
3221 ILGenerator ig = ec.ig;
3222 temp = ig.DeclareLocal (type);
3225 ig.Emit (OpCodes.Dup);
3226 ig.Emit (OpCodes.Stloc, temp);
3227 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3231 ig.BeginExceptionBlock ();
3232 Statement.Emit (ec);
3237 ig.EndExceptionBlock ();
3240 public override void EmitFinally (EmitContext ec)
3242 ILGenerator ig = ec.ig;
3243 ig.Emit (OpCodes.Ldloc, temp);
3244 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3248 public class Unchecked : Statement {
3249 public readonly Block Block;
3251 public Unchecked (Block b)
3257 public override bool Resolve (EmitContext ec)
3259 bool previous_state = ec.CheckState;
3260 bool previous_state_const = ec.ConstantCheckState;
3262 ec.CheckState = false;
3263 ec.ConstantCheckState = false;
3264 bool ret = Block.Resolve (ec);
3265 ec.CheckState = previous_state;
3266 ec.ConstantCheckState = previous_state_const;
3271 protected override void DoEmit (EmitContext ec)
3273 bool previous_state = ec.CheckState;
3274 bool previous_state_const = ec.ConstantCheckState;
3276 ec.CheckState = false;
3277 ec.ConstantCheckState = false;
3279 ec.CheckState = previous_state;
3280 ec.ConstantCheckState = previous_state_const;
3284 public class Checked : Statement {
3285 public readonly Block Block;
3287 public Checked (Block b)
3290 b.Unchecked = false;
3293 public override bool Resolve (EmitContext ec)
3295 bool previous_state = ec.CheckState;
3296 bool previous_state_const = ec.ConstantCheckState;
3298 ec.CheckState = true;
3299 ec.ConstantCheckState = true;
3300 bool ret = Block.Resolve (ec);
3301 ec.CheckState = previous_state;
3302 ec.ConstantCheckState = previous_state_const;
3307 protected override void DoEmit (EmitContext ec)
3309 bool previous_state = ec.CheckState;
3310 bool previous_state_const = ec.ConstantCheckState;
3312 ec.CheckState = true;
3313 ec.ConstantCheckState = true;
3315 ec.CheckState = previous_state;
3316 ec.ConstantCheckState = previous_state_const;
3320 public class Unsafe : Statement {
3321 public readonly Block Block;
3323 public Unsafe (Block b)
3326 Block.Unsafe = true;
3329 public override bool Resolve (EmitContext ec)
3331 bool previous_state = ec.InUnsafe;
3335 val = Block.Resolve (ec);
3336 ec.InUnsafe = previous_state;
3341 protected override void DoEmit (EmitContext ec)
3343 bool previous_state = ec.InUnsafe;
3347 ec.InUnsafe = previous_state;
3354 public class Fixed : Statement {
3356 ArrayList declarators;
3357 Statement statement;
3362 abstract class Emitter
3364 protected LocalInfo vi;
3365 protected Expression converted;
3367 protected Emitter (Expression expr, LocalInfo li)
3373 public abstract void Emit (EmitContext ec);
3374 public abstract void EmitExit (ILGenerator ig);
3377 class ExpressionEmitter: Emitter {
3378 public ExpressionEmitter (Expression converted, LocalInfo li) :
3379 base (converted, li)
3383 public override void Emit (EmitContext ec) {
3385 // Store pointer in pinned location
3387 converted.Emit (ec);
3388 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3391 public override void EmitExit (ILGenerator ig)
3393 ig.Emit (OpCodes.Ldc_I4_0);
3394 ig.Emit (OpCodes.Conv_U);
3395 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3399 class StringEmitter: Emitter {
3400 LocalBuilder pinned_string;
3403 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3409 public override void Emit (EmitContext ec)
3411 ILGenerator ig = ec.ig;
3412 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3414 converted.Emit (ec);
3415 ig.Emit (OpCodes.Stloc, pinned_string);
3417 Expression sptr = new StringPtr (pinned_string, loc);
3418 converted = Convert.ImplicitConversionRequired (
3419 ec, sptr, vi.VariableType, loc);
3421 if (converted == null)
3424 converted.Emit (ec);
3425 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3428 public override void EmitExit(ILGenerator ig)
3430 ig.Emit (OpCodes.Ldnull);
3431 ig.Emit (OpCodes.Stloc, pinned_string);
3435 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3438 declarators = decls;
3443 public override bool Resolve (EmitContext ec)
3446 Expression.UnsafeError (loc);
3450 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3454 expr_type = texpr.ResolveType (ec);
3456 CheckObsolete (expr_type);
3458 if (ec.RemapToProxy){
3459 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3463 data = new Emitter [declarators.Count];
3465 if (!expr_type.IsPointer){
3466 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3471 foreach (Pair p in declarators){
3472 LocalInfo vi = (LocalInfo) p.First;
3473 Expression e = (Expression) p.Second;
3475 vi.VariableInfo.SetAssigned (ec);
3476 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3479 // The rules for the possible declarators are pretty wise,
3480 // but the production on the grammar is more concise.
3482 // So we have to enforce these rules here.
3484 // We do not resolve before doing the case 1 test,
3485 // because the grammar is explicit in that the token &
3486 // is present, so we need to test for this particular case.
3490 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3495 // Case 1: & object.
3497 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3498 Expression child = ((Unary) e).Expr;
3500 if (child is ParameterReference || child is LocalVariableReference){
3503 "No need to use fixed statement for parameters or " +
3504 "local variable declarations (address is already " +
3509 ec.InFixedInitializer = true;
3511 ec.InFixedInitializer = false;
3515 child = ((Unary) e).Expr;
3517 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3520 data [i] = new ExpressionEmitter (e, vi);
3526 ec.InFixedInitializer = true;
3528 ec.InFixedInitializer = false;
3535 if (e.Type.IsArray){
3536 Type array_type = TypeManager.GetElementType (e.Type);
3539 // Provided that array_type is unmanaged,
3541 if (!TypeManager.VerifyUnManaged (array_type, loc))
3545 // and T* is implicitly convertible to the
3546 // pointer type given in the fixed statement.
3548 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3550 Expression converted = Convert.ImplicitConversionRequired (
3551 ec, array_ptr, vi.VariableType, loc);
3552 if (converted == null)
3555 data [i] = new ExpressionEmitter (converted, vi);
3564 if (e.Type == TypeManager.string_type){
3565 data [i] = new StringEmitter (e, vi, loc);
3570 // Case 4: fixed buffer
3571 FieldExpr fe = e as FieldExpr;
3573 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3575 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3577 Expression converted = Convert.ImplicitConversionRequired (
3578 ec, fixed_buffer_ptr, vi.VariableType, loc);
3579 if (converted == null)
3582 data [i] = new ExpressionEmitter (converted, vi);
3590 // For other cases, flag a `this is already fixed expression'
3592 if (e is LocalVariableReference || e is ParameterReference ||
3593 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3595 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3599 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3603 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3605 if (!statement.Resolve (ec)) {
3606 ec.KillFlowBranching ();
3610 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3611 has_ret = reachability.IsUnreachable;
3616 protected override void DoEmit (EmitContext ec)
3618 for (int i = 0; i < data.Length; i++) {
3622 statement.Emit (ec);
3627 ILGenerator ig = ec.ig;
3630 // Clear the pinned variable
3632 for (int i = 0; i < data.Length; i++) {
3633 data [i].EmitExit (ig);
3638 public class Catch: Statement {
3639 public readonly string Name;
3640 public readonly Block Block;
3642 Expression type_expr;
3645 public Catch (Expression type, string name, Block block, Location l)
3653 public Type CatchType {
3659 public bool IsGeneral {
3661 return type_expr == null;
3665 protected override void DoEmit(EmitContext ec)
3669 public override bool Resolve (EmitContext ec)
3671 bool was_catch = ec.InCatch;
3674 if (type_expr != null) {
3675 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3679 type = te.ResolveType (ec);
3681 CheckObsolete (type);
3683 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3684 Error (155, "The type caught or thrown must be derived from System.Exception");
3690 return Block.Resolve (ec);
3693 ec.InCatch = was_catch;
3698 public class Try : ExceptionStatement {
3699 public readonly Block Fini, Block;
3700 public readonly ArrayList Specific;
3701 public readonly Catch General;
3703 bool need_exc_block;
3706 // specific, general and fini might all be null.
3708 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3710 if (specific == null && general == null){
3711 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3715 this.Specific = specific;
3716 this.General = general;
3721 public override bool Resolve (EmitContext ec)
3725 FlowBranchingException branching = ec.StartFlowBranching (this);
3727 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3729 if (!Block.Resolve (ec))
3732 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3734 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3736 Type[] prevCatches = new Type [Specific.Count];
3738 foreach (Catch c in Specific){
3739 ec.CurrentBranching.CreateSibling (
3740 c.Block, FlowBranching.SiblingType.Catch);
3742 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3744 if (c.Name != null) {
3745 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3747 throw new Exception ();
3749 vi.VariableInfo = null;
3752 if (!c.Resolve (ec))
3755 Type resolvedType = c.CatchType;
3756 for (int ii = 0; ii < last_index; ++ii) {
3757 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3758 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3763 prevCatches [last_index++] = resolvedType;
3764 need_exc_block = true;
3767 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3769 if (General != null){
3770 ec.CurrentBranching.CreateSibling (
3771 General.Block, FlowBranching.SiblingType.Catch);
3773 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3775 if (!General.Resolve (ec))
3778 need_exc_block = true;
3781 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3785 ec.CurrentBranching.CreateSibling (
3786 Fini, FlowBranching.SiblingType.Finally);
3788 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3789 bool was_finally = ec.InFinally;
3790 ec.InFinally = true;
3791 if (!Fini.Resolve (ec))
3793 ec.InFinally = was_finally;
3796 need_exc_block = true;
3799 if (ec.InIterator) {
3800 ResolveFinally (branching);
3801 need_exc_block |= emit_finally;
3803 emit_finally = Fini != null;
3805 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3807 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3809 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3811 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3812 // Unfortunately, System.Reflection.Emit automatically emits
3813 // a leave to the end of the finally block. This is a problem
3814 // if `returns' is true since we may jump to a point after the
3815 // end of the method.
3816 // As a workaround, emit an explicit ret here.
3817 ec.NeedReturnLabel ();
3823 protected override void DoEmit (EmitContext ec)
3825 ILGenerator ig = ec.ig;
3828 ig.BeginExceptionBlock ();
3831 foreach (Catch c in Specific){
3834 ig.BeginCatchBlock (c.CatchType);
3836 if (c.Name != null){
3837 vi = c.Block.GetLocalInfo (c.Name);
3839 throw new Exception ("Variable does not exist in this block");
3841 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3843 ig.Emit (OpCodes.Pop);
3848 if (General != null){
3849 ig.BeginCatchBlock (TypeManager.object_type);
3850 ig.Emit (OpCodes.Pop);
3851 General.Block.Emit (ec);
3856 ig.EndExceptionBlock ();
3859 public override void EmitFinally (EmitContext ec)
3865 public bool HasCatch
3868 return General != null || Specific.Count > 0;
3873 public class Using : ExceptionStatement {
3874 object expression_or_block;
3875 Statement Statement;
3880 Expression [] resolved_vars;
3881 Expression [] converted_vars;
3882 ExpressionStatement [] assign;
3883 LocalBuilder local_copy;
3885 public Using (object expression_or_block, Statement stmt, Location l)
3887 this.expression_or_block = expression_or_block;
3893 // Resolves for the case of using using a local variable declaration.
3895 bool ResolveLocalVariableDecls (EmitContext ec)
3899 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3903 expr_type = texpr.ResolveType (ec);
3906 // The type must be an IDisposable or an implicit conversion
3909 converted_vars = new Expression [var_list.Count];
3910 resolved_vars = new Expression [var_list.Count];
3911 assign = new ExpressionStatement [var_list.Count];
3913 bool need_conv = !TypeManager.ImplementsInterface (
3914 expr_type, TypeManager.idisposable_type);
3916 foreach (DictionaryEntry e in var_list){
3917 Expression var = (Expression) e.Key;
3919 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3923 resolved_vars [i] = var;
3930 converted_vars [i] = Convert.ImplicitConversionRequired (
3931 ec, var, TypeManager.idisposable_type, loc);
3933 if (converted_vars [i] == null)
3940 foreach (DictionaryEntry e in var_list){
3941 Expression var = resolved_vars [i];
3942 Expression new_expr = (Expression) e.Value;
3945 a = new Assign (var, new_expr, loc);
3951 converted_vars [i] = var;
3952 assign [i] = (ExpressionStatement) a;
3959 bool ResolveExpression (EmitContext ec)
3961 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3962 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3963 Report.Error (1674, loc, "'{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3964 TypeManager.CSharpName (expr_type));
3973 // Emits the code for the case of using using a local variable declaration.
3975 void EmitLocalVariableDecls (EmitContext ec)
3977 ILGenerator ig = ec.ig;
3980 for (i = 0; i < assign.Length; i++) {
3981 assign [i].EmitStatement (ec);
3984 ig.BeginExceptionBlock ();
3986 Statement.Emit (ec);
3987 var_list.Reverse ();
3992 void EmitLocalVariableDeclFinally (EmitContext ec)
3994 ILGenerator ig = ec.ig;
3996 int i = assign.Length;
3997 for (int ii = 0; ii < var_list.Count; ++ii){
3998 Expression var = resolved_vars [--i];
3999 Label skip = ig.DefineLabel ();
4001 if (!var.Type.IsValueType) {
4003 ig.Emit (OpCodes.Brfalse, skip);
4004 converted_vars [i].Emit (ec);
4005 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4007 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4009 if (!(ml is MethodGroupExpr)) {
4011 ig.Emit (OpCodes.Box, var.Type);
4012 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4014 MethodInfo mi = null;
4016 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4017 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4024 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4028 IMemoryLocation mloc = (IMemoryLocation) var;
4030 mloc.AddressOf (ec, AddressOp.Load);
4031 ig.Emit (OpCodes.Call, mi);
4035 ig.MarkLabel (skip);
4038 ig.EndExceptionBlock ();
4040 ig.BeginFinallyBlock ();
4045 void EmitExpression (EmitContext ec)
4048 // Make a copy of the expression and operate on that.
4050 ILGenerator ig = ec.ig;
4051 local_copy = ig.DeclareLocal (expr_type);
4056 ig.Emit (OpCodes.Stloc, local_copy);
4059 ig.BeginExceptionBlock ();
4061 Statement.Emit (ec);
4065 ig.EndExceptionBlock ();
4068 void EmitExpressionFinally (EmitContext ec)
4070 ILGenerator ig = ec.ig;
4071 if (!local_copy.LocalType.IsValueType) {
4072 Label skip = ig.DefineLabel ();
4073 ig.Emit (OpCodes.Ldloc, local_copy);
4074 ig.Emit (OpCodes.Brfalse, skip);
4075 ig.Emit (OpCodes.Ldloc, local_copy);
4076 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4077 ig.MarkLabel (skip);
4079 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4081 if (!(ml is MethodGroupExpr)) {
4082 ig.Emit (OpCodes.Ldloc, local_copy);
4083 ig.Emit (OpCodes.Box, local_copy.LocalType);
4084 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4086 MethodInfo mi = null;
4088 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4089 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4096 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4100 ig.Emit (OpCodes.Ldloca, local_copy);
4101 ig.Emit (OpCodes.Call, mi);
4106 public override bool Resolve (EmitContext ec)
4108 if (expression_or_block is DictionaryEntry){
4109 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4110 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4112 if (!ResolveLocalVariableDecls (ec))
4115 } else if (expression_or_block is Expression){
4116 expr = (Expression) expression_or_block;
4118 expr = expr.Resolve (ec);
4122 expr_type = expr.Type;
4124 if (!ResolveExpression (ec))
4128 FlowBranchingException branching = ec.StartFlowBranching (this);
4130 bool ok = Statement.Resolve (ec);
4133 ec.KillFlowBranching ();
4137 ResolveFinally (branching);
4138 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4140 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4141 // Unfortunately, System.Reflection.Emit automatically emits a leave
4142 // to the end of the finally block. This is a problem if `returns'
4143 // is true since we may jump to a point after the end of the method.
4144 // As a workaround, emit an explicit ret here.
4145 ec.NeedReturnLabel ();
4151 protected override void DoEmit (EmitContext ec)
4153 if (expression_or_block is DictionaryEntry)
4154 EmitLocalVariableDecls (ec);
4155 else if (expression_or_block is Expression)
4156 EmitExpression (ec);
4159 public override void EmitFinally (EmitContext ec)
4161 if (expression_or_block is DictionaryEntry)
4162 EmitLocalVariableDeclFinally (ec);
4163 else if (expression_or_block is Expression)
4164 EmitExpressionFinally (ec);
4169 /// Implementation of the foreach C# statement
4171 public class Foreach : Statement {
4173 Expression variable;
4175 Statement statement;
4177 CollectionForeach collection;
4179 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4180 Statement stmt, Location l)
4183 this.variable = var;
4189 public override bool Resolve (EmitContext ec)
4191 expr = expr.Resolve (ec);
4195 if (expr is NullLiteral) {
4196 Report.Error (186, expr.Location, "Use of null is not valid in this context");
4200 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4204 Type var_type = texpr.Type;
4207 // We need an instance variable. Not sure this is the best
4208 // way of doing this.
4210 // FIXME: When we implement propertyaccess, will those turn
4211 // out to return values in ExprClass? I think they should.
4213 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4214 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4215 CollectionForeach.error1579 (expr.Type, loc);
4219 if (expr.Type.IsArray) {
4220 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4221 return array.Resolve (ec);
4223 collection = new CollectionForeach (
4224 var_type, variable, expr, statement, loc);
4225 return collection.Resolve (ec);
4229 protected override void DoEmit (EmitContext ec)
4231 ILGenerator ig = ec.ig;
4233 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4234 ec.LoopBegin = ig.DefineLabel ();
4235 ec.LoopEnd = ig.DefineLabel ();
4237 if (collection != null)
4238 collection.Emit (ec);
4242 ec.LoopBegin = old_begin;
4243 ec.LoopEnd = old_end;
4246 protected class TemporaryVariable : Expression, IMemoryLocation
4251 public TemporaryVariable (Type type, Location loc)
4255 eclass = ExprClass.Value;
4260 public override Expression DoResolve (EmitContext ec)
4262 if (ec.InIterator) {
4264 fb = ec.CurrentIterator.MapVariable (
4265 "s_", count.ToString (), type);
4267 TypeExpr te = new TypeExpression (type, loc);
4268 li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
4269 if (!li.Resolve (ec))
4276 public override void Emit (EmitContext ec)
4278 ILGenerator ig = ec.ig;
4281 ig.Emit (OpCodes.Ldarg_0);
4282 ig.Emit (OpCodes.Ldfld, fb);
4284 ig.Emit (OpCodes.Ldloc, li.LocalBuilder);
4288 public void EmitLoadAddress (EmitContext ec)
4290 ILGenerator ig = ec.ig;
4293 ig.Emit (OpCodes.Ldarg_0);
4294 ig.Emit (OpCodes.Ldflda, fb);
4296 ig.Emit (OpCodes.Ldloca, li.LocalBuilder);
4300 public void Store (EmitContext ec, Expression right_side)
4303 ec.ig.Emit (OpCodes.Ldarg_0);
4305 right_side.Emit (ec);
4307 ec.ig.Emit (OpCodes.Stfld, fb);
4309 ec.ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4312 public void EmitThis (ILGenerator ig)
4315 ig.Emit (OpCodes.Ldarg_0);
4318 public void EmitStore (ILGenerator ig)
4321 ig.Emit (OpCodes.Stfld, fb);
4323 ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4326 public void AddressOf (EmitContext ec, AddressOp mode)
4328 EmitLoadAddress (ec);
4332 protected class ArrayCounter : TemporaryVariable
4334 public ArrayCounter (Location loc)
4335 : base (TypeManager.int32_type, loc)
4338 public void Initialize (EmitContext ec)
4341 ec.ig.Emit (OpCodes.Ldc_I4_0);
4345 public void Increment (EmitContext ec)
4349 ec.ig.Emit (OpCodes.Ldc_I4_1);
4350 ec.ig.Emit (OpCodes.Add);
4355 protected class ArrayForeach : Statement
4357 Expression variable, expr, conv;
4358 Statement statement;
4359 Type array_type, element_type;
4361 TemporaryVariable[] lengths;
4362 ArrayCounter[] counter;
4365 TemporaryVariable copy;
4368 public ArrayForeach (Type var_type, Expression var,
4369 Expression expr, Statement stmt, Location l)
4371 this.var_type = var_type;
4372 this.variable = var;
4378 public override bool Resolve (EmitContext ec)
4380 array_type = expr.Type;
4381 element_type = TypeManager.GetElementType (array_type);
4382 rank = array_type.GetArrayRank ();
4384 copy = new TemporaryVariable (array_type, loc);
4387 counter = new ArrayCounter [rank];
4388 lengths = new TemporaryVariable [rank];
4390 ArrayList list = new ArrayList ();
4391 for (int i = 0; i < rank; i++) {
4392 counter [i] = new ArrayCounter (loc);
4393 counter [i].Resolve (ec);
4395 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4396 lengths [i].Resolve (ec);
4398 list.Add (counter [i]);
4401 access = new ElementAccess (copy, list, loc).Resolve (ec);
4405 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4411 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4412 ec.CurrentBranching.CreateSibling ();
4414 variable = variable.ResolveLValue (ec, conv, loc);
4415 if (variable == null)
4418 if (!statement.Resolve (ec))
4421 ec.EndFlowBranching ();
4426 protected override void DoEmit (EmitContext ec)
4428 ILGenerator ig = ec.ig;
4430 copy.Store (ec, expr);
4432 Label[] test = new Label [rank];
4433 Label[] loop = new Label [rank];
4435 for (int i = 0; i < rank; i++) {
4436 test [i] = ig.DefineLabel ();
4437 loop [i] = ig.DefineLabel ();
4439 lengths [i].EmitThis (ig);
4440 ((ArrayAccess) access).EmitGetLength (ec, i);
4441 lengths [i].EmitStore (ig);
4444 for (int i = 0; i < rank; i++) {
4445 counter [i].Initialize (ec);
4447 ig.Emit (OpCodes.Br, test [i]);
4448 ig.MarkLabel (loop [i]);
4451 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4453 statement.Emit (ec);
4455 ig.MarkLabel (ec.LoopBegin);
4457 for (int i = rank - 1; i >= 0; i--){
4458 counter [i].Increment (ec);
4460 ig.MarkLabel (test [i]);
4461 counter [i].Emit (ec);
4462 lengths [i].Emit (ec);
4463 ig.Emit (OpCodes.Blt, loop [i]);
4466 ig.MarkLabel (ec.LoopEnd);
4470 protected class CollectionForeach : ExceptionStatement
4472 Expression variable, expr;
4473 Statement statement;
4475 TemporaryVariable enumerator;
4479 MethodGroupExpr get_enumerator;
4480 PropertyExpr get_current;
4481 MethodInfo move_next;
4482 Type var_type, enumerator_type;
4485 public CollectionForeach (Type var_type, Expression var,
4486 Expression expr, Statement stmt, Location l)
4488 this.var_type = var_type;
4489 this.variable = var;
4495 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4497 Type [] args = TypeManager.GetArgumentTypes (mi);
4499 if (args.Length != 0)
4503 if (TypeManager.IsOverride (mi))
4506 // Check whether GetEnumerator is public
4507 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4510 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4512 // Apply the same optimization as MS: skip the GetEnumerator
4513 // returning an IEnumerator, and use the one returning a
4514 // CharEnumerator instead. This allows us to avoid the
4515 // try-finally block and the boxing.
4520 // Ok, we can access it, now make sure that we can do something
4521 // with this `GetEnumerator'
4524 Type return_type = mi.ReturnType;
4525 if (mi.ReturnType == TypeManager.ienumerator_type ||
4526 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4527 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4529 // If it is not an interface, lets try to find the methods ourselves.
4530 // For example, if we have:
4531 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4532 // We can avoid the iface call. This is a runtime perf boost.
4533 // even bigger if we have a ValueType, because we avoid the cost
4536 // We have to make sure that both methods exist for us to take
4537 // this path. If one of the methods does not exist, we will just
4538 // use the interface. Sadly, this complex if statement is the only
4539 // way I could do this without a goto
4542 if (return_type.IsInterface ||
4543 !FetchMoveNext (ec, return_type) ||
4544 !FetchGetCurrent (ec, return_type)) {
4545 move_next = TypeManager.bool_movenext_void;
4546 get_current = new PropertyExpr (
4547 ec, TypeManager.ienumerator_getcurrent, loc);
4552 // Ok, so they dont return an IEnumerable, we will have to
4553 // find if they support the GetEnumerator pattern.
4556 if (!FetchMoveNext (ec, return_type))
4559 if (!FetchGetCurrent (ec, return_type))
4563 enumerator_type = return_type;
4564 is_disposable = !enumerator_type.IsSealed ||
4565 TypeManager.ImplementsInterface (
4566 enumerator_type, TypeManager.idisposable_type);
4572 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4574 bool FetchMoveNext (EmitContext ec, Type t)
4576 MemberList move_next_list;
4578 move_next_list = TypeContainer.FindMembers (
4579 t, MemberTypes.Method,
4580 BindingFlags.Public | BindingFlags.Instance,
4581 Type.FilterName, "MoveNext");
4582 if (move_next_list.Count == 0)
4585 foreach (MemberInfo m in move_next_list){
4586 MethodInfo mi = (MethodInfo) m;
4589 args = TypeManager.GetArgumentTypes (mi);
4590 if ((args != null) && (args.Length == 0) &&
4591 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4601 // Retrieves a `public T get_Current ()' method from the Type `t'
4603 bool FetchGetCurrent (EmitContext ec, Type t)
4605 PropertyExpr pe = Expression.MemberLookup (
4606 ec, t, "Current", MemberTypes.Property,
4607 Expression.AllBindingFlags, loc) as PropertyExpr;
4616 // Retrieves a `public void Dispose ()' method from the Type `t'
4618 static MethodInfo FetchMethodDispose (Type t)
4620 MemberList dispose_list;
4622 dispose_list = TypeContainer.FindMembers (
4623 t, MemberTypes.Method,
4624 BindingFlags.Public | BindingFlags.Instance,
4625 Type.FilterName, "Dispose");
4626 if (dispose_list.Count == 0)
4629 foreach (MemberInfo m in dispose_list){
4630 MethodInfo mi = (MethodInfo) m;
4633 args = TypeManager.GetArgumentTypes (mi);
4634 if (args != null && args.Length == 0){
4635 if (mi.ReturnType == TypeManager.void_type)
4642 static public void error1579 (Type t, Location loc)
4644 Report.Error (1579, loc, "foreach statement cannot operate on " +
4645 "variables of type `{0}' because that class does " +
4646 "not provide a GetEnumerator method or it is " +
4647 "inaccessible", t.FullName);
4650 bool TryType (EmitContext ec, Type t)
4652 MethodGroupExpr mg = Expression.MemberLookup (
4653 ec, t, "GetEnumerator", MemberTypes.Method,
4654 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4658 foreach (MethodBase mb in mg.Methods) {
4659 if (!GetEnumeratorFilter (ec, (MethodInfo) mb))
4662 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) mb };
4663 get_enumerator = new MethodGroupExpr (mi, loc);
4665 if (t != expr.Type) {
4666 expr = Convert.ExplicitConversion (
4669 throw new InternalErrorException ();
4672 get_enumerator.InstanceExpression = expr;
4673 get_enumerator.IsBase = t != expr.Type;
4681 bool ProbeCollectionType (EmitContext ec, Type t)
4683 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4684 if (TryType (ec, tt))
4690 // Now try to find the method in the interfaces
4693 Type [] ifaces = t.GetInterfaces ();
4695 foreach (Type i in ifaces){
4696 if (TryType (ec, i))
4701 // Since TypeBuilder.GetInterfaces only returns the interface
4702 // types for this type, we have to keep looping, but once
4703 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4704 // done, because it returns all the types
4706 if ((t is TypeBuilder))
4715 public override bool Resolve (EmitContext ec)
4717 enumerator_type = TypeManager.ienumerator_type;
4718 is_disposable = true;
4720 if (!ProbeCollectionType (ec, expr.Type)) {
4721 error1579 (expr.Type, loc);
4725 enumerator = new TemporaryVariable (enumerator_type, loc);
4726 enumerator.Resolve (ec);
4728 init = new Invocation (get_enumerator, new ArrayList (), loc);
4729 init = init.Resolve (ec);
4733 Expression move_next_expr;
4735 MemberInfo[] mi = new MemberInfo[] { move_next };
4736 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4737 mg.InstanceExpression = enumerator;
4739 move_next_expr = new Invocation (mg, new ArrayList (), loc);
4742 get_current.InstanceExpression = enumerator;
4744 Statement block = new CollectionForeachStatement (
4745 var_type, variable, get_current, statement, loc);
4747 loop = new While (move_next_expr, block, loc);
4751 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4752 ec.CurrentBranching.CreateSibling ();
4754 FlowBranchingException branching = null;
4756 branching = ec.StartFlowBranching (this);
4758 if (!loop.Resolve (ec))
4761 if (is_disposable) {
4762 ResolveFinally (branching);
4763 ec.EndFlowBranching ();
4765 emit_finally = true;
4767 ec.EndFlowBranching ();
4772 protected override void DoEmit (EmitContext ec)
4774 ILGenerator ig = ec.ig;
4776 enumerator.Store (ec, init);
4779 // Protect the code in a try/finalize block, so that
4780 // if the beast implement IDisposable, we get rid of it
4782 if (is_disposable && emit_finally)
4783 ig.BeginExceptionBlock ();
4788 // Now the finally block
4790 if (is_disposable) {
4793 ig.EndExceptionBlock ();
4798 public override void EmitFinally (EmitContext ec)
4800 ILGenerator ig = ec.ig;
4802 if (enumerator_type.IsValueType) {
4803 enumerator.Emit (ec);
4805 MethodInfo mi = FetchMethodDispose (enumerator_type);
4807 enumerator.EmitLoadAddress (ec);
4808 ig.Emit (OpCodes.Call, mi);
4810 enumerator.Emit (ec);
4811 ig.Emit (OpCodes.Box, enumerator_type);
4812 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4815 Label call_dispose = ig.DefineLabel ();
4817 enumerator.Emit (ec);
4818 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4819 ig.Emit (OpCodes.Dup);
4820 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4821 ig.Emit (OpCodes.Pop);
4823 Label end_finally = ig.DefineLabel ();
4824 ig.Emit (OpCodes.Br, end_finally);
4826 ig.MarkLabel (call_dispose);
4827 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4828 ig.MarkLabel (end_finally);
4833 protected class CollectionForeachStatement : Statement
4836 Expression variable, current, conv;
4837 Statement statement;
4840 public CollectionForeachStatement (Type type, Expression variable,
4841 Expression current, Statement statement,
4845 this.variable = variable;
4846 this.current = current;
4847 this.statement = statement;
4851 public override bool Resolve (EmitContext ec)
4853 current = current.Resolve (ec);
4854 if (current == null)
4857 conv = Convert.ExplicitConversion (ec, current, type, loc);
4861 assign = new Assign (variable, conv, loc);
4862 if (assign.Resolve (ec) == null)
4865 if (!statement.Resolve (ec))
4871 protected override void DoEmit (EmitContext ec)
4873 assign.EmitStatement (ec);
4874 statement.Emit (ec);