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 in_exc = 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;
654 public override bool Resolve (EmitContext ec)
656 label = ec.CurrentBranching.LookupLabel (target, loc);
660 // If this is a forward goto.
661 if (!label.IsDefined)
662 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
664 ec.CurrentBranching.CurrentUsageVector.Goto ();
665 label.AddReference ();
670 public Goto (string label, Location l)
676 public string Target {
682 protected override void DoEmit (EmitContext ec)
684 Label l = label.LabelTarget (ec);
685 ec.ig.Emit (OpCodes.Br, l);
689 public class LabeledStatement : Statement {
696 FlowBranching.UsageVector vectors;
698 public LabeledStatement (string name, Location l)
704 public Label LabelTarget (EmitContext ec)
709 label = ec.ig.DefineLabel ();
719 public bool IsDefined {
720 get { return defined; }
723 public bool HasBeenReferenced {
724 get { return referenced; }
727 public FlowBranching.UsageVector JumpOrigins {
728 get { return vectors; }
731 public void AddUsageVector (FlowBranching.UsageVector vector)
733 vector = vector.Clone ();
734 vector.Next = vectors;
738 public override bool Resolve (EmitContext ec)
740 ec.CurrentBranching.Label (vectors);
742 // this flow-branching will be terminated when the surrounding block ends
743 ec.StartFlowBranching (this);
747 protected override void DoEmit (EmitContext ec)
749 if (ig != null && ig != ec.ig) {
750 // TODO: location is wrong
751 Report.Error (1632, loc, "Control cannot leave the body of an anonymous method");
755 ec.ig.MarkLabel (label);
758 public void AddReference ()
766 /// `goto default' statement
768 public class GotoDefault : Statement {
770 public GotoDefault (Location l)
775 public override bool Resolve (EmitContext ec)
777 ec.CurrentBranching.CurrentUsageVector.Goto ();
781 protected override void DoEmit (EmitContext ec)
783 if (ec.Switch == null){
784 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
788 if (!ec.Switch.GotDefault){
789 Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
792 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
797 /// `goto case' statement
799 public class GotoCase : Statement {
803 public GotoCase (Expression e, Location l)
809 public override bool Resolve (EmitContext ec)
811 if (ec.Switch == null){
812 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
816 expr = expr.Resolve (ec);
820 Constant c = expr as Constant;
822 Error (150, "A constant value is expected");
826 c = c.ToType (ec.Switch.SwitchType, loc);
830 object val = c.GetValue ();
832 val = SwitchLabel.NullStringCase;
834 sl = (SwitchLabel) ec.Switch.Elements [val];
837 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", c.GetValue () == null ? "null" : val.ToString ());
841 ec.CurrentBranching.CurrentUsageVector.Goto ();
845 protected override void DoEmit (EmitContext ec)
847 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
851 public class Throw : Statement {
854 public Throw (Expression expr, Location l)
860 public override bool Resolve (EmitContext ec)
862 ec.CurrentBranching.CurrentUsageVector.Throw ();
865 expr = expr.Resolve (ec);
869 ExprClass eclass = expr.eclass;
871 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
872 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
873 expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
879 if ((t != TypeManager.exception_type) &&
880 !t.IsSubclassOf (TypeManager.exception_type) &&
881 !(expr is NullLiteral)) {
883 "The type caught or thrown must be derived " +
884 "from System.Exception");
891 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
896 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
902 protected override void DoEmit (EmitContext ec)
905 ec.ig.Emit (OpCodes.Rethrow);
909 ec.ig.Emit (OpCodes.Throw);
914 public class Break : Statement {
916 public Break (Location l)
923 public override bool Resolve (EmitContext ec)
925 int errors = Report.Errors;
926 crossing_exc = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
927 ec.CurrentBranching.CurrentUsageVector.Goto ();
928 return errors == Report.Errors;
931 protected override void DoEmit (EmitContext ec)
933 ec.ig.Emit (crossing_exc ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
937 public class Continue : Statement {
939 public Continue (Location l)
946 public override bool Resolve (EmitContext ec)
948 int errors = Report.Errors;
949 crossing_exc = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
950 ec.CurrentBranching.CurrentUsageVector.Goto ();
951 return errors == Report.Errors;
954 protected override void DoEmit (EmitContext ec)
956 ec.ig.Emit (crossing_exc ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
961 // The information about a user-perceived local variable
963 public class LocalInfo {
964 public Expression Type;
967 // Most of the time a variable will be stored in a LocalBuilder
969 // But sometimes, it will be stored in a field (variables that have been
970 // hoisted by iterators or by anonymous methods). The context of the field will
971 // be stored in the EmitContext
974 public LocalBuilder LocalBuilder;
975 public FieldBuilder FieldBuilder;
977 public Type VariableType;
978 public readonly string Name;
979 public readonly Location Location;
980 public readonly Block Block;
982 public VariableInfo VariableInfo;
991 CompilerGenerated = 64
994 public enum ReadOnlyContext: byte {
1001 ReadOnlyContext ro_context;
1003 public LocalInfo (Expression type, string name, Block block, Location l)
1011 public LocalInfo (DeclSpace ds, Block block, Location l)
1013 VariableType = ds.TypeBuilder;
1018 public bool IsThisAssigned (EmitContext ec, Location loc)
1020 if (VariableInfo == null)
1021 throw new Exception ();
1023 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1026 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1029 public bool IsAssigned (EmitContext ec)
1031 if (VariableInfo == null)
1032 throw new Exception ();
1034 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1037 public bool Resolve (EmitContext ec)
1039 if (VariableType == null) {
1040 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1044 VariableType = texpr.Type;
1047 if (VariableType == TypeManager.void_type) {
1048 Report.Error (1547, Location,
1049 "Keyword 'void' cannot be used in this context");
1053 if (VariableType.IsAbstract && VariableType.IsSealed) {
1054 Report.Error (723, Location, "Cannot declare variable of static type `{0}'", TypeManager.CSharpName (VariableType));
1058 if (VariableType.IsPointer && !ec.InUnsafe)
1059 Expression.UnsafeError (Location);
1064 public bool IsCaptured {
1066 return (flags & Flags.Captured) != 0;
1070 flags |= Flags.Captured;
1074 public bool AddressTaken {
1076 return (flags & Flags.AddressTaken) != 0;
1080 flags |= Flags.AddressTaken;
1084 public bool CompilerGenerated {
1086 return (flags & Flags.CompilerGenerated) != 0;
1090 flags |= Flags.CompilerGenerated;
1094 public override string ToString ()
1096 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1097 Name, Type, VariableInfo, Location);
1102 return (flags & Flags.Used) != 0;
1105 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1109 public bool ReadOnly {
1111 return (flags & Flags.ReadOnly) != 0;
1115 public void SetReadOnlyContext (ReadOnlyContext context)
1117 flags |= Flags.ReadOnly;
1118 ro_context = context;
1121 public string GetReadOnlyContext ()
1124 throw new InternalErrorException ("Variable is not readonly");
1126 switch (ro_context) {
1127 case ReadOnlyContext.Fixed:
1128 return "fixed variable";
1129 case ReadOnlyContext.Foreach:
1130 return "foreach iteration variable";
1131 case ReadOnlyContext.Using:
1132 return "using variable";
1134 throw new NotImplementedException ();
1138 // Whether the variable is pinned, if Pinned the variable has been
1139 // allocated in a pinned slot with DeclareLocal.
1141 public bool Pinned {
1143 return (flags & Flags.Pinned) != 0;
1146 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1150 public bool IsThis {
1152 return (flags & Flags.IsThis) != 0;
1155 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1161 /// Block represents a C# block.
1165 /// This class is used in a number of places: either to represent
1166 /// explicit blocks that the programmer places or implicit blocks.
1168 /// Implicit blocks are used as labels or to introduce variable
1171 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1172 /// they contain extra information that is not necessary on normal blocks.
1174 public class Block : Statement {
1175 public Block Parent;
1176 public readonly Location StartLocation;
1177 public Location EndLocation = Location.Null;
1179 public readonly ToplevelBlock Toplevel;
1182 public enum Flags : ushort {
1186 VariablesInitialized = 8,
1191 HasVarargs = 256 // Used in ToplevelBlock
1193 protected Flags flags;
1195 public bool Implicit {
1196 get { return (flags & Flags.Implicit) != 0; }
1199 public bool Unchecked {
1200 get { return (flags & Flags.Unchecked) != 0; }
1201 set { flags |= Flags.Unchecked; }
1204 public bool Unsafe {
1205 get { return (flags & Flags.Unsafe) != 0; }
1206 set { flags |= Flags.Unsafe; }
1210 // The statements in this block
1212 ArrayList statements;
1216 // An array of Blocks. We keep track of children just
1217 // to generate the local variable declarations.
1219 // Statements and child statements are handled through the
1225 // Labels. (label, block) pairs.
1230 // Keeps track of (name, type) pairs
1232 IDictionary variables;
1235 // Keeps track of constants
1236 Hashtable constants;
1239 // Temporary variables.
1241 ArrayList temporary_variables;
1244 // If this is a switch section, the enclosing switch block.
1248 protected static int id;
1252 public Block (Block parent)
1253 : this (parent, (Flags) 0, Location.Null, Location.Null)
1256 public Block (Block parent, Flags flags)
1257 : this (parent, flags, Location.Null, Location.Null)
1260 public Block (Block parent, Location start, Location end)
1261 : this (parent, (Flags) 0, start, end)
1264 public Block (Block parent, Flags flags, Location start, Location end)
1267 parent.AddChild (this);
1269 this.Parent = parent;
1271 this.StartLocation = start;
1272 this.EndLocation = end;
1275 statements = new ArrayList ();
1277 if ((flags & Flags.IsToplevel) != 0)
1278 Toplevel = (ToplevelBlock) this;
1280 Toplevel = parent.Toplevel;
1282 if (parent != null && Implicit) {
1283 if (parent.known_variables == null)
1284 parent.known_variables = new Hashtable ();
1285 // share with parent
1286 known_variables = parent.known_variables;
1290 public Block CreateSwitchBlock (Location start)
1292 Block new_block = new Block (this, start, start);
1293 new_block.switch_block = this;
1298 get { return this_id; }
1301 protected IDictionary Variables {
1303 if (variables == null)
1304 variables = new ListDictionary ();
1309 void AddChild (Block b)
1311 if (children == null)
1312 children = new ArrayList ();
1317 public void SetEndLocation (Location loc)
1323 /// Adds a label to the current block.
1327 /// false if the name already exists in this block. true
1331 public bool AddLabel (LabeledStatement target)
1333 if (switch_block != null)
1334 return switch_block.AddLabel (target);
1336 string name = target.Name;
1339 while (cur != null) {
1340 if (cur.DoLookupLabel (name) != null) {
1341 Report.Error (140, target.loc, "The label `{0}' is a duplicate", name);
1351 while (cur != null) {
1352 if (cur.DoLookupLabel (name) != null) {
1355 "The label `{0}' shadows another label by the same name in a contained scope.",
1360 if (children != null) {
1361 foreach (Block b in children) {
1362 LabeledStatement s = b.DoLookupLabel (name);
1368 "The label `{0}' shadows another label by the same name in a contained scope.",
1379 labels = new Hashtable ();
1381 labels.Add (name, target);
1385 public LabeledStatement LookupLabel (string name)
1387 LabeledStatement s = DoLookupLabel (name);
1391 if (children == null)
1394 foreach (Block child in children) {
1395 if (!child.Implicit)
1398 s = child.LookupLabel (name);
1406 LabeledStatement DoLookupLabel (string name)
1408 if (switch_block != null)
1409 return switch_block.LookupLabel (name);
1412 if (labels.Contains (name))
1413 return ((LabeledStatement) labels [name]);
1418 Hashtable known_variables;
1421 // Marks a variable with name @name as being used in this or a child block.
1422 // If a variable name has been used in a child block, it's illegal to
1423 // declare a variable with the same name in the current block.
1425 void AddKnownVariable (string name, LocalInfo info)
1427 if (known_variables == null)
1428 known_variables = new Hashtable ();
1430 known_variables [name] = info;
1433 LocalInfo GetKnownVariableInfo (string name)
1435 if (known_variables == null)
1437 return (LocalInfo) known_variables [name];
1440 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1443 LocalInfo kvi = b.GetKnownVariableInfo (name);
1444 while (kvi == null) {
1450 kvi = b.GetKnownVariableInfo (name);
1456 // Is kvi.Block nested inside 'b'
1457 if (b.known_variables != kvi.Block.known_variables) {
1459 // If a variable by the same name it defined in a nested block of this
1460 // block, we violate the invariant meaning in a block.
1463 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1464 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1469 // It's ok if the definition is in a nested subblock of b, but not
1470 // nested inside this block -- a definition in a sibling block
1471 // should not affect us.
1477 // Block 'b' and kvi.Block are the same textual block.
1478 // However, different variables are extant.
1480 // Check if the variable is in scope in both blocks. We use
1481 // an indirect check that depends on AddVariable doing its
1482 // part in maintaining the invariant-meaning-in-block property.
1484 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1488 // Even though we detected the error when the name is used, we
1489 // treat it as if the variable declaration was in error.
1491 Report.SymbolRelatedToPreviousError (loc, name);
1492 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1496 public LocalInfo AddVariable (Expression type, string name, Location l)
1498 LocalInfo vi = GetLocalInfo (name);
1500 Report.SymbolRelatedToPreviousError (vi.Location, name);
1501 if (known_variables == vi.Block.known_variables)
1502 Report.Error (128, l,
1503 "A local variable named `{0}' is already defined in this scope", name);
1505 Error_AlreadyDeclared (l, name, "parent");
1509 vi = GetKnownVariableInfo (name);
1511 Report.SymbolRelatedToPreviousError (vi.Location, name);
1512 Error_AlreadyDeclared (l, name, "child");
1517 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1519 Report.SymbolRelatedToPreviousError (p.Location, name);
1520 Error_AlreadyDeclared (l, name, "method argument");
1524 vi = new LocalInfo (type, name, this, l);
1526 Variables.Add (name, vi);
1528 for (Block b = this; b != null; b = b.Parent)
1529 b.AddKnownVariable (name, vi);
1531 if ((flags & Flags.VariablesInitialized) != 0)
1532 throw new Exception ();
1537 void Error_AlreadyDeclared (Location loc, string var, string reason)
1539 Report.Error (136, loc, "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning to `{0}', " +
1540 "which is already used in a `{1}' scope", var, reason);
1543 public bool AddConstant (Expression type, string name, Expression value, Location l)
1545 if (AddVariable (type, name, l) == null)
1548 if (constants == null)
1549 constants = new Hashtable ();
1551 constants.Add (name, value);
1553 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1558 static int next_temp_id = 0;
1560 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1562 if (temporary_variables == null)
1563 temporary_variables = new ArrayList ();
1565 int id = ++next_temp_id;
1566 string name = "$s_" + id.ToString ();
1568 LocalInfo li = new LocalInfo (te, name, this, loc);
1569 li.CompilerGenerated = true;
1570 temporary_variables.Add (li);
1574 public LocalInfo GetLocalInfo (string name)
1576 for (Block b = this; b != null; b = b.Parent) {
1577 if (b.variables != null) {
1578 LocalInfo ret = b.variables [name] as LocalInfo;
1586 public Expression GetVariableType (string name)
1588 LocalInfo vi = GetLocalInfo (name);
1589 return vi == null ? null : vi.Type;
1592 public Expression GetConstantExpression (string name)
1594 for (Block b = this; b != null; b = b.Parent) {
1595 if (b.constants != null) {
1596 Expression ret = b.constants [name] as Expression;
1604 public void AddStatement (Statement s)
1607 flags |= Flags.BlockUsed;
1611 get { return (flags & Flags.BlockUsed) != 0; }
1616 flags |= Flags.BlockUsed;
1619 public bool HasRet {
1620 get { return (flags & Flags.HasRet) != 0; }
1623 public bool IsDestructor {
1624 get { return (flags & Flags.IsDestructor) != 0; }
1627 public void SetDestructor ()
1629 flags |= Flags.IsDestructor;
1632 VariableMap param_map, local_map;
1634 public VariableMap ParameterMap {
1636 if ((flags & Flags.VariablesInitialized) == 0)
1637 throw new Exception ("Variables have not been initialized yet");
1643 public VariableMap LocalMap {
1645 if ((flags & Flags.VariablesInitialized) == 0)
1646 throw new Exception ("Variables have not been initialized yet");
1653 /// Emits the variable declarations and labels.
1656 /// tc: is our typecontainer (to resolve type references)
1657 /// ig: is the code generator:
1659 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
1661 bool old_unsafe = ec.InUnsafe;
1663 // If some parent block was unsafe, we remain unsafe even if this block
1664 // isn't explicitly marked as such.
1665 ec.InUnsafe |= Unsafe;
1668 // Compute the VariableMap's.
1670 // Unfortunately, we don't know the type when adding variables with
1671 // AddVariable(), so we need to compute this info here.
1675 if (variables != null) {
1676 foreach (LocalInfo li in variables.Values)
1679 locals = new LocalInfo [variables.Count];
1680 variables.Values.CopyTo (locals, 0);
1682 locals = new LocalInfo [0];
1685 local_map = new VariableMap (Parent.LocalMap, locals);
1687 local_map = new VariableMap (locals);
1689 param_map = new VariableMap (ip);
1690 flags |= Flags.VariablesInitialized;
1692 bool old_check_state = ec.ConstantCheckState;
1693 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1696 // Process this block variables
1698 if (variables != null){
1699 foreach (DictionaryEntry de in variables){
1700 string name = (string) de.Key;
1701 LocalInfo vi = (LocalInfo) de.Value;
1703 if (vi.VariableType == null)
1706 Type variable_type = vi.VariableType;
1708 if (variable_type.IsPointer){
1710 // Am not really convinced that this test is required (Microsoft does it)
1711 // but the fact is that you would not be able to use the pointer variable
1714 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1719 if (constants == null)
1722 Expression cv = (Expression) constants [name];
1726 // Don't let 'const int Foo = Foo;' succeed.
1727 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
1728 // which in turn causes the 'must be constant' error to be triggered.
1729 constants.Remove (name);
1731 ec.CurrentBlock = this;
1732 Expression e = cv.Resolve (ec);
1736 Constant ce = e as Constant;
1738 Const.Error_ExpressionMustBeConstant (variable_type, vi.Location, name);
1742 e = ce.ToType (variable_type, vi.Location);
1746 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue) {
1747 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
1751 constants.Add (name, e);
1754 ec.ConstantCheckState = old_check_state;
1757 // Now, handle the children
1759 if (children != null){
1760 foreach (Block b in children)
1761 b.ResolveMeta (toplevel, ec, ip);
1763 ec.InUnsafe = old_unsafe;
1767 // Emits the local variable declarations for a block
1769 public void EmitMeta (EmitContext ec)
1771 ILGenerator ig = ec.ig;
1773 if (variables != null){
1774 bool have_captured_vars = ec.HaveCapturedVariables ();
1776 foreach (DictionaryEntry de in variables){
1777 LocalInfo vi = (LocalInfo) de.Value;
1779 if (have_captured_vars && ec.IsCaptured (vi))
1784 // This is needed to compile on both .NET 1.x and .NET 2.x
1785 // the later introduced `DeclareLocal (Type t, bool pinned)'
1787 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1788 else if (!vi.IsThis)
1789 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1793 if (temporary_variables != null) {
1794 AnonymousContainer am = ec.CurrentAnonymousMethod;
1795 TypeBuilder scope = null;
1796 if ((am != null) && am.IsIterator) {
1797 scope = am.Scope.ScopeTypeBuilder;
1799 throw new InternalErrorException ();
1801 foreach (LocalInfo vi in temporary_variables) {
1802 if (scope != null) {
1803 if (vi.FieldBuilder == null)
1804 vi.FieldBuilder = scope.DefineField (
1805 vi.Name, vi.VariableType, FieldAttributes.Assembly);
1807 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1811 if (children != null){
1812 foreach (Block b in children)
1817 void UsageWarning (FlowBranching.UsageVector vector)
1821 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1822 foreach (DictionaryEntry de in variables){
1823 LocalInfo vi = (LocalInfo) de.Value;
1828 name = (string) de.Key;
1830 // vi.VariableInfo can be null for 'catch' variables
1831 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
1832 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
1834 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
1840 bool unreachable_shown;
1843 private void CheckPossibleMistakenEmptyStatement (Statement s)
1847 // Some statements are wrapped by a Block. Since
1848 // others' internal could be changed, here I treat
1849 // them as possibly wrapped by Block equally.
1850 Block b = s as Block;
1851 if (b != null && b.statements.Count == 1)
1852 s = (Statement) b.statements [0];
1855 body = ((Lock) s).Statement;
1857 body = ((For) s).Statement;
1858 else if (s is Foreach)
1859 body = ((Foreach) s).Statement;
1860 else if (s is While)
1861 body = ((While) s).Statement;
1862 else if (s is Using)
1863 body = ((Using) s).Statement;
1864 else if (s is Fixed)
1865 body = ((Fixed) s).Statement;
1869 if (body == null || body is EmptyStatement)
1870 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
1873 public override bool Resolve (EmitContext ec)
1875 Block prev_block = ec.CurrentBlock;
1878 int errors = Report.Errors;
1880 ec.CurrentBlock = this;
1881 ec.StartFlowBranching (this);
1883 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1885 int statement_count = statements.Count;
1886 for (int ix = 0; ix < statement_count; ix++){
1887 Statement s = (Statement) statements [ix];
1888 // Check possible empty statement (CS0642)
1889 if (RootContext.WarningLevel >= 3 &&
1890 ix + 1 < statement_count &&
1891 statements [ix + 1] is Block)
1892 CheckPossibleMistakenEmptyStatement (s);
1895 // Warn if we detect unreachable code.
1898 if (s is EmptyStatement)
1902 ((Block) s).unreachable = true;
1904 if (!unreachable_shown) {
1905 Report.Warning (162, 2, s.loc, "Unreachable code detected");
1906 unreachable_shown = true;
1911 // Note that we're not using ResolveUnreachable() for unreachable
1912 // statements here. ResolveUnreachable() creates a temporary
1913 // flow branching and kills it afterwards. This leads to problems
1914 // if you have two unreachable statements where the first one
1915 // assigns a variable and the second one tries to access it.
1918 if (!s.Resolve (ec)) {
1920 statements [ix] = EmptyStatement.Value;
1924 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1925 statements [ix] = EmptyStatement.Value;
1927 num_statements = ix + 1;
1928 if (s is LabeledStatement)
1929 unreachable = false;
1931 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1934 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1935 ec.CurrentBranching, statement_count, num_statements);
1937 while (ec.CurrentBranching is FlowBranchingLabeled)
1938 ec.EndFlowBranching ();
1940 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1942 ec.CurrentBlock = prev_block;
1944 // If we're a non-static `struct' constructor which doesn't have an
1945 // initializer, then we must initialize all of the struct's fields.
1946 if ((flags & Flags.IsToplevel) != 0 &&
1947 !Toplevel.IsThisAssigned (ec) &&
1948 !vector.Reachability.AlwaysThrows)
1951 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1952 foreach (LabeledStatement label in labels.Values)
1953 if (!label.HasBeenReferenced)
1954 Report.Warning (164, 2, label.loc,
1955 "This label has not been referenced");
1958 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1960 if (vector.Reachability.IsUnreachable)
1961 flags |= Flags.HasRet;
1963 if (ok && (errors == Report.Errors)) {
1964 if (RootContext.WarningLevel >= 3)
1965 UsageWarning (vector);
1971 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1973 unreachable_shown = true;
1977 Report.Warning (162, 2, loc, "Unreachable code detected");
1979 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1980 bool ok = Resolve (ec);
1981 ec.KillFlowBranching ();
1986 protected override void DoEmit (EmitContext ec)
1988 for (int ix = 0; ix < num_statements; ix++){
1989 Statement s = (Statement) statements [ix];
1991 // Check whether we are the last statement in a
1994 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
1995 ec.IsLastStatement = true;
1997 ec.IsLastStatement = false;
2003 public override void Emit (EmitContext ec)
2005 Block prev_block = ec.CurrentBlock;
2007 ec.CurrentBlock = this;
2009 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2010 bool is_lexical_block = !Implicit && (Parent != null);
2012 if (emit_debug_info) {
2013 if (is_lexical_block)
2016 if (variables != null) {
2017 foreach (DictionaryEntry de in variables) {
2018 string name = (string) de.Key;
2019 LocalInfo vi = (LocalInfo) de.Value;
2021 if (vi.LocalBuilder == null)
2024 ec.DefineLocalVariable (name, vi.LocalBuilder);
2028 ec.Mark (StartLocation, true);
2029 ec.EmitScopeInitFromBlock (this);
2031 ec.Mark (EndLocation, true);
2033 if (emit_debug_info && is_lexical_block)
2036 ec.CurrentBlock = prev_block;
2040 // Returns true if we ar ea child of `b'.
2042 public bool IsChildOf (Block b)
2044 Block current = this;
2047 if (current.Parent == b)
2049 current = current.Parent;
2050 } while (current != null);
2054 public override string ToString ()
2056 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2061 // A toplevel block contains extra information, the split is done
2062 // only to separate information that would otherwise bloat the more
2063 // lightweight Block.
2065 // In particular, this was introduced when the support for Anonymous
2066 // Methods was implemented.
2068 public class ToplevelBlock : Block {
2070 // Pointer to the host of this anonymous method, or null
2071 // if we are the topmost block
2073 ToplevelBlock container;
2074 CaptureContext capture_context;
2075 FlowBranching top_level_branching;
2077 Hashtable capture_contexts;
2080 public bool HasVarargs {
2081 get { return (flags & Flags.HasVarargs) != 0; }
2082 set { flags |= Flags.HasVarargs; }
2086 // The parameters for the block.
2088 public readonly Parameters Parameters;
2090 public void RegisterCaptureContext (CaptureContext cc)
2092 if (capture_contexts == null)
2093 capture_contexts = new Hashtable ();
2094 capture_contexts [cc] = cc;
2097 public void CompleteContexts ()
2099 if (capture_contexts == null)
2102 foreach (CaptureContext cc in capture_contexts.Keys){
2107 public CaptureContext ToplevelBlockCaptureContext {
2108 get { return capture_context; }
2111 public ToplevelBlock Container {
2112 get { return container; }
2115 protected void AddChild (ToplevelBlock block)
2117 if (children == null)
2118 children = new ArrayList ();
2120 children.Add (block);
2124 // Parent is only used by anonymous blocks to link back to their
2127 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2128 this (container, (Flags) 0, parameters, start)
2132 public ToplevelBlock (Parameters parameters, Location start) :
2133 this (null, (Flags) 0, parameters, start)
2137 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2138 this (null, flags, parameters, start)
2142 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2143 base (null, flags | Flags.IsToplevel, start, Location.Null)
2145 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2146 this.container = container;
2148 if (container != null)
2149 container.AddChild (this);
2152 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2156 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2158 if (capture_context == null)
2159 capture_context = new CaptureContext (this, loc, host);
2162 public CaptureContext CaptureContext {
2163 get { return capture_context; }
2166 public FlowBranching TopLevelBranching {
2167 get { return top_level_branching; }
2171 // This is used if anonymous methods are used inside an iterator
2172 // (see 2test-22.cs for an example).
2174 // The AnonymousMethod is created while parsing - at a time when we don't
2175 // know yet that we're inside an iterator, so it's `Container' is initially
2176 // null. Later on, when resolving the iterator, we need to move the
2177 // anonymous method into that iterator.
2179 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2181 foreach (ToplevelBlock block in children) {
2182 if (block.CaptureContext == null)
2185 block.container = new_parent;
2186 block.CaptureContext.ReParent (new_parent, new_host);
2191 // Returns a `ParameterReference' for the given name, or null if there
2192 // is no such parameter
2194 public ParameterReference GetParameterReference (string name, Location loc)
2199 for (ToplevelBlock t = this; t != null; t = t.Container) {
2200 Parameters pars = t.Parameters;
2201 par = pars.GetParameterByName (name, out idx);
2203 return new ParameterReference (par, this, idx, loc);
2209 // Whether the parameter named `name' is local to this block,
2210 // or false, if the parameter belongs to an encompassing block.
2212 public bool IsLocalParameter (string name)
2214 return Parameters.GetParameterByName (name) != null;
2218 // Whether the `name' is a parameter reference
2220 public bool IsParameterReference (string name)
2222 for (ToplevelBlock t = this; t != null; t = t.Container) {
2223 if (t.IsLocalParameter (name))
2229 LocalInfo this_variable = null;
2232 // Returns the "this" instance variable of this block.
2233 // See AddThisVariable() for more information.
2235 public LocalInfo ThisVariable {
2236 get { return this_variable; }
2241 // This is used by non-static `struct' constructors which do not have an
2242 // initializer - in this case, the constructor must initialize all of the
2243 // struct's fields. To do this, we add a "this" variable and use the flow
2244 // analysis code to ensure that it's been fully initialized before control
2245 // leaves the constructor.
2247 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2249 if (this_variable == null) {
2250 this_variable = new LocalInfo (ds, this, l);
2251 this_variable.Used = true;
2252 this_variable.IsThis = true;
2254 Variables.Add ("this", this_variable);
2257 return this_variable;
2260 public bool IsThisAssigned (EmitContext ec)
2262 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2265 public bool ResolveMeta (EmitContext ec, Parameters ip)
2267 int errors = Report.Errors;
2269 if (top_level_branching != null)
2272 ResolveMeta (this, ec, ip);
2274 top_level_branching = ec.StartFlowBranching (this);
2276 return Report.Errors == errors;
2280 public class SwitchLabel {
2287 Label il_label_code;
2288 bool il_label_code_set;
2290 public static readonly object NullStringCase = new object ();
2293 // if expr == null, then it is the default case.
2295 public SwitchLabel (Expression expr, Location l)
2301 public Expression Label {
2307 public object Converted {
2313 public Label GetILLabel (EmitContext ec)
2316 il_label = ec.ig.DefineLabel ();
2317 il_label_set = true;
2322 public Label GetILLabelCode (EmitContext ec)
2324 if (!il_label_code_set){
2325 il_label_code = ec.ig.DefineLabel ();
2326 il_label_code_set = true;
2328 return il_label_code;
2332 // Resolves the expression, reduces it to a literal if possible
2333 // and then converts it to the requested type.
2335 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2337 Expression e = label.Resolve (ec);
2342 Constant c = e as Constant;
2344 Report.Error (150, loc, "A constant value is expected");
2348 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2349 converted = NullStringCase;
2353 c = c.ToType (required_type, loc);
2357 converted = c.GetValue ();
2361 public void Erorr_AlreadyOccurs ()
2364 if (converted == null)
2366 else if (converted == NullStringCase)
2369 label = converted.ToString ();
2371 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2375 public class SwitchSection {
2376 // An array of SwitchLabels.
2377 public readonly ArrayList Labels;
2378 public readonly Block Block;
2380 public SwitchSection (ArrayList labels, Block block)
2387 public class Switch : Statement {
2388 public readonly ArrayList Sections;
2389 public Expression Expr;
2392 /// Maps constants whose type type SwitchType to their SwitchLabels.
2394 public IDictionary Elements;
2397 /// The governing switch type
2399 public Type SwitchType;
2404 Label default_target;
2405 Expression new_expr;
2407 SwitchSection constant_section;
2408 SwitchSection default_section;
2411 // The types allowed to be implicitly cast from
2412 // on the governing type
2414 static Type [] allowed_types;
2416 public Switch (Expression e, ArrayList sects, Location l)
2423 public bool GotDefault {
2425 return default_section != null;
2429 public Label DefaultTarget {
2431 return default_target;
2436 // Determines the governing type for a switch. The returned
2437 // expression might be the expression from the switch, or an
2438 // expression that includes any potential conversions to the
2439 // integral types or to string.
2441 Expression SwitchGoverningType (EmitContext ec, Type t)
2443 if (t == TypeManager.byte_type ||
2444 t == TypeManager.sbyte_type ||
2445 t == TypeManager.ushort_type ||
2446 t == TypeManager.short_type ||
2447 t == TypeManager.uint32_type ||
2448 t == TypeManager.int32_type ||
2449 t == TypeManager.uint64_type ||
2450 t == TypeManager.int64_type ||
2451 t == TypeManager.char_type ||
2452 t == TypeManager.string_type ||
2453 t == TypeManager.bool_type ||
2454 t.IsSubclassOf (TypeManager.enum_type))
2457 if (allowed_types == null){
2458 allowed_types = new Type [] {
2459 TypeManager.sbyte_type,
2460 TypeManager.byte_type,
2461 TypeManager.short_type,
2462 TypeManager.ushort_type,
2463 TypeManager.int32_type,
2464 TypeManager.uint32_type,
2465 TypeManager.int64_type,
2466 TypeManager.uint64_type,
2467 TypeManager.char_type,
2468 TypeManager.string_type,
2469 TypeManager.bool_type
2474 // Try to find a *user* defined implicit conversion.
2476 // If there is no implicit conversion, or if there are multiple
2477 // conversions, we have to report an error
2479 Expression converted = null;
2480 foreach (Type tt in allowed_types){
2483 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2488 // Ignore over-worked ImplicitUserConversions that do
2489 // an implicit conversion in addition to the user conversion.
2491 if (!(e is UserCast))
2494 if (converted != null){
2495 Report.ExtraInformation (
2497 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2498 TypeManager.CSharpName (Expr.Type)));
2508 // Performs the basic sanity checks on the switch statement
2509 // (looks for duplicate keys and non-constant expressions).
2511 // It also returns a hashtable with the keys that we will later
2512 // use to compute the switch tables
2514 bool CheckSwitch (EmitContext ec)
2517 Elements = Sections.Count > 10 ?
2518 (IDictionary)new Hashtable () :
2519 (IDictionary)new ListDictionary ();
2521 foreach (SwitchSection ss in Sections){
2522 foreach (SwitchLabel sl in ss.Labels){
2523 if (sl.Label == null){
2524 if (default_section != null){
2525 sl.Erorr_AlreadyOccurs ();
2528 default_section = ss;
2532 if (!sl.ResolveAndReduce (ec, SwitchType)){
2537 object key = sl.Converted;
2539 Elements.Add (key, sl);
2541 catch (ArgumentException) {
2542 sl.Erorr_AlreadyOccurs ();
2550 void EmitObjectInteger (ILGenerator ig, object k)
2553 IntConstant.EmitInt (ig, (int) k);
2554 else if (k is Constant) {
2555 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2558 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2561 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2563 IntConstant.EmitInt (ig, (int) (long) k);
2564 ig.Emit (OpCodes.Conv_I8);
2567 LongConstant.EmitLong (ig, (long) k);
2569 else if (k is ulong)
2571 ulong ul = (ulong) k;
2574 IntConstant.EmitInt (ig, unchecked ((int) ul));
2575 ig.Emit (OpCodes.Conv_U8);
2579 LongConstant.EmitLong (ig, unchecked ((long) ul));
2583 IntConstant.EmitInt (ig, (int) ((char) k));
2584 else if (k is sbyte)
2585 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2587 IntConstant.EmitInt (ig, (int) ((byte) k));
2588 else if (k is short)
2589 IntConstant.EmitInt (ig, (int) ((short) k));
2590 else if (k is ushort)
2591 IntConstant.EmitInt (ig, (int) ((ushort) k));
2593 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2595 throw new Exception ("Unhandled case");
2598 // structure used to hold blocks of keys while calculating table switch
2599 class KeyBlock : IComparable
2601 public KeyBlock (long _nFirst)
2603 nFirst = nLast = _nFirst;
2607 public ArrayList rgKeys = null;
2608 // how many items are in the bucket
2609 public int Size = 1;
2612 get { return (int) (nLast - nFirst + 1); }
2614 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2616 return kbLast.nLast - kbFirst.nFirst + 1;
2618 public int CompareTo (object obj)
2620 KeyBlock kb = (KeyBlock) obj;
2621 int nLength = Length;
2622 int nLengthOther = kb.Length;
2623 if (nLengthOther == nLength)
2624 return (int) (kb.nFirst - nFirst);
2625 return nLength - nLengthOther;
2630 /// This method emits code for a lookup-based switch statement (non-string)
2631 /// Basically it groups the cases into blocks that are at least half full,
2632 /// and then spits out individual lookup opcodes for each block.
2633 /// It emits the longest blocks first, and short blocks are just
2634 /// handled with direct compares.
2636 /// <param name="ec"></param>
2637 /// <param name="val"></param>
2638 /// <returns></returns>
2639 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2641 int cElements = Elements.Count;
2642 object [] rgKeys = new object [cElements];
2643 Elements.Keys.CopyTo (rgKeys, 0);
2644 Array.Sort (rgKeys);
2646 // initialize the block list with one element per key
2647 ArrayList rgKeyBlocks = new ArrayList ();
2648 foreach (object key in rgKeys)
2649 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2652 // iteratively merge the blocks while they are at least half full
2653 // there's probably a really cool way to do this with a tree...
2654 while (rgKeyBlocks.Count > 1)
2656 ArrayList rgKeyBlocksNew = new ArrayList ();
2657 kbCurr = (KeyBlock) rgKeyBlocks [0];
2658 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2660 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2661 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2664 kbCurr.nLast = kb.nLast;
2665 kbCurr.Size += kb.Size;
2669 // start a new block
2670 rgKeyBlocksNew.Add (kbCurr);
2674 rgKeyBlocksNew.Add (kbCurr);
2675 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2677 rgKeyBlocks = rgKeyBlocksNew;
2680 // initialize the key lists
2681 foreach (KeyBlock kb in rgKeyBlocks)
2682 kb.rgKeys = new ArrayList ();
2684 // fill the key lists
2686 if (rgKeyBlocks.Count > 0) {
2687 kbCurr = (KeyBlock) rgKeyBlocks [0];
2688 foreach (object key in rgKeys)
2690 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2691 System.Convert.ToInt64 (key) > kbCurr.nLast;
2693 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2694 kbCurr.rgKeys.Add (key);
2698 // sort the blocks so we can tackle the largest ones first
2699 rgKeyBlocks.Sort ();
2701 // okay now we can start...
2702 ILGenerator ig = ec.ig;
2703 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2704 Label lblDefault = ig.DefineLabel ();
2706 Type typeKeys = null;
2707 if (rgKeys.Length > 0)
2708 typeKeys = rgKeys [0].GetType (); // used for conversions
2712 if (TypeManager.IsEnumType (SwitchType))
2713 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2715 compare_type = SwitchType;
2717 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2719 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2720 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2723 foreach (object key in kb.rgKeys)
2725 ig.Emit (OpCodes.Ldloc, val);
2726 EmitObjectInteger (ig, key);
2727 SwitchLabel sl = (SwitchLabel) Elements [key];
2728 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2733 // TODO: if all the keys in the block are the same and there are
2734 // no gaps/defaults then just use a range-check.
2735 if (compare_type == TypeManager.int64_type ||
2736 compare_type == TypeManager.uint64_type)
2738 // TODO: optimize constant/I4 cases
2740 // check block range (could be > 2^31)
2741 ig.Emit (OpCodes.Ldloc, val);
2742 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2743 ig.Emit (OpCodes.Blt, lblDefault);
2744 ig.Emit (OpCodes.Ldloc, val);
2745 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2746 ig.Emit (OpCodes.Bgt, lblDefault);
2749 ig.Emit (OpCodes.Ldloc, val);
2752 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2753 ig.Emit (OpCodes.Sub);
2755 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2760 ig.Emit (OpCodes.Ldloc, val);
2761 int nFirst = (int) kb.nFirst;
2764 IntConstant.EmitInt (ig, nFirst);
2765 ig.Emit (OpCodes.Sub);
2767 else if (nFirst < 0)
2769 IntConstant.EmitInt (ig, -nFirst);
2770 ig.Emit (OpCodes.Add);
2774 // first, build the list of labels for the switch
2776 int cJumps = kb.Length;
2777 Label [] rgLabels = new Label [cJumps];
2778 for (int iJump = 0; iJump < cJumps; iJump++)
2780 object key = kb.rgKeys [iKey];
2781 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2783 SwitchLabel sl = (SwitchLabel) Elements [key];
2784 rgLabels [iJump] = sl.GetILLabel (ec);
2788 rgLabels [iJump] = lblDefault;
2790 // emit the switch opcode
2791 ig.Emit (OpCodes.Switch, rgLabels);
2794 // mark the default for this block
2796 ig.MarkLabel (lblDefault);
2799 // TODO: find the default case and emit it here,
2800 // to prevent having to do the following jump.
2801 // make sure to mark other labels in the default section
2803 // the last default just goes to the end
2804 ig.Emit (OpCodes.Br, lblDefault);
2806 // now emit the code for the sections
2807 bool fFoundDefault = false;
2808 foreach (SwitchSection ss in Sections)
2810 foreach (SwitchLabel sl in ss.Labels)
2812 ig.MarkLabel (sl.GetILLabel (ec));
2813 ig.MarkLabel (sl.GetILLabelCode (ec));
2814 if (sl.Label == null)
2816 ig.MarkLabel (lblDefault);
2817 fFoundDefault = true;
2821 //ig.Emit (OpCodes.Br, lblEnd);
2824 if (!fFoundDefault) {
2825 ig.MarkLabel (lblDefault);
2827 ig.MarkLabel (lblEnd);
2830 // This simple emit switch works, but does not take advantage of the
2832 // TODO: remove non-string logic from here
2833 // TODO: binary search strings?
2835 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2837 ILGenerator ig = ec.ig;
2838 Label end_of_switch = ig.DefineLabel ();
2839 Label next_test = ig.DefineLabel ();
2840 Label null_target = ig.DefineLabel ();
2841 bool first_test = true;
2842 bool pending_goto_end = false;
2843 bool null_marked = false;
2846 ig.Emit (OpCodes.Ldloc, val);
2848 if (Elements.Contains (SwitchLabel.NullStringCase)){
2849 ig.Emit (OpCodes.Brfalse, null_target);
2851 ig.Emit (OpCodes.Brfalse, default_target);
2853 ig.Emit (OpCodes.Ldloc, val);
2854 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2855 ig.Emit (OpCodes.Stloc, val);
2857 int section_count = Sections.Count;
2858 for (int section = 0; section < section_count; section++){
2859 SwitchSection ss = (SwitchSection) Sections [section];
2861 if (ss == default_section)
2864 Label sec_begin = ig.DefineLabel ();
2866 ig.Emit (OpCodes.Nop);
2868 if (pending_goto_end)
2869 ig.Emit (OpCodes.Br, end_of_switch);
2871 int label_count = ss.Labels.Count;
2873 for (int label = 0; label < label_count; label++){
2874 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2875 ig.MarkLabel (sl.GetILLabel (ec));
2878 ig.MarkLabel (next_test);
2879 next_test = ig.DefineLabel ();
2882 // If we are the default target
2884 if (sl.Label != null){
2885 object lit = sl.Converted;
2887 if (lit == SwitchLabel.NullStringCase){
2889 if (label_count == 1)
2890 ig.Emit (OpCodes.Br, next_test);
2894 ig.Emit (OpCodes.Ldloc, val);
2895 ig.Emit (OpCodes.Ldstr, (string)lit);
2896 if (label_count == 1)
2897 ig.Emit (OpCodes.Bne_Un, next_test);
2899 if (label+1 == label_count)
2900 ig.Emit (OpCodes.Bne_Un, next_test);
2902 ig.Emit (OpCodes.Beq, sec_begin);
2907 ig.MarkLabel (null_target);
2910 ig.MarkLabel (sec_begin);
2911 foreach (SwitchLabel sl in ss.Labels)
2912 ig.MarkLabel (sl.GetILLabelCode (ec));
2915 pending_goto_end = !ss.Block.HasRet;
2918 ig.MarkLabel (next_test);
2919 ig.MarkLabel (default_target);
2921 ig.MarkLabel (null_target);
2922 if (default_section != null)
2923 default_section.Block.Emit (ec);
2924 ig.MarkLabel (end_of_switch);
2927 SwitchSection FindSection (SwitchLabel label)
2929 foreach (SwitchSection ss in Sections){
2930 foreach (SwitchLabel sl in ss.Labels){
2939 public override bool Resolve (EmitContext ec)
2941 Expr = Expr.Resolve (ec);
2945 new_expr = SwitchGoverningType (ec, Expr.Type);
2946 if (new_expr == null){
2947 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2952 SwitchType = new_expr.Type;
2954 if (!CheckSwitch (ec))
2957 Switch old_switch = ec.Switch;
2959 ec.Switch.SwitchType = SwitchType;
2961 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2962 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2964 is_constant = new_expr is Constant;
2966 object key = ((Constant) new_expr).GetValue ();
2967 SwitchLabel label = (SwitchLabel) Elements [key];
2969 constant_section = FindSection (label);
2970 if (constant_section == null)
2971 constant_section = default_section;
2975 foreach (SwitchSection ss in Sections){
2977 ec.CurrentBranching.CreateSibling (
2978 null, FlowBranching.SiblingType.SwitchSection);
2982 if (is_constant && (ss != constant_section)) {
2983 // If we're a constant switch, we're only emitting
2984 // one single section - mark all the others as
2986 ec.CurrentBranching.CurrentUsageVector.Goto ();
2987 if (!ss.Block.ResolveUnreachable (ec, true))
2990 if (!ss.Block.Resolve (ec))
2995 if (default_section == null)
2996 ec.CurrentBranching.CreateSibling (
2997 null, FlowBranching.SiblingType.SwitchSection);
2999 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3000 ec.Switch = old_switch;
3002 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3008 protected override void DoEmit (EmitContext ec)
3010 ILGenerator ig = ec.ig;
3012 // Store variable for comparission purposes
3015 value = ig.DeclareLocal (SwitchType);
3017 ig.Emit (OpCodes.Stloc, value);
3021 default_target = ig.DefineLabel ();
3024 // Setup the codegen context
3026 Label old_end = ec.LoopEnd;
3027 Switch old_switch = ec.Switch;
3029 ec.LoopEnd = ig.DefineLabel ();
3034 if (constant_section != null)
3035 constant_section.Block.Emit (ec);
3036 } else if (SwitchType == TypeManager.string_type)
3037 SimpleSwitchEmit (ec, value);
3039 TableSwitchEmit (ec, value);
3041 // Restore context state.
3042 ig.MarkLabel (ec.LoopEnd);
3045 // Restore the previous context
3047 ec.LoopEnd = old_end;
3048 ec.Switch = old_switch;
3052 public abstract class ExceptionStatement : Statement
3054 public abstract void EmitFinally (EmitContext ec);
3056 protected bool emit_finally = true;
3057 ArrayList parent_vectors;
3059 protected void DoEmitFinally (EmitContext ec)
3062 ec.ig.BeginFinallyBlock ();
3063 else if (ec.InIterator)
3064 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3068 protected void ResolveFinally (FlowBranchingException branching)
3070 emit_finally = branching.EmitFinally;
3072 branching.Parent.StealFinallyClauses (ref parent_vectors);
3076 public class Lock : ExceptionStatement {
3078 public Statement Statement;
3079 TemporaryVariable temp;
3081 public Lock (Expression expr, Statement stmt, Location l)
3088 public override bool Resolve (EmitContext ec)
3090 expr = expr.Resolve (ec);
3094 if (expr.Type.IsValueType){
3095 Report.Error (185, loc,
3096 "`{0}' is not a reference type as required by the lock statement",
3097 TypeManager.CSharpName (expr.Type));
3101 FlowBranchingException branching = ec.StartFlowBranching (this);
3102 bool ok = Statement.Resolve (ec);
3104 ec.KillFlowBranching ();
3108 ResolveFinally (branching);
3110 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3111 if (!reachability.AlwaysReturns) {
3112 // Unfortunately, System.Reflection.Emit automatically emits
3113 // a leave to the end of the finally block.
3114 // This is a problem if `returns' is true since we may jump
3115 // to a point after the end of the method.
3116 // As a workaround, emit an explicit ret here.
3117 ec.NeedReturnLabel ();
3120 temp = new TemporaryVariable (expr.Type, loc);
3126 protected override void DoEmit (EmitContext ec)
3128 ILGenerator ig = ec.ig;
3130 temp.Store (ec, expr);
3132 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3136 ig.BeginExceptionBlock ();
3137 Statement.Emit (ec);
3142 ig.EndExceptionBlock ();
3145 public override void EmitFinally (EmitContext ec)
3148 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3152 public class Unchecked : Statement {
3153 public readonly Block Block;
3155 public Unchecked (Block b)
3161 public override bool Resolve (EmitContext ec)
3163 bool previous_state = ec.CheckState;
3164 bool previous_state_const = ec.ConstantCheckState;
3166 ec.CheckState = false;
3167 ec.ConstantCheckState = false;
3168 bool ret = Block.Resolve (ec);
3169 ec.CheckState = previous_state;
3170 ec.ConstantCheckState = previous_state_const;
3175 protected override void DoEmit (EmitContext ec)
3177 bool previous_state = ec.CheckState;
3178 bool previous_state_const = ec.ConstantCheckState;
3180 ec.CheckState = false;
3181 ec.ConstantCheckState = false;
3183 ec.CheckState = previous_state;
3184 ec.ConstantCheckState = previous_state_const;
3188 public class Checked : Statement {
3189 public readonly Block Block;
3191 public Checked (Block b)
3194 b.Unchecked = false;
3197 public override bool Resolve (EmitContext ec)
3199 bool previous_state = ec.CheckState;
3200 bool previous_state_const = ec.ConstantCheckState;
3202 ec.CheckState = true;
3203 ec.ConstantCheckState = true;
3204 bool ret = Block.Resolve (ec);
3205 ec.CheckState = previous_state;
3206 ec.ConstantCheckState = previous_state_const;
3211 protected override void DoEmit (EmitContext ec)
3213 bool previous_state = ec.CheckState;
3214 bool previous_state_const = ec.ConstantCheckState;
3216 ec.CheckState = true;
3217 ec.ConstantCheckState = true;
3219 ec.CheckState = previous_state;
3220 ec.ConstantCheckState = previous_state_const;
3224 public class Unsafe : Statement {
3225 public readonly Block Block;
3227 public Unsafe (Block b)
3230 Block.Unsafe = true;
3233 public override bool Resolve (EmitContext ec)
3235 bool previous_state = ec.InUnsafe;
3239 val = Block.Resolve (ec);
3240 ec.InUnsafe = previous_state;
3245 protected override void DoEmit (EmitContext ec)
3247 bool previous_state = ec.InUnsafe;
3251 ec.InUnsafe = previous_state;
3258 public class Fixed : Statement {
3260 ArrayList declarators;
3261 Statement statement;
3266 abstract class Emitter
3268 protected LocalInfo vi;
3269 protected Expression converted;
3271 protected Emitter (Expression expr, LocalInfo li)
3277 public abstract void Emit (EmitContext ec);
3278 public abstract void EmitExit (ILGenerator ig);
3281 class ExpressionEmitter : Emitter {
3282 public ExpressionEmitter (Expression converted, LocalInfo li) :
3283 base (converted, li)
3287 public override void Emit (EmitContext ec) {
3289 // Store pointer in pinned location
3291 converted.Emit (ec);
3292 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3295 public override void EmitExit (ILGenerator ig)
3297 ig.Emit (OpCodes.Ldc_I4_0);
3298 ig.Emit (OpCodes.Conv_U);
3299 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3303 class StringEmitter : Emitter {
3304 LocalBuilder pinned_string;
3307 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3313 public override void Emit (EmitContext ec)
3315 ILGenerator ig = ec.ig;
3316 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3318 converted.Emit (ec);
3319 ig.Emit (OpCodes.Stloc, pinned_string);
3321 Expression sptr = new StringPtr (pinned_string, loc);
3322 converted = Convert.ImplicitConversionRequired (
3323 ec, sptr, vi.VariableType, loc);
3325 if (converted == null)
3328 converted.Emit (ec);
3329 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3332 public override void EmitExit(ILGenerator ig)
3334 ig.Emit (OpCodes.Ldnull);
3335 ig.Emit (OpCodes.Stloc, pinned_string);
3339 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3342 declarators = decls;
3347 public Statement Statement {
3348 get { return statement; }
3351 public override bool Resolve (EmitContext ec)
3354 Expression.UnsafeError (loc);
3358 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3362 expr_type = texpr.Type;
3364 data = new Emitter [declarators.Count];
3366 if (!expr_type.IsPointer){
3367 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3372 foreach (Pair p in declarators){
3373 LocalInfo vi = (LocalInfo) p.First;
3374 Expression e = (Expression) p.Second;
3376 vi.VariableInfo.SetAssigned (ec);
3377 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3380 // The rules for the possible declarators are pretty wise,
3381 // but the production on the grammar is more concise.
3383 // So we have to enforce these rules here.
3385 // We do not resolve before doing the case 1 test,
3386 // because the grammar is explicit in that the token &
3387 // is present, so we need to test for this particular case.
3391 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3396 // Case 1: & object.
3398 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3399 Expression child = ((Unary) e).Expr;
3401 if (child is ParameterReference || child is LocalVariableReference){
3404 "No need to use fixed statement for parameters or " +
3405 "local variable declarations (address is already " +
3410 ec.InFixedInitializer = true;
3412 ec.InFixedInitializer = false;
3416 child = ((Unary) e).Expr;
3418 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3421 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
3422 e.Error_ValueCannotBeConverted (e.Location, expr_type, false);
3426 data [i] = new ExpressionEmitter (e, vi);
3432 ec.InFixedInitializer = true;
3434 ec.InFixedInitializer = false;
3441 if (e.Type.IsArray){
3442 Type array_type = TypeManager.GetElementType (e.Type);
3445 // Provided that array_type is unmanaged,
3447 if (!TypeManager.VerifyUnManaged (array_type, loc))
3451 // and T* is implicitly convertible to the
3452 // pointer type given in the fixed statement.
3454 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3456 Expression converted = Convert.ImplicitConversionRequired (
3457 ec, array_ptr, vi.VariableType, loc);
3458 if (converted == null)
3461 data [i] = new ExpressionEmitter (converted, vi);
3470 if (e.Type == TypeManager.string_type){
3471 data [i] = new StringEmitter (e, vi, loc);
3476 // Case 4: fixed buffer
3477 FieldExpr fe = e as FieldExpr;
3479 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3481 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3483 Expression converted = Convert.ImplicitConversionRequired (
3484 ec, fixed_buffer_ptr, vi.VariableType, loc);
3485 if (converted == null)
3488 data [i] = new ExpressionEmitter (converted, vi);
3496 // For other cases, flag a `this is already fixed expression'
3498 if (e is LocalVariableReference || e is ParameterReference ||
3499 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3501 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3505 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3509 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3511 if (!statement.Resolve (ec)) {
3512 ec.KillFlowBranching ();
3516 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3517 has_ret = reachability.IsUnreachable;
3522 protected override void DoEmit (EmitContext ec)
3524 for (int i = 0; i < data.Length; i++) {
3528 statement.Emit (ec);
3533 ILGenerator ig = ec.ig;
3536 // Clear the pinned variable
3538 for (int i = 0; i < data.Length; i++) {
3539 data [i].EmitExit (ig);
3544 public class Catch : Statement {
3545 public readonly string Name;
3546 public readonly Block Block;
3547 public readonly Block VarBlock;
3549 Expression type_expr;
3552 public Catch (Expression type, string name, Block block, Block var_block, Location l)
3557 VarBlock = var_block;
3561 public Type CatchType {
3567 public bool IsGeneral {
3569 return type_expr == null;
3573 protected override void DoEmit(EmitContext ec)
3577 public override bool Resolve (EmitContext ec)
3579 bool was_catch = ec.InCatch;
3582 if (type_expr != null) {
3583 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3589 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3590 Error (155, "The type caught or thrown must be derived from System.Exception");
3596 if (!Block.Resolve (ec))
3599 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
3600 // emit the "unused variable" warnings.
3601 if (VarBlock != null)
3602 return VarBlock.Resolve (ec);
3607 ec.InCatch = was_catch;
3612 public class Try : ExceptionStatement {
3613 public readonly Block Fini, Block;
3614 public readonly ArrayList Specific;
3615 public readonly Catch General;
3617 bool need_exc_block;
3620 // specific, general and fini might all be null.
3622 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3624 if (specific == null && general == null){
3625 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3629 this.Specific = specific;
3630 this.General = general;
3635 public override bool Resolve (EmitContext ec)
3639 FlowBranchingException branching = ec.StartFlowBranching (this);
3641 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3643 if (!Block.Resolve (ec))
3646 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3648 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3650 Type[] prevCatches = new Type [Specific.Count];
3652 foreach (Catch c in Specific){
3653 ec.CurrentBranching.CreateSibling (
3654 c.Block, FlowBranching.SiblingType.Catch);
3656 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3658 if (c.Name != null) {
3659 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3661 throw new Exception ();
3663 vi.VariableInfo = null;
3666 if (!c.Resolve (ec))
3669 Type resolvedType = c.CatchType;
3670 for (int ii = 0; ii < last_index; ++ii) {
3671 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3672 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3677 prevCatches [last_index++] = resolvedType;
3678 need_exc_block = true;
3681 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3683 if (General != null){
3684 if (CodeGen.Assembly.WrapNonExceptionThrows) {
3685 foreach (Catch c in Specific){
3686 if (c.CatchType == TypeManager.exception_type) {
3687 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'");
3692 ec.CurrentBranching.CreateSibling (
3693 General.Block, FlowBranching.SiblingType.Catch);
3695 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3697 if (!General.Resolve (ec))
3700 need_exc_block = true;
3703 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3707 ec.CurrentBranching.CreateSibling (
3708 Fini, FlowBranching.SiblingType.Finally);
3710 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3711 bool was_finally = ec.InFinally;
3712 ec.InFinally = true;
3713 if (!Fini.Resolve (ec))
3715 ec.InFinally = was_finally;
3718 need_exc_block = true;
3721 if (ec.InIterator) {
3722 ResolveFinally (branching);
3723 need_exc_block |= emit_finally;
3725 emit_finally = Fini != null;
3727 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3729 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3731 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3733 if (!reachability.AlwaysReturns) {
3734 // Unfortunately, System.Reflection.Emit automatically emits
3735 // a leave to the end of the finally block. This is a problem
3736 // if `returns' is true since we may jump to a point after the
3737 // end of the method.
3738 // As a workaround, emit an explicit ret here.
3739 ec.NeedReturnLabel ();
3745 protected override void DoEmit (EmitContext ec)
3747 ILGenerator ig = ec.ig;
3750 ig.BeginExceptionBlock ();
3753 foreach (Catch c in Specific){
3756 ig.BeginCatchBlock (c.CatchType);
3758 if (c.VarBlock != null)
3759 ec.EmitScopeInitFromBlock (c.VarBlock);
3760 if (c.Name != null){
3761 vi = c.Block.GetLocalInfo (c.Name);
3763 throw new Exception ("Variable does not exist in this block");
3766 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
3767 ig.Emit (OpCodes.Stloc, e);
3769 ec.EmitCapturedVariableInstance (vi);
3770 ig.Emit (OpCodes.Ldloc, e);
3771 ig.Emit (OpCodes.Stfld, vi.FieldBuilder);
3773 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3775 ig.Emit (OpCodes.Pop);
3780 if (General != null){
3781 ig.BeginCatchBlock (TypeManager.object_type);
3782 ig.Emit (OpCodes.Pop);
3783 General.Block.Emit (ec);
3788 ig.EndExceptionBlock ();
3791 public override void EmitFinally (EmitContext ec)
3797 public bool HasCatch
3800 return General != null || Specific.Count > 0;
3805 public class Using : ExceptionStatement {
3806 object expression_or_block;
3807 public Statement Statement;
3811 Expression [] resolved_vars;
3812 Expression [] converted_vars;
3813 ExpressionStatement [] assign;
3814 LocalBuilder local_copy;
3816 public Using (object expression_or_block, Statement stmt, Location l)
3818 this.expression_or_block = expression_or_block;
3824 // Resolves for the case of using using a local variable declaration.
3826 bool ResolveLocalVariableDecls (EmitContext ec)
3830 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3834 expr_type = texpr.Type;
3837 // The type must be an IDisposable or an implicit conversion
3840 converted_vars = new Expression [var_list.Count];
3841 resolved_vars = new Expression [var_list.Count];
3842 assign = new ExpressionStatement [var_list.Count];
3844 bool need_conv = !TypeManager.ImplementsInterface (
3845 expr_type, TypeManager.idisposable_type);
3847 foreach (DictionaryEntry e in var_list){
3848 Expression var = (Expression) e.Key;
3850 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3854 resolved_vars [i] = var;
3861 converted_vars [i] = Convert.ImplicitConversion (
3862 ec, var, TypeManager.idisposable_type, loc);
3864 if (converted_vars [i] == null) {
3865 Error_IsNotConvertibleToIDisposable ();
3873 foreach (DictionaryEntry e in var_list){
3874 Expression var = resolved_vars [i];
3875 Expression new_expr = (Expression) e.Value;
3878 a = new Assign (var, new_expr, loc);
3884 converted_vars [i] = var;
3885 assign [i] = (ExpressionStatement) a;
3892 void Error_IsNotConvertibleToIDisposable ()
3894 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
3895 TypeManager.CSharpName (expr_type));
3898 bool ResolveExpression (EmitContext ec)
3900 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3901 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3902 Error_IsNotConvertibleToIDisposable ();
3911 // Emits the code for the case of using using a local variable declaration.
3913 void EmitLocalVariableDecls (EmitContext ec)
3915 ILGenerator ig = ec.ig;
3918 for (i = 0; i < assign.Length; i++) {
3919 assign [i].EmitStatement (ec);
3922 ig.BeginExceptionBlock ();
3924 Statement.Emit (ec);
3925 var_list.Reverse ();
3930 void EmitLocalVariableDeclFinally (EmitContext ec)
3932 ILGenerator ig = ec.ig;
3934 int i = assign.Length;
3935 for (int ii = 0; ii < var_list.Count; ++ii){
3936 Expression var = resolved_vars [--i];
3937 Label skip = ig.DefineLabel ();
3939 if (!var.Type.IsValueType) {
3941 ig.Emit (OpCodes.Brfalse, skip);
3942 converted_vars [i].Emit (ec);
3943 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3945 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3947 if (!(ml is MethodGroupExpr)) {
3949 ig.Emit (OpCodes.Box, var.Type);
3950 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3952 MethodInfo mi = null;
3954 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3955 if (TypeManager.GetParameterData (mk).Count == 0) {
3962 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3966 IMemoryLocation mloc = (IMemoryLocation) var;
3968 mloc.AddressOf (ec, AddressOp.Load);
3969 ig.Emit (OpCodes.Call, mi);
3973 ig.MarkLabel (skip);
3976 ig.EndExceptionBlock ();
3978 ig.BeginFinallyBlock ();
3983 void EmitExpression (EmitContext ec)
3986 // Make a copy of the expression and operate on that.
3988 ILGenerator ig = ec.ig;
3989 local_copy = ig.DeclareLocal (expr_type);
3992 ig.Emit (OpCodes.Stloc, local_copy);
3995 ig.BeginExceptionBlock ();
3997 Statement.Emit (ec);
4001 ig.EndExceptionBlock ();
4004 void EmitExpressionFinally (EmitContext ec)
4006 ILGenerator ig = ec.ig;
4007 if (!local_copy.LocalType.IsValueType) {
4008 Label skip = ig.DefineLabel ();
4009 ig.Emit (OpCodes.Ldloc, local_copy);
4010 ig.Emit (OpCodes.Brfalse, skip);
4011 ig.Emit (OpCodes.Ldloc, local_copy);
4012 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4013 ig.MarkLabel (skip);
4015 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4017 if (!(ml is MethodGroupExpr)) {
4018 ig.Emit (OpCodes.Ldloc, local_copy);
4019 ig.Emit (OpCodes.Box, local_copy.LocalType);
4020 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4022 MethodInfo mi = null;
4024 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4025 if (TypeManager.GetParameterData (mk).Count == 0) {
4032 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4036 ig.Emit (OpCodes.Ldloca, local_copy);
4037 ig.Emit (OpCodes.Call, mi);
4042 public override bool Resolve (EmitContext ec)
4044 if (expression_or_block is DictionaryEntry){
4045 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4046 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4048 if (!ResolveLocalVariableDecls (ec))
4051 } else if (expression_or_block is Expression){
4052 expr = (Expression) expression_or_block;
4054 expr = expr.Resolve (ec);
4058 expr_type = expr.Type;
4060 if (!ResolveExpression (ec))
4064 FlowBranchingException branching = ec.StartFlowBranching (this);
4066 bool ok = Statement.Resolve (ec);
4069 ec.KillFlowBranching ();
4073 ResolveFinally (branching);
4074 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4076 if (!reachability.AlwaysReturns) {
4077 // Unfortunately, System.Reflection.Emit automatically emits a leave
4078 // to the end of the finally block. This is a problem if `returns'
4079 // is true since we may jump to a point after the end of the method.
4080 // As a workaround, emit an explicit ret here.
4081 ec.NeedReturnLabel ();
4087 protected override void DoEmit (EmitContext ec)
4089 if (expression_or_block is DictionaryEntry)
4090 EmitLocalVariableDecls (ec);
4091 else if (expression_or_block is Expression)
4092 EmitExpression (ec);
4095 public override void EmitFinally (EmitContext ec)
4097 if (expression_or_block is DictionaryEntry)
4098 EmitLocalVariableDeclFinally (ec);
4099 else if (expression_or_block is Expression)
4100 EmitExpressionFinally (ec);
4105 /// Implementation of the foreach C# statement
4107 public class Foreach : Statement {
4109 Expression variable;
4111 Statement statement;
4113 CollectionForeach collection;
4115 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4116 Statement stmt, Location l)
4119 this.variable = var;
4125 public Statement Statement {
4126 get { return statement; }
4129 public override bool Resolve (EmitContext ec)
4131 expr = expr.Resolve (ec);
4135 Constant c = expr as Constant;
4136 if (c != null && c.GetValue () == null) {
4137 Report.Error (186, loc, "Use of null is not valid in this context");
4141 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4145 Type var_type = texpr.Type;
4147 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethod) {
4148 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4149 expr.ExprClassName);
4154 // We need an instance variable. Not sure this is the best
4155 // way of doing this.
4157 // FIXME: When we implement propertyaccess, will those turn
4158 // out to return values in ExprClass? I think they should.
4160 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4161 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4162 collection.Error_Enumerator ();
4166 if (expr.Type.IsArray) {
4167 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4168 return array.Resolve (ec);
4170 collection = new CollectionForeach (
4171 var_type, variable, expr, statement, loc);
4172 return collection.Resolve (ec);
4176 protected override void DoEmit (EmitContext ec)
4178 ILGenerator ig = ec.ig;
4180 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4181 ec.LoopBegin = ig.DefineLabel ();
4182 ec.LoopEnd = ig.DefineLabel ();
4184 if (collection != null)
4185 collection.Emit (ec);
4189 ec.LoopBegin = old_begin;
4190 ec.LoopEnd = old_end;
4193 protected class ArrayCounter : TemporaryVariable
4195 public ArrayCounter (Location loc)
4196 : base (TypeManager.int32_type, loc)
4199 public void Initialize (EmitContext ec)
4202 ec.ig.Emit (OpCodes.Ldc_I4_0);
4206 public void Increment (EmitContext ec)
4210 ec.ig.Emit (OpCodes.Ldc_I4_1);
4211 ec.ig.Emit (OpCodes.Add);
4216 protected class ArrayForeach : Statement
4218 Expression variable, expr, conv;
4219 Statement statement;
4222 TemporaryVariable[] lengths;
4223 ArrayCounter[] counter;
4226 TemporaryVariable copy;
4229 public ArrayForeach (Type var_type, Expression var,
4230 Expression expr, Statement stmt, Location l)
4232 this.var_type = var_type;
4233 this.variable = var;
4239 public override bool Resolve (EmitContext ec)
4241 array_type = expr.Type;
4242 rank = array_type.GetArrayRank ();
4244 copy = new TemporaryVariable (array_type, loc);
4247 counter = new ArrayCounter [rank];
4248 lengths = new TemporaryVariable [rank];
4250 ArrayList list = new ArrayList ();
4251 for (int i = 0; i < rank; i++) {
4252 counter [i] = new ArrayCounter (loc);
4253 counter [i].Resolve (ec);
4255 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4256 lengths [i].Resolve (ec);
4258 list.Add (counter [i]);
4261 access = new ElementAccess (copy, list).Resolve (ec);
4265 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4271 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4272 ec.CurrentBranching.CreateSibling ();
4274 variable = variable.ResolveLValue (ec, conv, loc);
4275 if (variable == null)
4278 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4279 if (!statement.Resolve (ec))
4281 ec.EndFlowBranching ();
4283 // There's no direct control flow from the end of the embedded statement to the end of the loop
4284 ec.CurrentBranching.CurrentUsageVector.Goto ();
4286 ec.EndFlowBranching ();
4291 protected override void DoEmit (EmitContext ec)
4293 ILGenerator ig = ec.ig;
4295 copy.Store (ec, expr);
4297 Label[] test = new Label [rank];
4298 Label[] loop = new Label [rank];
4300 for (int i = 0; i < rank; i++) {
4301 test [i] = ig.DefineLabel ();
4302 loop [i] = ig.DefineLabel ();
4304 lengths [i].EmitThis (ec);
4305 ((ArrayAccess) access).EmitGetLength (ec, i);
4306 lengths [i].EmitStore (ig);
4309 for (int i = 0; i < rank; i++) {
4310 counter [i].Initialize (ec);
4312 ig.Emit (OpCodes.Br, test [i]);
4313 ig.MarkLabel (loop [i]);
4316 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4318 statement.Emit (ec);
4320 ig.MarkLabel (ec.LoopBegin);
4322 for (int i = rank - 1; i >= 0; i--){
4323 counter [i].Increment (ec);
4325 ig.MarkLabel (test [i]);
4326 counter [i].Emit (ec);
4327 lengths [i].Emit (ec);
4328 ig.Emit (OpCodes.Blt, loop [i]);
4331 ig.MarkLabel (ec.LoopEnd);
4335 protected class CollectionForeach : ExceptionStatement
4337 Expression variable, expr;
4338 Statement statement;
4340 TemporaryVariable enumerator;
4344 MethodGroupExpr get_enumerator;
4345 PropertyExpr get_current;
4346 MethodInfo move_next;
4347 Type var_type, enumerator_type;
4349 bool enumerator_found;
4351 public CollectionForeach (Type var_type, Expression var,
4352 Expression expr, Statement stmt, Location l)
4354 this.var_type = var_type;
4355 this.variable = var;
4361 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4363 Type return_type = mi.ReturnType;
4365 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4367 // Apply the same optimization as MS: skip the GetEnumerator
4368 // returning an IEnumerator, and use the one returning a
4369 // CharEnumerator instead. This allows us to avoid the
4370 // try-finally block and the boxing.
4375 // Ok, we can access it, now make sure that we can do something
4376 // with this `GetEnumerator'
4379 if (return_type == TypeManager.ienumerator_type ||
4380 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4381 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4383 // If it is not an interface, lets try to find the methods ourselves.
4384 // For example, if we have:
4385 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4386 // We can avoid the iface call. This is a runtime perf boost.
4387 // even bigger if we have a ValueType, because we avoid the cost
4390 // We have to make sure that both methods exist for us to take
4391 // this path. If one of the methods does not exist, we will just
4392 // use the interface. Sadly, this complex if statement is the only
4393 // way I could do this without a goto
4396 if (return_type.IsInterface ||
4397 !FetchMoveNext (return_type) ||
4398 !FetchGetCurrent (ec, return_type)) {
4399 move_next = TypeManager.bool_movenext_void;
4400 get_current = new PropertyExpr (
4401 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4406 // Ok, so they dont return an IEnumerable, we will have to
4407 // find if they support the GetEnumerator pattern.
4410 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
4411 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",
4412 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
4417 enumerator_type = return_type;
4418 is_disposable = !enumerator_type.IsSealed ||
4419 TypeManager.ImplementsInterface (
4420 enumerator_type, TypeManager.idisposable_type);
4426 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4428 bool FetchMoveNext (Type t)
4430 MemberList move_next_list;
4432 move_next_list = TypeContainer.FindMembers (
4433 t, MemberTypes.Method,
4434 BindingFlags.Public | BindingFlags.Instance,
4435 Type.FilterName, "MoveNext");
4436 if (move_next_list.Count == 0)
4439 foreach (MemberInfo m in move_next_list){
4440 MethodInfo mi = (MethodInfo) m;
4442 if ((TypeManager.GetParameterData (mi).Count == 0) &&
4443 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4453 // Retrieves a `public T get_Current ()' method from the Type `t'
4455 bool FetchGetCurrent (EmitContext ec, Type t)
4457 PropertyExpr pe = Expression.MemberLookup (
4458 ec.ContainerType, t, "Current", MemberTypes.Property,
4459 Expression.AllBindingFlags, loc) as PropertyExpr;
4468 // Retrieves a `public void Dispose ()' method from the Type `t'
4470 static MethodInfo FetchMethodDispose (Type t)
4472 MemberList dispose_list;
4474 dispose_list = TypeContainer.FindMembers (
4475 t, MemberTypes.Method,
4476 BindingFlags.Public | BindingFlags.Instance,
4477 Type.FilterName, "Dispose");
4478 if (dispose_list.Count == 0)
4481 foreach (MemberInfo m in dispose_list){
4482 MethodInfo mi = (MethodInfo) m;
4484 if (TypeManager.GetParameterData (mi).Count == 0){
4485 if (mi.ReturnType == TypeManager.void_type)
4492 public void Error_Enumerator ()
4494 if (enumerator_found) {
4498 Report.Error (1579, loc,
4499 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4500 TypeManager.CSharpName (expr.Type));
4503 bool TryType (EmitContext ec, Type t)
4505 MethodGroupExpr mg = Expression.MemberLookup (
4506 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
4507 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4511 foreach (MethodBase mb in mg.Methods) {
4512 if (TypeManager.GetParameterData (mb).Count != 0)
4515 // Check whether GetEnumerator is public
4516 if ((mb.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4519 if (TypeManager.IsOverride (mb))
4522 enumerator_found = true;
4524 if (!GetEnumeratorFilter (ec, (MethodInfo) mb))
4527 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) mb };
4528 get_enumerator = new MethodGroupExpr (mi, loc);
4530 if (t != expr.Type) {
4531 expr = Convert.ExplicitConversion (
4534 throw new InternalErrorException ();
4537 get_enumerator.InstanceExpression = expr;
4538 get_enumerator.IsBase = t != expr.Type;
4546 bool ProbeCollectionType (EmitContext ec, Type t)
4548 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4549 if (TryType (ec, tt))
4555 // Now try to find the method in the interfaces
4558 Type [] ifaces = t.GetInterfaces ();
4560 foreach (Type i in ifaces){
4561 if (TryType (ec, i))
4566 // Since TypeBuilder.GetInterfaces only returns the interface
4567 // types for this type, we have to keep looping, but once
4568 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4569 // done, because it returns all the types
4571 if ((t is TypeBuilder))
4580 public override bool Resolve (EmitContext ec)
4582 enumerator_type = TypeManager.ienumerator_type;
4583 is_disposable = true;
4585 if (!ProbeCollectionType (ec, expr.Type)) {
4586 Error_Enumerator ();
4590 enumerator = new TemporaryVariable (enumerator_type, loc);
4591 enumerator.Resolve (ec);
4593 init = new Invocation (get_enumerator, new ArrayList ());
4594 init = init.Resolve (ec);
4598 Expression move_next_expr;
4600 MemberInfo[] mi = new MemberInfo[] { move_next };
4601 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4602 mg.InstanceExpression = enumerator;
4604 move_next_expr = new Invocation (mg, new ArrayList ());
4607 get_current.InstanceExpression = enumerator;
4609 Statement block = new CollectionForeachStatement (
4610 var_type, variable, get_current, statement, loc);
4612 loop = new While (move_next_expr, block, loc);
4616 FlowBranchingException branching = null;
4618 branching = ec.StartFlowBranching (this);
4620 if (!loop.Resolve (ec))
4623 if (is_disposable) {
4624 ResolveFinally (branching);
4625 ec.EndFlowBranching ();
4627 emit_finally = true;
4632 protected override void DoEmit (EmitContext ec)
4634 ILGenerator ig = ec.ig;
4636 enumerator.Store (ec, init);
4639 // Protect the code in a try/finalize block, so that
4640 // if the beast implement IDisposable, we get rid of it
4642 if (is_disposable && emit_finally)
4643 ig.BeginExceptionBlock ();
4648 // Now the finally block
4650 if (is_disposable) {
4653 ig.EndExceptionBlock ();
4658 public override void EmitFinally (EmitContext ec)
4660 ILGenerator ig = ec.ig;
4662 if (enumerator_type.IsValueType) {
4663 MethodInfo mi = FetchMethodDispose (enumerator_type);
4665 enumerator.EmitLoadAddress (ec);
4666 ig.Emit (OpCodes.Call, mi);
4668 enumerator.Emit (ec);
4669 ig.Emit (OpCodes.Box, enumerator_type);
4670 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4673 Label call_dispose = ig.DefineLabel ();
4675 enumerator.Emit (ec);
4676 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4677 ig.Emit (OpCodes.Dup);
4678 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4679 ig.Emit (OpCodes.Pop);
4681 Label end_finally = ig.DefineLabel ();
4682 ig.Emit (OpCodes.Br, end_finally);
4684 ig.MarkLabel (call_dispose);
4685 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4686 ig.MarkLabel (end_finally);
4691 protected class CollectionForeachStatement : Statement
4694 Expression variable, current, conv;
4695 Statement statement;
4698 public CollectionForeachStatement (Type type, Expression variable,
4699 Expression current, Statement statement,
4703 this.variable = variable;
4704 this.current = current;
4705 this.statement = statement;
4709 public override bool Resolve (EmitContext ec)
4711 current = current.Resolve (ec);
4712 if (current == null)
4715 conv = Convert.ExplicitConversion (ec, current, type, loc);
4719 assign = new Assign (variable, conv, loc);
4720 if (assign.Resolve (ec) == null)
4723 if (!statement.Resolve (ec))
4729 protected override void DoEmit (EmitContext ec)
4731 assign.EmitStatement (ec);
4732 statement.Emit (ec);