2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@ximian.com)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 // (C) 2003, 2004 Novell, Inc.
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Diagnostics;
17 using System.Collections;
18 using System.Collections.Specialized;
20 namespace Mono.CSharp {
22 public abstract class Statement {
26 /// Resolves the statement, true means that all sub-statements
29 public virtual bool Resolve (EmitContext ec)
35 /// We already know that the statement is unreachable, but we still
36 /// need to resolve it to catch errors.
38 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
41 // This conflicts with csc's way of doing this, but IMHO it's
42 // the right thing to do.
44 // If something is unreachable, we still check whether it's
45 // correct. This means that you cannot use unassigned variables
46 // in unreachable code, for instance.
50 Report.Warning (162, 2, loc, "Unreachable code detected");
52 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
53 bool ok = Resolve (ec);
54 ec.KillFlowBranching ();
60 /// Return value indicates whether all code paths emitted return.
62 protected abstract void DoEmit (EmitContext ec);
65 /// Utility wrapper routine for Error, just to beautify the code
67 public void Error (int error, string format, params object[] args)
69 Error (error, String.Format (format, args));
72 public void Error (int error, string s)
75 Report.Error (error, loc, s);
77 Report.Error (error, s);
81 /// Return value indicates whether all code paths emitted return.
83 public virtual void Emit (EmitContext ec)
90 public sealed class EmptyStatement : Statement {
92 private EmptyStatement () {}
94 public static readonly EmptyStatement Value = new EmptyStatement ();
96 public override bool Resolve (EmitContext ec)
101 public override bool ResolveUnreachable (EmitContext ec, bool warn)
106 protected override void DoEmit (EmitContext ec)
111 public class If : Statement {
113 public Statement TrueStatement;
114 public Statement FalseStatement;
118 public If (Expression expr, Statement trueStatement, Location l)
121 TrueStatement = trueStatement;
125 public If (Expression expr,
126 Statement trueStatement,
127 Statement falseStatement,
131 TrueStatement = trueStatement;
132 FalseStatement = falseStatement;
136 public override bool Resolve (EmitContext ec)
140 Report.Debug (1, "START IF BLOCK", loc);
142 expr = Expression.ResolveBoolean (ec, expr, loc);
148 Assign ass = expr as Assign;
149 if (ass != null && ass.Source is Constant) {
150 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
154 // Dead code elimination
156 if (expr is BoolConstant){
157 bool take = ((BoolConstant) expr).Value;
160 if (!TrueStatement.Resolve (ec))
163 if ((FalseStatement != null) &&
164 !FalseStatement.ResolveUnreachable (ec, true))
166 FalseStatement = null;
168 if (!TrueStatement.ResolveUnreachable (ec, true))
170 TrueStatement = null;
172 if ((FalseStatement != null) &&
173 !FalseStatement.Resolve (ec))
180 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
182 ok &= TrueStatement.Resolve (ec);
184 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
186 ec.CurrentBranching.CreateSibling ();
188 if (FalseStatement != null)
189 ok &= FalseStatement.Resolve (ec);
191 ec.EndFlowBranching ();
193 Report.Debug (1, "END IF BLOCK", loc);
198 protected override void DoEmit (EmitContext ec)
200 ILGenerator ig = ec.ig;
201 Label false_target = ig.DefineLabel ();
205 // If we're a boolean expression, Resolve() already
206 // eliminated dead code for us.
208 if (expr is BoolConstant){
209 bool take = ((BoolConstant) expr).Value;
212 TrueStatement.Emit (ec);
213 else if (FalseStatement != null)
214 FalseStatement.Emit (ec);
219 expr.EmitBranchable (ec, false_target, false);
221 TrueStatement.Emit (ec);
223 if (FalseStatement != null){
224 bool branch_emitted = false;
226 end = ig.DefineLabel ();
228 ig.Emit (OpCodes.Br, end);
229 branch_emitted = true;
232 ig.MarkLabel (false_target);
233 FalseStatement.Emit (ec);
238 ig.MarkLabel (false_target);
243 public class Do : Statement {
244 public Expression expr;
245 public readonly Statement EmbeddedStatement;
248 public Do (Statement statement, Expression boolExpr, Location l)
251 EmbeddedStatement = statement;
255 public override bool Resolve (EmitContext ec)
259 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
261 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
263 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
264 if (!EmbeddedStatement.Resolve (ec))
266 ec.EndFlowBranching ();
268 if (ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable && !was_unreachable)
269 Report.Warning (162, 2, expr.Location, "Unreachable code detected");
271 expr = Expression.ResolveBoolean (ec, expr, loc);
274 else if (expr is BoolConstant){
275 bool res = ((BoolConstant) expr).Value;
281 ec.CurrentBranching.CurrentUsageVector.Goto ();
283 ec.EndFlowBranching ();
288 protected override void DoEmit (EmitContext ec)
290 ILGenerator ig = ec.ig;
291 Label loop = ig.DefineLabel ();
292 Label old_begin = ec.LoopBegin;
293 Label old_end = ec.LoopEnd;
295 ec.LoopBegin = ig.DefineLabel ();
296 ec.LoopEnd = ig.DefineLabel ();
299 EmbeddedStatement.Emit (ec);
300 ig.MarkLabel (ec.LoopBegin);
303 // Dead code elimination
305 if (expr is BoolConstant){
306 bool res = ((BoolConstant) expr).Value;
309 ec.ig.Emit (OpCodes.Br, loop);
311 expr.EmitBranchable (ec, loop, true);
313 ig.MarkLabel (ec.LoopEnd);
315 ec.LoopBegin = old_begin;
316 ec.LoopEnd = old_end;
320 public class While : Statement {
321 public Expression expr;
322 public readonly Statement Statement;
323 bool infinite, empty;
325 public While (Expression boolExpr, Statement statement, Location l)
327 this.expr = boolExpr;
328 Statement = statement;
332 public override bool Resolve (EmitContext ec)
336 expr = Expression.ResolveBoolean (ec, expr, loc);
341 // Inform whether we are infinite or not
343 if (expr is BoolConstant){
344 BoolConstant bc = (BoolConstant) expr;
346 if (bc.Value == false){
347 if (!Statement.ResolveUnreachable (ec, true))
355 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
357 ec.CurrentBranching.CreateSibling ();
359 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
360 if (!Statement.Resolve (ec))
362 ec.EndFlowBranching ();
364 // There's no direct control flow from the end of the embedded statement to the end of the loop
365 ec.CurrentBranching.CurrentUsageVector.Goto ();
367 ec.EndFlowBranching ();
372 protected override void DoEmit (EmitContext ec)
377 ILGenerator ig = ec.ig;
378 Label old_begin = ec.LoopBegin;
379 Label old_end = ec.LoopEnd;
381 ec.LoopBegin = ig.DefineLabel ();
382 ec.LoopEnd = ig.DefineLabel ();
385 // Inform whether we are infinite or not
387 if (expr is BoolConstant){
388 ig.MarkLabel (ec.LoopBegin);
390 ig.Emit (OpCodes.Br, ec.LoopBegin);
393 // Inform that we are infinite (ie, `we return'), only
394 // if we do not `break' inside the code.
396 ig.MarkLabel (ec.LoopEnd);
398 Label while_loop = ig.DefineLabel ();
400 ig.Emit (OpCodes.Br, ec.LoopBegin);
401 ig.MarkLabel (while_loop);
405 ig.MarkLabel (ec.LoopBegin);
407 expr.EmitBranchable (ec, while_loop, true);
409 ig.MarkLabel (ec.LoopEnd);
412 ec.LoopBegin = old_begin;
413 ec.LoopEnd = old_end;
417 public class For : Statement {
419 readonly Statement InitStatement;
420 readonly Statement Increment;
421 public readonly Statement Statement;
422 bool infinite, empty;
424 public For (Statement initStatement,
430 InitStatement = initStatement;
432 Increment = increment;
433 Statement = statement;
437 public override bool Resolve (EmitContext ec)
441 if (InitStatement != null){
442 if (!InitStatement.Resolve (ec))
447 Test = Expression.ResolveBoolean (ec, Test, loc);
450 else if (Test is BoolConstant){
451 BoolConstant bc = (BoolConstant) Test;
453 if (bc.Value == false){
454 if (!Statement.ResolveUnreachable (ec, true))
456 if ((Increment != null) &&
457 !Increment.ResolveUnreachable (ec, false))
467 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
469 ec.CurrentBranching.CreateSibling ();
471 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
473 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
474 if (!Statement.Resolve (ec))
476 ec.EndFlowBranching ();
478 if (Increment != null){
479 if (ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable) {
480 if (!Increment.ResolveUnreachable (ec, !was_unreachable))
483 if (!Increment.Resolve (ec))
488 // There's no direct control flow from the end of the embedded statement to the end of the loop
489 ec.CurrentBranching.CurrentUsageVector.Goto ();
491 ec.EndFlowBranching ();
496 protected override void DoEmit (EmitContext ec)
501 ILGenerator ig = ec.ig;
502 Label old_begin = ec.LoopBegin;
503 Label old_end = ec.LoopEnd;
504 Label loop = ig.DefineLabel ();
505 Label test = ig.DefineLabel ();
507 if (InitStatement != null && InitStatement != EmptyStatement.Value)
508 InitStatement.Emit (ec);
510 ec.LoopBegin = ig.DefineLabel ();
511 ec.LoopEnd = ig.DefineLabel ();
513 ig.Emit (OpCodes.Br, test);
517 ig.MarkLabel (ec.LoopBegin);
518 if (Increment != EmptyStatement.Value)
523 // If test is null, there is no test, and we are just
528 // The Resolve code already catches the case for
529 // Test == BoolConstant (false) so we know that
532 if (Test is BoolConstant)
533 ig.Emit (OpCodes.Br, loop);
535 Test.EmitBranchable (ec, loop, true);
538 ig.Emit (OpCodes.Br, loop);
539 ig.MarkLabel (ec.LoopEnd);
541 ec.LoopBegin = old_begin;
542 ec.LoopEnd = old_end;
546 public class StatementExpression : Statement {
547 ExpressionStatement expr;
549 public StatementExpression (ExpressionStatement expr)
555 public override bool Resolve (EmitContext ec)
558 expr = expr.ResolveStatement (ec);
562 protected override void DoEmit (EmitContext ec)
564 expr.EmitStatement (ec);
567 public override string ToString ()
569 return "StatementExpression (" + expr + ")";
574 /// Implements the return statement
576 public class Return : Statement {
577 public Expression Expr;
579 public Return (Expression expr, Location l)
587 public override bool Resolve (EmitContext ec)
589 AnonymousContainer am = ec.CurrentAnonymousMethod;
590 if ((am != null) && am.IsIterator && ec.InIterator) {
591 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
592 "statement to return a value, or yield break to end the iteration");
596 if (ec.ReturnType == null){
598 if (ec.CurrentAnonymousMethod != null){
599 Report.Error (1662, loc,
600 "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",
601 ec.CurrentAnonymousMethod.GetSignatureForError ());
603 Error (127, "A return keyword must not be followed by any expression when method returns void");
608 Error (126, "An object of a type convertible to `{0}' is required " +
609 "for the return statement",
610 TypeManager.CSharpName (ec.ReturnType));
614 Expr = Expr.Resolve (ec);
618 if (Expr.Type != ec.ReturnType) {
619 Expr = Convert.ImplicitConversionRequired (
620 ec, Expr, ec.ReturnType, loc);
626 int errors = Report.Errors;
627 unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
629 ec.NeedReturnLabel ();
630 ec.CurrentBranching.CurrentUsageVector.Return ();
631 return errors == Report.Errors;
634 protected override void DoEmit (EmitContext ec)
640 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
644 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
646 ec.ig.Emit (OpCodes.Ret);
650 public class Goto : Statement {
652 LabeledStatement label;
655 public override bool Resolve (EmitContext ec)
657 int errors = Report.Errors;
658 unwind_protect = ec.CurrentBranching.AddGotoOrigin (ec.CurrentBranching.CurrentUsageVector, this);
659 ec.CurrentBranching.CurrentUsageVector.Goto ();
660 return errors == Report.Errors;
663 public Goto (string label, Location l)
669 public string Target {
670 get { return target; }
673 public void SetResolvedTarget (LabeledStatement label)
676 label.AddReference ();
679 protected override void DoEmit (EmitContext ec)
682 throw new InternalErrorException ("goto emitted before target resolved");
683 Label l = label.LabelTarget (ec);
684 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
688 public class LabeledStatement : Statement {
695 FlowBranching.UsageVector vectors;
697 public LabeledStatement (string name, Location l)
703 public Label LabelTarget (EmitContext ec)
708 label = ec.ig.DefineLabel ();
718 public bool IsDefined {
719 get { return defined; }
722 public bool HasBeenReferenced {
723 get { return referenced; }
726 public FlowBranching.UsageVector JumpOrigins {
727 get { return vectors; }
730 public void AddUsageVector (FlowBranching.UsageVector vector)
732 vector = vector.Clone ();
733 vector.Next = vectors;
737 public override bool Resolve (EmitContext ec)
739 // this flow-branching will be terminated when the surrounding block ends
740 ec.StartFlowBranching (this);
744 protected override void DoEmit (EmitContext ec)
746 if (ig != null && ig != ec.ig)
747 throw new InternalErrorException ("cannot happen");
749 ec.ig.MarkLabel (label);
752 public void AddReference ()
760 /// `goto default' statement
762 public class GotoDefault : Statement {
764 public GotoDefault (Location l)
769 public override bool Resolve (EmitContext ec)
771 ec.CurrentBranching.CurrentUsageVector.Goto ();
775 protected override void DoEmit (EmitContext ec)
777 if (ec.Switch == null){
778 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
782 if (!ec.Switch.GotDefault){
783 Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
786 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
791 /// `goto case' statement
793 public class GotoCase : Statement {
797 public GotoCase (Expression e, Location l)
803 public override bool Resolve (EmitContext ec)
805 if (ec.Switch == null){
806 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
810 expr = expr.Resolve (ec);
814 Constant c = expr as Constant;
816 Error (150, "A constant value is expected");
820 Type type = ec.Switch.SwitchType;
821 if (!Convert.ImplicitStandardConversionExists (c, type))
822 Report.Warning (469, 2, loc, "The `goto case' value is not implicitly " +
823 "convertible to type `{0}'", TypeManager.CSharpName (type));
826 object val = c.GetValue ();
827 if ((val != null) && (c.Type != type) && (c.Type != TypeManager.object_type))
828 val = TypeManager.ChangeType (val, type, out fail);
831 Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
832 c.GetSignatureForError (), TypeManager.CSharpName (type));
837 val = SwitchLabel.NullStringCase;
839 sl = (SwitchLabel) ec.Switch.Elements [val];
842 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", c.GetValue () == null ? "null" : val.ToString ());
846 ec.CurrentBranching.CurrentUsageVector.Goto ();
850 protected override void DoEmit (EmitContext ec)
852 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
856 public class Throw : Statement {
859 public Throw (Expression expr, Location l)
865 public override bool Resolve (EmitContext ec)
867 ec.CurrentBranching.CurrentUsageVector.Throw ();
870 expr = expr.Resolve (ec);
874 ExprClass eclass = expr.eclass;
876 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
877 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
878 expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
884 if ((t != TypeManager.exception_type) &&
885 !t.IsSubclassOf (TypeManager.exception_type) &&
886 !(expr is NullLiteral)) {
888 "The type caught or thrown must be derived " +
889 "from System.Exception");
896 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
901 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
907 protected override void DoEmit (EmitContext ec)
910 ec.ig.Emit (OpCodes.Rethrow);
914 ec.ig.Emit (OpCodes.Throw);
919 public class Break : Statement {
921 public Break (Location l)
928 public override bool Resolve (EmitContext ec)
930 int errors = Report.Errors;
931 unwind_protect = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
932 ec.CurrentBranching.CurrentUsageVector.Goto ();
933 return errors == Report.Errors;
936 protected override void DoEmit (EmitContext ec)
938 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
942 public class Continue : Statement {
944 public Continue (Location l)
951 public override bool Resolve (EmitContext ec)
953 int errors = Report.Errors;
954 unwind_protect = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
955 ec.CurrentBranching.CurrentUsageVector.Goto ();
956 return errors == Report.Errors;
959 protected override void DoEmit (EmitContext ec)
961 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
966 // The information about a user-perceived local variable
968 public class LocalInfo {
969 public Expression Type;
972 // Most of the time a variable will be stored in a LocalBuilder
974 // But sometimes, it will be stored in a field (variables that have been
975 // hoisted by iterators or by anonymous methods). The context of the field will
976 // be stored in the EmitContext
979 public LocalBuilder LocalBuilder;
980 public FieldBuilder FieldBuilder;
982 public Type VariableType;
983 public readonly string Name;
984 public readonly Location Location;
985 public readonly Block Block;
987 public VariableInfo VariableInfo;
997 CompilerGenerated = 64,
1001 public enum ReadOnlyContext: byte {
1008 ReadOnlyContext ro_context;
1010 public LocalInfo (Expression type, string name, Block block, Location l)
1018 public LocalInfo (DeclSpace ds, Block block, Location l)
1020 VariableType = ds.TypeBuilder;
1025 public void DeclareLocal (ILGenerator ig)
1029 // This is needed to compile on both .NET 1.x and .NET 2.x
1030 // the later introduced `DeclareLocal (Type t, bool pinned)'
1032 LocalBuilder = TypeManager.DeclareLocalPinned (ig, VariableType);
1035 if (!IsThis && !IsConstant)
1036 LocalBuilder = ig.DeclareLocal (VariableType);
1039 public bool IsThisAssigned (EmitContext ec, Location loc)
1041 if (VariableInfo == null)
1042 throw new Exception ();
1044 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1047 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1050 public bool IsAssigned (EmitContext ec)
1052 if (VariableInfo == null)
1053 throw new Exception ();
1055 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1058 public bool Resolve (EmitContext ec)
1060 if (VariableType == null) {
1061 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1065 VariableType = texpr.Type;
1068 if (VariableType == TypeManager.void_type) {
1069 Report.Error (1547, Location,
1070 "Keyword 'void' cannot be used in this context");
1074 if (VariableType.IsAbstract && VariableType.IsSealed) {
1075 Report.Error (723, Location, "Cannot declare variable of static type `{0}'", TypeManager.CSharpName (VariableType));
1079 if (VariableType.IsPointer && !ec.InUnsafe)
1080 Expression.UnsafeError (Location);
1085 public bool IsCaptured {
1087 return (flags & Flags.Captured) != 0;
1091 flags |= Flags.Captured;
1095 public bool IsConstant {
1097 return (flags & Flags.IsConstant) != 0;
1100 flags |= Flags.IsConstant;
1104 public bool AddressTaken {
1106 return (flags & Flags.AddressTaken) != 0;
1110 flags |= Flags.AddressTaken;
1114 public bool CompilerGenerated {
1116 return (flags & Flags.CompilerGenerated) != 0;
1120 flags |= Flags.CompilerGenerated;
1124 public override string ToString ()
1126 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1127 Name, Type, VariableInfo, Location);
1132 return (flags & Flags.Used) != 0;
1135 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1139 public bool ReadOnly {
1141 return (flags & Flags.ReadOnly) != 0;
1145 public void SetReadOnlyContext (ReadOnlyContext context)
1147 flags |= Flags.ReadOnly;
1148 ro_context = context;
1151 public string GetReadOnlyContext ()
1154 throw new InternalErrorException ("Variable is not readonly");
1156 switch (ro_context) {
1157 case ReadOnlyContext.Fixed:
1158 return "fixed variable";
1159 case ReadOnlyContext.Foreach:
1160 return "foreach iteration variable";
1161 case ReadOnlyContext.Using:
1162 return "using variable";
1164 throw new NotImplementedException ();
1168 // Whether the variable is pinned, if Pinned the variable has been
1169 // allocated in a pinned slot with DeclareLocal.
1171 public bool Pinned {
1173 return (flags & Flags.Pinned) != 0;
1176 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1180 public bool IsThis {
1182 return (flags & Flags.IsThis) != 0;
1185 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1191 /// Block represents a C# block.
1195 /// This class is used in a number of places: either to represent
1196 /// explicit blocks that the programmer places or implicit blocks.
1198 /// Implicit blocks are used as labels or to introduce variable
1201 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1202 /// they contain extra information that is not necessary on normal blocks.
1204 public class Block : Statement {
1205 public Block Parent;
1206 public readonly Location StartLocation;
1207 public Location EndLocation = Location.Null;
1209 public readonly ToplevelBlock Toplevel;
1212 public enum Flags : ushort {
1216 VariablesInitialized = 8,
1221 HasVarargs = 256 // Used in ToplevelBlock
1223 protected Flags flags;
1225 public bool Implicit {
1226 get { return (flags & Flags.Implicit) != 0; }
1229 public bool Unchecked {
1230 get { return (flags & Flags.Unchecked) != 0; }
1231 set { flags |= Flags.Unchecked; }
1234 public bool Unsafe {
1235 get { return (flags & Flags.Unsafe) != 0; }
1236 set { flags |= Flags.Unsafe; }
1240 // The statements in this block
1242 ArrayList statements;
1246 // An array of Blocks. We keep track of children just
1247 // to generate the local variable declarations.
1249 // Statements and child statements are handled through the
1255 // Labels. (label, block) pairs.
1260 // Keeps track of (name, type) pairs
1262 IDictionary variables;
1265 // Keeps track of constants
1266 Hashtable constants;
1269 // Temporary variables.
1271 ArrayList temporary_variables;
1274 // If this is a switch section, the enclosing switch block.
1278 protected static int id;
1282 public Block (Block parent)
1283 : this (parent, (Flags) 0, Location.Null, Location.Null)
1286 public Block (Block parent, Flags flags)
1287 : this (parent, flags, Location.Null, Location.Null)
1290 public Block (Block parent, Location start, Location end)
1291 : this (parent, (Flags) 0, start, end)
1294 public Block (Block parent, Flags flags, Location start, Location end)
1297 parent.AddChild (this);
1299 this.Parent = parent;
1301 this.StartLocation = start;
1302 this.EndLocation = end;
1305 statements = new ArrayList ();
1307 if ((flags & Flags.IsToplevel) != 0)
1308 Toplevel = (ToplevelBlock) this;
1310 Toplevel = parent.Toplevel;
1312 if (parent != null && Implicit) {
1313 if (parent.known_variables == null)
1314 parent.known_variables = new Hashtable ();
1315 // share with parent
1316 known_variables = parent.known_variables;
1320 public Block CreateSwitchBlock (Location start)
1322 Block new_block = new Block (this, start, start);
1323 new_block.switch_block = this;
1328 get { return this_id; }
1331 protected IDictionary Variables {
1333 if (variables == null)
1334 variables = new ListDictionary ();
1339 void AddChild (Block b)
1341 if (children == null)
1342 children = new ArrayList ();
1347 public void SetEndLocation (Location loc)
1353 /// Adds a label to the current block.
1357 /// false if the name already exists in this block. true
1361 public bool AddLabel (LabeledStatement target)
1363 if (switch_block != null)
1364 return switch_block.AddLabel (target);
1366 string name = target.Name;
1369 while (cur != null) {
1370 if (cur.DoLookupLabel (name) != null) {
1371 Report.Error (140, target.loc, "The label `{0}' is a duplicate", name);
1381 while (cur != null) {
1382 if (cur.DoLookupLabel (name) != null) {
1385 "The label `{0}' shadows another label by the same name in a contained scope.",
1390 if (children != null) {
1391 foreach (Block b in children) {
1392 LabeledStatement s = b.DoLookupLabel (name);
1398 "The label `{0}' shadows another label by the same name in a contained scope.",
1409 labels = new Hashtable ();
1411 labels.Add (name, target);
1415 public LabeledStatement LookupLabel (string name)
1417 LabeledStatement s = DoLookupLabel (name);
1421 if (children == null)
1424 foreach (Block child in children) {
1425 if (!child.Implicit)
1428 s = child.LookupLabel (name);
1436 LabeledStatement DoLookupLabel (string name)
1438 if (switch_block != null)
1439 return switch_block.LookupLabel (name);
1442 if (labels.Contains (name))
1443 return ((LabeledStatement) labels [name]);
1448 Hashtable known_variables;
1451 // Marks a variable with name @name as being used in this or a child block.
1452 // If a variable name has been used in a child block, it's illegal to
1453 // declare a variable with the same name in the current block.
1455 void AddKnownVariable (string name, LocalInfo info)
1457 if (known_variables == null)
1458 known_variables = new Hashtable ();
1460 known_variables [name] = info;
1463 LocalInfo GetKnownVariableInfo (string name)
1465 if (known_variables == null)
1467 return (LocalInfo) known_variables [name];
1470 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1473 LocalInfo kvi = b.GetKnownVariableInfo (name);
1474 while (kvi == null) {
1480 kvi = b.GetKnownVariableInfo (name);
1486 // Is kvi.Block nested inside 'b'
1487 if (b.known_variables != kvi.Block.known_variables) {
1489 // If a variable by the same name it defined in a nested block of this
1490 // block, we violate the invariant meaning in a block.
1493 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1494 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1499 // It's ok if the definition is in a nested subblock of b, but not
1500 // nested inside this block -- a definition in a sibling block
1501 // should not affect us.
1507 // Block 'b' and kvi.Block are the same textual block.
1508 // However, different variables are extant.
1510 // Check if the variable is in scope in both blocks. We use
1511 // an indirect check that depends on AddVariable doing its
1512 // part in maintaining the invariant-meaning-in-block property.
1514 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1518 // Even though we detected the error when the name is used, we
1519 // treat it as if the variable declaration was in error.
1521 Report.SymbolRelatedToPreviousError (loc, name);
1522 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1526 public LocalInfo AddVariable (Expression type, string name, Location l)
1528 LocalInfo vi = GetLocalInfo (name);
1530 Report.SymbolRelatedToPreviousError (vi.Location, name);
1531 if (known_variables == vi.Block.known_variables)
1532 Report.Error (128, l,
1533 "A local variable named `{0}' is already defined in this scope", name);
1535 Error_AlreadyDeclared (l, name, "parent");
1539 vi = GetKnownVariableInfo (name);
1541 Report.SymbolRelatedToPreviousError (vi.Location, name);
1542 Error_AlreadyDeclared (l, name, "child");
1547 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1549 Report.SymbolRelatedToPreviousError (p.Location, name);
1550 Error_AlreadyDeclared (l, name, "method argument");
1554 vi = new LocalInfo (type, name, this, l);
1556 Variables.Add (name, vi);
1558 for (Block b = this; b != null; b = b.Parent)
1559 b.AddKnownVariable (name, vi);
1561 if ((flags & Flags.VariablesInitialized) != 0)
1562 throw new Exception ();
1567 void Error_AlreadyDeclared (Location loc, string var, string reason)
1569 Report.Error (136, loc, "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning to `{0}', " +
1570 "which is already used in a `{1}' scope", var, reason);
1573 public bool AddConstant (Expression type, string name, Expression value, Location l)
1575 if (AddVariable (type, name, l) == null)
1578 if (constants == null)
1579 constants = new Hashtable ();
1581 constants.Add (name, value);
1583 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1588 static int next_temp_id = 0;
1590 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1592 if (temporary_variables == null)
1593 temporary_variables = new ArrayList ();
1595 int id = ++next_temp_id;
1596 string name = "$s_" + id.ToString ();
1598 LocalInfo li = new LocalInfo (te, name, this, loc);
1599 li.CompilerGenerated = true;
1600 temporary_variables.Add (li);
1604 public LocalInfo GetLocalInfo (string name)
1606 for (Block b = this; b != null; b = b.Parent) {
1607 if (b.variables != null) {
1608 LocalInfo ret = b.variables [name] as LocalInfo;
1616 public Expression GetVariableType (string name)
1618 LocalInfo vi = GetLocalInfo (name);
1619 return vi == null ? null : vi.Type;
1622 public Expression GetConstantExpression (string name)
1624 for (Block b = this; b != null; b = b.Parent) {
1625 if (b.constants != null) {
1626 Expression ret = b.constants [name] as Expression;
1634 public void AddStatement (Statement s)
1637 flags |= Flags.BlockUsed;
1641 get { return (flags & Flags.BlockUsed) != 0; }
1646 flags |= Flags.BlockUsed;
1649 public bool HasRet {
1650 get { return (flags & Flags.HasRet) != 0; }
1653 public bool IsDestructor {
1654 get { return (flags & Flags.IsDestructor) != 0; }
1657 public void SetDestructor ()
1659 flags |= Flags.IsDestructor;
1662 VariableMap param_map, local_map;
1664 public VariableMap ParameterMap {
1666 if ((flags & Flags.VariablesInitialized) == 0)
1667 throw new Exception ("Variables have not been initialized yet");
1673 public VariableMap LocalMap {
1675 if ((flags & Flags.VariablesInitialized) == 0)
1676 throw new Exception ("Variables have not been initialized yet");
1683 /// Emits the variable declarations and labels.
1686 /// tc: is our typecontainer (to resolve type references)
1687 /// ig: is the code generator:
1689 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
1691 // If some parent block was unsafe, we remain unsafe even if this block
1692 // isn't explicitly marked as such.
1693 using (ec.WithUnsafe (ec.InUnsafe | Unsafe)) {
1695 // Compute the VariableMap's.
1697 // Unfortunately, we don't know the type when adding variables with
1698 // AddVariable(), so we need to compute this info here.
1702 if (variables != null) {
1703 foreach (LocalInfo li in variables.Values)
1706 locals = new LocalInfo [variables.Count];
1707 variables.Values.CopyTo (locals, 0);
1709 locals = new LocalInfo [0];
1712 local_map = new VariableMap (Parent.LocalMap, locals);
1714 local_map = new VariableMap (locals);
1716 param_map = new VariableMap (ip);
1717 flags |= Flags.VariablesInitialized;
1720 // Process this block variables
1722 if (variables != null) {
1723 foreach (DictionaryEntry de in variables) {
1724 string name = (string) de.Key;
1725 LocalInfo vi = (LocalInfo) de.Value;
1726 Type variable_type = vi.VariableType;
1728 if (variable_type == null)
1731 if (variable_type.IsPointer) {
1733 // Am not really convinced that this test is required (Microsoft does it)
1734 // but the fact is that you would not be able to use the pointer variable
1737 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1742 if (constants == null)
1745 Expression cv = (Expression) constants [name];
1749 // Don't let 'const int Foo = Foo;' succeed.
1750 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
1751 // which in turn causes the 'must be constant' error to be triggered.
1752 constants.Remove (name);
1754 using (ec.WithCheckState (ec.CheckState, (flags & Flags.Unchecked) == 0)) {
1755 ec.CurrentBlock = this;
1756 Expression e = cv.Resolve (ec);
1760 Constant ce = e as Constant;
1762 Const.Error_ExpressionMustBeConstant (variable_type, vi.Location, name);
1766 e = ce.ToType (variable_type, vi.Location);
1770 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue) {
1771 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
1775 constants.Add (name, e);
1776 vi.IsConstant = true;
1782 // Now, handle the children
1784 if (children != null) {
1785 foreach (Block b in children)
1786 b.ResolveMeta (toplevel, ec, ip);
1792 // Emits the local variable declarations for a block
1794 public void EmitMeta (EmitContext ec)
1796 ILGenerator ig = ec.ig;
1798 if (variables != null){
1799 bool have_captured_vars = ec.HaveCapturedVariables ();
1801 foreach (DictionaryEntry de in variables){
1802 LocalInfo vi = (LocalInfo) de.Value;
1804 if (have_captured_vars && ec.IsCaptured (vi))
1807 vi.DeclareLocal (ig);
1811 if (temporary_variables != null) {
1812 AnonymousContainer am = ec.CurrentAnonymousMethod;
1813 TypeBuilder scope = null;
1814 if ((am != null) && am.IsIterator) {
1815 scope = am.Scope.ScopeTypeBuilder;
1817 throw new InternalErrorException ();
1819 foreach (LocalInfo vi in temporary_variables) {
1820 if (scope != null) {
1821 if (vi.FieldBuilder == null)
1822 vi.FieldBuilder = scope.DefineField (
1823 vi.Name, vi.VariableType, FieldAttributes.Assembly);
1825 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1829 if (children != null){
1830 foreach (Block b in children)
1835 void UsageWarning (FlowBranching.UsageVector vector)
1839 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1840 foreach (DictionaryEntry de in variables){
1841 LocalInfo vi = (LocalInfo) de.Value;
1846 name = (string) de.Key;
1848 // vi.VariableInfo can be null for 'catch' variables
1849 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
1850 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
1852 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
1858 bool unreachable_shown;
1861 private void CheckPossibleMistakenEmptyStatement (Statement s)
1865 // Some statements are wrapped by a Block. Since
1866 // others' internal could be changed, here I treat
1867 // them as possibly wrapped by Block equally.
1868 Block b = s as Block;
1869 if (b != null && b.statements.Count == 1)
1870 s = (Statement) b.statements [0];
1873 body = ((Lock) s).Statement;
1875 body = ((For) s).Statement;
1876 else if (s is Foreach)
1877 body = ((Foreach) s).Statement;
1878 else if (s is While)
1879 body = ((While) s).Statement;
1880 else if (s is Using)
1881 body = ((Using) s).Statement;
1882 else if (s is Fixed)
1883 body = ((Fixed) s).Statement;
1887 if (body == null || body is EmptyStatement)
1888 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
1891 public override bool Resolve (EmitContext ec)
1893 Block prev_block = ec.CurrentBlock;
1896 int errors = Report.Errors;
1898 ec.CurrentBlock = this;
1899 ec.StartFlowBranching (this);
1901 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1903 int statement_count = statements.Count;
1904 for (int ix = 0; ix < statement_count; ix++){
1905 Statement s = (Statement) statements [ix];
1906 // Check possible empty statement (CS0642)
1907 if (RootContext.WarningLevel >= 3 &&
1908 ix + 1 < statement_count &&
1909 statements [ix + 1] is Block)
1910 CheckPossibleMistakenEmptyStatement (s);
1913 // Warn if we detect unreachable code.
1916 if (s is EmptyStatement)
1920 ((Block) s).unreachable = true;
1922 if (!unreachable_shown && !(s is LabeledStatement)) {
1923 Report.Warning (162, 2, s.loc, "Unreachable code detected");
1924 unreachable_shown = true;
1929 // Note that we're not using ResolveUnreachable() for unreachable
1930 // statements here. ResolveUnreachable() creates a temporary
1931 // flow branching and kills it afterwards. This leads to problems
1932 // if you have two unreachable statements where the first one
1933 // assigns a variable and the second one tries to access it.
1936 if (!s.Resolve (ec)) {
1938 statements [ix] = EmptyStatement.Value;
1942 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1943 statements [ix] = EmptyStatement.Value;
1945 num_statements = ix + 1;
1947 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1948 if (unreachable && s is LabeledStatement)
1949 throw new InternalErrorException ("should not happen");
1952 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1953 ec.CurrentBranching, statement_count, num_statements);
1955 while (ec.CurrentBranching is FlowBranchingLabeled)
1956 ec.EndFlowBranching ();
1958 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1960 ec.CurrentBlock = prev_block;
1962 // If we're a non-static `struct' constructor which doesn't have an
1963 // initializer, then we must initialize all of the struct's fields.
1964 if ((flags & Flags.IsToplevel) != 0 &&
1965 !Toplevel.IsThisAssigned (ec) &&
1966 !vector.Reachability.AlwaysThrows)
1969 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1970 foreach (LabeledStatement label in labels.Values)
1971 if (!label.HasBeenReferenced)
1972 Report.Warning (164, 2, label.loc,
1973 "This label has not been referenced");
1976 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1978 if (vector.Reachability.IsUnreachable)
1979 flags |= Flags.HasRet;
1981 if (ok && (errors == Report.Errors)) {
1982 if (RootContext.WarningLevel >= 3)
1983 UsageWarning (vector);
1989 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1991 unreachable_shown = true;
1995 Report.Warning (162, 2, loc, "Unreachable code detected");
1997 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1998 bool ok = Resolve (ec);
1999 ec.KillFlowBranching ();
2004 protected override void DoEmit (EmitContext ec)
2006 for (int ix = 0; ix < num_statements; ix++){
2007 Statement s = (Statement) statements [ix];
2009 // Check whether we are the last statement in a
2012 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2013 ec.IsLastStatement = true;
2015 ec.IsLastStatement = false;
2021 public override void Emit (EmitContext ec)
2023 Block prev_block = ec.CurrentBlock;
2025 ec.CurrentBlock = this;
2027 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2028 bool is_lexical_block = !Implicit && (Parent != null);
2030 if (emit_debug_info) {
2031 if (is_lexical_block)
2034 if (variables != null) {
2035 foreach (DictionaryEntry de in variables) {
2036 string name = (string) de.Key;
2037 LocalInfo vi = (LocalInfo) de.Value;
2039 if (vi.LocalBuilder == null)
2042 ec.DefineLocalVariable (name, vi.LocalBuilder);
2046 ec.Mark (StartLocation, true);
2047 ec.EmitScopeInitFromBlock (this);
2049 ec.Mark (EndLocation, true);
2051 if (emit_debug_info && is_lexical_block)
2054 ec.CurrentBlock = prev_block;
2058 // Returns true if we ar ea child of `b'.
2060 public bool IsChildOf (Block b)
2062 Block current = this;
2065 if (current.Parent == b)
2067 current = current.Parent;
2068 } while (current != null);
2072 public override string ToString ()
2074 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2079 // A toplevel block contains extra information, the split is done
2080 // only to separate information that would otherwise bloat the more
2081 // lightweight Block.
2083 // In particular, this was introduced when the support for Anonymous
2084 // Methods was implemented.
2086 public class ToplevelBlock : Block {
2088 // Pointer to the host of this anonymous method, or null
2089 // if we are the topmost block
2091 ToplevelBlock container;
2092 CaptureContext capture_context;
2093 FlowBranching top_level_branching;
2095 Hashtable capture_contexts;
2098 public bool HasVarargs {
2099 get { return (flags & Flags.HasVarargs) != 0; }
2100 set { flags |= Flags.HasVarargs; }
2104 // The parameters for the block.
2106 public readonly Parameters Parameters;
2108 public void RegisterCaptureContext (CaptureContext cc)
2110 if (capture_contexts == null)
2111 capture_contexts = new Hashtable ();
2112 capture_contexts [cc] = cc;
2115 public void CompleteContexts ()
2117 if (capture_contexts == null)
2120 foreach (CaptureContext cc in capture_contexts.Keys){
2125 public CaptureContext ToplevelBlockCaptureContext {
2126 get { return capture_context; }
2129 public ToplevelBlock Container {
2130 get { return container; }
2133 protected void AddChild (ToplevelBlock block)
2135 if (children == null)
2136 children = new ArrayList ();
2138 children.Add (block);
2142 // Parent is only used by anonymous blocks to link back to their
2145 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2146 this (container, (Flags) 0, parameters, start)
2150 public ToplevelBlock (Parameters parameters, Location start) :
2151 this (null, (Flags) 0, parameters, start)
2155 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2156 this (null, flags, parameters, start)
2160 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2161 base (null, flags | Flags.IsToplevel, start, Location.Null)
2163 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2164 this.container = container;
2166 if (container != null)
2167 container.AddChild (this);
2170 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2174 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2176 if (capture_context == null)
2177 capture_context = new CaptureContext (this, loc, host);
2180 public CaptureContext CaptureContext {
2181 get { return capture_context; }
2184 public FlowBranching TopLevelBranching {
2185 get { return top_level_branching; }
2189 // This is used if anonymous methods are used inside an iterator
2190 // (see 2test-22.cs for an example).
2192 // The AnonymousMethod is created while parsing - at a time when we don't
2193 // know yet that we're inside an iterator, so it's `Container' is initially
2194 // null. Later on, when resolving the iterator, we need to move the
2195 // anonymous method into that iterator.
2197 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2199 foreach (ToplevelBlock block in children) {
2200 if (block.CaptureContext == null)
2203 block.container = new_parent;
2204 block.CaptureContext.ReParent (new_parent, new_host);
2209 // Returns a `ParameterReference' for the given name, or null if there
2210 // is no such parameter
2212 public ParameterReference GetParameterReference (string name, Location loc)
2217 for (ToplevelBlock t = this; t != null; t = t.Container) {
2218 Parameters pars = t.Parameters;
2219 par = pars.GetParameterByName (name, out idx);
2221 return new ParameterReference (par, this, idx, loc);
2227 // Whether the parameter named `name' is local to this block,
2228 // or false, if the parameter belongs to an encompassing block.
2230 public bool IsLocalParameter (string name)
2232 return Parameters.GetParameterByName (name) != null;
2236 // Whether the `name' is a parameter reference
2238 public bool IsParameterReference (string name)
2240 for (ToplevelBlock t = this; t != null; t = t.Container) {
2241 if (t.IsLocalParameter (name))
2247 LocalInfo this_variable = null;
2250 // Returns the "this" instance variable of this block.
2251 // See AddThisVariable() for more information.
2253 public LocalInfo ThisVariable {
2254 get { return this_variable; }
2259 // This is used by non-static `struct' constructors which do not have an
2260 // initializer - in this case, the constructor must initialize all of the
2261 // struct's fields. To do this, we add a "this" variable and use the flow
2262 // analysis code to ensure that it's been fully initialized before control
2263 // leaves the constructor.
2265 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2267 if (this_variable == null) {
2268 this_variable = new LocalInfo (ds, this, l);
2269 this_variable.Used = true;
2270 this_variable.IsThis = true;
2272 Variables.Add ("this", this_variable);
2275 return this_variable;
2278 public bool IsThisAssigned (EmitContext ec)
2280 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2283 public bool ResolveMeta (EmitContext ec, Parameters ip)
2285 int errors = Report.Errors;
2287 if (top_level_branching != null)
2290 ResolveMeta (this, ec, ip);
2292 top_level_branching = ec.StartFlowBranching (this);
2294 return Report.Errors == errors;
2298 public class SwitchLabel {
2305 Label il_label_code;
2306 bool il_label_code_set;
2308 public static readonly object NullStringCase = new object ();
2311 // if expr == null, then it is the default case.
2313 public SwitchLabel (Expression expr, Location l)
2319 public Expression Label {
2325 public object Converted {
2331 public Label GetILLabel (EmitContext ec)
2334 il_label = ec.ig.DefineLabel ();
2335 il_label_set = true;
2340 public Label GetILLabelCode (EmitContext ec)
2342 if (!il_label_code_set){
2343 il_label_code = ec.ig.DefineLabel ();
2344 il_label_code_set = true;
2346 return il_label_code;
2350 // Resolves the expression, reduces it to a literal if possible
2351 // and then converts it to the requested type.
2353 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2355 Expression e = label.Resolve (ec);
2360 Constant c = e as Constant;
2362 Report.Error (150, loc, "A constant value is expected");
2366 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2367 converted = NullStringCase;
2371 c = c.ToType (required_type, loc);
2375 converted = c.GetValue ();
2379 public void Erorr_AlreadyOccurs ()
2382 if (converted == null)
2384 else if (converted == NullStringCase)
2387 label = converted.ToString ();
2389 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2393 public class SwitchSection {
2394 // An array of SwitchLabels.
2395 public readonly ArrayList Labels;
2396 public readonly Block Block;
2398 public SwitchSection (ArrayList labels, Block block)
2405 public class Switch : Statement {
2406 public readonly ArrayList Sections;
2407 public Expression Expr;
2410 /// Maps constants whose type type SwitchType to their SwitchLabels.
2412 public IDictionary Elements;
2415 /// The governing switch type
2417 public Type SwitchType;
2422 Label default_target;
2423 Expression new_expr;
2425 SwitchSection constant_section;
2426 SwitchSection default_section;
2429 // The types allowed to be implicitly cast from
2430 // on the governing type
2432 static Type [] allowed_types;
2434 public Switch (Expression e, ArrayList sects, Location l)
2441 public bool GotDefault {
2443 return default_section != null;
2447 public Label DefaultTarget {
2449 return default_target;
2454 // Determines the governing type for a switch. The returned
2455 // expression might be the expression from the switch, or an
2456 // expression that includes any potential conversions to the
2457 // integral types or to string.
2459 Expression SwitchGoverningType (EmitContext ec, Type t)
2461 if (t == TypeManager.byte_type ||
2462 t == TypeManager.sbyte_type ||
2463 t == TypeManager.ushort_type ||
2464 t == TypeManager.short_type ||
2465 t == TypeManager.uint32_type ||
2466 t == TypeManager.int32_type ||
2467 t == TypeManager.uint64_type ||
2468 t == TypeManager.int64_type ||
2469 t == TypeManager.char_type ||
2470 t == TypeManager.string_type ||
2471 t == TypeManager.bool_type ||
2472 t.IsSubclassOf (TypeManager.enum_type))
2475 if (allowed_types == null){
2476 allowed_types = new Type [] {
2477 TypeManager.sbyte_type,
2478 TypeManager.byte_type,
2479 TypeManager.short_type,
2480 TypeManager.ushort_type,
2481 TypeManager.int32_type,
2482 TypeManager.uint32_type,
2483 TypeManager.int64_type,
2484 TypeManager.uint64_type,
2485 TypeManager.char_type,
2486 TypeManager.string_type,
2487 TypeManager.bool_type
2492 // Try to find a *user* defined implicit conversion.
2494 // If there is no implicit conversion, or if there are multiple
2495 // conversions, we have to report an error
2497 Expression converted = null;
2498 foreach (Type tt in allowed_types){
2501 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2506 // Ignore over-worked ImplicitUserConversions that do
2507 // an implicit conversion in addition to the user conversion.
2509 if (!(e is UserCast))
2512 if (converted != null){
2513 Report.ExtraInformation (
2515 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2516 TypeManager.CSharpName (Expr.Type)));
2526 // Performs the basic sanity checks on the switch statement
2527 // (looks for duplicate keys and non-constant expressions).
2529 // It also returns a hashtable with the keys that we will later
2530 // use to compute the switch tables
2532 bool CheckSwitch (EmitContext ec)
2535 Elements = Sections.Count > 10 ?
2536 (IDictionary)new Hashtable () :
2537 (IDictionary)new ListDictionary ();
2539 foreach (SwitchSection ss in Sections){
2540 foreach (SwitchLabel sl in ss.Labels){
2541 if (sl.Label == null){
2542 if (default_section != null){
2543 sl.Erorr_AlreadyOccurs ();
2546 default_section = ss;
2550 if (!sl.ResolveAndReduce (ec, SwitchType)){
2555 object key = sl.Converted;
2557 Elements.Add (key, sl);
2559 catch (ArgumentException) {
2560 sl.Erorr_AlreadyOccurs ();
2568 void EmitObjectInteger (ILGenerator ig, object k)
2571 IntConstant.EmitInt (ig, (int) k);
2572 else if (k is Constant) {
2573 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2576 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2579 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2581 IntConstant.EmitInt (ig, (int) (long) k);
2582 ig.Emit (OpCodes.Conv_I8);
2585 LongConstant.EmitLong (ig, (long) k);
2587 else if (k is ulong)
2589 ulong ul = (ulong) k;
2592 IntConstant.EmitInt (ig, unchecked ((int) ul));
2593 ig.Emit (OpCodes.Conv_U8);
2597 LongConstant.EmitLong (ig, unchecked ((long) ul));
2601 IntConstant.EmitInt (ig, (int) ((char) k));
2602 else if (k is sbyte)
2603 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2605 IntConstant.EmitInt (ig, (int) ((byte) k));
2606 else if (k is short)
2607 IntConstant.EmitInt (ig, (int) ((short) k));
2608 else if (k is ushort)
2609 IntConstant.EmitInt (ig, (int) ((ushort) k));
2611 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2613 throw new Exception ("Unhandled case");
2616 // structure used to hold blocks of keys while calculating table switch
2617 class KeyBlock : IComparable
2619 public KeyBlock (long _nFirst)
2621 nFirst = nLast = _nFirst;
2625 public ArrayList rgKeys = null;
2626 // how many items are in the bucket
2627 public int Size = 1;
2630 get { return (int) (nLast - nFirst + 1); }
2632 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2634 return kbLast.nLast - kbFirst.nFirst + 1;
2636 public int CompareTo (object obj)
2638 KeyBlock kb = (KeyBlock) obj;
2639 int nLength = Length;
2640 int nLengthOther = kb.Length;
2641 if (nLengthOther == nLength)
2642 return (int) (kb.nFirst - nFirst);
2643 return nLength - nLengthOther;
2648 /// This method emits code for a lookup-based switch statement (non-string)
2649 /// Basically it groups the cases into blocks that are at least half full,
2650 /// and then spits out individual lookup opcodes for each block.
2651 /// It emits the longest blocks first, and short blocks are just
2652 /// handled with direct compares.
2654 /// <param name="ec"></param>
2655 /// <param name="val"></param>
2656 /// <returns></returns>
2657 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2659 int cElements = Elements.Count;
2660 object [] rgKeys = new object [cElements];
2661 Elements.Keys.CopyTo (rgKeys, 0);
2662 Array.Sort (rgKeys);
2664 // initialize the block list with one element per key
2665 ArrayList rgKeyBlocks = new ArrayList ();
2666 foreach (object key in rgKeys)
2667 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2670 // iteratively merge the blocks while they are at least half full
2671 // there's probably a really cool way to do this with a tree...
2672 while (rgKeyBlocks.Count > 1)
2674 ArrayList rgKeyBlocksNew = new ArrayList ();
2675 kbCurr = (KeyBlock) rgKeyBlocks [0];
2676 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2678 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2679 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2682 kbCurr.nLast = kb.nLast;
2683 kbCurr.Size += kb.Size;
2687 // start a new block
2688 rgKeyBlocksNew.Add (kbCurr);
2692 rgKeyBlocksNew.Add (kbCurr);
2693 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2695 rgKeyBlocks = rgKeyBlocksNew;
2698 // initialize the key lists
2699 foreach (KeyBlock kb in rgKeyBlocks)
2700 kb.rgKeys = new ArrayList ();
2702 // fill the key lists
2704 if (rgKeyBlocks.Count > 0) {
2705 kbCurr = (KeyBlock) rgKeyBlocks [0];
2706 foreach (object key in rgKeys)
2708 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2709 System.Convert.ToInt64 (key) > kbCurr.nLast;
2711 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2712 kbCurr.rgKeys.Add (key);
2716 // sort the blocks so we can tackle the largest ones first
2717 rgKeyBlocks.Sort ();
2719 // okay now we can start...
2720 ILGenerator ig = ec.ig;
2721 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2722 Label lblDefault = ig.DefineLabel ();
2724 Type typeKeys = null;
2725 if (rgKeys.Length > 0)
2726 typeKeys = rgKeys [0].GetType (); // used for conversions
2730 if (TypeManager.IsEnumType (SwitchType))
2731 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2733 compare_type = SwitchType;
2735 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2737 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2738 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2741 foreach (object key in kb.rgKeys)
2743 ig.Emit (OpCodes.Ldloc, val);
2744 EmitObjectInteger (ig, key);
2745 SwitchLabel sl = (SwitchLabel) Elements [key];
2746 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2751 // TODO: if all the keys in the block are the same and there are
2752 // no gaps/defaults then just use a range-check.
2753 if (compare_type == TypeManager.int64_type ||
2754 compare_type == TypeManager.uint64_type)
2756 // TODO: optimize constant/I4 cases
2758 // check block range (could be > 2^31)
2759 ig.Emit (OpCodes.Ldloc, val);
2760 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2761 ig.Emit (OpCodes.Blt, lblDefault);
2762 ig.Emit (OpCodes.Ldloc, val);
2763 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2764 ig.Emit (OpCodes.Bgt, lblDefault);
2767 ig.Emit (OpCodes.Ldloc, val);
2770 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2771 ig.Emit (OpCodes.Sub);
2773 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2778 ig.Emit (OpCodes.Ldloc, val);
2779 int nFirst = (int) kb.nFirst;
2782 IntConstant.EmitInt (ig, nFirst);
2783 ig.Emit (OpCodes.Sub);
2785 else if (nFirst < 0)
2787 IntConstant.EmitInt (ig, -nFirst);
2788 ig.Emit (OpCodes.Add);
2792 // first, build the list of labels for the switch
2794 int cJumps = kb.Length;
2795 Label [] rgLabels = new Label [cJumps];
2796 for (int iJump = 0; iJump < cJumps; iJump++)
2798 object key = kb.rgKeys [iKey];
2799 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2801 SwitchLabel sl = (SwitchLabel) Elements [key];
2802 rgLabels [iJump] = sl.GetILLabel (ec);
2806 rgLabels [iJump] = lblDefault;
2808 // emit the switch opcode
2809 ig.Emit (OpCodes.Switch, rgLabels);
2812 // mark the default for this block
2814 ig.MarkLabel (lblDefault);
2817 // TODO: find the default case and emit it here,
2818 // to prevent having to do the following jump.
2819 // make sure to mark other labels in the default section
2821 // the last default just goes to the end
2822 ig.Emit (OpCodes.Br, lblDefault);
2824 // now emit the code for the sections
2825 bool fFoundDefault = false;
2826 foreach (SwitchSection ss in Sections)
2828 foreach (SwitchLabel sl in ss.Labels)
2830 ig.MarkLabel (sl.GetILLabel (ec));
2831 ig.MarkLabel (sl.GetILLabelCode (ec));
2832 if (sl.Label == null)
2834 ig.MarkLabel (lblDefault);
2835 fFoundDefault = true;
2839 //ig.Emit (OpCodes.Br, lblEnd);
2842 if (!fFoundDefault) {
2843 ig.MarkLabel (lblDefault);
2845 ig.MarkLabel (lblEnd);
2848 // This simple emit switch works, but does not take advantage of the
2850 // TODO: remove non-string logic from here
2851 // TODO: binary search strings?
2853 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2855 ILGenerator ig = ec.ig;
2856 Label end_of_switch = ig.DefineLabel ();
2857 Label next_test = ig.DefineLabel ();
2858 Label null_target = ig.DefineLabel ();
2859 bool first_test = true;
2860 bool pending_goto_end = false;
2861 bool null_marked = false;
2864 ig.Emit (OpCodes.Ldloc, val);
2866 if (Elements.Contains (SwitchLabel.NullStringCase)){
2867 ig.Emit (OpCodes.Brfalse, null_target);
2869 ig.Emit (OpCodes.Brfalse, default_target);
2871 ig.Emit (OpCodes.Ldloc, val);
2872 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2873 ig.Emit (OpCodes.Stloc, val);
2875 int section_count = Sections.Count;
2876 for (int section = 0; section < section_count; section++){
2877 SwitchSection ss = (SwitchSection) Sections [section];
2879 if (ss == default_section)
2882 Label sec_begin = ig.DefineLabel ();
2884 ig.Emit (OpCodes.Nop);
2886 if (pending_goto_end)
2887 ig.Emit (OpCodes.Br, end_of_switch);
2889 int label_count = ss.Labels.Count;
2891 for (int label = 0; label < label_count; label++){
2892 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2893 ig.MarkLabel (sl.GetILLabel (ec));
2896 ig.MarkLabel (next_test);
2897 next_test = ig.DefineLabel ();
2900 // If we are the default target
2902 if (sl.Label != null){
2903 object lit = sl.Converted;
2905 if (lit == SwitchLabel.NullStringCase){
2907 if (label + 1 == label_count)
2908 ig.Emit (OpCodes.Br, next_test);
2912 ig.Emit (OpCodes.Ldloc, val);
2913 ig.Emit (OpCodes.Ldstr, (string)lit);
2914 if (label_count == 1)
2915 ig.Emit (OpCodes.Bne_Un, next_test);
2917 if (label+1 == label_count)
2918 ig.Emit (OpCodes.Bne_Un, next_test);
2920 ig.Emit (OpCodes.Beq, sec_begin);
2925 ig.MarkLabel (null_target);
2928 ig.MarkLabel (sec_begin);
2929 foreach (SwitchLabel sl in ss.Labels)
2930 ig.MarkLabel (sl.GetILLabelCode (ec));
2933 pending_goto_end = !ss.Block.HasRet;
2936 ig.MarkLabel (next_test);
2937 ig.MarkLabel (default_target);
2939 ig.MarkLabel (null_target);
2940 if (default_section != null)
2941 default_section.Block.Emit (ec);
2942 ig.MarkLabel (end_of_switch);
2945 SwitchSection FindSection (SwitchLabel label)
2947 foreach (SwitchSection ss in Sections){
2948 foreach (SwitchLabel sl in ss.Labels){
2957 public override bool Resolve (EmitContext ec)
2959 Expr = Expr.Resolve (ec);
2963 new_expr = SwitchGoverningType (ec, Expr.Type);
2964 if (new_expr == null){
2965 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2970 SwitchType = new_expr.Type;
2972 if (!CheckSwitch (ec))
2975 Switch old_switch = ec.Switch;
2977 ec.Switch.SwitchType = SwitchType;
2979 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2980 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2982 is_constant = new_expr is Constant;
2984 object key = ((Constant) new_expr).GetValue ();
2985 SwitchLabel label = (SwitchLabel) Elements [key];
2987 constant_section = FindSection (label);
2988 if (constant_section == null)
2989 constant_section = default_section;
2993 foreach (SwitchSection ss in Sections){
2995 ec.CurrentBranching.CreateSibling (
2996 null, FlowBranching.SiblingType.SwitchSection);
3000 if (is_constant && (ss != constant_section)) {
3001 // If we're a constant switch, we're only emitting
3002 // one single section - mark all the others as
3004 ec.CurrentBranching.CurrentUsageVector.Goto ();
3005 if (!ss.Block.ResolveUnreachable (ec, true))
3008 if (!ss.Block.Resolve (ec))
3013 if (default_section == null)
3014 ec.CurrentBranching.CreateSibling (
3015 null, FlowBranching.SiblingType.SwitchSection);
3017 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3018 ec.Switch = old_switch;
3020 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3026 protected override void DoEmit (EmitContext ec)
3028 ILGenerator ig = ec.ig;
3030 // Store variable for comparission purposes
3033 value = ig.DeclareLocal (SwitchType);
3035 ig.Emit (OpCodes.Stloc, value);
3039 default_target = ig.DefineLabel ();
3042 // Setup the codegen context
3044 Label old_end = ec.LoopEnd;
3045 Switch old_switch = ec.Switch;
3047 ec.LoopEnd = ig.DefineLabel ();
3052 if (constant_section != null)
3053 constant_section.Block.Emit (ec);
3054 } else if (SwitchType == TypeManager.string_type)
3055 SimpleSwitchEmit (ec, value);
3057 TableSwitchEmit (ec, value);
3059 // Restore context state.
3060 ig.MarkLabel (ec.LoopEnd);
3063 // Restore the previous context
3065 ec.LoopEnd = old_end;
3066 ec.Switch = old_switch;
3070 public abstract class ExceptionStatement : Statement
3072 public abstract void EmitFinally (EmitContext ec);
3074 protected bool emit_finally = true;
3075 ArrayList parent_vectors;
3077 protected void DoEmitFinally (EmitContext ec)
3080 ec.ig.BeginFinallyBlock ();
3081 else if (ec.InIterator)
3082 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3086 protected void ResolveFinally (FlowBranchingException branching)
3088 emit_finally = branching.EmitFinally;
3090 branching.Parent.StealFinallyClauses (ref parent_vectors);
3094 public class Lock : ExceptionStatement {
3096 public Statement Statement;
3097 TemporaryVariable temp;
3099 public Lock (Expression expr, Statement stmt, Location l)
3106 public override bool Resolve (EmitContext ec)
3108 expr = expr.Resolve (ec);
3112 if (expr.Type.IsValueType){
3113 Report.Error (185, loc,
3114 "`{0}' is not a reference type as required by the lock statement",
3115 TypeManager.CSharpName (expr.Type));
3119 FlowBranchingException branching = ec.StartFlowBranching (this);
3120 bool ok = Statement.Resolve (ec);
3122 ec.KillFlowBranching ();
3126 ResolveFinally (branching);
3128 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3129 if (!reachability.AlwaysReturns) {
3130 // Unfortunately, System.Reflection.Emit automatically emits
3131 // a leave to the end of the finally block.
3132 // This is a problem if `returns' is true since we may jump
3133 // to a point after the end of the method.
3134 // As a workaround, emit an explicit ret here.
3135 ec.NeedReturnLabel ();
3138 // Avoid creating libraries that reference the internal
3141 if (t == TypeManager.null_type)
3142 t = TypeManager.object_type;
3144 temp = new TemporaryVariable (t, loc);
3150 protected override void DoEmit (EmitContext ec)
3152 ILGenerator ig = ec.ig;
3154 temp.Store (ec, expr);
3156 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3160 ig.BeginExceptionBlock ();
3161 Statement.Emit (ec);
3166 ig.EndExceptionBlock ();
3169 public override void EmitFinally (EmitContext ec)
3172 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3176 public class Unchecked : Statement {
3177 public readonly Block Block;
3179 public Unchecked (Block b)
3185 public override bool Resolve (EmitContext ec)
3187 using (ec.WithCheckState (false, false))
3188 return Block.Resolve (ec);
3191 protected override void DoEmit (EmitContext ec)
3193 using (ec.WithCheckState (false, false))
3198 public class Checked : Statement {
3199 public readonly Block Block;
3201 public Checked (Block b)
3204 b.Unchecked = false;
3207 public override bool Resolve (EmitContext ec)
3209 using (ec.WithCheckState (true, true))
3210 return Block.Resolve (ec);
3213 protected override void DoEmit (EmitContext ec)
3215 using (ec.WithCheckState (true, true))
3220 public class Unsafe : Statement {
3221 public readonly Block Block;
3223 public Unsafe (Block b)
3226 Block.Unsafe = true;
3229 public override bool Resolve (EmitContext ec)
3231 using (ec.WithUnsafe (true))
3232 return Block.Resolve (ec);
3235 protected override void DoEmit (EmitContext ec)
3237 using (ec.WithUnsafe (true))
3245 public class Fixed : Statement {
3247 ArrayList declarators;
3248 Statement statement;
3253 abstract class Emitter
3255 protected LocalInfo vi;
3256 protected Expression converted;
3258 protected Emitter (Expression expr, LocalInfo li)
3264 public abstract void Emit (EmitContext ec);
3265 public abstract void EmitExit (ILGenerator ig);
3268 class ExpressionEmitter : Emitter {
3269 public ExpressionEmitter (Expression converted, LocalInfo li) :
3270 base (converted, li)
3274 public override void Emit (EmitContext ec) {
3276 // Store pointer in pinned location
3278 converted.Emit (ec);
3279 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3282 public override void EmitExit (ILGenerator ig)
3284 ig.Emit (OpCodes.Ldc_I4_0);
3285 ig.Emit (OpCodes.Conv_U);
3286 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3290 class StringEmitter : Emitter {
3291 LocalBuilder pinned_string;
3294 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3300 public override void Emit (EmitContext ec)
3302 ILGenerator ig = ec.ig;
3303 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3305 converted.Emit (ec);
3306 ig.Emit (OpCodes.Stloc, pinned_string);
3308 Expression sptr = new StringPtr (pinned_string, loc);
3309 converted = Convert.ImplicitConversionRequired (
3310 ec, sptr, vi.VariableType, loc);
3312 if (converted == null)
3315 converted.Emit (ec);
3316 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3319 public override void EmitExit(ILGenerator ig)
3321 ig.Emit (OpCodes.Ldnull);
3322 ig.Emit (OpCodes.Stloc, pinned_string);
3326 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3329 declarators = decls;
3334 public Statement Statement {
3335 get { return statement; }
3338 public override bool Resolve (EmitContext ec)
3341 Expression.UnsafeError (loc);
3345 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3349 expr_type = texpr.Type;
3351 data = new Emitter [declarators.Count];
3353 if (!expr_type.IsPointer){
3354 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3359 foreach (Pair p in declarators){
3360 LocalInfo vi = (LocalInfo) p.First;
3361 Expression e = (Expression) p.Second;
3363 vi.VariableInfo.SetAssigned (ec);
3364 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3367 // The rules for the possible declarators are pretty wise,
3368 // but the production on the grammar is more concise.
3370 // So we have to enforce these rules here.
3372 // We do not resolve before doing the case 1 test,
3373 // because the grammar is explicit in that the token &
3374 // is present, so we need to test for this particular case.
3378 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3383 // Case 1: & object.
3385 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3386 Expression child = ((Unary) e).Expr;
3388 if (child is ParameterReference || child is LocalVariableReference){
3391 "No need to use fixed statement for parameters or " +
3392 "local variable declarations (address is already " +
3397 ec.InFixedInitializer = true;
3399 ec.InFixedInitializer = false;
3403 child = ((Unary) e).Expr;
3405 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3408 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
3409 e.Error_ValueCannotBeConverted (e.Location, expr_type, false);
3413 data [i] = new ExpressionEmitter (e, vi);
3419 ec.InFixedInitializer = true;
3421 ec.InFixedInitializer = false;
3428 if (e.Type.IsArray){
3429 Type array_type = TypeManager.GetElementType (e.Type);
3432 // Provided that array_type is unmanaged,
3434 if (!TypeManager.VerifyUnManaged (array_type, loc))
3438 // and T* is implicitly convertible to the
3439 // pointer type given in the fixed statement.
3441 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3443 Expression converted = Convert.ImplicitConversionRequired (
3444 ec, array_ptr, vi.VariableType, loc);
3445 if (converted == null)
3448 data [i] = new ExpressionEmitter (converted, vi);
3457 if (e.Type == TypeManager.string_type){
3458 data [i] = new StringEmitter (e, vi, loc);
3463 // Case 4: fixed buffer
3464 FieldExpr fe = e as FieldExpr;
3466 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3468 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3470 Expression converted = Convert.ImplicitConversionRequired (
3471 ec, fixed_buffer_ptr, vi.VariableType, loc);
3472 if (converted == null)
3475 data [i] = new ExpressionEmitter (converted, vi);
3483 // For other cases, flag a `this is already fixed expression'
3485 if (e is LocalVariableReference || e is ParameterReference ||
3486 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3488 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3492 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3496 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3498 if (!statement.Resolve (ec)) {
3499 ec.KillFlowBranching ();
3503 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3504 has_ret = reachability.IsUnreachable;
3509 protected override void DoEmit (EmitContext ec)
3511 for (int i = 0; i < data.Length; i++) {
3515 statement.Emit (ec);
3520 ILGenerator ig = ec.ig;
3523 // Clear the pinned variable
3525 for (int i = 0; i < data.Length; i++) {
3526 data [i].EmitExit (ig);
3531 public class Catch : Statement {
3532 public readonly string Name;
3533 public readonly Block Block;
3534 public readonly Block VarBlock;
3536 Expression type_expr;
3539 public Catch (Expression type, string name, Block block, Block var_block, Location l)
3544 VarBlock = var_block;
3548 public Type CatchType {
3554 public bool IsGeneral {
3556 return type_expr == null;
3560 protected override void DoEmit(EmitContext ec)
3564 public override bool Resolve (EmitContext ec)
3566 bool was_catch = ec.InCatch;
3569 if (type_expr != null) {
3570 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3576 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3577 Error (155, "The type caught or thrown must be derived from System.Exception");
3583 if (!Block.Resolve (ec))
3586 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
3587 // emit the "unused variable" warnings.
3588 if (VarBlock != null)
3589 return VarBlock.Resolve (ec);
3594 ec.InCatch = was_catch;
3599 public class Try : ExceptionStatement {
3600 public readonly Block Fini, Block;
3601 public readonly ArrayList Specific;
3602 public readonly Catch General;
3604 bool need_exc_block;
3607 // specific, general and fini might all be null.
3609 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3611 if (specific == null && general == null){
3612 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3616 this.Specific = specific;
3617 this.General = general;
3622 public override bool Resolve (EmitContext ec)
3626 FlowBranchingException branching = ec.StartFlowBranching (this);
3628 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3630 if (!Block.Resolve (ec))
3633 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3635 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3637 Type[] prevCatches = new Type [Specific.Count];
3639 foreach (Catch c in Specific){
3640 ec.CurrentBranching.CreateSibling (
3641 c.Block, FlowBranching.SiblingType.Catch);
3643 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3645 if (c.Name != null) {
3646 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3648 throw new Exception ();
3650 vi.VariableInfo = null;
3653 if (!c.Resolve (ec))
3656 Type resolvedType = c.CatchType;
3657 for (int ii = 0; ii < last_index; ++ii) {
3658 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3659 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3664 prevCatches [last_index++] = resolvedType;
3665 need_exc_block = true;
3668 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3670 if (General != null){
3671 if (CodeGen.Assembly.WrapNonExceptionThrows) {
3672 foreach (Catch c in Specific){
3673 if (c.CatchType == TypeManager.exception_type) {
3674 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'");
3679 ec.CurrentBranching.CreateSibling (
3680 General.Block, FlowBranching.SiblingType.Catch);
3682 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3684 if (!General.Resolve (ec))
3687 need_exc_block = true;
3690 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3694 ec.CurrentBranching.CreateSibling (
3695 Fini, FlowBranching.SiblingType.Finally);
3697 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3698 bool was_finally = ec.InFinally;
3699 ec.InFinally = true;
3700 if (!Fini.Resolve (ec))
3702 ec.InFinally = was_finally;
3705 need_exc_block = true;
3708 if (ec.InIterator) {
3709 ResolveFinally (branching);
3710 need_exc_block |= emit_finally;
3712 emit_finally = Fini != null;
3714 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3716 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3718 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3720 if (!reachability.AlwaysReturns) {
3721 // Unfortunately, System.Reflection.Emit automatically emits
3722 // a leave to the end of the finally block. This is a problem
3723 // if `returns' is true since we may jump to a point after the
3724 // end of the method.
3725 // As a workaround, emit an explicit ret here.
3726 ec.NeedReturnLabel ();
3732 protected override void DoEmit (EmitContext ec)
3734 ILGenerator ig = ec.ig;
3737 ig.BeginExceptionBlock ();
3740 foreach (Catch c in Specific){
3743 ig.BeginCatchBlock (c.CatchType);
3745 if (c.VarBlock != null)
3746 ec.EmitScopeInitFromBlock (c.VarBlock);
3747 if (c.Name != null){
3748 vi = c.Block.GetLocalInfo (c.Name);
3750 throw new Exception ("Variable does not exist in this block");
3753 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
3754 ig.Emit (OpCodes.Stloc, e);
3756 ec.EmitCapturedVariableInstance (vi);
3757 ig.Emit (OpCodes.Ldloc, e);
3758 ig.Emit (OpCodes.Stfld, vi.FieldBuilder);
3760 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3762 ig.Emit (OpCodes.Pop);
3767 if (General != null){
3768 ig.BeginCatchBlock (TypeManager.object_type);
3769 ig.Emit (OpCodes.Pop);
3770 General.Block.Emit (ec);
3775 ig.EndExceptionBlock ();
3778 public override void EmitFinally (EmitContext ec)
3784 public bool HasCatch
3787 return General != null || Specific.Count > 0;
3792 public class Using : ExceptionStatement {
3793 object expression_or_block;
3794 public Statement Statement;
3798 Expression [] resolved_vars;
3799 Expression [] converted_vars;
3800 ExpressionStatement [] assign;
3801 LocalBuilder local_copy;
3803 public Using (object expression_or_block, Statement stmt, Location l)
3805 this.expression_or_block = expression_or_block;
3811 // Resolves for the case of using using a local variable declaration.
3813 bool ResolveLocalVariableDecls (EmitContext ec)
3817 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3821 expr_type = texpr.Type;
3824 // The type must be an IDisposable or an implicit conversion
3827 converted_vars = new Expression [var_list.Count];
3828 resolved_vars = new Expression [var_list.Count];
3829 assign = new ExpressionStatement [var_list.Count];
3831 bool need_conv = !TypeManager.ImplementsInterface (
3832 expr_type, TypeManager.idisposable_type);
3834 foreach (DictionaryEntry e in var_list){
3835 Expression var = (Expression) e.Key;
3837 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3841 resolved_vars [i] = var;
3848 converted_vars [i] = Convert.ImplicitConversion (
3849 ec, var, TypeManager.idisposable_type, loc);
3851 if (converted_vars [i] == null) {
3852 Error_IsNotConvertibleToIDisposable ();
3860 foreach (DictionaryEntry e in var_list){
3861 Expression var = resolved_vars [i];
3862 Expression new_expr = (Expression) e.Value;
3865 a = new Assign (var, new_expr, loc);
3871 converted_vars [i] = var;
3872 assign [i] = (ExpressionStatement) a;
3879 void Error_IsNotConvertibleToIDisposable ()
3881 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
3882 TypeManager.CSharpName (expr_type));
3885 bool ResolveExpression (EmitContext ec)
3887 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3888 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3889 Error_IsNotConvertibleToIDisposable ();
3898 // Emits the code for the case of using using a local variable declaration.
3900 void EmitLocalVariableDecls (EmitContext ec)
3902 ILGenerator ig = ec.ig;
3905 for (i = 0; i < assign.Length; i++) {
3906 assign [i].EmitStatement (ec);
3909 ig.BeginExceptionBlock ();
3911 Statement.Emit (ec);
3912 var_list.Reverse ();
3917 void EmitLocalVariableDeclFinally (EmitContext ec)
3919 ILGenerator ig = ec.ig;
3921 int i = assign.Length;
3922 for (int ii = 0; ii < var_list.Count; ++ii){
3923 Expression var = resolved_vars [--i];
3924 Label skip = ig.DefineLabel ();
3926 if (!var.Type.IsValueType) {
3928 ig.Emit (OpCodes.Brfalse, skip);
3929 converted_vars [i].Emit (ec);
3930 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3932 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3934 if (!(ml is MethodGroupExpr)) {
3936 ig.Emit (OpCodes.Box, var.Type);
3937 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3939 MethodInfo mi = null;
3941 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3942 if (TypeManager.GetParameterData (mk).Count == 0) {
3949 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3953 IMemoryLocation mloc = (IMemoryLocation) var;
3955 mloc.AddressOf (ec, AddressOp.Load);
3956 ig.Emit (OpCodes.Call, mi);
3960 ig.MarkLabel (skip);
3963 ig.EndExceptionBlock ();
3965 ig.BeginFinallyBlock ();
3970 void EmitExpression (EmitContext ec)
3973 // Make a copy of the expression and operate on that.
3975 ILGenerator ig = ec.ig;
3976 local_copy = ig.DeclareLocal (expr_type);
3979 ig.Emit (OpCodes.Stloc, local_copy);
3982 ig.BeginExceptionBlock ();
3984 Statement.Emit (ec);
3988 ig.EndExceptionBlock ();
3991 void EmitExpressionFinally (EmitContext ec)
3993 ILGenerator ig = ec.ig;
3994 if (!local_copy.LocalType.IsValueType) {
3995 Label skip = ig.DefineLabel ();
3996 ig.Emit (OpCodes.Ldloc, local_copy);
3997 ig.Emit (OpCodes.Brfalse, skip);
3998 ig.Emit (OpCodes.Ldloc, local_copy);
3999 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4000 ig.MarkLabel (skip);
4002 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4004 if (!(ml is MethodGroupExpr)) {
4005 ig.Emit (OpCodes.Ldloc, local_copy);
4006 ig.Emit (OpCodes.Box, local_copy.LocalType);
4007 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4009 MethodInfo mi = null;
4011 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4012 if (TypeManager.GetParameterData (mk).Count == 0) {
4019 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4023 ig.Emit (OpCodes.Ldloca, local_copy);
4024 ig.Emit (OpCodes.Call, mi);
4029 public override bool Resolve (EmitContext ec)
4031 if (expression_or_block is DictionaryEntry){
4032 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4033 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4035 if (!ResolveLocalVariableDecls (ec))
4038 } else if (expression_or_block is Expression){
4039 expr = (Expression) expression_or_block;
4041 expr = expr.Resolve (ec);
4045 expr_type = expr.Type;
4047 if (!ResolveExpression (ec))
4051 FlowBranchingException branching = ec.StartFlowBranching (this);
4053 bool ok = Statement.Resolve (ec);
4056 ec.KillFlowBranching ();
4060 ResolveFinally (branching);
4061 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4063 if (!reachability.AlwaysReturns) {
4064 // Unfortunately, System.Reflection.Emit automatically emits a leave
4065 // to the end of the finally block. This is a problem if `returns'
4066 // is true since we may jump to a point after the end of the method.
4067 // As a workaround, emit an explicit ret here.
4068 ec.NeedReturnLabel ();
4074 protected override void DoEmit (EmitContext ec)
4076 if (expression_or_block is DictionaryEntry)
4077 EmitLocalVariableDecls (ec);
4078 else if (expression_or_block is Expression)
4079 EmitExpression (ec);
4082 public override void EmitFinally (EmitContext ec)
4084 if (expression_or_block is DictionaryEntry)
4085 EmitLocalVariableDeclFinally (ec);
4086 else if (expression_or_block is Expression)
4087 EmitExpressionFinally (ec);
4092 /// Implementation of the foreach C# statement
4094 public class Foreach : Statement {
4096 Expression variable;
4098 Statement statement;
4100 CollectionForeach collection;
4102 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4103 Statement stmt, Location l)
4106 this.variable = var;
4112 public Statement Statement {
4113 get { return statement; }
4116 public override bool Resolve (EmitContext ec)
4118 expr = expr.Resolve (ec);
4122 Constant c = expr as Constant;
4123 if (c != null && c.GetValue () == null) {
4124 Report.Error (186, loc, "Use of null is not valid in this context");
4128 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4132 Type var_type = texpr.Type;
4134 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethod) {
4135 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4136 expr.ExprClassName);
4141 // We need an instance variable. Not sure this is the best
4142 // way of doing this.
4144 // FIXME: When we implement propertyaccess, will those turn
4145 // out to return values in ExprClass? I think they should.
4147 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4148 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4149 collection.Error_Enumerator ();
4153 if (expr.Type.IsArray) {
4154 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4155 return array.Resolve (ec);
4157 collection = new CollectionForeach (
4158 var_type, variable, expr, statement, loc);
4159 return collection.Resolve (ec);
4163 protected override void DoEmit (EmitContext ec)
4165 ILGenerator ig = ec.ig;
4167 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4168 ec.LoopBegin = ig.DefineLabel ();
4169 ec.LoopEnd = ig.DefineLabel ();
4171 if (collection != null)
4172 collection.Emit (ec);
4176 ec.LoopBegin = old_begin;
4177 ec.LoopEnd = old_end;
4180 protected class ArrayCounter : TemporaryVariable
4182 public ArrayCounter (Location loc)
4183 : base (TypeManager.int32_type, loc)
4186 public void Initialize (EmitContext ec)
4189 ec.ig.Emit (OpCodes.Ldc_I4_0);
4193 public void Increment (EmitContext ec)
4197 ec.ig.Emit (OpCodes.Ldc_I4_1);
4198 ec.ig.Emit (OpCodes.Add);
4203 protected class ArrayForeach : Statement
4205 Expression variable, expr, conv;
4206 Statement statement;
4209 TemporaryVariable[] lengths;
4210 ArrayCounter[] counter;
4213 TemporaryVariable copy;
4216 public ArrayForeach (Type var_type, Expression var,
4217 Expression expr, Statement stmt, Location l)
4219 this.var_type = var_type;
4220 this.variable = var;
4226 public override bool Resolve (EmitContext ec)
4228 array_type = expr.Type;
4229 rank = array_type.GetArrayRank ();
4231 copy = new TemporaryVariable (array_type, loc);
4234 counter = new ArrayCounter [rank];
4235 lengths = new TemporaryVariable [rank];
4237 ArrayList list = new ArrayList ();
4238 for (int i = 0; i < rank; i++) {
4239 counter [i] = new ArrayCounter (loc);
4240 counter [i].Resolve (ec);
4242 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4243 lengths [i].Resolve (ec);
4245 list.Add (counter [i]);
4248 access = new ElementAccess (copy, list).Resolve (ec);
4252 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4258 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4259 ec.CurrentBranching.CreateSibling ();
4261 variable = variable.ResolveLValue (ec, conv, loc);
4262 if (variable == null)
4265 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4266 if (!statement.Resolve (ec))
4268 ec.EndFlowBranching ();
4270 // There's no direct control flow from the end of the embedded statement to the end of the loop
4271 ec.CurrentBranching.CurrentUsageVector.Goto ();
4273 ec.EndFlowBranching ();
4278 protected override void DoEmit (EmitContext ec)
4280 ILGenerator ig = ec.ig;
4282 copy.Store (ec, expr);
4284 Label[] test = new Label [rank];
4285 Label[] loop = new Label [rank];
4287 for (int i = 0; i < rank; i++) {
4288 test [i] = ig.DefineLabel ();
4289 loop [i] = ig.DefineLabel ();
4291 lengths [i].EmitThis (ec);
4292 ((ArrayAccess) access).EmitGetLength (ec, i);
4293 lengths [i].EmitStore (ig);
4296 for (int i = 0; i < rank; i++) {
4297 counter [i].Initialize (ec);
4299 ig.Emit (OpCodes.Br, test [i]);
4300 ig.MarkLabel (loop [i]);
4303 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4305 statement.Emit (ec);
4307 ig.MarkLabel (ec.LoopBegin);
4309 for (int i = rank - 1; i >= 0; i--){
4310 counter [i].Increment (ec);
4312 ig.MarkLabel (test [i]);
4313 counter [i].Emit (ec);
4314 lengths [i].Emit (ec);
4315 ig.Emit (OpCodes.Blt, loop [i]);
4318 ig.MarkLabel (ec.LoopEnd);
4322 protected class CollectionForeach : ExceptionStatement
4324 Expression variable, expr;
4325 Statement statement;
4327 TemporaryVariable enumerator;
4331 MethodGroupExpr get_enumerator;
4332 PropertyExpr get_current;
4333 MethodInfo move_next;
4334 Type var_type, enumerator_type;
4336 bool enumerator_found;
4338 public CollectionForeach (Type var_type, Expression var,
4339 Expression expr, Statement stmt, Location l)
4341 this.var_type = var_type;
4342 this.variable = var;
4348 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4350 Type return_type = mi.ReturnType;
4352 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4354 // Apply the same optimization as MS: skip the GetEnumerator
4355 // returning an IEnumerator, and use the one returning a
4356 // CharEnumerator instead. This allows us to avoid the
4357 // try-finally block and the boxing.
4362 // Ok, we can access it, now make sure that we can do something
4363 // with this `GetEnumerator'
4366 if (return_type == TypeManager.ienumerator_type ||
4367 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4368 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4370 // If it is not an interface, lets try to find the methods ourselves.
4371 // For example, if we have:
4372 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4373 // We can avoid the iface call. This is a runtime perf boost.
4374 // even bigger if we have a ValueType, because we avoid the cost
4377 // We have to make sure that both methods exist for us to take
4378 // this path. If one of the methods does not exist, we will just
4379 // use the interface. Sadly, this complex if statement is the only
4380 // way I could do this without a goto
4383 if (return_type.IsInterface ||
4384 !FetchMoveNext (return_type) ||
4385 !FetchGetCurrent (ec, return_type)) {
4386 move_next = TypeManager.bool_movenext_void;
4387 get_current = new PropertyExpr (
4388 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4393 // Ok, so they dont return an IEnumerable, we will have to
4394 // find if they support the GetEnumerator pattern.
4397 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
4398 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",
4399 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
4404 enumerator_type = return_type;
4405 is_disposable = !enumerator_type.IsSealed ||
4406 TypeManager.ImplementsInterface (
4407 enumerator_type, TypeManager.idisposable_type);
4413 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4415 bool FetchMoveNext (Type t)
4417 MemberList move_next_list;
4419 move_next_list = TypeContainer.FindMembers (
4420 t, MemberTypes.Method,
4421 BindingFlags.Public | BindingFlags.Instance,
4422 Type.FilterName, "MoveNext");
4423 if (move_next_list.Count == 0)
4426 foreach (MemberInfo m in move_next_list){
4427 MethodInfo mi = (MethodInfo) m;
4429 if ((TypeManager.GetParameterData (mi).Count == 0) &&
4430 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4440 // Retrieves a `public T get_Current ()' method from the Type `t'
4442 bool FetchGetCurrent (EmitContext ec, Type t)
4444 PropertyExpr pe = Expression.MemberLookup (
4445 ec.ContainerType, t, "Current", MemberTypes.Property,
4446 Expression.AllBindingFlags, loc) as PropertyExpr;
4455 // Retrieves a `public void Dispose ()' method from the Type `t'
4457 static MethodInfo FetchMethodDispose (Type t)
4459 MemberList dispose_list;
4461 dispose_list = TypeContainer.FindMembers (
4462 t, MemberTypes.Method,
4463 BindingFlags.Public | BindingFlags.Instance,
4464 Type.FilterName, "Dispose");
4465 if (dispose_list.Count == 0)
4468 foreach (MemberInfo m in dispose_list){
4469 MethodInfo mi = (MethodInfo) m;
4471 if (TypeManager.GetParameterData (mi).Count == 0){
4472 if (mi.ReturnType == TypeManager.void_type)
4479 public void Error_Enumerator ()
4481 if (enumerator_found) {
4485 Report.Error (1579, loc,
4486 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4487 TypeManager.CSharpName (expr.Type));
4490 bool TryType (EmitContext ec, Type t)
4492 MethodGroupExpr mg = Expression.MemberLookup (
4493 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
4494 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4498 foreach (MethodBase mb in mg.Methods) {
4499 if (TypeManager.GetParameterData (mb).Count != 0)
4502 // Check whether GetEnumerator is public
4503 if ((mb.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4506 if (TypeManager.IsOverride (mb))
4509 enumerator_found = true;
4511 if (!GetEnumeratorFilter (ec, (MethodInfo) mb))
4514 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) mb };
4515 get_enumerator = new MethodGroupExpr (mi, loc);
4517 if (t != expr.Type) {
4518 expr = Convert.ExplicitConversion (
4521 throw new InternalErrorException ();
4524 get_enumerator.InstanceExpression = expr;
4525 get_enumerator.IsBase = t != expr.Type;
4533 bool ProbeCollectionType (EmitContext ec, Type t)
4535 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4536 if (TryType (ec, tt))
4542 // Now try to find the method in the interfaces
4545 Type [] ifaces = t.GetInterfaces ();
4547 foreach (Type i in ifaces){
4548 if (TryType (ec, i))
4553 // Since TypeBuilder.GetInterfaces only returns the interface
4554 // types for this type, we have to keep looping, but once
4555 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4556 // done, because it returns all the types
4558 if ((t is TypeBuilder))
4567 public override bool Resolve (EmitContext ec)
4569 enumerator_type = TypeManager.ienumerator_type;
4570 is_disposable = true;
4572 if (!ProbeCollectionType (ec, expr.Type)) {
4573 Error_Enumerator ();
4577 enumerator = new TemporaryVariable (enumerator_type, loc);
4578 enumerator.Resolve (ec);
4580 init = new Invocation (get_enumerator, new ArrayList ());
4581 init = init.Resolve (ec);
4585 Expression move_next_expr;
4587 MemberInfo[] mi = new MemberInfo[] { move_next };
4588 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4589 mg.InstanceExpression = enumerator;
4591 move_next_expr = new Invocation (mg, new ArrayList ());
4594 get_current.InstanceExpression = enumerator;
4596 Statement block = new CollectionForeachStatement (
4597 var_type, variable, get_current, statement, loc);
4599 loop = new While (move_next_expr, block, loc);
4603 FlowBranchingException branching = null;
4605 branching = ec.StartFlowBranching (this);
4607 if (!loop.Resolve (ec))
4610 if (is_disposable) {
4611 ResolveFinally (branching);
4612 ec.EndFlowBranching ();
4614 emit_finally = true;
4619 protected override void DoEmit (EmitContext ec)
4621 ILGenerator ig = ec.ig;
4623 enumerator.Store (ec, init);
4626 // Protect the code in a try/finalize block, so that
4627 // if the beast implement IDisposable, we get rid of it
4629 if (is_disposable && emit_finally)
4630 ig.BeginExceptionBlock ();
4635 // Now the finally block
4637 if (is_disposable) {
4640 ig.EndExceptionBlock ();
4645 public override void EmitFinally (EmitContext ec)
4647 ILGenerator ig = ec.ig;
4649 if (enumerator_type.IsValueType) {
4650 MethodInfo mi = FetchMethodDispose (enumerator_type);
4652 enumerator.EmitLoadAddress (ec);
4653 ig.Emit (OpCodes.Call, mi);
4655 enumerator.Emit (ec);
4656 ig.Emit (OpCodes.Box, enumerator_type);
4657 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4660 Label call_dispose = ig.DefineLabel ();
4662 enumerator.Emit (ec);
4663 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4664 ig.Emit (OpCodes.Dup);
4665 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4666 ig.Emit (OpCodes.Pop);
4668 Label end_finally = ig.DefineLabel ();
4669 ig.Emit (OpCodes.Br, end_finally);
4671 ig.MarkLabel (call_dispose);
4672 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4673 ig.MarkLabel (end_finally);
4678 protected class CollectionForeachStatement : Statement
4681 Expression variable, current, conv;
4682 Statement statement;
4685 public CollectionForeachStatement (Type type, Expression variable,
4686 Expression current, Statement statement,
4690 this.variable = variable;
4691 this.current = current;
4692 this.statement = statement;
4696 public override bool Resolve (EmitContext ec)
4698 current = current.Resolve (ec);
4699 if (current == null)
4702 conv = Convert.ExplicitConversion (ec, current, type, loc);
4706 assign = new Assign (variable, conv, loc);
4707 if (assign.Resolve (ec) == null)
4710 if (!statement.Resolve (ec))
4716 protected override void DoEmit (EmitContext ec)
4718 assign.EmitStatement (ec);
4719 statement.Emit (ec);