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 () || ec.CurrentBranching.InSwitch ())
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;
1013 CompilerGenerated = 64
1016 public enum ReadOnlyContext: byte {
1023 ReadOnlyContext ro_context;
1025 public LocalInfo (Expression type, string name, Block block, Location l)
1033 public LocalInfo (TypeContainer tc, Block block, Location l)
1035 VariableType = tc.TypeBuilder;
1040 public bool IsThisAssigned (EmitContext ec, Location loc)
1042 if (VariableInfo == null)
1043 throw new Exception ();
1045 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1048 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1051 public bool IsAssigned (EmitContext ec)
1053 if (VariableInfo == null)
1054 throw new Exception ();
1056 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1059 public bool Resolve (EmitContext ec)
1061 if (VariableType == null) {
1062 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
1066 VariableType = texpr.Type;
1069 if (VariableType == TypeManager.void_type) {
1070 Report.Error (1547, Location,
1071 "Keyword 'void' cannot be used in this context");
1075 if (VariableType.IsAbstract && VariableType.IsSealed) {
1076 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1079 // TODO: breaks the build
1080 // if (VariableType.IsPointer && !ec.InUnsafe)
1081 // Expression.UnsafeError (Location);
1087 // Whether the variable is Fixed (because its Pinned or its a value type)
1089 public bool IsFixed {
1091 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1098 public bool IsCaptured {
1100 return (flags & Flags.Captured) != 0;
1104 flags |= Flags.Captured;
1108 public bool AddressTaken {
1110 return (flags & Flags.AddressTaken) != 0;
1114 flags |= Flags.AddressTaken;
1118 public bool CompilerGenerated {
1120 return (flags & Flags.CompilerGenerated) != 0;
1124 flags |= Flags.CompilerGenerated;
1128 public override string ToString ()
1130 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1131 Name, Type, VariableInfo, Location);
1136 return (flags & Flags.Used) != 0;
1139 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1143 public bool ReadOnly {
1145 return (flags & Flags.ReadOnly) != 0;
1149 public void SetReadOnlyContext (ReadOnlyContext context)
1151 flags |= Flags.ReadOnly;
1152 ro_context = context;
1155 public string GetReadOnlyContext ()
1158 throw new InternalErrorException ("Variable is not readonly");
1160 switch (ro_context) {
1161 case ReadOnlyContext.Fixed:
1162 return "fixed variable";
1163 case ReadOnlyContext.Foreach:
1164 return "foreach iteration variable";
1165 case ReadOnlyContext.Using:
1166 return "using variable";
1168 throw new NotImplementedException ();
1172 // Whether the variable is pinned, if Pinned the variable has been
1173 // allocated in a pinned slot with DeclareLocal.
1175 public bool Pinned {
1177 return (flags & Flags.Pinned) != 0;
1180 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1184 public bool IsThis {
1186 return (flags & Flags.IsThis) != 0;
1189 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1195 /// Block represents a C# block.
1199 /// This class is used in a number of places: either to represent
1200 /// explicit blocks that the programmer places or implicit blocks.
1202 /// Implicit blocks are used as labels or to introduce variable
1205 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1206 /// they contain extra information that is not necessary on normal blocks.
1208 public class Block : Statement {
1209 public Block Parent;
1210 public readonly Location StartLocation;
1211 public Location EndLocation = Location.Null;
1213 public readonly ToplevelBlock Toplevel;
1220 VariablesInitialized = 8,
1229 public bool Implicit {
1231 return (flags & Flags.Implicit) != 0;
1235 public bool Unchecked {
1237 return (flags & Flags.Unchecked) != 0;
1240 flags |= Flags.Unchecked;
1244 public bool Unsafe {
1246 return (flags & Flags.Unsafe) != 0;
1249 flags |= Flags.Unsafe;
1253 public bool HasVarargs {
1256 return Parent.HasVarargs;
1258 return (flags & Flags.HasVarargs) != 0;
1261 flags |= Flags.HasVarargs;
1266 // The statements in this block
1268 ArrayList statements;
1272 // An array of Blocks. We keep track of children just
1273 // to generate the local variable declarations.
1275 // Statements and child statements are handled through the
1281 // Labels. (label, block) pairs.
1286 // Keeps track of (name, type) pairs
1288 Hashtable variables;
1291 // Keeps track of constants
1292 Hashtable constants;
1295 // Temporary variables.
1297 ArrayList temporary_variables;
1300 // If this is a switch section, the enclosing switch block.
1304 protected static int id;
1308 public Block (Block parent)
1309 : this (parent, (Flags) 0, Location.Null, Location.Null)
1312 public Block (Block parent, Flags flags)
1313 : this (parent, flags, Location.Null, Location.Null)
1316 public Block (Block parent, Location start, Location end)
1317 : this (parent, (Flags) 0, start, end)
1320 public Block (Block parent, Flags flags, Location start, Location end)
1323 parent.AddChild (this);
1325 this.Parent = parent;
1327 this.StartLocation = start;
1328 this.EndLocation = end;
1331 statements = new ArrayList ();
1333 if ((flags & Flags.IsToplevel) != 0)
1334 Toplevel = (ToplevelBlock) this;
1336 Toplevel = parent.Toplevel;
1338 if (parent != null && Implicit) {
1339 if (parent.known_variables == null)
1340 parent.known_variables = new Hashtable ();
1341 // share with parent
1342 known_variables = parent.known_variables;
1347 public Block CreateSwitchBlock (Location start)
1349 Block new_block = new Block (this, start, start);
1350 new_block.switch_block = this;
1360 void AddChild (Block b)
1362 if (children == null)
1363 children = new ArrayList ();
1368 public void SetEndLocation (Location loc)
1374 /// Adds a label to the current block.
1378 /// false if the name already exists in this block. true
1382 public bool AddLabel (string name, LabeledStatement target, Location loc)
1384 if (switch_block != null)
1385 return switch_block.AddLabel (name, target, loc);
1388 while (cur != null) {
1389 if (cur.DoLookupLabel (name) != null) {
1391 140, loc, "The label '{0}' is a duplicate",
1402 while (cur != null) {
1403 if (cur.DoLookupLabel (name) != null) {
1406 "The label '{0}' shadows another label " +
1407 "by the same name in a containing scope.",
1412 if (children != null) {
1413 foreach (Block b in children) {
1414 LabeledStatement s = b.DoLookupLabel (name);
1420 "The label '{0}' shadows another " +
1421 "label by the same name in a " +
1422 "containing scope.",
1433 labels = new Hashtable ();
1435 labels.Add (name, target);
1439 public LabeledStatement LookupLabel (string name)
1441 LabeledStatement s = DoLookupLabel (name);
1445 if (children == null)
1448 foreach (Block child in children) {
1449 if (!child.Implicit)
1452 s = child.LookupLabel (name);
1460 LabeledStatement DoLookupLabel (string name)
1462 if (switch_block != null)
1463 return switch_block.LookupLabel (name);
1466 if (labels.Contains (name))
1467 return ((LabeledStatement) labels [name]);
1472 LocalInfo this_variable = null;
1475 // Returns the "this" instance variable of this block.
1476 // See AddThisVariable() for more information.
1478 public LocalInfo ThisVariable {
1480 for (Block b = this; b != null; b = b.Parent) {
1481 if (b.this_variable != null)
1482 return b.this_variable;
1489 Hashtable known_variables;
1492 // Marks a variable with name @name as being used in this or a child block.
1493 // If a variable name has been used in a child block, it's illegal to
1494 // declare a variable with the same name in the current block.
1496 void AddKnownVariable (string name, LocalInfo info)
1498 if (known_variables == null)
1499 known_variables = new Hashtable ();
1501 known_variables [name] = info;
1504 LocalInfo GetKnownVariableInfo (string name)
1506 if (known_variables == null)
1508 return (LocalInfo) known_variables [name];
1511 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1513 LocalInfo kvi = GetKnownVariableInfo (name);
1514 if (kvi == null || kvi.Block == this)
1517 if (known_variables != kvi.Block.known_variables) {
1518 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1519 Report.Error (135, loc, "'{0}' has a different meaning in a child block", name);
1524 // this block and kvi.Block are the same textual block.
1525 // However, different variables are extant.
1527 // Check if the variable is in scope in both blocks. We use
1528 // an indirect check that depends on AddVariable doing its
1529 // part in maintaining the invariant-meaning-in-block property.
1531 if (e is LocalVariableReference || (e is Constant && GetLocalInfo (name) != null))
1534 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1535 Report.Error (136, loc, "'{0}' has a different meaning later in the block", name);
1540 // This is used by non-static `struct' constructors which do not have an
1541 // initializer - in this case, the constructor must initialize all of the
1542 // struct's fields. To do this, we add a "this" variable and use the flow
1543 // analysis code to ensure that it's been fully initialized before control
1544 // leaves the constructor.
1546 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1548 if (this_variable != null)
1549 return this_variable;
1551 if (variables == null)
1552 variables = new Hashtable ();
1554 this_variable = new LocalInfo (tc, this, l);
1555 this_variable.Used = true;
1556 this_variable.IsThis = true;
1558 variables.Add ("this", this_variable);
1560 return this_variable;
1563 public LocalInfo AddVariable (Expression type, string name, Location l)
1565 if (variables == null)
1566 variables = new Hashtable ();
1568 LocalInfo vi = GetLocalInfo (name);
1570 Report.SymbolRelatedToPreviousError (vi.Location, name);
1571 if (known_variables == vi.Block.known_variables)
1572 Report.Error (128, l,
1573 "A local variable '{0}' is already declared in this scope", name);
1575 Report.Error (136, l,
1576 "'{0}' hides the declaration of local variable '{0}' in a parent scope", name);
1580 vi = GetKnownVariableInfo (name);
1582 Report.SymbolRelatedToPreviousError (vi.Location, name);
1583 Report.Error (136, l,
1584 "A child block already has a declaration of local variable '{0}':" +
1585 " allowing this declaration would violate 'invariant meaning in a block'",
1591 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1593 Report.SymbolRelatedToPreviousError (Toplevel.Parameters.Location, name);
1594 Report.Error (136, l, "'{0}' hides a method parameter", name);
1598 vi = new LocalInfo (type, name, this, l);
1600 variables.Add (name, vi);
1602 for (Block b = this; b != null; b = b.Parent)
1603 b.AddKnownVariable (name, vi);
1605 if ((flags & Flags.VariablesInitialized) != 0)
1606 throw new Exception ();
1608 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1612 public bool AddConstant (Expression type, string name, Expression value, Location l)
1614 if (AddVariable (type, name, l) == null)
1617 if (constants == null)
1618 constants = new Hashtable ();
1620 constants.Add (name, value);
1624 static int next_temp_id = 0;
1626 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1628 if (temporary_variables == null)
1629 temporary_variables = new ArrayList ();
1631 int id = ++next_temp_id;
1632 string name = "$s_" + id.ToString ();
1634 LocalInfo li = new LocalInfo (te, name, this, loc);
1635 li.CompilerGenerated = true;
1636 temporary_variables.Add (li);
1640 public Hashtable Variables {
1646 public LocalInfo GetLocalInfo (string name)
1648 for (Block b = this; b != null; b = b.Parent) {
1649 if (b.variables != null) {
1650 LocalInfo ret = b.variables [name] as LocalInfo;
1658 public Expression GetVariableType (string name)
1660 LocalInfo vi = GetLocalInfo (name);
1668 public Expression GetConstantExpression (string name)
1670 for (Block b = this; b != null; b = b.Parent) {
1671 if (b.constants != null) {
1672 Expression ret = b.constants [name] as Expression;
1681 /// True if the variable named @name is a constant
1683 public bool IsConstant (string name)
1685 Expression e = null;
1687 e = GetConstantExpression (name);
1693 /// A list of labels that were not used within this block
1695 public string [] GetUnreferenced ()
1697 // FIXME: Implement me
1701 public void AddStatement (Statement s)
1704 flags |= Flags.BlockUsed;
1709 return (flags & Flags.BlockUsed) != 0;
1715 flags |= Flags.BlockUsed;
1718 public bool HasRet {
1720 return (flags & Flags.HasRet) != 0;
1724 public bool IsDestructor {
1726 return (flags & Flags.IsDestructor) != 0;
1730 public void SetDestructor ()
1732 flags |= Flags.IsDestructor;
1735 VariableMap param_map, local_map;
1737 public VariableMap ParameterMap {
1739 if ((flags & Flags.VariablesInitialized) == 0)
1740 throw new Exception ("Variables have not been initialized yet");
1746 public VariableMap LocalMap {
1748 if ((flags & Flags.VariablesInitialized) == 0)
1749 throw new Exception ("Variables have not been initialized yet");
1756 /// Emits the variable declarations and labels.
1759 /// tc: is our typecontainer (to resolve type references)
1760 /// ig: is the code generator:
1762 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1764 bool old_unsafe = ec.InUnsafe;
1766 // If some parent block was unsafe, we remain unsafe even if this block
1767 // isn't explicitly marked as such.
1768 ec.InUnsafe |= Unsafe;
1771 // Compute the VariableMap's.
1773 // Unfortunately, we don't know the type when adding variables with
1774 // AddVariable(), so we need to compute this info here.
1778 if (variables != null) {
1779 foreach (LocalInfo li in variables.Values)
1782 locals = new LocalInfo [variables.Count];
1783 variables.Values.CopyTo (locals, 0);
1785 locals = new LocalInfo [0];
1788 local_map = new VariableMap (Parent.LocalMap, locals);
1790 local_map = new VariableMap (locals);
1792 param_map = new VariableMap (ip);
1793 flags |= Flags.VariablesInitialized;
1795 bool old_check_state = ec.ConstantCheckState;
1796 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1799 // Process this block variables
1801 if (variables != null){
1802 foreach (DictionaryEntry de in variables){
1803 string name = (string) de.Key;
1804 LocalInfo vi = (LocalInfo) de.Value;
1806 if (vi.VariableType == null)
1809 Type variable_type = vi.VariableType;
1811 if (variable_type.IsPointer){
1813 // Am not really convinced that this test is required (Microsoft does it)
1814 // but the fact is that you would not be able to use the pointer variable
1817 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1824 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1827 // This is needed to compile on both .NET 1.x and .NET 2.x
1828 // the later introduced `DeclareLocal (Type t, bool pinned)'
1830 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1831 else if (!vi.IsThis)
1832 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1835 if (constants == null)
1838 Expression cv = (Expression) constants [name];
1842 ec.CurrentBlock = this;
1843 Expression e = cv.Resolve (ec);
1845 Constant ce = e as Constant;
1847 Report.Error (133, vi.Location,
1848 "The expression being assigned to '{0}' must be constant", name);
1852 if (e.Type != variable_type){
1853 e = Const.ChangeType (vi.Location, ce, variable_type);
1858 constants.Remove (name);
1859 constants.Add (name, e);
1862 ec.ConstantCheckState = old_check_state;
1865 // Now, handle the children
1867 if (children != null){
1868 foreach (Block b in children)
1869 b.ResolveMeta (toplevel, ec, ip);
1871 ec.InUnsafe = old_unsafe;
1875 // Emits the local variable declarations for a block
1877 public void EmitMeta (EmitContext ec)
1879 ILGenerator ig = ec.ig;
1881 if (variables != null){
1882 bool have_captured_vars = ec.HaveCapturedVariables ();
1883 bool remap_locals = ec.RemapToProxy;
1885 foreach (DictionaryEntry de in variables){
1886 LocalInfo vi = (LocalInfo) de.Value;
1888 if (have_captured_vars && ec.IsCaptured (vi))
1892 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1896 // This is needed to compile on both .NET 1.x and .NET 2.x
1897 // the later introduced `DeclareLocal (Type t, bool pinned)'
1899 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1900 else if (!vi.IsThis)
1901 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1906 if (temporary_variables != null) {
1907 foreach (LocalInfo vi in temporary_variables) {
1908 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1912 if (children != null){
1913 foreach (Block b in children)
1918 void UsageWarning (FlowBranching.UsageVector vector)
1922 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1923 foreach (DictionaryEntry de in variables){
1924 LocalInfo vi = (LocalInfo) de.Value;
1929 name = (string) de.Key;
1931 if (vector.IsAssigned (vi.VariableInfo)){
1932 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1934 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1940 bool unreachable_shown;
1943 public override bool Resolve (EmitContext ec)
1945 Block prev_block = ec.CurrentBlock;
1948 int errors = Report.Errors;
1950 ec.CurrentBlock = this;
1951 ec.StartFlowBranching (this);
1953 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1956 // This flag is used to notate nested statements as unreachable from the beginning of this block.
1957 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
1958 // from the beginning of the function. The outer Resolve() that detected the unreachability is
1959 // responsible for handling the situation.
1961 int statement_count = statements.Count;
1962 for (int ix = 0; ix < statement_count; ix++){
1963 Statement s = (Statement) statements [ix];
1967 ((Block) s).unreachable = true;
1969 if (!unreachable_shown && (RootContext.WarningLevel >= 2)) {
1971 162, loc, "Unreachable code detected");
1972 unreachable_shown = true;
1976 if (!s.Resolve (ec)) {
1978 statements [ix] = EmptyStatement.Value;
1982 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1983 statements [ix] = EmptyStatement.Value;
1985 num_statements = ix + 1;
1986 if (s is LabeledStatement)
1987 unreachable = false;
1989 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1992 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1993 ec.CurrentBranching, statement_count, num_statements);
1996 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1998 ec.CurrentBlock = prev_block;
2000 // If we're a non-static `struct' constructor which doesn't have an
2001 // initializer, then we must initialize all of the struct's fields.
2002 if ((this_variable != null) &&
2003 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
2004 !this_variable.IsThisAssigned (ec, loc))
2007 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2008 foreach (LabeledStatement label in labels.Values)
2009 if (!label.HasBeenReferenced)
2010 Report.Warning (164, label.Location,
2011 "This label has not been referenced");
2014 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2016 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2017 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2018 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2019 flags |= Flags.HasRet;
2021 if (ok && (errors == Report.Errors)) {
2022 if (RootContext.WarningLevel >= 3)
2023 UsageWarning (vector);
2029 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2031 unreachable_shown = true;
2034 if (warn && (RootContext.WarningLevel >= 2))
2035 Report.Warning (162, loc, "Unreachable code detected");
2037 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2038 bool ok = Resolve (ec);
2039 ec.KillFlowBranching ();
2044 protected override void DoEmit (EmitContext ec)
2046 for (int ix = 0; ix < num_statements; ix++){
2047 Statement s = (Statement) statements [ix];
2049 // Check whether we are the last statement in a
2052 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2053 ec.IsLastStatement = true;
2055 ec.IsLastStatement = false;
2061 public override void Emit (EmitContext ec)
2063 Block prev_block = ec.CurrentBlock;
2065 ec.CurrentBlock = this;
2067 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2068 bool is_lexical_block = !Implicit && (Parent != null);
2070 if (emit_debug_info) {
2071 if (is_lexical_block)
2074 if (variables != null) {
2075 foreach (DictionaryEntry de in variables) {
2076 string name = (string) de.Key;
2077 LocalInfo vi = (LocalInfo) de.Value;
2079 if (vi.LocalBuilder == null)
2082 ec.DefineLocalVariable (name, vi.LocalBuilder);
2087 ec.Mark (StartLocation, true);
2089 ec.Mark (EndLocation, true);
2091 if (emit_debug_info && is_lexical_block)
2094 ec.CurrentBlock = prev_block;
2098 // Returns true if we ar ea child of `b'.
2100 public bool IsChildOf (Block b)
2102 Block current = this;
2105 if (current.Parent == b)
2107 current = current.Parent;
2108 } while (current != null);
2112 public override string ToString ()
2114 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2119 // A toplevel block contains extra information, the split is done
2120 // only to separate information that would otherwise bloat the more
2121 // lightweight Block.
2123 // In particular, this was introduced when the support for Anonymous
2124 // Methods was implemented.
2126 public class ToplevelBlock : Block {
2128 // Pointer to the host of this anonymous method, or null
2129 // if we are the topmost block
2131 public ToplevelBlock Container;
2132 CaptureContext capture_context;
2133 FlowBranching top_level_branching;
2135 Hashtable capture_contexts;
2138 // The parameters for the block.
2140 public readonly Parameters Parameters;
2142 public void RegisterCaptureContext (CaptureContext cc)
2144 if (capture_contexts == null)
2145 capture_contexts = new Hashtable ();
2146 capture_contexts [cc] = cc;
2149 public void CompleteContexts ()
2151 if (capture_contexts == null)
2154 foreach (CaptureContext cc in capture_contexts.Keys){
2159 public CaptureContext ToplevelBlockCaptureContext {
2161 return capture_context;
2166 // Parent is only used by anonymous blocks to link back to their
2169 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2170 this (container, (Flags) 0, parameters, start)
2174 public ToplevelBlock (Parameters parameters, Location start) :
2175 this (null, (Flags) 0, parameters, start)
2179 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2180 this (null, flags, parameters, start)
2184 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2185 base (null, flags | Flags.IsToplevel, start, Location.Null)
2187 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2188 Container = container;
2191 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2195 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2197 if (capture_context == null)
2198 capture_context = new CaptureContext (this, loc, host);
2201 public CaptureContext CaptureContext {
2203 return capture_context;
2207 public FlowBranching TopLevelBranching {
2209 return top_level_branching;
2214 // Returns a `ParameterReference' for the given name, or null if there
2215 // is no such parameter
2217 public ParameterReference GetParameterReference (string name, Location loc)
2222 for (ToplevelBlock t = this; t != null; t = t.Container) {
2223 Parameters pars = t.Parameters;
2224 par = pars.GetParameterByName (name, out idx);
2226 return new ParameterReference (pars, this, idx, name, loc);
2232 // Whether the parameter named `name' is local to this block,
2233 // or false, if the parameter belongs to an encompassing block.
2235 public bool IsLocalParameter (string name)
2237 return Parameters.GetParameterByName (name) != null;
2241 // Whether the `name' is a parameter reference
2243 public bool IsParameterReference (string name)
2245 for (ToplevelBlock t = this; t != null; t = t.Container) {
2246 if (t.IsLocalParameter (name))
2252 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2254 int errors = Report.Errors;
2256 if (top_level_branching != null)
2259 ResolveMeta (this, ec, ip);
2261 top_level_branching = ec.StartFlowBranching (this);
2263 return Report.Errors == errors;
2267 public class SwitchLabel {
2270 public Location loc;
2274 Label il_label_code;
2275 bool il_label_code_set;
2278 // if expr == null, then it is the default case.
2280 public SwitchLabel (Expression expr, Location l)
2286 public Expression Label {
2292 public object Converted {
2298 public Label GetILLabel (EmitContext ec)
2301 il_label = ec.ig.DefineLabel ();
2302 il_label_set = true;
2307 public Label GetILLabelCode (EmitContext ec)
2309 if (!il_label_code_set){
2310 il_label_code = ec.ig.DefineLabel ();
2311 il_label_code_set = true;
2313 return il_label_code;
2317 // Resolves the expression, reduces it to a literal if possible
2318 // and then converts it to the requested type.
2320 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2325 Expression e = label.Resolve (ec);
2330 if (!(e is Constant)){
2331 Report.Error (150, loc, "A constant value is expected, got: " + e);
2335 if (e is StringConstant || e is NullLiteral){
2336 if (required_type == TypeManager.string_type){
2342 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2343 if (converted == null)
2350 public class SwitchSection {
2351 // An array of SwitchLabels.
2352 public readonly ArrayList Labels;
2353 public readonly Block Block;
2355 public SwitchSection (ArrayList labels, Block block)
2362 public class Switch : Statement {
2363 public readonly ArrayList Sections;
2364 public Expression Expr;
2367 /// Maps constants whose type type SwitchType to their SwitchLabels.
2369 public Hashtable Elements;
2372 /// The governing switch type
2374 public Type SwitchType;
2379 Label default_target;
2380 Expression new_expr;
2382 SwitchSection constant_section;
2383 SwitchSection default_section;
2386 // The types allowed to be implicitly cast from
2387 // on the governing type
2389 static Type [] allowed_types;
2391 public Switch (Expression e, ArrayList sects, Location l)
2398 public bool GotDefault {
2400 return default_section != null;
2404 public Label DefaultTarget {
2406 return default_target;
2411 // Determines the governing type for a switch. The returned
2412 // expression might be the expression from the switch, or an
2413 // expression that includes any potential conversions to the
2414 // integral types or to string.
2416 Expression SwitchGoverningType (EmitContext ec, Type t)
2418 if (t == TypeManager.int32_type ||
2419 t == TypeManager.uint32_type ||
2420 t == TypeManager.char_type ||
2421 t == TypeManager.byte_type ||
2422 t == TypeManager.sbyte_type ||
2423 t == TypeManager.ushort_type ||
2424 t == TypeManager.short_type ||
2425 t == TypeManager.uint64_type ||
2426 t == TypeManager.int64_type ||
2427 t == TypeManager.string_type ||
2428 t == TypeManager.bool_type ||
2429 t.IsSubclassOf (TypeManager.enum_type))
2432 if (allowed_types == null){
2433 allowed_types = new Type [] {
2434 TypeManager.int32_type,
2435 TypeManager.uint32_type,
2436 TypeManager.sbyte_type,
2437 TypeManager.byte_type,
2438 TypeManager.short_type,
2439 TypeManager.ushort_type,
2440 TypeManager.int64_type,
2441 TypeManager.uint64_type,
2442 TypeManager.char_type,
2443 TypeManager.bool_type,
2444 TypeManager.string_type
2449 // Try to find a *user* defined implicit conversion.
2451 // If there is no implicit conversion, or if there are multiple
2452 // conversions, we have to report an error
2454 Expression converted = null;
2455 foreach (Type tt in allowed_types){
2458 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2463 // Ignore over-worked ImplicitUserConversions that do
2464 // an implicit conversion in addition to the user conversion.
2467 UserCast ue = e as UserCast;
2469 if (ue.Source != Expr)
2473 if (converted != null){
2474 Report.ExtraInformation (
2476 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2477 TypeManager.CSharpName (Expr.Type)));
2486 static string Error152 {
2488 return "The label '{0}:' already occurs in this switch statement";
2493 // Performs the basic sanity checks on the switch statement
2494 // (looks for duplicate keys and non-constant expressions).
2496 // It also returns a hashtable with the keys that we will later
2497 // use to compute the switch tables
2499 bool CheckSwitch (EmitContext ec)
2503 Elements = new Hashtable ();
2505 if (TypeManager.IsEnumType (SwitchType)){
2506 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2508 compare_type = SwitchType;
2510 foreach (SwitchSection ss in Sections){
2511 foreach (SwitchLabel sl in ss.Labels){
2512 if (!sl.ResolveAndReduce (ec, SwitchType)){
2517 if (sl.Label == null){
2518 if (default_section != null){
2519 Report.Error (152, sl.loc, Error152, "default");
2522 default_section = ss;
2526 object key = sl.Converted;
2528 if (key is Constant)
2529 key = ((Constant) key).GetValue ();
2532 key = NullLiteral.Null;
2534 string lname = null;
2535 if (compare_type == TypeManager.uint64_type){
2536 ulong v = (ulong) key;
2538 if (Elements.Contains (v))
2539 lname = v.ToString ();
2541 Elements.Add (v, sl);
2542 } else if (compare_type == TypeManager.int64_type){
2543 long v = (long) key;
2545 if (Elements.Contains (v))
2546 lname = v.ToString ();
2548 Elements.Add (v, sl);
2549 } else if (compare_type == TypeManager.uint32_type){
2550 uint v = (uint) key;
2552 if (Elements.Contains (v))
2553 lname = v.ToString ();
2555 Elements.Add (v, sl);
2556 } else if (compare_type == TypeManager.char_type){
2557 char v = (char) key;
2559 if (Elements.Contains (v))
2560 lname = v.ToString ();
2562 Elements.Add (v, sl);
2563 } else if (compare_type == TypeManager.byte_type){
2564 byte v = (byte) key;
2566 if (Elements.Contains (v))
2567 lname = v.ToString ();
2569 Elements.Add (v, sl);
2570 } else if (compare_type == TypeManager.sbyte_type){
2571 sbyte v = (sbyte) key;
2573 if (Elements.Contains (v))
2574 lname = v.ToString ();
2576 Elements.Add (v, sl);
2577 } else if (compare_type == TypeManager.short_type){
2578 short v = (short) key;
2580 if (Elements.Contains (v))
2581 lname = v.ToString ();
2583 Elements.Add (v, sl);
2584 } else if (compare_type == TypeManager.ushort_type){
2585 ushort v = (ushort) key;
2587 if (Elements.Contains (v))
2588 lname = v.ToString ();
2590 Elements.Add (v, sl);
2591 } else if (compare_type == TypeManager.string_type){
2592 if (key is NullLiteral){
2593 if (Elements.Contains (NullLiteral.Null))
2596 Elements.Add (NullLiteral.Null, null);
2598 string s = (string) key;
2600 if (Elements.Contains (s))
2603 Elements.Add (s, sl);
2605 } else if (compare_type == TypeManager.int32_type) {
2608 if (Elements.Contains (v))
2609 lname = v.ToString ();
2611 Elements.Add (v, sl);
2612 } else if (compare_type == TypeManager.bool_type) {
2613 bool v = (bool) key;
2615 if (Elements.Contains (v))
2616 lname = v.ToString ();
2618 Elements.Add (v, sl);
2622 throw new Exception ("Unknown switch type!" +
2623 SwitchType + " " + compare_type);
2627 Report.Error (152, sl.loc, Error152, "case " + lname);
2638 void EmitObjectInteger (ILGenerator ig, object k)
2641 IntConstant.EmitInt (ig, (int) k);
2642 else if (k is Constant) {
2643 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2646 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2649 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2651 IntConstant.EmitInt (ig, (int) (long) k);
2652 ig.Emit (OpCodes.Conv_I8);
2655 LongConstant.EmitLong (ig, (long) k);
2657 else if (k is ulong)
2659 if ((ulong) k < (1L<<32))
2661 IntConstant.EmitInt (ig, (int) (long) k);
2662 ig.Emit (OpCodes.Conv_U8);
2666 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2670 IntConstant.EmitInt (ig, (int) ((char) k));
2671 else if (k is sbyte)
2672 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2674 IntConstant.EmitInt (ig, (int) ((byte) k));
2675 else if (k is short)
2676 IntConstant.EmitInt (ig, (int) ((short) k));
2677 else if (k is ushort)
2678 IntConstant.EmitInt (ig, (int) ((ushort) k));
2680 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2682 throw new Exception ("Unhandled case");
2685 // structure used to hold blocks of keys while calculating table switch
2686 class KeyBlock : IComparable
2688 public KeyBlock (long _nFirst)
2690 nFirst = nLast = _nFirst;
2694 public ArrayList rgKeys = null;
2695 // how many items are in the bucket
2696 public int Size = 1;
2699 get { return (int) (nLast - nFirst + 1); }
2701 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2703 return kbLast.nLast - kbFirst.nFirst + 1;
2705 public int CompareTo (object obj)
2707 KeyBlock kb = (KeyBlock) obj;
2708 int nLength = Length;
2709 int nLengthOther = kb.Length;
2710 if (nLengthOther == nLength)
2711 return (int) (kb.nFirst - nFirst);
2712 return nLength - nLengthOther;
2717 /// This method emits code for a lookup-based switch statement (non-string)
2718 /// Basically it groups the cases into blocks that are at least half full,
2719 /// and then spits out individual lookup opcodes for each block.
2720 /// It emits the longest blocks first, and short blocks are just
2721 /// handled with direct compares.
2723 /// <param name="ec"></param>
2724 /// <param name="val"></param>
2725 /// <returns></returns>
2726 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2728 int cElements = Elements.Count;
2729 object [] rgKeys = new object [cElements];
2730 Elements.Keys.CopyTo (rgKeys, 0);
2731 Array.Sort (rgKeys);
2733 // initialize the block list with one element per key
2734 ArrayList rgKeyBlocks = new ArrayList ();
2735 foreach (object key in rgKeys)
2736 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2739 // iteratively merge the blocks while they are at least half full
2740 // there's probably a really cool way to do this with a tree...
2741 while (rgKeyBlocks.Count > 1)
2743 ArrayList rgKeyBlocksNew = new ArrayList ();
2744 kbCurr = (KeyBlock) rgKeyBlocks [0];
2745 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2747 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2748 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2751 kbCurr.nLast = kb.nLast;
2752 kbCurr.Size += kb.Size;
2756 // start a new block
2757 rgKeyBlocksNew.Add (kbCurr);
2761 rgKeyBlocksNew.Add (kbCurr);
2762 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2764 rgKeyBlocks = rgKeyBlocksNew;
2767 // initialize the key lists
2768 foreach (KeyBlock kb in rgKeyBlocks)
2769 kb.rgKeys = new ArrayList ();
2771 // fill the key lists
2773 if (rgKeyBlocks.Count > 0) {
2774 kbCurr = (KeyBlock) rgKeyBlocks [0];
2775 foreach (object key in rgKeys)
2777 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2778 System.Convert.ToInt64 (key) > kbCurr.nLast;
2780 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2781 kbCurr.rgKeys.Add (key);
2785 // sort the blocks so we can tackle the largest ones first
2786 rgKeyBlocks.Sort ();
2788 // okay now we can start...
2789 ILGenerator ig = ec.ig;
2790 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2791 Label lblDefault = ig.DefineLabel ();
2793 Type typeKeys = null;
2794 if (rgKeys.Length > 0)
2795 typeKeys = rgKeys [0].GetType (); // used for conversions
2799 if (TypeManager.IsEnumType (SwitchType))
2800 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2802 compare_type = SwitchType;
2804 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2806 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2807 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2810 foreach (object key in kb.rgKeys)
2812 ig.Emit (OpCodes.Ldloc, val);
2813 EmitObjectInteger (ig, key);
2814 SwitchLabel sl = (SwitchLabel) Elements [key];
2815 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2820 // TODO: if all the keys in the block are the same and there are
2821 // no gaps/defaults then just use a range-check.
2822 if (compare_type == TypeManager.int64_type ||
2823 compare_type == TypeManager.uint64_type)
2825 // TODO: optimize constant/I4 cases
2827 // check block range (could be > 2^31)
2828 ig.Emit (OpCodes.Ldloc, val);
2829 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2830 ig.Emit (OpCodes.Blt, lblDefault);
2831 ig.Emit (OpCodes.Ldloc, val);
2832 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2833 ig.Emit (OpCodes.Bgt, lblDefault);
2836 ig.Emit (OpCodes.Ldloc, val);
2839 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2840 ig.Emit (OpCodes.Sub);
2842 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2847 ig.Emit (OpCodes.Ldloc, val);
2848 int nFirst = (int) kb.nFirst;
2851 IntConstant.EmitInt (ig, nFirst);
2852 ig.Emit (OpCodes.Sub);
2854 else if (nFirst < 0)
2856 IntConstant.EmitInt (ig, -nFirst);
2857 ig.Emit (OpCodes.Add);
2861 // first, build the list of labels for the switch
2863 int cJumps = kb.Length;
2864 Label [] rgLabels = new Label [cJumps];
2865 for (int iJump = 0; iJump < cJumps; iJump++)
2867 object key = kb.rgKeys [iKey];
2868 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2870 SwitchLabel sl = (SwitchLabel) Elements [key];
2871 rgLabels [iJump] = sl.GetILLabel (ec);
2875 rgLabels [iJump] = lblDefault;
2877 // emit the switch opcode
2878 ig.Emit (OpCodes.Switch, rgLabels);
2881 // mark the default for this block
2883 ig.MarkLabel (lblDefault);
2886 // TODO: find the default case and emit it here,
2887 // to prevent having to do the following jump.
2888 // make sure to mark other labels in the default section
2890 // the last default just goes to the end
2891 ig.Emit (OpCodes.Br, lblDefault);
2893 // now emit the code for the sections
2894 bool fFoundDefault = false;
2895 foreach (SwitchSection ss in Sections)
2897 foreach (SwitchLabel sl in ss.Labels)
2899 ig.MarkLabel (sl.GetILLabel (ec));
2900 ig.MarkLabel (sl.GetILLabelCode (ec));
2901 if (sl.Label == null)
2903 ig.MarkLabel (lblDefault);
2904 fFoundDefault = true;
2908 //ig.Emit (OpCodes.Br, lblEnd);
2911 if (!fFoundDefault) {
2912 ig.MarkLabel (lblDefault);
2914 ig.MarkLabel (lblEnd);
2917 // This simple emit switch works, but does not take advantage of the
2919 // TODO: remove non-string logic from here
2920 // TODO: binary search strings?
2922 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2924 ILGenerator ig = ec.ig;
2925 Label end_of_switch = ig.DefineLabel ();
2926 Label next_test = ig.DefineLabel ();
2927 Label null_target = ig.DefineLabel ();
2928 bool first_test = true;
2929 bool pending_goto_end = false;
2930 bool null_marked = false;
2933 ig.Emit (OpCodes.Ldloc, val);
2935 if (Elements.Contains (NullLiteral.Null)){
2936 ig.Emit (OpCodes.Brfalse, null_target);
2938 ig.Emit (OpCodes.Brfalse, default_target);
2940 ig.Emit (OpCodes.Ldloc, val);
2941 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2942 ig.Emit (OpCodes.Stloc, val);
2944 int section_count = Sections.Count;
2945 for (int section = 0; section < section_count; section++){
2946 SwitchSection ss = (SwitchSection) Sections [section];
2948 if (ss == default_section)
2951 Label sec_begin = ig.DefineLabel ();
2953 ig.Emit (OpCodes.Nop);
2955 if (pending_goto_end)
2956 ig.Emit (OpCodes.Br, end_of_switch);
2958 int label_count = ss.Labels.Count;
2960 for (int label = 0; label < label_count; label++){
2961 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2962 ig.MarkLabel (sl.GetILLabel (ec));
2965 ig.MarkLabel (next_test);
2966 next_test = ig.DefineLabel ();
2969 // If we are the default target
2971 if (sl.Label != null){
2972 object lit = sl.Converted;
2974 if (lit is NullLiteral){
2976 if (label_count == 1)
2977 ig.Emit (OpCodes.Br, next_test);
2981 StringConstant str = (StringConstant) lit;
2983 ig.Emit (OpCodes.Ldloc, val);
2984 ig.Emit (OpCodes.Ldstr, str.Value);
2985 if (label_count == 1)
2986 ig.Emit (OpCodes.Bne_Un, next_test);
2988 if (label+1 == label_count)
2989 ig.Emit (OpCodes.Bne_Un, next_test);
2991 ig.Emit (OpCodes.Beq, sec_begin);
2996 ig.MarkLabel (null_target);
2999 ig.MarkLabel (sec_begin);
3000 foreach (SwitchLabel sl in ss.Labels)
3001 ig.MarkLabel (sl.GetILLabelCode (ec));
3004 pending_goto_end = !ss.Block.HasRet;
3007 ig.MarkLabel (next_test);
3008 ig.MarkLabel (default_target);
3010 ig.MarkLabel (null_target);
3011 if (default_section != null)
3012 default_section.Block.Emit (ec);
3013 ig.MarkLabel (end_of_switch);
3016 SwitchSection FindSection (SwitchLabel label)
3018 foreach (SwitchSection ss in Sections){
3019 foreach (SwitchLabel sl in ss.Labels){
3028 public override bool Resolve (EmitContext ec)
3030 Expr = Expr.Resolve (ec);
3034 new_expr = SwitchGoverningType (ec, Expr.Type);
3035 if (new_expr == null){
3036 Report.Error (151, loc, "An integer type or string was expected for switch");
3041 SwitchType = new_expr.Type;
3043 if (!CheckSwitch (ec))
3046 Switch old_switch = ec.Switch;
3048 ec.Switch.SwitchType = SwitchType;
3050 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3051 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3053 is_constant = new_expr is Constant;
3055 object key = ((Constant) new_expr).GetValue ();
3056 SwitchLabel label = (SwitchLabel) Elements [key];
3058 constant_section = FindSection (label);
3059 if (constant_section == null)
3060 constant_section = default_section;
3064 foreach (SwitchSection ss in Sections){
3066 ec.CurrentBranching.CreateSibling (
3067 null, FlowBranching.SiblingType.SwitchSection);
3071 if (is_constant && (ss != constant_section)) {
3072 // If we're a constant switch, we're only emitting
3073 // one single section - mark all the others as
3075 ec.CurrentBranching.CurrentUsageVector.Goto ();
3076 if (!ss.Block.ResolveUnreachable (ec, true))
3079 if (!ss.Block.Resolve (ec))
3084 if (default_section == null)
3085 ec.CurrentBranching.CreateSibling (
3086 null, FlowBranching.SiblingType.SwitchSection);
3088 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3089 ec.Switch = old_switch;
3091 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3097 protected override void DoEmit (EmitContext ec)
3099 ILGenerator ig = ec.ig;
3101 // Store variable for comparission purposes
3104 value = ig.DeclareLocal (SwitchType);
3106 ig.Emit (OpCodes.Stloc, value);
3110 default_target = ig.DefineLabel ();
3113 // Setup the codegen context
3115 Label old_end = ec.LoopEnd;
3116 Switch old_switch = ec.Switch;
3118 ec.LoopEnd = ig.DefineLabel ();
3123 if (constant_section != null)
3124 constant_section.Block.Emit (ec);
3125 } else if (SwitchType == TypeManager.string_type)
3126 SimpleSwitchEmit (ec, value);
3128 TableSwitchEmit (ec, value);
3130 // Restore context state.
3131 ig.MarkLabel (ec.LoopEnd);
3134 // Restore the previous context
3136 ec.LoopEnd = old_end;
3137 ec.Switch = old_switch;
3141 public abstract class ExceptionStatement : Statement
3143 public abstract void EmitFinally (EmitContext ec);
3145 protected bool emit_finally = true;
3146 ArrayList parent_vectors;
3148 protected void DoEmitFinally (EmitContext ec)
3151 ec.ig.BeginFinallyBlock ();
3152 else if (ec.InIterator)
3153 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3157 protected void ResolveFinally (FlowBranchingException branching)
3159 emit_finally = branching.EmitFinally;
3161 branching.Parent.StealFinallyClauses (ref parent_vectors);
3165 public class Lock : ExceptionStatement {
3167 Statement Statement;
3170 public Lock (Expression expr, Statement stmt, Location l)
3177 public override bool Resolve (EmitContext ec)
3179 expr = expr.Resolve (ec);
3183 if (expr.Type.IsValueType){
3184 Error (185, "lock statement requires the expression to be " +
3185 " a reference type (type is: `{0}'",
3186 TypeManager.CSharpName (expr.Type));
3190 FlowBranchingException branching = ec.StartFlowBranching (this);
3191 bool ok = Statement.Resolve (ec);
3193 ec.KillFlowBranching ();
3197 ResolveFinally (branching);
3199 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3200 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3201 // Unfortunately, System.Reflection.Emit automatically emits
3202 // a leave to the end of the finally block.
3203 // This is a problem if `returns' is true since we may jump
3204 // to a point after the end of the method.
3205 // As a workaround, emit an explicit ret here.
3206 ec.NeedReturnLabel ();
3212 protected override void DoEmit (EmitContext ec)
3214 Type type = expr.Type;
3216 ILGenerator ig = ec.ig;
3217 temp = ig.DeclareLocal (type);
3220 ig.Emit (OpCodes.Dup);
3221 ig.Emit (OpCodes.Stloc, temp);
3222 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3226 ig.BeginExceptionBlock ();
3227 Statement.Emit (ec);
3232 ig.EndExceptionBlock ();
3235 public override void EmitFinally (EmitContext ec)
3237 ILGenerator ig = ec.ig;
3238 ig.Emit (OpCodes.Ldloc, temp);
3239 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3243 public class Unchecked : Statement {
3244 public readonly Block Block;
3246 public Unchecked (Block b)
3252 public override bool Resolve (EmitContext ec)
3254 bool previous_state = ec.CheckState;
3255 bool previous_state_const = ec.ConstantCheckState;
3257 ec.CheckState = false;
3258 ec.ConstantCheckState = false;
3259 bool ret = Block.Resolve (ec);
3260 ec.CheckState = previous_state;
3261 ec.ConstantCheckState = previous_state_const;
3266 protected override void DoEmit (EmitContext ec)
3268 bool previous_state = ec.CheckState;
3269 bool previous_state_const = ec.ConstantCheckState;
3271 ec.CheckState = false;
3272 ec.ConstantCheckState = false;
3274 ec.CheckState = previous_state;
3275 ec.ConstantCheckState = previous_state_const;
3279 public class Checked : Statement {
3280 public readonly Block Block;
3282 public Checked (Block b)
3285 b.Unchecked = false;
3288 public override bool Resolve (EmitContext ec)
3290 bool previous_state = ec.CheckState;
3291 bool previous_state_const = ec.ConstantCheckState;
3293 ec.CheckState = true;
3294 ec.ConstantCheckState = true;
3295 bool ret = Block.Resolve (ec);
3296 ec.CheckState = previous_state;
3297 ec.ConstantCheckState = previous_state_const;
3302 protected override void DoEmit (EmitContext ec)
3304 bool previous_state = ec.CheckState;
3305 bool previous_state_const = ec.ConstantCheckState;
3307 ec.CheckState = true;
3308 ec.ConstantCheckState = true;
3310 ec.CheckState = previous_state;
3311 ec.ConstantCheckState = previous_state_const;
3315 public class Unsafe : Statement {
3316 public readonly Block Block;
3318 public Unsafe (Block b)
3321 Block.Unsafe = true;
3324 public override bool Resolve (EmitContext ec)
3326 bool previous_state = ec.InUnsafe;
3330 val = Block.Resolve (ec);
3331 ec.InUnsafe = previous_state;
3336 protected override void DoEmit (EmitContext ec)
3338 bool previous_state = ec.InUnsafe;
3342 ec.InUnsafe = previous_state;
3349 public class Fixed : Statement {
3351 ArrayList declarators;
3352 Statement statement;
3357 abstract class Emitter
3359 protected LocalInfo vi;
3360 protected Expression converted;
3362 protected Emitter (Expression expr, LocalInfo li)
3368 public abstract void Emit (EmitContext ec);
3369 public abstract void EmitExit (ILGenerator ig);
3372 class ExpressionEmitter: Emitter {
3373 public ExpressionEmitter (Expression converted, LocalInfo li) :
3374 base (converted, li)
3378 public override void Emit (EmitContext ec) {
3380 // Store pointer in pinned location
3382 converted.Emit (ec);
3383 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3386 public override void EmitExit (ILGenerator ig)
3388 ig.Emit (OpCodes.Ldc_I4_0);
3389 ig.Emit (OpCodes.Conv_U);
3390 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3394 class StringEmitter: Emitter {
3395 LocalBuilder pinned_string;
3398 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3404 public override void Emit (EmitContext ec)
3406 ILGenerator ig = ec.ig;
3407 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3409 converted.Emit (ec);
3410 ig.Emit (OpCodes.Stloc, pinned_string);
3412 Expression sptr = new StringPtr (pinned_string, loc);
3413 converted = Convert.ImplicitConversionRequired (
3414 ec, sptr, vi.VariableType, loc);
3416 if (converted == null)
3419 converted.Emit (ec);
3420 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3423 public override void EmitExit(ILGenerator ig)
3425 ig.Emit (OpCodes.Ldnull);
3426 ig.Emit (OpCodes.Stloc, pinned_string);
3430 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3433 declarators = decls;
3438 public override bool Resolve (EmitContext ec)
3441 Expression.UnsafeError (loc);
3445 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3449 expr_type = texpr.Type;
3451 CheckObsolete (expr_type);
3453 if (ec.RemapToProxy){
3454 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3458 data = new Emitter [declarators.Count];
3460 if (!expr_type.IsPointer){
3461 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3466 foreach (Pair p in declarators){
3467 LocalInfo vi = (LocalInfo) p.First;
3468 Expression e = (Expression) p.Second;
3470 vi.VariableInfo.SetAssigned (ec);
3471 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3474 // The rules for the possible declarators are pretty wise,
3475 // but the production on the grammar is more concise.
3477 // So we have to enforce these rules here.
3479 // We do not resolve before doing the case 1 test,
3480 // because the grammar is explicit in that the token &
3481 // is present, so we need to test for this particular case.
3485 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3490 // Case 1: & object.
3492 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3493 Expression child = ((Unary) e).Expr;
3495 if (child is ParameterReference || child is LocalVariableReference){
3498 "No need to use fixed statement for parameters or " +
3499 "local variable declarations (address is already " +
3504 ec.InFixedInitializer = true;
3506 ec.InFixedInitializer = false;
3510 child = ((Unary) e).Expr;
3512 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3515 data [i] = new ExpressionEmitter (e, vi);
3521 ec.InFixedInitializer = true;
3523 ec.InFixedInitializer = false;
3530 if (e.Type.IsArray){
3531 Type array_type = TypeManager.GetElementType (e.Type);
3534 // Provided that array_type is unmanaged,
3536 if (!TypeManager.VerifyUnManaged (array_type, loc))
3540 // and T* is implicitly convertible to the
3541 // pointer type given in the fixed statement.
3543 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3545 Expression converted = Convert.ImplicitConversionRequired (
3546 ec, array_ptr, vi.VariableType, loc);
3547 if (converted == null)
3550 data [i] = new ExpressionEmitter (converted, vi);
3559 if (e.Type == TypeManager.string_type){
3560 data [i] = new StringEmitter (e, vi, loc);
3565 // Case 4: fixed buffer
3566 FieldExpr fe = e as FieldExpr;
3568 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3570 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3572 Expression converted = Convert.ImplicitConversionRequired (
3573 ec, fixed_buffer_ptr, vi.VariableType, loc);
3574 if (converted == null)
3577 data [i] = new ExpressionEmitter (converted, vi);
3585 // For other cases, flag a `this is already fixed expression'
3587 if (e is LocalVariableReference || e is ParameterReference ||
3588 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3590 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3594 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3598 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3600 if (!statement.Resolve (ec)) {
3601 ec.KillFlowBranching ();
3605 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3606 has_ret = reachability.IsUnreachable;
3611 protected override void DoEmit (EmitContext ec)
3613 for (int i = 0; i < data.Length; i++) {
3617 statement.Emit (ec);
3622 ILGenerator ig = ec.ig;
3625 // Clear the pinned variable
3627 for (int i = 0; i < data.Length; i++) {
3628 data [i].EmitExit (ig);
3633 public class Catch: Statement {
3634 public readonly string Name;
3635 public readonly Block Block;
3637 Expression type_expr;
3640 public Catch (Expression type, string name, Block block, Location l)
3648 public Type CatchType {
3654 public bool IsGeneral {
3656 return type_expr == null;
3660 protected override void DoEmit(EmitContext ec)
3664 public override bool Resolve (EmitContext ec)
3666 bool was_catch = ec.InCatch;
3669 if (type_expr != null) {
3670 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3674 type = te.ResolveType (ec);
3676 CheckObsolete (type);
3678 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3679 Error (155, "The type caught or thrown must be derived from System.Exception");
3685 return Block.Resolve (ec);
3688 ec.InCatch = was_catch;
3693 public class Try : ExceptionStatement {
3694 public readonly Block Fini, Block;
3695 public readonly ArrayList Specific;
3696 public readonly Catch General;
3698 bool need_exc_block;
3701 // specific, general and fini might all be null.
3703 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3705 if (specific == null && general == null){
3706 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3710 this.Specific = specific;
3711 this.General = general;
3716 public override bool Resolve (EmitContext ec)
3720 FlowBranchingException branching = ec.StartFlowBranching (this);
3722 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3724 if (!Block.Resolve (ec))
3727 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3729 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3731 Type[] prevCatches = new Type [Specific.Count];
3733 foreach (Catch c in Specific){
3734 ec.CurrentBranching.CreateSibling (
3735 c.Block, FlowBranching.SiblingType.Catch);
3737 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3739 if (c.Name != null) {
3740 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3742 throw new Exception ();
3744 vi.VariableInfo = null;
3747 if (!c.Resolve (ec))
3750 Type resolvedType = c.CatchType;
3751 for (int ii = 0; ii < last_index; ++ii) {
3752 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3753 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3758 prevCatches [last_index++] = resolvedType;
3759 need_exc_block = true;
3762 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3764 if (General != null){
3765 ec.CurrentBranching.CreateSibling (
3766 General.Block, FlowBranching.SiblingType.Catch);
3768 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3770 if (!General.Resolve (ec))
3773 need_exc_block = true;
3776 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3780 ec.CurrentBranching.CreateSibling (
3781 Fini, FlowBranching.SiblingType.Finally);
3783 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3784 bool was_finally = ec.InFinally;
3785 ec.InFinally = true;
3786 if (!Fini.Resolve (ec))
3788 ec.InFinally = was_finally;
3791 need_exc_block = true;
3794 if (ec.InIterator) {
3795 ResolveFinally (branching);
3796 need_exc_block |= emit_finally;
3798 emit_finally = Fini != null;
3800 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3802 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3804 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3806 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3807 // Unfortunately, System.Reflection.Emit automatically emits
3808 // a leave to the end of the finally block. This is a problem
3809 // if `returns' is true since we may jump to a point after the
3810 // end of the method.
3811 // As a workaround, emit an explicit ret here.
3812 ec.NeedReturnLabel ();
3818 protected override void DoEmit (EmitContext ec)
3820 ILGenerator ig = ec.ig;
3823 ig.BeginExceptionBlock ();
3826 foreach (Catch c in Specific){
3829 ig.BeginCatchBlock (c.CatchType);
3831 if (c.Name != null){
3832 vi = c.Block.GetLocalInfo (c.Name);
3834 throw new Exception ("Variable does not exist in this block");
3836 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3838 ig.Emit (OpCodes.Pop);
3843 if (General != null){
3844 ig.BeginCatchBlock (TypeManager.object_type);
3845 ig.Emit (OpCodes.Pop);
3846 General.Block.Emit (ec);
3851 ig.EndExceptionBlock ();
3854 public override void EmitFinally (EmitContext ec)
3860 public bool HasCatch
3863 return General != null || Specific.Count > 0;
3868 public class Using : ExceptionStatement {
3869 object expression_or_block;
3870 Statement Statement;
3875 Expression [] resolved_vars;
3876 Expression [] converted_vars;
3877 ExpressionStatement [] assign;
3878 LocalBuilder local_copy;
3880 public Using (object expression_or_block, Statement stmt, Location l)
3882 this.expression_or_block = expression_or_block;
3888 // Resolves for the case of using using a local variable declaration.
3890 bool ResolveLocalVariableDecls (EmitContext ec)
3894 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3898 expr_type = texpr.Type;
3901 // The type must be an IDisposable or an implicit conversion
3904 converted_vars = new Expression [var_list.Count];
3905 resolved_vars = new Expression [var_list.Count];
3906 assign = new ExpressionStatement [var_list.Count];
3908 bool need_conv = !TypeManager.ImplementsInterface (
3909 expr_type, TypeManager.idisposable_type);
3911 foreach (DictionaryEntry e in var_list){
3912 Expression var = (Expression) e.Key;
3914 var = var.ResolveLValue (ec, new EmptyExpression ());
3918 resolved_vars [i] = var;
3925 converted_vars [i] = Convert.ImplicitConversionRequired (
3926 ec, var, TypeManager.idisposable_type, loc);
3928 if (converted_vars [i] == null)
3935 foreach (DictionaryEntry e in var_list){
3936 Expression var = resolved_vars [i];
3937 Expression new_expr = (Expression) e.Value;
3940 a = new Assign (var, new_expr, loc);
3946 converted_vars [i] = var;
3947 assign [i] = (ExpressionStatement) a;
3954 bool ResolveExpression (EmitContext ec)
3956 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3957 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3958 Report.Error (1674, loc, "'{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3959 TypeManager.CSharpName (expr_type));
3968 // Emits the code for the case of using using a local variable declaration.
3970 void EmitLocalVariableDecls (EmitContext ec)
3972 ILGenerator ig = ec.ig;
3975 for (i = 0; i < assign.Length; i++) {
3976 assign [i].EmitStatement (ec);
3979 ig.BeginExceptionBlock ();
3981 Statement.Emit (ec);
3983 var_list.Reverse ();
3988 void EmitLocalVariableDeclFinally (EmitContext ec)
3990 ILGenerator ig = ec.ig;
3992 int i = assign.Length;
3993 for (int ii = 0; ii < var_list.Count; ++ii){
3994 Expression var = resolved_vars [--i];
3995 Label skip = ig.DefineLabel ();
3997 ig.BeginFinallyBlock ();
3999 if (!var.Type.IsValueType) {
4001 ig.Emit (OpCodes.Brfalse, skip);
4002 converted_vars [i].Emit (ec);
4003 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4005 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4007 if (!(ml is MethodGroupExpr)) {
4009 ig.Emit (OpCodes.Box, var.Type);
4010 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4012 MethodInfo mi = null;
4014 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4015 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4022 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4026 IMemoryLocation mloc = (IMemoryLocation) var;
4028 mloc.AddressOf (ec, AddressOp.Load);
4029 ig.Emit (OpCodes.Call, mi);
4033 ig.MarkLabel (skip);
4036 ig.EndExceptionBlock ();
4038 ig.BeginFinallyBlock ();
4043 void EmitExpression (EmitContext ec)
4046 // Make a copy of the expression and operate on that.
4048 ILGenerator ig = ec.ig;
4049 local_copy = ig.DeclareLocal (expr_type);
4054 ig.Emit (OpCodes.Stloc, local_copy);
4057 ig.BeginExceptionBlock ();
4059 Statement.Emit (ec);
4063 ig.EndExceptionBlock ();
4066 void EmitExpressionFinally (EmitContext ec)
4068 ILGenerator ig = ec.ig;
4069 if (!local_copy.LocalType.IsValueType) {
4070 Label skip = ig.DefineLabel ();
4071 ig.Emit (OpCodes.Ldloc, local_copy);
4072 ig.Emit (OpCodes.Brfalse, skip);
4073 ig.Emit (OpCodes.Ldloc, local_copy);
4074 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4075 ig.MarkLabel (skip);
4077 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4079 if (!(ml is MethodGroupExpr)) {
4080 ig.Emit (OpCodes.Ldloc, local_copy);
4081 ig.Emit (OpCodes.Box, local_copy.LocalType);
4082 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4084 MethodInfo mi = null;
4086 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4087 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4094 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4098 ig.Emit (OpCodes.Ldloca, local_copy);
4099 ig.Emit (OpCodes.Call, mi);
4104 public override bool Resolve (EmitContext ec)
4106 if (expression_or_block is DictionaryEntry){
4107 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4108 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4110 if (!ResolveLocalVariableDecls (ec))
4113 } else if (expression_or_block is Expression){
4114 expr = (Expression) expression_or_block;
4116 expr = expr.Resolve (ec);
4120 expr_type = expr.Type;
4122 if (!ResolveExpression (ec))
4126 FlowBranchingException branching = ec.StartFlowBranching (this);
4128 bool ok = Statement.Resolve (ec);
4131 ec.KillFlowBranching ();
4135 ResolveFinally (branching);
4136 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4138 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4139 // Unfortunately, System.Reflection.Emit automatically emits a leave
4140 // to the end of the finally block. This is a problem if `returns'
4141 // is true since we may jump to a point after the end of the method.
4142 // As a workaround, emit an explicit ret here.
4143 ec.NeedReturnLabel ();
4149 protected override void DoEmit (EmitContext ec)
4151 if (expression_or_block is DictionaryEntry)
4152 EmitLocalVariableDecls (ec);
4153 else if (expression_or_block is Expression)
4154 EmitExpression (ec);
4157 public override void EmitFinally (EmitContext ec)
4159 if (expression_or_block is DictionaryEntry)
4160 EmitLocalVariableDeclFinally (ec);
4161 else if (expression_or_block is Expression)
4162 EmitExpressionFinally (ec);
4167 /// Implementation of the foreach C# statement
4169 public class Foreach : Statement {
4171 Expression variable;
4173 Statement statement;
4175 CollectionForeach collection;
4177 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4178 Statement stmt, Location l)
4181 this.variable = var;
4187 public override bool Resolve (EmitContext ec)
4189 expr = expr.Resolve (ec);
4193 if (expr is NullLiteral) {
4194 Report.Error (186, expr.Location, "Use of null is not valid in this context");
4198 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4202 Type var_type = texpr.Type;
4205 // We need an instance variable. Not sure this is the best
4206 // way of doing this.
4208 // FIXME: When we implement propertyaccess, will those turn
4209 // out to return values in ExprClass? I think they should.
4211 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4212 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4213 CollectionForeach.error1579 (expr.Type, loc);
4217 if (expr.Type.IsArray) {
4218 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4219 return array.Resolve (ec);
4221 collection = new CollectionForeach (
4222 var_type, variable, expr, statement, loc);
4223 return collection.Resolve (ec);
4227 protected override void DoEmit (EmitContext ec)
4229 ILGenerator ig = ec.ig;
4231 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4232 ec.LoopBegin = ig.DefineLabel ();
4233 ec.LoopEnd = ig.DefineLabel ();
4235 if (collection != null)
4236 collection.Emit (ec);
4240 ec.LoopBegin = old_begin;
4241 ec.LoopEnd = old_end;
4244 protected class TemporaryVariable : Expression, IMemoryLocation
4249 public TemporaryVariable (Type type, Location loc)
4253 eclass = ExprClass.Value;
4258 public override Expression DoResolve (EmitContext ec)
4260 if (ec.InIterator) {
4262 fb = ec.CurrentIterator.MapVariable (
4263 "s_", count.ToString (), type);
4265 TypeExpr te = new TypeExpression (type, loc);
4266 li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
4267 if (!li.Resolve (ec))
4274 public override void Emit (EmitContext ec)
4276 ILGenerator ig = ec.ig;
4279 ig.Emit (OpCodes.Ldarg_0);
4280 ig.Emit (OpCodes.Ldfld, fb);
4282 ig.Emit (OpCodes.Ldloc, li.LocalBuilder);
4286 public void EmitLoadAddress (EmitContext ec)
4288 ILGenerator ig = ec.ig;
4291 ig.Emit (OpCodes.Ldarg_0);
4292 ig.Emit (OpCodes.Ldflda, fb);
4294 ig.Emit (OpCodes.Ldloca, li.LocalBuilder);
4298 public void Store (EmitContext ec, Expression right_side)
4301 ec.ig.Emit (OpCodes.Ldarg_0);
4303 right_side.Emit (ec);
4305 ec.ig.Emit (OpCodes.Stfld, fb);
4307 ec.ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4310 public void EmitThis (ILGenerator ig)
4313 ig.Emit (OpCodes.Ldarg_0);
4316 public void EmitStore (ILGenerator ig)
4319 ig.Emit (OpCodes.Stfld, fb);
4321 ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4324 public void AddressOf (EmitContext ec, AddressOp mode)
4326 EmitLoadAddress (ec);
4330 protected class ArrayCounter : TemporaryVariable
4332 public ArrayCounter (Location loc)
4333 : base (TypeManager.int32_type, loc)
4336 public void Initialize (EmitContext ec)
4339 ec.ig.Emit (OpCodes.Ldc_I4_0);
4343 public void Increment (EmitContext ec)
4347 ec.ig.Emit (OpCodes.Ldc_I4_1);
4348 ec.ig.Emit (OpCodes.Add);
4353 protected class ArrayForeach : Statement
4355 Expression variable, expr, conv;
4356 Statement statement;
4359 TemporaryVariable[] lengths;
4360 ArrayCounter[] counter;
4363 TemporaryVariable copy;
4366 public ArrayForeach (Type var_type, Expression var,
4367 Expression expr, Statement stmt, Location l)
4369 this.var_type = var_type;
4370 this.variable = var;
4376 public override bool Resolve (EmitContext ec)
4378 array_type = expr.Type;
4379 rank = array_type.GetArrayRank ();
4381 copy = new TemporaryVariable (array_type, loc);
4384 counter = new ArrayCounter [rank];
4385 lengths = new TemporaryVariable [rank];
4387 ArrayList list = new ArrayList ();
4388 for (int i = 0; i < rank; i++) {
4389 counter [i] = new ArrayCounter (loc);
4390 counter [i].Resolve (ec);
4392 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4393 lengths [i].Resolve (ec);
4395 list.Add (counter [i]);
4398 access = new ElementAccess (copy, list, loc).Resolve (ec);
4402 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4408 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4409 ec.CurrentBranching.CreateSibling ();
4411 variable = variable.ResolveLValue (ec, conv);
4412 if (variable == null)
4415 if (!statement.Resolve (ec))
4418 ec.EndFlowBranching ();
4423 protected override void DoEmit (EmitContext ec)
4425 ILGenerator ig = ec.ig;
4427 copy.Store (ec, expr);
4429 Label[] test = new Label [rank];
4430 Label[] loop = new Label [rank];
4432 for (int i = 0; i < rank; i++) {
4433 test [i] = ig.DefineLabel ();
4434 loop [i] = ig.DefineLabel ();
4436 lengths [i].EmitThis (ig);
4437 ((ArrayAccess) access).EmitGetLength (ec, i);
4438 lengths [i].EmitStore (ig);
4441 for (int i = 0; i < rank; i++) {
4442 counter [i].Initialize (ec);
4444 ig.Emit (OpCodes.Br, test [i]);
4445 ig.MarkLabel (loop [i]);
4448 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4450 statement.Emit (ec);
4452 ig.MarkLabel (ec.LoopBegin);
4454 for (int i = rank - 1; i >= 0; i--){
4455 counter [i].Increment (ec);
4457 ig.MarkLabel (test [i]);
4458 counter [i].Emit (ec);
4459 lengths [i].Emit (ec);
4460 ig.Emit (OpCodes.Blt, loop [i]);
4463 ig.MarkLabel (ec.LoopEnd);
4467 protected class CollectionForeach : ExceptionStatement
4469 Expression variable, expr;
4470 Statement statement;
4472 TemporaryVariable enumerator;
4476 MethodGroupExpr get_enumerator;
4477 PropertyExpr get_current;
4478 MethodInfo move_next;
4479 Type var_type, enumerator_type;
4482 public CollectionForeach (Type var_type, Expression var,
4483 Expression expr, Statement stmt, Location l)
4485 this.var_type = var_type;
4486 this.variable = var;
4492 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4494 Type [] args = TypeManager.GetArgumentTypes (mi);
4496 if (args.Length != 0)
4500 if (TypeManager.IsOverride (mi))
4503 // Check whether GetEnumerator is public
4504 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4507 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4509 // Apply the same optimization as MS: skip the GetEnumerator
4510 // returning an IEnumerator, and use the one returning a
4511 // CharEnumerator instead. This allows us to avoid the
4512 // try-finally block and the boxing.
4517 // Ok, we can access it, now make sure that we can do something
4518 // with this `GetEnumerator'
4521 Type return_type = mi.ReturnType;
4522 if (mi.ReturnType == TypeManager.ienumerator_type ||
4523 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4524 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4526 // If it is not an interface, lets try to find the methods ourselves.
4527 // For example, if we have:
4528 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4529 // We can avoid the iface call. This is a runtime perf boost.
4530 // even bigger if we have a ValueType, because we avoid the cost
4533 // We have to make sure that both methods exist for us to take
4534 // this path. If one of the methods does not exist, we will just
4535 // use the interface. Sadly, this complex if statement is the only
4536 // way I could do this without a goto
4539 if (return_type.IsInterface ||
4540 !FetchMoveNext (ec, return_type) ||
4541 !FetchGetCurrent (ec, return_type)) {
4542 move_next = TypeManager.bool_movenext_void;
4543 get_current = new PropertyExpr (
4544 ec, TypeManager.ienumerator_getcurrent, loc);
4549 // Ok, so they dont return an IEnumerable, we will have to
4550 // find if they support the GetEnumerator pattern.
4553 if (!FetchMoveNext (ec, return_type))
4556 if (!FetchGetCurrent (ec, return_type))
4560 enumerator_type = return_type;
4561 is_disposable = !enumerator_type.IsSealed ||
4562 TypeManager.ImplementsInterface (
4563 enumerator_type, TypeManager.idisposable_type);
4569 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4571 bool FetchMoveNext (EmitContext ec, Type t)
4573 MemberList move_next_list;
4575 move_next_list = TypeContainer.FindMembers (
4576 t, MemberTypes.Method,
4577 BindingFlags.Public | BindingFlags.Instance,
4578 Type.FilterName, "MoveNext");
4579 if (move_next_list.Count == 0)
4582 foreach (MemberInfo m in move_next_list){
4583 MethodInfo mi = (MethodInfo) m;
4586 args = TypeManager.GetArgumentTypes (mi);
4587 if ((args != null) && (args.Length == 0) &&
4588 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4598 // Retrieves a `public T get_Current ()' method from the Type `t'
4600 bool FetchGetCurrent (EmitContext ec, Type t)
4602 PropertyExpr pe = Expression.MemberLookup (
4603 ec, t, "Current", MemberTypes.Property,
4604 Expression.AllBindingFlags, loc) as PropertyExpr;
4613 // Retrieves a `public void Dispose ()' method from the Type `t'
4615 static MethodInfo FetchMethodDispose (Type t)
4617 MemberList dispose_list;
4619 dispose_list = TypeContainer.FindMembers (
4620 t, MemberTypes.Method,
4621 BindingFlags.Public | BindingFlags.Instance,
4622 Type.FilterName, "Dispose");
4623 if (dispose_list.Count == 0)
4626 foreach (MemberInfo m in dispose_list){
4627 MethodInfo mi = (MethodInfo) m;
4630 args = TypeManager.GetArgumentTypes (mi);
4631 if (args != null && args.Length == 0){
4632 if (mi.ReturnType == TypeManager.void_type)
4639 static public void error1579 (Type t, Location loc)
4641 Report.Error (1579, loc, "foreach statement cannot operate on " +
4642 "variables of type `{0}' because that class does " +
4643 "not provide a GetEnumerator method or it is " +
4644 "inaccessible", t.FullName);
4647 bool TryType (EmitContext ec, Type t)
4649 MethodGroupExpr mg = Expression.MemberLookup (
4650 ec, t, "GetEnumerator", MemberTypes.Method,
4651 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4655 foreach (MethodBase mb in mg.Methods) {
4656 if (!GetEnumeratorFilter (ec, (MethodInfo) mb))
4659 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) mb };
4660 get_enumerator = new MethodGroupExpr (mi, loc);
4662 if (t != expr.Type) {
4663 expr = Convert.ExplicitConversion (
4666 throw new InternalErrorException ();
4669 get_enumerator.InstanceExpression = expr;
4670 get_enumerator.IsBase = t != expr.Type;
4678 bool ProbeCollectionType (EmitContext ec, Type t)
4680 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4681 if (TryType (ec, tt))
4687 // Now try to find the method in the interfaces
4690 Type [] ifaces = t.GetInterfaces ();
4692 foreach (Type i in ifaces){
4693 if (TryType (ec, i))
4698 // Since TypeBuilder.GetInterfaces only returns the interface
4699 // types for this type, we have to keep looping, but once
4700 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4701 // done, because it returns all the types
4703 if ((t is TypeBuilder))
4712 public override bool Resolve (EmitContext ec)
4714 enumerator_type = TypeManager.ienumerator_type;
4715 is_disposable = true;
4717 if (!ProbeCollectionType (ec, expr.Type)) {
4718 error1579 (expr.Type, loc);
4722 enumerator = new TemporaryVariable (enumerator_type, loc);
4723 enumerator.Resolve (ec);
4725 init = new Invocation (get_enumerator, new ArrayList (), loc);
4726 init = init.Resolve (ec);
4730 Expression move_next_expr;
4732 MemberInfo[] mi = new MemberInfo[] { move_next };
4733 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4734 mg.InstanceExpression = enumerator;
4736 move_next_expr = new Invocation (mg, new ArrayList (), loc);
4739 get_current.InstanceExpression = enumerator;
4741 Statement block = new CollectionForeachStatement (
4742 var_type, variable, get_current, statement, loc);
4744 loop = new While (move_next_expr, block, loc);
4748 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4749 ec.CurrentBranching.CreateSibling ();
4751 FlowBranchingException branching = null;
4753 branching = ec.StartFlowBranching (this);
4755 if (!loop.Resolve (ec))
4758 if (is_disposable) {
4759 ResolveFinally (branching);
4760 ec.EndFlowBranching ();
4762 emit_finally = true;
4764 ec.EndFlowBranching ();
4769 protected override void DoEmit (EmitContext ec)
4771 ILGenerator ig = ec.ig;
4773 enumerator.Store (ec, init);
4776 // Protect the code in a try/finalize block, so that
4777 // if the beast implement IDisposable, we get rid of it
4779 if (is_disposable && emit_finally)
4780 ig.BeginExceptionBlock ();
4785 // Now the finally block
4787 if (is_disposable) {
4790 ig.EndExceptionBlock ();
4795 public override void EmitFinally (EmitContext ec)
4797 ILGenerator ig = ec.ig;
4799 if (enumerator_type.IsValueType) {
4800 enumerator.Emit (ec);
4802 MethodInfo mi = FetchMethodDispose (enumerator_type);
4804 enumerator.EmitLoadAddress (ec);
4805 ig.Emit (OpCodes.Call, mi);
4807 enumerator.Emit (ec);
4808 ig.Emit (OpCodes.Box, enumerator_type);
4809 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4812 Label call_dispose = ig.DefineLabel ();
4814 enumerator.Emit (ec);
4815 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4816 ig.Emit (OpCodes.Dup);
4817 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4818 ig.Emit (OpCodes.Pop);
4820 Label end_finally = ig.DefineLabel ();
4821 ig.Emit (OpCodes.Br, end_finally);
4823 ig.MarkLabel (call_dispose);
4824 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4825 ig.MarkLabel (end_finally);
4830 protected class CollectionForeachStatement : Statement
4833 Expression variable, current, conv;
4834 Statement statement;
4837 public CollectionForeachStatement (Type type, Expression variable,
4838 Expression current, Statement statement,
4842 this.variable = variable;
4843 this.current = current;
4844 this.statement = statement;
4848 public override bool Resolve (EmitContext ec)
4850 current = current.Resolve (ec);
4851 if (current == null)
4854 conv = Convert.ExplicitConversion (ec, current, type, loc);
4858 assign = new Assign (variable, conv, loc);
4859 if (assign.Resolve (ec) == null)
4862 if (!statement.Resolve (ec))
4868 protected override void DoEmit (EmitContext ec)
4870 assign.EmitStatement (ec);
4871 statement.Emit (ec);