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.TypeBuilder;
1043 public void ResolveVariable (EmitContext ec)
1045 Block theblock = Block;
1046 while (theblock.Implicit)
1047 theblock = theblock.Parent;
1048 if (theblock.ScopeInfo != null)
1049 var = theblock.ScopeInfo.GetCapturedVariable (this);
1052 LocalBuilder builder;
1055 // This is needed to compile on both .NET 1.x and .NET 2.x
1056 // the later introduced `DeclareLocal (Type t, bool pinned)'
1058 builder = TypeManager.DeclareLocalPinned (ec.ig, VariableType);
1060 builder = ec.ig.DeclareLocal (VariableType);
1062 var = new LocalVariable (this, builder);
1066 public bool IsThisAssigned (EmitContext ec, Location loc)
1068 if (VariableInfo == null)
1069 throw new Exception ();
1071 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1074 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1077 public bool IsAssigned (EmitContext ec)
1079 if (VariableInfo == null)
1080 throw new Exception ();
1082 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1085 public bool Resolve (EmitContext ec)
1087 if (VariableType == null) {
1088 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1092 VariableType = texpr.Type;
1095 if (VariableType == TypeManager.void_type) {
1096 Expression.Error_VoidInvalidInTheContext (Location);
1100 if (VariableType.IsAbstract && VariableType.IsSealed) {
1101 FieldMember.Error_VariableOfStaticClass (Location, Name, VariableType);
1105 if (VariableType.IsPointer && !ec.InUnsafe)
1106 Expression.UnsafeError (Location);
1111 public bool IsCaptured {
1113 return (flags & Flags.Captured) != 0;
1117 flags |= Flags.Captured;
1121 public bool IsConstant {
1123 return (flags & Flags.IsConstant) != 0;
1126 flags |= Flags.IsConstant;
1130 public bool AddressTaken {
1132 return (flags & Flags.AddressTaken) != 0;
1136 flags |= Flags.AddressTaken;
1140 public bool CompilerGenerated {
1142 return (flags & Flags.CompilerGenerated) != 0;
1146 flags |= Flags.CompilerGenerated;
1150 public override string ToString ()
1152 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1153 Name, Type, VariableInfo, Location);
1158 return (flags & Flags.Used) != 0;
1161 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1165 public bool ReadOnly {
1167 return (flags & Flags.ReadOnly) != 0;
1171 public void SetReadOnlyContext (ReadOnlyContext context)
1173 flags |= Flags.ReadOnly;
1174 ro_context = context;
1177 public string GetReadOnlyContext ()
1180 throw new InternalErrorException ("Variable is not readonly");
1182 switch (ro_context) {
1183 case ReadOnlyContext.Fixed:
1184 return "fixed variable";
1185 case ReadOnlyContext.Foreach:
1186 return "foreach iteration variable";
1187 case ReadOnlyContext.Using:
1188 return "using variable";
1190 throw new NotImplementedException ();
1194 // Whether the variable is pinned, if Pinned the variable has been
1195 // allocated in a pinned slot with DeclareLocal.
1197 public bool Pinned {
1199 return (flags & Flags.Pinned) != 0;
1202 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1206 public bool IsThis {
1208 return (flags & Flags.IsThis) != 0;
1211 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1215 protected class LocalVariable : Variable
1217 public readonly LocalInfo LocalInfo;
1218 LocalBuilder builder;
1220 public LocalVariable (LocalInfo local, LocalBuilder builder)
1222 this.LocalInfo = local;
1223 this.builder = builder;
1226 public override Type Type {
1227 get { return LocalInfo.VariableType; }
1230 public override bool HasInstance {
1231 get { return false; }
1234 public override bool NeedsTemporary {
1235 get { return false; }
1238 public override void EmitInstance (EmitContext ec)
1243 public override void Emit (EmitContext ec)
1245 ec.ig.Emit (OpCodes.Ldloc, builder);
1248 public override void EmitAssign (EmitContext ec)
1250 ec.ig.Emit (OpCodes.Stloc, builder);
1253 public override void EmitAddressOf (EmitContext ec)
1255 ec.ig.Emit (OpCodes.Ldloca, builder);
1261 /// Block represents a C# block.
1265 /// This class is used in a number of places: either to represent
1266 /// explicit blocks that the programmer places or implicit blocks.
1268 /// Implicit blocks are used as labels or to introduce variable
1271 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1272 /// they contain extra information that is not necessary on normal blocks.
1274 public class Block : Statement {
1275 public Block Parent;
1276 public readonly Location StartLocation;
1277 public Location EndLocation = Location.Null;
1279 public readonly ToplevelBlock Toplevel;
1282 public enum Flags : ushort {
1286 VariablesInitialized = 8,
1291 HasVarargs = 256, // Used in ToplevelBlock
1295 protected Flags flags;
1297 public bool Implicit {
1298 get { return (flags & Flags.Implicit) != 0; }
1301 public bool Unchecked {
1302 get { return (flags & Flags.Unchecked) != 0; }
1303 set { flags |= Flags.Unchecked; }
1306 public bool Unsafe {
1307 get { return (flags & Flags.Unsafe) != 0; }
1308 set { flags |= Flags.Unsafe; }
1312 // The statements in this block
1314 protected ArrayList statements;
1318 // An array of Blocks. We keep track of children just
1319 // to generate the local variable declarations.
1321 // Statements and child statements are handled through the
1327 // Labels. (label, block) pairs.
1332 // Keeps track of (name, type) pairs
1334 IDictionary variables;
1337 // Keeps track of constants
1338 Hashtable constants;
1341 // Temporary variables.
1343 ArrayList temporary_variables;
1346 // If this is a switch section, the enclosing switch block.
1350 ExpressionStatement scope_init;
1352 ArrayList anonymous_children;
1354 protected static int id;
1358 public Block (Block parent)
1359 : this (parent, (Flags) 0, Location.Null, Location.Null)
1362 public Block (Block parent, Flags flags)
1363 : this (parent, flags, Location.Null, Location.Null)
1366 public Block (Block parent, Location start, Location end)
1367 : this (parent, (Flags) 0, start, end)
1370 public Block (Block parent, Flags flags, Location start, Location end)
1373 parent.AddChild (this);
1375 this.Parent = parent;
1377 this.StartLocation = start;
1378 this.EndLocation = end;
1381 statements = new ArrayList ();
1383 if ((flags & Flags.IsToplevel) != 0)
1384 Toplevel = (ToplevelBlock) this;
1386 Toplevel = parent.Toplevel;
1388 if (parent != null && Implicit) {
1389 if (parent.known_variables == null)
1390 parent.known_variables = new Hashtable ();
1391 // share with parent
1392 known_variables = parent.known_variables;
1396 public Block CreateSwitchBlock (Location start)
1398 Block new_block = new Block (this, start, start);
1399 new_block.switch_block = this;
1404 get { return this_id; }
1407 public IDictionary Variables {
1409 if (variables == null)
1410 variables = new ListDictionary ();
1415 void AddChild (Block b)
1417 if (children == null)
1418 children = new ArrayList ();
1423 public void SetEndLocation (Location loc)
1428 protected static void Error_158 (string name, Location loc)
1430 Report.Error (158, loc, "The label `{0}' shadows another label " +
1431 "by the same name in a contained scope.", name);
1435 /// Adds a label to the current block.
1439 /// false if the name already exists in this block. true
1443 public bool AddLabel (LabeledStatement target)
1445 if (switch_block != null)
1446 return switch_block.AddLabel (target);
1448 string name = target.Name;
1451 while (cur != null) {
1452 if (cur.DoLookupLabel (name) != null) {
1453 Report.Error (140, target.loc,
1454 "The label `{0}' is a duplicate", name);
1464 while (cur != null) {
1465 if (cur.DoLookupLabel (name) != null) {
1466 Error_158 (name, target.loc);
1470 if (children != null) {
1471 foreach (Block b in children) {
1472 LabeledStatement s = b.DoLookupLabel (name);
1476 Error_158 (name, target.loc);
1484 Toplevel.CheckError158 (name, target.loc);
1487 labels = new Hashtable ();
1489 labels.Add (name, target);
1493 public LabeledStatement LookupLabel (string name)
1495 LabeledStatement s = DoLookupLabel (name);
1499 if (children == null)
1502 foreach (Block child in children) {
1503 if (!child.Implicit)
1506 s = child.LookupLabel (name);
1514 LabeledStatement DoLookupLabel (string name)
1516 if (switch_block != null)
1517 return switch_block.LookupLabel (name);
1520 if (labels.Contains (name))
1521 return ((LabeledStatement) labels [name]);
1526 Hashtable known_variables;
1529 // Marks a variable with name @name as being used in this or a child block.
1530 // If a variable name has been used in a child block, it's illegal to
1531 // declare a variable with the same name in the current block.
1533 void AddKnownVariable (string name, LocalInfo info)
1535 if (known_variables == null)
1536 known_variables = new Hashtable ();
1538 known_variables [name] = info;
1541 LocalInfo GetKnownVariableInfo (string name, bool recurse)
1543 if (known_variables != null) {
1544 LocalInfo vi = (LocalInfo) known_variables [name];
1549 if (!recurse || (children == null))
1552 foreach (Block block in children) {
1553 LocalInfo vi = block.GetKnownVariableInfo (name, true);
1561 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1564 LocalInfo kvi = b.GetKnownVariableInfo (name, true);
1565 while (kvi == null) {
1571 kvi = b.GetKnownVariableInfo (name, false);
1577 // Is kvi.Block nested inside 'b'
1578 if (b.known_variables != kvi.Block.known_variables) {
1580 // If a variable by the same name it defined in a nested block of this
1581 // block, we violate the invariant meaning in a block.
1584 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1585 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1590 // It's ok if the definition is in a nested subblock of b, but not
1591 // nested inside this block -- a definition in a sibling block
1592 // should not affect us.
1598 // Block 'b' and kvi.Block are the same textual block.
1599 // However, different variables are extant.
1601 // Check if the variable is in scope in both blocks. We use
1602 // an indirect check that depends on AddVariable doing its
1603 // part in maintaining the invariant-meaning-in-block property.
1605 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1609 // Even though we detected the error when the name is used, we
1610 // treat it as if the variable declaration was in error.
1612 Report.SymbolRelatedToPreviousError (loc, name);
1613 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1617 public bool CheckError136_InParents (string name, Location loc)
1619 for (Block b = Parent; b != null; b = b.Parent) {
1620 if (!b.DoCheckError136 (name, "parent or current", loc))
1624 for (Block b = Toplevel.ContainerBlock; b != null; b = b.Toplevel.ContainerBlock) {
1625 if (!b.CheckError136_InParents (name, loc))
1632 public bool CheckError136_InChildren (string name, Location loc)
1634 if (!DoCheckError136_InChildren (name, loc))
1638 while (b.Implicit) {
1639 if (!b.Parent.DoCheckError136_InChildren (name, loc))
1647 protected bool DoCheckError136_InChildren (string name, Location loc)
1649 if (!DoCheckError136 (name, "child", loc))
1652 if (AnonymousChildren != null) {
1653 foreach (ToplevelBlock child in AnonymousChildren) {
1654 if (!child.DoCheckError136_InChildren (name, loc))
1659 if (children != null) {
1660 foreach (Block child in children) {
1661 if (!child.DoCheckError136_InChildren (name, loc))
1669 public bool CheckError136 (string name, string scope, bool check_parents,
1670 bool check_children, Location loc)
1672 if (!DoCheckError136 (name, scope, loc))
1675 if (check_parents) {
1676 if (!CheckError136_InParents (name, loc))
1680 if (check_children) {
1681 if (!CheckError136_InChildren (name, loc))
1685 for (Block c = Toplevel.ContainerBlock; c != null; c = c.Toplevel.ContainerBlock) {
1686 if (!c.DoCheckError136 (name, "parent or current", loc))
1693 protected bool DoCheckError136 (string name, string scope, Location loc)
1695 LocalInfo vi = GetKnownVariableInfo (name, false);
1697 Report.SymbolRelatedToPreviousError (vi.Location, name);
1698 Error_AlreadyDeclared (loc, name, scope != null ? scope : "child");
1703 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1705 Report.SymbolRelatedToPreviousError (p.Location, name);
1706 Error_AlreadyDeclared (
1707 loc, name, scope != null ? scope : "method argument");
1714 public LocalInfo AddVariable (Expression type, string name, Location l)
1716 LocalInfo vi = GetLocalInfo (name);
1718 Report.SymbolRelatedToPreviousError (vi.Location, name);
1719 if (known_variables == vi.Block.known_variables)
1720 Report.Error (128, l,
1721 "A local variable named `{0}' is already defined in this scope", name);
1723 Error_AlreadyDeclared (l, name, "parent");
1727 if (!CheckError136 (name, null, true, true, l))
1730 vi = new LocalInfo (type, name, this, l);
1731 Variables.Add (name, vi);
1732 AddKnownVariable (name, vi);
1734 if ((flags & Flags.VariablesInitialized) != 0)
1735 throw new Exception ();
1740 void Error_AlreadyDeclared (Location loc, string var, string reason)
1742 Report.Error (136, loc, "A local variable named `{0}' cannot be declared " +
1743 "in this scope because it would give a different meaning " +
1744 "to `{0}', which is already used in a `{1}' scope " +
1745 "to denote something else", var, reason);
1748 public bool AddConstant (Expression type, string name, Expression value, Location l)
1750 if (AddVariable (type, name, l) == null)
1753 if (constants == null)
1754 constants = new Hashtable ();
1756 constants.Add (name, value);
1758 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1763 static int next_temp_id = 0;
1765 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1767 Report.Debug (64, "ADD TEMPORARY", this, Toplevel, loc);
1769 if (temporary_variables == null)
1770 temporary_variables = new ArrayList ();
1772 int id = ++next_temp_id;
1773 string name = "$s_" + id.ToString ();
1775 LocalInfo li = new LocalInfo (te, name, this, loc);
1776 li.CompilerGenerated = true;
1777 temporary_variables.Add (li);
1781 public LocalInfo GetLocalInfo (string name)
1783 for (Block b = this; b != null; b = b.Parent) {
1784 if (b.variables != null) {
1785 LocalInfo ret = b.variables [name] as LocalInfo;
1793 public Expression GetVariableType (string name)
1795 LocalInfo vi = GetLocalInfo (name);
1796 return vi == null ? null : vi.Type;
1799 public Expression GetConstantExpression (string name)
1801 for (Block b = this; b != null; b = b.Parent) {
1802 if (b.constants != null) {
1803 Expression ret = b.constants [name] as Expression;
1811 public void AddStatement (Statement s)
1814 flags |= Flags.BlockUsed;
1818 get { return (flags & Flags.BlockUsed) != 0; }
1823 flags |= Flags.BlockUsed;
1826 public bool HasRet {
1827 get { return (flags & Flags.HasRet) != 0; }
1830 public bool IsDestructor {
1831 get { return (flags & Flags.IsDestructor) != 0; }
1834 public void SetDestructor ()
1836 flags |= Flags.IsDestructor;
1839 VariableMap param_map, local_map;
1841 public VariableMap ParameterMap {
1843 if ((flags & Flags.VariablesInitialized) == 0)
1844 throw new Exception ("Variables have not been initialized yet");
1850 public VariableMap LocalMap {
1852 if ((flags & Flags.VariablesInitialized) == 0)
1853 throw new Exception ("Variables have not been initialized yet");
1859 public ScopeInfo ScopeInfo;
1861 public ScopeInfo CreateScopeInfo ()
1864 return Parent.CreateScopeInfo ();
1866 if (ScopeInfo == null)
1867 ScopeInfo = new ScopeInfo (Toplevel.AnonymousMethodHost, this);
1872 public ArrayList AnonymousChildren {
1873 get { return anonymous_children; }
1876 public void AddAnonymousChild (ToplevelBlock b)
1878 if (anonymous_children == null)
1879 anonymous_children = new ArrayList ();
1881 anonymous_children.Add (b);
1885 /// Emits the variable declarations and labels.
1888 /// tc: is our typecontainer (to resolve type references)
1889 /// ig: is the code generator:
1891 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
1893 Report.Debug (64, "BLOCK RESOLVE META", this, Parent, toplevel);
1895 // If some parent block was unsafe, we remain unsafe even if this block
1896 // isn't explicitly marked as such.
1897 using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
1899 // Compute the VariableMap's.
1901 // Unfortunately, we don't know the type when adding variables with
1902 // AddVariable(), so we need to compute this info here.
1906 if (variables != null) {
1907 foreach (LocalInfo li in variables.Values)
1910 locals = new LocalInfo [variables.Count];
1911 variables.Values.CopyTo (locals, 0);
1913 locals = new LocalInfo [0];
1916 local_map = new VariableMap (Parent.LocalMap, locals);
1918 local_map = new VariableMap (locals);
1920 param_map = new VariableMap (ip);
1921 flags |= Flags.VariablesInitialized;
1924 // Process this block variables
1926 if (variables != null) {
1927 foreach (DictionaryEntry de in variables) {
1928 string name = (string) de.Key;
1929 LocalInfo vi = (LocalInfo) de.Value;
1930 Type variable_type = vi.VariableType;
1932 if (variable_type == null)
1935 if (variable_type.IsPointer) {
1937 // Am not really convinced that this test is required (Microsoft does it)
1938 // but the fact is that you would not be able to use the pointer variable
1941 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1946 if (constants == null)
1949 Expression cv = (Expression) constants [name];
1953 // Don't let 'const int Foo = Foo;' succeed.
1954 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
1955 // which in turn causes the 'must be constant' error to be triggered.
1956 constants.Remove (name);
1958 if (!Const.IsConstantTypeValid (variable_type)) {
1959 Const.Error_InvalidConstantType (variable_type, loc);
1963 using (ec.With (EmitContext.Flags.ConstantCheckState, (flags & Flags.Unchecked) == 0)) {
1964 ec.CurrentBlock = this;
1965 Expression e = cv.Resolve (ec);
1969 Constant ce = e as Constant;
1971 Const.Error_ExpressionMustBeConstant (vi.Location, name);
1975 e = ce.ImplicitConversionRequired (variable_type, vi.Location);
1979 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue) {
1980 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
1984 constants.Add (name, e);
1985 vi.IsConstant = true;
1991 // Now, handle the children
1993 if (children != null) {
1994 foreach (Block b in children)
1995 b.ResolveMeta (toplevel, ec, ip);
2001 // Emits the local variable declarations for a block
2003 public virtual void EmitMeta (EmitContext ec)
2005 Report.Debug (64, "BLOCK EMIT META", this, Toplevel, ScopeInfo, ec);
2006 if (ScopeInfo != null) {
2007 scope_init = ScopeInfo.GetScopeInitializer (ec);
2008 Report.Debug (64, "BLOCK EMIT META #1", this, Toplevel, ScopeInfo,
2012 if (variables != null){
2013 foreach (LocalInfo vi in variables.Values)
2014 vi.ResolveVariable (ec);
2017 if (temporary_variables != null) {
2018 foreach (LocalInfo vi in temporary_variables)
2019 vi.ResolveVariable (ec);
2022 if (children != null){
2023 foreach (Block b in children)
2028 void UsageWarning (FlowBranching.UsageVector vector)
2032 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
2033 foreach (DictionaryEntry de in variables){
2034 LocalInfo vi = (LocalInfo) de.Value;
2039 name = (string) de.Key;
2041 // vi.VariableInfo can be null for 'catch' variables
2042 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
2043 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
2045 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
2051 bool unreachable_shown;
2054 private void CheckPossibleMistakenEmptyStatement (Statement s)
2058 // Some statements are wrapped by a Block. Since
2059 // others' internal could be changed, here I treat
2060 // them as possibly wrapped by Block equally.
2061 Block b = s as Block;
2062 if (b != null && b.statements.Count == 1)
2063 s = (Statement) b.statements [0];
2066 body = ((Lock) s).Statement;
2068 body = ((For) s).Statement;
2069 else if (s is Foreach)
2070 body = ((Foreach) s).Statement;
2071 else if (s is While)
2072 body = ((While) s).Statement;
2073 else if (s is Using)
2074 body = ((Using) s).Statement;
2075 else if (s is Fixed)
2076 body = ((Fixed) s).Statement;
2080 if (body == null || body is EmptyStatement)
2081 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
2084 public override bool Resolve (EmitContext ec)
2086 Block prev_block = ec.CurrentBlock;
2089 int errors = Report.Errors;
2091 ec.CurrentBlock = this;
2092 ec.StartFlowBranching (this);
2094 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
2097 // This flag is used to notate nested statements as unreachable from the beginning of this block.
2098 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
2099 // from the beginning of the function. The outer Resolve() that detected the unreachability is
2100 // responsible for handling the situation.
2102 int statement_count = statements.Count;
2103 for (int ix = 0; ix < statement_count; ix++){
2104 Statement s = (Statement) statements [ix];
2105 // Check possible empty statement (CS0642)
2106 if (RootContext.WarningLevel >= 3 &&
2107 ix + 1 < statement_count &&
2108 statements [ix + 1] is Block)
2109 CheckPossibleMistakenEmptyStatement (s);
2112 // Warn if we detect unreachable code.
2115 if (s is EmptyStatement)
2119 ((Block) s).unreachable = true;
2121 if (!unreachable_shown && !(s is LabeledStatement)) {
2122 Report.Warning (162, 2, s.loc, "Unreachable code detected");
2123 unreachable_shown = true;
2128 // Note that we're not using ResolveUnreachable() for unreachable
2129 // statements here. ResolveUnreachable() creates a temporary
2130 // flow branching and kills it afterwards. This leads to problems
2131 // if you have two unreachable statements where the first one
2132 // assigns a variable and the second one tries to access it.
2135 if (!s.Resolve (ec)) {
2137 statements [ix] = EmptyStatement.Value;
2141 if (unreachable && !(s is LabeledStatement) && !(s is Block))
2142 statements [ix] = EmptyStatement.Value;
2144 num_statements = ix + 1;
2146 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
2147 if (unreachable && s is LabeledStatement)
2148 throw new InternalErrorException ("should not happen");
2151 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
2152 ec.CurrentBranching, statement_count, num_statements);
2154 while (ec.CurrentBranching is FlowBranchingLabeled)
2155 ec.EndFlowBranching ();
2157 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
2159 ec.CurrentBlock = prev_block;
2161 // If we're a non-static `struct' constructor which doesn't have an
2162 // initializer, then we must initialize all of the struct's fields.
2163 if ((flags & Flags.IsToplevel) != 0 &&
2164 !Toplevel.IsThisAssigned (ec) &&
2165 !vector.Reachability.AlwaysThrows)
2168 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2169 foreach (LabeledStatement label in labels.Values)
2170 if (!label.HasBeenReferenced)
2171 Report.Warning (164, 2, label.loc,
2172 "This label has not been referenced");
2175 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2177 if (vector.Reachability.IsUnreachable)
2178 flags |= Flags.HasRet;
2180 if (ok && (errors == Report.Errors)) {
2181 if (RootContext.WarningLevel >= 3)
2182 UsageWarning (vector);
2188 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2190 unreachable_shown = true;
2194 Report.Warning (162, 2, loc, "Unreachable code detected");
2196 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2197 bool ok = Resolve (ec);
2198 ec.KillFlowBranching ();
2203 protected override void DoEmit (EmitContext ec)
2205 for (int ix = 0; ix < num_statements; ix++){
2206 Statement s = (Statement) statements [ix];
2208 // Check whether we are the last statement in a
2211 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2212 ec.IsLastStatement = true;
2214 ec.IsLastStatement = false;
2220 public override void Emit (EmitContext ec)
2222 Block prev_block = ec.CurrentBlock;
2224 ec.CurrentBlock = this;
2226 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2227 bool is_lexical_block = !Implicit && (Parent != null);
2229 if (emit_debug_info) {
2230 if (is_lexical_block)
2233 ec.Mark (StartLocation, true);
2234 if (scope_init != null)
2235 scope_init.EmitStatement (ec);
2237 ec.Mark (EndLocation, true);
2239 if (emit_debug_info && is_lexical_block)
2242 ec.CurrentBlock = prev_block;
2246 // Returns true if we ar ea child of `b'.
2248 public bool IsChildOf (Block b)
2250 Block current = this;
2253 if (current.Parent == b)
2255 current = current.Parent;
2256 } while (current != null);
2260 public override string ToString ()
2262 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2267 // A toplevel block contains extra information, the split is done
2268 // only to separate information that would otherwise bloat the more
2269 // lightweight Block.
2271 // In particular, this was introduced when the support for Anonymous
2272 // Methods was implemented.
2274 public class ToplevelBlock : Block {
2276 // Pointer to the host of this anonymous method, or null
2277 // if we are the topmost block
2280 ToplevelBlock child;
2281 GenericMethod generic;
2282 FlowBranchingToplevel top_level_branching;
2283 AnonymousMethodHost anonymous_method_host;
2285 public bool HasVarargs {
2286 get { return (flags & Flags.HasVarargs) != 0; }
2287 set { flags |= Flags.HasVarargs; }
2290 public bool IsIterator {
2291 get { return (flags & Flags.IsIterator) != 0; }
2295 // The parameters for the block.
2297 Parameters parameters;
2298 public Parameters Parameters {
2299 get { return parameters; }
2302 public bool CompleteContexts (EmitContext ec)
2304 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS", this,
2305 container, anonymous_method_host);
2307 if (anonymous_method_host != null)
2308 anonymous_method_host.LinkScopes ();
2310 if ((container == null) && (anonymous_method_host != null)) {
2311 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS #1", this,
2312 anonymous_method_host);
2314 if (anonymous_method_host.DefineType () == null)
2316 if (!anonymous_method_host.ResolveType ())
2318 if (!anonymous_method_host.ResolveMembers ())
2320 if (!anonymous_method_host.DefineMembers ())
2327 public GenericMethod GenericMethod {
2328 get { return generic; }
2331 public ToplevelBlock Container {
2332 get { return container != null ? container.Toplevel : null; }
2335 public Block ContainerBlock {
2336 get { return container; }
2340 // Parent is only used by anonymous blocks to link back to their
2343 public ToplevelBlock (Block container, Parameters parameters, Location start) :
2344 this (container, (Flags) 0, parameters, start)
2348 public ToplevelBlock (Block container, Parameters parameters, GenericMethod generic,
2350 this (container, parameters, start)
2352 this.generic = generic;
2355 public ToplevelBlock (Parameters parameters, Location start) :
2356 this (null, (Flags) 0, parameters, start)
2360 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2361 this (null, flags, parameters, start)
2365 public ToplevelBlock (Block container, Flags flags, Parameters parameters, Location start) :
2366 base (null, flags | Flags.IsToplevel, start, Location.Null)
2368 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2369 this.container = container;
2372 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2376 public bool CheckError158 (string name, Location loc)
2378 if (AnonymousChildren != null) {
2379 foreach (ToplevelBlock child in AnonymousChildren) {
2380 if (!child.CheckError158 (name, loc))
2385 for (ToplevelBlock c = Container; c != null; c = c.Container) {
2386 if (!c.DoCheckError158 (name, loc))
2393 bool DoCheckError158 (string name, Location loc)
2395 LabeledStatement s = LookupLabel (name);
2397 Error_158 (name, loc);
2404 public AnonymousMethodHost CreateAnonymousMethodHost (TypeContainer host)
2406 if (anonymous_method_host != null)
2407 return anonymous_method_host;
2409 if (Container != null)
2410 anonymous_method_host = new AnonymousMethodHost (
2411 this, Container.anonymous_method_host, null, StartLocation);
2413 anonymous_method_host = new AnonymousMethodHost (
2414 this, host, generic, StartLocation);
2416 ScopeInfo = anonymous_method_host;
2417 return anonymous_method_host;
2420 public void CreateIteratorHost (AnonymousMethodHost root_scope)
2422 Report.Debug (64, "CREATE ITERATOR HOST", this, root_scope,
2423 container, anonymous_method_host);
2425 if ((container != null) || (anonymous_method_host != null))
2426 throw new InternalErrorException ();
2428 ScopeInfo = anonymous_method_host = root_scope;
2431 public AnonymousMethodHost AnonymousMethodHost {
2433 if (anonymous_method_host != null)
2434 return anonymous_method_host;
2435 else if (Container != null)
2436 return Container.AnonymousMethodHost;
2442 public void EmitScopeInstance (EmitContext ec, ScopeInfo scope)
2444 AnonymousMethodHost root_scope = AnonymousMethodHost;
2446 root_scope.EmitScopeInstance (ec);
2447 while (root_scope != scope.Host) {
2448 ec.ig.Emit (OpCodes.Ldfld, root_scope.ParentLink.FieldBuilder);
2449 root_scope = root_scope.ParentHost;
2451 if (root_scope == null)
2452 throw new InternalErrorException (
2453 "Never found scope {0} starting at block {1}",
2454 scope, ec.CurrentBlock.ID);
2457 if (scope != scope.Host)
2458 scope.ScopeInstance.Emit (ec);
2461 public FlowBranchingToplevel TopLevelBranching {
2462 get { return top_level_branching; }
2466 // This is used if anonymous methods are used inside an iterator
2467 // (see 2test-22.cs for an example).
2469 // The AnonymousMethod is created while parsing - at a time when we don't
2470 // know yet that we're inside an iterator, so it's `Container' is initially
2471 // null. Later on, when resolving the iterator, we need to move the
2472 // anonymous method into that iterator.
2474 public void ReParent (ToplevelBlock new_parent)
2476 container = new_parent;
2477 Parent = new_parent;
2478 new_parent.child = this;
2481 if (container != null)
2482 container.AddAnonymousChild (this);
2487 // Returns a `ParameterReference' for the given name, or null if there
2488 // is no such parameter
2490 public ParameterReference GetParameterReference (string name, Location loc)
2495 for (ToplevelBlock t = this; t != null; t = t.Container) {
2496 Parameters pars = t.Parameters;
2497 par = pars.GetParameterByName (name, out idx);
2499 return new ParameterReference (par, this, idx, loc);
2505 // Whether the parameter named `name' is local to this block,
2506 // or false, if the parameter belongs to an encompassing block.
2508 public bool IsLocalParameter (string name)
2510 return Parameters.GetParameterByName (name) != null;
2514 // Whether the `name' is a parameter reference
2516 public bool IsParameterReference (string name)
2518 for (ToplevelBlock t = this; t != null; t = t.Container) {
2519 if (t.IsLocalParameter (name))
2525 LocalInfo this_variable = null;
2528 // Returns the "this" instance variable of this block.
2529 // See AddThisVariable() for more information.
2531 public LocalInfo ThisVariable {
2532 get { return this_variable; }
2537 // This is used by non-static `struct' constructors which do not have an
2538 // initializer - in this case, the constructor must initialize all of the
2539 // struct's fields. To do this, we add a "this" variable and use the flow
2540 // analysis code to ensure that it's been fully initialized before control
2541 // leaves the constructor.
2543 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2545 if (this_variable == null) {
2546 this_variable = new LocalInfo (ds, this, l);
2547 this_variable.Used = true;
2548 this_variable.IsThis = true;
2550 Variables.Add ("this", this_variable);
2553 return this_variable;
2556 public bool IsThisAssigned (EmitContext ec)
2558 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2561 public bool ResolveMeta (EmitContext ec, Parameters ip)
2563 int errors = Report.Errors;
2565 if (top_level_branching != null)
2571 if (!IsIterator && (container != null) && (parameters != null)) {
2572 foreach (Parameter p in parameters.FixedParameters) {
2573 if (!CheckError136_InParents (p.Name, loc))
2578 ResolveMeta (this, ec, ip);
2581 child.ResolveMeta (this, ec, ip);
2583 top_level_branching = ec.StartFlowBranching (this);
2585 return Report.Errors == errors;
2588 public override void EmitMeta (EmitContext ec)
2591 parameters.ResolveVariable (this);
2594 public void MakeIterator (Iterator iterator)
2596 flags |= Flags.IsIterator;
2598 Block block = new Block (this);
2599 foreach (Statement stmt in statements)
2600 block.AddStatement (stmt);
2601 statements = new ArrayList ();
2602 statements.Add (new MoveNextStatement (iterator, block));
2605 protected class MoveNextStatement : Statement {
2609 public MoveNextStatement (Iterator iterator, Block block)
2611 this.iterator = iterator;
2613 this.loc = iterator.Location;
2616 public override bool Resolve (EmitContext ec)
2618 return block.Resolve (ec);
2621 protected override void DoEmit (EmitContext ec)
2623 iterator.EmitMoveNext (ec, block);
2627 public override string ToString ()
2629 return String.Format ("{0} ({1}:{2}{3})", GetType (), ID, StartLocation,
2630 anonymous_method_host);
2634 public class SwitchLabel {
2641 Label il_label_code;
2642 bool il_label_code_set;
2644 public static readonly object NullStringCase = new object ();
2647 // if expr == null, then it is the default case.
2649 public SwitchLabel (Expression expr, Location l)
2655 public Expression Label {
2661 public object Converted {
2667 public Label GetILLabel (EmitContext ec)
2670 il_label = ec.ig.DefineLabel ();
2671 il_label_set = true;
2676 public Label GetILLabelCode (EmitContext ec)
2678 if (!il_label_code_set){
2679 il_label_code = ec.ig.DefineLabel ();
2680 il_label_code_set = true;
2682 return il_label_code;
2686 // Resolves the expression, reduces it to a literal if possible
2687 // and then converts it to the requested type.
2689 public bool ResolveAndReduce (EmitContext ec, Type required_type, bool allow_nullable)
2691 Expression e = label.Resolve (ec);
2696 Constant c = e as Constant;
2698 Report.Error (150, loc, "A constant value is expected");
2702 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2703 converted = NullStringCase;
2707 if (allow_nullable && c.GetValue () == null) {
2708 converted = NullStringCase;
2712 c = c.ImplicitConversionRequired (required_type, loc);
2716 converted = c.GetValue ();
2720 public void Erorr_AlreadyOccurs ()
2723 if (converted == null)
2725 else if (converted == NullStringCase)
2728 label = converted.ToString ();
2730 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2734 public class SwitchSection {
2735 // An array of SwitchLabels.
2736 public readonly ArrayList Labels;
2737 public readonly Block Block;
2739 public SwitchSection (ArrayList labels, Block block)
2746 public class Switch : Statement {
2747 public readonly ArrayList Sections;
2748 public Expression Expr;
2751 /// Maps constants whose type type SwitchType to their SwitchLabels.
2753 public IDictionary Elements;
2756 /// The governing switch type
2758 public Type SwitchType;
2763 Label default_target;
2765 Expression new_expr;
2767 SwitchSection constant_section;
2768 SwitchSection default_section;
2772 // Nullable Types support for GMCS.
2774 Nullable.Unwrap unwrap;
2776 protected bool HaveUnwrap {
2777 get { return unwrap != null; }
2780 protected bool HaveUnwrap {
2781 get { return false; }
2786 // The types allowed to be implicitly cast from
2787 // on the governing type
2789 static Type [] allowed_types;
2791 public Switch (Expression e, ArrayList sects, Location l)
2798 public bool GotDefault {
2800 return default_section != null;
2804 public Label DefaultTarget {
2806 return default_target;
2811 // Determines the governing type for a switch. The returned
2812 // expression might be the expression from the switch, or an
2813 // expression that includes any potential conversions to the
2814 // integral types or to string.
2816 Expression SwitchGoverningType (EmitContext ec, Expression expr)
2820 if (t == TypeManager.byte_type ||
2821 t == TypeManager.sbyte_type ||
2822 t == TypeManager.ushort_type ||
2823 t == TypeManager.short_type ||
2824 t == TypeManager.uint32_type ||
2825 t == TypeManager.int32_type ||
2826 t == TypeManager.uint64_type ||
2827 t == TypeManager.int64_type ||
2828 t == TypeManager.char_type ||
2829 t == TypeManager.string_type ||
2830 t == TypeManager.bool_type ||
2831 t.IsSubclassOf (TypeManager.enum_type))
2834 if (allowed_types == null){
2835 allowed_types = new Type [] {
2836 TypeManager.sbyte_type,
2837 TypeManager.byte_type,
2838 TypeManager.short_type,
2839 TypeManager.ushort_type,
2840 TypeManager.int32_type,
2841 TypeManager.uint32_type,
2842 TypeManager.int64_type,
2843 TypeManager.uint64_type,
2844 TypeManager.char_type,
2845 TypeManager.string_type,
2846 TypeManager.bool_type
2851 // Try to find a *user* defined implicit conversion.
2853 // If there is no implicit conversion, or if there are multiple
2854 // conversions, we have to report an error
2856 Expression converted = null;
2857 foreach (Type tt in allowed_types){
2860 e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
2865 // Ignore over-worked ImplicitUserConversions that do
2866 // an implicit conversion in addition to the user conversion.
2868 if (!(e is UserCast))
2871 if (converted != null){
2872 Report.ExtraInformation (
2874 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2875 TypeManager.CSharpName (expr.Type)));
2885 // Performs the basic sanity checks on the switch statement
2886 // (looks for duplicate keys and non-constant expressions).
2888 // It also returns a hashtable with the keys that we will later
2889 // use to compute the switch tables
2891 bool CheckSwitch (EmitContext ec)
2894 Elements = Sections.Count > 10 ?
2895 (IDictionary)new Hashtable () :
2896 (IDictionary)new ListDictionary ();
2898 foreach (SwitchSection ss in Sections){
2899 foreach (SwitchLabel sl in ss.Labels){
2900 if (sl.Label == null){
2901 if (default_section != null){
2902 sl.Erorr_AlreadyOccurs ();
2905 default_section = ss;
2909 if (!sl.ResolveAndReduce (ec, SwitchType, HaveUnwrap)) {
2914 object key = sl.Converted;
2916 Elements.Add (key, sl);
2917 } catch (ArgumentException) {
2918 sl.Erorr_AlreadyOccurs ();
2926 void EmitObjectInteger (ILGenerator ig, object k)
2929 IntConstant.EmitInt (ig, (int) k);
2930 else if (k is Constant) {
2931 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2934 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2937 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2939 IntConstant.EmitInt (ig, (int) (long) k);
2940 ig.Emit (OpCodes.Conv_I8);
2943 LongConstant.EmitLong (ig, (long) k);
2945 else if (k is ulong)
2947 ulong ul = (ulong) k;
2950 IntConstant.EmitInt (ig, unchecked ((int) ul));
2951 ig.Emit (OpCodes.Conv_U8);
2955 LongConstant.EmitLong (ig, unchecked ((long) ul));
2959 IntConstant.EmitInt (ig, (int) ((char) k));
2960 else if (k is sbyte)
2961 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2963 IntConstant.EmitInt (ig, (int) ((byte) k));
2964 else if (k is short)
2965 IntConstant.EmitInt (ig, (int) ((short) k));
2966 else if (k is ushort)
2967 IntConstant.EmitInt (ig, (int) ((ushort) k));
2969 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2971 throw new Exception ("Unhandled case");
2974 // structure used to hold blocks of keys while calculating table switch
2975 class KeyBlock : IComparable
2977 public KeyBlock (long _nFirst)
2979 nFirst = nLast = _nFirst;
2983 public ArrayList rgKeys = null;
2984 // how many items are in the bucket
2985 public int Size = 1;
2988 get { return (int) (nLast - nFirst + 1); }
2990 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2992 return kbLast.nLast - kbFirst.nFirst + 1;
2994 public int CompareTo (object obj)
2996 KeyBlock kb = (KeyBlock) obj;
2997 int nLength = Length;
2998 int nLengthOther = kb.Length;
2999 if (nLengthOther == nLength)
3000 return (int) (kb.nFirst - nFirst);
3001 return nLength - nLengthOther;
3006 /// This method emits code for a lookup-based switch statement (non-string)
3007 /// Basically it groups the cases into blocks that are at least half full,
3008 /// and then spits out individual lookup opcodes for each block.
3009 /// It emits the longest blocks first, and short blocks are just
3010 /// handled with direct compares.
3012 /// <param name="ec"></param>
3013 /// <param name="val"></param>
3014 /// <returns></returns>
3015 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
3017 int cElements = Elements.Count;
3018 object [] rgKeys = new object [cElements];
3019 Elements.Keys.CopyTo (rgKeys, 0);
3020 Array.Sort (rgKeys);
3022 // initialize the block list with one element per key
3023 ArrayList rgKeyBlocks = new ArrayList ();
3024 foreach (object key in rgKeys)
3025 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
3028 // iteratively merge the blocks while they are at least half full
3029 // there's probably a really cool way to do this with a tree...
3030 while (rgKeyBlocks.Count > 1)
3032 ArrayList rgKeyBlocksNew = new ArrayList ();
3033 kbCurr = (KeyBlock) rgKeyBlocks [0];
3034 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3036 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3037 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3040 kbCurr.nLast = kb.nLast;
3041 kbCurr.Size += kb.Size;
3045 // start a new block
3046 rgKeyBlocksNew.Add (kbCurr);
3050 rgKeyBlocksNew.Add (kbCurr);
3051 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3053 rgKeyBlocks = rgKeyBlocksNew;
3056 // initialize the key lists
3057 foreach (KeyBlock kb in rgKeyBlocks)
3058 kb.rgKeys = new ArrayList ();
3060 // fill the key lists
3062 if (rgKeyBlocks.Count > 0) {
3063 kbCurr = (KeyBlock) rgKeyBlocks [0];
3064 foreach (object key in rgKeys)
3066 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
3067 System.Convert.ToInt64 (key) > kbCurr.nLast;
3069 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3070 kbCurr.rgKeys.Add (key);
3074 // sort the blocks so we can tackle the largest ones first
3075 rgKeyBlocks.Sort ();
3077 // okay now we can start...
3078 ILGenerator ig = ec.ig;
3079 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3080 Label lblDefault = ig.DefineLabel ();
3082 Type typeKeys = null;
3083 if (rgKeys.Length > 0)
3084 typeKeys = rgKeys [0].GetType (); // used for conversions
3088 if (TypeManager.IsEnumType (SwitchType))
3089 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3091 compare_type = SwitchType;
3093 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3095 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3096 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3099 foreach (object key in kb.rgKeys)
3101 ig.Emit (OpCodes.Ldloc, val);
3102 EmitObjectInteger (ig, key);
3103 SwitchLabel sl = (SwitchLabel) Elements [key];
3104 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
3109 // TODO: if all the keys in the block are the same and there are
3110 // no gaps/defaults then just use a range-check.
3111 if (compare_type == TypeManager.int64_type ||
3112 compare_type == TypeManager.uint64_type)
3114 // TODO: optimize constant/I4 cases
3116 // check block range (could be > 2^31)
3117 ig.Emit (OpCodes.Ldloc, val);
3118 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3119 ig.Emit (OpCodes.Blt, lblDefault);
3120 ig.Emit (OpCodes.Ldloc, val);
3121 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
3122 ig.Emit (OpCodes.Bgt, lblDefault);
3125 ig.Emit (OpCodes.Ldloc, val);
3128 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3129 ig.Emit (OpCodes.Sub);
3131 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3136 ig.Emit (OpCodes.Ldloc, val);
3137 int nFirst = (int) kb.nFirst;
3140 IntConstant.EmitInt (ig, nFirst);
3141 ig.Emit (OpCodes.Sub);
3143 else if (nFirst < 0)
3145 IntConstant.EmitInt (ig, -nFirst);
3146 ig.Emit (OpCodes.Add);
3150 // first, build the list of labels for the switch
3152 int cJumps = kb.Length;
3153 Label [] rgLabels = new Label [cJumps];
3154 for (int iJump = 0; iJump < cJumps; iJump++)
3156 object key = kb.rgKeys [iKey];
3157 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
3159 SwitchLabel sl = (SwitchLabel) Elements [key];
3160 rgLabels [iJump] = sl.GetILLabel (ec);
3164 rgLabels [iJump] = lblDefault;
3166 // emit the switch opcode
3167 ig.Emit (OpCodes.Switch, rgLabels);
3170 // mark the default for this block
3172 ig.MarkLabel (lblDefault);
3175 // TODO: find the default case and emit it here,
3176 // to prevent having to do the following jump.
3177 // make sure to mark other labels in the default section
3179 // the last default just goes to the end
3180 ig.Emit (OpCodes.Br, lblDefault);
3182 // now emit the code for the sections
3183 bool fFoundDefault = false;
3184 bool fFoundNull = false;
3185 foreach (SwitchSection ss in Sections)
3187 foreach (SwitchLabel sl in ss.Labels)
3188 if (sl.Converted == SwitchLabel.NullStringCase)
3192 foreach (SwitchSection ss in Sections)
3194 foreach (SwitchLabel sl in ss.Labels)
3196 ig.MarkLabel (sl.GetILLabel (ec));
3197 ig.MarkLabel (sl.GetILLabelCode (ec));
3198 if (sl.Converted == SwitchLabel.NullStringCase)
3199 ig.MarkLabel (null_target);
3200 else if (sl.Label == null) {
3201 ig.MarkLabel (lblDefault);
3202 fFoundDefault = true;
3204 ig.MarkLabel (null_target);
3210 if (!fFoundDefault) {
3211 ig.MarkLabel (lblDefault);
3213 ig.MarkLabel (lblEnd);
3216 // This simple emit switch works, but does not take advantage of the
3218 // TODO: remove non-string logic from here
3219 // TODO: binary search strings?
3221 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3223 ILGenerator ig = ec.ig;
3224 Label end_of_switch = ig.DefineLabel ();
3225 Label next_test = ig.DefineLabel ();
3226 bool first_test = true;
3227 bool pending_goto_end = false;
3228 bool null_marked = false;
3231 ig.Emit (OpCodes.Ldloc, val);
3233 if (Elements.Contains (SwitchLabel.NullStringCase)){
3234 ig.Emit (OpCodes.Brfalse, null_target);
3236 ig.Emit (OpCodes.Brfalse, default_target);
3238 ig.Emit (OpCodes.Ldloc, val);
3239 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3240 ig.Emit (OpCodes.Stloc, val);
3242 int section_count = Sections.Count;
3243 for (int section = 0; section < section_count; section++){
3244 SwitchSection ss = (SwitchSection) Sections [section];
3246 if (ss == default_section)
3249 Label sec_begin = ig.DefineLabel ();
3251 ig.Emit (OpCodes.Nop);
3253 if (pending_goto_end)
3254 ig.Emit (OpCodes.Br, end_of_switch);
3256 int label_count = ss.Labels.Count;
3258 for (int label = 0; label < label_count; label++){
3259 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
3260 ig.MarkLabel (sl.GetILLabel (ec));
3263 ig.MarkLabel (next_test);
3264 next_test = ig.DefineLabel ();
3267 // If we are the default target
3269 if (sl.Label != null){
3270 object lit = sl.Converted;
3272 if (lit == SwitchLabel.NullStringCase){
3274 if (label + 1 == label_count)
3275 ig.Emit (OpCodes.Br, next_test);
3279 ig.Emit (OpCodes.Ldloc, val);
3280 ig.Emit (OpCodes.Ldstr, (string)lit);
3281 if (label_count == 1)
3282 ig.Emit (OpCodes.Bne_Un, next_test);
3284 if (label+1 == label_count)
3285 ig.Emit (OpCodes.Bne_Un, next_test);
3287 ig.Emit (OpCodes.Beq, sec_begin);
3292 ig.MarkLabel (null_target);
3295 ig.MarkLabel (sec_begin);
3296 foreach (SwitchLabel sl in ss.Labels)
3297 ig.MarkLabel (sl.GetILLabelCode (ec));
3300 pending_goto_end = !ss.Block.HasRet;
3303 ig.MarkLabel (next_test);
3304 ig.MarkLabel (default_target);
3306 ig.MarkLabel (null_target);
3307 if (default_section != null)
3308 default_section.Block.Emit (ec);
3309 ig.MarkLabel (end_of_switch);
3312 SwitchSection FindSection (SwitchLabel label)
3314 foreach (SwitchSection ss in Sections){
3315 foreach (SwitchLabel sl in ss.Labels){
3324 public override bool Resolve (EmitContext ec)
3326 Expr = Expr.Resolve (ec);
3330 new_expr = SwitchGoverningType (ec, Expr);
3333 if ((new_expr == null) && TypeManager.IsNullableType (Expr.Type)) {
3334 unwrap = Nullable.Unwrap.Create (Expr, ec);
3338 new_expr = SwitchGoverningType (ec, unwrap);
3342 if (new_expr == null){
3343 Report.Error (151, loc, "A value of an integral type or string expected for switch");
3348 SwitchType = new_expr.Type;
3350 if (!CheckSwitch (ec))
3354 Elements.Remove (SwitchLabel.NullStringCase);
3356 Switch old_switch = ec.Switch;
3358 ec.Switch.SwitchType = SwitchType;
3360 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3361 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3363 is_constant = new_expr is Constant;
3365 object key = ((Constant) new_expr).GetValue ();
3366 SwitchLabel label = (SwitchLabel) Elements [key];
3368 constant_section = FindSection (label);
3369 if (constant_section == null)
3370 constant_section = default_section;
3374 foreach (SwitchSection ss in Sections){
3376 ec.CurrentBranching.CreateSibling (
3377 null, FlowBranching.SiblingType.SwitchSection);
3381 if (is_constant && (ss != constant_section)) {
3382 // If we're a constant switch, we're only emitting
3383 // one single section - mark all the others as
3385 ec.CurrentBranching.CurrentUsageVector.Goto ();
3386 if (!ss.Block.ResolveUnreachable (ec, true))
3389 if (!ss.Block.Resolve (ec))
3394 if (default_section == null)
3395 ec.CurrentBranching.CreateSibling (
3396 null, FlowBranching.SiblingType.SwitchSection);
3398 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3399 ec.Switch = old_switch;
3401 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3407 protected override void DoEmit (EmitContext ec)
3409 ILGenerator ig = ec.ig;
3411 default_target = ig.DefineLabel ();
3412 null_target = ig.DefineLabel ();
3414 // Store variable for comparission purposes
3417 value = ig.DeclareLocal (SwitchType);
3419 unwrap.EmitCheck (ec);
3420 ig.Emit (OpCodes.Brfalse, null_target);
3422 ig.Emit (OpCodes.Stloc, value);
3424 } else if (!is_constant) {
3425 value = ig.DeclareLocal (SwitchType);
3427 ig.Emit (OpCodes.Stloc, value);
3432 // Setup the codegen context
3434 Label old_end = ec.LoopEnd;
3435 Switch old_switch = ec.Switch;
3437 ec.LoopEnd = ig.DefineLabel ();
3442 if (constant_section != null)
3443 constant_section.Block.Emit (ec);
3444 } else if (SwitchType == TypeManager.string_type)
3445 SimpleSwitchEmit (ec, value);
3447 TableSwitchEmit (ec, value);
3449 // Restore context state.
3450 ig.MarkLabel (ec.LoopEnd);
3453 // Restore the previous context
3455 ec.LoopEnd = old_end;
3456 ec.Switch = old_switch;
3460 public abstract class ExceptionStatement : Statement
3462 public abstract void EmitFinally (EmitContext ec);
3464 protected bool emit_finally = true;
3465 ArrayList parent_vectors;
3467 protected void DoEmitFinally (EmitContext ec)
3470 ec.ig.BeginFinallyBlock ();
3471 else if (ec.InIterator)
3472 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3476 protected void ResolveFinally (FlowBranchingException branching)
3478 emit_finally = branching.EmitFinally;
3480 branching.Parent.StealFinallyClauses (ref parent_vectors);
3484 public class Lock : ExceptionStatement {
3486 public Statement Statement;
3487 TemporaryVariable temp;
3489 public Lock (Expression expr, Statement stmt, Location l)
3496 public override bool Resolve (EmitContext ec)
3498 expr = expr.Resolve (ec);
3502 if (expr.Type.IsValueType){
3503 Report.Error (185, loc,
3504 "`{0}' is not a reference type as required by the lock statement",
3505 TypeManager.CSharpName (expr.Type));
3509 FlowBranchingException branching = ec.StartFlowBranching (this);
3510 bool ok = Statement.Resolve (ec);
3512 ec.KillFlowBranching ();
3516 ResolveFinally (branching);
3518 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3519 if (!reachability.AlwaysReturns) {
3520 // Unfortunately, System.Reflection.Emit automatically emits
3521 // a leave to the end of the finally block.
3522 // This is a problem if `returns' is true since we may jump
3523 // to a point after the end of the method.
3524 // As a workaround, emit an explicit ret here.
3525 ec.NeedReturnLabel ();
3528 // Avoid creating libraries that reference the internal
3531 if (t == TypeManager.null_type)
3532 t = TypeManager.object_type;
3534 temp = new TemporaryVariable (t, loc);
3540 protected override void DoEmit (EmitContext ec)
3542 ILGenerator ig = ec.ig;
3544 temp.Store (ec, expr);
3546 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3550 ig.BeginExceptionBlock ();
3551 Statement.Emit (ec);
3556 ig.EndExceptionBlock ();
3559 public override void EmitFinally (EmitContext ec)
3562 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3566 public class Unchecked : Statement {
3567 public readonly Block Block;
3569 public Unchecked (Block b)
3575 public override bool Resolve (EmitContext ec)
3577 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3578 return Block.Resolve (ec);
3581 protected override void DoEmit (EmitContext ec)
3583 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3588 public class Checked : Statement {
3589 public readonly Block Block;
3591 public Checked (Block b)
3594 b.Unchecked = false;
3597 public override bool Resolve (EmitContext ec)
3599 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3600 return Block.Resolve (ec);
3603 protected override void DoEmit (EmitContext ec)
3605 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3610 public class Unsafe : Statement {
3611 public readonly Block Block;
3613 public Unsafe (Block b)
3616 Block.Unsafe = true;
3619 public override bool Resolve (EmitContext ec)
3621 using (ec.With (EmitContext.Flags.InUnsafe, true))
3622 return Block.Resolve (ec);
3625 protected override void DoEmit (EmitContext ec)
3627 using (ec.With (EmitContext.Flags.InUnsafe, true))
3635 public class Fixed : Statement {
3637 ArrayList declarators;
3638 Statement statement;
3643 abstract class Emitter
3645 protected LocalInfo vi;
3646 protected Expression converted;
3648 protected Emitter (Expression expr, LocalInfo li)
3654 public abstract void Emit (EmitContext ec);
3655 public abstract void EmitExit (EmitContext ec);
3658 class ExpressionEmitter : Emitter {
3659 public ExpressionEmitter (Expression converted, LocalInfo li) :
3660 base (converted, li)
3664 public override void Emit (EmitContext ec) {
3666 // Store pointer in pinned location
3668 converted.Emit (ec);
3669 vi.Variable.EmitAssign (ec);
3672 public override void EmitExit (EmitContext ec)
3674 ec.ig.Emit (OpCodes.Ldc_I4_0);
3675 ec.ig.Emit (OpCodes.Conv_U);
3676 vi.Variable.EmitAssign (ec);
3680 class StringEmitter : Emitter {
3681 LocalBuilder pinned_string;
3684 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3690 public override void Emit (EmitContext ec)
3692 ILGenerator ig = ec.ig;
3693 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3695 converted.Emit (ec);
3696 ig.Emit (OpCodes.Stloc, pinned_string);
3698 Expression sptr = new StringPtr (pinned_string, loc);
3699 converted = Convert.ImplicitConversionRequired (
3700 ec, sptr, vi.VariableType, loc);
3702 if (converted == null)
3705 converted.Emit (ec);
3706 vi.Variable.EmitAssign (ec);
3709 public override void EmitExit (EmitContext ec)
3711 ec.ig.Emit (OpCodes.Ldnull);
3712 ec.ig.Emit (OpCodes.Stloc, pinned_string);
3716 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3719 declarators = decls;
3724 public Statement Statement {
3725 get { return statement; }
3728 public override bool Resolve (EmitContext ec)
3731 Expression.UnsafeError (loc);
3735 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3739 expr_type = texpr.Type;
3741 data = new Emitter [declarators.Count];
3743 if (!expr_type.IsPointer){
3744 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3749 foreach (Pair p in declarators){
3750 LocalInfo vi = (LocalInfo) p.First;
3751 Expression e = (Expression) p.Second;
3753 vi.VariableInfo.SetAssigned (ec);
3754 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3757 // The rules for the possible declarators are pretty wise,
3758 // but the production on the grammar is more concise.
3760 // So we have to enforce these rules here.
3762 // We do not resolve before doing the case 1 test,
3763 // because the grammar is explicit in that the token &
3764 // is present, so we need to test for this particular case.
3768 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3773 // Case 1: & object.
3775 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3776 Expression child = ((Unary) e).Expr;
3778 if (child is ParameterReference || child is LocalVariableReference){
3781 "No need to use fixed statement for parameters or " +
3782 "local variable declarations (address is already " +
3787 ec.InFixedInitializer = true;
3789 ec.InFixedInitializer = false;
3793 child = ((Unary) e).Expr;
3795 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3798 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
3799 e.Error_ValueCannotBeConverted (e.Location, expr_type, false);
3803 data [i] = new ExpressionEmitter (e, vi);
3809 ec.InFixedInitializer = true;
3811 ec.InFixedInitializer = false;
3818 if (e.Type.IsArray){
3819 Type array_type = TypeManager.GetElementType (e.Type);
3822 // Provided that array_type is unmanaged,
3824 if (!TypeManager.VerifyUnManaged (array_type, loc))
3828 // and T* is implicitly convertible to the
3829 // pointer type given in the fixed statement.
3831 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3833 Expression converted = Convert.ImplicitConversionRequired (
3834 ec, array_ptr, vi.VariableType, loc);
3835 if (converted == null)
3838 data [i] = new ExpressionEmitter (converted, vi);
3847 if (e.Type == TypeManager.string_type){
3848 data [i] = new StringEmitter (e, vi, loc);
3853 // Case 4: fixed buffer
3854 FieldExpr fe = e as FieldExpr;
3856 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3858 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3860 Expression converted = Convert.ImplicitConversionRequired (
3861 ec, fixed_buffer_ptr, vi.VariableType, loc);
3862 if (converted == null)
3865 data [i] = new ExpressionEmitter (converted, vi);
3873 // For other cases, flag a `this is already fixed expression'
3875 if (e is LocalVariableReference || e is ParameterReference ||
3876 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3878 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3882 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3886 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3888 if (!statement.Resolve (ec)) {
3889 ec.KillFlowBranching ();
3893 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3894 has_ret = reachability.IsUnreachable;
3899 protected override void DoEmit (EmitContext ec)
3901 for (int i = 0; i < data.Length; i++) {
3905 statement.Emit (ec);
3911 // Clear the pinned variable
3913 for (int i = 0; i < data.Length; i++) {
3914 data [i].EmitExit (ec);
3919 public class Catch : Statement {
3920 public readonly string Name;
3921 public readonly Block Block;
3922 public readonly Block VarBlock;
3924 Expression type_expr;
3927 public Catch (Expression type, string name, Block block, Block var_block, Location l)
3932 VarBlock = var_block;
3936 public Type CatchType {
3942 public bool IsGeneral {
3944 return type_expr == null;
3948 protected override void DoEmit(EmitContext ec)
3950 ILGenerator ig = ec.ig;
3952 if (CatchType != null)
3953 ig.BeginCatchBlock (CatchType);
3955 ig.BeginCatchBlock (TypeManager.object_type);
3957 if (VarBlock != null)
3961 LocalInfo vi = Block.GetLocalInfo (Name);
3963 throw new Exception ("Variable does not exist in this block");
3965 if (vi.Variable.NeedsTemporary) {
3966 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
3967 ig.Emit (OpCodes.Stloc, e);
3969 vi.Variable.EmitInstance (ec);
3970 ig.Emit (OpCodes.Ldloc, e);
3971 vi.Variable.EmitAssign (ec);
3973 vi.Variable.EmitAssign (ec);
3975 ig.Emit (OpCodes.Pop);
3980 public override bool Resolve (EmitContext ec)
3982 using (ec.With (EmitContext.Flags.InCatch, true)) {
3983 if (type_expr != null) {
3984 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3990 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3991 Error (155, "The type caught or thrown must be derived from System.Exception");
3997 if (!Block.Resolve (ec))
4000 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
4001 // emit the "unused variable" warnings.
4002 if (VarBlock != null)
4003 return VarBlock.Resolve (ec);
4010 public class Try : ExceptionStatement {
4011 public readonly Block Fini, Block;
4012 public readonly ArrayList Specific;
4013 public readonly Catch General;
4015 bool need_exc_block;
4018 // specific, general and fini might all be null.
4020 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4022 if (specific == null && general == null){
4023 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4027 this.Specific = specific;
4028 this.General = general;
4033 public override bool Resolve (EmitContext ec)
4037 FlowBranchingException branching = ec.StartFlowBranching (this);
4039 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4041 if (!Block.Resolve (ec))
4044 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4046 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4048 Type[] prevCatches = new Type [Specific.Count];
4050 foreach (Catch c in Specific){
4051 ec.CurrentBranching.CreateSibling (
4052 c.Block, FlowBranching.SiblingType.Catch);
4054 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4056 if (c.Name != null) {
4057 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
4059 throw new Exception ();
4061 vi.VariableInfo = null;
4064 if (!c.Resolve (ec))
4067 Type resolvedType = c.CatchType;
4068 for (int ii = 0; ii < last_index; ++ii) {
4069 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
4070 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
4075 prevCatches [last_index++] = resolvedType;
4076 need_exc_block = true;
4079 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4081 if (General != null){
4082 if (CodeGen.Assembly.WrapNonExceptionThrows) {
4083 foreach (Catch c in Specific){
4084 if (c.CatchType == TypeManager.exception_type) {
4085 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'");
4090 ec.CurrentBranching.CreateSibling (
4091 General.Block, FlowBranching.SiblingType.Catch);
4093 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4095 if (!General.Resolve (ec))
4098 need_exc_block = true;
4101 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4105 ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
4107 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4108 using (ec.With (EmitContext.Flags.InFinally, true)) {
4109 if (!Fini.Resolve (ec))
4114 need_exc_block = true;
4117 if (ec.InIterator) {
4118 ResolveFinally (branching);
4119 need_exc_block |= emit_finally;
4121 emit_finally = Fini != null;
4123 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4125 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4127 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
4129 if (!reachability.AlwaysReturns) {
4130 // Unfortunately, System.Reflection.Emit automatically emits
4131 // a leave to the end of the finally block. This is a problem
4132 // if `returns' is true since we may jump to a point after the
4133 // end of the method.
4134 // As a workaround, emit an explicit ret here.
4135 ec.NeedReturnLabel ();
4141 protected override void DoEmit (EmitContext ec)
4143 ILGenerator ig = ec.ig;
4146 ig.BeginExceptionBlock ();
4149 foreach (Catch c in Specific)
4152 if (General != null)
4157 ig.EndExceptionBlock ();
4160 public override void EmitFinally (EmitContext ec)
4166 public bool HasCatch
4169 return General != null || Specific.Count > 0;
4174 public class Using : ExceptionStatement {
4175 object expression_or_block;
4176 public Statement Statement;
4180 Expression [] resolved_vars;
4181 Expression [] converted_vars;
4182 ExpressionStatement [] assign;
4183 TemporaryVariable local_copy;
4185 public Using (object expression_or_block, Statement stmt, Location l)
4187 this.expression_or_block = expression_or_block;
4193 // Resolves for the case of using using a local variable declaration.
4195 bool ResolveLocalVariableDecls (EmitContext ec)
4199 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
4203 expr_type = texpr.Type;
4206 // The type must be an IDisposable or an implicit conversion
4209 converted_vars = new Expression [var_list.Count];
4210 resolved_vars = new Expression [var_list.Count];
4211 assign = new ExpressionStatement [var_list.Count];
4213 bool need_conv = !TypeManager.ImplementsInterface (
4214 expr_type, TypeManager.idisposable_type);
4216 foreach (DictionaryEntry e in var_list){
4217 Expression var = (Expression) e.Key;
4219 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
4223 resolved_vars [i] = var;
4230 converted_vars [i] = Convert.ImplicitConversion (
4231 ec, var, TypeManager.idisposable_type, loc);
4233 if (converted_vars [i] == null) {
4234 Error_IsNotConvertibleToIDisposable ();
4242 foreach (DictionaryEntry e in var_list){
4243 Expression var = resolved_vars [i];
4244 Expression new_expr = (Expression) e.Value;
4247 a = new Assign (var, new_expr, loc);
4253 converted_vars [i] = var;
4254 assign [i] = (ExpressionStatement) a;
4261 void Error_IsNotConvertibleToIDisposable ()
4263 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
4264 TypeManager.CSharpName (expr_type));
4267 bool ResolveExpression (EmitContext ec)
4269 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4270 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
4271 Error_IsNotConvertibleToIDisposable ();
4276 local_copy = new TemporaryVariable (expr_type, loc);
4277 local_copy.Resolve (ec);
4283 // Emits the code for the case of using using a local variable declaration.
4285 void EmitLocalVariableDecls (EmitContext ec)
4287 ILGenerator ig = ec.ig;
4290 for (i = 0; i < assign.Length; i++) {
4291 assign [i].EmitStatement (ec);
4294 ig.BeginExceptionBlock ();
4296 Statement.Emit (ec);
4298 var_list.Reverse ();
4303 void EmitLocalVariableDeclFinally (EmitContext ec)
4305 ILGenerator ig = ec.ig;
4307 int i = assign.Length;
4308 for (int ii = 0; ii < var_list.Count; ++ii){
4309 Expression var = resolved_vars [--i];
4310 Label skip = ig.DefineLabel ();
4313 ig.BeginFinallyBlock ();
4315 if (!var.Type.IsValueType) {
4317 ig.Emit (OpCodes.Brfalse, skip);
4318 converted_vars [i].Emit (ec);
4319 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4321 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4323 if (!(ml is MethodGroupExpr)) {
4325 ig.Emit (OpCodes.Box, var.Type);
4326 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4328 MethodInfo mi = null;
4330 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4331 if (TypeManager.GetParameterData (mk).Count == 0) {
4338 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4342 IMemoryLocation mloc = (IMemoryLocation) var;
4344 mloc.AddressOf (ec, AddressOp.Load);
4345 ig.Emit (OpCodes.Call, mi);
4349 ig.MarkLabel (skip);
4352 ig.EndExceptionBlock ();
4354 ig.BeginFinallyBlock ();
4359 void EmitExpression (EmitContext ec)
4362 // Make a copy of the expression and operate on that.
4364 ILGenerator ig = ec.ig;
4366 local_copy.Store (ec, expr);
4369 ig.BeginExceptionBlock ();
4371 Statement.Emit (ec);
4375 ig.EndExceptionBlock ();
4378 void EmitExpressionFinally (EmitContext ec)
4380 ILGenerator ig = ec.ig;
4381 if (!expr_type.IsValueType) {
4382 Label skip = ig.DefineLabel ();
4383 local_copy.Emit (ec);
4384 ig.Emit (OpCodes.Brfalse, skip);
4385 local_copy.Emit (ec);
4386 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4387 ig.MarkLabel (skip);
4389 Expression ml = Expression.MemberLookup (
4390 ec.ContainerType, TypeManager.idisposable_type, expr_type,
4391 "Dispose", Location.Null);
4393 if (!(ml is MethodGroupExpr)) {
4394 local_copy.Emit (ec);
4395 ig.Emit (OpCodes.Box, expr_type);
4396 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4398 MethodInfo mi = null;
4400 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4401 if (TypeManager.GetParameterData (mk).Count == 0) {
4408 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4412 local_copy.AddressOf (ec, AddressOp.Load);
4413 ig.Emit (OpCodes.Call, mi);
4418 public override bool Resolve (EmitContext ec)
4420 if (expression_or_block is DictionaryEntry){
4421 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4422 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4424 if (!ResolveLocalVariableDecls (ec))
4427 } else if (expression_or_block is Expression){
4428 expr = (Expression) expression_or_block;
4430 expr = expr.Resolve (ec);
4434 expr_type = expr.Type;
4436 if (!ResolveExpression (ec))
4440 FlowBranchingException branching = ec.StartFlowBranching (this);
4442 bool ok = Statement.Resolve (ec);
4445 ec.KillFlowBranching ();
4449 ResolveFinally (branching);
4450 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4452 if (!reachability.AlwaysReturns) {
4453 // Unfortunately, System.Reflection.Emit automatically emits a leave
4454 // to the end of the finally block. This is a problem if `returns'
4455 // is true since we may jump to a point after the end of the method.
4456 // As a workaround, emit an explicit ret here.
4457 ec.NeedReturnLabel ();
4463 protected override void DoEmit (EmitContext ec)
4465 if (expression_or_block is DictionaryEntry)
4466 EmitLocalVariableDecls (ec);
4467 else if (expression_or_block is Expression)
4468 EmitExpression (ec);
4471 public override void EmitFinally (EmitContext ec)
4473 if (expression_or_block is DictionaryEntry)
4474 EmitLocalVariableDeclFinally (ec);
4475 else if (expression_or_block is Expression)
4476 EmitExpressionFinally (ec);
4481 /// Implementation of the foreach C# statement
4483 public class Foreach : Statement {
4485 Expression variable;
4487 Statement statement;
4489 CollectionForeach collection;
4491 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4492 Statement stmt, Location l)
4495 this.variable = var;
4501 public Statement Statement {
4502 get { return statement; }
4505 public override bool Resolve (EmitContext ec)
4507 expr = expr.Resolve (ec);
4511 Constant c = expr as Constant;
4512 if (c != null && c.GetValue () == null) {
4513 Report.Error (186, loc, "Use of null is not valid in this context");
4517 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4521 Type var_type = texpr.Type;
4523 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
4524 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4525 expr.ExprClassName);
4530 // We need an instance variable. Not sure this is the best
4531 // way of doing this.
4533 // FIXME: When we implement propertyaccess, will those turn
4534 // out to return values in ExprClass? I think they should.
4536 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4537 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4538 collection.Error_Enumerator ();
4542 if (expr.Type.IsArray) {
4543 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4544 return array.Resolve (ec);
4546 collection = new CollectionForeach (
4547 var_type, variable, expr, statement, loc);
4548 return collection.Resolve (ec);
4552 protected override void DoEmit (EmitContext ec)
4554 ILGenerator ig = ec.ig;
4556 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4557 ec.LoopBegin = ig.DefineLabel ();
4558 ec.LoopEnd = ig.DefineLabel ();
4560 if (collection != null)
4561 collection.Emit (ec);
4565 ec.LoopBegin = old_begin;
4566 ec.LoopEnd = old_end;
4569 protected class ArrayCounter : TemporaryVariable
4571 public ArrayCounter (Location loc)
4572 : base (TypeManager.int32_type, loc)
4575 public void Initialize (EmitContext ec)
4578 ec.ig.Emit (OpCodes.Ldc_I4_0);
4582 public void Increment (EmitContext ec)
4586 ec.ig.Emit (OpCodes.Ldc_I4_1);
4587 ec.ig.Emit (OpCodes.Add);
4592 protected class ArrayForeach : Statement
4594 Expression variable, expr, conv;
4595 Statement statement;
4598 TemporaryVariable[] lengths;
4599 ArrayCounter[] counter;
4602 TemporaryVariable copy;
4605 public ArrayForeach (Type var_type, Expression var,
4606 Expression expr, Statement stmt, Location l)
4608 this.var_type = var_type;
4609 this.variable = var;
4615 public override bool Resolve (EmitContext ec)
4617 array_type = expr.Type;
4618 rank = array_type.GetArrayRank ();
4620 copy = new TemporaryVariable (array_type, loc);
4623 counter = new ArrayCounter [rank];
4624 lengths = new TemporaryVariable [rank];
4626 ArrayList list = new ArrayList ();
4627 for (int i = 0; i < rank; i++) {
4628 counter [i] = new ArrayCounter (loc);
4629 counter [i].Resolve (ec);
4631 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4632 lengths [i].Resolve (ec);
4634 list.Add (counter [i]);
4637 access = new ElementAccess (copy, list).Resolve (ec);
4641 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4647 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4648 ec.CurrentBranching.CreateSibling ();
4650 variable = variable.ResolveLValue (ec, conv, loc);
4651 if (variable == null)
4654 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4655 if (!statement.Resolve (ec))
4657 ec.EndFlowBranching ();
4659 // There's no direct control flow from the end of the embedded statement to the end of the loop
4660 ec.CurrentBranching.CurrentUsageVector.Goto ();
4662 ec.EndFlowBranching ();
4667 protected override void DoEmit (EmitContext ec)
4669 ILGenerator ig = ec.ig;
4671 copy.Store (ec, expr);
4673 Label[] test = new Label [rank];
4674 Label[] loop = new Label [rank];
4676 for (int i = 0; i < rank; i++) {
4677 test [i] = ig.DefineLabel ();
4678 loop [i] = ig.DefineLabel ();
4680 lengths [i].EmitThis (ec);
4681 ((ArrayAccess) access).EmitGetLength (ec, i);
4682 lengths [i].EmitStore (ec);
4685 for (int i = 0; i < rank; i++) {
4686 counter [i].Initialize (ec);
4688 ig.Emit (OpCodes.Br, test [i]);
4689 ig.MarkLabel (loop [i]);
4692 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4694 statement.Emit (ec);
4696 ig.MarkLabel (ec.LoopBegin);
4698 for (int i = rank - 1; i >= 0; i--){
4699 counter [i].Increment (ec);
4701 ig.MarkLabel (test [i]);
4702 counter [i].Emit (ec);
4703 lengths [i].Emit (ec);
4704 ig.Emit (OpCodes.Blt, loop [i]);
4707 ig.MarkLabel (ec.LoopEnd);
4711 protected class CollectionForeach : ExceptionStatement
4713 Expression variable, expr;
4714 Statement statement;
4716 TemporaryVariable enumerator;
4720 MethodGroupExpr get_enumerator;
4721 PropertyExpr get_current;
4722 MethodInfo move_next;
4723 Type var_type, enumerator_type;
4725 bool enumerator_found;
4727 public CollectionForeach (Type var_type, Expression var,
4728 Expression expr, Statement stmt, Location l)
4730 this.var_type = var_type;
4731 this.variable = var;
4737 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4739 Type return_type = mi.ReturnType;
4741 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4743 // Apply the same optimization as MS: skip the GetEnumerator
4744 // returning an IEnumerator, and use the one returning a
4745 // CharEnumerator instead. This allows us to avoid the
4746 // try-finally block and the boxing.
4751 // Ok, we can access it, now make sure that we can do something
4752 // with this `GetEnumerator'
4755 if (return_type == TypeManager.ienumerator_type ||
4756 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4757 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4759 // If it is not an interface, lets try to find the methods ourselves.
4760 // For example, if we have:
4761 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4762 // We can avoid the iface call. This is a runtime perf boost.
4763 // even bigger if we have a ValueType, because we avoid the cost
4766 // We have to make sure that both methods exist for us to take
4767 // this path. If one of the methods does not exist, we will just
4768 // use the interface. Sadly, this complex if statement is the only
4769 // way I could do this without a goto
4774 // Prefer a generic enumerator over a non-generic one.
4776 if (return_type.IsInterface && return_type.IsGenericType) {
4777 enumerator_type = return_type;
4778 if (!FetchGetCurrent (ec, return_type))
4779 get_current = new PropertyExpr (
4780 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4781 if (!FetchMoveNext (return_type))
4782 move_next = TypeManager.bool_movenext_void;
4787 if (return_type.IsInterface ||
4788 !FetchMoveNext (return_type) ||
4789 !FetchGetCurrent (ec, return_type)) {
4790 enumerator_type = return_type;
4791 move_next = TypeManager.bool_movenext_void;
4792 get_current = new PropertyExpr (
4793 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4798 // Ok, so they dont return an IEnumerable, we will have to
4799 // find if they support the GetEnumerator pattern.
4802 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
4803 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",
4804 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
4809 enumerator_type = return_type;
4810 is_disposable = !enumerator_type.IsSealed ||
4811 TypeManager.ImplementsInterface (
4812 enumerator_type, TypeManager.idisposable_type);
4818 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4820 bool FetchMoveNext (Type t)
4822 MemberList move_next_list;
4824 move_next_list = TypeContainer.FindMembers (
4825 t, MemberTypes.Method,
4826 BindingFlags.Public | BindingFlags.Instance,
4827 Type.FilterName, "MoveNext");
4828 if (move_next_list.Count == 0)
4831 foreach (MemberInfo m in move_next_list){
4832 MethodInfo mi = (MethodInfo) m;
4834 if ((TypeManager.GetParameterData (mi).Count == 0) &&
4835 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4845 // Retrieves a `public T get_Current ()' method from the Type `t'
4847 bool FetchGetCurrent (EmitContext ec, Type t)
4849 PropertyExpr pe = Expression.MemberLookup (
4850 ec.ContainerType, t, "Current", MemberTypes.Property,
4851 Expression.AllBindingFlags, loc) as PropertyExpr;
4860 // Retrieves a `public void Dispose ()' method from the Type `t'
4862 static MethodInfo FetchMethodDispose (Type t)
4864 MemberList dispose_list;
4866 dispose_list = TypeContainer.FindMembers (
4867 t, MemberTypes.Method,
4868 BindingFlags.Public | BindingFlags.Instance,
4869 Type.FilterName, "Dispose");
4870 if (dispose_list.Count == 0)
4873 foreach (MemberInfo m in dispose_list){
4874 MethodInfo mi = (MethodInfo) m;
4876 if (TypeManager.GetParameterData (mi).Count == 0){
4877 if (mi.ReturnType == TypeManager.void_type)
4884 public void Error_Enumerator ()
4886 if (enumerator_found) {
4890 Report.Error (1579, loc,
4891 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4892 TypeManager.CSharpName (expr.Type));
4895 bool TryType (EmitContext ec, Type t)
4897 MethodGroupExpr mg = Expression.MemberLookup (
4898 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
4899 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4903 MethodInfo result = null;
4904 MethodInfo tmp_move_next = null;
4905 PropertyExpr tmp_get_cur = null;
4906 Type tmp_enumerator_type = enumerator_type;
4907 foreach (MethodInfo mi in mg.Methods) {
4908 if (TypeManager.GetParameterData (mi).Count != 0)
4911 // Check whether GetEnumerator is public
4912 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4915 if (TypeManager.IsOverride (mi))
4918 enumerator_found = true;
4920 if (!GetEnumeratorFilter (ec, mi))
4923 if (result != null) {
4924 if (TypeManager.IsGenericType (result.ReturnType)) {
4925 if (!TypeManager.IsGenericType (mi.ReturnType))
4928 Report.SymbolRelatedToPreviousError(t);
4929 Report.Error(1640, loc, "foreach statement cannot operate on variables of type `{0}' " +
4930 "because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
4931 TypeManager.CSharpName (t), TypeManager.CSharpSignature (mi));
4934 Report.SymbolRelatedToPreviousError (result);
4935 Report.SymbolRelatedToPreviousError (mi);
4936 Report.Warning (278, 2, loc, "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
4937 TypeManager.CSharpName (t), "enumerable", TypeManager.CSharpSignature (result), TypeManager.CSharpSignature (mi));
4940 tmp_move_next = move_next;
4941 tmp_get_cur = get_current;
4942 tmp_enumerator_type = enumerator_type;
4943 if (mi.DeclaringType == t)
4947 if (result != null) {
4948 move_next = tmp_move_next;
4949 get_current = tmp_get_cur;
4950 enumerator_type = tmp_enumerator_type;
4951 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
4952 get_enumerator = new MethodGroupExpr (mi, loc);
4954 if (t != expr.Type) {
4955 expr = Convert.ExplicitConversion (
4958 throw new InternalErrorException ();
4961 get_enumerator.InstanceExpression = expr;
4962 get_enumerator.IsBase = t != expr.Type;
4970 bool ProbeCollectionType (EmitContext ec, Type t)
4972 int errors = Report.Errors;
4973 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4974 if (TryType (ec, tt))
4979 if (Report.Errors > errors)
4983 // Now try to find the method in the interfaces
4986 Type [] ifaces = t.GetInterfaces ();
4988 foreach (Type i in ifaces){
4989 if (TryType (ec, i))
4994 // Since TypeBuilder.GetInterfaces only returns the interface
4995 // types for this type, we have to keep looping, but once
4996 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4997 // done, because it returns all the types
4999 if ((t is TypeBuilder))
5008 public override bool Resolve (EmitContext ec)
5010 enumerator_type = TypeManager.ienumerator_type;
5011 is_disposable = true;
5013 if (!ProbeCollectionType (ec, expr.Type)) {
5014 Error_Enumerator ();
5018 enumerator = new TemporaryVariable (enumerator_type, loc);
5019 enumerator.Resolve (ec);
5021 init = new Invocation (get_enumerator, new ArrayList ());
5022 init = init.Resolve (ec);
5026 Expression move_next_expr;
5028 MemberInfo[] mi = new MemberInfo[] { move_next };
5029 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
5030 mg.InstanceExpression = enumerator;
5032 move_next_expr = new Invocation (mg, new ArrayList ());
5035 get_current.InstanceExpression = enumerator;
5037 Statement block = new CollectionForeachStatement (
5038 var_type, variable, get_current, statement, loc);
5040 loop = new While (move_next_expr, block, loc);
5044 FlowBranchingException branching = null;
5046 branching = ec.StartFlowBranching (this);
5048 if (!loop.Resolve (ec))
5051 if (is_disposable) {
5052 ResolveFinally (branching);
5053 ec.EndFlowBranching ();
5055 emit_finally = true;
5060 protected override void DoEmit (EmitContext ec)
5062 ILGenerator ig = ec.ig;
5064 enumerator.Store (ec, init);
5067 // Protect the code in a try/finalize block, so that
5068 // if the beast implement IDisposable, we get rid of it
5070 if (is_disposable && emit_finally)
5071 ig.BeginExceptionBlock ();
5076 // Now the finally block
5078 if (is_disposable) {
5081 ig.EndExceptionBlock ();
5086 public override void EmitFinally (EmitContext ec)
5088 ILGenerator ig = ec.ig;
5090 if (enumerator_type.IsValueType) {
5091 MethodInfo mi = FetchMethodDispose (enumerator_type);
5093 enumerator.EmitLoadAddress (ec);
5094 ig.Emit (OpCodes.Call, mi);
5096 enumerator.Emit (ec);
5097 ig.Emit (OpCodes.Box, enumerator_type);
5098 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5101 Label call_dispose = ig.DefineLabel ();
5103 enumerator.Emit (ec);
5104 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5105 ig.Emit (OpCodes.Dup);
5106 ig.Emit (OpCodes.Brtrue_S, call_dispose);
5107 ig.Emit (OpCodes.Pop);
5109 Label end_finally = ig.DefineLabel ();
5110 ig.Emit (OpCodes.Br, end_finally);
5112 ig.MarkLabel (call_dispose);
5113 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5114 ig.MarkLabel (end_finally);
5119 protected class CollectionForeachStatement : Statement
5122 Expression variable, current, conv;
5123 Statement statement;
5126 public CollectionForeachStatement (Type type, Expression variable,
5127 Expression current, Statement statement,
5131 this.variable = variable;
5132 this.current = current;
5133 this.statement = statement;
5137 public override bool Resolve (EmitContext ec)
5139 current = current.Resolve (ec);
5140 if (current == null)
5143 conv = Convert.ExplicitConversion (ec, current, type, loc);
5147 assign = new Assign (variable, conv, loc);
5148 if (assign.Resolve (ec) == null)
5151 if (!statement.Resolve (ec))
5157 protected override void DoEmit (EmitContext ec)
5159 assign.EmitStatement (ec);
5160 statement.Emit (ec);