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 Expression.Error_VoidInvalidInTheContext (Location);
1073 if (VariableType.IsAbstract && VariableType.IsSealed) {
1074 Report.Error (723, Location, "Cannot declare variable of static type `{0}'", TypeManager.CSharpName (VariableType));
1078 if (VariableType.IsPointer && !ec.InUnsafe)
1079 Expression.UnsafeError (Location);
1084 public bool IsCaptured {
1086 return (flags & Flags.Captured) != 0;
1090 flags |= Flags.Captured;
1094 public bool IsConstant {
1096 return (flags & Flags.IsConstant) != 0;
1099 flags |= Flags.IsConstant;
1103 public bool AddressTaken {
1105 return (flags & Flags.AddressTaken) != 0;
1109 flags |= Flags.AddressTaken;
1113 public bool CompilerGenerated {
1115 return (flags & Flags.CompilerGenerated) != 0;
1119 flags |= Flags.CompilerGenerated;
1123 public override string ToString ()
1125 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1126 Name, Type, VariableInfo, Location);
1131 return (flags & Flags.Used) != 0;
1134 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1138 public bool ReadOnly {
1140 return (flags & Flags.ReadOnly) != 0;
1144 public void SetReadOnlyContext (ReadOnlyContext context)
1146 flags |= Flags.ReadOnly;
1147 ro_context = context;
1150 public string GetReadOnlyContext ()
1153 throw new InternalErrorException ("Variable is not readonly");
1155 switch (ro_context) {
1156 case ReadOnlyContext.Fixed:
1157 return "fixed variable";
1158 case ReadOnlyContext.Foreach:
1159 return "foreach iteration variable";
1160 case ReadOnlyContext.Using:
1161 return "using variable";
1163 throw new NotImplementedException ();
1167 // Whether the variable is pinned, if Pinned the variable has been
1168 // allocated in a pinned slot with DeclareLocal.
1170 public bool Pinned {
1172 return (flags & Flags.Pinned) != 0;
1175 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1179 public bool IsThis {
1181 return (flags & Flags.IsThis) != 0;
1184 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1190 /// Block represents a C# block.
1194 /// This class is used in a number of places: either to represent
1195 /// explicit blocks that the programmer places or implicit blocks.
1197 /// Implicit blocks are used as labels or to introduce variable
1200 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1201 /// they contain extra information that is not necessary on normal blocks.
1203 public class Block : Statement {
1204 public Block Parent;
1205 public readonly Location StartLocation;
1206 public Location EndLocation = Location.Null;
1208 public readonly ToplevelBlock Toplevel;
1211 public enum Flags : ushort {
1215 VariablesInitialized = 8,
1220 HasVarargs = 256 // Used in ToplevelBlock
1222 protected Flags flags;
1224 public bool Implicit {
1225 get { return (flags & Flags.Implicit) != 0; }
1228 public bool Unchecked {
1229 get { return (flags & Flags.Unchecked) != 0; }
1230 set { flags |= Flags.Unchecked; }
1233 public bool Unsafe {
1234 get { return (flags & Flags.Unsafe) != 0; }
1235 set { flags |= Flags.Unsafe; }
1239 // The statements in this block
1241 ArrayList statements;
1245 // An array of Blocks. We keep track of children just
1246 // to generate the local variable declarations.
1248 // Statements and child statements are handled through the
1254 // Labels. (label, block) pairs.
1259 // Keeps track of (name, type) pairs
1261 IDictionary variables;
1264 // Keeps track of constants
1265 Hashtable constants;
1268 // Temporary variables.
1270 ArrayList temporary_variables;
1273 // If this is a switch section, the enclosing switch block.
1277 protected static int id;
1281 public Block (Block parent)
1282 : this (parent, (Flags) 0, Location.Null, Location.Null)
1285 public Block (Block parent, Flags flags)
1286 : this (parent, flags, Location.Null, Location.Null)
1289 public Block (Block parent, Location start, Location end)
1290 : this (parent, (Flags) 0, start, end)
1293 public Block (Block parent, Flags flags, Location start, Location end)
1296 parent.AddChild (this);
1298 this.Parent = parent;
1300 this.StartLocation = start;
1301 this.EndLocation = end;
1304 statements = new ArrayList ();
1306 if ((flags & Flags.IsToplevel) != 0)
1307 Toplevel = (ToplevelBlock) this;
1309 Toplevel = parent.Toplevel;
1311 if (parent != null && Implicit) {
1312 if (parent.known_variables == null)
1313 parent.known_variables = new Hashtable ();
1314 // share with parent
1315 known_variables = parent.known_variables;
1319 public Block CreateSwitchBlock (Location start)
1321 Block new_block = new Block (this, start, start);
1322 new_block.switch_block = this;
1327 get { return this_id; }
1330 protected IDictionary Variables {
1332 if (variables == null)
1333 variables = new ListDictionary ();
1338 void AddChild (Block b)
1340 if (children == null)
1341 children = new ArrayList ();
1346 public void SetEndLocation (Location loc)
1352 /// Adds a label to the current block.
1356 /// false if the name already exists in this block. true
1360 public bool AddLabel (LabeledStatement target)
1362 if (switch_block != null)
1363 return switch_block.AddLabel (target);
1365 string name = target.Name;
1368 while (cur != null) {
1369 if (cur.DoLookupLabel (name) != null) {
1370 Report.Error (140, target.loc, "The label `{0}' is a duplicate", name);
1380 while (cur != null) {
1381 if (cur.DoLookupLabel (name) != null) {
1384 "The label `{0}' shadows another label by the same name in a contained scope.",
1389 if (children != null) {
1390 foreach (Block b in children) {
1391 LabeledStatement s = b.DoLookupLabel (name);
1397 "The label `{0}' shadows another label by the same name in a contained scope.",
1408 labels = new Hashtable ();
1410 labels.Add (name, target);
1414 public LabeledStatement LookupLabel (string name)
1416 LabeledStatement s = DoLookupLabel (name);
1420 if (children == null)
1423 foreach (Block child in children) {
1424 if (!child.Implicit)
1427 s = child.LookupLabel (name);
1435 LabeledStatement DoLookupLabel (string name)
1437 if (switch_block != null)
1438 return switch_block.LookupLabel (name);
1441 if (labels.Contains (name))
1442 return ((LabeledStatement) labels [name]);
1447 Hashtable known_variables;
1450 // Marks a variable with name @name as being used in this or a child block.
1451 // If a variable name has been used in a child block, it's illegal to
1452 // declare a variable with the same name in the current block.
1454 void AddKnownVariable (string name, LocalInfo info)
1456 if (known_variables == null)
1457 known_variables = new Hashtable ();
1459 known_variables [name] = info;
1462 LocalInfo GetKnownVariableInfo (string name)
1464 if (known_variables == null)
1466 return (LocalInfo) known_variables [name];
1469 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1472 LocalInfo kvi = b.GetKnownVariableInfo (name);
1473 while (kvi == null) {
1479 kvi = b.GetKnownVariableInfo (name);
1485 // Is kvi.Block nested inside 'b'
1486 if (b.known_variables != kvi.Block.known_variables) {
1488 // If a variable by the same name it defined in a nested block of this
1489 // block, we violate the invariant meaning in a block.
1492 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1493 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1498 // It's ok if the definition is in a nested subblock of b, but not
1499 // nested inside this block -- a definition in a sibling block
1500 // should not affect us.
1506 // Block 'b' and kvi.Block are the same textual block.
1507 // However, different variables are extant.
1509 // Check if the variable is in scope in both blocks. We use
1510 // an indirect check that depends on AddVariable doing its
1511 // part in maintaining the invariant-meaning-in-block property.
1513 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1517 // Even though we detected the error when the name is used, we
1518 // treat it as if the variable declaration was in error.
1520 Report.SymbolRelatedToPreviousError (loc, name);
1521 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1525 public LocalInfo AddVariable (Expression type, string name, Location l)
1527 LocalInfo vi = GetLocalInfo (name);
1529 Report.SymbolRelatedToPreviousError (vi.Location, name);
1530 if (known_variables == vi.Block.known_variables)
1531 Report.Error (128, l,
1532 "A local variable named `{0}' is already defined in this scope", name);
1534 Error_AlreadyDeclared (l, name, "parent");
1538 vi = GetKnownVariableInfo (name);
1540 Report.SymbolRelatedToPreviousError (vi.Location, name);
1541 Error_AlreadyDeclared (l, name, "child");
1546 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1548 Report.SymbolRelatedToPreviousError (p.Location, name);
1549 Error_AlreadyDeclared (l, name, "method argument");
1553 vi = new LocalInfo (type, name, this, l);
1555 Variables.Add (name, vi);
1557 for (Block b = this; b != null; b = b.Parent)
1558 b.AddKnownVariable (name, vi);
1560 if ((flags & Flags.VariablesInitialized) != 0)
1561 throw new Exception ();
1566 void Error_AlreadyDeclared (Location loc, string var, string reason)
1568 Report.Error (136, loc, "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning to `{0}', " +
1569 "which is already used in a `{1}' scope", var, reason);
1572 public bool AddConstant (Expression type, string name, Expression value, Location l)
1574 if (AddVariable (type, name, l) == null)
1577 if (constants == null)
1578 constants = new Hashtable ();
1580 constants.Add (name, value);
1582 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1587 static int next_temp_id = 0;
1589 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1591 if (temporary_variables == null)
1592 temporary_variables = new ArrayList ();
1594 int id = ++next_temp_id;
1595 string name = "$s_" + id.ToString ();
1597 LocalInfo li = new LocalInfo (te, name, this, loc);
1598 li.CompilerGenerated = true;
1599 temporary_variables.Add (li);
1603 public LocalInfo GetLocalInfo (string name)
1605 for (Block b = this; b != null; b = b.Parent) {
1606 if (b.variables != null) {
1607 LocalInfo ret = b.variables [name] as LocalInfo;
1615 public Expression GetVariableType (string name)
1617 LocalInfo vi = GetLocalInfo (name);
1618 return vi == null ? null : vi.Type;
1621 public Expression GetConstantExpression (string name)
1623 for (Block b = this; b != null; b = b.Parent) {
1624 if (b.constants != null) {
1625 Expression ret = b.constants [name] as Expression;
1633 public void AddStatement (Statement s)
1636 flags |= Flags.BlockUsed;
1640 get { return (flags & Flags.BlockUsed) != 0; }
1645 flags |= Flags.BlockUsed;
1648 public bool HasRet {
1649 get { return (flags & Flags.HasRet) != 0; }
1652 public bool IsDestructor {
1653 get { return (flags & Flags.IsDestructor) != 0; }
1656 public void SetDestructor ()
1658 flags |= Flags.IsDestructor;
1661 VariableMap param_map, local_map;
1663 public VariableMap ParameterMap {
1665 if ((flags & Flags.VariablesInitialized) == 0)
1666 throw new Exception ("Variables have not been initialized yet");
1672 public VariableMap LocalMap {
1674 if ((flags & Flags.VariablesInitialized) == 0)
1675 throw new Exception ("Variables have not been initialized yet");
1682 /// Emits the variable declarations and labels.
1685 /// tc: is our typecontainer (to resolve type references)
1686 /// ig: is the code generator:
1688 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
1690 // If some parent block was unsafe, we remain unsafe even if this block
1691 // isn't explicitly marked as such.
1692 using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
1694 // Compute the VariableMap's.
1696 // Unfortunately, we don't know the type when adding variables with
1697 // AddVariable(), so we need to compute this info here.
1701 if (variables != null) {
1702 foreach (LocalInfo li in variables.Values)
1705 locals = new LocalInfo [variables.Count];
1706 variables.Values.CopyTo (locals, 0);
1708 locals = new LocalInfo [0];
1711 local_map = new VariableMap (Parent.LocalMap, locals);
1713 local_map = new VariableMap (locals);
1715 param_map = new VariableMap (ip);
1716 flags |= Flags.VariablesInitialized;
1719 // Process this block variables
1721 if (variables != null) {
1722 foreach (DictionaryEntry de in variables) {
1723 string name = (string) de.Key;
1724 LocalInfo vi = (LocalInfo) de.Value;
1725 Type variable_type = vi.VariableType;
1727 if (variable_type == null)
1730 if (variable_type.IsPointer) {
1732 // Am not really convinced that this test is required (Microsoft does it)
1733 // but the fact is that you would not be able to use the pointer variable
1736 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1741 if (constants == null)
1744 Expression cv = (Expression) constants [name];
1748 // Don't let 'const int Foo = Foo;' succeed.
1749 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
1750 // which in turn causes the 'must be constant' error to be triggered.
1751 constants.Remove (name);
1753 using (ec.With (EmitContext.Flags.ConstantCheckState, (flags & Flags.Unchecked) == 0)) {
1754 ec.CurrentBlock = this;
1755 Expression e = cv.Resolve (ec);
1759 Constant ce = e as Constant;
1761 Const.Error_ExpressionMustBeConstant (variable_type, vi.Location, name);
1765 e = ce.ToType (variable_type, vi.Location);
1769 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue) {
1770 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
1774 constants.Add (name, e);
1775 vi.IsConstant = true;
1781 // Now, handle the children
1783 if (children != null) {
1784 foreach (Block b in children)
1785 b.ResolveMeta (toplevel, ec, ip);
1791 // Emits the local variable declarations for a block
1793 public void EmitMeta (EmitContext ec)
1795 ILGenerator ig = ec.ig;
1797 if (variables != null){
1798 bool have_captured_vars = ec.HaveCapturedVariables ();
1800 foreach (DictionaryEntry de in variables){
1801 LocalInfo vi = (LocalInfo) de.Value;
1803 if (have_captured_vars && ec.IsCaptured (vi))
1806 vi.DeclareLocal (ig);
1810 if (temporary_variables != null) {
1811 AnonymousContainer am = ec.CurrentAnonymousMethod;
1812 TypeBuilder scope = null;
1813 if ((am != null) && am.IsIterator) {
1814 scope = am.Scope.ScopeTypeBuilder;
1816 throw new InternalErrorException ();
1818 foreach (LocalInfo vi in temporary_variables) {
1819 if (scope != null) {
1820 if (vi.FieldBuilder == null)
1821 vi.FieldBuilder = scope.DefineField (
1822 vi.Name, vi.VariableType, FieldAttributes.Assembly);
1824 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1828 if (children != null){
1829 foreach (Block b in children)
1834 void UsageWarning (FlowBranching.UsageVector vector)
1838 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1839 foreach (DictionaryEntry de in variables){
1840 LocalInfo vi = (LocalInfo) de.Value;
1845 name = (string) de.Key;
1847 // vi.VariableInfo can be null for 'catch' variables
1848 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
1849 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
1851 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
1857 bool unreachable_shown;
1860 private void CheckPossibleMistakenEmptyStatement (Statement s)
1864 // Some statements are wrapped by a Block. Since
1865 // others' internal could be changed, here I treat
1866 // them as possibly wrapped by Block equally.
1867 Block b = s as Block;
1868 if (b != null && b.statements.Count == 1)
1869 s = (Statement) b.statements [0];
1872 body = ((Lock) s).Statement;
1874 body = ((For) s).Statement;
1875 else if (s is Foreach)
1876 body = ((Foreach) s).Statement;
1877 else if (s is While)
1878 body = ((While) s).Statement;
1879 else if (s is Using)
1880 body = ((Using) s).Statement;
1881 else if (s is Fixed)
1882 body = ((Fixed) s).Statement;
1886 if (body == null || body is EmptyStatement)
1887 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
1890 public override bool Resolve (EmitContext ec)
1892 Block prev_block = ec.CurrentBlock;
1895 int errors = Report.Errors;
1897 ec.CurrentBlock = this;
1898 ec.StartFlowBranching (this);
1900 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1902 int statement_count = statements.Count;
1903 for (int ix = 0; ix < statement_count; ix++){
1904 Statement s = (Statement) statements [ix];
1905 // Check possible empty statement (CS0642)
1906 if (RootContext.WarningLevel >= 3 &&
1907 ix + 1 < statement_count &&
1908 statements [ix + 1] is Block)
1909 CheckPossibleMistakenEmptyStatement (s);
1912 // Warn if we detect unreachable code.
1915 if (s is EmptyStatement)
1919 ((Block) s).unreachable = true;
1921 if (!unreachable_shown && !(s is LabeledStatement)) {
1922 Report.Warning (162, 2, s.loc, "Unreachable code detected");
1923 unreachable_shown = true;
1928 // Note that we're not using ResolveUnreachable() for unreachable
1929 // statements here. ResolveUnreachable() creates a temporary
1930 // flow branching and kills it afterwards. This leads to problems
1931 // if you have two unreachable statements where the first one
1932 // assigns a variable and the second one tries to access it.
1935 if (!s.Resolve (ec)) {
1937 statements [ix] = EmptyStatement.Value;
1941 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1942 statements [ix] = EmptyStatement.Value;
1944 num_statements = ix + 1;
1946 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1947 if (unreachable && s is LabeledStatement)
1948 throw new InternalErrorException ("should not happen");
1951 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1952 ec.CurrentBranching, statement_count, num_statements);
1954 while (ec.CurrentBranching is FlowBranchingLabeled)
1955 ec.EndFlowBranching ();
1957 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1959 ec.CurrentBlock = prev_block;
1961 // If we're a non-static `struct' constructor which doesn't have an
1962 // initializer, then we must initialize all of the struct's fields.
1963 if ((flags & Flags.IsToplevel) != 0 &&
1964 !Toplevel.IsThisAssigned (ec) &&
1965 !vector.Reachability.AlwaysThrows)
1968 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1969 foreach (LabeledStatement label in labels.Values)
1970 if (!label.HasBeenReferenced)
1971 Report.Warning (164, 2, label.loc,
1972 "This label has not been referenced");
1975 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1977 if (vector.Reachability.IsUnreachable)
1978 flags |= Flags.HasRet;
1980 if (ok && (errors == Report.Errors)) {
1981 if (RootContext.WarningLevel >= 3)
1982 UsageWarning (vector);
1988 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1990 unreachable_shown = true;
1994 Report.Warning (162, 2, loc, "Unreachable code detected");
1996 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1997 bool ok = Resolve (ec);
1998 ec.KillFlowBranching ();
2003 protected override void DoEmit (EmitContext ec)
2005 for (int ix = 0; ix < num_statements; ix++){
2006 Statement s = (Statement) statements [ix];
2008 // Check whether we are the last statement in a
2011 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2012 ec.IsLastStatement = true;
2014 ec.IsLastStatement = false;
2020 public override void Emit (EmitContext ec)
2022 Block prev_block = ec.CurrentBlock;
2024 ec.CurrentBlock = this;
2026 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2027 bool is_lexical_block = !Implicit && (Parent != null);
2029 if (emit_debug_info) {
2030 if (is_lexical_block)
2033 if (variables != null) {
2034 foreach (DictionaryEntry de in variables) {
2035 string name = (string) de.Key;
2036 LocalInfo vi = (LocalInfo) de.Value;
2038 if (vi.LocalBuilder == null)
2041 ec.DefineLocalVariable (name, vi.LocalBuilder);
2045 ec.Mark (StartLocation, true);
2046 ec.EmitScopeInitFromBlock (this);
2048 ec.Mark (EndLocation, true);
2050 if (emit_debug_info && is_lexical_block)
2053 ec.CurrentBlock = prev_block;
2057 // Returns true if we ar ea child of `b'.
2059 public bool IsChildOf (Block b)
2061 Block current = this;
2064 if (current.Parent == b)
2066 current = current.Parent;
2067 } while (current != null);
2071 public override string ToString ()
2073 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2078 // A toplevel block contains extra information, the split is done
2079 // only to separate information that would otherwise bloat the more
2080 // lightweight Block.
2082 // In particular, this was introduced when the support for Anonymous
2083 // Methods was implemented.
2085 public class ToplevelBlock : Block {
2087 // Pointer to the host of this anonymous method, or null
2088 // if we are the topmost block
2090 ToplevelBlock container;
2091 CaptureContext capture_context;
2092 FlowBranchingToplevel top_level_branching;
2094 Hashtable capture_contexts;
2097 public bool HasVarargs {
2098 get { return (flags & Flags.HasVarargs) != 0; }
2099 set { flags |= Flags.HasVarargs; }
2103 // The parameters for the block.
2105 public readonly Parameters Parameters;
2107 public void RegisterCaptureContext (CaptureContext cc)
2109 if (capture_contexts == null)
2110 capture_contexts = new Hashtable ();
2111 capture_contexts [cc] = cc;
2114 public void CompleteContexts ()
2116 if (capture_contexts == null)
2119 foreach (CaptureContext cc in capture_contexts.Keys){
2124 public CaptureContext ToplevelBlockCaptureContext {
2125 get { return capture_context; }
2128 public ToplevelBlock Container {
2129 get { return container; }
2132 protected void AddChild (ToplevelBlock block)
2134 if (children == null)
2135 children = new ArrayList ();
2137 children.Add (block);
2141 // Parent is only used by anonymous blocks to link back to their
2144 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2145 this (container, (Flags) 0, parameters, start)
2149 public ToplevelBlock (Parameters parameters, Location start) :
2150 this (null, (Flags) 0, parameters, start)
2154 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2155 this (null, flags, parameters, start)
2159 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2160 base (null, flags | Flags.IsToplevel, start, Location.Null)
2162 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2163 this.container = container;
2165 if (container != null)
2166 container.AddChild (this);
2169 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2173 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2175 if (capture_context == null)
2176 capture_context = new CaptureContext (this, loc, host);
2179 public CaptureContext CaptureContext {
2180 get { return capture_context; }
2183 public FlowBranchingToplevel TopLevelBranching {
2184 get { return top_level_branching; }
2188 // This is used if anonymous methods are used inside an iterator
2189 // (see 2test-22.cs for an example).
2191 // The AnonymousMethod is created while parsing - at a time when we don't
2192 // know yet that we're inside an iterator, so it's `Container' is initially
2193 // null. Later on, when resolving the iterator, we need to move the
2194 // anonymous method into that iterator.
2196 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2198 foreach (ToplevelBlock block in children) {
2199 if (block.CaptureContext == null)
2202 block.container = new_parent;
2203 block.CaptureContext.ReParent (new_parent, new_host);
2208 // Returns a `ParameterReference' for the given name, or null if there
2209 // is no such parameter
2211 public ParameterReference GetParameterReference (string name, Location loc)
2216 for (ToplevelBlock t = this; t != null; t = t.Container) {
2217 Parameters pars = t.Parameters;
2218 par = pars.GetParameterByName (name, out idx);
2220 return new ParameterReference (par, this, idx, loc);
2226 // Whether the parameter named `name' is local to this block,
2227 // or false, if the parameter belongs to an encompassing block.
2229 public bool IsLocalParameter (string name)
2231 return Parameters.GetParameterByName (name) != null;
2235 // Whether the `name' is a parameter reference
2237 public bool IsParameterReference (string name)
2239 for (ToplevelBlock t = this; t != null; t = t.Container) {
2240 if (t.IsLocalParameter (name))
2246 LocalInfo this_variable = null;
2249 // Returns the "this" instance variable of this block.
2250 // See AddThisVariable() for more information.
2252 public LocalInfo ThisVariable {
2253 get { return this_variable; }
2258 // This is used by non-static `struct' constructors which do not have an
2259 // initializer - in this case, the constructor must initialize all of the
2260 // struct's fields. To do this, we add a "this" variable and use the flow
2261 // analysis code to ensure that it's been fully initialized before control
2262 // leaves the constructor.
2264 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2266 if (this_variable == null) {
2267 this_variable = new LocalInfo (ds, this, l);
2268 this_variable.Used = true;
2269 this_variable.IsThis = true;
2271 Variables.Add ("this", this_variable);
2274 return this_variable;
2277 public bool IsThisAssigned (EmitContext ec)
2279 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2282 public bool ResolveMeta (EmitContext ec, Parameters ip)
2284 int errors = Report.Errors;
2286 if (top_level_branching != null)
2289 ResolveMeta (this, ec, ip);
2291 top_level_branching = ec.StartFlowBranching (this);
2293 return Report.Errors == errors;
2297 public class SwitchLabel {
2304 Label il_label_code;
2305 bool il_label_code_set;
2307 public static readonly object NullStringCase = new object ();
2310 // if expr == null, then it is the default case.
2312 public SwitchLabel (Expression expr, Location l)
2318 public Expression Label {
2324 public object Converted {
2330 public Label GetILLabel (EmitContext ec)
2333 il_label = ec.ig.DefineLabel ();
2334 il_label_set = true;
2339 public Label GetILLabelCode (EmitContext ec)
2341 if (!il_label_code_set){
2342 il_label_code = ec.ig.DefineLabel ();
2343 il_label_code_set = true;
2345 return il_label_code;
2349 // Resolves the expression, reduces it to a literal if possible
2350 // and then converts it to the requested type.
2352 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2354 Expression e = label.Resolve (ec);
2359 Constant c = e as Constant;
2361 Report.Error (150, loc, "A constant value is expected");
2365 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2366 converted = NullStringCase;
2370 c = c.ToType (required_type, loc);
2374 converted = c.GetValue ();
2378 public void Erorr_AlreadyOccurs ()
2381 if (converted == null)
2383 else if (converted == NullStringCase)
2386 label = converted.ToString ();
2388 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2392 public class SwitchSection {
2393 // An array of SwitchLabels.
2394 public readonly ArrayList Labels;
2395 public readonly Block Block;
2397 public SwitchSection (ArrayList labels, Block block)
2404 public class Switch : Statement {
2405 public readonly ArrayList Sections;
2406 public Expression Expr;
2409 /// Maps constants whose type type SwitchType to their SwitchLabels.
2411 public IDictionary Elements;
2414 /// The governing switch type
2416 public Type SwitchType;
2421 Label default_target;
2422 Expression new_expr;
2424 SwitchSection constant_section;
2425 SwitchSection default_section;
2428 // The types allowed to be implicitly cast from
2429 // on the governing type
2431 static Type [] allowed_types;
2433 public Switch (Expression e, ArrayList sects, Location l)
2440 public bool GotDefault {
2442 return default_section != null;
2446 public Label DefaultTarget {
2448 return default_target;
2453 // Determines the governing type for a switch. The returned
2454 // expression might be the expression from the switch, or an
2455 // expression that includes any potential conversions to the
2456 // integral types or to string.
2458 Expression SwitchGoverningType (EmitContext ec, Type t)
2460 if (t == TypeManager.byte_type ||
2461 t == TypeManager.sbyte_type ||
2462 t == TypeManager.ushort_type ||
2463 t == TypeManager.short_type ||
2464 t == TypeManager.uint32_type ||
2465 t == TypeManager.int32_type ||
2466 t == TypeManager.uint64_type ||
2467 t == TypeManager.int64_type ||
2468 t == TypeManager.char_type ||
2469 t == TypeManager.string_type ||
2470 t == TypeManager.bool_type ||
2471 t.IsSubclassOf (TypeManager.enum_type))
2474 if (allowed_types == null){
2475 allowed_types = new Type [] {
2476 TypeManager.sbyte_type,
2477 TypeManager.byte_type,
2478 TypeManager.short_type,
2479 TypeManager.ushort_type,
2480 TypeManager.int32_type,
2481 TypeManager.uint32_type,
2482 TypeManager.int64_type,
2483 TypeManager.uint64_type,
2484 TypeManager.char_type,
2485 TypeManager.string_type,
2486 TypeManager.bool_type
2491 // Try to find a *user* defined implicit conversion.
2493 // If there is no implicit conversion, or if there are multiple
2494 // conversions, we have to report an error
2496 Expression converted = null;
2497 foreach (Type tt in allowed_types){
2500 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2505 // Ignore over-worked ImplicitUserConversions that do
2506 // an implicit conversion in addition to the user conversion.
2508 if (!(e is UserCast))
2511 if (converted != null){
2512 Report.ExtraInformation (
2514 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2515 TypeManager.CSharpName (Expr.Type)));
2525 // Performs the basic sanity checks on the switch statement
2526 // (looks for duplicate keys and non-constant expressions).
2528 // It also returns a hashtable with the keys that we will later
2529 // use to compute the switch tables
2531 bool CheckSwitch (EmitContext ec)
2534 Elements = Sections.Count > 10 ?
2535 (IDictionary)new Hashtable () :
2536 (IDictionary)new ListDictionary ();
2538 foreach (SwitchSection ss in Sections){
2539 foreach (SwitchLabel sl in ss.Labels){
2540 if (sl.Label == null){
2541 if (default_section != null){
2542 sl.Erorr_AlreadyOccurs ();
2545 default_section = ss;
2549 if (!sl.ResolveAndReduce (ec, SwitchType)){
2554 object key = sl.Converted;
2556 Elements.Add (key, sl);
2558 catch (ArgumentException) {
2559 sl.Erorr_AlreadyOccurs ();
2567 void EmitObjectInteger (ILGenerator ig, object k)
2570 IntConstant.EmitInt (ig, (int) k);
2571 else if (k is Constant) {
2572 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2575 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2578 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2580 IntConstant.EmitInt (ig, (int) (long) k);
2581 ig.Emit (OpCodes.Conv_I8);
2584 LongConstant.EmitLong (ig, (long) k);
2586 else if (k is ulong)
2588 ulong ul = (ulong) k;
2591 IntConstant.EmitInt (ig, unchecked ((int) ul));
2592 ig.Emit (OpCodes.Conv_U8);
2596 LongConstant.EmitLong (ig, unchecked ((long) ul));
2600 IntConstant.EmitInt (ig, (int) ((char) k));
2601 else if (k is sbyte)
2602 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2604 IntConstant.EmitInt (ig, (int) ((byte) k));
2605 else if (k is short)
2606 IntConstant.EmitInt (ig, (int) ((short) k));
2607 else if (k is ushort)
2608 IntConstant.EmitInt (ig, (int) ((ushort) k));
2610 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2612 throw new Exception ("Unhandled case");
2615 // structure used to hold blocks of keys while calculating table switch
2616 class KeyBlock : IComparable
2618 public KeyBlock (long _nFirst)
2620 nFirst = nLast = _nFirst;
2624 public ArrayList rgKeys = null;
2625 // how many items are in the bucket
2626 public int Size = 1;
2629 get { return (int) (nLast - nFirst + 1); }
2631 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2633 return kbLast.nLast - kbFirst.nFirst + 1;
2635 public int CompareTo (object obj)
2637 KeyBlock kb = (KeyBlock) obj;
2638 int nLength = Length;
2639 int nLengthOther = kb.Length;
2640 if (nLengthOther == nLength)
2641 return (int) (kb.nFirst - nFirst);
2642 return nLength - nLengthOther;
2647 /// This method emits code for a lookup-based switch statement (non-string)
2648 /// Basically it groups the cases into blocks that are at least half full,
2649 /// and then spits out individual lookup opcodes for each block.
2650 /// It emits the longest blocks first, and short blocks are just
2651 /// handled with direct compares.
2653 /// <param name="ec"></param>
2654 /// <param name="val"></param>
2655 /// <returns></returns>
2656 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2658 int cElements = Elements.Count;
2659 object [] rgKeys = new object [cElements];
2660 Elements.Keys.CopyTo (rgKeys, 0);
2661 Array.Sort (rgKeys);
2663 // initialize the block list with one element per key
2664 ArrayList rgKeyBlocks = new ArrayList ();
2665 foreach (object key in rgKeys)
2666 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2669 // iteratively merge the blocks while they are at least half full
2670 // there's probably a really cool way to do this with a tree...
2671 while (rgKeyBlocks.Count > 1)
2673 ArrayList rgKeyBlocksNew = new ArrayList ();
2674 kbCurr = (KeyBlock) rgKeyBlocks [0];
2675 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2677 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2678 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2681 kbCurr.nLast = kb.nLast;
2682 kbCurr.Size += kb.Size;
2686 // start a new block
2687 rgKeyBlocksNew.Add (kbCurr);
2691 rgKeyBlocksNew.Add (kbCurr);
2692 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2694 rgKeyBlocks = rgKeyBlocksNew;
2697 // initialize the key lists
2698 foreach (KeyBlock kb in rgKeyBlocks)
2699 kb.rgKeys = new ArrayList ();
2701 // fill the key lists
2703 if (rgKeyBlocks.Count > 0) {
2704 kbCurr = (KeyBlock) rgKeyBlocks [0];
2705 foreach (object key in rgKeys)
2707 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2708 System.Convert.ToInt64 (key) > kbCurr.nLast;
2710 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2711 kbCurr.rgKeys.Add (key);
2715 // sort the blocks so we can tackle the largest ones first
2716 rgKeyBlocks.Sort ();
2718 // okay now we can start...
2719 ILGenerator ig = ec.ig;
2720 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2721 Label lblDefault = ig.DefineLabel ();
2723 Type typeKeys = null;
2724 if (rgKeys.Length > 0)
2725 typeKeys = rgKeys [0].GetType (); // used for conversions
2729 if (TypeManager.IsEnumType (SwitchType))
2730 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2732 compare_type = SwitchType;
2734 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2736 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2737 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2740 foreach (object key in kb.rgKeys)
2742 ig.Emit (OpCodes.Ldloc, val);
2743 EmitObjectInteger (ig, key);
2744 SwitchLabel sl = (SwitchLabel) Elements [key];
2745 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2750 // TODO: if all the keys in the block are the same and there are
2751 // no gaps/defaults then just use a range-check.
2752 if (compare_type == TypeManager.int64_type ||
2753 compare_type == TypeManager.uint64_type)
2755 // TODO: optimize constant/I4 cases
2757 // check block range (could be > 2^31)
2758 ig.Emit (OpCodes.Ldloc, val);
2759 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2760 ig.Emit (OpCodes.Blt, lblDefault);
2761 ig.Emit (OpCodes.Ldloc, val);
2762 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2763 ig.Emit (OpCodes.Bgt, lblDefault);
2766 ig.Emit (OpCodes.Ldloc, val);
2769 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2770 ig.Emit (OpCodes.Sub);
2772 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2777 ig.Emit (OpCodes.Ldloc, val);
2778 int nFirst = (int) kb.nFirst;
2781 IntConstant.EmitInt (ig, nFirst);
2782 ig.Emit (OpCodes.Sub);
2784 else if (nFirst < 0)
2786 IntConstant.EmitInt (ig, -nFirst);
2787 ig.Emit (OpCodes.Add);
2791 // first, build the list of labels for the switch
2793 int cJumps = kb.Length;
2794 Label [] rgLabels = new Label [cJumps];
2795 for (int iJump = 0; iJump < cJumps; iJump++)
2797 object key = kb.rgKeys [iKey];
2798 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2800 SwitchLabel sl = (SwitchLabel) Elements [key];
2801 rgLabels [iJump] = sl.GetILLabel (ec);
2805 rgLabels [iJump] = lblDefault;
2807 // emit the switch opcode
2808 ig.Emit (OpCodes.Switch, rgLabels);
2811 // mark the default for this block
2813 ig.MarkLabel (lblDefault);
2816 // TODO: find the default case and emit it here,
2817 // to prevent having to do the following jump.
2818 // make sure to mark other labels in the default section
2820 // the last default just goes to the end
2821 ig.Emit (OpCodes.Br, lblDefault);
2823 // now emit the code for the sections
2824 bool fFoundDefault = false;
2825 foreach (SwitchSection ss in Sections)
2827 foreach (SwitchLabel sl in ss.Labels)
2829 ig.MarkLabel (sl.GetILLabel (ec));
2830 ig.MarkLabel (sl.GetILLabelCode (ec));
2831 if (sl.Label == null)
2833 ig.MarkLabel (lblDefault);
2834 fFoundDefault = true;
2838 //ig.Emit (OpCodes.Br, lblEnd);
2841 if (!fFoundDefault) {
2842 ig.MarkLabel (lblDefault);
2844 ig.MarkLabel (lblEnd);
2847 // This simple emit switch works, but does not take advantage of the
2849 // TODO: remove non-string logic from here
2850 // TODO: binary search strings?
2852 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2854 ILGenerator ig = ec.ig;
2855 Label end_of_switch = ig.DefineLabel ();
2856 Label next_test = ig.DefineLabel ();
2857 Label null_target = ig.DefineLabel ();
2858 bool first_test = true;
2859 bool pending_goto_end = false;
2860 bool null_marked = false;
2863 ig.Emit (OpCodes.Ldloc, val);
2865 if (Elements.Contains (SwitchLabel.NullStringCase)){
2866 ig.Emit (OpCodes.Brfalse, null_target);
2868 ig.Emit (OpCodes.Brfalse, default_target);
2870 ig.Emit (OpCodes.Ldloc, val);
2871 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2872 ig.Emit (OpCodes.Stloc, val);
2874 int section_count = Sections.Count;
2875 for (int section = 0; section < section_count; section++){
2876 SwitchSection ss = (SwitchSection) Sections [section];
2878 if (ss == default_section)
2881 Label sec_begin = ig.DefineLabel ();
2883 ig.Emit (OpCodes.Nop);
2885 if (pending_goto_end)
2886 ig.Emit (OpCodes.Br, end_of_switch);
2888 int label_count = ss.Labels.Count;
2890 for (int label = 0; label < label_count; label++){
2891 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2892 ig.MarkLabel (sl.GetILLabel (ec));
2895 ig.MarkLabel (next_test);
2896 next_test = ig.DefineLabel ();
2899 // If we are the default target
2901 if (sl.Label != null){
2902 object lit = sl.Converted;
2904 if (lit == SwitchLabel.NullStringCase){
2906 if (label + 1 == label_count)
2907 ig.Emit (OpCodes.Br, next_test);
2911 ig.Emit (OpCodes.Ldloc, val);
2912 ig.Emit (OpCodes.Ldstr, (string)lit);
2913 if (label_count == 1)
2914 ig.Emit (OpCodes.Bne_Un, next_test);
2916 if (label+1 == label_count)
2917 ig.Emit (OpCodes.Bne_Un, next_test);
2919 ig.Emit (OpCodes.Beq, sec_begin);
2924 ig.MarkLabel (null_target);
2927 ig.MarkLabel (sec_begin);
2928 foreach (SwitchLabel sl in ss.Labels)
2929 ig.MarkLabel (sl.GetILLabelCode (ec));
2932 pending_goto_end = !ss.Block.HasRet;
2935 ig.MarkLabel (next_test);
2936 ig.MarkLabel (default_target);
2938 ig.MarkLabel (null_target);
2939 if (default_section != null)
2940 default_section.Block.Emit (ec);
2941 ig.MarkLabel (end_of_switch);
2944 SwitchSection FindSection (SwitchLabel label)
2946 foreach (SwitchSection ss in Sections){
2947 foreach (SwitchLabel sl in ss.Labels){
2956 public override bool Resolve (EmitContext ec)
2958 Expr = Expr.Resolve (ec);
2962 new_expr = SwitchGoverningType (ec, Expr.Type);
2963 if (new_expr == null){
2964 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2969 SwitchType = new_expr.Type;
2971 if (!CheckSwitch (ec))
2974 Switch old_switch = ec.Switch;
2976 ec.Switch.SwitchType = SwitchType;
2978 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2979 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2981 is_constant = new_expr is Constant;
2983 object key = ((Constant) new_expr).GetValue ();
2984 SwitchLabel label = (SwitchLabel) Elements [key];
2986 constant_section = FindSection (label);
2987 if (constant_section == null)
2988 constant_section = default_section;
2992 foreach (SwitchSection ss in Sections){
2994 ec.CurrentBranching.CreateSibling (
2995 null, FlowBranching.SiblingType.SwitchSection);
2999 if (is_constant && (ss != constant_section)) {
3000 // If we're a constant switch, we're only emitting
3001 // one single section - mark all the others as
3003 ec.CurrentBranching.CurrentUsageVector.Goto ();
3004 if (!ss.Block.ResolveUnreachable (ec, true))
3007 if (!ss.Block.Resolve (ec))
3012 if (default_section == null)
3013 ec.CurrentBranching.CreateSibling (
3014 null, FlowBranching.SiblingType.SwitchSection);
3016 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3017 ec.Switch = old_switch;
3019 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3025 protected override void DoEmit (EmitContext ec)
3027 ILGenerator ig = ec.ig;
3029 // Store variable for comparission purposes
3032 value = ig.DeclareLocal (SwitchType);
3034 ig.Emit (OpCodes.Stloc, value);
3038 default_target = ig.DefineLabel ();
3041 // Setup the codegen context
3043 Label old_end = ec.LoopEnd;
3044 Switch old_switch = ec.Switch;
3046 ec.LoopEnd = ig.DefineLabel ();
3051 if (constant_section != null)
3052 constant_section.Block.Emit (ec);
3053 } else if (SwitchType == TypeManager.string_type)
3054 SimpleSwitchEmit (ec, value);
3056 TableSwitchEmit (ec, value);
3058 // Restore context state.
3059 ig.MarkLabel (ec.LoopEnd);
3062 // Restore the previous context
3064 ec.LoopEnd = old_end;
3065 ec.Switch = old_switch;
3069 public abstract class ExceptionStatement : Statement
3071 public abstract void EmitFinally (EmitContext ec);
3073 protected bool emit_finally = true;
3074 ArrayList parent_vectors;
3076 protected void DoEmitFinally (EmitContext ec)
3079 ec.ig.BeginFinallyBlock ();
3080 else if (ec.InIterator)
3081 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3085 protected void ResolveFinally (FlowBranchingException branching)
3087 emit_finally = branching.EmitFinally;
3089 branching.Parent.StealFinallyClauses (ref parent_vectors);
3093 public class Lock : ExceptionStatement {
3095 public Statement Statement;
3096 TemporaryVariable temp;
3098 public Lock (Expression expr, Statement stmt, Location l)
3105 public override bool Resolve (EmitContext ec)
3107 expr = expr.Resolve (ec);
3111 if (expr.Type.IsValueType){
3112 Report.Error (185, loc,
3113 "`{0}' is not a reference type as required by the lock statement",
3114 TypeManager.CSharpName (expr.Type));
3118 FlowBranchingException branching = ec.StartFlowBranching (this);
3119 bool ok = Statement.Resolve (ec);
3121 ec.KillFlowBranching ();
3125 ResolveFinally (branching);
3127 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3128 if (!reachability.AlwaysReturns) {
3129 // Unfortunately, System.Reflection.Emit automatically emits
3130 // a leave to the end of the finally block.
3131 // This is a problem if `returns' is true since we may jump
3132 // to a point after the end of the method.
3133 // As a workaround, emit an explicit ret here.
3134 ec.NeedReturnLabel ();
3137 // Avoid creating libraries that reference the internal
3140 if (t == TypeManager.null_type)
3141 t = TypeManager.object_type;
3143 temp = new TemporaryVariable (t, loc);
3149 protected override void DoEmit (EmitContext ec)
3151 ILGenerator ig = ec.ig;
3153 temp.Store (ec, expr);
3155 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3159 ig.BeginExceptionBlock ();
3160 Statement.Emit (ec);
3165 ig.EndExceptionBlock ();
3168 public override void EmitFinally (EmitContext ec)
3171 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3175 public class Unchecked : Statement {
3176 public readonly Block Block;
3178 public Unchecked (Block b)
3184 public override bool Resolve (EmitContext ec)
3186 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3187 return Block.Resolve (ec);
3190 protected override void DoEmit (EmitContext ec)
3192 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3197 public class Checked : Statement {
3198 public readonly Block Block;
3200 public Checked (Block b)
3203 b.Unchecked = false;
3206 public override bool Resolve (EmitContext ec)
3208 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3209 return Block.Resolve (ec);
3212 protected override void DoEmit (EmitContext ec)
3214 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3219 public class Unsafe : Statement {
3220 public readonly Block Block;
3222 public Unsafe (Block b)
3225 Block.Unsafe = true;
3228 public override bool Resolve (EmitContext ec)
3230 using (ec.With (EmitContext.Flags.InUnsafe, true))
3231 return Block.Resolve (ec);
3234 protected override void DoEmit (EmitContext ec)
3236 using (ec.With (EmitContext.Flags.InUnsafe, true))
3244 public class Fixed : Statement {
3246 ArrayList declarators;
3247 Statement statement;
3252 abstract class Emitter
3254 protected LocalInfo vi;
3255 protected Expression converted;
3257 protected Emitter (Expression expr, LocalInfo li)
3263 public abstract void Emit (EmitContext ec);
3264 public abstract void EmitExit (ILGenerator ig);
3267 class ExpressionEmitter : Emitter {
3268 public ExpressionEmitter (Expression converted, LocalInfo li) :
3269 base (converted, li)
3273 public override void Emit (EmitContext ec) {
3275 // Store pointer in pinned location
3277 converted.Emit (ec);
3278 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3281 public override void EmitExit (ILGenerator ig)
3283 ig.Emit (OpCodes.Ldc_I4_0);
3284 ig.Emit (OpCodes.Conv_U);
3285 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3289 class StringEmitter : Emitter {
3290 LocalBuilder pinned_string;
3293 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3299 public override void Emit (EmitContext ec)
3301 ILGenerator ig = ec.ig;
3302 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3304 converted.Emit (ec);
3305 ig.Emit (OpCodes.Stloc, pinned_string);
3307 Expression sptr = new StringPtr (pinned_string, loc);
3308 converted = Convert.ImplicitConversionRequired (
3309 ec, sptr, vi.VariableType, loc);
3311 if (converted == null)
3314 converted.Emit (ec);
3315 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3318 public override void EmitExit(ILGenerator ig)
3320 ig.Emit (OpCodes.Ldnull);
3321 ig.Emit (OpCodes.Stloc, pinned_string);
3325 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3328 declarators = decls;
3333 public Statement Statement {
3334 get { return statement; }
3337 public override bool Resolve (EmitContext ec)
3340 Expression.UnsafeError (loc);
3344 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3348 expr_type = texpr.Type;
3350 data = new Emitter [declarators.Count];
3352 if (!expr_type.IsPointer){
3353 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3358 foreach (Pair p in declarators){
3359 LocalInfo vi = (LocalInfo) p.First;
3360 Expression e = (Expression) p.Second;
3362 vi.VariableInfo.SetAssigned (ec);
3363 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3366 // The rules for the possible declarators are pretty wise,
3367 // but the production on the grammar is more concise.
3369 // So we have to enforce these rules here.
3371 // We do not resolve before doing the case 1 test,
3372 // because the grammar is explicit in that the token &
3373 // is present, so we need to test for this particular case.
3377 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3382 // Case 1: & object.
3384 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3385 Expression child = ((Unary) e).Expr;
3387 if (child is ParameterReference || child is LocalVariableReference){
3390 "No need to use fixed statement for parameters or " +
3391 "local variable declarations (address is already " +
3396 ec.InFixedInitializer = true;
3398 ec.InFixedInitializer = false;
3402 child = ((Unary) e).Expr;
3404 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3407 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
3408 e.Error_ValueCannotBeConverted (e.Location, expr_type, false);
3412 data [i] = new ExpressionEmitter (e, vi);
3418 ec.InFixedInitializer = true;
3420 ec.InFixedInitializer = false;
3427 if (e.Type.IsArray){
3428 Type array_type = TypeManager.GetElementType (e.Type);
3431 // Provided that array_type is unmanaged,
3433 if (!TypeManager.VerifyUnManaged (array_type, loc))
3437 // and T* is implicitly convertible to the
3438 // pointer type given in the fixed statement.
3440 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3442 Expression converted = Convert.ImplicitConversionRequired (
3443 ec, array_ptr, vi.VariableType, loc);
3444 if (converted == null)
3447 data [i] = new ExpressionEmitter (converted, vi);
3456 if (e.Type == TypeManager.string_type){
3457 data [i] = new StringEmitter (e, vi, loc);
3462 // Case 4: fixed buffer
3463 FieldExpr fe = e as FieldExpr;
3465 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3467 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3469 Expression converted = Convert.ImplicitConversionRequired (
3470 ec, fixed_buffer_ptr, vi.VariableType, loc);
3471 if (converted == null)
3474 data [i] = new ExpressionEmitter (converted, vi);
3482 // For other cases, flag a `this is already fixed expression'
3484 if (e is LocalVariableReference || e is ParameterReference ||
3485 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3487 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3491 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3495 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3497 if (!statement.Resolve (ec)) {
3498 ec.KillFlowBranching ();
3502 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3503 has_ret = reachability.IsUnreachable;
3508 protected override void DoEmit (EmitContext ec)
3510 for (int i = 0; i < data.Length; i++) {
3514 statement.Emit (ec);
3519 ILGenerator ig = ec.ig;
3522 // Clear the pinned variable
3524 for (int i = 0; i < data.Length; i++) {
3525 data [i].EmitExit (ig);
3530 public class Catch : Statement {
3531 public readonly string Name;
3532 public readonly Block Block;
3533 public readonly Block VarBlock;
3535 Expression type_expr;
3538 public Catch (Expression type, string name, Block block, Block var_block, Location l)
3543 VarBlock = var_block;
3547 public Type CatchType {
3553 public bool IsGeneral {
3555 return type_expr == null;
3559 protected override void DoEmit(EmitContext ec)
3563 public override bool Resolve (EmitContext ec)
3565 using (ec.With (EmitContext.Flags.InCatch, true)) {
3566 if (type_expr != null) {
3567 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3573 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3574 Error (155, "The type caught or thrown must be derived from System.Exception");
3580 if (!Block.Resolve (ec))
3583 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
3584 // emit the "unused variable" warnings.
3585 if (VarBlock != null)
3586 return VarBlock.Resolve (ec);
3593 public class Try : ExceptionStatement {
3594 public readonly Block Fini, Block;
3595 public readonly ArrayList Specific;
3596 public readonly Catch General;
3598 bool need_exc_block;
3601 // specific, general and fini might all be null.
3603 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3605 if (specific == null && general == null){
3606 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3610 this.Specific = specific;
3611 this.General = general;
3616 public override bool Resolve (EmitContext ec)
3620 FlowBranchingException branching = ec.StartFlowBranching (this);
3622 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3624 if (!Block.Resolve (ec))
3627 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3629 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3631 Type[] prevCatches = new Type [Specific.Count];
3633 foreach (Catch c in Specific){
3634 ec.CurrentBranching.CreateSibling (
3635 c.Block, FlowBranching.SiblingType.Catch);
3637 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3639 if (c.Name != null) {
3640 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3642 throw new Exception ();
3644 vi.VariableInfo = null;
3647 if (!c.Resolve (ec))
3650 Type resolvedType = c.CatchType;
3651 for (int ii = 0; ii < last_index; ++ii) {
3652 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3653 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3658 prevCatches [last_index++] = resolvedType;
3659 need_exc_block = true;
3662 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3664 if (General != null){
3665 if (CodeGen.Assembly.WrapNonExceptionThrows) {
3666 foreach (Catch c in Specific){
3667 if (c.CatchType == TypeManager.exception_type) {
3668 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'");
3673 ec.CurrentBranching.CreateSibling (
3674 General.Block, FlowBranching.SiblingType.Catch);
3676 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3678 if (!General.Resolve (ec))
3681 need_exc_block = true;
3684 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3688 ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
3690 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3691 using (ec.With (EmitContext.Flags.InFinally, true)) {
3692 if (!Fini.Resolve (ec))
3697 need_exc_block = true;
3700 if (ec.InIterator) {
3701 ResolveFinally (branching);
3702 need_exc_block |= emit_finally;
3704 emit_finally = Fini != null;
3706 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3708 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3710 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3712 if (!reachability.AlwaysReturns) {
3713 // Unfortunately, System.Reflection.Emit automatically emits
3714 // a leave to the end of the finally block. This is a problem
3715 // if `returns' is true since we may jump to a point after the
3716 // end of the method.
3717 // As a workaround, emit an explicit ret here.
3718 ec.NeedReturnLabel ();
3724 protected override void DoEmit (EmitContext ec)
3726 ILGenerator ig = ec.ig;
3729 ig.BeginExceptionBlock ();
3732 foreach (Catch c in Specific){
3735 ig.BeginCatchBlock (c.CatchType);
3737 if (c.VarBlock != null)
3738 ec.EmitScopeInitFromBlock (c.VarBlock);
3739 if (c.Name != null){
3740 vi = c.Block.GetLocalInfo (c.Name);
3742 throw new Exception ("Variable does not exist in this block");
3745 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
3746 ig.Emit (OpCodes.Stloc, e);
3748 ec.EmitCapturedVariableInstance (vi);
3749 ig.Emit (OpCodes.Ldloc, e);
3750 ig.Emit (OpCodes.Stfld, vi.FieldBuilder);
3752 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3754 ig.Emit (OpCodes.Pop);
3759 if (General != null){
3760 ig.BeginCatchBlock (TypeManager.object_type);
3761 ig.Emit (OpCodes.Pop);
3762 General.Block.Emit (ec);
3767 ig.EndExceptionBlock ();
3770 public override void EmitFinally (EmitContext ec)
3776 public bool HasCatch
3779 return General != null || Specific.Count > 0;
3784 public class Using : ExceptionStatement {
3785 object expression_or_block;
3786 public Statement Statement;
3790 Expression [] resolved_vars;
3791 Expression [] converted_vars;
3792 ExpressionStatement [] assign;
3793 LocalBuilder local_copy;
3795 public Using (object expression_or_block, Statement stmt, Location l)
3797 this.expression_or_block = expression_or_block;
3803 // Resolves for the case of using using a local variable declaration.
3805 bool ResolveLocalVariableDecls (EmitContext ec)
3809 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3813 expr_type = texpr.Type;
3816 // The type must be an IDisposable or an implicit conversion
3819 converted_vars = new Expression [var_list.Count];
3820 resolved_vars = new Expression [var_list.Count];
3821 assign = new ExpressionStatement [var_list.Count];
3823 bool need_conv = !TypeManager.ImplementsInterface (
3824 expr_type, TypeManager.idisposable_type);
3826 foreach (DictionaryEntry e in var_list){
3827 Expression var = (Expression) e.Key;
3829 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3833 resolved_vars [i] = var;
3840 converted_vars [i] = Convert.ImplicitConversion (
3841 ec, var, TypeManager.idisposable_type, loc);
3843 if (converted_vars [i] == null) {
3844 Error_IsNotConvertibleToIDisposable ();
3852 foreach (DictionaryEntry e in var_list){
3853 Expression var = resolved_vars [i];
3854 Expression new_expr = (Expression) e.Value;
3857 a = new Assign (var, new_expr, loc);
3863 converted_vars [i] = var;
3864 assign [i] = (ExpressionStatement) a;
3871 void Error_IsNotConvertibleToIDisposable ()
3873 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
3874 TypeManager.CSharpName (expr_type));
3877 bool ResolveExpression (EmitContext ec)
3879 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3880 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3881 Error_IsNotConvertibleToIDisposable ();
3890 // Emits the code for the case of using using a local variable declaration.
3892 void EmitLocalVariableDecls (EmitContext ec)
3894 ILGenerator ig = ec.ig;
3897 for (i = 0; i < assign.Length; i++) {
3898 assign [i].EmitStatement (ec);
3901 ig.BeginExceptionBlock ();
3903 Statement.Emit (ec);
3904 var_list.Reverse ();
3909 void EmitLocalVariableDeclFinally (EmitContext ec)
3911 ILGenerator ig = ec.ig;
3913 int i = assign.Length;
3914 for (int ii = 0; ii < var_list.Count; ++ii){
3915 Expression var = resolved_vars [--i];
3916 Label skip = ig.DefineLabel ();
3918 if (!var.Type.IsValueType) {
3920 ig.Emit (OpCodes.Brfalse, skip);
3921 converted_vars [i].Emit (ec);
3922 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3924 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3926 if (!(ml is MethodGroupExpr)) {
3928 ig.Emit (OpCodes.Box, var.Type);
3929 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3931 MethodInfo mi = null;
3933 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3934 if (TypeManager.GetParameterData (mk).Count == 0) {
3941 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3945 IMemoryLocation mloc = (IMemoryLocation) var;
3947 mloc.AddressOf (ec, AddressOp.Load);
3948 ig.Emit (OpCodes.Call, mi);
3952 ig.MarkLabel (skip);
3955 ig.EndExceptionBlock ();
3957 ig.BeginFinallyBlock ();
3962 void EmitExpression (EmitContext ec)
3965 // Make a copy of the expression and operate on that.
3967 ILGenerator ig = ec.ig;
3968 local_copy = ig.DeclareLocal (expr_type);
3971 ig.Emit (OpCodes.Stloc, local_copy);
3974 ig.BeginExceptionBlock ();
3976 Statement.Emit (ec);
3980 ig.EndExceptionBlock ();
3983 void EmitExpressionFinally (EmitContext ec)
3985 ILGenerator ig = ec.ig;
3986 if (!local_copy.LocalType.IsValueType) {
3987 Label skip = ig.DefineLabel ();
3988 ig.Emit (OpCodes.Ldloc, local_copy);
3989 ig.Emit (OpCodes.Brfalse, skip);
3990 ig.Emit (OpCodes.Ldloc, local_copy);
3991 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3992 ig.MarkLabel (skip);
3994 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
3996 if (!(ml is MethodGroupExpr)) {
3997 ig.Emit (OpCodes.Ldloc, local_copy);
3998 ig.Emit (OpCodes.Box, local_copy.LocalType);
3999 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4001 MethodInfo mi = null;
4003 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4004 if (TypeManager.GetParameterData (mk).Count == 0) {
4011 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4015 ig.Emit (OpCodes.Ldloca, local_copy);
4016 ig.Emit (OpCodes.Call, mi);
4021 public override bool Resolve (EmitContext ec)
4023 if (expression_or_block is DictionaryEntry){
4024 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4025 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4027 if (!ResolveLocalVariableDecls (ec))
4030 } else if (expression_or_block is Expression){
4031 expr = (Expression) expression_or_block;
4033 expr = expr.Resolve (ec);
4037 expr_type = expr.Type;
4039 if (!ResolveExpression (ec))
4043 FlowBranchingException branching = ec.StartFlowBranching (this);
4045 bool ok = Statement.Resolve (ec);
4048 ec.KillFlowBranching ();
4052 ResolveFinally (branching);
4053 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4055 if (!reachability.AlwaysReturns) {
4056 // Unfortunately, System.Reflection.Emit automatically emits a leave
4057 // to the end of the finally block. This is a problem if `returns'
4058 // is true since we may jump to a point after the end of the method.
4059 // As a workaround, emit an explicit ret here.
4060 ec.NeedReturnLabel ();
4066 protected override void DoEmit (EmitContext ec)
4068 if (expression_or_block is DictionaryEntry)
4069 EmitLocalVariableDecls (ec);
4070 else if (expression_or_block is Expression)
4071 EmitExpression (ec);
4074 public override void EmitFinally (EmitContext ec)
4076 if (expression_or_block is DictionaryEntry)
4077 EmitLocalVariableDeclFinally (ec);
4078 else if (expression_or_block is Expression)
4079 EmitExpressionFinally (ec);
4084 /// Implementation of the foreach C# statement
4086 public class Foreach : Statement {
4088 Expression variable;
4090 Statement statement;
4092 CollectionForeach collection;
4094 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4095 Statement stmt, Location l)
4098 this.variable = var;
4104 public Statement Statement {
4105 get { return statement; }
4108 public override bool Resolve (EmitContext ec)
4110 expr = expr.Resolve (ec);
4114 Constant c = expr as Constant;
4115 if (c != null && c.GetValue () == null) {
4116 Report.Error (186, loc, "Use of null is not valid in this context");
4120 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4124 Type var_type = texpr.Type;
4126 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethod) {
4127 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4128 expr.ExprClassName);
4133 // We need an instance variable. Not sure this is the best
4134 // way of doing this.
4136 // FIXME: When we implement propertyaccess, will those turn
4137 // out to return values in ExprClass? I think they should.
4139 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4140 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4141 collection.Error_Enumerator ();
4145 if (expr.Type.IsArray) {
4146 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4147 return array.Resolve (ec);
4149 collection = new CollectionForeach (
4150 var_type, variable, expr, statement, loc);
4151 return collection.Resolve (ec);
4155 protected override void DoEmit (EmitContext ec)
4157 ILGenerator ig = ec.ig;
4159 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4160 ec.LoopBegin = ig.DefineLabel ();
4161 ec.LoopEnd = ig.DefineLabel ();
4163 if (collection != null)
4164 collection.Emit (ec);
4168 ec.LoopBegin = old_begin;
4169 ec.LoopEnd = old_end;
4172 protected class ArrayCounter : TemporaryVariable
4174 public ArrayCounter (Location loc)
4175 : base (TypeManager.int32_type, loc)
4178 public void Initialize (EmitContext ec)
4181 ec.ig.Emit (OpCodes.Ldc_I4_0);
4185 public void Increment (EmitContext ec)
4189 ec.ig.Emit (OpCodes.Ldc_I4_1);
4190 ec.ig.Emit (OpCodes.Add);
4195 protected class ArrayForeach : Statement
4197 Expression variable, expr, conv;
4198 Statement statement;
4201 TemporaryVariable[] lengths;
4202 ArrayCounter[] counter;
4205 TemporaryVariable copy;
4208 public ArrayForeach (Type var_type, Expression var,
4209 Expression expr, Statement stmt, Location l)
4211 this.var_type = var_type;
4212 this.variable = var;
4218 public override bool Resolve (EmitContext ec)
4220 array_type = expr.Type;
4221 rank = array_type.GetArrayRank ();
4223 copy = new TemporaryVariable (array_type, loc);
4226 counter = new ArrayCounter [rank];
4227 lengths = new TemporaryVariable [rank];
4229 ArrayList list = new ArrayList ();
4230 for (int i = 0; i < rank; i++) {
4231 counter [i] = new ArrayCounter (loc);
4232 counter [i].Resolve (ec);
4234 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4235 lengths [i].Resolve (ec);
4237 list.Add (counter [i]);
4240 access = new ElementAccess (copy, list).Resolve (ec);
4244 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4250 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4251 ec.CurrentBranching.CreateSibling ();
4253 variable = variable.ResolveLValue (ec, conv, loc);
4254 if (variable == null)
4257 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4258 if (!statement.Resolve (ec))
4260 ec.EndFlowBranching ();
4262 // There's no direct control flow from the end of the embedded statement to the end of the loop
4263 ec.CurrentBranching.CurrentUsageVector.Goto ();
4265 ec.EndFlowBranching ();
4270 protected override void DoEmit (EmitContext ec)
4272 ILGenerator ig = ec.ig;
4274 copy.Store (ec, expr);
4276 Label[] test = new Label [rank];
4277 Label[] loop = new Label [rank];
4279 for (int i = 0; i < rank; i++) {
4280 test [i] = ig.DefineLabel ();
4281 loop [i] = ig.DefineLabel ();
4283 lengths [i].EmitThis (ec);
4284 ((ArrayAccess) access).EmitGetLength (ec, i);
4285 lengths [i].EmitStore (ig);
4288 for (int i = 0; i < rank; i++) {
4289 counter [i].Initialize (ec);
4291 ig.Emit (OpCodes.Br, test [i]);
4292 ig.MarkLabel (loop [i]);
4295 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4297 statement.Emit (ec);
4299 ig.MarkLabel (ec.LoopBegin);
4301 for (int i = rank - 1; i >= 0; i--){
4302 counter [i].Increment (ec);
4304 ig.MarkLabel (test [i]);
4305 counter [i].Emit (ec);
4306 lengths [i].Emit (ec);
4307 ig.Emit (OpCodes.Blt, loop [i]);
4310 ig.MarkLabel (ec.LoopEnd);
4314 protected class CollectionForeach : ExceptionStatement
4316 Expression variable, expr;
4317 Statement statement;
4319 TemporaryVariable enumerator;
4323 MethodGroupExpr get_enumerator;
4324 PropertyExpr get_current;
4325 MethodInfo move_next;
4326 Type var_type, enumerator_type;
4328 bool enumerator_found;
4330 public CollectionForeach (Type var_type, Expression var,
4331 Expression expr, Statement stmt, Location l)
4333 this.var_type = var_type;
4334 this.variable = var;
4340 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4342 Type return_type = mi.ReturnType;
4344 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4346 // Apply the same optimization as MS: skip the GetEnumerator
4347 // returning an IEnumerator, and use the one returning a
4348 // CharEnumerator instead. This allows us to avoid the
4349 // try-finally block and the boxing.
4354 // Ok, we can access it, now make sure that we can do something
4355 // with this `GetEnumerator'
4358 if (return_type == TypeManager.ienumerator_type ||
4359 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4360 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4362 // If it is not an interface, lets try to find the methods ourselves.
4363 // For example, if we have:
4364 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4365 // We can avoid the iface call. This is a runtime perf boost.
4366 // even bigger if we have a ValueType, because we avoid the cost
4369 // We have to make sure that both methods exist for us to take
4370 // this path. If one of the methods does not exist, we will just
4371 // use the interface. Sadly, this complex if statement is the only
4372 // way I could do this without a goto
4375 if (return_type.IsInterface ||
4376 !FetchMoveNext (return_type) ||
4377 !FetchGetCurrent (ec, return_type)) {
4378 move_next = TypeManager.bool_movenext_void;
4379 get_current = new PropertyExpr (
4380 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4385 // Ok, so they dont return an IEnumerable, we will have to
4386 // find if they support the GetEnumerator pattern.
4389 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
4390 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",
4391 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
4396 enumerator_type = return_type;
4397 is_disposable = !enumerator_type.IsSealed ||
4398 TypeManager.ImplementsInterface (
4399 enumerator_type, TypeManager.idisposable_type);
4405 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4407 bool FetchMoveNext (Type t)
4409 MemberList move_next_list;
4411 move_next_list = TypeContainer.FindMembers (
4412 t, MemberTypes.Method,
4413 BindingFlags.Public | BindingFlags.Instance,
4414 Type.FilterName, "MoveNext");
4415 if (move_next_list.Count == 0)
4418 foreach (MemberInfo m in move_next_list){
4419 MethodInfo mi = (MethodInfo) m;
4421 if ((TypeManager.GetParameterData (mi).Count == 0) &&
4422 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4432 // Retrieves a `public T get_Current ()' method from the Type `t'
4434 bool FetchGetCurrent (EmitContext ec, Type t)
4436 PropertyExpr pe = Expression.MemberLookup (
4437 ec.ContainerType, t, "Current", MemberTypes.Property,
4438 Expression.AllBindingFlags, loc) as PropertyExpr;
4447 // Retrieves a `public void Dispose ()' method from the Type `t'
4449 static MethodInfo FetchMethodDispose (Type t)
4451 MemberList dispose_list;
4453 dispose_list = TypeContainer.FindMembers (
4454 t, MemberTypes.Method,
4455 BindingFlags.Public | BindingFlags.Instance,
4456 Type.FilterName, "Dispose");
4457 if (dispose_list.Count == 0)
4460 foreach (MemberInfo m in dispose_list){
4461 MethodInfo mi = (MethodInfo) m;
4463 if (TypeManager.GetParameterData (mi).Count == 0){
4464 if (mi.ReturnType == TypeManager.void_type)
4471 public void Error_Enumerator ()
4473 if (enumerator_found) {
4477 Report.Error (1579, loc,
4478 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4479 TypeManager.CSharpName (expr.Type));
4482 bool TryType (EmitContext ec, Type t)
4484 MethodGroupExpr mg = Expression.MemberLookup (
4485 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
4486 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4490 foreach (MethodBase mb in mg.Methods) {
4491 if (TypeManager.GetParameterData (mb).Count != 0)
4494 // Check whether GetEnumerator is public
4495 if ((mb.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4498 if (TypeManager.IsOverride (mb))
4501 enumerator_found = true;
4503 if (!GetEnumeratorFilter (ec, (MethodInfo) mb))
4506 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) mb };
4507 get_enumerator = new MethodGroupExpr (mi, loc);
4509 if (t != expr.Type) {
4510 expr = Convert.ExplicitConversion (
4513 throw new InternalErrorException ();
4516 get_enumerator.InstanceExpression = expr;
4517 get_enumerator.IsBase = t != expr.Type;
4525 bool ProbeCollectionType (EmitContext ec, Type t)
4527 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4528 if (TryType (ec, tt))
4534 // Now try to find the method in the interfaces
4537 Type [] ifaces = t.GetInterfaces ();
4539 foreach (Type i in ifaces){
4540 if (TryType (ec, i))
4545 // Since TypeBuilder.GetInterfaces only returns the interface
4546 // types for this type, we have to keep looping, but once
4547 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4548 // done, because it returns all the types
4550 if ((t is TypeBuilder))
4559 public override bool Resolve (EmitContext ec)
4561 enumerator_type = TypeManager.ienumerator_type;
4562 is_disposable = true;
4564 if (!ProbeCollectionType (ec, expr.Type)) {
4565 Error_Enumerator ();
4569 enumerator = new TemporaryVariable (enumerator_type, loc);
4570 enumerator.Resolve (ec);
4572 init = new Invocation (get_enumerator, new ArrayList ());
4573 init = init.Resolve (ec);
4577 Expression move_next_expr;
4579 MemberInfo[] mi = new MemberInfo[] { move_next };
4580 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4581 mg.InstanceExpression = enumerator;
4583 move_next_expr = new Invocation (mg, new ArrayList ());
4586 get_current.InstanceExpression = enumerator;
4588 Statement block = new CollectionForeachStatement (
4589 var_type, variable, get_current, statement, loc);
4591 loop = new While (move_next_expr, block, loc);
4595 FlowBranchingException branching = null;
4597 branching = ec.StartFlowBranching (this);
4599 if (!loop.Resolve (ec))
4602 if (is_disposable) {
4603 ResolveFinally (branching);
4604 ec.EndFlowBranching ();
4606 emit_finally = true;
4611 protected override void DoEmit (EmitContext ec)
4613 ILGenerator ig = ec.ig;
4615 enumerator.Store (ec, init);
4618 // Protect the code in a try/finalize block, so that
4619 // if the beast implement IDisposable, we get rid of it
4621 if (is_disposable && emit_finally)
4622 ig.BeginExceptionBlock ();
4627 // Now the finally block
4629 if (is_disposable) {
4632 ig.EndExceptionBlock ();
4637 public override void EmitFinally (EmitContext ec)
4639 ILGenerator ig = ec.ig;
4641 if (enumerator_type.IsValueType) {
4642 MethodInfo mi = FetchMethodDispose (enumerator_type);
4644 enumerator.EmitLoadAddress (ec);
4645 ig.Emit (OpCodes.Call, mi);
4647 enumerator.Emit (ec);
4648 ig.Emit (OpCodes.Box, enumerator_type);
4649 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4652 Label call_dispose = ig.DefineLabel ();
4654 enumerator.Emit (ec);
4655 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4656 ig.Emit (OpCodes.Dup);
4657 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4658 ig.Emit (OpCodes.Pop);
4660 Label end_finally = ig.DefineLabel ();
4661 ig.Emit (OpCodes.Br, end_finally);
4663 ig.MarkLabel (call_dispose);
4664 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4665 ig.MarkLabel (end_finally);
4670 protected class CollectionForeachStatement : Statement
4673 Expression variable, current, conv;
4674 Statement statement;
4677 public CollectionForeachStatement (Type type, Expression variable,
4678 Expression current, Statement statement,
4682 this.variable = variable;
4683 this.current = current;
4684 this.statement = statement;
4688 public override bool Resolve (EmitContext ec)
4690 current = current.Resolve (ec);
4691 if (current == null)
4694 conv = Convert.ExplicitConversion (ec, current, type, loc);
4698 assign = new Assign (variable, conv, loc);
4699 if (assign.Resolve (ec) == null)
4702 if (!statement.Resolve (ec))
4708 protected override void DoEmit (EmitContext ec)
4710 assign.EmitStatement (ec);
4711 statement.Emit (ec);