2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@ximian.com)
7 // Marek Safar (marek.safar@seznam.cz)
9 // (C) 2001, 2002, 2003 Ximian, Inc.
10 // (C) 2003, 2004 Novell, Inc.
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Diagnostics;
18 using System.Collections;
19 using System.Collections.Specialized;
21 namespace Mono.CSharp {
23 public abstract class Statement {
27 /// Resolves the statement, true means that all sub-statements
30 public virtual bool Resolve (EmitContext ec)
36 /// We already know that the statement is unreachable, but we still
37 /// need to resolve it to catch errors.
39 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
42 // This conflicts with csc's way of doing this, but IMHO it's
43 // the right thing to do.
45 // If something is unreachable, we still check whether it's
46 // correct. This means that you cannot use unassigned variables
47 // in unreachable code, for instance.
51 Report.Warning (162, 2, loc, "Unreachable code detected");
53 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
54 bool ok = Resolve (ec);
55 ec.KillFlowBranching ();
61 /// Return value indicates whether all code paths emitted return.
63 protected abstract void DoEmit (EmitContext ec);
66 /// Utility wrapper routine for Error, just to beautify the code
68 public void Error (int error, string format, params object[] args)
70 Error (error, String.Format (format, args));
73 public void Error (int error, string s)
76 Report.Error (error, loc, s);
78 Report.Error (error, s);
82 /// Return value indicates whether all code paths emitted return.
84 public virtual void Emit (EmitContext ec)
91 public sealed class EmptyStatement : Statement {
93 private EmptyStatement () {}
95 public static readonly EmptyStatement Value = new EmptyStatement ();
97 public override bool Resolve (EmitContext ec)
102 public override bool ResolveUnreachable (EmitContext ec, bool warn)
107 protected override void DoEmit (EmitContext ec)
112 public class If : Statement {
114 public Statement TrueStatement;
115 public Statement FalseStatement;
119 public If (Expression expr, Statement trueStatement, Location l)
122 TrueStatement = trueStatement;
126 public If (Expression expr,
127 Statement trueStatement,
128 Statement falseStatement,
132 TrueStatement = trueStatement;
133 FalseStatement = falseStatement;
137 public override bool Resolve (EmitContext ec)
141 Report.Debug (1, "START IF BLOCK", loc);
143 expr = Expression.ResolveBoolean (ec, expr, loc);
149 Assign ass = expr as Assign;
150 if (ass != null && ass.Source is Constant) {
151 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
155 // Dead code elimination
157 if (expr is BoolConstant){
158 bool take = ((BoolConstant) expr).Value;
161 if (!TrueStatement.Resolve (ec))
164 if ((FalseStatement != null) &&
165 !FalseStatement.ResolveUnreachable (ec, true))
167 FalseStatement = null;
169 if (!TrueStatement.ResolveUnreachable (ec, true))
171 TrueStatement = null;
173 if ((FalseStatement != null) &&
174 !FalseStatement.Resolve (ec))
181 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
183 ok &= TrueStatement.Resolve (ec);
185 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
187 ec.CurrentBranching.CreateSibling ();
189 if (FalseStatement != null)
190 ok &= FalseStatement.Resolve (ec);
192 ec.EndFlowBranching ();
194 Report.Debug (1, "END IF BLOCK", loc);
199 protected override void DoEmit (EmitContext ec)
201 ILGenerator ig = ec.ig;
202 Label false_target = ig.DefineLabel ();
206 // If we're a boolean expression, Resolve() already
207 // eliminated dead code for us.
209 if (expr is BoolConstant){
210 bool take = ((BoolConstant) expr).Value;
213 TrueStatement.Emit (ec);
214 else if (FalseStatement != null)
215 FalseStatement.Emit (ec);
220 expr.EmitBranchable (ec, false_target, false);
222 TrueStatement.Emit (ec);
224 if (FalseStatement != null){
225 bool branch_emitted = false;
227 end = ig.DefineLabel ();
229 ig.Emit (OpCodes.Br, end);
230 branch_emitted = true;
233 ig.MarkLabel (false_target);
234 FalseStatement.Emit (ec);
239 ig.MarkLabel (false_target);
244 public class Do : Statement {
245 public Expression expr;
246 public readonly Statement EmbeddedStatement;
249 public Do (Statement statement, Expression boolExpr, Location l)
252 EmbeddedStatement = statement;
256 public override bool Resolve (EmitContext ec)
260 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
262 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
264 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
265 if (!EmbeddedStatement.Resolve (ec))
267 ec.EndFlowBranching ();
269 if (ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable && !was_unreachable)
270 Report.Warning (162, 2, expr.Location, "Unreachable code detected");
272 expr = Expression.ResolveBoolean (ec, expr, loc);
275 else if (expr is BoolConstant){
276 bool res = ((BoolConstant) expr).Value;
282 ec.CurrentBranching.CurrentUsageVector.Goto ();
284 ec.EndFlowBranching ();
289 protected override void DoEmit (EmitContext ec)
291 ILGenerator ig = ec.ig;
292 Label loop = ig.DefineLabel ();
293 Label old_begin = ec.LoopBegin;
294 Label old_end = ec.LoopEnd;
296 ec.LoopBegin = ig.DefineLabel ();
297 ec.LoopEnd = ig.DefineLabel ();
300 EmbeddedStatement.Emit (ec);
301 ig.MarkLabel (ec.LoopBegin);
304 // Dead code elimination
306 if (expr is BoolConstant){
307 bool res = ((BoolConstant) expr).Value;
310 ec.ig.Emit (OpCodes.Br, loop);
312 expr.EmitBranchable (ec, loop, true);
314 ig.MarkLabel (ec.LoopEnd);
316 ec.LoopBegin = old_begin;
317 ec.LoopEnd = old_end;
321 public class While : Statement {
322 public Expression expr;
323 public readonly Statement Statement;
324 bool infinite, empty;
326 public While (Expression boolExpr, Statement statement, Location l)
328 this.expr = boolExpr;
329 Statement = statement;
333 public override bool Resolve (EmitContext ec)
337 expr = Expression.ResolveBoolean (ec, expr, loc);
342 // Inform whether we are infinite or not
344 if (expr is BoolConstant){
345 BoolConstant bc = (BoolConstant) expr;
347 if (bc.Value == false){
348 if (!Statement.ResolveUnreachable (ec, true))
356 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
358 ec.CurrentBranching.CreateSibling ();
360 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
361 if (!Statement.Resolve (ec))
363 ec.EndFlowBranching ();
365 // There's no direct control flow from the end of the embedded statement to the end of the loop
366 ec.CurrentBranching.CurrentUsageVector.Goto ();
368 ec.EndFlowBranching ();
373 protected override void DoEmit (EmitContext ec)
378 ILGenerator ig = ec.ig;
379 Label old_begin = ec.LoopBegin;
380 Label old_end = ec.LoopEnd;
382 ec.LoopBegin = ig.DefineLabel ();
383 ec.LoopEnd = ig.DefineLabel ();
386 // Inform whether we are infinite or not
388 if (expr is BoolConstant){
389 ig.MarkLabel (ec.LoopBegin);
391 ig.Emit (OpCodes.Br, ec.LoopBegin);
394 // Inform that we are infinite (ie, `we return'), only
395 // if we do not `break' inside the code.
397 ig.MarkLabel (ec.LoopEnd);
399 Label while_loop = ig.DefineLabel ();
401 ig.Emit (OpCodes.Br, ec.LoopBegin);
402 ig.MarkLabel (while_loop);
406 ig.MarkLabel (ec.LoopBegin);
408 expr.EmitBranchable (ec, while_loop, true);
410 ig.MarkLabel (ec.LoopEnd);
413 ec.LoopBegin = old_begin;
414 ec.LoopEnd = old_end;
418 public class For : Statement {
420 readonly Statement InitStatement;
421 readonly Statement Increment;
422 public readonly Statement Statement;
423 bool infinite, empty;
425 public For (Statement initStatement,
431 InitStatement = initStatement;
433 Increment = increment;
434 Statement = statement;
438 public override bool Resolve (EmitContext ec)
442 if (InitStatement != null){
443 if (!InitStatement.Resolve (ec))
448 Test = Expression.ResolveBoolean (ec, Test, loc);
451 else if (Test is BoolConstant){
452 BoolConstant bc = (BoolConstant) Test;
454 if (bc.Value == false){
455 if (!Statement.ResolveUnreachable (ec, true))
457 if ((Increment != null) &&
458 !Increment.ResolveUnreachable (ec, false))
468 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
470 ec.CurrentBranching.CreateSibling ();
472 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
474 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
475 if (!Statement.Resolve (ec))
477 ec.EndFlowBranching ();
479 if (Increment != null){
480 if (ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable) {
481 if (!Increment.ResolveUnreachable (ec, !was_unreachable))
484 if (!Increment.Resolve (ec))
489 // There's no direct control flow from the end of the embedded statement to the end of the loop
490 ec.CurrentBranching.CurrentUsageVector.Goto ();
492 ec.EndFlowBranching ();
497 protected override void DoEmit (EmitContext ec)
502 ILGenerator ig = ec.ig;
503 Label old_begin = ec.LoopBegin;
504 Label old_end = ec.LoopEnd;
505 Label loop = ig.DefineLabel ();
506 Label test = ig.DefineLabel ();
508 if (InitStatement != null && InitStatement != EmptyStatement.Value)
509 InitStatement.Emit (ec);
511 ec.LoopBegin = ig.DefineLabel ();
512 ec.LoopEnd = ig.DefineLabel ();
514 ig.Emit (OpCodes.Br, test);
518 ig.MarkLabel (ec.LoopBegin);
519 if (Increment != EmptyStatement.Value)
524 // If test is null, there is no test, and we are just
529 // The Resolve code already catches the case for
530 // Test == BoolConstant (false) so we know that
533 if (Test is BoolConstant)
534 ig.Emit (OpCodes.Br, loop);
536 Test.EmitBranchable (ec, loop, true);
539 ig.Emit (OpCodes.Br, loop);
540 ig.MarkLabel (ec.LoopEnd);
542 ec.LoopBegin = old_begin;
543 ec.LoopEnd = old_end;
547 public class StatementExpression : Statement {
548 ExpressionStatement expr;
550 public StatementExpression (ExpressionStatement expr)
556 public override bool Resolve (EmitContext ec)
559 expr = expr.ResolveStatement (ec);
563 protected override void DoEmit (EmitContext ec)
565 expr.EmitStatement (ec);
568 public override string ToString ()
570 return "StatementExpression (" + expr + ")";
575 /// Implements the return statement
577 public class Return : Statement {
578 public Expression Expr;
580 public Return (Expression expr, Location l)
588 public override bool Resolve (EmitContext ec)
590 AnonymousContainer am = ec.CurrentAnonymousMethod;
591 if ((am != null) && am.IsIterator && ec.InIterator) {
592 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
593 "statement to return a value, or yield break to end the iteration");
597 if (ec.ReturnType == null){
599 if (ec.CurrentAnonymousMethod != null){
600 Report.Error (1662, loc,
601 "Cannot convert anonymous method block to delegate type `{0}' because some of the return types in the block are not implicitly convertible to the delegate return type",
602 ec.CurrentAnonymousMethod.GetSignatureForError ());
604 Error (127, "A return keyword must not be followed by any expression when method returns void");
609 Error (126, "An object of a type convertible to `{0}' is required " +
610 "for the return statement",
611 TypeManager.CSharpName (ec.ReturnType));
615 Expr = Expr.Resolve (ec);
619 if (Expr.Type != ec.ReturnType) {
620 Expr = Convert.ImplicitConversionRequired (
621 ec, Expr, ec.ReturnType, loc);
627 int errors = Report.Errors;
628 unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
630 ec.NeedReturnLabel ();
631 ec.CurrentBranching.CurrentUsageVector.Return ();
632 return errors == Report.Errors;
635 protected override void DoEmit (EmitContext ec)
641 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
645 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
647 ec.ig.Emit (OpCodes.Ret);
651 public class Goto : Statement {
653 LabeledStatement label;
656 public override bool Resolve (EmitContext ec)
658 int errors = Report.Errors;
659 unwind_protect = ec.CurrentBranching.AddGotoOrigin (ec.CurrentBranching.CurrentUsageVector, this);
660 ec.CurrentBranching.CurrentUsageVector.Goto ();
661 return errors == Report.Errors;
664 public Goto (string label, Location l)
670 public string Target {
671 get { return target; }
674 public void SetResolvedTarget (LabeledStatement label)
677 label.AddReference ();
680 protected override void DoEmit (EmitContext ec)
683 throw new InternalErrorException ("goto emitted before target resolved");
684 Label l = label.LabelTarget (ec);
685 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
689 public class LabeledStatement : Statement {
696 FlowBranching.UsageVector vectors;
698 public LabeledStatement (string name, Location l)
704 public Label LabelTarget (EmitContext ec)
709 label = ec.ig.DefineLabel ();
719 public bool IsDefined {
720 get { return defined; }
723 public bool HasBeenReferenced {
724 get { return referenced; }
727 public FlowBranching.UsageVector JumpOrigins {
728 get { return vectors; }
731 public void AddUsageVector (FlowBranching.UsageVector vector)
733 vector = vector.Clone ();
734 vector.Next = vectors;
738 public override bool Resolve (EmitContext ec)
740 // this flow-branching will be terminated when the surrounding block ends
741 ec.StartFlowBranching (this);
745 protected override void DoEmit (EmitContext ec)
747 if (ig != null && ig != ec.ig)
748 throw new InternalErrorException ("cannot happen");
750 ec.ig.MarkLabel (label);
753 public void AddReference ()
761 /// `goto default' statement
763 public class GotoDefault : Statement {
765 public GotoDefault (Location l)
770 public override bool Resolve (EmitContext ec)
772 ec.CurrentBranching.CurrentUsageVector.Goto ();
776 protected override void DoEmit (EmitContext ec)
778 if (ec.Switch == null){
779 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
783 if (!ec.Switch.GotDefault){
784 Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
787 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
792 /// `goto case' statement
794 public class GotoCase : Statement {
798 public GotoCase (Expression e, Location l)
804 public override bool Resolve (EmitContext ec)
806 if (ec.Switch == null){
807 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
811 expr = expr.Resolve (ec);
815 Constant c = expr as Constant;
817 Error (150, "A constant value is expected");
821 Type type = ec.Switch.SwitchType;
822 if (!Convert.ImplicitStandardConversionExists (c, type))
823 Report.Warning (469, 2, loc, "The `goto case' value is not implicitly " +
824 "convertible to type `{0}'", TypeManager.CSharpName (type));
827 object val = c.GetValue ();
828 if ((val != null) && (c.Type != type) && (c.Type != TypeManager.object_type))
829 val = TypeManager.ChangeType (val, type, out fail);
832 Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
833 c.GetSignatureForError (), TypeManager.CSharpName (type));
838 val = SwitchLabel.NullStringCase;
840 sl = (SwitchLabel) ec.Switch.Elements [val];
843 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", c.GetValue () == null ? "null" : val.ToString ());
847 ec.CurrentBranching.CurrentUsageVector.Goto ();
851 protected override void DoEmit (EmitContext ec)
853 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
857 public class Throw : Statement {
860 public Throw (Expression expr, Location l)
866 public override bool Resolve (EmitContext ec)
868 ec.CurrentBranching.CurrentUsageVector.Throw ();
871 expr = expr.Resolve (ec);
875 ExprClass eclass = expr.eclass;
877 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
878 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
879 expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
885 if ((t != TypeManager.exception_type) &&
886 !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
887 !(expr is NullLiteral)) {
889 "The type caught or thrown must be derived " +
890 "from System.Exception");
897 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
902 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
908 protected override void DoEmit (EmitContext ec)
911 ec.ig.Emit (OpCodes.Rethrow);
915 ec.ig.Emit (OpCodes.Throw);
920 public class Break : Statement {
922 public Break (Location l)
929 public override bool Resolve (EmitContext ec)
931 int errors = Report.Errors;
932 unwind_protect = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
933 ec.CurrentBranching.CurrentUsageVector.Goto ();
934 return errors == Report.Errors;
937 protected override void DoEmit (EmitContext ec)
939 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
943 public class Continue : Statement {
945 public Continue (Location l)
952 public override bool Resolve (EmitContext ec)
954 int errors = Report.Errors;
955 unwind_protect = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
956 ec.CurrentBranching.CurrentUsageVector.Goto ();
957 return errors == Report.Errors;
960 protected override void DoEmit (EmitContext ec)
962 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
967 // The information about a user-perceived local variable
969 public class LocalInfo {
970 public Expression Type;
973 // Most of the time a variable will be stored in a LocalBuilder
975 // But sometimes, it will be stored in a field (variables that have been
976 // hoisted by iterators or by anonymous methods). The context of the field will
977 // be stored in the EmitContext
980 public LocalBuilder LocalBuilder;
981 public FieldBuilder FieldBuilder;
983 public Type VariableType;
984 public readonly string Name;
985 public readonly Location Location;
986 public readonly Block Block;
988 public VariableInfo VariableInfo;
998 CompilerGenerated = 64,
1002 public enum ReadOnlyContext: byte {
1009 ReadOnlyContext ro_context;
1011 public LocalInfo (Expression type, string name, Block block, Location l)
1019 public LocalInfo (DeclSpace ds, Block block, Location l)
1021 VariableType = ds.TypeBuilder;
1026 public void DeclareLocal (ILGenerator ig)
1030 // This is needed to compile on both .NET 1.x and .NET 2.x
1031 // the later introduced `DeclareLocal (Type t, bool pinned)'
1033 LocalBuilder = TypeManager.DeclareLocalPinned (ig, VariableType);
1036 if (!IsThis && !IsConstant)
1037 LocalBuilder = ig.DeclareLocal (VariableType);
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.Type;
1069 if (VariableType == TypeManager.void_type) {
1070 Expression.Error_VoidInvalidInTheContext (Location);
1074 if (VariableType.IsAbstract && VariableType.IsSealed) {
1075 FieldMember.Error_VariableOfStaticClass (Location, Name, VariableType);
1079 if (VariableType.IsPointer && !ec.InUnsafe)
1080 Expression.UnsafeError (Location);
1085 public bool IsCaptured {
1087 return (flags & Flags.Captured) != 0;
1091 flags |= Flags.Captured;
1095 public bool IsConstant {
1097 return (flags & Flags.IsConstant) != 0;
1100 flags |= Flags.IsConstant;
1104 public bool AddressTaken {
1106 return (flags & Flags.AddressTaken) != 0;
1110 flags |= Flags.AddressTaken;
1114 public bool CompilerGenerated {
1116 return (flags & Flags.CompilerGenerated) != 0;
1120 flags |= Flags.CompilerGenerated;
1124 public override string ToString ()
1126 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1127 Name, Type, VariableInfo, Location);
1132 return (flags & Flags.Used) != 0;
1135 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1139 public bool ReadOnly {
1141 return (flags & Flags.ReadOnly) != 0;
1145 public void SetReadOnlyContext (ReadOnlyContext context)
1147 flags |= Flags.ReadOnly;
1148 ro_context = context;
1151 public string GetReadOnlyContext ()
1154 throw new InternalErrorException ("Variable is not readonly");
1156 switch (ro_context) {
1157 case ReadOnlyContext.Fixed:
1158 return "fixed variable";
1159 case ReadOnlyContext.Foreach:
1160 return "foreach iteration variable";
1161 case ReadOnlyContext.Using:
1162 return "using variable";
1164 throw new NotImplementedException ();
1168 // Whether the variable is pinned, if Pinned the variable has been
1169 // allocated in a pinned slot with DeclareLocal.
1171 public bool Pinned {
1173 return (flags & Flags.Pinned) != 0;
1176 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1180 public bool IsThis {
1182 return (flags & Flags.IsThis) != 0;
1185 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1191 /// Block represents a C# block.
1195 /// This class is used in a number of places: either to represent
1196 /// explicit blocks that the programmer places or implicit blocks.
1198 /// Implicit blocks are used as labels or to introduce variable
1201 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1202 /// they contain extra information that is not necessary on normal blocks.
1204 public class Block : Statement {
1205 public Block Parent;
1206 public readonly Location StartLocation;
1207 public Location EndLocation = Location.Null;
1209 public readonly ToplevelBlock Toplevel;
1212 public enum Flags : ushort {
1216 VariablesInitialized = 8,
1221 HasVarargs = 256 // Used in ToplevelBlock
1223 protected Flags flags;
1225 public bool Implicit {
1226 get { return (flags & Flags.Implicit) != 0; }
1229 public bool Unchecked {
1230 get { return (flags & Flags.Unchecked) != 0; }
1231 set { flags |= Flags.Unchecked; }
1234 public bool Unsafe {
1235 get { return (flags & Flags.Unsafe) != 0; }
1236 set { flags |= Flags.Unsafe; }
1240 // The statements in this block
1242 ArrayList statements;
1246 // An array of Blocks. We keep track of children just
1247 // to generate the local variable declarations.
1249 // Statements and child statements are handled through the
1255 // Labels. (label, block) pairs.
1260 // Keeps track of (name, type) pairs
1262 IDictionary variables;
1265 // Keeps track of constants
1266 Hashtable constants;
1269 // Temporary variables.
1271 ArrayList temporary_variables;
1274 // If this is a switch section, the enclosing switch block.
1278 protected static int id;
1282 public Block (Block parent)
1283 : this (parent, (Flags) 0, Location.Null, Location.Null)
1286 public Block (Block parent, Flags flags)
1287 : this (parent, flags, Location.Null, Location.Null)
1290 public Block (Block parent, Location start, Location end)
1291 : this (parent, (Flags) 0, start, end)
1294 public Block (Block parent, Flags flags, Location start, Location end)
1297 parent.AddChild (this);
1299 this.Parent = parent;
1301 this.StartLocation = start;
1302 this.EndLocation = end;
1305 statements = new ArrayList ();
1307 if ((flags & Flags.IsToplevel) != 0)
1308 Toplevel = (ToplevelBlock) this;
1310 Toplevel = parent.Toplevel;
1312 if (parent != null && Implicit) {
1313 if (parent.known_variables == null)
1314 parent.known_variables = new Hashtable ();
1315 // share with parent
1316 known_variables = parent.known_variables;
1320 public Block CreateSwitchBlock (Location start)
1322 Block new_block = new Block (this, start, start);
1323 new_block.switch_block = this;
1328 get { return this_id; }
1331 public IDictionary Variables {
1333 if (variables == null)
1334 variables = new ListDictionary ();
1339 void AddChild (Block b)
1341 if (children == null)
1342 children = new ArrayList ();
1347 public void SetEndLocation (Location loc)
1353 /// Adds a label to the current block.
1357 /// false if the name already exists in this block. true
1361 public bool AddLabel (LabeledStatement target)
1363 if (switch_block != null)
1364 return switch_block.AddLabel (target);
1366 string name = target.Name;
1369 while (cur != null) {
1370 if (cur.DoLookupLabel (name) != null) {
1371 Report.Error (140, target.loc, "The label `{0}' is a duplicate", name);
1381 while (cur != null) {
1382 if (cur.DoLookupLabel (name) != null) {
1385 "The label `{0}' shadows another label by the same name in a contained scope.",
1390 if (children != null) {
1391 foreach (Block b in children) {
1392 LabeledStatement s = b.DoLookupLabel (name);
1398 "The label `{0}' shadows another label by the same name in a contained scope.",
1409 labels = new Hashtable ();
1411 labels.Add (name, target);
1415 public LabeledStatement LookupLabel (string name)
1417 LabeledStatement s = DoLookupLabel (name);
1421 if (children == null)
1424 foreach (Block child in children) {
1425 if (!child.Implicit)
1428 s = child.LookupLabel (name);
1436 LabeledStatement DoLookupLabel (string name)
1438 if (switch_block != null)
1439 return switch_block.LookupLabel (name);
1442 if (labels.Contains (name))
1443 return ((LabeledStatement) labels [name]);
1448 Hashtable known_variables;
1451 // Marks a variable with name @name as being used in this or a child block.
1452 // If a variable name has been used in a child block, it's illegal to
1453 // declare a variable with the same name in the current block.
1455 void AddKnownVariable (string name, LocalInfo info)
1457 if (known_variables == null)
1458 known_variables = new Hashtable ();
1460 known_variables [name] = info;
1463 LocalInfo GetKnownVariableInfo (string name)
1465 if (known_variables == null)
1467 return (LocalInfo) known_variables [name];
1470 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1473 LocalInfo kvi = b.GetKnownVariableInfo (name);
1474 while (kvi == null) {
1480 kvi = b.GetKnownVariableInfo (name);
1486 // Is kvi.Block nested inside 'b'
1487 if (b.known_variables != kvi.Block.known_variables) {
1489 // If a variable by the same name it defined in a nested block of this
1490 // block, we violate the invariant meaning in a block.
1493 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1494 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1499 // It's ok if the definition is in a nested subblock of b, but not
1500 // nested inside this block -- a definition in a sibling block
1501 // should not affect us.
1507 // Block 'b' and kvi.Block are the same textual block.
1508 // However, different variables are extant.
1510 // Check if the variable is in scope in both blocks. We use
1511 // an indirect check that depends on AddVariable doing its
1512 // part in maintaining the invariant-meaning-in-block property.
1514 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1518 // Even though we detected the error when the name is used, we
1519 // treat it as if the variable declaration was in error.
1521 Report.SymbolRelatedToPreviousError (loc, name);
1522 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1526 public LocalInfo AddVariable (Expression type, string name, Location l)
1528 LocalInfo vi = GetLocalInfo (name);
1530 Report.SymbolRelatedToPreviousError (vi.Location, name);
1531 if (known_variables == vi.Block.known_variables)
1532 Report.Error (128, l,
1533 "A local variable named `{0}' is already defined in this scope", name);
1535 Error_AlreadyDeclared (l, name, "parent");
1539 vi = GetKnownVariableInfo (name);
1541 Report.SymbolRelatedToPreviousError (vi.Location, name);
1542 Error_AlreadyDeclared (l, name, "child");
1547 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1549 Report.SymbolRelatedToPreviousError (p.Location, name);
1550 Error_AlreadyDeclared (l, name, "method argument");
1554 vi = new LocalInfo (type, name, this, l);
1556 Variables.Add (name, vi);
1558 for (Block b = this; b != null; b = b.Parent)
1559 b.AddKnownVariable (name, vi);
1561 if ((flags & Flags.VariablesInitialized) != 0)
1562 throw new Exception ();
1567 void Error_AlreadyDeclared (Location loc, string var, string reason)
1569 Report.Error (136, loc, "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning to `{0}', " +
1570 "which is already used in a `{1}' scope to denote something else", var, reason);
1573 public bool AddConstant (Expression type, string name, Expression value, Location l)
1575 if (AddVariable (type, name, l) == null)
1578 if (constants == null)
1579 constants = new Hashtable ();
1581 constants.Add (name, value);
1583 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1588 static int next_temp_id = 0;
1590 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1592 if (temporary_variables == null)
1593 temporary_variables = new ArrayList ();
1595 int id = ++next_temp_id;
1596 string name = "$s_" + id.ToString ();
1598 LocalInfo li = new LocalInfo (te, name, this, loc);
1599 li.CompilerGenerated = true;
1600 temporary_variables.Add (li);
1604 public LocalInfo GetLocalInfo (string name)
1606 for (Block b = this; b != null; b = b.Parent) {
1607 if (b.variables != null) {
1608 LocalInfo ret = b.variables [name] as LocalInfo;
1616 public Expression GetVariableType (string name)
1618 LocalInfo vi = GetLocalInfo (name);
1619 return vi == null ? null : vi.Type;
1622 public Expression GetConstantExpression (string name)
1624 for (Block b = this; b != null; b = b.Parent) {
1625 if (b.constants != null) {
1626 Expression ret = b.constants [name] as Expression;
1634 public void AddStatement (Statement s)
1637 flags |= Flags.BlockUsed;
1641 get { return (flags & Flags.BlockUsed) != 0; }
1646 flags |= Flags.BlockUsed;
1649 public bool HasRet {
1650 get { return (flags & Flags.HasRet) != 0; }
1653 public bool IsDestructor {
1654 get { return (flags & Flags.IsDestructor) != 0; }
1657 public void SetDestructor ()
1659 flags |= Flags.IsDestructor;
1662 VariableMap param_map, local_map;
1664 public VariableMap ParameterMap {
1666 if ((flags & Flags.VariablesInitialized) == 0)
1667 throw new Exception ("Variables have not been initialized yet");
1673 public VariableMap LocalMap {
1675 if ((flags & Flags.VariablesInitialized) == 0)
1676 throw new Exception ("Variables have not been initialized yet");
1683 /// Emits the variable declarations and labels.
1686 /// tc: is our typecontainer (to resolve type references)
1687 /// ig: is the code generator:
1689 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
1691 // If some parent block was unsafe, we remain unsafe even if this block
1692 // isn't explicitly marked as such.
1693 using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
1695 // Compute the VariableMap's.
1697 // Unfortunately, we don't know the type when adding variables with
1698 // AddVariable(), so we need to compute this info here.
1702 if (variables != null) {
1703 foreach (LocalInfo li in variables.Values)
1706 locals = new LocalInfo [variables.Count];
1707 variables.Values.CopyTo (locals, 0);
1709 locals = new LocalInfo [0];
1712 local_map = new VariableMap (Parent.LocalMap, locals);
1714 local_map = new VariableMap (locals);
1716 param_map = new VariableMap (ip);
1717 flags |= Flags.VariablesInitialized;
1720 // Process this block variables
1722 if (variables != null) {
1723 foreach (DictionaryEntry de in variables) {
1724 string name = (string) de.Key;
1725 LocalInfo vi = (LocalInfo) de.Value;
1726 Type variable_type = vi.VariableType;
1728 if (variable_type == null)
1731 if (variable_type.IsPointer) {
1733 // Am not really convinced that this test is required (Microsoft does it)
1734 // but the fact is that you would not be able to use the pointer variable
1737 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1742 if (constants == null)
1745 Expression cv = (Expression) constants [name];
1749 // Don't let 'const int Foo = Foo;' succeed.
1750 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
1751 // which in turn causes the 'must be constant' error to be triggered.
1752 constants.Remove (name);
1754 if (!Const.IsConstantTypeValid (variable_type)) {
1755 Const.Error_InvalidConstantType (variable_type, loc);
1759 using (ec.With (EmitContext.Flags.ConstantCheckState, (flags & Flags.Unchecked) == 0)) {
1760 ec.CurrentBlock = this;
1761 Expression e = cv.Resolve (ec);
1765 Constant ce = e as Constant;
1767 Const.Error_ExpressionMustBeConstant (vi.Location, name);
1771 e = ce.ImplicitConversionRequired (variable_type, vi.Location);
1775 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue) {
1776 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
1780 constants.Add (name, e);
1781 vi.IsConstant = true;
1787 // Now, handle the children
1789 if (children != null) {
1790 foreach (Block b in children)
1791 b.ResolveMeta (toplevel, ec, ip);
1797 // Emits the local variable declarations for a block
1799 public void EmitMeta (EmitContext ec)
1801 ILGenerator ig = ec.ig;
1803 if (variables != null){
1804 bool have_captured_vars = ec.HaveCapturedVariables ();
1806 foreach (DictionaryEntry de in variables){
1807 LocalInfo vi = (LocalInfo) de.Value;
1809 if (have_captured_vars && ec.IsCaptured (vi))
1812 vi.DeclareLocal (ig);
1816 if (temporary_variables != null) {
1817 AnonymousContainer am = ec.CurrentAnonymousMethod;
1818 TypeBuilder scope = null;
1819 if ((am != null) && am.IsIterator) {
1820 scope = am.Scope.ScopeTypeBuilder;
1822 throw new InternalErrorException ();
1824 foreach (LocalInfo vi in temporary_variables) {
1825 if (scope != null) {
1826 if (vi.FieldBuilder == null)
1827 vi.FieldBuilder = scope.DefineField (
1828 vi.Name, vi.VariableType, FieldAttributes.Assembly);
1830 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1834 if (children != null){
1835 foreach (Block b in children)
1840 void UsageWarning (FlowBranching.UsageVector vector)
1844 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1845 foreach (DictionaryEntry de in variables){
1846 LocalInfo vi = (LocalInfo) de.Value;
1851 name = (string) de.Key;
1853 // vi.VariableInfo can be null for 'catch' variables
1854 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
1855 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
1857 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
1863 bool unreachable_shown;
1866 private void CheckPossibleMistakenEmptyStatement (Statement s)
1870 // Some statements are wrapped by a Block. Since
1871 // others' internal could be changed, here I treat
1872 // them as possibly wrapped by Block equally.
1873 Block b = s as Block;
1874 if (b != null && b.statements.Count == 1)
1875 s = (Statement) b.statements [0];
1878 body = ((Lock) s).Statement;
1880 body = ((For) s).Statement;
1881 else if (s is Foreach)
1882 body = ((Foreach) s).Statement;
1883 else if (s is While)
1884 body = ((While) s).Statement;
1885 else if (s is Using)
1886 body = ((Using) s).Statement;
1887 else if (s is Fixed)
1888 body = ((Fixed) s).Statement;
1892 if (body == null || body is EmptyStatement)
1893 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
1896 public override bool Resolve (EmitContext ec)
1898 Block prev_block = ec.CurrentBlock;
1901 int errors = Report.Errors;
1903 ec.CurrentBlock = this;
1904 ec.StartFlowBranching (this);
1906 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1909 // This flag is used to notate nested statements as unreachable from the beginning of this block.
1910 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
1911 // from the beginning of the function. The outer Resolve() that detected the unreachability is
1912 // responsible for handling the situation.
1914 int statement_count = statements.Count;
1915 for (int ix = 0; ix < statement_count; ix++){
1916 Statement s = (Statement) statements [ix];
1917 // Check possible empty statement (CS0642)
1918 if (RootContext.WarningLevel >= 3 &&
1919 ix + 1 < statement_count &&
1920 statements [ix + 1] is Block)
1921 CheckPossibleMistakenEmptyStatement (s);
1924 // Warn if we detect unreachable code.
1927 if (s is EmptyStatement)
1931 ((Block) s).unreachable = true;
1933 if (!unreachable_shown && !(s is LabeledStatement)) {
1934 Report.Warning (162, 2, s.loc, "Unreachable code detected");
1935 unreachable_shown = true;
1940 // Note that we're not using ResolveUnreachable() for unreachable
1941 // statements here. ResolveUnreachable() creates a temporary
1942 // flow branching and kills it afterwards. This leads to problems
1943 // if you have two unreachable statements where the first one
1944 // assigns a variable and the second one tries to access it.
1947 if (!s.Resolve (ec)) {
1949 statements [ix] = EmptyStatement.Value;
1953 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1954 statements [ix] = EmptyStatement.Value;
1956 num_statements = ix + 1;
1958 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1959 if (unreachable && s is LabeledStatement)
1960 throw new InternalErrorException ("should not happen");
1963 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1964 ec.CurrentBranching, statement_count, num_statements);
1966 while (ec.CurrentBranching is FlowBranchingLabeled)
1967 ec.EndFlowBranching ();
1969 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1971 ec.CurrentBlock = prev_block;
1973 // If we're a non-static `struct' constructor which doesn't have an
1974 // initializer, then we must initialize all of the struct's fields.
1975 if ((flags & Flags.IsToplevel) != 0 &&
1976 !Toplevel.IsThisAssigned (ec) &&
1977 !vector.Reachability.AlwaysThrows)
1980 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1981 foreach (LabeledStatement label in labels.Values)
1982 if (!label.HasBeenReferenced)
1983 Report.Warning (164, 2, label.loc,
1984 "This label has not been referenced");
1987 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1989 if (vector.Reachability.IsUnreachable)
1990 flags |= Flags.HasRet;
1992 if (ok && (errors == Report.Errors)) {
1993 if (RootContext.WarningLevel >= 3)
1994 UsageWarning (vector);
2000 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2002 unreachable_shown = true;
2006 Report.Warning (162, 2, loc, "Unreachable code detected");
2008 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2009 bool ok = Resolve (ec);
2010 ec.KillFlowBranching ();
2015 protected override void DoEmit (EmitContext ec)
2017 for (int ix = 0; ix < num_statements; ix++){
2018 Statement s = (Statement) statements [ix];
2020 // Check whether we are the last statement in a
2023 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2024 ec.IsLastStatement = true;
2026 ec.IsLastStatement = false;
2032 public override void Emit (EmitContext ec)
2034 Block prev_block = ec.CurrentBlock;
2036 ec.CurrentBlock = this;
2038 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2039 bool is_lexical_block = !Implicit && (Parent != null);
2041 if (emit_debug_info) {
2042 if (is_lexical_block)
2045 if (variables != null) {
2046 foreach (DictionaryEntry de in variables) {
2047 string name = (string) de.Key;
2048 LocalInfo vi = (LocalInfo) de.Value;
2050 if (vi.LocalBuilder == null)
2053 ec.DefineLocalVariable (name, vi.LocalBuilder);
2057 ec.Mark (StartLocation, true);
2058 ec.EmitScopeInitFromBlock (this);
2060 ec.Mark (EndLocation, true);
2062 if (emit_debug_info && is_lexical_block)
2065 ec.CurrentBlock = prev_block;
2069 // Returns true if we ar ea child of `b'.
2071 public bool IsChildOf (Block b)
2073 Block current = this;
2076 if (current.Parent == b)
2078 current = current.Parent;
2079 } while (current != null);
2083 public override string ToString ()
2085 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2090 // A toplevel block contains extra information, the split is done
2091 // only to separate information that would otherwise bloat the more
2092 // lightweight Block.
2094 // In particular, this was introduced when the support for Anonymous
2095 // Methods was implemented.
2097 public class ToplevelBlock : Block {
2099 // Pointer to the host of this anonymous method, or null
2100 // if we are the topmost block
2102 ToplevelBlock container;
2103 CaptureContext capture_context;
2104 FlowBranchingToplevel top_level_branching;
2106 Hashtable capture_contexts;
2109 public bool HasVarargs {
2110 get { return (flags & Flags.HasVarargs) != 0; }
2111 set { flags |= Flags.HasVarargs; }
2115 // The parameters for the block.
2117 Parameters parameters;
2118 public Parameters Parameters {
2119 get { return parameters; }
2122 public void RegisterCaptureContext (CaptureContext cc)
2124 if (capture_contexts == null)
2125 capture_contexts = new Hashtable ();
2126 capture_contexts [cc] = cc;
2129 public void CompleteContexts ()
2131 if (capture_contexts == null)
2134 foreach (CaptureContext cc in capture_contexts.Keys){
2139 public CaptureContext ToplevelBlockCaptureContext {
2140 get { return capture_context; }
2143 public ToplevelBlock Container {
2144 get { return container; }
2147 protected void AddChild (ToplevelBlock block)
2149 if (children == null)
2150 children = new ArrayList ();
2152 children.Add (block);
2156 // Parent is only used by anonymous blocks to link back to their
2159 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2160 this (container, (Flags) 0, parameters, start)
2164 public ToplevelBlock (Parameters parameters, Location start) :
2165 this (null, (Flags) 0, parameters, start)
2169 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2170 this (null, flags, parameters, start)
2174 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2175 base (null, flags | Flags.IsToplevel, start, Location.Null)
2177 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2178 this.container = container;
2180 if (container != null)
2181 container.AddChild (this);
2184 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2188 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2190 if (capture_context == null)
2191 capture_context = new CaptureContext (this, loc, host);
2194 public CaptureContext CaptureContext {
2195 get { return capture_context; }
2198 public FlowBranchingToplevel TopLevelBranching {
2199 get { return top_level_branching; }
2203 // This is used if anonymous methods are used inside an iterator
2204 // (see 2test-22.cs for an example).
2206 // The AnonymousMethod is created while parsing - at a time when we don't
2207 // know yet that we're inside an iterator, so it's `Container' is initially
2208 // null. Later on, when resolving the iterator, we need to move the
2209 // anonymous method into that iterator.
2211 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2213 foreach (ToplevelBlock block in children) {
2214 if (block.CaptureContext == null)
2217 block.container = new_parent;
2218 block.CaptureContext.ReParent (new_parent, new_host);
2223 // Returns a `ParameterReference' for the given name, or null if there
2224 // is no such parameter
2226 public ParameterReference GetParameterReference (string name, Location loc)
2231 for (ToplevelBlock t = this; t != null; t = t.Container) {
2232 Parameters pars = t.Parameters;
2233 par = pars.GetParameterByName (name, out idx);
2235 return new ParameterReference (par, this, idx, loc);
2241 // Whether the parameter named `name' is local to this block,
2242 // or false, if the parameter belongs to an encompassing block.
2244 public bool IsLocalParameter (string name)
2246 return Parameters.GetParameterByName (name) != null;
2250 // Whether the `name' is a parameter reference
2252 public bool IsParameterReference (string name)
2254 for (ToplevelBlock t = this; t != null; t = t.Container) {
2255 if (t.IsLocalParameter (name))
2261 LocalInfo this_variable = null;
2264 // Returns the "this" instance variable of this block.
2265 // See AddThisVariable() for more information.
2267 public LocalInfo ThisVariable {
2268 get { return this_variable; }
2273 // This is used by non-static `struct' constructors which do not have an
2274 // initializer - in this case, the constructor must initialize all of the
2275 // struct's fields. To do this, we add a "this" variable and use the flow
2276 // analysis code to ensure that it's been fully initialized before control
2277 // leaves the constructor.
2279 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2281 if (this_variable == null) {
2282 this_variable = new LocalInfo (ds, this, l);
2283 this_variable.Used = true;
2284 this_variable.IsThis = true;
2286 Variables.Add ("this", this_variable);
2289 return this_variable;
2292 public bool IsThisAssigned (EmitContext ec)
2294 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2297 public bool ResolveMeta (EmitContext ec, Parameters ip)
2299 int errors = Report.Errors;
2301 if (top_level_branching != null)
2307 ResolveMeta (this, ec, ip);
2309 top_level_branching = ec.StartFlowBranching (this);
2311 return Report.Errors == errors;
2315 public class SwitchLabel {
2322 Label il_label_code;
2323 bool il_label_code_set;
2325 public static readonly object NullStringCase = new object ();
2328 // if expr == null, then it is the default case.
2330 public SwitchLabel (Expression expr, Location l)
2336 public Expression Label {
2342 public object Converted {
2348 public Label GetILLabel (EmitContext ec)
2351 il_label = ec.ig.DefineLabel ();
2352 il_label_set = true;
2357 public Label GetILLabelCode (EmitContext ec)
2359 if (!il_label_code_set){
2360 il_label_code = ec.ig.DefineLabel ();
2361 il_label_code_set = true;
2363 return il_label_code;
2367 // Resolves the expression, reduces it to a literal if possible
2368 // and then converts it to the requested type.
2370 public bool ResolveAndReduce (EmitContext ec, Type required_type, bool allow_nullable)
2372 Expression e = label.Resolve (ec);
2377 Constant c = e as Constant;
2379 Report.Error (150, loc, "A constant value is expected");
2383 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2384 converted = NullStringCase;
2388 if (allow_nullable && c.GetValue () == null) {
2389 converted = NullStringCase;
2393 c = c.ImplicitConversionRequired (required_type, loc);
2397 converted = c.GetValue ();
2401 public void Erorr_AlreadyOccurs ()
2404 if (converted == null)
2406 else if (converted == NullStringCase)
2409 label = converted.ToString ();
2411 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2415 public class SwitchSection {
2416 // An array of SwitchLabels.
2417 public readonly ArrayList Labels;
2418 public readonly Block Block;
2420 public SwitchSection (ArrayList labels, Block block)
2427 public class Switch : Statement {
2428 public readonly ArrayList Sections;
2429 public Expression Expr;
2432 /// Maps constants whose type type SwitchType to their SwitchLabels.
2434 public IDictionary Elements;
2437 /// The governing switch type
2439 public Type SwitchType;
2444 Label default_target;
2446 Expression new_expr;
2448 SwitchSection constant_section;
2449 SwitchSection default_section;
2453 // Nullable Types support for GMCS.
2455 Nullable.Unwrap unwrap;
2457 protected bool HaveUnwrap {
2458 get { return unwrap != null; }
2461 protected bool HaveUnwrap {
2462 get { return false; }
2467 // The types allowed to be implicitly cast from
2468 // on the governing type
2470 static Type [] allowed_types;
2472 public Switch (Expression e, ArrayList sects, Location l)
2479 public bool GotDefault {
2481 return default_section != null;
2485 public Label DefaultTarget {
2487 return default_target;
2492 // Determines the governing type for a switch. The returned
2493 // expression might be the expression from the switch, or an
2494 // expression that includes any potential conversions to the
2495 // integral types or to string.
2497 Expression SwitchGoverningType (EmitContext ec, Expression expr)
2501 if (t == TypeManager.byte_type ||
2502 t == TypeManager.sbyte_type ||
2503 t == TypeManager.ushort_type ||
2504 t == TypeManager.short_type ||
2505 t == TypeManager.uint32_type ||
2506 t == TypeManager.int32_type ||
2507 t == TypeManager.uint64_type ||
2508 t == TypeManager.int64_type ||
2509 t == TypeManager.char_type ||
2510 t == TypeManager.string_type ||
2511 t == TypeManager.bool_type ||
2512 t.IsSubclassOf (TypeManager.enum_type))
2515 if (allowed_types == null){
2516 allowed_types = new Type [] {
2517 TypeManager.sbyte_type,
2518 TypeManager.byte_type,
2519 TypeManager.short_type,
2520 TypeManager.ushort_type,
2521 TypeManager.int32_type,
2522 TypeManager.uint32_type,
2523 TypeManager.int64_type,
2524 TypeManager.uint64_type,
2525 TypeManager.char_type,
2526 TypeManager.string_type,
2527 TypeManager.bool_type
2532 // Try to find a *user* defined implicit conversion.
2534 // If there is no implicit conversion, or if there are multiple
2535 // conversions, we have to report an error
2537 Expression converted = null;
2538 foreach (Type tt in allowed_types){
2541 e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
2546 // Ignore over-worked ImplicitUserConversions that do
2547 // an implicit conversion in addition to the user conversion.
2549 if (!(e is UserCast))
2552 if (converted != null){
2553 Report.ExtraInformation (
2555 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2556 TypeManager.CSharpName (expr.Type)));
2566 // Performs the basic sanity checks on the switch statement
2567 // (looks for duplicate keys and non-constant expressions).
2569 // It also returns a hashtable with the keys that we will later
2570 // use to compute the switch tables
2572 bool CheckSwitch (EmitContext ec)
2575 Elements = Sections.Count > 10 ?
2576 (IDictionary)new Hashtable () :
2577 (IDictionary)new ListDictionary ();
2579 foreach (SwitchSection ss in Sections){
2580 foreach (SwitchLabel sl in ss.Labels){
2581 if (sl.Label == null){
2582 if (default_section != null){
2583 sl.Erorr_AlreadyOccurs ();
2586 default_section = ss;
2590 if (!sl.ResolveAndReduce (ec, SwitchType, HaveUnwrap)) {
2595 object key = sl.Converted;
2597 Elements.Add (key, sl);
2598 } catch (ArgumentException) {
2599 sl.Erorr_AlreadyOccurs ();
2607 void EmitObjectInteger (ILGenerator ig, object k)
2610 IntConstant.EmitInt (ig, (int) k);
2611 else if (k is Constant) {
2612 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2615 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2618 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2620 IntConstant.EmitInt (ig, (int) (long) k);
2621 ig.Emit (OpCodes.Conv_I8);
2624 LongConstant.EmitLong (ig, (long) k);
2626 else if (k is ulong)
2628 ulong ul = (ulong) k;
2631 IntConstant.EmitInt (ig, unchecked ((int) ul));
2632 ig.Emit (OpCodes.Conv_U8);
2636 LongConstant.EmitLong (ig, unchecked ((long) ul));
2640 IntConstant.EmitInt (ig, (int) ((char) k));
2641 else if (k is sbyte)
2642 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2644 IntConstant.EmitInt (ig, (int) ((byte) k));
2645 else if (k is short)
2646 IntConstant.EmitInt (ig, (int) ((short) k));
2647 else if (k is ushort)
2648 IntConstant.EmitInt (ig, (int) ((ushort) k));
2650 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2652 throw new Exception ("Unhandled case");
2655 // structure used to hold blocks of keys while calculating table switch
2656 class KeyBlock : IComparable
2658 public KeyBlock (long _nFirst)
2660 nFirst = nLast = _nFirst;
2664 public ArrayList rgKeys = null;
2665 // how many items are in the bucket
2666 public int Size = 1;
2669 get { return (int) (nLast - nFirst + 1); }
2671 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2673 return kbLast.nLast - kbFirst.nFirst + 1;
2675 public int CompareTo (object obj)
2677 KeyBlock kb = (KeyBlock) obj;
2678 int nLength = Length;
2679 int nLengthOther = kb.Length;
2680 if (nLengthOther == nLength)
2681 return (int) (kb.nFirst - nFirst);
2682 return nLength - nLengthOther;
2687 /// This method emits code for a lookup-based switch statement (non-string)
2688 /// Basically it groups the cases into blocks that are at least half full,
2689 /// and then spits out individual lookup opcodes for each block.
2690 /// It emits the longest blocks first, and short blocks are just
2691 /// handled with direct compares.
2693 /// <param name="ec"></param>
2694 /// <param name="val"></param>
2695 /// <returns></returns>
2696 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2698 int cElements = Elements.Count;
2699 object [] rgKeys = new object [cElements];
2700 Elements.Keys.CopyTo (rgKeys, 0);
2701 Array.Sort (rgKeys);
2703 // initialize the block list with one element per key
2704 ArrayList rgKeyBlocks = new ArrayList ();
2705 foreach (object key in rgKeys)
2706 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2709 // iteratively merge the blocks while they are at least half full
2710 // there's probably a really cool way to do this with a tree...
2711 while (rgKeyBlocks.Count > 1)
2713 ArrayList rgKeyBlocksNew = new ArrayList ();
2714 kbCurr = (KeyBlock) rgKeyBlocks [0];
2715 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2717 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2718 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2721 kbCurr.nLast = kb.nLast;
2722 kbCurr.Size += kb.Size;
2726 // start a new block
2727 rgKeyBlocksNew.Add (kbCurr);
2731 rgKeyBlocksNew.Add (kbCurr);
2732 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2734 rgKeyBlocks = rgKeyBlocksNew;
2737 // initialize the key lists
2738 foreach (KeyBlock kb in rgKeyBlocks)
2739 kb.rgKeys = new ArrayList ();
2741 // fill the key lists
2743 if (rgKeyBlocks.Count > 0) {
2744 kbCurr = (KeyBlock) rgKeyBlocks [0];
2745 foreach (object key in rgKeys)
2747 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2748 System.Convert.ToInt64 (key) > kbCurr.nLast;
2750 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2751 kbCurr.rgKeys.Add (key);
2755 // sort the blocks so we can tackle the largest ones first
2756 rgKeyBlocks.Sort ();
2758 // okay now we can start...
2759 ILGenerator ig = ec.ig;
2760 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2761 Label lblDefault = ig.DefineLabel ();
2763 Type typeKeys = null;
2764 if (rgKeys.Length > 0)
2765 typeKeys = rgKeys [0].GetType (); // used for conversions
2769 if (TypeManager.IsEnumType (SwitchType))
2770 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2772 compare_type = SwitchType;
2774 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2776 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2777 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2780 foreach (object key in kb.rgKeys)
2782 ig.Emit (OpCodes.Ldloc, val);
2783 EmitObjectInteger (ig, key);
2784 SwitchLabel sl = (SwitchLabel) Elements [key];
2785 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2790 // TODO: if all the keys in the block are the same and there are
2791 // no gaps/defaults then just use a range-check.
2792 if (compare_type == TypeManager.int64_type ||
2793 compare_type == TypeManager.uint64_type)
2795 // TODO: optimize constant/I4 cases
2797 // check block range (could be > 2^31)
2798 ig.Emit (OpCodes.Ldloc, val);
2799 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2800 ig.Emit (OpCodes.Blt, lblDefault);
2801 ig.Emit (OpCodes.Ldloc, val);
2802 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2803 ig.Emit (OpCodes.Bgt, lblDefault);
2806 ig.Emit (OpCodes.Ldloc, val);
2809 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2810 ig.Emit (OpCodes.Sub);
2812 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2817 ig.Emit (OpCodes.Ldloc, val);
2818 int nFirst = (int) kb.nFirst;
2821 IntConstant.EmitInt (ig, nFirst);
2822 ig.Emit (OpCodes.Sub);
2824 else if (nFirst < 0)
2826 IntConstant.EmitInt (ig, -nFirst);
2827 ig.Emit (OpCodes.Add);
2831 // first, build the list of labels for the switch
2833 int cJumps = kb.Length;
2834 Label [] rgLabels = new Label [cJumps];
2835 for (int iJump = 0; iJump < cJumps; iJump++)
2837 object key = kb.rgKeys [iKey];
2838 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2840 SwitchLabel sl = (SwitchLabel) Elements [key];
2841 rgLabels [iJump] = sl.GetILLabel (ec);
2845 rgLabels [iJump] = lblDefault;
2847 // emit the switch opcode
2848 ig.Emit (OpCodes.Switch, rgLabels);
2851 // mark the default for this block
2853 ig.MarkLabel (lblDefault);
2856 // TODO: find the default case and emit it here,
2857 // to prevent having to do the following jump.
2858 // make sure to mark other labels in the default section
2860 // the last default just goes to the end
2861 ig.Emit (OpCodes.Br, lblDefault);
2863 // now emit the code for the sections
2864 bool fFoundDefault = false;
2865 bool fFoundNull = false;
2866 foreach (SwitchSection ss in Sections)
2868 foreach (SwitchLabel sl in ss.Labels)
2869 if (sl.Converted == SwitchLabel.NullStringCase)
2873 foreach (SwitchSection ss in Sections)
2875 foreach (SwitchLabel sl in ss.Labels)
2877 ig.MarkLabel (sl.GetILLabel (ec));
2878 ig.MarkLabel (sl.GetILLabelCode (ec));
2879 if (sl.Converted == SwitchLabel.NullStringCase)
2880 ig.MarkLabel (null_target);
2881 else if (sl.Label == null) {
2882 ig.MarkLabel (lblDefault);
2883 fFoundDefault = true;
2885 ig.MarkLabel (null_target);
2891 if (!fFoundDefault) {
2892 ig.MarkLabel (lblDefault);
2894 ig.MarkLabel (lblEnd);
2897 // This simple emit switch works, but does not take advantage of the
2899 // TODO: remove non-string logic from here
2900 // TODO: binary search strings?
2902 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2904 ILGenerator ig = ec.ig;
2905 Label end_of_switch = ig.DefineLabel ();
2906 Label next_test = ig.DefineLabel ();
2907 bool first_test = true;
2908 bool pending_goto_end = false;
2909 bool null_marked = false;
2912 ig.Emit (OpCodes.Ldloc, val);
2914 if (Elements.Contains (SwitchLabel.NullStringCase)){
2915 ig.Emit (OpCodes.Brfalse, null_target);
2917 ig.Emit (OpCodes.Brfalse, default_target);
2919 ig.Emit (OpCodes.Ldloc, val);
2920 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2921 ig.Emit (OpCodes.Stloc, val);
2923 int section_count = Sections.Count;
2924 for (int section = 0; section < section_count; section++){
2925 SwitchSection ss = (SwitchSection) Sections [section];
2927 if (ss == default_section)
2930 Label sec_begin = ig.DefineLabel ();
2932 ig.Emit (OpCodes.Nop);
2934 if (pending_goto_end)
2935 ig.Emit (OpCodes.Br, end_of_switch);
2937 int label_count = ss.Labels.Count;
2939 for (int label = 0; label < label_count; label++){
2940 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2941 ig.MarkLabel (sl.GetILLabel (ec));
2944 ig.MarkLabel (next_test);
2945 next_test = ig.DefineLabel ();
2948 // If we are the default target
2950 if (sl.Label != null){
2951 object lit = sl.Converted;
2953 if (lit == SwitchLabel.NullStringCase){
2955 if (label + 1 == label_count)
2956 ig.Emit (OpCodes.Br, next_test);
2960 ig.Emit (OpCodes.Ldloc, val);
2961 ig.Emit (OpCodes.Ldstr, (string)lit);
2962 if (label_count == 1)
2963 ig.Emit (OpCodes.Bne_Un, next_test);
2965 if (label+1 == label_count)
2966 ig.Emit (OpCodes.Bne_Un, next_test);
2968 ig.Emit (OpCodes.Beq, sec_begin);
2973 ig.MarkLabel (null_target);
2976 ig.MarkLabel (sec_begin);
2977 foreach (SwitchLabel sl in ss.Labels)
2978 ig.MarkLabel (sl.GetILLabelCode (ec));
2981 pending_goto_end = !ss.Block.HasRet;
2984 ig.MarkLabel (next_test);
2985 ig.MarkLabel (default_target);
2987 ig.MarkLabel (null_target);
2988 if (default_section != null)
2989 default_section.Block.Emit (ec);
2990 ig.MarkLabel (end_of_switch);
2993 SwitchSection FindSection (SwitchLabel label)
2995 foreach (SwitchSection ss in Sections){
2996 foreach (SwitchLabel sl in ss.Labels){
3005 public override bool Resolve (EmitContext ec)
3007 Expr = Expr.Resolve (ec);
3011 new_expr = SwitchGoverningType (ec, Expr);
3014 if ((new_expr == null) && TypeManager.IsNullableType (Expr.Type)) {
3015 unwrap = Nullable.Unwrap.Create (Expr, ec);
3019 new_expr = SwitchGoverningType (ec, unwrap);
3023 if (new_expr == null){
3024 Report.Error (151, loc, "A value of an integral type or string expected for switch");
3029 SwitchType = new_expr.Type;
3031 if (!CheckSwitch (ec))
3035 Elements.Remove (SwitchLabel.NullStringCase);
3037 Switch old_switch = ec.Switch;
3039 ec.Switch.SwitchType = SwitchType;
3041 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3042 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3044 is_constant = new_expr is Constant;
3046 object key = ((Constant) new_expr).GetValue ();
3047 SwitchLabel label = (SwitchLabel) Elements [key];
3049 constant_section = FindSection (label);
3050 if (constant_section == null)
3051 constant_section = default_section;
3055 foreach (SwitchSection ss in Sections){
3057 ec.CurrentBranching.CreateSibling (
3058 null, FlowBranching.SiblingType.SwitchSection);
3062 if (is_constant && (ss != constant_section)) {
3063 // If we're a constant switch, we're only emitting
3064 // one single section - mark all the others as
3066 ec.CurrentBranching.CurrentUsageVector.Goto ();
3067 if (!ss.Block.ResolveUnreachable (ec, true))
3070 if (!ss.Block.Resolve (ec))
3075 if (default_section == null)
3076 ec.CurrentBranching.CreateSibling (
3077 null, FlowBranching.SiblingType.SwitchSection);
3079 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3080 ec.Switch = old_switch;
3082 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3088 protected override void DoEmit (EmitContext ec)
3090 ILGenerator ig = ec.ig;
3092 default_target = ig.DefineLabel ();
3093 null_target = ig.DefineLabel ();
3095 // Store variable for comparission purposes
3098 value = ig.DeclareLocal (SwitchType);
3100 unwrap.EmitCheck (ec);
3101 ig.Emit (OpCodes.Brfalse, null_target);
3103 ig.Emit (OpCodes.Stloc, value);
3105 } else if (!is_constant) {
3106 value = ig.DeclareLocal (SwitchType);
3108 ig.Emit (OpCodes.Stloc, value);
3113 // Setup the codegen context
3115 Label old_end = ec.LoopEnd;
3116 Switch old_switch = ec.Switch;
3118 ec.LoopEnd = ig.DefineLabel ();
3123 if (constant_section != null)
3124 constant_section.Block.Emit (ec);
3125 } else if (SwitchType == TypeManager.string_type)
3126 SimpleSwitchEmit (ec, value);
3128 TableSwitchEmit (ec, value);
3130 // Restore context state.
3131 ig.MarkLabel (ec.LoopEnd);
3134 // Restore the previous context
3136 ec.LoopEnd = old_end;
3137 ec.Switch = old_switch;
3141 public abstract class ExceptionStatement : Statement
3143 public abstract void EmitFinally (EmitContext ec);
3145 protected bool emit_finally = true;
3146 ArrayList parent_vectors;
3148 protected void DoEmitFinally (EmitContext ec)
3151 ec.ig.BeginFinallyBlock ();
3152 else if (ec.InIterator)
3153 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3157 protected void ResolveFinally (FlowBranchingException branching)
3159 emit_finally = branching.EmitFinally;
3161 branching.Parent.StealFinallyClauses (ref parent_vectors);
3165 public class Lock : ExceptionStatement {
3167 public Statement Statement;
3168 TemporaryVariable temp;
3170 public Lock (Expression expr, Statement stmt, Location l)
3177 public override bool Resolve (EmitContext ec)
3179 expr = expr.Resolve (ec);
3183 if (expr.Type.IsValueType){
3184 Report.Error (185, loc,
3185 "`{0}' is not a reference type as required by the lock statement",
3186 TypeManager.CSharpName (expr.Type));
3190 FlowBranchingException branching = ec.StartFlowBranching (this);
3191 bool ok = Statement.Resolve (ec);
3193 ec.KillFlowBranching ();
3197 ResolveFinally (branching);
3199 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3200 if (!reachability.AlwaysReturns) {
3201 // Unfortunately, System.Reflection.Emit automatically emits
3202 // a leave to the end of the finally block.
3203 // This is a problem if `returns' is true since we may jump
3204 // to a point after the end of the method.
3205 // As a workaround, emit an explicit ret here.
3206 ec.NeedReturnLabel ();
3209 // Avoid creating libraries that reference the internal
3212 if (t == TypeManager.null_type)
3213 t = TypeManager.object_type;
3215 temp = new TemporaryVariable (t, loc);
3221 protected override void DoEmit (EmitContext ec)
3223 ILGenerator ig = ec.ig;
3225 temp.Store (ec, expr);
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)
3243 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3247 public class Unchecked : Statement {
3248 public readonly Block Block;
3250 public Unchecked (Block b)
3256 public override bool Resolve (EmitContext ec)
3258 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3259 return Block.Resolve (ec);
3262 protected override void DoEmit (EmitContext ec)
3264 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3269 public class Checked : Statement {
3270 public readonly Block Block;
3272 public Checked (Block b)
3275 b.Unchecked = false;
3278 public override bool Resolve (EmitContext ec)
3280 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3281 return Block.Resolve (ec);
3284 protected override void DoEmit (EmitContext ec)
3286 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3291 public class Unsafe : Statement {
3292 public readonly Block Block;
3294 public Unsafe (Block b)
3297 Block.Unsafe = true;
3300 public override bool Resolve (EmitContext ec)
3302 using (ec.With (EmitContext.Flags.InUnsafe, true))
3303 return Block.Resolve (ec);
3306 protected override void DoEmit (EmitContext ec)
3308 using (ec.With (EmitContext.Flags.InUnsafe, true))
3316 public class Fixed : Statement {
3318 ArrayList declarators;
3319 Statement statement;
3324 abstract class Emitter
3326 protected LocalInfo vi;
3327 protected Expression converted;
3329 protected Emitter (Expression expr, LocalInfo li)
3335 public abstract void Emit (EmitContext ec);
3336 public abstract void EmitExit (ILGenerator ig);
3339 class ExpressionEmitter : Emitter {
3340 public ExpressionEmitter (Expression converted, LocalInfo li) :
3341 base (converted, li)
3345 public override void Emit (EmitContext ec) {
3347 // Store pointer in pinned location
3349 converted.Emit (ec);
3350 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3353 public override void EmitExit (ILGenerator ig)
3355 ig.Emit (OpCodes.Ldc_I4_0);
3356 ig.Emit (OpCodes.Conv_U);
3357 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3361 class StringEmitter : Emitter {
3362 LocalBuilder pinned_string;
3365 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3371 public override void Emit (EmitContext ec)
3373 ILGenerator ig = ec.ig;
3374 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3376 converted.Emit (ec);
3377 ig.Emit (OpCodes.Stloc, pinned_string);
3379 Expression sptr = new StringPtr (pinned_string, loc);
3380 converted = Convert.ImplicitConversionRequired (
3381 ec, sptr, vi.VariableType, loc);
3383 if (converted == null)
3386 converted.Emit (ec);
3387 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3390 public override void EmitExit(ILGenerator ig)
3392 ig.Emit (OpCodes.Ldnull);
3393 ig.Emit (OpCodes.Stloc, pinned_string);
3397 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3400 declarators = decls;
3405 public Statement Statement {
3406 get { return statement; }
3409 public override bool Resolve (EmitContext ec)
3412 Expression.UnsafeError (loc);
3416 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3420 expr_type = texpr.Type;
3422 data = new Emitter [declarators.Count];
3424 if (!expr_type.IsPointer){
3425 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3430 foreach (Pair p in declarators){
3431 LocalInfo vi = (LocalInfo) p.First;
3432 Expression e = (Expression) p.Second;
3434 vi.VariableInfo.SetAssigned (ec);
3435 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3438 // The rules for the possible declarators are pretty wise,
3439 // but the production on the grammar is more concise.
3441 // So we have to enforce these rules here.
3443 // We do not resolve before doing the case 1 test,
3444 // because the grammar is explicit in that the token &
3445 // is present, so we need to test for this particular case.
3449 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3454 // Case 1: & object.
3456 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3457 Expression child = ((Unary) e).Expr;
3459 if (child is ParameterReference || child is LocalVariableReference){
3462 "No need to use fixed statement for parameters or " +
3463 "local variable declarations (address is already " +
3468 ec.InFixedInitializer = true;
3470 ec.InFixedInitializer = false;
3474 child = ((Unary) e).Expr;
3476 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3479 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
3480 e.Error_ValueCannotBeConverted (e.Location, expr_type, false);
3484 data [i] = new ExpressionEmitter (e, vi);
3490 ec.InFixedInitializer = true;
3492 ec.InFixedInitializer = false;
3499 if (e.Type.IsArray){
3500 Type array_type = TypeManager.GetElementType (e.Type);
3503 // Provided that array_type is unmanaged,
3505 if (!TypeManager.VerifyUnManaged (array_type, loc))
3509 // and T* is implicitly convertible to the
3510 // pointer type given in the fixed statement.
3512 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3514 Expression converted = Convert.ImplicitConversionRequired (
3515 ec, array_ptr, vi.VariableType, loc);
3516 if (converted == null)
3519 data [i] = new ExpressionEmitter (converted, vi);
3528 if (e.Type == TypeManager.string_type){
3529 data [i] = new StringEmitter (e, vi, loc);
3534 // Case 4: fixed buffer
3535 FieldExpr fe = e as FieldExpr;
3537 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3539 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3541 Expression converted = Convert.ImplicitConversionRequired (
3542 ec, fixed_buffer_ptr, vi.VariableType, loc);
3543 if (converted == null)
3546 data [i] = new ExpressionEmitter (converted, vi);
3554 // For other cases, flag a `this is already fixed expression'
3556 if (e is LocalVariableReference || e is ParameterReference ||
3557 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3559 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3563 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3567 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3569 if (!statement.Resolve (ec)) {
3570 ec.KillFlowBranching ();
3574 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3575 has_ret = reachability.IsUnreachable;
3580 protected override void DoEmit (EmitContext ec)
3582 for (int i = 0; i < data.Length; i++) {
3586 statement.Emit (ec);
3591 ILGenerator ig = ec.ig;
3594 // Clear the pinned variable
3596 for (int i = 0; i < data.Length; i++) {
3597 data [i].EmitExit (ig);
3602 public class Catch : Statement {
3603 public readonly string Name;
3604 public readonly Block Block;
3605 public readonly Block VarBlock;
3607 Expression type_expr;
3610 public Catch (Expression type, string name, Block block, Block var_block, Location l)
3615 VarBlock = var_block;
3619 public Type CatchType {
3625 public bool IsGeneral {
3627 return type_expr == null;
3631 protected override void DoEmit(EmitContext ec)
3635 public override bool Resolve (EmitContext ec)
3637 using (ec.With (EmitContext.Flags.InCatch, true)) {
3638 if (type_expr != null) {
3639 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3645 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3646 Error (155, "The type caught or thrown must be derived from System.Exception");
3652 if (!Block.Resolve (ec))
3655 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
3656 // emit the "unused variable" warnings.
3657 if (VarBlock != null)
3658 return VarBlock.Resolve (ec);
3665 public class Try : ExceptionStatement {
3666 public readonly Block Fini, Block;
3667 public readonly ArrayList Specific;
3668 public readonly Catch General;
3670 bool need_exc_block;
3673 // specific, general and fini might all be null.
3675 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3677 if (specific == null && general == null){
3678 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3682 this.Specific = specific;
3683 this.General = general;
3688 public override bool Resolve (EmitContext ec)
3692 FlowBranchingException branching = ec.StartFlowBranching (this);
3694 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3696 if (!Block.Resolve (ec))
3699 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3701 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3703 Type[] prevCatches = new Type [Specific.Count];
3705 foreach (Catch c in Specific){
3706 ec.CurrentBranching.CreateSibling (
3707 c.Block, FlowBranching.SiblingType.Catch);
3709 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3711 if (c.Name != null) {
3712 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3714 throw new Exception ();
3716 vi.VariableInfo = null;
3719 if (!c.Resolve (ec))
3722 Type resolvedType = c.CatchType;
3723 for (int ii = 0; ii < last_index; ++ii) {
3724 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3725 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3730 prevCatches [last_index++] = resolvedType;
3731 need_exc_block = true;
3734 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3736 if (General != null){
3737 if (CodeGen.Assembly.WrapNonExceptionThrows) {
3738 foreach (Catch c in Specific){
3739 if (c.CatchType == TypeManager.exception_type) {
3740 Report.Warning (1058, 1, c.loc, "A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a `System.Runtime.CompilerServices.RuntimeWrappedException'");
3745 ec.CurrentBranching.CreateSibling (
3746 General.Block, FlowBranching.SiblingType.Catch);
3748 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3750 if (!General.Resolve (ec))
3753 need_exc_block = true;
3756 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3760 ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
3762 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3763 using (ec.With (EmitContext.Flags.InFinally, true)) {
3764 if (!Fini.Resolve (ec))
3769 need_exc_block = true;
3772 if (ec.InIterator) {
3773 ResolveFinally (branching);
3774 need_exc_block |= emit_finally;
3776 emit_finally = Fini != null;
3778 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3780 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3782 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3784 if (!reachability.AlwaysReturns) {
3785 // Unfortunately, System.Reflection.Emit automatically emits
3786 // a leave to the end of the finally block. This is a problem
3787 // if `returns' is true since we may jump to a point after the
3788 // end of the method.
3789 // As a workaround, emit an explicit ret here.
3790 ec.NeedReturnLabel ();
3796 protected override void DoEmit (EmitContext ec)
3798 ILGenerator ig = ec.ig;
3801 ig.BeginExceptionBlock ();
3804 foreach (Catch c in Specific){
3807 ig.BeginCatchBlock (c.CatchType);
3809 if (c.VarBlock != null)
3810 ec.EmitScopeInitFromBlock (c.VarBlock);
3811 if (c.Name != null){
3812 vi = c.Block.GetLocalInfo (c.Name);
3814 throw new Exception ("Variable does not exist in this block");
3817 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
3818 ig.Emit (OpCodes.Stloc, e);
3820 ec.EmitCapturedVariableInstance (vi);
3821 ig.Emit (OpCodes.Ldloc, e);
3822 ig.Emit (OpCodes.Stfld, vi.FieldBuilder);
3824 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3826 ig.Emit (OpCodes.Pop);
3831 if (General != null){
3832 ig.BeginCatchBlock (TypeManager.object_type);
3833 ig.Emit (OpCodes.Pop);
3834 General.Block.Emit (ec);
3839 ig.EndExceptionBlock ();
3842 public override void EmitFinally (EmitContext ec)
3848 public bool HasCatch
3851 return General != null || Specific.Count > 0;
3856 public class Using : ExceptionStatement {
3857 object expression_or_block;
3858 public Statement Statement;
3862 Expression [] resolved_vars;
3863 Expression [] converted_vars;
3864 ExpressionStatement [] assign;
3865 LocalBuilder local_copy;
3867 public Using (object expression_or_block, Statement stmt, Location l)
3869 this.expression_or_block = expression_or_block;
3875 // Resolves for the case of using using a local variable declaration.
3877 bool ResolveLocalVariableDecls (EmitContext ec)
3881 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3885 expr_type = texpr.Type;
3888 // The type must be an IDisposable or an implicit conversion
3891 converted_vars = new Expression [var_list.Count];
3892 resolved_vars = new Expression [var_list.Count];
3893 assign = new ExpressionStatement [var_list.Count];
3895 bool need_conv = !TypeManager.ImplementsInterface (
3896 expr_type, TypeManager.idisposable_type);
3898 foreach (DictionaryEntry e in var_list){
3899 Expression var = (Expression) e.Key;
3901 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3905 resolved_vars [i] = var;
3912 converted_vars [i] = Convert.ImplicitConversion (
3913 ec, var, TypeManager.idisposable_type, loc);
3915 if (converted_vars [i] == null) {
3916 Error_IsNotConvertibleToIDisposable ();
3924 foreach (DictionaryEntry e in var_list){
3925 Expression var = resolved_vars [i];
3926 Expression new_expr = (Expression) e.Value;
3929 a = new Assign (var, new_expr, loc);
3935 converted_vars [i] = var;
3936 assign [i] = (ExpressionStatement) a;
3943 void Error_IsNotConvertibleToIDisposable ()
3945 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
3946 TypeManager.CSharpName (expr_type));
3949 bool ResolveExpression (EmitContext ec)
3951 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3952 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3953 Error_IsNotConvertibleToIDisposable ();
3962 // Emits the code for the case of using using a local variable declaration.
3964 void EmitLocalVariableDecls (EmitContext ec)
3966 ILGenerator ig = ec.ig;
3969 for (i = 0; i < assign.Length; i++) {
3970 assign [i].EmitStatement (ec);
3973 ig.BeginExceptionBlock ();
3975 Statement.Emit (ec);
3976 var_list.Reverse ();
3981 void EmitLocalVariableDeclFinally (EmitContext ec)
3983 ILGenerator ig = ec.ig;
3985 int i = assign.Length;
3986 for (int ii = 0; ii < var_list.Count; ++ii){
3987 Expression var = resolved_vars [--i];
3988 Label skip = ig.DefineLabel ();
3990 ig.BeginFinallyBlock ();
3992 if (!var.Type.IsValueType) {
3994 ig.Emit (OpCodes.Brfalse, skip);
3995 converted_vars [i].Emit (ec);
3996 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3998 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4000 if (!(ml is MethodGroupExpr)) {
4002 ig.Emit (OpCodes.Box, var.Type);
4003 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4005 MethodInfo mi = null;
4007 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4008 if (TypeManager.GetParameterData (mk).Count == 0) {
4015 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4019 IMemoryLocation mloc = (IMemoryLocation) var;
4021 mloc.AddressOf (ec, AddressOp.Load);
4022 ig.Emit (OpCodes.Call, mi);
4026 ig.MarkLabel (skip);
4029 ig.EndExceptionBlock ();
4031 ig.BeginFinallyBlock ();
4036 void EmitExpression (EmitContext ec)
4039 // Make a copy of the expression and operate on that.
4041 ILGenerator ig = ec.ig;
4042 local_copy = ig.DeclareLocal (expr_type);
4045 ig.Emit (OpCodes.Stloc, local_copy);
4048 ig.BeginExceptionBlock ();
4050 Statement.Emit (ec);
4054 ig.EndExceptionBlock ();
4057 void EmitExpressionFinally (EmitContext ec)
4059 ILGenerator ig = ec.ig;
4060 if (!local_copy.LocalType.IsValueType) {
4061 Label skip = ig.DefineLabel ();
4062 ig.Emit (OpCodes.Ldloc, local_copy);
4063 ig.Emit (OpCodes.Brfalse, skip);
4064 ig.Emit (OpCodes.Ldloc, local_copy);
4065 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4066 ig.MarkLabel (skip);
4068 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4070 if (!(ml is MethodGroupExpr)) {
4071 ig.Emit (OpCodes.Ldloc, local_copy);
4072 ig.Emit (OpCodes.Box, local_copy.LocalType);
4073 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4075 MethodInfo mi = null;
4077 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4078 if (TypeManager.GetParameterData (mk).Count == 0) {
4085 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4089 ig.Emit (OpCodes.Ldloca, local_copy);
4090 ig.Emit (OpCodes.Call, mi);
4095 public override bool Resolve (EmitContext ec)
4097 if (expression_or_block is DictionaryEntry){
4098 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4099 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4101 if (!ResolveLocalVariableDecls (ec))
4104 } else if (expression_or_block is Expression){
4105 expr = (Expression) expression_or_block;
4107 expr = expr.Resolve (ec);
4111 expr_type = expr.Type;
4113 if (!ResolveExpression (ec))
4117 FlowBranchingException branching = ec.StartFlowBranching (this);
4119 bool ok = Statement.Resolve (ec);
4122 ec.KillFlowBranching ();
4126 ResolveFinally (branching);
4127 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4129 if (!reachability.AlwaysReturns) {
4130 // Unfortunately, System.Reflection.Emit automatically emits a leave
4131 // to the end of the finally block. This is a problem if `returns'
4132 // is true since we may jump to a point after the end of the method.
4133 // As a workaround, emit an explicit ret here.
4134 ec.NeedReturnLabel ();
4140 protected override void DoEmit (EmitContext ec)
4142 if (expression_or_block is DictionaryEntry)
4143 EmitLocalVariableDecls (ec);
4144 else if (expression_or_block is Expression)
4145 EmitExpression (ec);
4148 public override void EmitFinally (EmitContext ec)
4150 if (expression_or_block is DictionaryEntry)
4151 EmitLocalVariableDeclFinally (ec);
4152 else if (expression_or_block is Expression)
4153 EmitExpressionFinally (ec);
4158 /// Implementation of the foreach C# statement
4160 public class Foreach : Statement {
4162 Expression variable;
4164 Statement statement;
4166 CollectionForeach collection;
4168 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4169 Statement stmt, Location l)
4172 this.variable = var;
4178 public Statement Statement {
4179 get { return statement; }
4182 public override bool Resolve (EmitContext ec)
4184 expr = expr.Resolve (ec);
4188 Constant c = expr as Constant;
4189 if (c != null && c.GetValue () == null) {
4190 Report.Error (186, loc, "Use of null is not valid in this context");
4194 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4198 Type var_type = texpr.Type;
4200 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethod) {
4201 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4202 expr.ExprClassName);
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 collection.Error_Enumerator ();
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 ArrayCounter : TemporaryVariable
4248 public ArrayCounter (Location loc)
4249 : base (TypeManager.int32_type, loc)
4252 public void Initialize (EmitContext ec)
4255 ec.ig.Emit (OpCodes.Ldc_I4_0);
4259 public void Increment (EmitContext ec)
4263 ec.ig.Emit (OpCodes.Ldc_I4_1);
4264 ec.ig.Emit (OpCodes.Add);
4269 protected class ArrayForeach : Statement
4271 Expression variable, expr, conv;
4272 Statement statement;
4275 TemporaryVariable[] lengths;
4276 ArrayCounter[] counter;
4279 TemporaryVariable copy;
4282 public ArrayForeach (Type var_type, Expression var,
4283 Expression expr, Statement stmt, Location l)
4285 this.var_type = var_type;
4286 this.variable = var;
4292 public override bool Resolve (EmitContext ec)
4294 array_type = expr.Type;
4295 rank = array_type.GetArrayRank ();
4297 copy = new TemporaryVariable (array_type, loc);
4300 counter = new ArrayCounter [rank];
4301 lengths = new TemporaryVariable [rank];
4303 ArrayList list = new ArrayList ();
4304 for (int i = 0; i < rank; i++) {
4305 counter [i] = new ArrayCounter (loc);
4306 counter [i].Resolve (ec);
4308 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4309 lengths [i].Resolve (ec);
4311 list.Add (counter [i]);
4314 access = new ElementAccess (copy, list).Resolve (ec);
4318 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4324 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4325 ec.CurrentBranching.CreateSibling ();
4327 variable = variable.ResolveLValue (ec, conv, loc);
4328 if (variable == null)
4331 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4332 if (!statement.Resolve (ec))
4334 ec.EndFlowBranching ();
4336 // There's no direct control flow from the end of the embedded statement to the end of the loop
4337 ec.CurrentBranching.CurrentUsageVector.Goto ();
4339 ec.EndFlowBranching ();
4344 protected override void DoEmit (EmitContext ec)
4346 ILGenerator ig = ec.ig;
4348 copy.Store (ec, expr);
4350 Label[] test = new Label [rank];
4351 Label[] loop = new Label [rank];
4353 for (int i = 0; i < rank; i++) {
4354 test [i] = ig.DefineLabel ();
4355 loop [i] = ig.DefineLabel ();
4357 lengths [i].EmitThis (ec);
4358 ((ArrayAccess) access).EmitGetLength (ec, i);
4359 lengths [i].EmitStore (ig);
4362 for (int i = 0; i < rank; i++) {
4363 counter [i].Initialize (ec);
4365 ig.Emit (OpCodes.Br, test [i]);
4366 ig.MarkLabel (loop [i]);
4369 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4371 statement.Emit (ec);
4373 ig.MarkLabel (ec.LoopBegin);
4375 for (int i = rank - 1; i >= 0; i--){
4376 counter [i].Increment (ec);
4378 ig.MarkLabel (test [i]);
4379 counter [i].Emit (ec);
4380 lengths [i].Emit (ec);
4381 ig.Emit (OpCodes.Blt, loop [i]);
4384 ig.MarkLabel (ec.LoopEnd);
4388 protected class CollectionForeach : ExceptionStatement
4390 Expression variable, expr;
4391 Statement statement;
4393 TemporaryVariable enumerator;
4397 MethodGroupExpr get_enumerator;
4398 PropertyExpr get_current;
4399 MethodInfo move_next;
4400 Type var_type, enumerator_type;
4402 bool enumerator_found;
4404 public CollectionForeach (Type var_type, Expression var,
4405 Expression expr, Statement stmt, Location l)
4407 this.var_type = var_type;
4408 this.variable = var;
4414 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4416 Type return_type = mi.ReturnType;
4418 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4420 // Apply the same optimization as MS: skip the GetEnumerator
4421 // returning an IEnumerator, and use the one returning a
4422 // CharEnumerator instead. This allows us to avoid the
4423 // try-finally block and the boxing.
4428 // Ok, we can access it, now make sure that we can do something
4429 // with this `GetEnumerator'
4432 if (return_type == TypeManager.ienumerator_type ||
4433 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4434 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4436 // If it is not an interface, lets try to find the methods ourselves.
4437 // For example, if we have:
4438 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4439 // We can avoid the iface call. This is a runtime perf boost.
4440 // even bigger if we have a ValueType, because we avoid the cost
4443 // We have to make sure that both methods exist for us to take
4444 // this path. If one of the methods does not exist, we will just
4445 // use the interface. Sadly, this complex if statement is the only
4446 // way I could do this without a goto
4451 // Prefer a generic enumerator over a non-generic one.
4453 if (return_type.IsInterface && return_type.IsGenericType) {
4454 enumerator_type = return_type;
4455 if (!FetchGetCurrent (ec, return_type))
4456 get_current = new PropertyExpr (
4457 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4458 if (!FetchMoveNext (return_type))
4459 move_next = TypeManager.bool_movenext_void;
4464 if (return_type.IsInterface ||
4465 !FetchMoveNext (return_type) ||
4466 !FetchGetCurrent (ec, return_type)) {
4467 enumerator_type = return_type;
4468 move_next = TypeManager.bool_movenext_void;
4469 get_current = new PropertyExpr (
4470 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4475 // Ok, so they dont return an IEnumerable, we will have to
4476 // find if they support the GetEnumerator pattern.
4479 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
4480 Report.Error (202, loc, "foreach statement requires that the return type `{0}' of `{1}' must have a suitable public MoveNext method and public Current property",
4481 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
4486 enumerator_type = return_type;
4487 is_disposable = !enumerator_type.IsSealed ||
4488 TypeManager.ImplementsInterface (
4489 enumerator_type, TypeManager.idisposable_type);
4495 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4497 bool FetchMoveNext (Type t)
4499 MemberList move_next_list;
4501 move_next_list = TypeContainer.FindMembers (
4502 t, MemberTypes.Method,
4503 BindingFlags.Public | BindingFlags.Instance,
4504 Type.FilterName, "MoveNext");
4505 if (move_next_list.Count == 0)
4508 foreach (MemberInfo m in move_next_list){
4509 MethodInfo mi = (MethodInfo) m;
4511 if ((TypeManager.GetParameterData (mi).Count == 0) &&
4512 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4522 // Retrieves a `public T get_Current ()' method from the Type `t'
4524 bool FetchGetCurrent (EmitContext ec, Type t)
4526 PropertyExpr pe = Expression.MemberLookup (
4527 ec.ContainerType, t, "Current", MemberTypes.Property,
4528 Expression.AllBindingFlags, loc) as PropertyExpr;
4537 // Retrieves a `public void Dispose ()' method from the Type `t'
4539 static MethodInfo FetchMethodDispose (Type t)
4541 MemberList dispose_list;
4543 dispose_list = TypeContainer.FindMembers (
4544 t, MemberTypes.Method,
4545 BindingFlags.Public | BindingFlags.Instance,
4546 Type.FilterName, "Dispose");
4547 if (dispose_list.Count == 0)
4550 foreach (MemberInfo m in dispose_list){
4551 MethodInfo mi = (MethodInfo) m;
4553 if (TypeManager.GetParameterData (mi).Count == 0){
4554 if (mi.ReturnType == TypeManager.void_type)
4561 public void Error_Enumerator ()
4563 if (enumerator_found) {
4567 Report.Error (1579, loc,
4568 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4569 TypeManager.CSharpName (expr.Type));
4572 bool TryType (EmitContext ec, Type t)
4574 MethodGroupExpr mg = Expression.MemberLookup (
4575 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
4576 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4580 MethodBase result = null;
4581 MethodInfo tmp_move_next = null;
4582 PropertyExpr tmp_get_cur = null;
4583 Type tmp_enumerator_type = enumerator_type;
4584 foreach (MethodInfo mi in mg.Methods) {
4585 if (TypeManager.GetParameterData (mi).Count != 0)
4588 // Check whether GetEnumerator is public
4589 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4592 if (TypeManager.IsOverride (mi))
4595 enumerator_found = true;
4597 if (!GetEnumeratorFilter (ec, mi))
4601 tmp_move_next = move_next;
4602 tmp_get_cur = get_current;
4603 tmp_enumerator_type = enumerator_type;
4604 if (mi.DeclaringType == t)
4608 if (result != null) {
4609 move_next = tmp_move_next;
4610 get_current = tmp_get_cur;
4611 enumerator_type = tmp_enumerator_type;
4612 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
4613 get_enumerator = new MethodGroupExpr (mi, loc);
4615 if (t != expr.Type) {
4616 expr = Convert.ExplicitConversion (
4619 throw new InternalErrorException ();
4622 get_enumerator.InstanceExpression = expr;
4623 get_enumerator.IsBase = t != expr.Type;
4631 bool ProbeCollectionType (EmitContext ec, Type t)
4633 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4634 if (TryType (ec, tt))
4640 // Now try to find the method in the interfaces
4643 Type [] ifaces = t.GetInterfaces ();
4645 foreach (Type i in ifaces){
4646 if (TryType (ec, i))
4651 // Since TypeBuilder.GetInterfaces only returns the interface
4652 // types for this type, we have to keep looping, but once
4653 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4654 // done, because it returns all the types
4656 if ((t is TypeBuilder))
4665 public override bool Resolve (EmitContext ec)
4667 enumerator_type = TypeManager.ienumerator_type;
4668 is_disposable = true;
4670 if (!ProbeCollectionType (ec, expr.Type)) {
4671 Error_Enumerator ();
4675 enumerator = new TemporaryVariable (enumerator_type, loc);
4676 enumerator.Resolve (ec);
4678 init = new Invocation (get_enumerator, new ArrayList ());
4679 init = init.Resolve (ec);
4683 Expression move_next_expr;
4685 MemberInfo[] mi = new MemberInfo[] { move_next };
4686 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4687 mg.InstanceExpression = enumerator;
4689 move_next_expr = new Invocation (mg, new ArrayList ());
4692 get_current.InstanceExpression = enumerator;
4694 Statement block = new CollectionForeachStatement (
4695 var_type, variable, get_current, statement, loc);
4697 loop = new While (move_next_expr, block, loc);
4701 FlowBranchingException branching = null;
4703 branching = ec.StartFlowBranching (this);
4705 if (!loop.Resolve (ec))
4708 if (is_disposable) {
4709 ResolveFinally (branching);
4710 ec.EndFlowBranching ();
4712 emit_finally = true;
4717 protected override void DoEmit (EmitContext ec)
4719 ILGenerator ig = ec.ig;
4721 enumerator.Store (ec, init);
4724 // Protect the code in a try/finalize block, so that
4725 // if the beast implement IDisposable, we get rid of it
4727 if (is_disposable && emit_finally)
4728 ig.BeginExceptionBlock ();
4733 // Now the finally block
4735 if (is_disposable) {
4738 ig.EndExceptionBlock ();
4743 public override void EmitFinally (EmitContext ec)
4745 ILGenerator ig = ec.ig;
4747 if (enumerator_type.IsValueType) {
4748 MethodInfo mi = FetchMethodDispose (enumerator_type);
4750 enumerator.EmitLoadAddress (ec);
4751 ig.Emit (OpCodes.Call, mi);
4753 enumerator.Emit (ec);
4754 ig.Emit (OpCodes.Box, enumerator_type);
4755 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4758 Label call_dispose = ig.DefineLabel ();
4760 enumerator.Emit (ec);
4761 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4762 ig.Emit (OpCodes.Dup);
4763 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4764 ig.Emit (OpCodes.Pop);
4766 Label end_finally = ig.DefineLabel ();
4767 ig.Emit (OpCodes.Br, end_finally);
4769 ig.MarkLabel (call_dispose);
4770 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4771 ig.MarkLabel (end_finally);
4776 protected class CollectionForeachStatement : Statement
4779 Expression variable, current, conv;
4780 Statement statement;
4783 public CollectionForeachStatement (Type type, Expression variable,
4784 Expression current, Statement statement,
4788 this.variable = variable;
4789 this.current = current;
4790 this.statement = statement;
4794 public override bool Resolve (EmitContext ec)
4796 current = current.Resolve (ec);
4797 if (current == null)
4800 conv = Convert.ExplicitConversion (ec, current, type, loc);
4804 assign = new Assign (variable, conv, loc);
4805 if (assign.Resolve (ec) == null)
4808 if (!statement.Resolve (ec))
4814 protected override void DoEmit (EmitContext ec)
4816 assign.EmitStatement (ec);
4817 statement.Emit (ec);