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);
966 public abstract class Variable
968 public abstract Type Type {
972 public abstract bool HasInstance {
976 public abstract bool NeedsTemporary {
980 public abstract void EmitInstance (EmitContext ec);
982 public abstract void Emit (EmitContext ec);
984 public abstract void EmitAssign (EmitContext ec);
986 public abstract void EmitAddressOf (EmitContext ec);
990 // The information about a user-perceived local variable
992 public class LocalInfo {
993 public Expression Type;
995 public Type VariableType;
996 public readonly string Name;
997 public readonly Location Location;
998 public readonly Block Block;
1000 public VariableInfo VariableInfo;
1003 public Variable Variable {
1015 CompilerGenerated = 64,
1019 public enum ReadOnlyContext: byte {
1026 ReadOnlyContext ro_context;
1028 public LocalInfo (Expression type, string name, Block block, Location l)
1036 public LocalInfo (DeclSpace ds, Block block, Location l)
1038 VariableType = ds.IsGeneric ? ds.CurrentType : ds.TypeBuilder;
1043 public void ResolveVariable (EmitContext ec)
1045 Block theblock = Block;
1046 if (theblock.ScopeInfo != null)
1047 var = theblock.ScopeInfo.GetCapturedVariable (this);
1050 LocalBuilder builder;
1053 // This is needed to compile on both .NET 1.x and .NET 2.x
1054 // the later introduced `DeclareLocal (Type t, bool pinned)'
1056 builder = TypeManager.DeclareLocalPinned (ec.ig, VariableType);
1058 builder = ec.ig.DeclareLocal (VariableType);
1060 var = new LocalVariable (this, builder);
1064 public bool IsThisAssigned (EmitContext ec, Location loc)
1066 if (VariableInfo == null)
1067 throw new Exception ();
1069 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1072 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1075 public bool IsAssigned (EmitContext ec)
1077 if (VariableInfo == null)
1078 throw new Exception ();
1080 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1083 public bool Resolve (EmitContext ec)
1085 if (VariableType == null) {
1086 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1090 VariableType = texpr.Type;
1093 if (VariableType == TypeManager.void_type) {
1094 Expression.Error_VoidInvalidInTheContext (Location);
1098 if (VariableType.IsAbstract && VariableType.IsSealed) {
1099 FieldMember.Error_VariableOfStaticClass (Location, Name, VariableType);
1103 if (VariableType.IsPointer && !ec.InUnsafe)
1104 Expression.UnsafeError (Location);
1109 public bool IsCaptured {
1111 return (flags & Flags.Captured) != 0;
1115 flags |= Flags.Captured;
1119 public bool IsConstant {
1121 return (flags & Flags.IsConstant) != 0;
1124 flags |= Flags.IsConstant;
1128 public bool AddressTaken {
1130 return (flags & Flags.AddressTaken) != 0;
1134 flags |= Flags.AddressTaken;
1138 public bool CompilerGenerated {
1140 return (flags & Flags.CompilerGenerated) != 0;
1144 flags |= Flags.CompilerGenerated;
1148 public override string ToString ()
1150 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1151 Name, Type, VariableInfo, Location);
1156 return (flags & Flags.Used) != 0;
1159 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1163 public bool ReadOnly {
1165 return (flags & Flags.ReadOnly) != 0;
1169 public void SetReadOnlyContext (ReadOnlyContext context)
1171 flags |= Flags.ReadOnly;
1172 ro_context = context;
1175 public string GetReadOnlyContext ()
1178 throw new InternalErrorException ("Variable is not readonly");
1180 switch (ro_context) {
1181 case ReadOnlyContext.Fixed:
1182 return "fixed variable";
1183 case ReadOnlyContext.Foreach:
1184 return "foreach iteration variable";
1185 case ReadOnlyContext.Using:
1186 return "using variable";
1188 throw new NotImplementedException ();
1192 // Whether the variable is pinned, if Pinned the variable has been
1193 // allocated in a pinned slot with DeclareLocal.
1195 public bool Pinned {
1197 return (flags & Flags.Pinned) != 0;
1200 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1204 public bool IsThis {
1206 return (flags & Flags.IsThis) != 0;
1209 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1213 protected class LocalVariable : Variable
1215 public readonly LocalInfo LocalInfo;
1216 LocalBuilder builder;
1218 public LocalVariable (LocalInfo local, LocalBuilder builder)
1220 this.LocalInfo = local;
1221 this.builder = builder;
1224 public override Type Type {
1225 get { return LocalInfo.VariableType; }
1228 public override bool HasInstance {
1229 get { return false; }
1232 public override bool NeedsTemporary {
1233 get { return false; }
1236 public override void EmitInstance (EmitContext ec)
1241 public override void Emit (EmitContext ec)
1243 ec.ig.Emit (OpCodes.Ldloc, builder);
1246 public override void EmitAssign (EmitContext ec)
1248 ec.ig.Emit (OpCodes.Stloc, builder);
1251 public override void EmitAddressOf (EmitContext ec)
1253 ec.ig.Emit (OpCodes.Ldloca, builder);
1259 /// Block represents a C# block.
1263 /// This class is used in a number of places: either to represent
1264 /// explicit blocks that the programmer places or implicit blocks.
1266 /// Implicit blocks are used as labels or to introduce variable
1269 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1270 /// they contain extra information that is not necessary on normal blocks.
1272 public class Block : Statement {
1273 public Block Parent;
1274 public readonly Location StartLocation;
1275 public Location EndLocation = Location.Null;
1277 public readonly ToplevelBlock Toplevel;
1280 public enum Flags : ushort {
1284 VariablesInitialized = 8,
1289 HasVarargs = 256, // Used in ToplevelBlock
1293 protected Flags flags;
1295 public bool Implicit {
1296 get { return (flags & Flags.Implicit) != 0; }
1299 public bool Unchecked {
1300 get { return (flags & Flags.Unchecked) != 0; }
1301 set { flags |= Flags.Unchecked; }
1304 public bool Unsafe {
1305 get { return (flags & Flags.Unsafe) != 0; }
1306 set { flags |= Flags.Unsafe; }
1310 // The statements in this block
1312 protected ArrayList statements;
1316 // An array of Blocks. We keep track of children just
1317 // to generate the local variable declarations.
1319 // Statements and child statements are handled through the
1325 // Labels. (label, block) pairs.
1330 // Keeps track of (name, type) pairs
1332 IDictionary variables;
1335 // Keeps track of constants
1336 Hashtable constants;
1339 // Temporary variables.
1341 ArrayList temporary_variables;
1344 // If this is a switch section, the enclosing switch block.
1348 ExpressionStatement scope_init;
1350 ArrayList anonymous_children;
1352 protected static int id;
1356 public Block (Block parent)
1357 : this (parent, (Flags) 0, Location.Null, Location.Null)
1360 public Block (Block parent, Flags flags)
1361 : this (parent, flags, Location.Null, Location.Null)
1364 public Block (Block parent, Location start, Location end)
1365 : this (parent, (Flags) 0, start, end)
1368 public Block (Block parent, Flags flags, Location start, Location end)
1371 parent.AddChild (this);
1373 this.Parent = parent;
1375 this.StartLocation = start;
1376 this.EndLocation = end;
1379 statements = new ArrayList ();
1381 if ((flags & Flags.IsToplevel) != 0)
1382 Toplevel = (ToplevelBlock) this;
1384 Toplevel = parent.Toplevel;
1386 if (parent != null && Implicit) {
1387 if (parent.known_variables == null)
1388 parent.known_variables = new Hashtable ();
1389 // share with parent
1390 known_variables = parent.known_variables;
1394 public Block CreateSwitchBlock (Location start)
1396 Block new_block = new Block (this, start, start);
1397 new_block.switch_block = this;
1402 get { return this_id; }
1405 public IDictionary Variables {
1407 if (variables == null)
1408 variables = new ListDictionary ();
1413 void AddChild (Block b)
1415 if (children == null)
1416 children = new ArrayList ();
1421 public void SetEndLocation (Location loc)
1426 protected static void Error_158 (string name, Location loc)
1428 Report.Error (158, loc, "The label `{0}' shadows another label " +
1429 "by the same name in a contained scope.", name);
1433 /// Adds a label to the current block.
1437 /// false if the name already exists in this block. true
1441 public bool AddLabel (LabeledStatement target)
1443 if (switch_block != null)
1444 return switch_block.AddLabel (target);
1446 string name = target.Name;
1449 while (cur != null) {
1450 if (cur.DoLookupLabel (name) != null) {
1451 Report.Error (140, target.loc,
1452 "The label `{0}' is a duplicate", name);
1462 while (cur != null) {
1463 if (cur.DoLookupLabel (name) != null) {
1464 Error_158 (name, target.loc);
1468 if (children != null) {
1469 foreach (Block b in children) {
1470 LabeledStatement s = b.DoLookupLabel (name);
1474 Error_158 (name, target.loc);
1482 Toplevel.CheckError158 (name, target.loc);
1485 labels = new Hashtable ();
1487 labels.Add (name, target);
1491 public LabeledStatement LookupLabel (string name)
1493 LabeledStatement s = DoLookupLabel (name);
1497 if (children == null)
1500 foreach (Block child in children) {
1501 if (!child.Implicit)
1504 s = child.LookupLabel (name);
1512 LabeledStatement DoLookupLabel (string name)
1514 if (switch_block != null)
1515 return switch_block.LookupLabel (name);
1518 if (labels.Contains (name))
1519 return ((LabeledStatement) labels [name]);
1524 Hashtable known_variables;
1527 // Marks a variable with name @name as being used in this or a child block.
1528 // If a variable name has been used in a child block, it's illegal to
1529 // declare a variable with the same name in the current block.
1531 void AddKnownVariable (string name, LocalInfo info)
1533 if (known_variables == null)
1534 known_variables = new Hashtable ();
1536 known_variables [name] = info;
1539 LocalInfo GetKnownVariableInfo (string name, bool recurse)
1541 if (known_variables != null) {
1542 LocalInfo vi = (LocalInfo) known_variables [name];
1547 if (!recurse || (children == null))
1550 foreach (Block block in children) {
1551 LocalInfo vi = block.GetKnownVariableInfo (name, true);
1559 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1562 LocalInfo kvi = b.GetKnownVariableInfo (name, true);
1563 while (kvi == null) {
1569 kvi = b.GetKnownVariableInfo (name, false);
1575 // Is kvi.Block nested inside 'b'
1576 if (b.known_variables != kvi.Block.known_variables) {
1578 // If a variable by the same name it defined in a nested block of this
1579 // block, we violate the invariant meaning in a block.
1582 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1583 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1588 // It's ok if the definition is in a nested subblock of b, but not
1589 // nested inside this block -- a definition in a sibling block
1590 // should not affect us.
1596 // Block 'b' and kvi.Block are the same textual block.
1597 // However, different variables are extant.
1599 // Check if the variable is in scope in both blocks. We use
1600 // an indirect check that depends on AddVariable doing its
1601 // part in maintaining the invariant-meaning-in-block property.
1603 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1607 // Even though we detected the error when the name is used, we
1608 // treat it as if the variable declaration was in error.
1610 Report.SymbolRelatedToPreviousError (loc, name);
1611 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1615 public bool CheckError136_InParents (string name, Location loc)
1617 for (Block b = Parent; b != null; b = b.Parent) {
1618 if (!b.DoCheckError136 (name, "parent or current", loc))
1622 for (Block b = Toplevel.ContainerBlock; b != null; b = b.Toplevel.ContainerBlock) {
1623 if (!b.CheckError136_InParents (name, loc))
1630 public bool CheckError136_InChildren (string name, Location loc)
1632 if (!DoCheckError136_InChildren (name, loc))
1636 while (b.Implicit) {
1637 if (!b.Parent.DoCheckError136_InChildren (name, loc))
1645 protected bool DoCheckError136_InChildren (string name, Location loc)
1647 if (!DoCheckError136 (name, "child", loc))
1650 if (AnonymousChildren != null) {
1651 foreach (ToplevelBlock child in AnonymousChildren) {
1652 if (!child.DoCheckError136_InChildren (name, loc))
1657 if (children != null) {
1658 foreach (Block child in children) {
1659 if (!child.DoCheckError136_InChildren (name, loc))
1667 public bool CheckError136 (string name, string scope, bool check_parents,
1668 bool check_children, Location loc)
1670 if (!DoCheckError136 (name, scope, loc))
1673 if (check_parents) {
1674 if (!CheckError136_InParents (name, loc))
1678 if (check_children) {
1679 if (!CheckError136_InChildren (name, loc))
1683 for (Block c = Toplevel.ContainerBlock; c != null; c = c.Toplevel.ContainerBlock) {
1684 if (!c.DoCheckError136 (name, "parent or current", loc))
1691 protected bool DoCheckError136 (string name, string scope, Location loc)
1693 LocalInfo vi = GetKnownVariableInfo (name, false);
1695 Report.SymbolRelatedToPreviousError (vi.Location, name);
1696 Error_AlreadyDeclared (loc, name, scope != null ? scope : "child");
1701 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1703 Report.SymbolRelatedToPreviousError (p.Location, name);
1704 Error_AlreadyDeclared (
1705 loc, name, scope != null ? scope : "method argument");
1712 public LocalInfo AddVariable (Expression type, string name, Location l)
1714 LocalInfo vi = GetLocalInfo (name);
1716 Report.SymbolRelatedToPreviousError (vi.Location, name);
1717 if (known_variables == vi.Block.known_variables)
1718 Report.Error (128, l,
1719 "A local variable named `{0}' is already defined in this scope", name);
1721 Error_AlreadyDeclared (l, name, "parent");
1725 if (!CheckError136 (name, null, true, true, l))
1728 vi = new LocalInfo (type, name, this, l);
1729 Variables.Add (name, vi);
1730 AddKnownVariable (name, vi);
1732 if ((flags & Flags.VariablesInitialized) != 0)
1733 throw new Exception ();
1738 void Error_AlreadyDeclared (Location loc, string var, string reason)
1740 Report.Error (136, loc, "A local variable named `{0}' cannot be declared " +
1741 "in this scope because it would give a different meaning " +
1742 "to `{0}', which is already used in a `{1}' scope " +
1743 "to denote something else", var, reason);
1746 public bool AddConstant (Expression type, string name, Expression value, Location l)
1748 if (AddVariable (type, name, l) == null)
1751 if (constants == null)
1752 constants = new Hashtable ();
1754 constants.Add (name, value);
1756 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1761 static int next_temp_id = 0;
1763 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1765 Report.Debug (64, "ADD TEMPORARY", this, Toplevel, loc);
1767 if (temporary_variables == null)
1768 temporary_variables = new ArrayList ();
1770 int id = ++next_temp_id;
1771 string name = "$s_" + id.ToString ();
1773 LocalInfo li = new LocalInfo (te, name, this, loc);
1774 li.CompilerGenerated = true;
1775 temporary_variables.Add (li);
1779 public LocalInfo GetLocalInfo (string name)
1781 for (Block b = this; b != null; b = b.Parent) {
1782 if (b.variables != null) {
1783 LocalInfo ret = b.variables [name] as LocalInfo;
1791 public Expression GetVariableType (string name)
1793 LocalInfo vi = GetLocalInfo (name);
1794 return vi == null ? null : vi.Type;
1797 public Expression GetConstantExpression (string name)
1799 for (Block b = this; b != null; b = b.Parent) {
1800 if (b.constants != null) {
1801 Expression ret = b.constants [name] as Expression;
1809 public void AddStatement (Statement s)
1812 flags |= Flags.BlockUsed;
1816 get { return (flags & Flags.BlockUsed) != 0; }
1821 flags |= Flags.BlockUsed;
1824 public bool HasRet {
1825 get { return (flags & Flags.HasRet) != 0; }
1828 public bool IsDestructor {
1829 get { return (flags & Flags.IsDestructor) != 0; }
1832 public void SetDestructor ()
1834 flags |= Flags.IsDestructor;
1837 VariableMap param_map, local_map;
1839 public VariableMap ParameterMap {
1841 if ((flags & Flags.VariablesInitialized) == 0)
1842 throw new Exception ("Variables have not been initialized yet");
1848 public VariableMap LocalMap {
1850 if ((flags & Flags.VariablesInitialized) == 0)
1851 throw new Exception ("Variables have not been initialized yet");
1857 public ScopeInfo ScopeInfo;
1859 public ScopeInfo CreateScopeInfo ()
1861 if (ScopeInfo == null)
1862 ScopeInfo = ScopeInfo.CreateScope (this);
1867 public ArrayList AnonymousChildren {
1868 get { return anonymous_children; }
1871 public void AddAnonymousChild (ToplevelBlock b)
1873 if (anonymous_children == null)
1874 anonymous_children = new ArrayList ();
1876 anonymous_children.Add (b);
1880 /// Emits the variable declarations and labels.
1883 /// tc: is our typecontainer (to resolve type references)
1884 /// ig: is the code generator:
1886 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
1888 Report.Debug (64, "BLOCK RESOLVE META", this, Parent, toplevel);
1890 // If some parent block was unsafe, we remain unsafe even if this block
1891 // isn't explicitly marked as such.
1892 using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
1894 // Compute the VariableMap's.
1896 // Unfortunately, we don't know the type when adding variables with
1897 // AddVariable(), so we need to compute this info here.
1901 if (variables != null) {
1902 foreach (LocalInfo li in variables.Values)
1905 locals = new LocalInfo [variables.Count];
1906 variables.Values.CopyTo (locals, 0);
1908 locals = new LocalInfo [0];
1911 local_map = new VariableMap (Parent.LocalMap, locals);
1913 local_map = new VariableMap (locals);
1915 param_map = new VariableMap (ip);
1916 flags |= Flags.VariablesInitialized;
1919 // Process this block variables
1921 if (variables != null) {
1922 foreach (DictionaryEntry de in variables) {
1923 string name = (string) de.Key;
1924 LocalInfo vi = (LocalInfo) de.Value;
1925 Type variable_type = vi.VariableType;
1927 if (variable_type == null)
1930 if (variable_type.IsPointer) {
1932 // Am not really convinced that this test is required (Microsoft does it)
1933 // but the fact is that you would not be able to use the pointer variable
1936 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1941 if (constants == null)
1944 Expression cv = (Expression) constants [name];
1948 // Don't let 'const int Foo = Foo;' succeed.
1949 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
1950 // which in turn causes the 'must be constant' error to be triggered.
1951 constants.Remove (name);
1953 if (!Const.IsConstantTypeValid (variable_type)) {
1954 Const.Error_InvalidConstantType (variable_type, loc);
1958 using (ec.With (EmitContext.Flags.ConstantCheckState, (flags & Flags.Unchecked) == 0)) {
1959 ec.CurrentBlock = this;
1960 Expression e = cv.Resolve (ec);
1964 Constant ce = e as Constant;
1966 Const.Error_ExpressionMustBeConstant (vi.Location, name);
1970 e = ce.ImplicitConversionRequired (variable_type, vi.Location);
1974 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue) {
1975 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
1979 constants.Add (name, e);
1980 vi.IsConstant = true;
1986 // Now, handle the children
1988 if (children != null) {
1989 foreach (Block b in children)
1990 b.ResolveMeta (toplevel, ec, ip);
1996 // Emits the local variable declarations for a block
1998 public virtual void EmitMeta (EmitContext ec)
2000 Report.Debug (64, "BLOCK EMIT META", this, Parent, Toplevel, ScopeInfo, ec);
2001 if (ScopeInfo != null) {
2002 scope_init = ScopeInfo.GetScopeInitializer (ec);
2003 Report.Debug (64, "BLOCK EMIT META #1", this, Toplevel, ScopeInfo,
2007 if (variables != null){
2008 foreach (LocalInfo vi in variables.Values)
2009 vi.ResolveVariable (ec);
2012 if (temporary_variables != null) {
2013 foreach (LocalInfo vi in temporary_variables)
2014 vi.ResolveVariable (ec);
2017 if (children != null){
2018 foreach (Block b in children)
2023 void UsageWarning (FlowBranching.UsageVector vector)
2027 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
2028 foreach (DictionaryEntry de in variables){
2029 LocalInfo vi = (LocalInfo) de.Value;
2034 name = (string) de.Key;
2036 // vi.VariableInfo can be null for 'catch' variables
2037 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
2038 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
2040 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
2046 bool unreachable_shown;
2049 private void CheckPossibleMistakenEmptyStatement (Statement s)
2053 // Some statements are wrapped by a Block. Since
2054 // others' internal could be changed, here I treat
2055 // them as possibly wrapped by Block equally.
2056 Block b = s as Block;
2057 if (b != null && b.statements.Count == 1)
2058 s = (Statement) b.statements [0];
2061 body = ((Lock) s).Statement;
2063 body = ((For) s).Statement;
2064 else if (s is Foreach)
2065 body = ((Foreach) s).Statement;
2066 else if (s is While)
2067 body = ((While) s).Statement;
2068 else if (s is Using)
2069 body = ((Using) s).Statement;
2070 else if (s is Fixed)
2071 body = ((Fixed) s).Statement;
2075 if (body == null || body is EmptyStatement)
2076 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
2079 public override bool Resolve (EmitContext ec)
2081 Block prev_block = ec.CurrentBlock;
2084 int errors = Report.Errors;
2086 ec.CurrentBlock = this;
2087 ec.StartFlowBranching (this);
2089 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
2092 // This flag is used to notate nested statements as unreachable from the beginning of this block.
2093 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
2094 // from the beginning of the function. The outer Resolve() that detected the unreachability is
2095 // responsible for handling the situation.
2097 int statement_count = statements.Count;
2098 for (int ix = 0; ix < statement_count; ix++){
2099 Statement s = (Statement) statements [ix];
2100 // Check possible empty statement (CS0642)
2101 if (RootContext.WarningLevel >= 3 &&
2102 ix + 1 < statement_count &&
2103 statements [ix + 1] is Block)
2104 CheckPossibleMistakenEmptyStatement (s);
2107 // Warn if we detect unreachable code.
2110 if (s is EmptyStatement)
2114 ((Block) s).unreachable = true;
2116 if (!unreachable_shown && !(s is LabeledStatement)) {
2117 Report.Warning (162, 2, s.loc, "Unreachable code detected");
2118 unreachable_shown = true;
2123 // Note that we're not using ResolveUnreachable() for unreachable
2124 // statements here. ResolveUnreachable() creates a temporary
2125 // flow branching and kills it afterwards. This leads to problems
2126 // if you have two unreachable statements where the first one
2127 // assigns a variable and the second one tries to access it.
2130 if (!s.Resolve (ec)) {
2132 statements [ix] = EmptyStatement.Value;
2136 if (unreachable && !(s is LabeledStatement) && !(s is Block))
2137 statements [ix] = EmptyStatement.Value;
2139 num_statements = ix + 1;
2141 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
2142 if (unreachable && s is LabeledStatement)
2143 throw new InternalErrorException ("should not happen");
2146 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
2147 ec.CurrentBranching, statement_count, num_statements);
2149 while (ec.CurrentBranching is FlowBranchingLabeled)
2150 ec.EndFlowBranching ();
2152 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
2154 ec.CurrentBlock = prev_block;
2156 // If we're a non-static `struct' constructor which doesn't have an
2157 // initializer, then we must initialize all of the struct's fields.
2158 if ((flags & Flags.IsToplevel) != 0 &&
2159 !Toplevel.IsThisAssigned (ec) &&
2160 !vector.Reachability.AlwaysThrows)
2163 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2164 foreach (LabeledStatement label in labels.Values)
2165 if (!label.HasBeenReferenced)
2166 Report.Warning (164, 2, label.loc,
2167 "This label has not been referenced");
2170 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2172 if (vector.Reachability.IsUnreachable)
2173 flags |= Flags.HasRet;
2175 if (ok && (errors == Report.Errors)) {
2176 if (RootContext.WarningLevel >= 3)
2177 UsageWarning (vector);
2183 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2185 unreachable_shown = true;
2189 Report.Warning (162, 2, loc, "Unreachable code detected");
2191 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2192 bool ok = Resolve (ec);
2193 ec.KillFlowBranching ();
2198 protected override void DoEmit (EmitContext ec)
2200 for (int ix = 0; ix < num_statements; ix++){
2201 Statement s = (Statement) statements [ix];
2203 // Check whether we are the last statement in a
2206 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2207 ec.IsLastStatement = true;
2209 ec.IsLastStatement = false;
2215 public override void Emit (EmitContext ec)
2217 Block prev_block = ec.CurrentBlock;
2219 ec.CurrentBlock = this;
2221 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2222 bool is_lexical_block = !Implicit && (Parent != null);
2224 if (emit_debug_info) {
2225 if (is_lexical_block)
2228 ec.Mark (StartLocation, true);
2229 if (scope_init != null)
2230 scope_init.EmitStatement (ec);
2232 ec.Mark (EndLocation, true);
2234 if (emit_debug_info && is_lexical_block)
2237 ec.CurrentBlock = prev_block;
2241 // Returns true if we ar ea child of `b'.
2243 public bool IsChildOf (Block b)
2245 Block current = this;
2248 if (current.Parent == b)
2250 current = current.Parent;
2251 } while (current != null);
2255 public override string ToString ()
2257 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2262 // A toplevel block contains extra information, the split is done
2263 // only to separate information that would otherwise bloat the more
2264 // lightweight Block.
2266 // In particular, this was introduced when the support for Anonymous
2267 // Methods was implemented.
2269 public class ToplevelBlock : Block {
2271 // Pointer to the host of this anonymous method, or null
2272 // if we are the topmost block
2275 ToplevelBlock child;
2276 GenericMethod generic;
2277 FlowBranchingToplevel top_level_branching;
2278 AnonymousContainer anonymous_container;
2279 RootScopeInfo root_scope;
2281 public bool HasVarargs {
2282 get { return (flags & Flags.HasVarargs) != 0; }
2283 set { flags |= Flags.HasVarargs; }
2286 public bool IsIterator {
2287 get { return (flags & Flags.IsIterator) != 0; }
2291 // The parameters for the block.
2293 Parameters parameters;
2294 public Parameters Parameters {
2295 get { return parameters; }
2298 public bool CompleteContexts (EmitContext ec)
2300 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS", this,
2301 container, root_scope);
2303 if (root_scope != null)
2304 root_scope.LinkScopes ();
2306 if ((container == null) && (root_scope != null)) {
2307 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS #1", this,
2310 if (root_scope.DefineType () == null)
2312 if (!root_scope.ResolveType ())
2314 if (!root_scope.ResolveMembers ())
2316 if (!root_scope.DefineMembers ())
2323 public GenericMethod GenericMethod {
2324 get { return generic; }
2327 public ToplevelBlock Container {
2328 get { return container != null ? container.Toplevel : null; }
2331 public Block ContainerBlock {
2332 get { return container; }
2335 public AnonymousContainer AnonymousContainer {
2336 get { return anonymous_container; }
2337 set { anonymous_container = value; }
2341 // Parent is only used by anonymous blocks to link back to their
2344 public ToplevelBlock (Block container, Parameters parameters, Location start) :
2345 this (container, (Flags) 0, parameters, start)
2349 public ToplevelBlock (Block container, Parameters parameters, GenericMethod generic,
2351 this (container, parameters, start)
2353 this.generic = generic;
2356 public ToplevelBlock (Parameters parameters, Location start) :
2357 this (null, (Flags) 0, parameters, start)
2361 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2362 this (null, flags, parameters, start)
2366 public ToplevelBlock (Block container, Flags flags, Parameters parameters, Location start) :
2367 base (null, flags | Flags.IsToplevel, start, Location.Null)
2369 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2370 this.container = container;
2373 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2377 public bool CheckError158 (string name, Location loc)
2379 if (AnonymousChildren != null) {
2380 foreach (ToplevelBlock child in AnonymousChildren) {
2381 if (!child.CheckError158 (name, loc))
2386 for (ToplevelBlock c = Container; c != null; c = c.Container) {
2387 if (!c.DoCheckError158 (name, loc))
2394 bool DoCheckError158 (string name, Location loc)
2396 LabeledStatement s = LookupLabel (name);
2398 Error_158 (name, loc);
2405 public RootScopeInfo CreateRootScope (TypeContainer host)
2407 if (root_scope != null)
2410 if (Container == null)
2411 root_scope = new RootScopeInfo (
2412 this, host, generic, StartLocation);
2414 ScopeInfo = root_scope;
2418 public void CreateIteratorHost (RootScopeInfo root)
2420 Report.Debug (64, "CREATE ITERATOR HOST", this, root,
2421 container, root_scope);
2423 if ((container != null) || (root_scope != null))
2424 throw new InternalErrorException ();
2426 ScopeInfo = root_scope = root;
2429 public RootScopeInfo RootScope {
2431 if (root_scope != null)
2433 else if (Container != null)
2434 return Container.RootScope;
2440 public FlowBranchingToplevel TopLevelBranching {
2441 get { return top_level_branching; }
2445 // This is used if anonymous methods are used inside an iterator
2446 // (see 2test-22.cs for an example).
2448 // The AnonymousMethod is created while parsing - at a time when we don't
2449 // know yet that we're inside an iterator, so it's `Container' is initially
2450 // null. Later on, when resolving the iterator, we need to move the
2451 // anonymous method into that iterator.
2453 public void ReParent (ToplevelBlock new_parent)
2455 container = new_parent;
2456 Parent = new_parent;
2457 new_parent.child = this;
2461 // Returns a `ParameterReference' for the given name, or null if there
2462 // is no such parameter
2464 public ParameterReference GetParameterReference (string name, Location loc)
2469 for (ToplevelBlock t = this; t != null; t = t.Container) {
2470 Parameters pars = t.Parameters;
2471 par = pars.GetParameterByName (name, out idx);
2473 return new ParameterReference (par, this, idx, loc);
2479 // Whether the parameter named `name' is local to this block,
2480 // or false, if the parameter belongs to an encompassing block.
2482 public bool IsLocalParameter (string name)
2484 return Parameters.GetParameterByName (name) != null;
2488 // Whether the `name' is a parameter reference
2490 public bool IsParameterReference (string name)
2492 for (ToplevelBlock t = this; t != null; t = t.Container) {
2493 if (t.IsLocalParameter (name))
2499 LocalInfo this_variable = null;
2502 // Returns the "this" instance variable of this block.
2503 // See AddThisVariable() for more information.
2505 public LocalInfo ThisVariable {
2506 get { return this_variable; }
2511 // This is used by non-static `struct' constructors which do not have an
2512 // initializer - in this case, the constructor must initialize all of the
2513 // struct's fields. To do this, we add a "this" variable and use the flow
2514 // analysis code to ensure that it's been fully initialized before control
2515 // leaves the constructor.
2517 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2519 if (this_variable == null) {
2520 this_variable = new LocalInfo (ds, this, l);
2521 this_variable.Used = true;
2522 this_variable.IsThis = true;
2524 Variables.Add ("this", this_variable);
2527 return this_variable;
2530 public bool IsThisAssigned (EmitContext ec)
2532 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2535 public bool ResolveMeta (EmitContext ec, Parameters ip)
2537 int errors = Report.Errors;
2539 if (top_level_branching != null)
2545 if (!IsIterator && (container != null) && (parameters != null)) {
2546 foreach (Parameter p in parameters.FixedParameters) {
2547 if (!CheckError136_InParents (p.Name, loc))
2552 ResolveMeta (this, ec, ip);
2555 child.ResolveMeta (this, ec, ip);
2557 top_level_branching = ec.StartFlowBranching (this);
2559 return Report.Errors == errors;
2562 public override void EmitMeta (EmitContext ec)
2565 parameters.ResolveVariable (this);
2568 public void MakeIterator (Iterator iterator)
2570 flags |= Flags.IsIterator;
2572 Block block = new Block (this);
2573 foreach (Statement stmt in statements)
2574 block.AddStatement (stmt);
2575 statements = new ArrayList ();
2576 statements.Add (new MoveNextStatement (iterator, block));
2579 protected class MoveNextStatement : Statement {
2583 public MoveNextStatement (Iterator iterator, Block block)
2585 this.iterator = iterator;
2587 this.loc = iterator.Location;
2590 public override bool Resolve (EmitContext ec)
2592 return block.Resolve (ec);
2595 protected override void DoEmit (EmitContext ec)
2597 iterator.EmitMoveNext (ec, block);
2601 public override string ToString ()
2603 return String.Format ("{0} ({1}:{2}{3}:{4})", GetType (), ID, StartLocation,
2604 root_scope, anonymous_container != null ?
2605 anonymous_container.Scope : null);
2609 public class SwitchLabel {
2616 Label il_label_code;
2617 bool il_label_code_set;
2619 public static readonly object NullStringCase = new object ();
2622 // if expr == null, then it is the default case.
2624 public SwitchLabel (Expression expr, Location l)
2630 public Expression Label {
2636 public object Converted {
2642 public Label GetILLabel (EmitContext ec)
2645 il_label = ec.ig.DefineLabel ();
2646 il_label_set = true;
2651 public Label GetILLabelCode (EmitContext ec)
2653 if (!il_label_code_set){
2654 il_label_code = ec.ig.DefineLabel ();
2655 il_label_code_set = true;
2657 return il_label_code;
2661 // Resolves the expression, reduces it to a literal if possible
2662 // and then converts it to the requested type.
2664 public bool ResolveAndReduce (EmitContext ec, Type required_type, bool allow_nullable)
2666 Expression e = label.Resolve (ec);
2671 Constant c = e as Constant;
2673 Report.Error (150, loc, "A constant value is expected");
2677 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2678 converted = NullStringCase;
2682 if (allow_nullable && c.GetValue () == null) {
2683 converted = NullStringCase;
2687 c = c.ImplicitConversionRequired (required_type, loc);
2691 converted = c.GetValue ();
2695 public void Erorr_AlreadyOccurs ()
2698 if (converted == null)
2700 else if (converted == NullStringCase)
2703 label = converted.ToString ();
2705 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2709 public class SwitchSection {
2710 // An array of SwitchLabels.
2711 public readonly ArrayList Labels;
2712 public readonly Block Block;
2714 public SwitchSection (ArrayList labels, Block block)
2721 public class Switch : Statement {
2722 public readonly ArrayList Sections;
2723 public Expression Expr;
2726 /// Maps constants whose type type SwitchType to their SwitchLabels.
2728 public IDictionary Elements;
2731 /// The governing switch type
2733 public Type SwitchType;
2738 Label default_target;
2740 Expression new_expr;
2742 SwitchSection constant_section;
2743 SwitchSection default_section;
2747 // Nullable Types support for GMCS.
2749 Nullable.Unwrap unwrap;
2751 protected bool HaveUnwrap {
2752 get { return unwrap != null; }
2755 protected bool HaveUnwrap {
2756 get { return false; }
2761 // The types allowed to be implicitly cast from
2762 // on the governing type
2764 static Type [] allowed_types;
2766 public Switch (Expression e, ArrayList sects, Location l)
2773 public bool GotDefault {
2775 return default_section != null;
2779 public Label DefaultTarget {
2781 return default_target;
2786 // Determines the governing type for a switch. The returned
2787 // expression might be the expression from the switch, or an
2788 // expression that includes any potential conversions to the
2789 // integral types or to string.
2791 Expression SwitchGoverningType (EmitContext ec, Expression expr)
2795 if (t == TypeManager.byte_type ||
2796 t == TypeManager.sbyte_type ||
2797 t == TypeManager.ushort_type ||
2798 t == TypeManager.short_type ||
2799 t == TypeManager.uint32_type ||
2800 t == TypeManager.int32_type ||
2801 t == TypeManager.uint64_type ||
2802 t == TypeManager.int64_type ||
2803 t == TypeManager.char_type ||
2804 t == TypeManager.string_type ||
2805 t == TypeManager.bool_type ||
2806 t.IsSubclassOf (TypeManager.enum_type))
2809 if (allowed_types == null){
2810 allowed_types = new Type [] {
2811 TypeManager.sbyte_type,
2812 TypeManager.byte_type,
2813 TypeManager.short_type,
2814 TypeManager.ushort_type,
2815 TypeManager.int32_type,
2816 TypeManager.uint32_type,
2817 TypeManager.int64_type,
2818 TypeManager.uint64_type,
2819 TypeManager.char_type,
2820 TypeManager.string_type,
2821 TypeManager.bool_type
2826 // Try to find a *user* defined implicit conversion.
2828 // If there is no implicit conversion, or if there are multiple
2829 // conversions, we have to report an error
2831 Expression converted = null;
2832 foreach (Type tt in allowed_types){
2835 e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
2840 // Ignore over-worked ImplicitUserConversions that do
2841 // an implicit conversion in addition to the user conversion.
2843 if (!(e is UserCast))
2846 if (converted != null){
2847 Report.ExtraInformation (
2849 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2850 TypeManager.CSharpName (expr.Type)));
2860 // Performs the basic sanity checks on the switch statement
2861 // (looks for duplicate keys and non-constant expressions).
2863 // It also returns a hashtable with the keys that we will later
2864 // use to compute the switch tables
2866 bool CheckSwitch (EmitContext ec)
2869 Elements = Sections.Count > 10 ?
2870 (IDictionary)new Hashtable () :
2871 (IDictionary)new ListDictionary ();
2873 foreach (SwitchSection ss in Sections){
2874 foreach (SwitchLabel sl in ss.Labels){
2875 if (sl.Label == null){
2876 if (default_section != null){
2877 sl.Erorr_AlreadyOccurs ();
2880 default_section = ss;
2884 if (!sl.ResolveAndReduce (ec, SwitchType, HaveUnwrap)) {
2889 object key = sl.Converted;
2891 Elements.Add (key, sl);
2892 } catch (ArgumentException) {
2893 sl.Erorr_AlreadyOccurs ();
2901 void EmitObjectInteger (ILGenerator ig, object k)
2904 IntConstant.EmitInt (ig, (int) k);
2905 else if (k is Constant) {
2906 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2909 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2912 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2914 IntConstant.EmitInt (ig, (int) (long) k);
2915 ig.Emit (OpCodes.Conv_I8);
2918 LongConstant.EmitLong (ig, (long) k);
2920 else if (k is ulong)
2922 ulong ul = (ulong) k;
2925 IntConstant.EmitInt (ig, unchecked ((int) ul));
2926 ig.Emit (OpCodes.Conv_U8);
2930 LongConstant.EmitLong (ig, unchecked ((long) ul));
2934 IntConstant.EmitInt (ig, (int) ((char) k));
2935 else if (k is sbyte)
2936 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2938 IntConstant.EmitInt (ig, (int) ((byte) k));
2939 else if (k is short)
2940 IntConstant.EmitInt (ig, (int) ((short) k));
2941 else if (k is ushort)
2942 IntConstant.EmitInt (ig, (int) ((ushort) k));
2944 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2946 throw new Exception ("Unhandled case");
2949 // structure used to hold blocks of keys while calculating table switch
2950 class KeyBlock : IComparable
2952 public KeyBlock (long _nFirst)
2954 nFirst = nLast = _nFirst;
2958 public ArrayList rgKeys = null;
2959 // how many items are in the bucket
2960 public int Size = 1;
2963 get { return (int) (nLast - nFirst + 1); }
2965 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2967 return kbLast.nLast - kbFirst.nFirst + 1;
2969 public int CompareTo (object obj)
2971 KeyBlock kb = (KeyBlock) obj;
2972 int nLength = Length;
2973 int nLengthOther = kb.Length;
2974 if (nLengthOther == nLength)
2975 return (int) (kb.nFirst - nFirst);
2976 return nLength - nLengthOther;
2981 /// This method emits code for a lookup-based switch statement (non-string)
2982 /// Basically it groups the cases into blocks that are at least half full,
2983 /// and then spits out individual lookup opcodes for each block.
2984 /// It emits the longest blocks first, and short blocks are just
2985 /// handled with direct compares.
2987 /// <param name="ec"></param>
2988 /// <param name="val"></param>
2989 /// <returns></returns>
2990 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2992 int cElements = Elements.Count;
2993 object [] rgKeys = new object [cElements];
2994 Elements.Keys.CopyTo (rgKeys, 0);
2995 Array.Sort (rgKeys);
2997 // initialize the block list with one element per key
2998 ArrayList rgKeyBlocks = new ArrayList ();
2999 foreach (object key in rgKeys)
3000 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
3003 // iteratively merge the blocks while they are at least half full
3004 // there's probably a really cool way to do this with a tree...
3005 while (rgKeyBlocks.Count > 1)
3007 ArrayList rgKeyBlocksNew = new ArrayList ();
3008 kbCurr = (KeyBlock) rgKeyBlocks [0];
3009 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3011 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3012 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3015 kbCurr.nLast = kb.nLast;
3016 kbCurr.Size += kb.Size;
3020 // start a new block
3021 rgKeyBlocksNew.Add (kbCurr);
3025 rgKeyBlocksNew.Add (kbCurr);
3026 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3028 rgKeyBlocks = rgKeyBlocksNew;
3031 // initialize the key lists
3032 foreach (KeyBlock kb in rgKeyBlocks)
3033 kb.rgKeys = new ArrayList ();
3035 // fill the key lists
3037 if (rgKeyBlocks.Count > 0) {
3038 kbCurr = (KeyBlock) rgKeyBlocks [0];
3039 foreach (object key in rgKeys)
3041 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
3042 System.Convert.ToInt64 (key) > kbCurr.nLast;
3044 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3045 kbCurr.rgKeys.Add (key);
3049 // sort the blocks so we can tackle the largest ones first
3050 rgKeyBlocks.Sort ();
3052 // okay now we can start...
3053 ILGenerator ig = ec.ig;
3054 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3055 Label lblDefault = ig.DefineLabel ();
3057 Type typeKeys = null;
3058 if (rgKeys.Length > 0)
3059 typeKeys = rgKeys [0].GetType (); // used for conversions
3063 if (TypeManager.IsEnumType (SwitchType))
3064 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3066 compare_type = SwitchType;
3068 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3070 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3071 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3074 foreach (object key in kb.rgKeys)
3076 ig.Emit (OpCodes.Ldloc, val);
3077 EmitObjectInteger (ig, key);
3078 SwitchLabel sl = (SwitchLabel) Elements [key];
3079 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
3084 // TODO: if all the keys in the block are the same and there are
3085 // no gaps/defaults then just use a range-check.
3086 if (compare_type == TypeManager.int64_type ||
3087 compare_type == TypeManager.uint64_type)
3089 // TODO: optimize constant/I4 cases
3091 // check block range (could be > 2^31)
3092 ig.Emit (OpCodes.Ldloc, val);
3093 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3094 ig.Emit (OpCodes.Blt, lblDefault);
3095 ig.Emit (OpCodes.Ldloc, val);
3096 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
3097 ig.Emit (OpCodes.Bgt, lblDefault);
3100 ig.Emit (OpCodes.Ldloc, val);
3103 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3104 ig.Emit (OpCodes.Sub);
3106 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3111 ig.Emit (OpCodes.Ldloc, val);
3112 int nFirst = (int) kb.nFirst;
3115 IntConstant.EmitInt (ig, nFirst);
3116 ig.Emit (OpCodes.Sub);
3118 else if (nFirst < 0)
3120 IntConstant.EmitInt (ig, -nFirst);
3121 ig.Emit (OpCodes.Add);
3125 // first, build the list of labels for the switch
3127 int cJumps = kb.Length;
3128 Label [] rgLabels = new Label [cJumps];
3129 for (int iJump = 0; iJump < cJumps; iJump++)
3131 object key = kb.rgKeys [iKey];
3132 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
3134 SwitchLabel sl = (SwitchLabel) Elements [key];
3135 rgLabels [iJump] = sl.GetILLabel (ec);
3139 rgLabels [iJump] = lblDefault;
3141 // emit the switch opcode
3142 ig.Emit (OpCodes.Switch, rgLabels);
3145 // mark the default for this block
3147 ig.MarkLabel (lblDefault);
3150 // TODO: find the default case and emit it here,
3151 // to prevent having to do the following jump.
3152 // make sure to mark other labels in the default section
3154 // the last default just goes to the end
3155 ig.Emit (OpCodes.Br, lblDefault);
3157 // now emit the code for the sections
3158 bool fFoundDefault = false;
3159 bool fFoundNull = false;
3160 foreach (SwitchSection ss in Sections)
3162 foreach (SwitchLabel sl in ss.Labels)
3163 if (sl.Converted == SwitchLabel.NullStringCase)
3167 foreach (SwitchSection ss in Sections)
3169 foreach (SwitchLabel sl in ss.Labels)
3171 ig.MarkLabel (sl.GetILLabel (ec));
3172 ig.MarkLabel (sl.GetILLabelCode (ec));
3173 if (sl.Converted == SwitchLabel.NullStringCase)
3174 ig.MarkLabel (null_target);
3175 else if (sl.Label == null) {
3176 ig.MarkLabel (lblDefault);
3177 fFoundDefault = true;
3179 ig.MarkLabel (null_target);
3185 if (!fFoundDefault) {
3186 ig.MarkLabel (lblDefault);
3188 ig.MarkLabel (lblEnd);
3191 // This simple emit switch works, but does not take advantage of the
3193 // TODO: remove non-string logic from here
3194 // TODO: binary search strings?
3196 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3198 ILGenerator ig = ec.ig;
3199 Label end_of_switch = ig.DefineLabel ();
3200 Label next_test = ig.DefineLabel ();
3201 bool first_test = true;
3202 bool pending_goto_end = false;
3203 bool null_marked = false;
3206 ig.Emit (OpCodes.Ldloc, val);
3208 if (Elements.Contains (SwitchLabel.NullStringCase)){
3209 ig.Emit (OpCodes.Brfalse, null_target);
3211 ig.Emit (OpCodes.Brfalse, default_target);
3213 ig.Emit (OpCodes.Ldloc, val);
3214 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3215 ig.Emit (OpCodes.Stloc, val);
3217 int section_count = Sections.Count;
3218 for (int section = 0; section < section_count; section++){
3219 SwitchSection ss = (SwitchSection) Sections [section];
3221 if (ss == default_section)
3224 Label sec_begin = ig.DefineLabel ();
3226 ig.Emit (OpCodes.Nop);
3228 if (pending_goto_end)
3229 ig.Emit (OpCodes.Br, end_of_switch);
3231 int label_count = ss.Labels.Count;
3233 for (int label = 0; label < label_count; label++){
3234 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
3235 ig.MarkLabel (sl.GetILLabel (ec));
3238 ig.MarkLabel (next_test);
3239 next_test = ig.DefineLabel ();
3242 // If we are the default target
3244 if (sl.Label != null){
3245 object lit = sl.Converted;
3247 if (lit == SwitchLabel.NullStringCase){
3249 if (label + 1 == label_count)
3250 ig.Emit (OpCodes.Br, next_test);
3254 ig.Emit (OpCodes.Ldloc, val);
3255 ig.Emit (OpCodes.Ldstr, (string)lit);
3256 if (label_count == 1)
3257 ig.Emit (OpCodes.Bne_Un, next_test);
3259 if (label+1 == label_count)
3260 ig.Emit (OpCodes.Bne_Un, next_test);
3262 ig.Emit (OpCodes.Beq, sec_begin);
3267 ig.MarkLabel (null_target);
3270 ig.MarkLabel (sec_begin);
3271 foreach (SwitchLabel sl in ss.Labels)
3272 ig.MarkLabel (sl.GetILLabelCode (ec));
3275 pending_goto_end = !ss.Block.HasRet;
3278 ig.MarkLabel (next_test);
3279 ig.MarkLabel (default_target);
3281 ig.MarkLabel (null_target);
3282 if (default_section != null)
3283 default_section.Block.Emit (ec);
3284 ig.MarkLabel (end_of_switch);
3287 SwitchSection FindSection (SwitchLabel label)
3289 foreach (SwitchSection ss in Sections){
3290 foreach (SwitchLabel sl in ss.Labels){
3299 public override bool Resolve (EmitContext ec)
3301 Expr = Expr.Resolve (ec);
3305 new_expr = SwitchGoverningType (ec, Expr);
3308 if ((new_expr == null) && TypeManager.IsNullableType (Expr.Type)) {
3309 unwrap = Nullable.Unwrap.Create (Expr, ec);
3313 new_expr = SwitchGoverningType (ec, unwrap);
3317 if (new_expr == null){
3318 Report.Error (151, loc, "A value of an integral type or string expected for switch");
3323 SwitchType = new_expr.Type;
3325 if (!CheckSwitch (ec))
3329 Elements.Remove (SwitchLabel.NullStringCase);
3331 Switch old_switch = ec.Switch;
3333 ec.Switch.SwitchType = SwitchType;
3335 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3336 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3338 is_constant = new_expr is Constant;
3340 object key = ((Constant) new_expr).GetValue ();
3341 SwitchLabel label = (SwitchLabel) Elements [key];
3343 constant_section = FindSection (label);
3344 if (constant_section == null)
3345 constant_section = default_section;
3349 foreach (SwitchSection ss in Sections){
3351 ec.CurrentBranching.CreateSibling (
3352 null, FlowBranching.SiblingType.SwitchSection);
3356 if (is_constant && (ss != constant_section)) {
3357 // If we're a constant switch, we're only emitting
3358 // one single section - mark all the others as
3360 ec.CurrentBranching.CurrentUsageVector.Goto ();
3361 if (!ss.Block.ResolveUnreachable (ec, true))
3364 if (!ss.Block.Resolve (ec))
3369 if (default_section == null)
3370 ec.CurrentBranching.CreateSibling (
3371 null, FlowBranching.SiblingType.SwitchSection);
3373 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3374 ec.Switch = old_switch;
3376 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3382 protected override void DoEmit (EmitContext ec)
3384 ILGenerator ig = ec.ig;
3386 default_target = ig.DefineLabel ();
3387 null_target = ig.DefineLabel ();
3389 // Store variable for comparission purposes
3392 value = ig.DeclareLocal (SwitchType);
3394 unwrap.EmitCheck (ec);
3395 ig.Emit (OpCodes.Brfalse, null_target);
3397 ig.Emit (OpCodes.Stloc, value);
3399 } else if (!is_constant) {
3400 value = ig.DeclareLocal (SwitchType);
3402 ig.Emit (OpCodes.Stloc, value);
3407 // Setup the codegen context
3409 Label old_end = ec.LoopEnd;
3410 Switch old_switch = ec.Switch;
3412 ec.LoopEnd = ig.DefineLabel ();
3417 if (constant_section != null)
3418 constant_section.Block.Emit (ec);
3419 } else if (SwitchType == TypeManager.string_type)
3420 SimpleSwitchEmit (ec, value);
3422 TableSwitchEmit (ec, value);
3424 // Restore context state.
3425 ig.MarkLabel (ec.LoopEnd);
3428 // Restore the previous context
3430 ec.LoopEnd = old_end;
3431 ec.Switch = old_switch;
3435 public abstract class ExceptionStatement : Statement
3437 public abstract void EmitFinally (EmitContext ec);
3439 protected bool emit_finally = true;
3440 ArrayList parent_vectors;
3442 protected void DoEmitFinally (EmitContext ec)
3445 ec.ig.BeginFinallyBlock ();
3446 else if (ec.InIterator)
3447 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3451 protected void ResolveFinally (FlowBranchingException branching)
3453 emit_finally = branching.EmitFinally;
3455 branching.Parent.StealFinallyClauses (ref parent_vectors);
3459 public class Lock : ExceptionStatement {
3461 public Statement Statement;
3462 TemporaryVariable temp;
3464 public Lock (Expression expr, Statement stmt, Location l)
3471 public override bool Resolve (EmitContext ec)
3473 expr = expr.Resolve (ec);
3477 if (expr.Type.IsValueType){
3478 Report.Error (185, loc,
3479 "`{0}' is not a reference type as required by the lock statement",
3480 TypeManager.CSharpName (expr.Type));
3484 FlowBranchingException branching = ec.StartFlowBranching (this);
3485 bool ok = Statement.Resolve (ec);
3487 ec.KillFlowBranching ();
3491 ResolveFinally (branching);
3493 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3494 if (!reachability.AlwaysReturns) {
3495 // Unfortunately, System.Reflection.Emit automatically emits
3496 // a leave to the end of the finally block.
3497 // This is a problem if `returns' is true since we may jump
3498 // to a point after the end of the method.
3499 // As a workaround, emit an explicit ret here.
3500 ec.NeedReturnLabel ();
3503 // Avoid creating libraries that reference the internal
3506 if (t == TypeManager.null_type)
3507 t = TypeManager.object_type;
3509 temp = new TemporaryVariable (t, loc);
3515 protected override void DoEmit (EmitContext ec)
3517 ILGenerator ig = ec.ig;
3519 temp.Store (ec, expr);
3521 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3525 ig.BeginExceptionBlock ();
3526 Statement.Emit (ec);
3531 ig.EndExceptionBlock ();
3534 public override void EmitFinally (EmitContext ec)
3537 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3541 public class Unchecked : Statement {
3542 public readonly Block Block;
3544 public Unchecked (Block b)
3550 public override bool Resolve (EmitContext ec)
3552 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3553 return Block.Resolve (ec);
3556 protected override void DoEmit (EmitContext ec)
3558 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3563 public class Checked : Statement {
3564 public readonly Block Block;
3566 public Checked (Block b)
3569 b.Unchecked = false;
3572 public override bool Resolve (EmitContext ec)
3574 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3575 return Block.Resolve (ec);
3578 protected override void DoEmit (EmitContext ec)
3580 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3585 public class Unsafe : Statement {
3586 public readonly Block Block;
3588 public Unsafe (Block b)
3591 Block.Unsafe = true;
3594 public override bool Resolve (EmitContext ec)
3596 using (ec.With (EmitContext.Flags.InUnsafe, true))
3597 return Block.Resolve (ec);
3600 protected override void DoEmit (EmitContext ec)
3602 using (ec.With (EmitContext.Flags.InUnsafe, true))
3610 public class Fixed : Statement {
3612 ArrayList declarators;
3613 Statement statement;
3618 abstract class Emitter
3620 protected LocalInfo vi;
3621 protected Expression converted;
3623 protected Emitter (Expression expr, LocalInfo li)
3629 public abstract void Emit (EmitContext ec);
3630 public abstract void EmitExit (EmitContext ec);
3633 class ExpressionEmitter : Emitter {
3634 public ExpressionEmitter (Expression converted, LocalInfo li) :
3635 base (converted, li)
3639 public override void Emit (EmitContext ec) {
3641 // Store pointer in pinned location
3643 converted.Emit (ec);
3644 vi.Variable.EmitAssign (ec);
3647 public override void EmitExit (EmitContext ec)
3649 ec.ig.Emit (OpCodes.Ldc_I4_0);
3650 ec.ig.Emit (OpCodes.Conv_U);
3651 vi.Variable.EmitAssign (ec);
3655 class StringEmitter : Emitter {
3656 LocalBuilder pinned_string;
3659 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3665 public override void Emit (EmitContext ec)
3667 ILGenerator ig = ec.ig;
3668 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3670 converted.Emit (ec);
3671 ig.Emit (OpCodes.Stloc, pinned_string);
3673 Expression sptr = new StringPtr (pinned_string, loc);
3674 converted = Convert.ImplicitConversionRequired (
3675 ec, sptr, vi.VariableType, loc);
3677 if (converted == null)
3680 converted.Emit (ec);
3681 vi.Variable.EmitAssign (ec);
3684 public override void EmitExit (EmitContext ec)
3686 ec.ig.Emit (OpCodes.Ldnull);
3687 ec.ig.Emit (OpCodes.Stloc, pinned_string);
3691 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3694 declarators = decls;
3699 public Statement Statement {
3700 get { return statement; }
3703 public override bool Resolve (EmitContext ec)
3706 Expression.UnsafeError (loc);
3710 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3714 expr_type = texpr.Type;
3716 data = new Emitter [declarators.Count];
3718 if (!expr_type.IsPointer){
3719 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3724 foreach (Pair p in declarators){
3725 LocalInfo vi = (LocalInfo) p.First;
3726 Expression e = (Expression) p.Second;
3728 vi.VariableInfo.SetAssigned (ec);
3729 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3732 // The rules for the possible declarators are pretty wise,
3733 // but the production on the grammar is more concise.
3735 // So we have to enforce these rules here.
3737 // We do not resolve before doing the case 1 test,
3738 // because the grammar is explicit in that the token &
3739 // is present, so we need to test for this particular case.
3743 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3748 // Case 1: & object.
3750 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3751 Expression child = ((Unary) e).Expr;
3753 if (child is ParameterReference || child is LocalVariableReference){
3756 "No need to use fixed statement for parameters or " +
3757 "local variable declarations (address is already " +
3762 ec.InFixedInitializer = true;
3764 ec.InFixedInitializer = false;
3768 child = ((Unary) e).Expr;
3770 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3773 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
3774 e.Error_ValueCannotBeConverted (e.Location, expr_type, false);
3778 data [i] = new ExpressionEmitter (e, vi);
3784 ec.InFixedInitializer = true;
3786 ec.InFixedInitializer = false;
3793 if (e.Type.IsArray){
3794 Type array_type = TypeManager.GetElementType (e.Type);
3797 // Provided that array_type is unmanaged,
3799 if (!TypeManager.VerifyUnManaged (array_type, loc))
3803 // and T* is implicitly convertible to the
3804 // pointer type given in the fixed statement.
3806 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3808 Expression converted = Convert.ImplicitConversionRequired (
3809 ec, array_ptr, vi.VariableType, loc);
3810 if (converted == null)
3813 data [i] = new ExpressionEmitter (converted, vi);
3822 if (e.Type == TypeManager.string_type){
3823 data [i] = new StringEmitter (e, vi, loc);
3828 // Case 4: fixed buffer
3829 FieldExpr fe = e as FieldExpr;
3831 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3833 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3835 Expression converted = Convert.ImplicitConversionRequired (
3836 ec, fixed_buffer_ptr, vi.VariableType, loc);
3837 if (converted == null)
3840 data [i] = new ExpressionEmitter (converted, vi);
3848 // For other cases, flag a `this is already fixed expression'
3850 if (e is LocalVariableReference || e is ParameterReference ||
3851 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3853 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3857 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3861 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3863 if (!statement.Resolve (ec)) {
3864 ec.KillFlowBranching ();
3868 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3869 has_ret = reachability.IsUnreachable;
3874 protected override void DoEmit (EmitContext ec)
3876 for (int i = 0; i < data.Length; i++) {
3880 statement.Emit (ec);
3886 // Clear the pinned variable
3888 for (int i = 0; i < data.Length; i++) {
3889 data [i].EmitExit (ec);
3894 public class Catch : Statement {
3895 public readonly string Name;
3896 public readonly Block Block;
3897 public readonly Block VarBlock;
3899 Expression type_expr;
3902 public Catch (Expression type, string name, Block block, Block var_block, Location l)
3907 VarBlock = var_block;
3911 public Type CatchType {
3917 public bool IsGeneral {
3919 return type_expr == null;
3923 protected override void DoEmit(EmitContext ec)
3925 ILGenerator ig = ec.ig;
3927 if (CatchType != null)
3928 ig.BeginCatchBlock (CatchType);
3930 ig.BeginCatchBlock (TypeManager.object_type);
3932 if (VarBlock != null)
3936 LocalInfo vi = Block.GetLocalInfo (Name);
3938 throw new Exception ("Variable does not exist in this block");
3940 if (vi.Variable.NeedsTemporary) {
3941 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
3942 ig.Emit (OpCodes.Stloc, e);
3944 vi.Variable.EmitInstance (ec);
3945 ig.Emit (OpCodes.Ldloc, e);
3946 vi.Variable.EmitAssign (ec);
3948 vi.Variable.EmitAssign (ec);
3950 ig.Emit (OpCodes.Pop);
3955 public override bool Resolve (EmitContext ec)
3957 using (ec.With (EmitContext.Flags.InCatch, true)) {
3958 if (type_expr != null) {
3959 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3965 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3966 Error (155, "The type caught or thrown must be derived from System.Exception");
3972 if (!Block.Resolve (ec))
3975 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
3976 // emit the "unused variable" warnings.
3977 if (VarBlock != null)
3978 return VarBlock.Resolve (ec);
3985 public class Try : ExceptionStatement {
3986 public readonly Block Fini, Block;
3987 public readonly ArrayList Specific;
3988 public readonly Catch General;
3990 bool need_exc_block;
3993 // specific, general and fini might all be null.
3995 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3997 if (specific == null && general == null){
3998 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4002 this.Specific = specific;
4003 this.General = general;
4008 public override bool Resolve (EmitContext ec)
4012 FlowBranchingException branching = ec.StartFlowBranching (this);
4014 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4016 if (!Block.Resolve (ec))
4019 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4021 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4023 Type[] prevCatches = new Type [Specific.Count];
4025 foreach (Catch c in Specific){
4026 ec.CurrentBranching.CreateSibling (
4027 c.Block, FlowBranching.SiblingType.Catch);
4029 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4031 if (c.Name != null) {
4032 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
4034 throw new Exception ();
4036 vi.VariableInfo = null;
4039 if (!c.Resolve (ec))
4042 Type resolvedType = c.CatchType;
4043 for (int ii = 0; ii < last_index; ++ii) {
4044 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
4045 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
4050 prevCatches [last_index++] = resolvedType;
4051 need_exc_block = true;
4054 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4056 if (General != null){
4057 if (CodeGen.Assembly.WrapNonExceptionThrows) {
4058 foreach (Catch c in Specific){
4059 if (c.CatchType == TypeManager.exception_type) {
4060 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'");
4065 ec.CurrentBranching.CreateSibling (
4066 General.Block, FlowBranching.SiblingType.Catch);
4068 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4070 if (!General.Resolve (ec))
4073 need_exc_block = true;
4076 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4080 ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
4082 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4083 using (ec.With (EmitContext.Flags.InFinally, true)) {
4084 if (!Fini.Resolve (ec))
4089 need_exc_block = true;
4092 if (ec.InIterator) {
4093 ResolveFinally (branching);
4094 need_exc_block |= emit_finally;
4096 emit_finally = Fini != null;
4098 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4100 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4102 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
4104 if (!reachability.AlwaysReturns) {
4105 // Unfortunately, System.Reflection.Emit automatically emits
4106 // a leave to the end of the finally block. This is a problem
4107 // if `returns' is true since we may jump to a point after the
4108 // end of the method.
4109 // As a workaround, emit an explicit ret here.
4110 ec.NeedReturnLabel ();
4116 protected override void DoEmit (EmitContext ec)
4118 ILGenerator ig = ec.ig;
4121 ig.BeginExceptionBlock ();
4124 foreach (Catch c in Specific)
4127 if (General != null)
4132 ig.EndExceptionBlock ();
4135 public override void EmitFinally (EmitContext ec)
4141 public bool HasCatch
4144 return General != null || Specific.Count > 0;
4149 public class Using : ExceptionStatement {
4150 object expression_or_block;
4151 public Statement Statement;
4155 Expression [] resolved_vars;
4156 Expression [] converted_vars;
4157 ExpressionStatement [] assign;
4158 TemporaryVariable local_copy;
4160 public Using (object expression_or_block, Statement stmt, Location l)
4162 this.expression_or_block = expression_or_block;
4168 // Resolves for the case of using using a local variable declaration.
4170 bool ResolveLocalVariableDecls (EmitContext ec)
4174 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
4178 expr_type = texpr.Type;
4181 // The type must be an IDisposable or an implicit conversion
4184 converted_vars = new Expression [var_list.Count];
4185 resolved_vars = new Expression [var_list.Count];
4186 assign = new ExpressionStatement [var_list.Count];
4188 bool need_conv = !TypeManager.ImplementsInterface (
4189 expr_type, TypeManager.idisposable_type);
4191 foreach (DictionaryEntry e in var_list){
4192 Expression var = (Expression) e.Key;
4194 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
4198 resolved_vars [i] = var;
4205 converted_vars [i] = Convert.ImplicitConversion (
4206 ec, var, TypeManager.idisposable_type, loc);
4208 if (converted_vars [i] == null) {
4209 Error_IsNotConvertibleToIDisposable ();
4217 foreach (DictionaryEntry e in var_list){
4218 Expression var = resolved_vars [i];
4219 Expression new_expr = (Expression) e.Value;
4222 a = new Assign (var, new_expr, loc);
4228 converted_vars [i] = var;
4229 assign [i] = (ExpressionStatement) a;
4236 void Error_IsNotConvertibleToIDisposable ()
4238 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
4239 TypeManager.CSharpName (expr_type));
4242 bool ResolveExpression (EmitContext ec)
4244 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4245 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
4246 Error_IsNotConvertibleToIDisposable ();
4251 local_copy = new TemporaryVariable (expr_type, loc);
4252 local_copy.Resolve (ec);
4258 // Emits the code for the case of using using a local variable declaration.
4260 void EmitLocalVariableDecls (EmitContext ec)
4262 ILGenerator ig = ec.ig;
4265 for (i = 0; i < assign.Length; i++) {
4266 assign [i].EmitStatement (ec);
4269 ig.BeginExceptionBlock ();
4271 Statement.Emit (ec);
4273 var_list.Reverse ();
4278 void EmitLocalVariableDeclFinally (EmitContext ec)
4280 ILGenerator ig = ec.ig;
4282 int i = assign.Length;
4283 for (int ii = 0; ii < var_list.Count; ++ii){
4284 Expression var = resolved_vars [--i];
4285 Label skip = ig.DefineLabel ();
4288 ig.BeginFinallyBlock ();
4290 if (!var.Type.IsValueType) {
4292 ig.Emit (OpCodes.Brfalse, skip);
4293 converted_vars [i].Emit (ec);
4294 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4296 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4298 if (!(ml is MethodGroupExpr)) {
4300 ig.Emit (OpCodes.Box, var.Type);
4301 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4303 MethodInfo mi = null;
4305 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4306 if (TypeManager.GetParameterData (mk).Count == 0) {
4313 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4317 IMemoryLocation mloc = (IMemoryLocation) var;
4319 mloc.AddressOf (ec, AddressOp.Load);
4320 ig.Emit (OpCodes.Call, mi);
4324 ig.MarkLabel (skip);
4327 ig.EndExceptionBlock ();
4329 ig.BeginFinallyBlock ();
4334 void EmitExpression (EmitContext ec)
4337 // Make a copy of the expression and operate on that.
4339 ILGenerator ig = ec.ig;
4341 local_copy.Store (ec, expr);
4344 ig.BeginExceptionBlock ();
4346 Statement.Emit (ec);
4350 ig.EndExceptionBlock ();
4353 void EmitExpressionFinally (EmitContext ec)
4355 ILGenerator ig = ec.ig;
4356 if (!expr_type.IsValueType) {
4357 Label skip = ig.DefineLabel ();
4358 local_copy.Emit (ec);
4359 ig.Emit (OpCodes.Brfalse, skip);
4360 local_copy.Emit (ec);
4361 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4362 ig.MarkLabel (skip);
4364 Expression ml = Expression.MemberLookup (
4365 ec.ContainerType, TypeManager.idisposable_type, expr_type,
4366 "Dispose", Location.Null);
4368 if (!(ml is MethodGroupExpr)) {
4369 local_copy.Emit (ec);
4370 ig.Emit (OpCodes.Box, expr_type);
4371 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4373 MethodInfo mi = null;
4375 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4376 if (TypeManager.GetParameterData (mk).Count == 0) {
4383 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4387 local_copy.AddressOf (ec, AddressOp.Load);
4388 ig.Emit (OpCodes.Call, mi);
4393 public override bool Resolve (EmitContext ec)
4395 if (expression_or_block is DictionaryEntry){
4396 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4397 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4399 if (!ResolveLocalVariableDecls (ec))
4402 } else if (expression_or_block is Expression){
4403 expr = (Expression) expression_or_block;
4405 expr = expr.Resolve (ec);
4409 expr_type = expr.Type;
4411 if (!ResolveExpression (ec))
4415 FlowBranchingException branching = ec.StartFlowBranching (this);
4417 bool ok = Statement.Resolve (ec);
4420 ec.KillFlowBranching ();
4424 ResolveFinally (branching);
4425 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4427 if (!reachability.AlwaysReturns) {
4428 // Unfortunately, System.Reflection.Emit automatically emits a leave
4429 // to the end of the finally block. This is a problem if `returns'
4430 // is true since we may jump to a point after the end of the method.
4431 // As a workaround, emit an explicit ret here.
4432 ec.NeedReturnLabel ();
4438 protected override void DoEmit (EmitContext ec)
4440 if (expression_or_block is DictionaryEntry)
4441 EmitLocalVariableDecls (ec);
4442 else if (expression_or_block is Expression)
4443 EmitExpression (ec);
4446 public override void EmitFinally (EmitContext ec)
4448 if (expression_or_block is DictionaryEntry)
4449 EmitLocalVariableDeclFinally (ec);
4450 else if (expression_or_block is Expression)
4451 EmitExpressionFinally (ec);
4456 /// Implementation of the foreach C# statement
4458 public class Foreach : Statement {
4460 Expression variable;
4462 Statement statement;
4464 CollectionForeach collection;
4466 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4467 Statement stmt, Location l)
4470 this.variable = var;
4476 public Statement Statement {
4477 get { return statement; }
4480 public override bool Resolve (EmitContext ec)
4482 expr = expr.Resolve (ec);
4486 Constant c = expr as Constant;
4487 if (c != null && c.GetValue () == null) {
4488 Report.Error (186, loc, "Use of null is not valid in this context");
4492 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4496 Type var_type = texpr.Type;
4498 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
4499 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4500 expr.ExprClassName);
4505 // We need an instance variable. Not sure this is the best
4506 // way of doing this.
4508 // FIXME: When we implement propertyaccess, will those turn
4509 // out to return values in ExprClass? I think they should.
4511 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4512 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4513 collection.Error_Enumerator ();
4517 if (expr.Type.IsArray) {
4518 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4519 return array.Resolve (ec);
4521 collection = new CollectionForeach (
4522 var_type, variable, expr, statement, loc);
4523 return collection.Resolve (ec);
4527 protected override void DoEmit (EmitContext ec)
4529 ILGenerator ig = ec.ig;
4531 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4532 ec.LoopBegin = ig.DefineLabel ();
4533 ec.LoopEnd = ig.DefineLabel ();
4535 if (collection != null)
4536 collection.Emit (ec);
4540 ec.LoopBegin = old_begin;
4541 ec.LoopEnd = old_end;
4544 protected class ArrayCounter : TemporaryVariable
4546 public ArrayCounter (Location loc)
4547 : base (TypeManager.int32_type, loc)
4550 public void Initialize (EmitContext ec)
4553 ec.ig.Emit (OpCodes.Ldc_I4_0);
4557 public void Increment (EmitContext ec)
4561 ec.ig.Emit (OpCodes.Ldc_I4_1);
4562 ec.ig.Emit (OpCodes.Add);
4567 protected class ArrayForeach : Statement
4569 Expression variable, expr, conv;
4570 Statement statement;
4573 TemporaryVariable[] lengths;
4574 ArrayCounter[] counter;
4577 TemporaryVariable copy;
4580 public ArrayForeach (Type var_type, Expression var,
4581 Expression expr, Statement stmt, Location l)
4583 this.var_type = var_type;
4584 this.variable = var;
4590 public override bool Resolve (EmitContext ec)
4592 array_type = expr.Type;
4593 rank = array_type.GetArrayRank ();
4595 copy = new TemporaryVariable (array_type, loc);
4598 counter = new ArrayCounter [rank];
4599 lengths = new TemporaryVariable [rank];
4601 ArrayList list = new ArrayList ();
4602 for (int i = 0; i < rank; i++) {
4603 counter [i] = new ArrayCounter (loc);
4604 counter [i].Resolve (ec);
4606 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4607 lengths [i].Resolve (ec);
4609 list.Add (counter [i]);
4612 access = new ElementAccess (copy, list).Resolve (ec);
4616 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4622 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4623 ec.CurrentBranching.CreateSibling ();
4625 variable = variable.ResolveLValue (ec, conv, loc);
4626 if (variable == null)
4629 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4630 if (!statement.Resolve (ec))
4632 ec.EndFlowBranching ();
4634 // There's no direct control flow from the end of the embedded statement to the end of the loop
4635 ec.CurrentBranching.CurrentUsageVector.Goto ();
4637 ec.EndFlowBranching ();
4642 protected override void DoEmit (EmitContext ec)
4644 ILGenerator ig = ec.ig;
4646 copy.Store (ec, expr);
4648 Label[] test = new Label [rank];
4649 Label[] loop = new Label [rank];
4651 for (int i = 0; i < rank; i++) {
4652 test [i] = ig.DefineLabel ();
4653 loop [i] = ig.DefineLabel ();
4655 lengths [i].EmitThis (ec);
4656 ((ArrayAccess) access).EmitGetLength (ec, i);
4657 lengths [i].EmitStore (ec);
4660 for (int i = 0; i < rank; i++) {
4661 counter [i].Initialize (ec);
4663 ig.Emit (OpCodes.Br, test [i]);
4664 ig.MarkLabel (loop [i]);
4667 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4669 statement.Emit (ec);
4671 ig.MarkLabel (ec.LoopBegin);
4673 for (int i = rank - 1; i >= 0; i--){
4674 counter [i].Increment (ec);
4676 ig.MarkLabel (test [i]);
4677 counter [i].Emit (ec);
4678 lengths [i].Emit (ec);
4679 ig.Emit (OpCodes.Blt, loop [i]);
4682 ig.MarkLabel (ec.LoopEnd);
4686 protected class CollectionForeach : ExceptionStatement
4688 Expression variable, expr;
4689 Statement statement;
4691 TemporaryVariable enumerator;
4695 MethodGroupExpr get_enumerator;
4696 PropertyExpr get_current;
4697 MethodInfo move_next;
4698 Type var_type, enumerator_type;
4700 bool enumerator_found;
4702 public CollectionForeach (Type var_type, Expression var,
4703 Expression expr, Statement stmt, Location l)
4705 this.var_type = var_type;
4706 this.variable = var;
4712 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4714 Type return_type = mi.ReturnType;
4716 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4718 // Apply the same optimization as MS: skip the GetEnumerator
4719 // returning an IEnumerator, and use the one returning a
4720 // CharEnumerator instead. This allows us to avoid the
4721 // try-finally block and the boxing.
4726 // Ok, we can access it, now make sure that we can do something
4727 // with this `GetEnumerator'
4730 if (return_type == TypeManager.ienumerator_type ||
4731 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4732 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4734 // If it is not an interface, lets try to find the methods ourselves.
4735 // For example, if we have:
4736 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4737 // We can avoid the iface call. This is a runtime perf boost.
4738 // even bigger if we have a ValueType, because we avoid the cost
4741 // We have to make sure that both methods exist for us to take
4742 // this path. If one of the methods does not exist, we will just
4743 // use the interface. Sadly, this complex if statement is the only
4744 // way I could do this without a goto
4749 // Prefer a generic enumerator over a non-generic one.
4751 if (return_type.IsInterface && return_type.IsGenericType) {
4752 enumerator_type = return_type;
4753 if (!FetchGetCurrent (ec, return_type))
4754 get_current = new PropertyExpr (
4755 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4756 if (!FetchMoveNext (return_type))
4757 move_next = TypeManager.bool_movenext_void;
4762 if (return_type.IsInterface ||
4763 !FetchMoveNext (return_type) ||
4764 !FetchGetCurrent (ec, return_type)) {
4765 enumerator_type = return_type;
4766 move_next = TypeManager.bool_movenext_void;
4767 get_current = new PropertyExpr (
4768 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4773 // Ok, so they dont return an IEnumerable, we will have to
4774 // find if they support the GetEnumerator pattern.
4777 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
4778 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",
4779 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
4784 enumerator_type = return_type;
4785 is_disposable = !enumerator_type.IsSealed ||
4786 TypeManager.ImplementsInterface (
4787 enumerator_type, TypeManager.idisposable_type);
4793 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4795 bool FetchMoveNext (Type t)
4797 MemberList move_next_list;
4799 move_next_list = TypeContainer.FindMembers (
4800 t, MemberTypes.Method,
4801 BindingFlags.Public | BindingFlags.Instance,
4802 Type.FilterName, "MoveNext");
4803 if (move_next_list.Count == 0)
4806 foreach (MemberInfo m in move_next_list){
4807 MethodInfo mi = (MethodInfo) m;
4809 if ((TypeManager.GetParameterData (mi).Count == 0) &&
4810 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4820 // Retrieves a `public T get_Current ()' method from the Type `t'
4822 bool FetchGetCurrent (EmitContext ec, Type t)
4824 PropertyExpr pe = Expression.MemberLookup (
4825 ec.ContainerType, t, "Current", MemberTypes.Property,
4826 Expression.AllBindingFlags, loc) as PropertyExpr;
4835 // Retrieves a `public void Dispose ()' method from the Type `t'
4837 static MethodInfo FetchMethodDispose (Type t)
4839 MemberList dispose_list;
4841 dispose_list = TypeContainer.FindMembers (
4842 t, MemberTypes.Method,
4843 BindingFlags.Public | BindingFlags.Instance,
4844 Type.FilterName, "Dispose");
4845 if (dispose_list.Count == 0)
4848 foreach (MemberInfo m in dispose_list){
4849 MethodInfo mi = (MethodInfo) m;
4851 if (TypeManager.GetParameterData (mi).Count == 0){
4852 if (mi.ReturnType == TypeManager.void_type)
4859 public void Error_Enumerator ()
4861 if (enumerator_found) {
4865 Report.Error (1579, loc,
4866 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4867 TypeManager.CSharpName (expr.Type));
4870 bool TryType (EmitContext ec, Type t)
4872 MethodGroupExpr mg = Expression.MemberLookup (
4873 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
4874 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4878 MethodInfo result = null;
4879 MethodInfo tmp_move_next = null;
4880 PropertyExpr tmp_get_cur = null;
4881 Type tmp_enumerator_type = enumerator_type;
4882 foreach (MethodInfo mi in mg.Methods) {
4883 if (TypeManager.GetParameterData (mi).Count != 0)
4886 // Check whether GetEnumerator is public
4887 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4890 if (TypeManager.IsOverride (mi))
4893 enumerator_found = true;
4895 if (!GetEnumeratorFilter (ec, mi))
4898 if (result != null) {
4899 if (TypeManager.IsGenericType (result.ReturnType)) {
4900 if (!TypeManager.IsGenericType (mi.ReturnType))
4903 Report.SymbolRelatedToPreviousError(t);
4904 Report.Error(1640, loc, "foreach statement cannot operate on variables of type `{0}' " +
4905 "because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
4906 TypeManager.CSharpName (t), TypeManager.CSharpSignature (mi));
4909 Report.SymbolRelatedToPreviousError (result);
4910 Report.SymbolRelatedToPreviousError (mi);
4911 Report.Warning (278, 2, loc, "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
4912 TypeManager.CSharpName (t), "enumerable", TypeManager.CSharpSignature (result), TypeManager.CSharpSignature (mi));
4915 tmp_move_next = move_next;
4916 tmp_get_cur = get_current;
4917 tmp_enumerator_type = enumerator_type;
4918 if (mi.DeclaringType == t)
4922 if (result != null) {
4923 move_next = tmp_move_next;
4924 get_current = tmp_get_cur;
4925 enumerator_type = tmp_enumerator_type;
4926 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
4927 get_enumerator = new MethodGroupExpr (mi, loc);
4929 if (t != expr.Type) {
4930 expr = Convert.ExplicitConversion (
4933 throw new InternalErrorException ();
4936 get_enumerator.InstanceExpression = expr;
4937 get_enumerator.IsBase = t != expr.Type;
4945 bool ProbeCollectionType (EmitContext ec, Type t)
4947 int errors = Report.Errors;
4948 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4949 if (TryType (ec, tt))
4954 if (Report.Errors > errors)
4958 // Now try to find the method in the interfaces
4961 Type [] ifaces = t.GetInterfaces ();
4963 foreach (Type i in ifaces){
4964 if (TryType (ec, i))
4969 // Since TypeBuilder.GetInterfaces only returns the interface
4970 // types for this type, we have to keep looping, but once
4971 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4972 // done, because it returns all the types
4974 if ((t is TypeBuilder))
4983 public override bool Resolve (EmitContext ec)
4985 enumerator_type = TypeManager.ienumerator_type;
4986 is_disposable = true;
4988 if (!ProbeCollectionType (ec, expr.Type)) {
4989 Error_Enumerator ();
4993 enumerator = new TemporaryVariable (enumerator_type, loc);
4994 enumerator.Resolve (ec);
4996 init = new Invocation (get_enumerator, new ArrayList ());
4997 init = init.Resolve (ec);
5001 Expression move_next_expr;
5003 MemberInfo[] mi = new MemberInfo[] { move_next };
5004 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
5005 mg.InstanceExpression = enumerator;
5007 move_next_expr = new Invocation (mg, new ArrayList ());
5010 get_current.InstanceExpression = enumerator;
5012 Statement block = new CollectionForeachStatement (
5013 var_type, variable, get_current, statement, loc);
5015 loop = new While (move_next_expr, block, loc);
5019 FlowBranchingException branching = null;
5021 branching = ec.StartFlowBranching (this);
5023 if (!loop.Resolve (ec))
5026 if (is_disposable) {
5027 ResolveFinally (branching);
5028 ec.EndFlowBranching ();
5030 emit_finally = true;
5035 protected override void DoEmit (EmitContext ec)
5037 ILGenerator ig = ec.ig;
5039 enumerator.Store (ec, init);
5042 // Protect the code in a try/finalize block, so that
5043 // if the beast implement IDisposable, we get rid of it
5045 if (is_disposable && emit_finally)
5046 ig.BeginExceptionBlock ();
5051 // Now the finally block
5053 if (is_disposable) {
5056 ig.EndExceptionBlock ();
5061 public override void EmitFinally (EmitContext ec)
5063 ILGenerator ig = ec.ig;
5065 if (enumerator_type.IsValueType) {
5066 MethodInfo mi = FetchMethodDispose (enumerator_type);
5068 enumerator.EmitLoadAddress (ec);
5069 ig.Emit (OpCodes.Call, mi);
5071 enumerator.Emit (ec);
5072 ig.Emit (OpCodes.Box, enumerator_type);
5073 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5076 Label call_dispose = ig.DefineLabel ();
5078 enumerator.Emit (ec);
5079 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5080 ig.Emit (OpCodes.Dup);
5081 ig.Emit (OpCodes.Brtrue_S, call_dispose);
5082 ig.Emit (OpCodes.Pop);
5084 Label end_finally = ig.DefineLabel ();
5085 ig.Emit (OpCodes.Br, end_finally);
5087 ig.MarkLabel (call_dispose);
5088 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5089 ig.MarkLabel (end_finally);
5094 protected class CollectionForeachStatement : Statement
5097 Expression variable, current, conv;
5098 Statement statement;
5101 public CollectionForeachStatement (Type type, Expression variable,
5102 Expression current, Statement statement,
5106 this.variable = variable;
5107 this.current = current;
5108 this.statement = statement;
5112 public override bool Resolve (EmitContext ec)
5114 current = current.Resolve (ec);
5115 if (current == null)
5118 conv = Convert.ExplicitConversion (ec, current, type, loc);
5122 assign = new Assign (variable, conv, loc);
5123 if (assign.Resolve (ec) == null)
5126 if (!statement.Resolve (ec))
5132 protected override void DoEmit (EmitContext ec)
5134 assign.EmitStatement (ec);
5135 statement.Emit (ec);