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;
18 namespace Mono.CSharp {
20 using System.Collections;
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.
49 if (warn && (RootContext.WarningLevel >= 2))
50 Report.Warning (162, loc, "Unreachable code detected");
52 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
53 bool ok = Resolve (ec);
54 ec.KillFlowBranching ();
59 protected void CheckObsolete (Type type)
61 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
62 if (obsolete_attr == null)
65 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
69 /// Return value indicates whether all code paths emitted return.
71 protected abstract void DoEmit (EmitContext ec);
74 /// Utility wrapper routine for Error, just to beautify the code
76 public void Error (int error, string format, params object[] args)
78 Error (error, String.Format (format, args));
81 public void Error (int error, string s)
83 if (!Location.IsNull (loc))
84 Report.Error (error, loc, s);
86 Report.Error (error, s);
90 /// Return value indicates whether all code paths emitted return.
92 public virtual void Emit (EmitContext ec)
99 public sealed class EmptyStatement : Statement {
101 private EmptyStatement () {}
103 public static readonly EmptyStatement Value = new EmptyStatement ();
105 public override bool Resolve (EmitContext ec)
110 protected override void DoEmit (EmitContext ec)
115 public class If : Statement {
117 public Statement TrueStatement;
118 public Statement FalseStatement;
122 public If (Expression expr, Statement trueStatement, Location l)
125 TrueStatement = trueStatement;
129 public If (Expression expr,
130 Statement trueStatement,
131 Statement falseStatement,
135 TrueStatement = trueStatement;
136 FalseStatement = falseStatement;
140 public override bool Resolve (EmitContext ec)
144 Report.Debug (1, "START IF BLOCK", loc);
146 expr = Expression.ResolveBoolean (ec, expr, loc);
152 Assign ass = expr as Assign;
153 if (ass != null && ass.Source is Constant) {
154 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
158 // Dead code elimination
160 if (expr is BoolConstant){
161 bool take = ((BoolConstant) expr).Value;
164 if (!TrueStatement.Resolve (ec))
167 if ((FalseStatement != null) &&
168 !FalseStatement.ResolveUnreachable (ec, true))
170 FalseStatement = null;
172 if (!TrueStatement.ResolveUnreachable (ec, true))
174 TrueStatement = null;
176 if ((FalseStatement != null) &&
177 !FalseStatement.Resolve (ec))
184 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
186 ok &= TrueStatement.Resolve (ec);
188 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
190 ec.CurrentBranching.CreateSibling ();
192 if (FalseStatement != null)
193 ok &= FalseStatement.Resolve (ec);
195 ec.EndFlowBranching ();
197 Report.Debug (1, "END IF BLOCK", loc);
202 protected override void DoEmit (EmitContext ec)
204 ILGenerator ig = ec.ig;
205 Label false_target = ig.DefineLabel ();
209 // If we're a boolean expression, Resolve() already
210 // eliminated dead code for us.
212 if (expr is BoolConstant){
213 bool take = ((BoolConstant) expr).Value;
216 TrueStatement.Emit (ec);
217 else if (FalseStatement != null)
218 FalseStatement.Emit (ec);
223 expr.EmitBranchable (ec, false_target, false);
225 TrueStatement.Emit (ec);
227 if (FalseStatement != null){
228 bool branch_emitted = false;
230 end = ig.DefineLabel ();
232 ig.Emit (OpCodes.Br, end);
233 branch_emitted = true;
236 ig.MarkLabel (false_target);
237 FalseStatement.Emit (ec);
242 ig.MarkLabel (false_target);
247 public class Do : Statement {
248 public Expression expr;
249 public readonly Statement EmbeddedStatement;
252 public Do (Statement statement, Expression boolExpr, Location l)
255 EmbeddedStatement = statement;
259 public override bool Resolve (EmitContext ec)
263 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
265 if (!EmbeddedStatement.Resolve (ec))
268 expr = Expression.ResolveBoolean (ec, expr, loc);
271 else if (expr is BoolConstant){
272 bool res = ((BoolConstant) expr).Value;
278 ec.CurrentBranching.Infinite = infinite;
279 ec.EndFlowBranching ();
284 protected override void DoEmit (EmitContext ec)
286 ILGenerator ig = ec.ig;
287 Label loop = ig.DefineLabel ();
288 Label old_begin = ec.LoopBegin;
289 Label old_end = ec.LoopEnd;
291 ec.LoopBegin = ig.DefineLabel ();
292 ec.LoopEnd = ig.DefineLabel ();
295 EmbeddedStatement.Emit (ec);
296 ig.MarkLabel (ec.LoopBegin);
299 // Dead code elimination
301 if (expr is BoolConstant){
302 bool res = ((BoolConstant) expr).Value;
305 ec.ig.Emit (OpCodes.Br, loop);
307 expr.EmitBranchable (ec, loop, true);
309 ig.MarkLabel (ec.LoopEnd);
311 ec.LoopBegin = old_begin;
312 ec.LoopEnd = old_end;
316 public class While : Statement {
317 public Expression expr;
318 public readonly Statement Statement;
319 bool infinite, empty;
321 public While (Expression boolExpr, Statement statement, Location l)
323 this.expr = boolExpr;
324 Statement = statement;
328 public override bool Resolve (EmitContext ec)
332 expr = Expression.ResolveBoolean (ec, expr, loc);
337 // Inform whether we are infinite or not
339 if (expr is BoolConstant){
340 BoolConstant bc = (BoolConstant) expr;
342 if (bc.Value == false){
343 if (!Statement.ResolveUnreachable (ec, true))
351 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
353 ec.CurrentBranching.CreateSibling ();
355 if (!Statement.Resolve (ec))
358 ec.CurrentBranching.Infinite = infinite;
359 ec.EndFlowBranching ();
364 protected override void DoEmit (EmitContext ec)
369 ILGenerator ig = ec.ig;
370 Label old_begin = ec.LoopBegin;
371 Label old_end = ec.LoopEnd;
373 ec.LoopBegin = ig.DefineLabel ();
374 ec.LoopEnd = ig.DefineLabel ();
377 // Inform whether we are infinite or not
379 if (expr is BoolConstant){
380 ig.MarkLabel (ec.LoopBegin);
382 ig.Emit (OpCodes.Br, ec.LoopBegin);
385 // Inform that we are infinite (ie, `we return'), only
386 // if we do not `break' inside the code.
388 ig.MarkLabel (ec.LoopEnd);
390 Label while_loop = ig.DefineLabel ();
392 ig.Emit (OpCodes.Br, ec.LoopBegin);
393 ig.MarkLabel (while_loop);
397 ig.MarkLabel (ec.LoopBegin);
399 expr.EmitBranchable (ec, while_loop, true);
401 ig.MarkLabel (ec.LoopEnd);
404 ec.LoopBegin = old_begin;
405 ec.LoopEnd = old_end;
409 public class For : Statement {
411 readonly Statement InitStatement;
412 readonly Statement Increment;
413 readonly Statement Statement;
414 bool infinite, empty;
416 public For (Statement initStatement,
422 InitStatement = initStatement;
424 Increment = increment;
425 Statement = statement;
429 public override bool Resolve (EmitContext ec)
433 if (InitStatement != null){
434 if (!InitStatement.Resolve (ec))
439 Test = Expression.ResolveBoolean (ec, Test, loc);
442 else if (Test is BoolConstant){
443 BoolConstant bc = (BoolConstant) Test;
445 if (bc.Value == false){
446 if (!Statement.ResolveUnreachable (ec, true))
448 if ((Increment != null) &&
449 !Increment.ResolveUnreachable (ec, false))
459 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
461 ec.CurrentBranching.CreateSibling ();
463 if (!Statement.Resolve (ec))
466 if (Increment != null){
467 if (!Increment.Resolve (ec))
471 ec.CurrentBranching.Infinite = infinite;
472 ec.EndFlowBranching ();
477 protected override void DoEmit (EmitContext ec)
482 ILGenerator ig = ec.ig;
483 Label old_begin = ec.LoopBegin;
484 Label old_end = ec.LoopEnd;
485 Label loop = ig.DefineLabel ();
486 Label test = ig.DefineLabel ();
488 if (InitStatement != null && InitStatement != EmptyStatement.Value)
489 InitStatement.Emit (ec);
491 ec.LoopBegin = ig.DefineLabel ();
492 ec.LoopEnd = ig.DefineLabel ();
494 ig.Emit (OpCodes.Br, test);
498 ig.MarkLabel (ec.LoopBegin);
499 if (Increment != EmptyStatement.Value)
504 // If test is null, there is no test, and we are just
509 // The Resolve code already catches the case for
510 // Test == BoolConstant (false) so we know that
513 if (Test is BoolConstant)
514 ig.Emit (OpCodes.Br, loop);
516 Test.EmitBranchable (ec, loop, true);
519 ig.Emit (OpCodes.Br, loop);
520 ig.MarkLabel (ec.LoopEnd);
522 ec.LoopBegin = old_begin;
523 ec.LoopEnd = old_end;
527 public class StatementExpression : Statement {
528 ExpressionStatement expr;
530 public StatementExpression (ExpressionStatement expr, Location l)
536 public override bool Resolve (EmitContext ec)
539 expr = expr.ResolveStatement (ec);
543 protected override void DoEmit (EmitContext ec)
545 expr.EmitStatement (ec);
548 public override string ToString ()
550 return "StatementExpression (" + expr + ")";
555 /// Implements the return statement
557 public class Return : Statement {
558 public Expression Expr;
560 public Return (Expression expr, Location l)
568 public override bool Resolve (EmitContext ec)
570 if (ec.ReturnType == null){
572 if (ec.CurrentAnonymousMethod != null){
573 Report.Error (1662, loc, String.Format (
574 "Anonymous method could not be converted to delegate " +
575 "since the return value does not match the delegate value"));
577 Error (127, "Return with a value not allowed here");
582 Error (126, "An object of type `{0}' is expected " +
583 "for the return statement",
584 TypeManager.CSharpName (ec.ReturnType));
589 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
590 "statement to return a value, or yield break to end the iteration");
594 Expr = Expr.Resolve (ec);
598 if (Expr.Type != ec.ReturnType) {
599 Expr = Convert.ImplicitConversionRequired (
600 ec, Expr, ec.ReturnType, loc);
607 Error (-206, "Return statement not allowed inside iterators");
611 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
613 if (ec.CurrentBranching.InTryOrCatch (true)) {
614 ec.CurrentBranching.AddFinallyVector (vector);
616 } else if (ec.InFinally) {
617 Error (157, "Control can not leave the body of the finally block");
620 vector.CheckOutParameters (ec.CurrentBranching);
623 ec.NeedReturnLabel ();
625 ec.CurrentBranching.CurrentUsageVector.Return ();
629 protected override void DoEmit (EmitContext ec)
635 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
639 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
641 ec.ig.Emit (OpCodes.Ret);
645 public class Goto : Statement {
647 LabeledStatement label;
649 public override bool Resolve (EmitContext ec)
651 label = ec.CurrentBranching.LookupLabel (target, loc);
655 // If this is a forward goto.
656 if (!label.IsDefined)
657 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
659 ec.CurrentBranching.CurrentUsageVector.Goto ();
660 label.AddReference ();
665 public Goto (string label, Location l)
671 public string Target {
677 protected override void DoEmit (EmitContext ec)
679 Label l = label.LabelTarget (ec);
680 ec.ig.Emit (OpCodes.Br, l);
684 public class LabeledStatement : Statement {
685 public readonly Location Location;
691 FlowBranching.UsageVector vectors;
693 public LabeledStatement (string label_name, Location l)
698 public Label LabelTarget (EmitContext ec)
703 label = ec.ig.DefineLabel ();
709 public bool IsDefined {
715 public bool HasBeenReferenced {
721 public void AddUsageVector (FlowBranching.UsageVector vector)
723 vector = vector.Clone ();
724 vector.Next = vectors;
728 public override bool Resolve (EmitContext ec)
730 ec.CurrentBranching.Label (vectors);
735 protected override void DoEmit (EmitContext ec)
737 if (ig != null && ig != ec.ig) {
738 Report.Error (1632, "Control cannot leave body of anonymous method");
742 ec.ig.MarkLabel (label);
745 public void AddReference ()
753 /// `goto default' statement
755 public class GotoDefault : Statement {
757 public GotoDefault (Location l)
762 public override bool Resolve (EmitContext ec)
764 ec.CurrentBranching.CurrentUsageVector.Goto ();
768 protected override void DoEmit (EmitContext ec)
770 if (ec.Switch == null){
771 Report.Error (153, loc, "goto default is only valid in a switch statement");
775 if (!ec.Switch.GotDefault){
776 Report.Error (159, loc, "No default target on switch statement");
779 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
784 /// `goto case' statement
786 public class GotoCase : Statement {
790 public GotoCase (Expression e, Location l)
796 public override bool Resolve (EmitContext ec)
798 if (ec.Switch == null){
799 Report.Error (153, loc, "goto case is only valid in a switch statement");
803 expr = expr.Resolve (ec);
807 if (!(expr is Constant)){
808 Report.Error (159, loc, "Target expression for goto case is not constant");
812 object val = Expression.ConvertIntLiteral (
813 (Constant) expr, ec.Switch.SwitchType, loc);
818 sl = (SwitchLabel) ec.Switch.Elements [val];
823 "No such label 'case " + val + "': for the goto case");
827 ec.CurrentBranching.CurrentUsageVector.Goto ();
831 protected override void DoEmit (EmitContext ec)
833 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
837 public class Throw : Statement {
840 public Throw (Expression expr, Location l)
846 public override bool Resolve (EmitContext ec)
848 ec.CurrentBranching.CurrentUsageVector.Throw ();
851 expr = expr.Resolve (ec);
855 ExprClass eclass = expr.eclass;
857 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
858 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
859 expr.Error_UnexpectedKind ("value, variable, property or indexer access ", loc);
865 if ((t != TypeManager.exception_type) &&
866 !t.IsSubclassOf (TypeManager.exception_type) &&
867 !(expr is NullLiteral)) {
869 "The type caught or thrown must be derived " +
870 "from System.Exception");
877 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
882 Error (724, "A throw statement with no argument is only allowed in a catch clause nested inside of the innermost catch clause");
888 protected override void DoEmit (EmitContext ec)
891 ec.ig.Emit (OpCodes.Rethrow);
895 ec.ig.Emit (OpCodes.Throw);
900 public class Break : Statement {
902 public Break (Location l)
909 public override bool Resolve (EmitContext ec)
911 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
912 Error (139, "No enclosing loop or switch to continue to");
914 } else if (ec.InFinally && ec.CurrentBranching.BreakCrossesTryCatchBoundary()) {
915 Error (157, "Control can not leave the body of the finally block");
917 } else if (ec.CurrentBranching.InTryOrCatch (false))
918 ec.CurrentBranching.AddFinallyVector (
919 ec.CurrentBranching.CurrentUsageVector);
920 else if (ec.CurrentBranching.InLoop ())
921 ec.CurrentBranching.AddBreakVector (
922 ec.CurrentBranching.CurrentUsageVector);
924 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
927 ec.NeedReturnLabel ();
929 ec.CurrentBranching.CurrentUsageVector.Break ();
933 protected override void DoEmit (EmitContext ec)
935 ILGenerator ig = ec.ig;
938 ig.Emit (OpCodes.Leave, ec.LoopEnd);
940 ig.Emit (OpCodes.Br, ec.LoopEnd);
945 public class Continue : Statement {
947 public Continue (Location l)
954 public override bool Resolve (EmitContext ec)
956 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
957 Error (139, "No enclosing loop to continue to");
959 } else if (ec.InFinally) {
960 Error (157, "Control can not leave the body of the finally block");
962 } else if (ec.CurrentBranching.InTryOrCatch (false))
963 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
965 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
967 ec.CurrentBranching.CurrentUsageVector.Goto ();
971 protected override void DoEmit (EmitContext ec)
973 Label begin = ec.LoopBegin;
976 ec.ig.Emit (OpCodes.Leave, begin);
978 ec.ig.Emit (OpCodes.Br, begin);
983 // The information about a user-perceived local variable
985 public class LocalInfo {
986 public Expression Type;
989 // Most of the time a variable will be stored in a LocalBuilder
991 // But sometimes, it will be stored in a field (variables that have been
992 // hoisted by iterators or by anonymous methods). The context of the field will
993 // be stored in the EmitContext
996 public LocalBuilder LocalBuilder;
997 public FieldBuilder FieldBuilder;
999 public Type VariableType;
1000 public readonly string Name;
1001 public readonly Location Location;
1002 public readonly Block Block;
1004 public VariableInfo VariableInfo;
1017 public LocalInfo (Expression type, string name, Block block, Location l)
1025 public LocalInfo (TypeContainer tc, Block block, Location l)
1027 VariableType = tc.TypeBuilder;
1032 public bool IsThisAssigned (EmitContext ec, Location loc)
1034 if (VariableInfo == null)
1035 throw new Exception ();
1037 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1040 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1043 public bool IsAssigned (EmitContext ec)
1045 if (VariableInfo == null)
1046 throw new Exception ();
1048 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1051 public bool Resolve (EmitContext ec)
1053 if (VariableType == null) {
1054 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
1058 VariableType = texpr.Type;
1061 if (VariableType == TypeManager.void_type) {
1062 Report.Error (1547, Location,
1063 "Keyword 'void' cannot be used in this context");
1067 if (VariableType.IsAbstract && VariableType.IsSealed) {
1068 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1071 // TODO: breaks the build
1072 // if (VariableType.IsPointer && !ec.InUnsafe)
1073 // Expression.UnsafeError (Location);
1079 // Whether the variable is Fixed (because its Pinned or its a value type)
1081 public bool IsFixed {
1083 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1090 public bool IsCaptured {
1092 return (flags & Flags.Captured) != 0;
1096 flags |= Flags.Captured;
1100 public bool AddressTaken {
1102 return (flags & Flags.AddressTaken) != 0;
1106 flags |= Flags.AddressTaken;
1110 public override string ToString ()
1112 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1113 Name, Type, VariableInfo, Location);
1118 return (flags & Flags.Used) != 0;
1121 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1125 public bool ReadOnly {
1127 return (flags & Flags.ReadOnly) != 0;
1130 flags = value ? (flags | Flags.ReadOnly) : (unchecked (flags & ~Flags.ReadOnly));
1135 // Whether the variable is pinned, if Pinned the variable has been
1136 // allocated in a pinned slot with DeclareLocal.
1138 public bool Pinned {
1140 return (flags & Flags.Pinned) != 0;
1143 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1147 public bool IsThis {
1149 return (flags & Flags.IsThis) != 0;
1152 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1158 /// Block represents a C# block.
1162 /// This class is used in a number of places: either to represent
1163 /// explicit blocks that the programmer places or implicit blocks.
1165 /// Implicit blocks are used as labels or to introduce variable
1168 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1169 /// they contain extra information that is not necessary on normal blocks.
1171 public class Block : Statement {
1172 public Block Parent;
1173 public readonly Location StartLocation;
1174 public Location EndLocation = Location.Null;
1176 public readonly ToplevelBlock Toplevel;
1183 VariablesInitialized = 8,
1192 public bool Implicit {
1194 return (flags & Flags.Implicit) != 0;
1198 public bool Unchecked {
1200 return (flags & Flags.Unchecked) != 0;
1203 flags |= Flags.Unchecked;
1207 public bool Unsafe {
1209 return (flags & Flags.Unsafe) != 0;
1212 flags |= Flags.Unsafe;
1216 public bool HasVarargs {
1219 return Parent.HasVarargs;
1221 return (flags & Flags.HasVarargs) != 0;
1224 flags |= Flags.HasVarargs;
1229 // The statements in this block
1231 ArrayList statements;
1235 // An array of Blocks. We keep track of children just
1236 // to generate the local variable declarations.
1238 // Statements and child statements are handled through the
1244 // Labels. (label, block) pairs.
1249 // Keeps track of (name, type) pairs
1251 Hashtable variables;
1254 // Keeps track of constants
1255 Hashtable constants;
1258 // If this is a switch section, the enclosing switch block.
1262 protected static int id;
1266 public Block (Block parent)
1267 : this (parent, (Flags) 0, Location.Null, Location.Null)
1270 public Block (Block parent, Flags flags)
1271 : this (parent, flags, Location.Null, Location.Null)
1274 public Block (Block parent, Location start, Location end)
1275 : this (parent, (Flags) 0, start, end)
1278 public Block (Block parent, Flags flags, Location start, Location end)
1281 parent.AddChild (this);
1283 this.Parent = parent;
1285 this.StartLocation = start;
1286 this.EndLocation = end;
1289 statements = new ArrayList ();
1291 if ((flags & Flags.IsToplevel) != 0)
1292 Toplevel = (ToplevelBlock) this;
1294 Toplevel = parent.Toplevel;
1296 if (parent != null && Implicit) {
1297 if (parent.known_variables == null)
1298 parent.known_variables = new Hashtable ();
1299 // share with parent
1300 known_variables = parent.known_variables;
1305 public Block CreateSwitchBlock (Location start)
1307 Block new_block = new Block (this, start, start);
1308 new_block.switch_block = this;
1318 void AddChild (Block b)
1320 if (children == null)
1321 children = new ArrayList ();
1326 public void SetEndLocation (Location loc)
1332 /// Adds a label to the current block.
1336 /// false if the name already exists in this block. true
1340 public bool AddLabel (string name, LabeledStatement target, Location loc)
1342 if (switch_block != null)
1343 return switch_block.AddLabel (name, target, loc);
1346 while (cur != null) {
1347 if (cur.DoLookupLabel (name) != null) {
1349 140, loc, "The label '{0}' is a duplicate",
1360 while (cur != null) {
1361 if (cur.DoLookupLabel (name) != null) {
1364 "The label '{0}' shadows another label " +
1365 "by the same name in a containing scope.",
1370 if (children != null) {
1371 foreach (Block b in children) {
1372 LabeledStatement s = b.DoLookupLabel (name);
1378 "The label '{0}' shadows another " +
1379 "label by the same name in a " +
1380 "containing scope.",
1391 labels = new Hashtable ();
1393 labels.Add (name, target);
1397 public LabeledStatement LookupLabel (string name)
1399 LabeledStatement s = DoLookupLabel (name);
1403 if (children == null)
1406 foreach (Block child in children) {
1407 if (!child.Implicit)
1410 s = child.LookupLabel (name);
1418 LabeledStatement DoLookupLabel (string name)
1420 if (switch_block != null)
1421 return switch_block.LookupLabel (name);
1424 if (labels.Contains (name))
1425 return ((LabeledStatement) labels [name]);
1430 LocalInfo this_variable = null;
1433 // Returns the "this" instance variable of this block.
1434 // See AddThisVariable() for more information.
1436 public LocalInfo ThisVariable {
1438 for (Block b = this; b != null; b = b.Parent) {
1439 if (b.this_variable != null)
1440 return b.this_variable;
1447 Hashtable known_variables;
1450 // Marks a variable with name @name as being used in this or a child block.
1451 // If a variable name has been used in a child block, it's illegal to
1452 // declare a variable with the same name in the current block.
1454 void AddKnownVariable (string name, LocalInfo info)
1456 if (known_variables == null)
1457 known_variables = new Hashtable ();
1459 known_variables [name] = info;
1462 LocalInfo GetKnownVariableInfo (string name)
1464 if (known_variables == null)
1466 return (LocalInfo) known_variables [name];
1469 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1471 LocalInfo kvi = GetKnownVariableInfo (name);
1472 if (kvi == null || kvi.Block == this)
1475 if (known_variables != kvi.Block.known_variables) {
1476 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1477 Report.Error (135, loc, "'{0}' has a different meaning in a child block", name);
1482 // this block and kvi.Block are the same textual block.
1483 // However, different variables are extant.
1485 // Check if the variable is in scope in both blocks. We use
1486 // an indirect check that depends on AddVariable doing its
1487 // part in maintaining the invariant-meaning-in-block property.
1489 if (e is LocalVariableReference || (e is Constant && GetLocalInfo (name) != null))
1492 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1493 Report.Error (136, loc, "'{0}' has a different meaning later in the block", name);
1498 // This is used by non-static `struct' constructors which do not have an
1499 // initializer - in this case, the constructor must initialize all of the
1500 // struct's fields. To do this, we add a "this" variable and use the flow
1501 // analysis code to ensure that it's been fully initialized before control
1502 // leaves the constructor.
1504 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1506 if (this_variable != null)
1507 return this_variable;
1509 if (variables == null)
1510 variables = new Hashtable ();
1512 this_variable = new LocalInfo (tc, this, l);
1513 this_variable.Used = true;
1514 this_variable.IsThis = true;
1516 variables.Add ("this", this_variable);
1518 return this_variable;
1521 public LocalInfo AddVariable (Expression type, string name, Location l)
1523 if (variables == null)
1524 variables = new Hashtable ();
1526 LocalInfo vi = GetLocalInfo (name);
1528 Report.SymbolRelatedToPreviousError (vi.Location, name);
1529 if (known_variables == vi.Block.known_variables)
1530 Report.Error (128, l,
1531 "A local variable '{0}' is already declared in this scope", name);
1533 Report.Error (136, l,
1534 "'{0}' hides the declaration of local variable '{0}' in a parent scope", name);
1538 vi = GetKnownVariableInfo (name);
1540 Report.SymbolRelatedToPreviousError (vi.Location, name);
1541 Report.Error (136, l,
1542 "A child block already has a declaration of local variable '{0}':" +
1543 " allowing this declaration would violate 'invariant meaning in a block'",
1549 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1551 Report.SymbolRelatedToPreviousError (Toplevel.Parameters.Location, name);
1552 Report.Error (136, l, "'{0}' hides a method parameter", name);
1556 vi = new LocalInfo (type, name, this, l);
1558 variables.Add (name, vi);
1560 for (Block b = this; b != null; b = b.Parent)
1561 b.AddKnownVariable (name, vi);
1563 if ((flags & Flags.VariablesInitialized) != 0)
1564 throw new Exception ();
1566 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1570 public bool AddConstant (Expression type, string name, Expression value, Location l)
1572 if (AddVariable (type, name, l) == null)
1575 if (constants == null)
1576 constants = new Hashtable ();
1578 constants.Add (name, value);
1582 public Hashtable Variables {
1588 public LocalInfo GetLocalInfo (string name)
1590 for (Block b = this; b != null; b = b.Parent) {
1591 if (b.variables != null) {
1592 LocalInfo ret = b.variables [name] as LocalInfo;
1600 public Expression GetVariableType (string name)
1602 LocalInfo vi = GetLocalInfo (name);
1610 public Expression GetConstantExpression (string name)
1612 for (Block b = this; b != null; b = b.Parent) {
1613 if (b.constants != null) {
1614 Expression ret = b.constants [name] as Expression;
1623 /// True if the variable named @name is a constant
1625 public bool IsConstant (string name)
1627 Expression e = null;
1629 e = GetConstantExpression (name);
1635 // Returns a `ParameterReference' for the given name, or null if there
1636 // is no such parameter
1638 public ParameterReference GetParameterReference (string name, Location loc)
1643 for (Block b = this; b != null; b = b.Toplevel.Parent) {
1644 Parameters pars = b.Toplevel.Parameters;
1645 par = pars.GetParameterByName (name, out idx);
1647 return new ParameterReference (pars, this, idx, name, loc);
1653 // Whether the parameter named `name' is local to this block,
1654 // or false, if the parameter belongs to an encompassing block.
1656 public bool IsLocalParameter (string name)
1658 return Toplevel.Parameters.GetParameterByName (name) != null;
1662 // Whether the `name' is a parameter reference
1664 public bool IsParameterReference (string name)
1669 for (Block b = this; b != null; b = b.Toplevel.Parent) {
1670 par = b.Toplevel.Parameters.GetParameterByName (name, out idx);
1678 /// A list of labels that were not used within this block
1680 public string [] GetUnreferenced ()
1682 // FIXME: Implement me
1686 public void AddStatement (Statement s)
1689 flags |= Flags.BlockUsed;
1694 return (flags & Flags.BlockUsed) != 0;
1700 flags |= Flags.BlockUsed;
1703 public bool HasRet {
1705 return (flags & Flags.HasRet) != 0;
1709 public bool IsDestructor {
1711 return (flags & Flags.IsDestructor) != 0;
1715 public void SetDestructor ()
1717 flags |= Flags.IsDestructor;
1720 VariableMap param_map, local_map;
1722 public VariableMap ParameterMap {
1724 if ((flags & Flags.VariablesInitialized) == 0)
1725 throw new Exception ("Variables have not been initialized yet");
1731 public VariableMap LocalMap {
1733 if ((flags & Flags.VariablesInitialized) == 0)
1734 throw new Exception ("Variables have not been initialized yet");
1741 /// Emits the variable declarations and labels.
1744 /// tc: is our typecontainer (to resolve type references)
1745 /// ig: is the code generator:
1747 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1749 bool old_unsafe = ec.InUnsafe;
1751 // If some parent block was unsafe, we remain unsafe even if this block
1752 // isn't explicitly marked as such.
1753 ec.InUnsafe |= Unsafe;
1756 // Compute the VariableMap's.
1758 // Unfortunately, we don't know the type when adding variables with
1759 // AddVariable(), so we need to compute this info here.
1763 if (variables != null) {
1764 foreach (LocalInfo li in variables.Values)
1767 locals = new LocalInfo [variables.Count];
1768 variables.Values.CopyTo (locals, 0);
1770 locals = new LocalInfo [0];
1773 local_map = new VariableMap (Parent.LocalMap, locals);
1775 local_map = new VariableMap (locals);
1777 param_map = new VariableMap (ip);
1778 flags |= Flags.VariablesInitialized;
1780 bool old_check_state = ec.ConstantCheckState;
1781 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1784 // Process this block variables
1786 if (variables != null){
1787 foreach (DictionaryEntry de in variables){
1788 string name = (string) de.Key;
1789 LocalInfo vi = (LocalInfo) de.Value;
1791 if (vi.VariableType == null)
1794 Type variable_type = vi.VariableType;
1796 if (variable_type.IsPointer){
1798 // Am not really convinced that this test is required (Microsoft does it)
1799 // but the fact is that you would not be able to use the pointer variable
1802 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1809 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1812 // This is needed to compile on both .NET 1.x and .NET 2.x
1813 // the later introduced `DeclareLocal (Type t, bool pinned)'
1815 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1816 else if (!vi.IsThis)
1817 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1820 if (constants == null)
1823 Expression cv = (Expression) constants [name];
1827 ec.CurrentBlock = this;
1828 Expression e = cv.Resolve (ec);
1830 Constant ce = e as Constant;
1832 Report.Error (133, vi.Location,
1833 "The expression being assigned to '{0}' must be constant", name);
1837 if (e.Type != variable_type){
1838 e = Const.ChangeType (vi.Location, ce, variable_type);
1843 constants.Remove (name);
1844 constants.Add (name, e);
1847 ec.ConstantCheckState = old_check_state;
1850 // Now, handle the children
1852 if (children != null){
1853 foreach (Block b in children)
1854 b.ResolveMeta (toplevel, ec, ip);
1856 ec.InUnsafe = old_unsafe;
1860 // Emits the local variable declarations for a block
1862 public void EmitMeta (EmitContext ec)
1864 ILGenerator ig = ec.ig;
1866 if (variables != null){
1867 bool have_captured_vars = ec.HaveCapturedVariables ();
1868 bool remap_locals = ec.RemapToProxy;
1870 foreach (DictionaryEntry de in variables){
1871 LocalInfo vi = (LocalInfo) de.Value;
1873 if (have_captured_vars && ec.IsCaptured (vi))
1877 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1881 // This is needed to compile on both .NET 1.x and .NET 2.x
1882 // the later introduced `DeclareLocal (Type t, bool pinned)'
1884 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1885 else if (!vi.IsThis)
1886 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1891 if (children != null){
1892 foreach (Block b in children)
1897 void UsageWarning (FlowBranching.UsageVector vector)
1901 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1902 foreach (DictionaryEntry de in variables){
1903 LocalInfo vi = (LocalInfo) de.Value;
1908 name = (string) de.Key;
1910 if (vector.IsAssigned (vi.VariableInfo)){
1911 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1913 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1919 bool unreachable_shown;
1921 public override bool Resolve (EmitContext ec)
1923 Block prev_block = ec.CurrentBlock;
1926 int errors = Report.Errors;
1928 ec.CurrentBlock = this;
1929 ec.StartFlowBranching (this);
1931 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1934 // This flag is used to notate nested statements as unreachable from the beginning of this block.
1935 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
1936 // from the beginning of the function. The outer Resolve() that detected the unreachability is
1937 // responsible for handling the situation.
1939 bool unreachable = false;
1941 int statement_count = statements.Count;
1942 for (int ix = 0; ix < statement_count; ix++){
1943 Statement s = (Statement) statements [ix];
1945 if (unreachable && !(s is LabeledStatement)) {
1946 if (s == EmptyStatement.Value)
1947 s.loc = EndLocation;
1949 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1952 if (s != EmptyStatement.Value)
1953 unreachable_shown = true;
1955 s.loc = Location.Null;
1957 if (ok && !(s is Block)) {
1958 statements [ix] = EmptyStatement.Value;
1963 if (s.Resolve (ec) == false) {
1965 statements [ix] = EmptyStatement.Value;
1969 num_statements = ix + 1;
1971 if (s is LabeledStatement)
1972 unreachable = false;
1974 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1977 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1978 ec.CurrentBranching, statement_count, num_statements);
1981 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1983 ec.CurrentBlock = prev_block;
1985 // If we're a non-static `struct' constructor which doesn't have an
1986 // initializer, then we must initialize all of the struct's fields.
1987 if ((this_variable != null) &&
1988 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1989 !this_variable.IsThisAssigned (ec, loc))
1992 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1993 foreach (LabeledStatement label in labels.Values)
1994 if (!label.HasBeenReferenced)
1995 Report.Warning (164, label.Location,
1996 "This label has not been referenced");
1999 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2001 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2002 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2003 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2004 flags |= Flags.HasRet;
2006 if (ok && (errors == Report.Errors)) {
2007 if (RootContext.WarningLevel >= 3)
2008 UsageWarning (vector);
2014 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2016 unreachable_shown = true;
2018 if (warn && (RootContext.WarningLevel >= 2))
2019 Report.Warning (162, loc, "Unreachable code detected");
2022 return Resolve (ec);
2024 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2025 bool ok = Resolve (ec);
2026 ec.KillFlowBranching ();
2031 protected override void DoEmit (EmitContext ec)
2033 for (int ix = 0; ix < num_statements; ix++){
2034 Statement s = (Statement) statements [ix];
2036 // Check whether we are the last statement in a
2039 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2040 ec.IsLastStatement = true;
2042 ec.IsLastStatement = false;
2048 public override void Emit (EmitContext ec)
2050 Block prev_block = ec.CurrentBlock;
2052 ec.CurrentBlock = this;
2054 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2055 bool is_lexical_block = !Implicit && (Parent != null);
2057 if (emit_debug_info) {
2058 if (is_lexical_block)
2061 if (variables != null) {
2062 foreach (DictionaryEntry de in variables) {
2063 string name = (string) de.Key;
2064 LocalInfo vi = (LocalInfo) de.Value;
2066 if (vi.LocalBuilder == null)
2069 ec.DefineLocalVariable (name, vi.LocalBuilder);
2074 ec.Mark (StartLocation, true);
2076 ec.Mark (EndLocation, true);
2078 if (emit_debug_info && is_lexical_block)
2081 ec.CurrentBlock = prev_block;
2085 // Returns true if we ar ea child of `b'.
2087 public bool IsChildOf (Block b)
2089 Block current = this;
2092 if (current.Parent == b)
2094 current = current.Parent;
2095 } while (current != null);
2099 public override string ToString ()
2101 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2106 // A toplevel block contains extra information, the split is done
2107 // only to separate information that would otherwise bloat the more
2108 // lightweight Block.
2110 // In particular, this was introduced when the support for Anonymous
2111 // Methods was implemented.
2113 public class ToplevelBlock : Block {
2115 // Pointer to the host of this anonymous method, or null
2116 // if we are the topmost block
2118 public ToplevelBlock Container;
2119 CaptureContext capture_context;
2120 FlowBranching top_level_branching;
2122 Hashtable capture_contexts;
2125 // The parameters for the block.
2127 public readonly Parameters Parameters;
2129 public void RegisterCaptureContext (CaptureContext cc)
2131 if (capture_contexts == null)
2132 capture_contexts = new Hashtable ();
2133 capture_contexts [cc] = cc;
2136 public void CompleteContexts ()
2138 if (capture_contexts == null)
2141 foreach (CaptureContext cc in capture_contexts.Keys){
2146 public CaptureContext ToplevelBlockCaptureContext {
2148 return capture_context;
2153 // Parent is only used by anonymous blocks to link back to their
2156 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2157 this (container, (Flags) 0, parameters, start)
2161 public ToplevelBlock (Parameters parameters, Location start) :
2162 this (null, (Flags) 0, parameters, start)
2166 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2167 this (null, flags, parameters, start)
2171 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2172 base (null, flags | Flags.IsToplevel, start, Location.Null)
2174 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2175 Container = container;
2178 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2182 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2184 if (capture_context == null)
2185 capture_context = new CaptureContext (this, loc, host);
2188 public CaptureContext CaptureContext {
2190 return capture_context;
2194 public FlowBranching TopLevelBranching {
2196 return top_level_branching;
2200 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2202 int errors = Report.Errors;
2204 if (top_level_branching != null)
2207 ResolveMeta (this, ec, ip);
2209 top_level_branching = ec.StartFlowBranching (this);
2211 return Report.Errors == errors;
2215 public class SwitchLabel {
2218 public Location loc;
2222 Label il_label_code;
2223 bool il_label_code_set;
2226 // if expr == null, then it is the default case.
2228 public SwitchLabel (Expression expr, Location l)
2234 public Expression Label {
2240 public object Converted {
2246 public Label GetILLabel (EmitContext ec)
2249 il_label = ec.ig.DefineLabel ();
2250 il_label_set = true;
2255 public Label GetILLabelCode (EmitContext ec)
2257 if (!il_label_code_set){
2258 il_label_code = ec.ig.DefineLabel ();
2259 il_label_code_set = true;
2261 return il_label_code;
2265 // Resolves the expression, reduces it to a literal if possible
2266 // and then converts it to the requested type.
2268 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2273 Expression e = label.Resolve (ec);
2278 if (!(e is Constant)){
2279 Report.Error (150, loc, "A constant value is expected, got: " + e);
2283 if (e is StringConstant || e is NullLiteral){
2284 if (required_type == TypeManager.string_type){
2290 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2291 if (converted == null)
2298 public class SwitchSection {
2299 // An array of SwitchLabels.
2300 public readonly ArrayList Labels;
2301 public readonly Block Block;
2303 public SwitchSection (ArrayList labels, Block block)
2310 public class Switch : Statement {
2311 public readonly ArrayList Sections;
2312 public Expression Expr;
2315 /// Maps constants whose type type SwitchType to their SwitchLabels.
2317 public Hashtable Elements;
2320 /// The governing switch type
2322 public Type SwitchType;
2327 Label default_target;
2328 Expression new_expr;
2330 SwitchSection constant_section;
2331 SwitchSection default_section;
2334 // The types allowed to be implicitly cast from
2335 // on the governing type
2337 static Type [] allowed_types;
2339 public Switch (Expression e, ArrayList sects, Location l)
2346 public bool GotDefault {
2348 return default_section != null;
2352 public Label DefaultTarget {
2354 return default_target;
2359 // Determines the governing type for a switch. The returned
2360 // expression might be the expression from the switch, or an
2361 // expression that includes any potential conversions to the
2362 // integral types or to string.
2364 Expression SwitchGoverningType (EmitContext ec, Type t)
2366 if (t == TypeManager.int32_type ||
2367 t == TypeManager.uint32_type ||
2368 t == TypeManager.char_type ||
2369 t == TypeManager.byte_type ||
2370 t == TypeManager.sbyte_type ||
2371 t == TypeManager.ushort_type ||
2372 t == TypeManager.short_type ||
2373 t == TypeManager.uint64_type ||
2374 t == TypeManager.int64_type ||
2375 t == TypeManager.string_type ||
2376 t == TypeManager.bool_type ||
2377 t.IsSubclassOf (TypeManager.enum_type))
2380 if (allowed_types == null){
2381 allowed_types = new Type [] {
2382 TypeManager.int32_type,
2383 TypeManager.uint32_type,
2384 TypeManager.sbyte_type,
2385 TypeManager.byte_type,
2386 TypeManager.short_type,
2387 TypeManager.ushort_type,
2388 TypeManager.int64_type,
2389 TypeManager.uint64_type,
2390 TypeManager.char_type,
2391 TypeManager.bool_type,
2392 TypeManager.string_type
2397 // Try to find a *user* defined implicit conversion.
2399 // If there is no implicit conversion, or if there are multiple
2400 // conversions, we have to report an error
2402 Expression converted = null;
2403 foreach (Type tt in allowed_types){
2406 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2411 // Ignore over-worked ImplicitUserConversions that do
2412 // an implicit conversion in addition to the user conversion.
2415 UserCast ue = e as UserCast;
2417 if (ue.Source != Expr)
2421 if (converted != null){
2422 Report.ExtraInformation (
2424 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2425 TypeManager.CSharpName (Expr.Type)));
2434 static string Error152 {
2436 return "The label '{0}:' already occurs in this switch statement";
2441 // Performs the basic sanity checks on the switch statement
2442 // (looks for duplicate keys and non-constant expressions).
2444 // It also returns a hashtable with the keys that we will later
2445 // use to compute the switch tables
2447 bool CheckSwitch (EmitContext ec)
2451 Elements = new Hashtable ();
2453 if (TypeManager.IsEnumType (SwitchType)){
2454 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2456 compare_type = SwitchType;
2458 foreach (SwitchSection ss in Sections){
2459 foreach (SwitchLabel sl in ss.Labels){
2460 if (!sl.ResolveAndReduce (ec, SwitchType)){
2465 if (sl.Label == null){
2466 if (default_section != null){
2467 Report.Error (152, sl.loc, Error152, "default");
2470 default_section = ss;
2474 object key = sl.Converted;
2476 if (key is Constant)
2477 key = ((Constant) key).GetValue ();
2480 key = NullLiteral.Null;
2482 string lname = null;
2483 if (compare_type == TypeManager.uint64_type){
2484 ulong v = (ulong) key;
2486 if (Elements.Contains (v))
2487 lname = v.ToString ();
2489 Elements.Add (v, sl);
2490 } else if (compare_type == TypeManager.int64_type){
2491 long v = (long) key;
2493 if (Elements.Contains (v))
2494 lname = v.ToString ();
2496 Elements.Add (v, sl);
2497 } else if (compare_type == TypeManager.uint32_type){
2498 uint v = (uint) key;
2500 if (Elements.Contains (v))
2501 lname = v.ToString ();
2503 Elements.Add (v, sl);
2504 } else if (compare_type == TypeManager.char_type){
2505 char v = (char) key;
2507 if (Elements.Contains (v))
2508 lname = v.ToString ();
2510 Elements.Add (v, sl);
2511 } else if (compare_type == TypeManager.byte_type){
2512 byte v = (byte) key;
2514 if (Elements.Contains (v))
2515 lname = v.ToString ();
2517 Elements.Add (v, sl);
2518 } else if (compare_type == TypeManager.sbyte_type){
2519 sbyte v = (sbyte) key;
2521 if (Elements.Contains (v))
2522 lname = v.ToString ();
2524 Elements.Add (v, sl);
2525 } else if (compare_type == TypeManager.short_type){
2526 short v = (short) key;
2528 if (Elements.Contains (v))
2529 lname = v.ToString ();
2531 Elements.Add (v, sl);
2532 } else if (compare_type == TypeManager.ushort_type){
2533 ushort v = (ushort) key;
2535 if (Elements.Contains (v))
2536 lname = v.ToString ();
2538 Elements.Add (v, sl);
2539 } else if (compare_type == TypeManager.string_type){
2540 if (key is NullLiteral){
2541 if (Elements.Contains (NullLiteral.Null))
2544 Elements.Add (NullLiteral.Null, null);
2546 string s = (string) key;
2548 if (Elements.Contains (s))
2551 Elements.Add (s, sl);
2553 } else if (compare_type == TypeManager.int32_type) {
2556 if (Elements.Contains (v))
2557 lname = v.ToString ();
2559 Elements.Add (v, sl);
2560 } else if (compare_type == TypeManager.bool_type) {
2561 bool v = (bool) key;
2563 if (Elements.Contains (v))
2564 lname = v.ToString ();
2566 Elements.Add (v, sl);
2570 throw new Exception ("Unknown switch type!" +
2571 SwitchType + " " + compare_type);
2575 Report.Error (152, sl.loc, Error152, "case " + lname);
2586 void EmitObjectInteger (ILGenerator ig, object k)
2589 IntConstant.EmitInt (ig, (int) k);
2590 else if (k is Constant) {
2591 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2594 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2597 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2599 IntConstant.EmitInt (ig, (int) (long) k);
2600 ig.Emit (OpCodes.Conv_I8);
2603 LongConstant.EmitLong (ig, (long) k);
2605 else if (k is ulong)
2607 if ((ulong) k < (1L<<32))
2609 IntConstant.EmitInt (ig, (int) (long) k);
2610 ig.Emit (OpCodes.Conv_U8);
2614 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2618 IntConstant.EmitInt (ig, (int) ((char) k));
2619 else if (k is sbyte)
2620 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2622 IntConstant.EmitInt (ig, (int) ((byte) k));
2623 else if (k is short)
2624 IntConstant.EmitInt (ig, (int) ((short) k));
2625 else if (k is ushort)
2626 IntConstant.EmitInt (ig, (int) ((ushort) k));
2628 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2630 throw new Exception ("Unhandled case");
2633 // structure used to hold blocks of keys while calculating table switch
2634 class KeyBlock : IComparable
2636 public KeyBlock (long _nFirst)
2638 nFirst = nLast = _nFirst;
2642 public ArrayList rgKeys = null;
2643 // how many items are in the bucket
2644 public int Size = 1;
2647 get { return (int) (nLast - nFirst + 1); }
2649 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2651 return kbLast.nLast - kbFirst.nFirst + 1;
2653 public int CompareTo (object obj)
2655 KeyBlock kb = (KeyBlock) obj;
2656 int nLength = Length;
2657 int nLengthOther = kb.Length;
2658 if (nLengthOther == nLength)
2659 return (int) (kb.nFirst - nFirst);
2660 return nLength - nLengthOther;
2665 /// This method emits code for a lookup-based switch statement (non-string)
2666 /// Basically it groups the cases into blocks that are at least half full,
2667 /// and then spits out individual lookup opcodes for each block.
2668 /// It emits the longest blocks first, and short blocks are just
2669 /// handled with direct compares.
2671 /// <param name="ec"></param>
2672 /// <param name="val"></param>
2673 /// <returns></returns>
2674 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2676 int cElements = Elements.Count;
2677 object [] rgKeys = new object [cElements];
2678 Elements.Keys.CopyTo (rgKeys, 0);
2679 Array.Sort (rgKeys);
2681 // initialize the block list with one element per key
2682 ArrayList rgKeyBlocks = new ArrayList ();
2683 foreach (object key in rgKeys)
2684 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2687 // iteratively merge the blocks while they are at least half full
2688 // there's probably a really cool way to do this with a tree...
2689 while (rgKeyBlocks.Count > 1)
2691 ArrayList rgKeyBlocksNew = new ArrayList ();
2692 kbCurr = (KeyBlock) rgKeyBlocks [0];
2693 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2695 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2696 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2699 kbCurr.nLast = kb.nLast;
2700 kbCurr.Size += kb.Size;
2704 // start a new block
2705 rgKeyBlocksNew.Add (kbCurr);
2709 rgKeyBlocksNew.Add (kbCurr);
2710 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2712 rgKeyBlocks = rgKeyBlocksNew;
2715 // initialize the key lists
2716 foreach (KeyBlock kb in rgKeyBlocks)
2717 kb.rgKeys = new ArrayList ();
2719 // fill the key lists
2721 if (rgKeyBlocks.Count > 0) {
2722 kbCurr = (KeyBlock) rgKeyBlocks [0];
2723 foreach (object key in rgKeys)
2725 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2726 System.Convert.ToInt64 (key) > kbCurr.nLast;
2728 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2729 kbCurr.rgKeys.Add (key);
2733 // sort the blocks so we can tackle the largest ones first
2734 rgKeyBlocks.Sort ();
2736 // okay now we can start...
2737 ILGenerator ig = ec.ig;
2738 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2739 Label lblDefault = ig.DefineLabel ();
2741 Type typeKeys = null;
2742 if (rgKeys.Length > 0)
2743 typeKeys = rgKeys [0].GetType (); // used for conversions
2747 if (TypeManager.IsEnumType (SwitchType))
2748 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2750 compare_type = SwitchType;
2752 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2754 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2755 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2758 foreach (object key in kb.rgKeys)
2760 ig.Emit (OpCodes.Ldloc, val);
2761 EmitObjectInteger (ig, key);
2762 SwitchLabel sl = (SwitchLabel) Elements [key];
2763 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2768 // TODO: if all the keys in the block are the same and there are
2769 // no gaps/defaults then just use a range-check.
2770 if (compare_type == TypeManager.int64_type ||
2771 compare_type == TypeManager.uint64_type)
2773 // TODO: optimize constant/I4 cases
2775 // check block range (could be > 2^31)
2776 ig.Emit (OpCodes.Ldloc, val);
2777 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2778 ig.Emit (OpCodes.Blt, lblDefault);
2779 ig.Emit (OpCodes.Ldloc, val);
2780 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2781 ig.Emit (OpCodes.Bgt, lblDefault);
2784 ig.Emit (OpCodes.Ldloc, val);
2787 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2788 ig.Emit (OpCodes.Sub);
2790 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2795 ig.Emit (OpCodes.Ldloc, val);
2796 int nFirst = (int) kb.nFirst;
2799 IntConstant.EmitInt (ig, nFirst);
2800 ig.Emit (OpCodes.Sub);
2802 else if (nFirst < 0)
2804 IntConstant.EmitInt (ig, -nFirst);
2805 ig.Emit (OpCodes.Add);
2809 // first, build the list of labels for the switch
2811 int cJumps = kb.Length;
2812 Label [] rgLabels = new Label [cJumps];
2813 for (int iJump = 0; iJump < cJumps; iJump++)
2815 object key = kb.rgKeys [iKey];
2816 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2818 SwitchLabel sl = (SwitchLabel) Elements [key];
2819 rgLabels [iJump] = sl.GetILLabel (ec);
2823 rgLabels [iJump] = lblDefault;
2825 // emit the switch opcode
2826 ig.Emit (OpCodes.Switch, rgLabels);
2829 // mark the default for this block
2831 ig.MarkLabel (lblDefault);
2834 // TODO: find the default case and emit it here,
2835 // to prevent having to do the following jump.
2836 // make sure to mark other labels in the default section
2838 // the last default just goes to the end
2839 ig.Emit (OpCodes.Br, lblDefault);
2841 // now emit the code for the sections
2842 bool fFoundDefault = false;
2843 foreach (SwitchSection ss in Sections)
2845 foreach (SwitchLabel sl in ss.Labels)
2847 ig.MarkLabel (sl.GetILLabel (ec));
2848 ig.MarkLabel (sl.GetILLabelCode (ec));
2849 if (sl.Label == null)
2851 ig.MarkLabel (lblDefault);
2852 fFoundDefault = true;
2856 //ig.Emit (OpCodes.Br, lblEnd);
2859 if (!fFoundDefault) {
2860 ig.MarkLabel (lblDefault);
2862 ig.MarkLabel (lblEnd);
2865 // This simple emit switch works, but does not take advantage of the
2867 // TODO: remove non-string logic from here
2868 // TODO: binary search strings?
2870 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2872 ILGenerator ig = ec.ig;
2873 Label end_of_switch = ig.DefineLabel ();
2874 Label next_test = ig.DefineLabel ();
2875 Label null_target = ig.DefineLabel ();
2876 bool first_test = true;
2877 bool pending_goto_end = false;
2878 bool null_marked = false;
2881 ig.Emit (OpCodes.Ldloc, val);
2883 if (Elements.Contains (NullLiteral.Null)){
2884 ig.Emit (OpCodes.Brfalse, null_target);
2886 ig.Emit (OpCodes.Brfalse, default_target);
2888 ig.Emit (OpCodes.Ldloc, val);
2889 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2890 ig.Emit (OpCodes.Stloc, val);
2892 int section_count = Sections.Count;
2893 for (int section = 0; section < section_count; section++){
2894 SwitchSection ss = (SwitchSection) Sections [section];
2896 if (ss == default_section)
2899 Label sec_begin = ig.DefineLabel ();
2901 ig.Emit (OpCodes.Nop);
2903 if (pending_goto_end)
2904 ig.Emit (OpCodes.Br, end_of_switch);
2906 int label_count = ss.Labels.Count;
2908 for (int label = 0; label < label_count; label++){
2909 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2910 ig.MarkLabel (sl.GetILLabel (ec));
2913 ig.MarkLabel (next_test);
2914 next_test = ig.DefineLabel ();
2917 // If we are the default target
2919 if (sl.Label != null){
2920 object lit = sl.Converted;
2922 if (lit is NullLiteral){
2924 if (label_count == 1)
2925 ig.Emit (OpCodes.Br, next_test);
2929 StringConstant str = (StringConstant) lit;
2931 ig.Emit (OpCodes.Ldloc, val);
2932 ig.Emit (OpCodes.Ldstr, str.Value);
2933 if (label_count == 1)
2934 ig.Emit (OpCodes.Bne_Un, next_test);
2936 if (label+1 == label_count)
2937 ig.Emit (OpCodes.Bne_Un, next_test);
2939 ig.Emit (OpCodes.Beq, sec_begin);
2944 ig.MarkLabel (null_target);
2947 ig.MarkLabel (sec_begin);
2948 foreach (SwitchLabel sl in ss.Labels)
2949 ig.MarkLabel (sl.GetILLabelCode (ec));
2952 pending_goto_end = !ss.Block.HasRet;
2955 ig.MarkLabel (next_test);
2956 ig.MarkLabel (default_target);
2958 ig.MarkLabel (null_target);
2959 if (default_section != null)
2960 default_section.Block.Emit (ec);
2961 ig.MarkLabel (end_of_switch);
2964 SwitchSection FindSection (SwitchLabel label)
2966 foreach (SwitchSection ss in Sections){
2967 foreach (SwitchLabel sl in ss.Labels){
2976 public override bool Resolve (EmitContext ec)
2978 Expr = Expr.Resolve (ec);
2982 new_expr = SwitchGoverningType (ec, Expr.Type);
2983 if (new_expr == null){
2984 Report.Error (151, loc, "An integer type or string was expected for switch");
2989 SwitchType = new_expr.Type;
2991 if (!CheckSwitch (ec))
2994 Switch old_switch = ec.Switch;
2996 ec.Switch.SwitchType = SwitchType;
2998 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2999 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3001 is_constant = new_expr is Constant;
3003 object key = ((Constant) new_expr).GetValue ();
3004 SwitchLabel label = (SwitchLabel) Elements [key];
3006 constant_section = FindSection (label);
3007 if (constant_section == null)
3008 constant_section = default_section;
3012 foreach (SwitchSection ss in Sections){
3014 ec.CurrentBranching.CreateSibling (
3015 null, FlowBranching.SiblingType.SwitchSection);
3019 if (is_constant && (ss != constant_section)) {
3020 // If we're a constant switch, we're only emitting
3021 // one single section - mark all the others as
3023 ec.CurrentBranching.CurrentUsageVector.Goto ();
3024 if (!ss.Block.ResolveUnreachable (ec, true))
3027 if (!ss.Block.Resolve (ec))
3032 if (default_section == null)
3033 ec.CurrentBranching.CreateSibling (
3034 null, FlowBranching.SiblingType.SwitchSection);
3036 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3037 ec.Switch = old_switch;
3039 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3045 protected override void DoEmit (EmitContext ec)
3047 ILGenerator ig = ec.ig;
3049 // Store variable for comparission purposes
3052 value = ig.DeclareLocal (SwitchType);
3054 ig.Emit (OpCodes.Stloc, value);
3058 default_target = ig.DefineLabel ();
3061 // Setup the codegen context
3063 Label old_end = ec.LoopEnd;
3064 Switch old_switch = ec.Switch;
3066 ec.LoopEnd = ig.DefineLabel ();
3071 if (constant_section != null)
3072 constant_section.Block.Emit (ec);
3073 } else if (SwitchType == TypeManager.string_type)
3074 SimpleSwitchEmit (ec, value);
3076 TableSwitchEmit (ec, value);
3078 // Restore context state.
3079 ig.MarkLabel (ec.LoopEnd);
3082 // Restore the previous context
3084 ec.LoopEnd = old_end;
3085 ec.Switch = old_switch;
3089 public abstract class ExceptionStatement : Statement
3091 public abstract void EmitFinally (EmitContext ec);
3093 protected bool emit_finally = true;
3094 ArrayList parent_vectors;
3096 protected void DoEmitFinally (EmitContext ec)
3099 ec.ig.BeginFinallyBlock ();
3101 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3105 protected void ResolveFinally (FlowBranchingException branching)
3107 emit_finally = branching.EmitFinally;
3109 branching.Parent.StealFinallyClauses (ref parent_vectors);
3113 public class Lock : ExceptionStatement {
3115 Statement Statement;
3118 public Lock (Expression expr, Statement stmt, Location l)
3125 public override bool Resolve (EmitContext ec)
3127 expr = expr.Resolve (ec);
3131 if (expr.Type.IsValueType){
3132 Error (185, "lock statement requires the expression to be " +
3133 " a reference type (type is: `{0}'",
3134 TypeManager.CSharpName (expr.Type));
3138 FlowBranchingException branching = ec.StartFlowBranching (this);
3139 bool ok = Statement.Resolve (ec);
3141 ec.KillFlowBranching ();
3145 ResolveFinally (branching);
3147 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3148 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3149 // Unfortunately, System.Reflection.Emit automatically emits
3150 // a leave to the end of the finally block.
3151 // This is a problem if `returns' is true since we may jump
3152 // to a point after the end of the method.
3153 // As a workaround, emit an explicit ret here.
3154 ec.NeedReturnLabel ();
3160 protected override void DoEmit (EmitContext ec)
3162 Type type = expr.Type;
3164 ILGenerator ig = ec.ig;
3165 temp = ig.DeclareLocal (type);
3168 ig.Emit (OpCodes.Dup);
3169 ig.Emit (OpCodes.Stloc, temp);
3170 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3174 ig.BeginExceptionBlock ();
3175 Statement.Emit (ec);
3180 ig.EndExceptionBlock ();
3183 public override void EmitFinally (EmitContext ec)
3185 ILGenerator ig = ec.ig;
3186 ig.Emit (OpCodes.Ldloc, temp);
3187 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3191 public class Unchecked : Statement {
3192 public readonly Block Block;
3194 public Unchecked (Block b)
3200 public override bool Resolve (EmitContext ec)
3202 bool previous_state = ec.CheckState;
3203 bool previous_state_const = ec.ConstantCheckState;
3205 ec.CheckState = false;
3206 ec.ConstantCheckState = false;
3207 bool ret = Block.Resolve (ec);
3208 ec.CheckState = previous_state;
3209 ec.ConstantCheckState = previous_state_const;
3214 protected override void DoEmit (EmitContext ec)
3216 bool previous_state = ec.CheckState;
3217 bool previous_state_const = ec.ConstantCheckState;
3219 ec.CheckState = false;
3220 ec.ConstantCheckState = false;
3222 ec.CheckState = previous_state;
3223 ec.ConstantCheckState = previous_state_const;
3227 public class Checked : Statement {
3228 public readonly Block Block;
3230 public Checked (Block b)
3233 b.Unchecked = false;
3236 public override bool Resolve (EmitContext ec)
3238 bool previous_state = ec.CheckState;
3239 bool previous_state_const = ec.ConstantCheckState;
3241 ec.CheckState = true;
3242 ec.ConstantCheckState = true;
3243 bool ret = Block.Resolve (ec);
3244 ec.CheckState = previous_state;
3245 ec.ConstantCheckState = previous_state_const;
3250 protected override void DoEmit (EmitContext ec)
3252 bool previous_state = ec.CheckState;
3253 bool previous_state_const = ec.ConstantCheckState;
3255 ec.CheckState = true;
3256 ec.ConstantCheckState = true;
3258 ec.CheckState = previous_state;
3259 ec.ConstantCheckState = previous_state_const;
3263 public class Unsafe : Statement {
3264 public readonly Block Block;
3266 public Unsafe (Block b)
3269 Block.Unsafe = true;
3272 public override bool Resolve (EmitContext ec)
3274 bool previous_state = ec.InUnsafe;
3278 val = Block.Resolve (ec);
3279 ec.InUnsafe = previous_state;
3284 protected override void DoEmit (EmitContext ec)
3286 bool previous_state = ec.InUnsafe;
3290 ec.InUnsafe = previous_state;
3297 public class Fixed : Statement {
3299 ArrayList declarators;
3300 Statement statement;
3305 abstract class Emitter
3307 protected LocalInfo vi;
3308 protected Expression converted;
3310 protected Emitter (Expression expr, LocalInfo li)
3316 public abstract void Emit (EmitContext ec);
3317 public abstract void EmitExit (ILGenerator ig);
3320 class ExpressionEmitter: Emitter {
3321 public ExpressionEmitter (Expression converted, LocalInfo li) :
3322 base (converted, li)
3326 public override void Emit (EmitContext ec) {
3328 // Store pointer in pinned location
3330 converted.Emit (ec);
3331 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3334 public override void EmitExit (ILGenerator ig)
3336 ig.Emit (OpCodes.Ldc_I4_0);
3337 ig.Emit (OpCodes.Conv_U);
3338 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3342 class StringEmitter: Emitter {
3343 LocalBuilder pinned_string;
3346 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3352 public override void Emit (EmitContext ec)
3354 ILGenerator ig = ec.ig;
3355 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3357 converted.Emit (ec);
3358 ig.Emit (OpCodes.Stloc, pinned_string);
3360 Expression sptr = new StringPtr (pinned_string, loc);
3361 converted = Convert.ImplicitConversionRequired (
3362 ec, sptr, vi.VariableType, loc);
3364 if (converted == null)
3367 converted.Emit (ec);
3368 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3371 public override void EmitExit(ILGenerator ig)
3373 ig.Emit (OpCodes.Ldnull);
3374 ig.Emit (OpCodes.Stloc, pinned_string);
3378 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3381 declarators = decls;
3386 public override bool Resolve (EmitContext ec)
3389 Expression.UnsafeError (loc);
3393 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3397 expr_type = texpr.Type;
3399 CheckObsolete (expr_type);
3401 if (ec.RemapToProxy){
3402 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3406 data = new Emitter [declarators.Count];
3408 if (!expr_type.IsPointer){
3409 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3414 foreach (Pair p in declarators){
3415 LocalInfo vi = (LocalInfo) p.First;
3416 Expression e = (Expression) p.Second;
3418 vi.VariableInfo.SetAssigned (ec);
3422 // The rules for the possible declarators are pretty wise,
3423 // but the production on the grammar is more concise.
3425 // So we have to enforce these rules here.
3427 // We do not resolve before doing the case 1 test,
3428 // because the grammar is explicit in that the token &
3429 // is present, so we need to test for this particular case.
3433 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3438 // Case 1: & object.
3440 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3441 Expression child = ((Unary) e).Expr;
3443 if (child is ParameterReference || child is LocalVariableReference){
3446 "No need to use fixed statement for parameters or " +
3447 "local variable declarations (address is already " +
3452 ec.InFixedInitializer = true;
3454 ec.InFixedInitializer = false;
3458 child = ((Unary) e).Expr;
3460 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3463 data [i] = new ExpressionEmitter (e, vi);
3469 ec.InFixedInitializer = true;
3471 ec.InFixedInitializer = false;
3478 if (e.Type.IsArray){
3479 Type array_type = TypeManager.GetElementType (e.Type);
3482 // Provided that array_type is unmanaged,
3484 if (!TypeManager.VerifyUnManaged (array_type, loc))
3488 // and T* is implicitly convertible to the
3489 // pointer type given in the fixed statement.
3491 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3493 Expression converted = Convert.ImplicitConversionRequired (
3494 ec, array_ptr, vi.VariableType, loc);
3495 if (converted == null)
3498 data [i] = new ExpressionEmitter (converted, vi);
3507 if (e.Type == TypeManager.string_type){
3508 data [i] = new StringEmitter (e, vi, loc);
3513 // Case 4: fixed buffer
3514 FieldExpr fe = e as FieldExpr;
3516 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3518 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3520 Expression converted = Convert.ImplicitConversionRequired (
3521 ec, fixed_buffer_ptr, vi.VariableType, loc);
3522 if (converted == null)
3525 data [i] = new ExpressionEmitter (converted, vi);
3533 // For other cases, flag a `this is already fixed expression'
3535 if (e is LocalVariableReference || e is ParameterReference ||
3536 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3538 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3542 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3546 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3548 if (!statement.Resolve (ec)) {
3549 ec.KillFlowBranching ();
3553 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3554 has_ret = reachability.IsUnreachable;
3559 protected override void DoEmit (EmitContext ec)
3561 for (int i = 0; i < data.Length; i++) {
3565 statement.Emit (ec);
3570 ILGenerator ig = ec.ig;
3573 // Clear the pinned variable
3575 for (int i = 0; i < data.Length; i++) {
3576 data [i].EmitExit (ig);
3581 public class Catch: Statement {
3582 public readonly string Name;
3583 public readonly Block Block;
3585 Expression type_expr;
3588 public Catch (Expression type, string name, Block block, Location l)
3596 public Type CatchType {
3602 public bool IsGeneral {
3604 return type_expr == null;
3608 protected override void DoEmit(EmitContext ec)
3612 public override bool Resolve (EmitContext ec)
3614 bool was_catch = ec.InCatch;
3617 if (type_expr != null) {
3618 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3622 type = te.ResolveType (ec);
3624 CheckObsolete (type);
3626 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3627 Error (155, "The type caught or thrown must be derived from System.Exception");
3633 return Block.Resolve (ec);
3636 ec.InCatch = was_catch;
3641 public class Try : ExceptionStatement {
3642 public readonly Block Fini, Block;
3643 public readonly ArrayList Specific;
3644 public readonly Catch General;
3646 bool need_exc_block;
3649 // specific, general and fini might all be null.
3651 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3653 if (specific == null && general == null){
3654 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3658 this.Specific = specific;
3659 this.General = general;
3664 public override bool Resolve (EmitContext ec)
3668 FlowBranchingException branching = ec.StartFlowBranching (this);
3670 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3672 if (!Block.Resolve (ec))
3675 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3677 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3679 Type[] prevCatches = new Type [Specific.Count];
3681 foreach (Catch c in Specific){
3682 ec.CurrentBranching.CreateSibling (
3683 c.Block, FlowBranching.SiblingType.Catch);
3685 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3687 if (c.Name != null) {
3688 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3690 throw new Exception ();
3692 vi.VariableInfo = null;
3695 if (!c.Resolve (ec))
3698 Type resolvedType = c.CatchType;
3699 for (int ii = 0; ii < last_index; ++ii) {
3700 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3701 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3706 prevCatches [last_index++] = resolvedType;
3707 need_exc_block = true;
3710 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3712 if (General != null){
3713 ec.CurrentBranching.CreateSibling (
3714 General.Block, FlowBranching.SiblingType.Catch);
3716 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3718 if (!General.Resolve (ec))
3721 need_exc_block = true;
3724 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3728 ec.CurrentBranching.CreateSibling (
3729 Fini, FlowBranching.SiblingType.Finally);
3731 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3732 bool was_finally = ec.InFinally;
3733 ec.InFinally = true;
3734 if (!Fini.Resolve (ec))
3736 ec.InFinally = was_finally;
3739 ResolveFinally (branching);
3740 need_exc_block |= emit_finally;
3742 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3744 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3746 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3748 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3749 // Unfortunately, System.Reflection.Emit automatically emits
3750 // a leave to the end of the finally block. This is a problem
3751 // if `returns' is true since we may jump to a point after the
3752 // end of the method.
3753 // As a workaround, emit an explicit ret here.
3754 ec.NeedReturnLabel ();
3760 protected override void DoEmit (EmitContext ec)
3762 ILGenerator ig = ec.ig;
3765 ig.BeginExceptionBlock ();
3768 foreach (Catch c in Specific){
3771 ig.BeginCatchBlock (c.CatchType);
3773 if (c.Name != null){
3774 vi = c.Block.GetLocalInfo (c.Name);
3776 throw new Exception ("Variable does not exist in this block");
3778 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3780 ig.Emit (OpCodes.Pop);
3785 if (General != null){
3786 ig.BeginCatchBlock (TypeManager.object_type);
3787 ig.Emit (OpCodes.Pop);
3788 General.Block.Emit (ec);
3793 ig.EndExceptionBlock ();
3796 public override void EmitFinally (EmitContext ec)
3803 public bool HasCatch
3806 return General != null || Specific.Count > 0;
3811 public class Using : ExceptionStatement {
3812 object expression_or_block;
3813 Statement Statement;
3818 Expression [] resolved_vars;
3819 Expression [] converted_vars;
3820 ExpressionStatement [] assign;
3821 LocalBuilder local_copy;
3823 public Using (object expression_or_block, Statement stmt, Location l)
3825 this.expression_or_block = expression_or_block;
3831 // Resolves for the case of using using a local variable declaration.
3833 bool ResolveLocalVariableDecls (EmitContext ec)
3837 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3841 expr_type = texpr.Type;
3844 // The type must be an IDisposable or an implicit conversion
3847 converted_vars = new Expression [var_list.Count];
3848 resolved_vars = new Expression [var_list.Count];
3849 assign = new ExpressionStatement [var_list.Count];
3851 bool need_conv = !TypeManager.ImplementsInterface (
3852 expr_type, TypeManager.idisposable_type);
3854 foreach (DictionaryEntry e in var_list){
3855 Expression var = (Expression) e.Key;
3857 var = var.ResolveLValue (ec, new EmptyExpression ());
3861 resolved_vars [i] = var;
3868 converted_vars [i] = Convert.ImplicitConversionRequired (
3869 ec, var, TypeManager.idisposable_type, loc);
3871 if (converted_vars [i] == null)
3878 foreach (DictionaryEntry e in var_list){
3879 Expression var = resolved_vars [i];
3880 Expression new_expr = (Expression) e.Value;
3883 a = new Assign (var, new_expr, loc);
3889 converted_vars [i] = var;
3890 assign [i] = (ExpressionStatement) a;
3897 bool ResolveExpression (EmitContext ec)
3899 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3900 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3901 Report.Error (1674, loc, "'{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3902 TypeManager.CSharpName (expr_type));
3911 // Emits the code for the case of using using a local variable declaration.
3913 void EmitLocalVariableDecls (EmitContext ec)
3915 ILGenerator ig = ec.ig;
3918 for (i = 0; i < assign.Length; i++) {
3919 assign [i].EmitStatement (ec);
3922 ig.BeginExceptionBlock ();
3924 Statement.Emit (ec);
3926 var_list.Reverse ();
3931 void EmitLocalVariableDeclFinally (EmitContext ec)
3933 ILGenerator ig = ec.ig;
3935 int i = assign.Length;
3936 for (int ii = 0; ii < var_list.Count; ++ii){
3937 Expression var = resolved_vars [--i];
3938 Label skip = ig.DefineLabel ();
3940 ig.BeginFinallyBlock ();
3942 if (!var.Type.IsValueType) {
3944 ig.Emit (OpCodes.Brfalse, skip);
3945 converted_vars [i].Emit (ec);
3946 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3948 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3950 if (!(ml is MethodGroupExpr)) {
3952 ig.Emit (OpCodes.Box, var.Type);
3953 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3955 MethodInfo mi = null;
3957 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3958 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3965 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3969 IMemoryLocation mloc = (IMemoryLocation) var;
3971 mloc.AddressOf (ec, AddressOp.Load);
3972 ig.Emit (OpCodes.Call, mi);
3976 ig.MarkLabel (skip);
3979 ig.EndExceptionBlock ();
3981 ig.BeginFinallyBlock ();
3986 void EmitExpression (EmitContext ec)
3989 // Make a copy of the expression and operate on that.
3991 ILGenerator ig = ec.ig;
3992 local_copy = ig.DeclareLocal (expr_type);
3997 ig.Emit (OpCodes.Stloc, local_copy);
4000 ig.BeginExceptionBlock ();
4002 Statement.Emit (ec);
4006 ig.EndExceptionBlock ();
4009 void EmitExpressionFinally (EmitContext ec)
4011 ILGenerator ig = ec.ig;
4012 if (!local_copy.LocalType.IsValueType) {
4013 Label skip = ig.DefineLabel ();
4014 ig.Emit (OpCodes.Ldloc, local_copy);
4015 ig.Emit (OpCodes.Brfalse, skip);
4016 ig.Emit (OpCodes.Ldloc, local_copy);
4017 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4018 ig.MarkLabel (skip);
4020 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4022 if (!(ml is MethodGroupExpr)) {
4023 ig.Emit (OpCodes.Ldloc, local_copy);
4024 ig.Emit (OpCodes.Box, local_copy.LocalType);
4025 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4027 MethodInfo mi = null;
4029 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4030 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4037 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4041 ig.Emit (OpCodes.Ldloca, local_copy);
4042 ig.Emit (OpCodes.Call, mi);
4047 public override bool Resolve (EmitContext ec)
4049 if (expression_or_block is DictionaryEntry){
4050 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4051 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4053 if (!ResolveLocalVariableDecls (ec))
4056 } else if (expression_or_block is Expression){
4057 expr = (Expression) expression_or_block;
4059 expr = expr.Resolve (ec);
4063 expr_type = expr.Type;
4065 if (!ResolveExpression (ec))
4069 FlowBranchingException branching = ec.StartFlowBranching (this);
4071 bool ok = Statement.Resolve (ec);
4074 ec.KillFlowBranching ();
4078 ResolveFinally (branching);
4079 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4081 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4082 // Unfortunately, System.Reflection.Emit automatically emits a leave
4083 // to the end of the finally block. This is a problem if `returns'
4084 // is true since we may jump to a point after the end of the method.
4085 // As a workaround, emit an explicit ret here.
4086 ec.NeedReturnLabel ();
4092 protected override void DoEmit (EmitContext ec)
4094 if (expression_or_block is DictionaryEntry)
4095 EmitLocalVariableDecls (ec);
4096 else if (expression_or_block is Expression)
4097 EmitExpression (ec);
4100 public override void EmitFinally (EmitContext ec)
4102 if (expression_or_block is DictionaryEntry)
4103 EmitLocalVariableDeclFinally (ec);
4104 else if (expression_or_block is Expression)
4105 EmitExpressionFinally (ec);
4110 /// Implementation of the foreach C# statement
4112 public class Foreach : ExceptionStatement {
4114 Expression variable;
4116 Statement statement;
4117 ForeachHelperMethods hm;
4118 Expression empty, conv;
4119 Type array_type, element_type;
4121 VariableStorage enumerator;
4124 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4125 Statement stmt, Location l)
4128 this.variable = var;
4134 public override bool Resolve (EmitContext ec)
4136 expr = expr.Resolve (ec);
4140 if (expr is NullLiteral) {
4141 Report.Error (186, expr.Location, "Use of null is not valid in this context");
4145 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4149 var_type = texpr.Type;
4152 // We need an instance variable. Not sure this is the best
4153 // way of doing this.
4155 // FIXME: When we implement propertyaccess, will those turn
4156 // out to return values in ExprClass? I think they should.
4158 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4159 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4160 error1579 (expr.Type);
4164 if (expr.Type.IsArray) {
4165 array_type = expr.Type;
4166 element_type = TypeManager.GetElementType (array_type);
4168 empty = new EmptyExpression (element_type);
4170 array = new ArrayForeach (type, variable, expr, statement, loc);
4171 return array.Resolve (ec);
4173 hm = ProbeCollectionType (ec, expr.Type);
4175 error1579 (expr.Type);
4179 array_type = expr.Type;
4180 element_type = hm.element_type;
4182 empty = new EmptyExpression (hm.element_type);
4187 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4188 ec.CurrentBranching.CreateSibling ();
4192 // FIXME: maybe we can apply the same trick we do in the
4193 // array handling to avoid creating empty and conv in some cases.
4195 // Although it is not as important in this case, as the type
4196 // will not likely be object (what the enumerator will return).
4198 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4202 variable = variable.ResolveLValue (ec, empty);
4203 if (variable == null)
4206 bool disposable = (hm != null) && hm.is_disposable;
4207 FlowBranchingException branching = null;
4209 branching = ec.StartFlowBranching (this);
4211 if (!statement.Resolve (ec))
4215 ResolveFinally (branching);
4216 ec.EndFlowBranching ();
4218 emit_finally = true;
4220 ec.EndFlowBranching ();
4226 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4228 static MethodInfo FetchMethodMoveNext (Type t)
4230 MemberList move_next_list;
4232 move_next_list = TypeContainer.FindMembers (
4233 t, MemberTypes.Method,
4234 BindingFlags.Public | BindingFlags.Instance,
4235 Type.FilterName, "MoveNext");
4236 if (move_next_list.Count == 0)
4239 foreach (MemberInfo m in move_next_list){
4240 MethodInfo mi = (MethodInfo) m;
4243 args = TypeManager.GetArgumentTypes (mi);
4244 if (args != null && args.Length == 0){
4245 if (TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type)
4253 // Retrieves a `public T get_Current ()' method from the Type `t'
4255 static MethodInfo FetchMethodGetCurrent (Type t)
4257 MemberList get_current_list;
4259 get_current_list = TypeContainer.FindMembers (
4260 t, MemberTypes.Method,
4261 BindingFlags.Public | BindingFlags.Instance,
4262 Type.FilterName, "get_Current");
4263 if (get_current_list.Count == 0)
4266 foreach (MemberInfo m in get_current_list){
4267 MethodInfo mi = (MethodInfo) m;
4270 args = TypeManager.GetArgumentTypes (mi);
4271 if (args != null && args.Length == 0)
4278 // Retrieves a `public void Dispose ()' method from the Type `t'
4280 static MethodInfo FetchMethodDispose (Type t)
4282 MemberList dispose_list;
4284 dispose_list = TypeContainer.FindMembers (
4285 t, MemberTypes.Method,
4286 BindingFlags.Public | BindingFlags.Instance,
4287 Type.FilterName, "Dispose");
4288 if (dispose_list.Count == 0)
4291 foreach (MemberInfo m in dispose_list){
4292 MethodInfo mi = (MethodInfo) m;
4295 args = TypeManager.GetArgumentTypes (mi);
4296 if (args != null && args.Length == 0){
4297 if (mi.ReturnType == TypeManager.void_type)
4305 // This struct records the helper methods used by the Foreach construct
4307 class ForeachHelperMethods {
4308 public EmitContext ec;
4309 public MethodInfo get_enumerator;
4310 public MethodInfo move_next;
4311 public MethodInfo get_current;
4312 public Type element_type;
4313 public Type enumerator_type;
4314 public bool is_disposable;
4316 public ForeachHelperMethods (EmitContext ec)
4319 this.element_type = TypeManager.object_type;
4320 this.enumerator_type = TypeManager.ienumerator_type;
4321 this.is_disposable = true;
4325 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4330 if (!(m is MethodInfo))
4333 if (m.Name != "GetEnumerator")
4336 MethodInfo mi = (MethodInfo) m;
4337 Type [] args = TypeManager.GetArgumentTypes (mi);
4339 if (args.Length != 0)
4342 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4344 // Check whether GetEnumerator is public
4345 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4348 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4350 // Apply the same optimization as MS: skip the GetEnumerator
4351 // returning an IEnumerator, and use the one returning a
4352 // CharEnumerator instead. This allows us to avoid the
4353 // try-finally block and the boxing.
4358 // Ok, we can access it, now make sure that we can do something
4359 // with this `GetEnumerator'
4362 Type return_type = mi.ReturnType;
4363 if (mi.ReturnType == TypeManager.ienumerator_type ||
4364 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4365 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4368 // If it is not an interface, lets try to find the methods ourselves.
4369 // For example, if we have:
4370 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4371 // We can avoid the iface call. This is a runtime perf boost.
4372 // even bigger if we have a ValueType, because we avoid the cost
4375 // We have to make sure that both methods exist for us to take
4376 // this path. If one of the methods does not exist, we will just
4377 // use the interface. Sadly, this complex if statement is the only
4378 // way I could do this without a goto
4381 if (return_type.IsInterface ||
4382 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4383 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4385 hm.move_next = TypeManager.bool_movenext_void;
4386 hm.get_current = TypeManager.object_getcurrent_void;
4393 // Ok, so they dont return an IEnumerable, we will have to
4394 // find if they support the GetEnumerator pattern.
4397 hm.move_next = FetchMethodMoveNext (return_type);
4398 if (hm.move_next == null)
4401 hm.get_current = FetchMethodGetCurrent (return_type);
4402 if (hm.get_current == null)
4406 hm.element_type = hm.get_current.ReturnType;
4407 hm.enumerator_type = return_type;
4408 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4409 TypeManager.ImplementsInterface (
4410 hm.enumerator_type, TypeManager.idisposable_type);
4416 /// This filter is used to find the GetEnumerator method
4417 /// on which IEnumerator operates
4419 static MemberFilter FilterEnumerator;
4423 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4426 void error1579 (Type t)
4428 Report.Error (1579, loc,
4429 "foreach statement cannot operate on variables of type `" +
4430 t.FullName + "' because that class does not provide a " +
4431 " GetEnumerator method or it is inaccessible");
4434 static bool TryType (Type t, ForeachHelperMethods hm)
4438 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4439 BindingFlags.Public | BindingFlags.NonPublic |
4440 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4441 FilterEnumerator, hm);
4446 hm.get_enumerator = (MethodInfo) mi [0];
4451 // Looks for a usable GetEnumerator in the Type, and if found returns
4452 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4454 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4456 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4458 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4459 if (TryType (tt, hm))
4465 // Now try to find the method in the interfaces
4468 Type [] ifaces = t.GetInterfaces ();
4470 foreach (Type i in ifaces){
4471 if (TryType (i, hm))
4476 // Since TypeBuilder.GetInterfaces only returns the interface
4477 // types for this type, we have to keep looping, but once
4478 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4479 // done, because it returns all the types
4481 if ((t is TypeBuilder))
4491 // FIXME: possible optimization.
4492 // We might be able to avoid creating `empty' if the type is the sam
4494 bool EmitCollectionForeach (EmitContext ec)
4496 ILGenerator ig = ec.ig;
4498 enumerator = new VariableStorage (ec, hm.enumerator_type);
4499 enumerator.EmitThis (ig);
4501 // Instantiate the enumerator
4503 if (expr.Type.IsValueType){
4504 IMemoryLocation ml = expr as IMemoryLocation;
4505 // Load the address of the value type.
4507 // This happens if, for example, you have a property
4508 // returning a struct which is IEnumerable
4509 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4511 ig.Emit (OpCodes.Stloc, t);
4512 ig.Emit (OpCodes.Ldloca, t);
4513 ec.FreeTemporaryLocal (t, expr.Type);
4515 ml.AddressOf (ec, AddressOp.Load);
4519 if (hm.get_enumerator.DeclaringType.IsValueType) {
4520 // the method is declared on the value type
4521 ig.Emit (OpCodes.Call, hm.get_enumerator);
4523 // it is an interface method, so we must box
4524 ig.Emit (OpCodes.Box, expr.Type);
4525 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4529 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4531 enumerator.EmitStore (ig);
4534 // Protect the code in a try/finalize block, so that
4535 // if the beast implement IDisposable, we get rid of it
4537 if (hm.is_disposable && emit_finally)
4538 ig.BeginExceptionBlock ();
4540 Label end_try = ig.DefineLabel ();
4542 ig.MarkLabel (ec.LoopBegin);
4544 enumerator.EmitCall (ig, hm.move_next);
4546 ig.Emit (OpCodes.Brfalse, end_try);
4549 ig.Emit (OpCodes.Ldarg_0);
4551 enumerator.EmitCall (ig, hm.get_current);
4555 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4557 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4559 statement.Emit (ec);
4560 ig.Emit (OpCodes.Br, ec.LoopBegin);
4561 ig.MarkLabel (end_try);
4563 // The runtime provides this for us.
4564 // ig.Emit (OpCodes.Leave, end);
4567 // Now the finally block
4569 if (hm.is_disposable) {
4572 ig.EndExceptionBlock ();
4575 ig.MarkLabel (ec.LoopEnd);
4579 public override void EmitFinally (EmitContext ec)
4581 ILGenerator ig = ec.ig;
4583 if (hm.enumerator_type.IsValueType) {
4584 enumerator.EmitThis (ig);
4586 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4588 enumerator.EmitLoadAddress (ig);
4589 ig.Emit (OpCodes.Call, mi);
4591 enumerator.EmitLoad (ig);
4592 ig.Emit (OpCodes.Box, hm.enumerator_type);
4593 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4596 Label call_dispose = ig.DefineLabel ();
4598 enumerator.EmitThis (ig);
4599 enumerator.EmitLoad (ig);
4600 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4601 ig.Emit (OpCodes.Dup);
4602 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4603 ig.Emit (OpCodes.Pop);
4605 Label end_finally = ig.DefineLabel ();
4606 ig.Emit (OpCodes.Br, end_finally);
4608 ig.MarkLabel (call_dispose);
4609 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4610 ig.MarkLabel (end_finally);
4613 ig.Emit (OpCodes.Endfinally);
4617 protected override void DoEmit (EmitContext ec)
4619 ILGenerator ig = ec.ig;
4621 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4622 ec.LoopBegin = ig.DefineLabel ();
4623 ec.LoopEnd = ig.DefineLabel ();
4626 EmitCollectionForeach (ec);
4630 ec.LoopBegin = old_begin;
4631 ec.LoopEnd = old_end;
4634 protected class TemporaryVariable : Expression
4639 public TemporaryVariable (Type type, Location loc)
4643 eclass = ExprClass.Value;
4648 public override Expression DoResolve (EmitContext ec)
4650 if (ec.InIterator) {
4652 fb = ec.CurrentIterator.MapVariable (
4653 "s_", count.ToString (), type);
4655 local = ec.ig.DeclareLocal (type);
4660 public override void Emit (EmitContext ec)
4662 ILGenerator ig = ec.ig;
4665 ig.Emit (OpCodes.Ldarg_0);
4666 ig.Emit (OpCodes.Ldfld, fb);
4668 ig.Emit (OpCodes.Ldloc, local);
4672 public void Store (EmitContext ec, Expression right_side)
4675 ec.ig.Emit (OpCodes.Ldarg_0);
4676 right_side.Emit (ec);
4678 ec.ig.Emit (OpCodes.Stloc, local);
4680 ec.ig.Emit (OpCodes.Stfld, fb);
4683 public void EmitThis (ILGenerator ig)
4686 ig.Emit (OpCodes.Ldarg_0);
4689 public void EmitStore (ILGenerator ig)
4692 ig.Emit (OpCodes.Stloc, local);
4694 ig.Emit (OpCodes.Stfld, fb);
4698 protected class ArrayCounter : TemporaryVariable
4700 public ArrayCounter (Location loc)
4701 : base (TypeManager.int32_type, loc)
4704 public void Initialize (EmitContext ec)
4707 ec.ig.Emit (OpCodes.Ldc_I4_0);
4711 public void Increment (EmitContext ec)
4715 ec.ig.Emit (OpCodes.Ldc_I4_1);
4716 ec.ig.Emit (OpCodes.Add);
4721 protected class ArrayForeach : Statement
4723 Expression type, variable, expr, conv;
4724 Statement statement;
4727 TemporaryVariable[] lengths;
4728 ArrayCounter[] counter;
4731 TemporaryVariable copy;
4734 public ArrayForeach (Expression type, Expression var,
4735 Expression expr, Statement stmt, Location l)
4738 this.variable = var;
4744 public override bool Resolve (EmitContext ec)
4746 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4750 var_type = texpr.Type;
4752 array_type = expr.Type;
4753 rank = array_type.GetArrayRank ();
4755 copy = new TemporaryVariable (array_type, loc);
4758 counter = new ArrayCounter [rank];
4759 lengths = new TemporaryVariable [rank];
4761 ArrayList list = new ArrayList ();
4762 for (int i = 0; i < rank; i++) {
4763 counter [i] = new ArrayCounter (loc);
4764 counter [i].Resolve (ec);
4766 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4767 lengths [i].Resolve (ec);
4769 list.Add (counter [i]);
4772 access = new ElementAccess (copy, list, loc).Resolve (ec);
4776 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4782 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4783 ec.CurrentBranching.CreateSibling ();
4785 variable = variable.ResolveLValue (ec, conv);
4786 if (variable == null)
4789 if (!statement.Resolve (ec))
4792 ec.EndFlowBranching ();
4797 protected override void DoEmit (EmitContext ec)
4799 ILGenerator ig = ec.ig;
4801 copy.Store (ec, expr);
4803 Label[] test = new Label [rank];
4804 Label[] loop = new Label [rank];
4806 for (int i = 0; i < rank; i++) {
4807 test [i] = ig.DefineLabel ();
4808 loop [i] = ig.DefineLabel ();
4810 lengths [i].EmitThis (ig);
4811 ((ArrayAccess) access).EmitGetLength (ec, i);
4812 lengths [i].EmitStore (ig);
4815 for (int i = 0; i < rank; i++) {
4816 counter [i].Initialize (ec);
4818 ig.Emit (OpCodes.Br, test [i]);
4819 ig.MarkLabel (loop [i]);
4822 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4824 statement.Emit (ec);
4826 ig.MarkLabel (ec.LoopBegin);
4828 for (int i = rank - 1; i >= 0; i--){
4829 counter [i].Increment (ec);
4831 ig.MarkLabel (test [i]);
4832 counter [i].Emit (ec);
4833 lengths [i].Emit (ec);
4834 ig.Emit (OpCodes.Blt, loop [i]);
4837 ig.MarkLabel (ec.LoopEnd);