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 !TypeManager.IsSubclassOf (t, 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);
1886 // This flag is used to notate nested statements as unreachable from the beginning of this block.
1887 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
1888 // from the beginning of the function. The outer Resolve() that detected the unreachability is
1889 // responsible for handling the situation.
1891 int statement_count = statements.Count;
1892 for (int ix = 0; ix < statement_count; ix++){
1893 Statement s = (Statement) statements [ix];
1894 // Check possible empty statement (CS0642)
1895 if (RootContext.WarningLevel >= 3 &&
1896 ix + 1 < statement_count &&
1897 statements [ix + 1] is Block)
1898 CheckPossibleMistakenEmptyStatement (s);
1901 if (s is EmptyStatement)
1905 ((Block) s).unreachable = true;
1907 if (!unreachable_shown) {
1908 Report.Warning (162, 2, s.loc, "Unreachable code detected");
1909 unreachable_shown = true;
1913 if (!s.Resolve (ec)) {
1915 statements [ix] = EmptyStatement.Value;
1919 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1920 statements [ix] = EmptyStatement.Value;
1922 num_statements = ix + 1;
1923 if (s is LabeledStatement)
1924 unreachable = false;
1926 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1929 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1930 ec.CurrentBranching, statement_count, num_statements);
1932 while (ec.CurrentBranching is FlowBranchingLabeled)
1933 ec.EndFlowBranching ();
1935 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1937 ec.CurrentBlock = prev_block;
1939 // If we're a non-static `struct' constructor which doesn't have an
1940 // initializer, then we must initialize all of the struct's fields.
1941 if ((flags & Flags.IsToplevel) != 0 &&
1942 !Toplevel.IsThisAssigned (ec) &&
1943 !vector.Reachability.AlwaysThrows)
1946 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1947 foreach (LabeledStatement label in labels.Values)
1948 if (!label.HasBeenReferenced)
1949 Report.Warning (164, 2, label.loc,
1950 "This label has not been referenced");
1953 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1955 if (vector.Reachability.IsUnreachable)
1956 flags |= Flags.HasRet;
1958 if (ok && (errors == Report.Errors)) {
1959 if (RootContext.WarningLevel >= 3)
1960 UsageWarning (vector);
1966 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1968 unreachable_shown = true;
1972 Report.Warning (162, 2, loc, "Unreachable code detected");
1974 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1975 bool ok = Resolve (ec);
1976 ec.KillFlowBranching ();
1981 protected override void DoEmit (EmitContext ec)
1983 for (int ix = 0; ix < num_statements; ix++){
1984 Statement s = (Statement) statements [ix];
1986 // Check whether we are the last statement in a
1989 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
1990 ec.IsLastStatement = true;
1992 ec.IsLastStatement = false;
1998 public override void Emit (EmitContext ec)
2000 Block prev_block = ec.CurrentBlock;
2002 ec.CurrentBlock = this;
2004 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2005 bool is_lexical_block = !Implicit && (Parent != null);
2007 if (emit_debug_info) {
2008 if (is_lexical_block)
2011 if (variables != null) {
2012 foreach (DictionaryEntry de in variables) {
2013 string name = (string) de.Key;
2014 LocalInfo vi = (LocalInfo) de.Value;
2016 if (vi.LocalBuilder == null)
2019 ec.DefineLocalVariable (name, vi.LocalBuilder);
2023 ec.Mark (StartLocation, true);
2024 ec.EmitScopeInitFromBlock (this);
2026 ec.Mark (EndLocation, true);
2028 if (emit_debug_info && is_lexical_block)
2031 ec.CurrentBlock = prev_block;
2035 // Returns true if we ar ea child of `b'.
2037 public bool IsChildOf (Block b)
2039 Block current = this;
2042 if (current.Parent == b)
2044 current = current.Parent;
2045 } while (current != null);
2049 public override string ToString ()
2051 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2056 // A toplevel block contains extra information, the split is done
2057 // only to separate information that would otherwise bloat the more
2058 // lightweight Block.
2060 // In particular, this was introduced when the support for Anonymous
2061 // Methods was implemented.
2063 public class ToplevelBlock : Block {
2065 // Pointer to the host of this anonymous method, or null
2066 // if we are the topmost block
2068 ToplevelBlock container;
2069 CaptureContext capture_context;
2070 FlowBranching top_level_branching;
2072 Hashtable capture_contexts;
2075 public bool HasVarargs {
2076 get { return (flags & Flags.HasVarargs) != 0; }
2077 set { flags |= Flags.HasVarargs; }
2081 // The parameters for the block.
2083 Parameters parameters;
2084 public Parameters Parameters {
2085 get { return parameters; }
2088 public void RegisterCaptureContext (CaptureContext cc)
2090 if (capture_contexts == null)
2091 capture_contexts = new Hashtable ();
2092 capture_contexts [cc] = cc;
2095 public void CompleteContexts ()
2097 if (capture_contexts == null)
2100 foreach (CaptureContext cc in capture_contexts.Keys){
2105 public CaptureContext ToplevelBlockCaptureContext {
2106 get { return capture_context; }
2109 public ToplevelBlock Container {
2110 get { return container; }
2113 protected void AddChild (ToplevelBlock block)
2115 if (children == null)
2116 children = new ArrayList ();
2118 children.Add (block);
2122 // Parent is only used by anonymous blocks to link back to their
2125 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2126 this (container, (Flags) 0, parameters, start)
2130 public ToplevelBlock (Parameters parameters, Location start) :
2131 this (null, (Flags) 0, parameters, start)
2135 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2136 this (null, flags, parameters, start)
2140 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2141 base (null, flags | Flags.IsToplevel, start, Location.Null)
2143 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2144 this.container = container;
2146 if (container != null)
2147 container.AddChild (this);
2150 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2154 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2156 if (capture_context == null)
2157 capture_context = new CaptureContext (this, loc, host);
2160 public CaptureContext CaptureContext {
2161 get { return capture_context; }
2164 public FlowBranching TopLevelBranching {
2165 get { return top_level_branching; }
2169 // This is used if anonymous methods are used inside an iterator
2170 // (see 2test-22.cs for an example).
2172 // The AnonymousMethod is created while parsing - at a time when we don't
2173 // know yet that we're inside an iterator, so it's `Container' is initially
2174 // null. Later on, when resolving the iterator, we need to move the
2175 // anonymous method into that iterator.
2177 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2179 foreach (ToplevelBlock block in children) {
2180 if (block.CaptureContext == null)
2183 block.container = new_parent;
2184 block.CaptureContext.ReParent (new_parent, new_host);
2189 // Returns a `ParameterReference' for the given name, or null if there
2190 // is no such parameter
2192 public ParameterReference GetParameterReference (string name, Location loc)
2197 for (ToplevelBlock t = this; t != null; t = t.Container) {
2198 Parameters pars = t.Parameters;
2199 par = pars.GetParameterByName (name, out idx);
2201 return new ParameterReference (par, this, idx, loc);
2207 // Whether the parameter named `name' is local to this block,
2208 // or false, if the parameter belongs to an encompassing block.
2210 public bool IsLocalParameter (string name)
2212 return Parameters.GetParameterByName (name) != null;
2216 // Whether the `name' is a parameter reference
2218 public bool IsParameterReference (string name)
2220 for (ToplevelBlock t = this; t != null; t = t.Container) {
2221 if (t.IsLocalParameter (name))
2227 LocalInfo this_variable = null;
2230 // Returns the "this" instance variable of this block.
2231 // See AddThisVariable() for more information.
2233 public LocalInfo ThisVariable {
2234 get { return this_variable; }
2239 // This is used by non-static `struct' constructors which do not have an
2240 // initializer - in this case, the constructor must initialize all of the
2241 // struct's fields. To do this, we add a "this" variable and use the flow
2242 // analysis code to ensure that it's been fully initialized before control
2243 // leaves the constructor.
2245 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2247 if (this_variable == null) {
2248 this_variable = new LocalInfo (ds, this, l);
2249 this_variable.Used = true;
2250 this_variable.IsThis = true;
2252 Variables.Add ("this", this_variable);
2255 return this_variable;
2258 public bool IsThisAssigned (EmitContext ec)
2260 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2263 public bool ResolveMeta (EmitContext ec, Parameters ip)
2265 int errors = Report.Errors;
2267 if (top_level_branching != null)
2273 ResolveMeta (this, ec, ip);
2275 top_level_branching = ec.StartFlowBranching (this);
2277 return Report.Errors == errors;
2281 public class SwitchLabel {
2288 Label il_label_code;
2289 bool il_label_code_set;
2291 public static readonly object NullStringCase = new object ();
2294 // if expr == null, then it is the default case.
2296 public SwitchLabel (Expression expr, Location l)
2302 public Expression Label {
2308 public object Converted {
2314 public Label GetILLabel (EmitContext ec)
2317 il_label = ec.ig.DefineLabel ();
2318 il_label_set = true;
2323 public Label GetILLabelCode (EmitContext ec)
2325 if (!il_label_code_set){
2326 il_label_code = ec.ig.DefineLabel ();
2327 il_label_code_set = true;
2329 return il_label_code;
2333 // Resolves the expression, reduces it to a literal if possible
2334 // and then converts it to the requested type.
2336 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2338 Expression e = label.Resolve (ec);
2343 Constant c = e as Constant;
2345 Report.Error (150, loc, "A constant value is expected");
2349 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2350 converted = NullStringCase;
2354 c = c.ToType (required_type, loc);
2358 converted = c.GetValue ();
2362 public void Erorr_AlreadyOccurs ()
2365 if (converted == null)
2367 else if (converted == NullStringCase)
2370 label = converted.ToString ();
2372 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2376 public class SwitchSection {
2377 // An array of SwitchLabels.
2378 public readonly ArrayList Labels;
2379 public readonly Block Block;
2381 public SwitchSection (ArrayList labels, Block block)
2388 public class Switch : Statement {
2389 public readonly ArrayList Sections;
2390 public Expression Expr;
2393 /// Maps constants whose type type SwitchType to their SwitchLabels.
2395 public IDictionary Elements;
2398 /// The governing switch type
2400 public Type SwitchType;
2405 Label default_target;
2406 Expression new_expr;
2408 SwitchSection constant_section;
2409 SwitchSection default_section;
2412 // The types allowed to be implicitly cast from
2413 // on the governing type
2415 static Type [] allowed_types;
2417 public Switch (Expression e, ArrayList sects, Location l)
2424 public bool GotDefault {
2426 return default_section != null;
2430 public Label DefaultTarget {
2432 return default_target;
2437 // Determines the governing type for a switch. The returned
2438 // expression might be the expression from the switch, or an
2439 // expression that includes any potential conversions to the
2440 // integral types or to string.
2442 Expression SwitchGoverningType (EmitContext ec, Type t)
2444 if (t == TypeManager.byte_type ||
2445 t == TypeManager.sbyte_type ||
2446 t == TypeManager.ushort_type ||
2447 t == TypeManager.short_type ||
2448 t == TypeManager.uint32_type ||
2449 t == TypeManager.int32_type ||
2450 t == TypeManager.uint64_type ||
2451 t == TypeManager.int64_type ||
2452 t == TypeManager.char_type ||
2453 t == TypeManager.string_type ||
2454 t == TypeManager.bool_type ||
2455 t.IsSubclassOf (TypeManager.enum_type))
2458 if (allowed_types == null){
2459 allowed_types = new Type [] {
2460 TypeManager.sbyte_type,
2461 TypeManager.byte_type,
2462 TypeManager.short_type,
2463 TypeManager.ushort_type,
2464 TypeManager.int32_type,
2465 TypeManager.uint32_type,
2466 TypeManager.int64_type,
2467 TypeManager.uint64_type,
2468 TypeManager.char_type,
2469 TypeManager.string_type,
2470 TypeManager.bool_type
2475 // Try to find a *user* defined implicit conversion.
2477 // If there is no implicit conversion, or if there are multiple
2478 // conversions, we have to report an error
2480 Expression converted = null;
2481 foreach (Type tt in allowed_types){
2484 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2489 // Ignore over-worked ImplicitUserConversions that do
2490 // an implicit conversion in addition to the user conversion.
2492 if (!(e is UserCast))
2495 if (converted != null){
2496 Report.ExtraInformation (
2498 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2499 TypeManager.CSharpName (Expr.Type)));
2509 // Performs the basic sanity checks on the switch statement
2510 // (looks for duplicate keys and non-constant expressions).
2512 // It also returns a hashtable with the keys that we will later
2513 // use to compute the switch tables
2515 bool CheckSwitch (EmitContext ec)
2518 Elements = Sections.Count > 10 ?
2519 (IDictionary)new Hashtable () :
2520 (IDictionary)new ListDictionary ();
2522 foreach (SwitchSection ss in Sections){
2523 foreach (SwitchLabel sl in ss.Labels){
2524 if (sl.Label == null){
2525 if (default_section != null){
2526 sl.Erorr_AlreadyOccurs ();
2529 default_section = ss;
2533 if (!sl.ResolveAndReduce (ec, SwitchType)){
2538 object key = sl.Converted;
2540 Elements.Add (key, sl);
2542 catch (ArgumentException) {
2543 sl.Erorr_AlreadyOccurs ();
2551 void EmitObjectInteger (ILGenerator ig, object k)
2554 IntConstant.EmitInt (ig, (int) k);
2555 else if (k is Constant) {
2556 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2559 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2562 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2564 IntConstant.EmitInt (ig, (int) (long) k);
2565 ig.Emit (OpCodes.Conv_I8);
2568 LongConstant.EmitLong (ig, (long) k);
2570 else if (k is ulong)
2572 ulong ul = (ulong) k;
2575 IntConstant.EmitInt (ig, unchecked ((int) ul));
2576 ig.Emit (OpCodes.Conv_U8);
2580 LongConstant.EmitLong (ig, unchecked ((long) ul));
2584 IntConstant.EmitInt (ig, (int) ((char) k));
2585 else if (k is sbyte)
2586 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2588 IntConstant.EmitInt (ig, (int) ((byte) k));
2589 else if (k is short)
2590 IntConstant.EmitInt (ig, (int) ((short) k));
2591 else if (k is ushort)
2592 IntConstant.EmitInt (ig, (int) ((ushort) k));
2594 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2596 throw new Exception ("Unhandled case");
2599 // structure used to hold blocks of keys while calculating table switch
2600 class KeyBlock : IComparable
2602 public KeyBlock (long _nFirst)
2604 nFirst = nLast = _nFirst;
2608 public ArrayList rgKeys = null;
2609 // how many items are in the bucket
2610 public int Size = 1;
2613 get { return (int) (nLast - nFirst + 1); }
2615 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2617 return kbLast.nLast - kbFirst.nFirst + 1;
2619 public int CompareTo (object obj)
2621 KeyBlock kb = (KeyBlock) obj;
2622 int nLength = Length;
2623 int nLengthOther = kb.Length;
2624 if (nLengthOther == nLength)
2625 return (int) (kb.nFirst - nFirst);
2626 return nLength - nLengthOther;
2631 /// This method emits code for a lookup-based switch statement (non-string)
2632 /// Basically it groups the cases into blocks that are at least half full,
2633 /// and then spits out individual lookup opcodes for each block.
2634 /// It emits the longest blocks first, and short blocks are just
2635 /// handled with direct compares.
2637 /// <param name="ec"></param>
2638 /// <param name="val"></param>
2639 /// <returns></returns>
2640 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2642 int cElements = Elements.Count;
2643 object [] rgKeys = new object [cElements];
2644 Elements.Keys.CopyTo (rgKeys, 0);
2645 Array.Sort (rgKeys);
2647 // initialize the block list with one element per key
2648 ArrayList rgKeyBlocks = new ArrayList ();
2649 foreach (object key in rgKeys)
2650 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2653 // iteratively merge the blocks while they are at least half full
2654 // there's probably a really cool way to do this with a tree...
2655 while (rgKeyBlocks.Count > 1)
2657 ArrayList rgKeyBlocksNew = new ArrayList ();
2658 kbCurr = (KeyBlock) rgKeyBlocks [0];
2659 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2661 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2662 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2665 kbCurr.nLast = kb.nLast;
2666 kbCurr.Size += kb.Size;
2670 // start a new block
2671 rgKeyBlocksNew.Add (kbCurr);
2675 rgKeyBlocksNew.Add (kbCurr);
2676 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2678 rgKeyBlocks = rgKeyBlocksNew;
2681 // initialize the key lists
2682 foreach (KeyBlock kb in rgKeyBlocks)
2683 kb.rgKeys = new ArrayList ();
2685 // fill the key lists
2687 if (rgKeyBlocks.Count > 0) {
2688 kbCurr = (KeyBlock) rgKeyBlocks [0];
2689 foreach (object key in rgKeys)
2691 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2692 System.Convert.ToInt64 (key) > kbCurr.nLast;
2694 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2695 kbCurr.rgKeys.Add (key);
2699 // sort the blocks so we can tackle the largest ones first
2700 rgKeyBlocks.Sort ();
2702 // okay now we can start...
2703 ILGenerator ig = ec.ig;
2704 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2705 Label lblDefault = ig.DefineLabel ();
2707 Type typeKeys = null;
2708 if (rgKeys.Length > 0)
2709 typeKeys = rgKeys [0].GetType (); // used for conversions
2713 if (TypeManager.IsEnumType (SwitchType))
2714 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2716 compare_type = SwitchType;
2718 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2720 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2721 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2724 foreach (object key in kb.rgKeys)
2726 ig.Emit (OpCodes.Ldloc, val);
2727 EmitObjectInteger (ig, key);
2728 SwitchLabel sl = (SwitchLabel) Elements [key];
2729 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2734 // TODO: if all the keys in the block are the same and there are
2735 // no gaps/defaults then just use a range-check.
2736 if (compare_type == TypeManager.int64_type ||
2737 compare_type == TypeManager.uint64_type)
2739 // TODO: optimize constant/I4 cases
2741 // check block range (could be > 2^31)
2742 ig.Emit (OpCodes.Ldloc, val);
2743 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2744 ig.Emit (OpCodes.Blt, lblDefault);
2745 ig.Emit (OpCodes.Ldloc, val);
2746 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2747 ig.Emit (OpCodes.Bgt, lblDefault);
2750 ig.Emit (OpCodes.Ldloc, val);
2753 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2754 ig.Emit (OpCodes.Sub);
2756 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2761 ig.Emit (OpCodes.Ldloc, val);
2762 int nFirst = (int) kb.nFirst;
2765 IntConstant.EmitInt (ig, nFirst);
2766 ig.Emit (OpCodes.Sub);
2768 else if (nFirst < 0)
2770 IntConstant.EmitInt (ig, -nFirst);
2771 ig.Emit (OpCodes.Add);
2775 // first, build the list of labels for the switch
2777 int cJumps = kb.Length;
2778 Label [] rgLabels = new Label [cJumps];
2779 for (int iJump = 0; iJump < cJumps; iJump++)
2781 object key = kb.rgKeys [iKey];
2782 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2784 SwitchLabel sl = (SwitchLabel) Elements [key];
2785 rgLabels [iJump] = sl.GetILLabel (ec);
2789 rgLabels [iJump] = lblDefault;
2791 // emit the switch opcode
2792 ig.Emit (OpCodes.Switch, rgLabels);
2795 // mark the default for this block
2797 ig.MarkLabel (lblDefault);
2800 // TODO: find the default case and emit it here,
2801 // to prevent having to do the following jump.
2802 // make sure to mark other labels in the default section
2804 // the last default just goes to the end
2805 ig.Emit (OpCodes.Br, lblDefault);
2807 // now emit the code for the sections
2808 bool fFoundDefault = false;
2809 foreach (SwitchSection ss in Sections)
2811 foreach (SwitchLabel sl in ss.Labels)
2813 ig.MarkLabel (sl.GetILLabel (ec));
2814 ig.MarkLabel (sl.GetILLabelCode (ec));
2815 if (sl.Label == null)
2817 ig.MarkLabel (lblDefault);
2818 fFoundDefault = true;
2822 //ig.Emit (OpCodes.Br, lblEnd);
2825 if (!fFoundDefault) {
2826 ig.MarkLabel (lblDefault);
2828 ig.MarkLabel (lblEnd);
2831 // This simple emit switch works, but does not take advantage of the
2833 // TODO: remove non-string logic from here
2834 // TODO: binary search strings?
2836 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2838 ILGenerator ig = ec.ig;
2839 Label end_of_switch = ig.DefineLabel ();
2840 Label next_test = ig.DefineLabel ();
2841 Label null_target = ig.DefineLabel ();
2842 bool first_test = true;
2843 bool pending_goto_end = false;
2844 bool null_marked = false;
2847 ig.Emit (OpCodes.Ldloc, val);
2849 if (Elements.Contains (SwitchLabel.NullStringCase)){
2850 ig.Emit (OpCodes.Brfalse, null_target);
2852 ig.Emit (OpCodes.Brfalse, default_target);
2854 ig.Emit (OpCodes.Ldloc, val);
2855 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2856 ig.Emit (OpCodes.Stloc, val);
2858 int section_count = Sections.Count;
2859 for (int section = 0; section < section_count; section++){
2860 SwitchSection ss = (SwitchSection) Sections [section];
2862 if (ss == default_section)
2865 Label sec_begin = ig.DefineLabel ();
2867 ig.Emit (OpCodes.Nop);
2869 if (pending_goto_end)
2870 ig.Emit (OpCodes.Br, end_of_switch);
2872 int label_count = ss.Labels.Count;
2874 for (int label = 0; label < label_count; label++){
2875 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2876 ig.MarkLabel (sl.GetILLabel (ec));
2879 ig.MarkLabel (next_test);
2880 next_test = ig.DefineLabel ();
2883 // If we are the default target
2885 if (sl.Label != null){
2886 object lit = sl.Converted;
2888 if (lit == SwitchLabel.NullStringCase){
2890 if (label_count == 1)
2891 ig.Emit (OpCodes.Br, next_test);
2895 ig.Emit (OpCodes.Ldloc, val);
2896 ig.Emit (OpCodes.Ldstr, (string)lit);
2897 if (label_count == 1)
2898 ig.Emit (OpCodes.Bne_Un, next_test);
2900 if (label+1 == label_count)
2901 ig.Emit (OpCodes.Bne_Un, next_test);
2903 ig.Emit (OpCodes.Beq, sec_begin);
2908 ig.MarkLabel (null_target);
2911 ig.MarkLabel (sec_begin);
2912 foreach (SwitchLabel sl in ss.Labels)
2913 ig.MarkLabel (sl.GetILLabelCode (ec));
2916 pending_goto_end = !ss.Block.HasRet;
2919 ig.MarkLabel (next_test);
2920 ig.MarkLabel (default_target);
2922 ig.MarkLabel (null_target);
2923 if (default_section != null)
2924 default_section.Block.Emit (ec);
2925 ig.MarkLabel (end_of_switch);
2928 SwitchSection FindSection (SwitchLabel label)
2930 foreach (SwitchSection ss in Sections){
2931 foreach (SwitchLabel sl in ss.Labels){
2940 public override bool Resolve (EmitContext ec)
2942 Expr = Expr.Resolve (ec);
2946 new_expr = SwitchGoverningType (ec, Expr.Type);
2947 if (new_expr == null){
2948 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2953 SwitchType = new_expr.Type;
2955 if (!CheckSwitch (ec))
2958 Switch old_switch = ec.Switch;
2960 ec.Switch.SwitchType = SwitchType;
2962 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2963 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2965 is_constant = new_expr is Constant;
2967 object key = ((Constant) new_expr).GetValue ();
2968 SwitchLabel label = (SwitchLabel) Elements [key];
2970 constant_section = FindSection (label);
2971 if (constant_section == null)
2972 constant_section = default_section;
2976 foreach (SwitchSection ss in Sections){
2978 ec.CurrentBranching.CreateSibling (
2979 null, FlowBranching.SiblingType.SwitchSection);
2983 if (is_constant && (ss != constant_section)) {
2984 // If we're a constant switch, we're only emitting
2985 // one single section - mark all the others as
2987 ec.CurrentBranching.CurrentUsageVector.Goto ();
2988 if (!ss.Block.ResolveUnreachable (ec, true))
2991 if (!ss.Block.Resolve (ec))
2996 if (default_section == null)
2997 ec.CurrentBranching.CreateSibling (
2998 null, FlowBranching.SiblingType.SwitchSection);
3000 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3001 ec.Switch = old_switch;
3003 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3009 protected override void DoEmit (EmitContext ec)
3011 ILGenerator ig = ec.ig;
3013 // Store variable for comparission purposes
3016 value = ig.DeclareLocal (SwitchType);
3018 ig.Emit (OpCodes.Stloc, value);
3022 default_target = ig.DefineLabel ();
3025 // Setup the codegen context
3027 Label old_end = ec.LoopEnd;
3028 Switch old_switch = ec.Switch;
3030 ec.LoopEnd = ig.DefineLabel ();
3035 if (constant_section != null)
3036 constant_section.Block.Emit (ec);
3037 } else if (SwitchType == TypeManager.string_type)
3038 SimpleSwitchEmit (ec, value);
3040 TableSwitchEmit (ec, value);
3042 // Restore context state.
3043 ig.MarkLabel (ec.LoopEnd);
3046 // Restore the previous context
3048 ec.LoopEnd = old_end;
3049 ec.Switch = old_switch;
3053 public abstract class ExceptionStatement : Statement
3055 public abstract void EmitFinally (EmitContext ec);
3057 protected bool emit_finally = true;
3058 ArrayList parent_vectors;
3060 protected void DoEmitFinally (EmitContext ec)
3063 ec.ig.BeginFinallyBlock ();
3064 else if (ec.InIterator)
3065 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3069 protected void ResolveFinally (FlowBranchingException branching)
3071 emit_finally = branching.EmitFinally;
3073 branching.Parent.StealFinallyClauses (ref parent_vectors);
3077 public class Lock : ExceptionStatement {
3079 public Statement Statement;
3080 TemporaryVariable temp;
3082 public Lock (Expression expr, Statement stmt, Location l)
3089 public override bool Resolve (EmitContext ec)
3091 expr = expr.Resolve (ec);
3095 if (expr.Type.IsValueType){
3096 Report.Error (185, loc,
3097 "`{0}' is not a reference type as required by the lock statement",
3098 TypeManager.CSharpName (expr.Type));
3102 FlowBranchingException branching = ec.StartFlowBranching (this);
3103 bool ok = Statement.Resolve (ec);
3105 ec.KillFlowBranching ();
3109 ResolveFinally (branching);
3111 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3112 if (!reachability.AlwaysReturns) {
3113 // Unfortunately, System.Reflection.Emit automatically emits
3114 // a leave to the end of the finally block.
3115 // This is a problem if `returns' is true since we may jump
3116 // to a point after the end of the method.
3117 // As a workaround, emit an explicit ret here.
3118 ec.NeedReturnLabel ();
3121 temp = new TemporaryVariable (expr.Type, loc);
3127 protected override void DoEmit (EmitContext ec)
3129 ILGenerator ig = ec.ig;
3131 temp.Store (ec, expr);
3133 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3137 ig.BeginExceptionBlock ();
3138 Statement.Emit (ec);
3143 ig.EndExceptionBlock ();
3146 public override void EmitFinally (EmitContext ec)
3149 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3153 public class Unchecked : Statement {
3154 public readonly Block Block;
3156 public Unchecked (Block b)
3162 public override bool Resolve (EmitContext ec)
3164 bool previous_state = ec.CheckState;
3165 bool previous_state_const = ec.ConstantCheckState;
3167 ec.CheckState = false;
3168 ec.ConstantCheckState = false;
3169 bool ret = Block.Resolve (ec);
3170 ec.CheckState = previous_state;
3171 ec.ConstantCheckState = previous_state_const;
3176 protected override void DoEmit (EmitContext ec)
3178 bool previous_state = ec.CheckState;
3179 bool previous_state_const = ec.ConstantCheckState;
3181 ec.CheckState = false;
3182 ec.ConstantCheckState = false;
3184 ec.CheckState = previous_state;
3185 ec.ConstantCheckState = previous_state_const;
3189 public class Checked : Statement {
3190 public readonly Block Block;
3192 public Checked (Block b)
3195 b.Unchecked = false;
3198 public override bool Resolve (EmitContext ec)
3200 bool previous_state = ec.CheckState;
3201 bool previous_state_const = ec.ConstantCheckState;
3203 ec.CheckState = true;
3204 ec.ConstantCheckState = true;
3205 bool ret = Block.Resolve (ec);
3206 ec.CheckState = previous_state;
3207 ec.ConstantCheckState = previous_state_const;
3212 protected override void DoEmit (EmitContext ec)
3214 bool previous_state = ec.CheckState;
3215 bool previous_state_const = ec.ConstantCheckState;
3217 ec.CheckState = true;
3218 ec.ConstantCheckState = true;
3220 ec.CheckState = previous_state;
3221 ec.ConstantCheckState = previous_state_const;
3225 public class Unsafe : Statement {
3226 public readonly Block Block;
3228 public Unsafe (Block b)
3231 Block.Unsafe = true;
3234 public override bool Resolve (EmitContext ec)
3236 bool previous_state = ec.InUnsafe;
3240 val = Block.Resolve (ec);
3241 ec.InUnsafe = previous_state;
3246 protected override void DoEmit (EmitContext ec)
3248 bool previous_state = ec.InUnsafe;
3252 ec.InUnsafe = previous_state;
3259 public class Fixed : Statement {
3261 ArrayList declarators;
3262 Statement statement;
3267 abstract class Emitter
3269 protected LocalInfo vi;
3270 protected Expression converted;
3272 protected Emitter (Expression expr, LocalInfo li)
3278 public abstract void Emit (EmitContext ec);
3279 public abstract void EmitExit (ILGenerator ig);
3282 class ExpressionEmitter : Emitter {
3283 public ExpressionEmitter (Expression converted, LocalInfo li) :
3284 base (converted, li)
3288 public override void Emit (EmitContext ec) {
3290 // Store pointer in pinned location
3292 converted.Emit (ec);
3293 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3296 public override void EmitExit (ILGenerator ig)
3298 ig.Emit (OpCodes.Ldc_I4_0);
3299 ig.Emit (OpCodes.Conv_U);
3300 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3304 class StringEmitter : Emitter {
3305 LocalBuilder pinned_string;
3308 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3314 public override void Emit (EmitContext ec)
3316 ILGenerator ig = ec.ig;
3317 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3319 converted.Emit (ec);
3320 ig.Emit (OpCodes.Stloc, pinned_string);
3322 Expression sptr = new StringPtr (pinned_string, loc);
3323 converted = Convert.ImplicitConversionRequired (
3324 ec, sptr, vi.VariableType, loc);
3326 if (converted == null)
3329 converted.Emit (ec);
3330 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3333 public override void EmitExit(ILGenerator ig)
3335 ig.Emit (OpCodes.Ldnull);
3336 ig.Emit (OpCodes.Stloc, pinned_string);
3340 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3343 declarators = decls;
3348 public Statement Statement {
3349 get { return statement; }
3352 public override bool Resolve (EmitContext ec)
3355 Expression.UnsafeError (loc);
3359 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3363 expr_type = texpr.Type;
3365 data = new Emitter [declarators.Count];
3367 if (!expr_type.IsPointer){
3368 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3373 foreach (Pair p in declarators){
3374 LocalInfo vi = (LocalInfo) p.First;
3375 Expression e = (Expression) p.Second;
3377 vi.VariableInfo.SetAssigned (ec);
3378 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3381 // The rules for the possible declarators are pretty wise,
3382 // but the production on the grammar is more concise.
3384 // So we have to enforce these rules here.
3386 // We do not resolve before doing the case 1 test,
3387 // because the grammar is explicit in that the token &
3388 // is present, so we need to test for this particular case.
3392 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3397 // Case 1: & object.
3399 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3400 Expression child = ((Unary) e).Expr;
3402 if (child is ParameterReference || child is LocalVariableReference){
3405 "No need to use fixed statement for parameters or " +
3406 "local variable declarations (address is already " +
3411 ec.InFixedInitializer = true;
3413 ec.InFixedInitializer = false;
3417 child = ((Unary) e).Expr;
3419 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3422 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
3423 e.Error_ValueCannotBeConverted (e.Location, expr_type, false);
3427 data [i] = new ExpressionEmitter (e, vi);
3433 ec.InFixedInitializer = true;
3435 ec.InFixedInitializer = false;
3442 if (e.Type.IsArray){
3443 Type array_type = TypeManager.GetElementType (e.Type);
3446 // Provided that array_type is unmanaged,
3448 if (!TypeManager.VerifyUnManaged (array_type, loc))
3452 // and T* is implicitly convertible to the
3453 // pointer type given in the fixed statement.
3455 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3457 Expression converted = Convert.ImplicitConversionRequired (
3458 ec, array_ptr, vi.VariableType, loc);
3459 if (converted == null)
3462 data [i] = new ExpressionEmitter (converted, vi);
3471 if (e.Type == TypeManager.string_type){
3472 data [i] = new StringEmitter (e, vi, loc);
3477 // Case 4: fixed buffer
3478 FieldExpr fe = e as FieldExpr;
3480 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3482 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3484 Expression converted = Convert.ImplicitConversionRequired (
3485 ec, fixed_buffer_ptr, vi.VariableType, loc);
3486 if (converted == null)
3489 data [i] = new ExpressionEmitter (converted, vi);
3497 // For other cases, flag a `this is already fixed expression'
3499 if (e is LocalVariableReference || e is ParameterReference ||
3500 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3502 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3506 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3510 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3512 if (!statement.Resolve (ec)) {
3513 ec.KillFlowBranching ();
3517 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3518 has_ret = reachability.IsUnreachable;
3523 protected override void DoEmit (EmitContext ec)
3525 for (int i = 0; i < data.Length; i++) {
3529 statement.Emit (ec);
3534 ILGenerator ig = ec.ig;
3537 // Clear the pinned variable
3539 for (int i = 0; i < data.Length; i++) {
3540 data [i].EmitExit (ig);
3545 public class Catch : Statement {
3546 public readonly string Name;
3547 public readonly Block Block;
3548 public readonly Block VarBlock;
3550 Expression type_expr;
3553 public Catch (Expression type, string name, Block block, Block var_block, Location l)
3558 VarBlock = var_block;
3562 public Type CatchType {
3568 public bool IsGeneral {
3570 return type_expr == null;
3574 protected override void DoEmit(EmitContext ec)
3578 public override bool Resolve (EmitContext ec)
3580 bool was_catch = ec.InCatch;
3583 if (type_expr != null) {
3584 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3590 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3591 Error (155, "The type caught or thrown must be derived from System.Exception");
3597 if (!Block.Resolve (ec))
3600 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
3601 // emit the "unused variable" warnings.
3602 if (VarBlock != null)
3603 return VarBlock.Resolve (ec);
3608 ec.InCatch = was_catch;
3613 public class Try : ExceptionStatement {
3614 public readonly Block Fini, Block;
3615 public readonly ArrayList Specific;
3616 public readonly Catch General;
3618 bool need_exc_block;
3621 // specific, general and fini might all be null.
3623 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3625 if (specific == null && general == null){
3626 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3630 this.Specific = specific;
3631 this.General = general;
3636 public override bool Resolve (EmitContext ec)
3640 FlowBranchingException branching = ec.StartFlowBranching (this);
3642 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3644 if (!Block.Resolve (ec))
3647 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3649 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3651 Type[] prevCatches = new Type [Specific.Count];
3653 foreach (Catch c in Specific){
3654 ec.CurrentBranching.CreateSibling (
3655 c.Block, FlowBranching.SiblingType.Catch);
3657 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3659 if (c.Name != null) {
3660 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3662 throw new Exception ();
3664 vi.VariableInfo = null;
3667 if (!c.Resolve (ec))
3670 Type resolvedType = c.CatchType;
3671 for (int ii = 0; ii < last_index; ++ii) {
3672 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3673 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3678 prevCatches [last_index++] = resolvedType;
3679 need_exc_block = true;
3682 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3684 if (General != null){
3685 if (CodeGen.Assembly.WrapNonExceptionThrows) {
3686 foreach (Catch c in Specific){
3687 if (c.CatchType == TypeManager.exception_type) {
3688 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'");
3693 ec.CurrentBranching.CreateSibling (
3694 General.Block, FlowBranching.SiblingType.Catch);
3696 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3698 if (!General.Resolve (ec))
3701 need_exc_block = true;
3704 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3708 ec.CurrentBranching.CreateSibling (
3709 Fini, FlowBranching.SiblingType.Finally);
3711 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3712 bool was_finally = ec.InFinally;
3713 ec.InFinally = true;
3714 if (!Fini.Resolve (ec))
3716 ec.InFinally = was_finally;
3719 need_exc_block = true;
3722 if (ec.InIterator) {
3723 ResolveFinally (branching);
3724 need_exc_block |= emit_finally;
3726 emit_finally = Fini != null;
3728 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3730 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3732 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3734 if (!reachability.AlwaysReturns) {
3735 // Unfortunately, System.Reflection.Emit automatically emits
3736 // a leave to the end of the finally block. This is a problem
3737 // if `returns' is true since we may jump to a point after the
3738 // end of the method.
3739 // As a workaround, emit an explicit ret here.
3740 ec.NeedReturnLabel ();
3746 protected override void DoEmit (EmitContext ec)
3748 ILGenerator ig = ec.ig;
3751 ig.BeginExceptionBlock ();
3754 foreach (Catch c in Specific){
3757 ig.BeginCatchBlock (c.CatchType);
3759 if (c.VarBlock != null)
3760 ec.EmitScopeInitFromBlock (c.VarBlock);
3761 if (c.Name != null){
3762 vi = c.Block.GetLocalInfo (c.Name);
3764 throw new Exception ("Variable does not exist in this block");
3767 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
3768 ig.Emit (OpCodes.Stloc, e);
3770 ec.EmitCapturedVariableInstance (vi);
3771 ig.Emit (OpCodes.Ldloc, e);
3772 ig.Emit (OpCodes.Stfld, vi.FieldBuilder);
3774 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3776 ig.Emit (OpCodes.Pop);
3781 if (General != null){
3782 ig.BeginCatchBlock (TypeManager.object_type);
3783 ig.Emit (OpCodes.Pop);
3784 General.Block.Emit (ec);
3789 ig.EndExceptionBlock ();
3792 public override void EmitFinally (EmitContext ec)
3798 public bool HasCatch
3801 return General != null || Specific.Count > 0;
3806 public class Using : ExceptionStatement {
3807 object expression_or_block;
3808 public Statement Statement;
3812 Expression [] resolved_vars;
3813 Expression [] converted_vars;
3814 ExpressionStatement [] assign;
3815 LocalBuilder local_copy;
3817 public Using (object expression_or_block, Statement stmt, Location l)
3819 this.expression_or_block = expression_or_block;
3825 // Resolves for the case of using using a local variable declaration.
3827 bool ResolveLocalVariableDecls (EmitContext ec)
3831 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3835 expr_type = texpr.Type;
3838 // The type must be an IDisposable or an implicit conversion
3841 converted_vars = new Expression [var_list.Count];
3842 resolved_vars = new Expression [var_list.Count];
3843 assign = new ExpressionStatement [var_list.Count];
3845 bool need_conv = !TypeManager.ImplementsInterface (
3846 expr_type, TypeManager.idisposable_type);
3848 foreach (DictionaryEntry e in var_list){
3849 Expression var = (Expression) e.Key;
3851 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3855 resolved_vars [i] = var;
3862 converted_vars [i] = Convert.ImplicitConversion (
3863 ec, var, TypeManager.idisposable_type, loc);
3865 if (converted_vars [i] == null) {
3866 Error_IsNotConvertibleToIDisposable ();
3874 foreach (DictionaryEntry e in var_list){
3875 Expression var = resolved_vars [i];
3876 Expression new_expr = (Expression) e.Value;
3879 a = new Assign (var, new_expr, loc);
3885 converted_vars [i] = var;
3886 assign [i] = (ExpressionStatement) a;
3893 void Error_IsNotConvertibleToIDisposable ()
3895 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
3896 TypeManager.CSharpName (expr_type));
3899 bool ResolveExpression (EmitContext ec)
3901 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3902 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3903 Error_IsNotConvertibleToIDisposable ();
3912 // Emits the code for the case of using using a local variable declaration.
3914 void EmitLocalVariableDecls (EmitContext ec)
3916 ILGenerator ig = ec.ig;
3919 for (i = 0; i < assign.Length; i++) {
3920 assign [i].EmitStatement (ec);
3923 ig.BeginExceptionBlock ();
3925 Statement.Emit (ec);
3927 var_list.Reverse ();
3932 void EmitLocalVariableDeclFinally (EmitContext ec)
3934 ILGenerator ig = ec.ig;
3936 int i = assign.Length;
3937 for (int ii = 0; ii < var_list.Count; ++ii){
3938 Expression var = resolved_vars [--i];
3939 Label skip = ig.DefineLabel ();
3941 ig.BeginFinallyBlock ();
3943 if (!var.Type.IsValueType) {
3945 ig.Emit (OpCodes.Brfalse, skip);
3946 converted_vars [i].Emit (ec);
3947 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3949 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3951 if (!(ml is MethodGroupExpr)) {
3953 ig.Emit (OpCodes.Box, var.Type);
3954 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3956 MethodInfo mi = null;
3958 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3959 if (TypeManager.GetParameterData (mk).Count == 0) {
3966 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3970 IMemoryLocation mloc = (IMemoryLocation) var;
3972 mloc.AddressOf (ec, AddressOp.Load);
3973 ig.Emit (OpCodes.Call, mi);
3977 ig.MarkLabel (skip);
3980 ig.EndExceptionBlock ();
3982 ig.BeginFinallyBlock ();
3987 void EmitExpression (EmitContext ec)
3990 // Make a copy of the expression and operate on that.
3992 ILGenerator ig = ec.ig;
3993 local_copy = ig.DeclareLocal (expr_type);
3996 ig.Emit (OpCodes.Stloc, local_copy);
3999 ig.BeginExceptionBlock ();
4001 Statement.Emit (ec);
4005 ig.EndExceptionBlock ();
4008 void EmitExpressionFinally (EmitContext ec)
4010 ILGenerator ig = ec.ig;
4011 if (!local_copy.LocalType.IsValueType) {
4012 Label skip = ig.DefineLabel ();
4013 ig.Emit (OpCodes.Ldloc, local_copy);
4014 ig.Emit (OpCodes.Brfalse, skip);
4015 ig.Emit (OpCodes.Ldloc, local_copy);
4016 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4017 ig.MarkLabel (skip);
4019 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4021 if (!(ml is MethodGroupExpr)) {
4022 ig.Emit (OpCodes.Ldloc, local_copy);
4023 ig.Emit (OpCodes.Box, local_copy.LocalType);
4024 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4026 MethodInfo mi = null;
4028 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4029 if (TypeManager.GetParameterData (mk).Count == 0) {
4036 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4040 ig.Emit (OpCodes.Ldloca, local_copy);
4041 ig.Emit (OpCodes.Call, mi);
4046 public override bool Resolve (EmitContext ec)
4048 if (expression_or_block is DictionaryEntry){
4049 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4050 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4052 if (!ResolveLocalVariableDecls (ec))
4055 } else if (expression_or_block is Expression){
4056 expr = (Expression) expression_or_block;
4058 expr = expr.Resolve (ec);
4062 expr_type = expr.Type;
4064 if (!ResolveExpression (ec))
4068 FlowBranchingException branching = ec.StartFlowBranching (this);
4070 bool ok = Statement.Resolve (ec);
4073 ec.KillFlowBranching ();
4077 ResolveFinally (branching);
4078 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4080 if (!reachability.AlwaysReturns) {
4081 // Unfortunately, System.Reflection.Emit automatically emits a leave
4082 // to the end of the finally block. This is a problem if `returns'
4083 // is true since we may jump to a point after the end of the method.
4084 // As a workaround, emit an explicit ret here.
4085 ec.NeedReturnLabel ();
4091 protected override void DoEmit (EmitContext ec)
4093 if (expression_or_block is DictionaryEntry)
4094 EmitLocalVariableDecls (ec);
4095 else if (expression_or_block is Expression)
4096 EmitExpression (ec);
4099 public override void EmitFinally (EmitContext ec)
4101 if (expression_or_block is DictionaryEntry)
4102 EmitLocalVariableDeclFinally (ec);
4103 else if (expression_or_block is Expression)
4104 EmitExpressionFinally (ec);
4109 /// Implementation of the foreach C# statement
4111 public class Foreach : Statement {
4113 Expression variable;
4115 Statement statement;
4117 CollectionForeach collection;
4119 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4120 Statement stmt, Location l)
4123 this.variable = var;
4129 public Statement Statement {
4130 get { return statement; }
4133 public override bool Resolve (EmitContext ec)
4135 expr = expr.Resolve (ec);
4139 Constant c = expr as Constant;
4140 if (c != null && c.GetValue () == null) {
4141 Report.Error (186, loc, "Use of null is not valid in this context");
4145 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4149 Type var_type = texpr.Type;
4151 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethod) {
4152 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4153 expr.ExprClassName);
4158 // We need an instance variable. Not sure this is the best
4159 // way of doing this.
4161 // FIXME: When we implement propertyaccess, will those turn
4162 // out to return values in ExprClass? I think they should.
4164 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4165 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4166 collection.Error_Enumerator ();
4170 if (expr.Type.IsArray) {
4171 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4172 return array.Resolve (ec);
4174 collection = new CollectionForeach (
4175 var_type, variable, expr, statement, loc);
4176 return collection.Resolve (ec);
4180 protected override void DoEmit (EmitContext ec)
4182 ILGenerator ig = ec.ig;
4184 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4185 ec.LoopBegin = ig.DefineLabel ();
4186 ec.LoopEnd = ig.DefineLabel ();
4188 if (collection != null)
4189 collection.Emit (ec);
4193 ec.LoopBegin = old_begin;
4194 ec.LoopEnd = old_end;
4197 protected class ArrayCounter : TemporaryVariable
4199 public ArrayCounter (Location loc)
4200 : base (TypeManager.int32_type, loc)
4203 public void Initialize (EmitContext ec)
4206 ec.ig.Emit (OpCodes.Ldc_I4_0);
4210 public void Increment (EmitContext ec)
4214 ec.ig.Emit (OpCodes.Ldc_I4_1);
4215 ec.ig.Emit (OpCodes.Add);
4220 protected class ArrayForeach : Statement
4222 Expression variable, expr, conv;
4223 Statement statement;
4226 TemporaryVariable[] lengths;
4227 ArrayCounter[] counter;
4230 TemporaryVariable copy;
4233 public ArrayForeach (Type var_type, Expression var,
4234 Expression expr, Statement stmt, Location l)
4236 this.var_type = var_type;
4237 this.variable = var;
4243 public override bool Resolve (EmitContext ec)
4245 array_type = expr.Type;
4246 rank = array_type.GetArrayRank ();
4248 copy = new TemporaryVariable (array_type, loc);
4251 counter = new ArrayCounter [rank];
4252 lengths = new TemporaryVariable [rank];
4254 ArrayList list = new ArrayList ();
4255 for (int i = 0; i < rank; i++) {
4256 counter [i] = new ArrayCounter (loc);
4257 counter [i].Resolve (ec);
4259 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4260 lengths [i].Resolve (ec);
4262 list.Add (counter [i]);
4265 access = new ElementAccess (copy, list).Resolve (ec);
4269 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4275 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4276 ec.CurrentBranching.CreateSibling ();
4278 variable = variable.ResolveLValue (ec, conv, loc);
4279 if (variable == null)
4282 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4283 if (!statement.Resolve (ec))
4285 ec.EndFlowBranching ();
4287 // There's no direct control flow from the end of the embedded statement to the end of the loop
4288 ec.CurrentBranching.CurrentUsageVector.Goto ();
4290 ec.EndFlowBranching ();
4295 protected override void DoEmit (EmitContext ec)
4297 ILGenerator ig = ec.ig;
4299 copy.Store (ec, expr);
4301 Label[] test = new Label [rank];
4302 Label[] loop = new Label [rank];
4304 for (int i = 0; i < rank; i++) {
4305 test [i] = ig.DefineLabel ();
4306 loop [i] = ig.DefineLabel ();
4308 lengths [i].EmitThis (ec);
4309 ((ArrayAccess) access).EmitGetLength (ec, i);
4310 lengths [i].EmitStore (ig);
4313 for (int i = 0; i < rank; i++) {
4314 counter [i].Initialize (ec);
4316 ig.Emit (OpCodes.Br, test [i]);
4317 ig.MarkLabel (loop [i]);
4320 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4322 statement.Emit (ec);
4324 ig.MarkLabel (ec.LoopBegin);
4326 for (int i = rank - 1; i >= 0; i--){
4327 counter [i].Increment (ec);
4329 ig.MarkLabel (test [i]);
4330 counter [i].Emit (ec);
4331 lengths [i].Emit (ec);
4332 ig.Emit (OpCodes.Blt, loop [i]);
4335 ig.MarkLabel (ec.LoopEnd);
4339 protected class CollectionForeach : ExceptionStatement
4341 Expression variable, expr;
4342 Statement statement;
4344 TemporaryVariable enumerator;
4348 MethodGroupExpr get_enumerator;
4349 PropertyExpr get_current;
4350 MethodInfo move_next;
4351 Type var_type, enumerator_type;
4353 bool enumerator_found;
4355 public CollectionForeach (Type var_type, Expression var,
4356 Expression expr, Statement stmt, Location l)
4358 this.var_type = var_type;
4359 this.variable = var;
4365 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4367 Type return_type = mi.ReturnType;
4369 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4371 // Apply the same optimization as MS: skip the GetEnumerator
4372 // returning an IEnumerator, and use the one returning a
4373 // CharEnumerator instead. This allows us to avoid the
4374 // try-finally block and the boxing.
4379 // Ok, we can access it, now make sure that we can do something
4380 // with this `GetEnumerator'
4383 if (return_type == TypeManager.ienumerator_type ||
4384 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4385 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4387 // If it is not an interface, lets try to find the methods ourselves.
4388 // For example, if we have:
4389 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4390 // We can avoid the iface call. This is a runtime perf boost.
4391 // even bigger if we have a ValueType, because we avoid the cost
4394 // We have to make sure that both methods exist for us to take
4395 // this path. If one of the methods does not exist, we will just
4396 // use the interface. Sadly, this complex if statement is the only
4397 // way I could do this without a goto
4400 if (return_type.IsInterface && return_type.IsGenericType) {
4401 enumerator_type = return_type;
4402 if (!FetchGetCurrent (ec, return_type))
4403 get_current = new PropertyExpr (
4404 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4405 if (!FetchMoveNext (return_type))
4406 move_next = TypeManager.bool_movenext_void;
4410 if (return_type.IsInterface ||
4411 !FetchMoveNext (return_type) ||
4412 !FetchGetCurrent (ec, return_type)) {
4413 enumerator_type = return_type;
4414 move_next = TypeManager.bool_movenext_void;
4415 get_current = new PropertyExpr (
4416 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4421 // Ok, so they dont return an IEnumerable, we will have to
4422 // find if they support the GetEnumerator pattern.
4425 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
4426 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",
4427 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
4432 enumerator_type = return_type;
4433 is_disposable = !enumerator_type.IsSealed ||
4434 TypeManager.ImplementsInterface (
4435 enumerator_type, TypeManager.idisposable_type);
4441 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4443 bool FetchMoveNext (Type t)
4445 MemberList move_next_list;
4447 move_next_list = TypeContainer.FindMembers (
4448 t, MemberTypes.Method,
4449 Expression.AllBindingFlags,
4450 Type.FilterName, "MoveNext");
4451 if (move_next_list.Count == 0)
4455 foreach (MemberInfo m in move_next_list){
4456 MethodInfo mi = (MethodInfo) m;
4458 if ((TypeManager.GetParameterData (mi).Count == 0) &&
4459 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4471 // Retrieves a `public T get_Current ()' method from the Type `t'
4473 bool FetchGetCurrent (EmitContext ec, Type t)
4475 PropertyExpr pe = Expression.MemberLookup (
4476 ec.ContainerType, t, "Current", MemberTypes.Property,
4477 Expression.AllBindingFlags, loc) as PropertyExpr;
4486 // Retrieves a `public void Dispose ()' method from the Type `t'
4488 static MethodInfo FetchMethodDispose (Type t)
4490 MemberList dispose_list;
4492 dispose_list = TypeContainer.FindMembers (
4493 t, MemberTypes.Method,
4494 BindingFlags.Public | BindingFlags.Instance,
4495 Type.FilterName, "Dispose");
4496 if (dispose_list.Count == 0)
4499 foreach (MemberInfo m in dispose_list){
4500 MethodInfo mi = (MethodInfo) m;
4502 if (TypeManager.GetParameterData (mi).Count == 0){
4503 if (mi.ReturnType == TypeManager.void_type)
4510 public void Error_Enumerator ()
4512 if (enumerator_found) {
4516 Report.Error (1579, loc,
4517 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4518 TypeManager.CSharpName (expr.Type));
4521 bool TryType (EmitContext ec, Type t)
4523 MethodGroupExpr mg = Expression.MemberLookup (
4524 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
4525 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4529 MethodBase result = null;
4530 MethodInfo tmp_move_next = null;
4531 PropertyExpr tmp_get_cur = null;
4532 Type tmp_enumerator_type = enumerator_type;
4533 foreach (MethodInfo mi in mg.Methods) {
4534 if (TypeManager.GetParameterData (mi).Count != 0)
4537 // Check whether GetEnumerator is public
4538 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4541 if (TypeManager.IsOverride (mi))
4544 enumerator_found = true;
4546 if (!GetEnumeratorFilter (ec, mi)) {
4551 tmp_move_next = move_next;
4552 tmp_get_cur = get_current;
4553 tmp_enumerator_type = enumerator_type;
4554 if (mi.DeclaringType == t)
4558 if (result != null) {
4559 move_next = tmp_move_next;
4560 get_current = tmp_get_cur;
4561 enumerator_type = tmp_enumerator_type;
4562 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
4563 get_enumerator = new MethodGroupExpr (mi, loc);
4565 if (t != expr.Type) {
4566 expr = Convert.ExplicitConversion (
4569 throw new InternalErrorException ();
4572 get_enumerator.InstanceExpression = expr;
4573 get_enumerator.IsBase = t != expr.Type;
4581 bool ProbeCollectionType (EmitContext ec, Type t)
4583 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4584 if (TryType (ec, tt))
4590 // Now try to find the method in the interfaces
4593 Type [] ifaces = t.GetInterfaces ();
4595 foreach (Type i in ifaces){
4596 if (TryType (ec, i))
4601 // Since TypeBuilder.GetInterfaces only returns the interface
4602 // types for this type, we have to keep looping, but once
4603 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4604 // done, because it returns all the types
4606 if ((t is TypeBuilder))
4615 public override bool Resolve (EmitContext ec)
4617 enumerator_type = TypeManager.ienumerator_type;
4618 is_disposable = true;
4620 if (!ProbeCollectionType (ec, expr.Type)) {
4621 Error_Enumerator ();
4625 enumerator = new TemporaryVariable (enumerator_type, loc);
4626 enumerator.Resolve (ec);
4628 init = new Invocation (get_enumerator, new ArrayList ());
4629 init = init.Resolve (ec);
4633 Expression move_next_expr;
4635 MemberInfo[] mi = new MemberInfo[] { move_next };
4636 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4637 mg.InstanceExpression = enumerator;
4639 move_next_expr = new Invocation (mg, new ArrayList ());
4642 get_current.InstanceExpression = enumerator;
4644 Statement block = new CollectionForeachStatement (
4645 var_type, variable, get_current, statement, loc);
4647 loop = new While (move_next_expr, block, loc);
4651 FlowBranchingException branching = null;
4653 branching = ec.StartFlowBranching (this);
4655 if (!loop.Resolve (ec))
4658 if (is_disposable) {
4659 ResolveFinally (branching);
4660 ec.EndFlowBranching ();
4662 emit_finally = true;
4667 protected override void DoEmit (EmitContext ec)
4669 ILGenerator ig = ec.ig;
4671 enumerator.Store (ec, init);
4674 // Protect the code in a try/finalize block, so that
4675 // if the beast implement IDisposable, we get rid of it
4677 if (is_disposable && emit_finally)
4678 ig.BeginExceptionBlock ();
4683 // Now the finally block
4685 if (is_disposable) {
4688 ig.EndExceptionBlock ();
4693 public override void EmitFinally (EmitContext ec)
4695 ILGenerator ig = ec.ig;
4697 if (enumerator_type.IsValueType) {
4698 MethodInfo mi = FetchMethodDispose (enumerator_type);
4700 enumerator.EmitLoadAddress (ec);
4701 ig.Emit (OpCodes.Call, mi);
4703 enumerator.Emit (ec);
4704 ig.Emit (OpCodes.Box, enumerator_type);
4705 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4708 Label call_dispose = ig.DefineLabel ();
4710 enumerator.Emit (ec);
4711 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4712 ig.Emit (OpCodes.Dup);
4713 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4714 ig.Emit (OpCodes.Pop);
4716 Label end_finally = ig.DefineLabel ();
4717 ig.Emit (OpCodes.Br, end_finally);
4719 ig.MarkLabel (call_dispose);
4720 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4721 ig.MarkLabel (end_finally);
4726 protected class CollectionForeachStatement : Statement
4729 Expression variable, current, conv;
4730 Statement statement;
4733 public CollectionForeachStatement (Type type, Expression variable,
4734 Expression current, Statement statement,
4738 this.variable = variable;
4739 this.current = current;
4740 this.statement = statement;
4744 public override bool Resolve (EmitContext ec)
4746 current = current.Resolve (ec);
4747 if (current == null)
4750 conv = Convert.ExplicitConversion (ec, current, type, loc);
4754 assign = new Assign (variable, conv, loc);
4755 if (assign.Resolve (ec) == null)
4758 if (!statement.Resolve (ec))
4764 protected override void DoEmit (EmitContext ec)
4766 assign.EmitStatement (ec);
4767 statement.Emit (ec);