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;
1015 public enum ReadOnlyContext: byte {
1022 ReadOnlyContext ro_context;
1024 public LocalInfo (Expression type, string name, Block block, Location l)
1032 public LocalInfo (TypeContainer tc, Block block, Location l)
1034 VariableType = tc.TypeBuilder;
1039 public bool IsThisAssigned (EmitContext ec, Location loc)
1041 if (VariableInfo == null)
1042 throw new Exception ();
1044 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1047 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1050 public bool IsAssigned (EmitContext ec)
1052 if (VariableInfo == null)
1053 throw new Exception ();
1055 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1058 public bool Resolve (EmitContext ec)
1060 if (VariableType == null) {
1061 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
1065 VariableType = texpr.Type;
1068 if (VariableType == TypeManager.void_type) {
1069 Report.Error (1547, Location,
1070 "Keyword 'void' cannot be used in this context");
1074 if (VariableType.IsAbstract && VariableType.IsSealed) {
1075 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1078 // TODO: breaks the build
1079 // if (VariableType.IsPointer && !ec.InUnsafe)
1080 // Expression.UnsafeError (Location);
1086 // Whether the variable is Fixed (because its Pinned or its a value type)
1088 public bool IsFixed {
1090 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1097 public bool IsCaptured {
1099 return (flags & Flags.Captured) != 0;
1103 flags |= Flags.Captured;
1107 public bool AddressTaken {
1109 return (flags & Flags.AddressTaken) != 0;
1113 flags |= Flags.AddressTaken;
1117 public override string ToString ()
1119 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1120 Name, Type, VariableInfo, Location);
1125 return (flags & Flags.Used) != 0;
1128 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1132 public bool ReadOnly {
1134 return (flags & Flags.ReadOnly) != 0;
1138 public void SetReadOnlyContext (ReadOnlyContext context)
1140 flags |= Flags.ReadOnly;
1141 ro_context = context;
1144 public string GetReadOnlyContext ()
1147 throw new InternalErrorException ("Variable is not readonly");
1149 switch (ro_context) {
1150 case ReadOnlyContext.Fixed:
1151 return "fixed variable";
1152 case ReadOnlyContext.Foreach:
1153 return "foreach iteration variable";
1154 case ReadOnlyContext.Using:
1155 return "using variable";
1157 throw new NotImplementedException ();
1161 // Whether the variable is pinned, if Pinned the variable has been
1162 // allocated in a pinned slot with DeclareLocal.
1164 public bool Pinned {
1166 return (flags & Flags.Pinned) != 0;
1169 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1173 public bool IsThis {
1175 return (flags & Flags.IsThis) != 0;
1178 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1184 /// Block represents a C# block.
1188 /// This class is used in a number of places: either to represent
1189 /// explicit blocks that the programmer places or implicit blocks.
1191 /// Implicit blocks are used as labels or to introduce variable
1194 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1195 /// they contain extra information that is not necessary on normal blocks.
1197 public class Block : Statement {
1198 public Block Parent;
1199 public readonly Location StartLocation;
1200 public Location EndLocation = Location.Null;
1202 public readonly ToplevelBlock Toplevel;
1209 VariablesInitialized = 8,
1218 public bool Implicit {
1220 return (flags & Flags.Implicit) != 0;
1224 public bool Unchecked {
1226 return (flags & Flags.Unchecked) != 0;
1229 flags |= Flags.Unchecked;
1233 public bool Unsafe {
1235 return (flags & Flags.Unsafe) != 0;
1238 flags |= Flags.Unsafe;
1242 public bool HasVarargs {
1245 return Parent.HasVarargs;
1247 return (flags & Flags.HasVarargs) != 0;
1250 flags |= Flags.HasVarargs;
1255 // The statements in this block
1257 ArrayList statements;
1261 // An array of Blocks. We keep track of children just
1262 // to generate the local variable declarations.
1264 // Statements and child statements are handled through the
1270 // Labels. (label, block) pairs.
1275 // Keeps track of (name, type) pairs
1277 Hashtable variables;
1280 // Keeps track of constants
1281 Hashtable constants;
1284 // If this is a switch section, the enclosing switch block.
1288 protected static int id;
1292 public Block (Block parent)
1293 : this (parent, (Flags) 0, Location.Null, Location.Null)
1296 public Block (Block parent, Flags flags)
1297 : this (parent, flags, Location.Null, Location.Null)
1300 public Block (Block parent, Location start, Location end)
1301 : this (parent, (Flags) 0, start, end)
1304 public Block (Block parent, Flags flags, Location start, Location end)
1307 parent.AddChild (this);
1309 this.Parent = parent;
1311 this.StartLocation = start;
1312 this.EndLocation = end;
1315 statements = new ArrayList ();
1317 if ((flags & Flags.IsToplevel) != 0)
1318 Toplevel = (ToplevelBlock) this;
1320 Toplevel = parent.Toplevel;
1322 if (parent != null && Implicit) {
1323 if (parent.known_variables == null)
1324 parent.known_variables = new Hashtable ();
1325 // share with parent
1326 known_variables = parent.known_variables;
1331 public Block CreateSwitchBlock (Location start)
1333 Block new_block = new Block (this, start, start);
1334 new_block.switch_block = this;
1344 void AddChild (Block b)
1346 if (children == null)
1347 children = new ArrayList ();
1352 public void SetEndLocation (Location loc)
1358 /// Adds a label to the current block.
1362 /// false if the name already exists in this block. true
1366 public bool AddLabel (string name, LabeledStatement target, Location loc)
1368 if (switch_block != null)
1369 return switch_block.AddLabel (name, target, loc);
1372 while (cur != null) {
1373 if (cur.DoLookupLabel (name) != null) {
1375 140, loc, "The label '{0}' is a duplicate",
1386 while (cur != null) {
1387 if (cur.DoLookupLabel (name) != null) {
1390 "The label '{0}' shadows another label " +
1391 "by the same name in a containing scope.",
1396 if (children != null) {
1397 foreach (Block b in children) {
1398 LabeledStatement s = b.DoLookupLabel (name);
1404 "The label '{0}' shadows another " +
1405 "label by the same name in a " +
1406 "containing scope.",
1417 labels = new Hashtable ();
1419 labels.Add (name, target);
1423 public LabeledStatement LookupLabel (string name)
1425 LabeledStatement s = DoLookupLabel (name);
1429 if (children == null)
1432 foreach (Block child in children) {
1433 if (!child.Implicit)
1436 s = child.LookupLabel (name);
1444 LabeledStatement DoLookupLabel (string name)
1446 if (switch_block != null)
1447 return switch_block.LookupLabel (name);
1450 if (labels.Contains (name))
1451 return ((LabeledStatement) labels [name]);
1456 LocalInfo this_variable = null;
1459 // Returns the "this" instance variable of this block.
1460 // See AddThisVariable() for more information.
1462 public LocalInfo ThisVariable {
1464 for (Block b = this; b != null; b = b.Parent) {
1465 if (b.this_variable != null)
1466 return b.this_variable;
1473 Hashtable known_variables;
1476 // Marks a variable with name @name as being used in this or a child block.
1477 // If a variable name has been used in a child block, it's illegal to
1478 // declare a variable with the same name in the current block.
1480 void AddKnownVariable (string name, LocalInfo info)
1482 if (known_variables == null)
1483 known_variables = new Hashtable ();
1485 known_variables [name] = info;
1488 LocalInfo GetKnownVariableInfo (string name)
1490 if (known_variables == null)
1492 return (LocalInfo) known_variables [name];
1495 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1497 LocalInfo kvi = GetKnownVariableInfo (name);
1498 if (kvi == null || kvi.Block == this)
1501 if (known_variables != kvi.Block.known_variables) {
1502 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1503 Report.Error (135, loc, "'{0}' has a different meaning in a child block", name);
1508 // this block and kvi.Block are the same textual block.
1509 // However, different variables are extant.
1511 // Check if the variable is in scope in both blocks. We use
1512 // an indirect check that depends on AddVariable doing its
1513 // part in maintaining the invariant-meaning-in-block property.
1515 if (e is LocalVariableReference || (e is Constant && GetLocalInfo (name) != null))
1518 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1519 Report.Error (136, loc, "'{0}' has a different meaning later in the block", name);
1524 // This is used by non-static `struct' constructors which do not have an
1525 // initializer - in this case, the constructor must initialize all of the
1526 // struct's fields. To do this, we add a "this" variable and use the flow
1527 // analysis code to ensure that it's been fully initialized before control
1528 // leaves the constructor.
1530 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1532 if (this_variable != null)
1533 return this_variable;
1535 if (variables == null)
1536 variables = new Hashtable ();
1538 this_variable = new LocalInfo (tc, this, l);
1539 this_variable.Used = true;
1540 this_variable.IsThis = true;
1542 variables.Add ("this", this_variable);
1544 return this_variable;
1547 public LocalInfo AddVariable (Expression type, string name, Location l)
1549 if (variables == null)
1550 variables = new Hashtable ();
1552 LocalInfo vi = GetLocalInfo (name);
1554 Report.SymbolRelatedToPreviousError (vi.Location, name);
1555 if (known_variables == vi.Block.known_variables)
1556 Report.Error (128, l,
1557 "A local variable '{0}' is already declared in this scope", name);
1559 Report.Error (136, l,
1560 "'{0}' hides the declaration of local variable '{0}' in a parent scope", name);
1564 vi = GetKnownVariableInfo (name);
1566 Report.SymbolRelatedToPreviousError (vi.Location, name);
1567 Report.Error (136, l,
1568 "A child block already has a declaration of local variable '{0}':" +
1569 " allowing this declaration would violate 'invariant meaning in a block'",
1575 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1577 Report.SymbolRelatedToPreviousError (Toplevel.Parameters.Location, name);
1578 Report.Error (136, l, "'{0}' hides a method parameter", name);
1582 vi = new LocalInfo (type, name, this, l);
1584 variables.Add (name, vi);
1586 for (Block b = this; b != null; b = b.Parent)
1587 b.AddKnownVariable (name, vi);
1589 if ((flags & Flags.VariablesInitialized) != 0)
1590 throw new Exception ();
1592 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1596 public bool AddConstant (Expression type, string name, Expression value, Location l)
1598 if (AddVariable (type, name, l) == null)
1601 if (constants == null)
1602 constants = new Hashtable ();
1604 constants.Add (name, value);
1608 public Hashtable Variables {
1614 public LocalInfo GetLocalInfo (string name)
1616 for (Block b = this; b != null; b = b.Parent) {
1617 if (b.variables != null) {
1618 LocalInfo ret = b.variables [name] as LocalInfo;
1626 public Expression GetVariableType (string name)
1628 LocalInfo vi = GetLocalInfo (name);
1636 public Expression GetConstantExpression (string name)
1638 for (Block b = this; b != null; b = b.Parent) {
1639 if (b.constants != null) {
1640 Expression ret = b.constants [name] as Expression;
1649 /// True if the variable named @name is a constant
1651 public bool IsConstant (string name)
1653 Expression e = null;
1655 e = GetConstantExpression (name);
1661 /// A list of labels that were not used within this block
1663 public string [] GetUnreferenced ()
1665 // FIXME: Implement me
1669 public void AddStatement (Statement s)
1672 flags |= Flags.BlockUsed;
1677 return (flags & Flags.BlockUsed) != 0;
1683 flags |= Flags.BlockUsed;
1686 public bool HasRet {
1688 return (flags & Flags.HasRet) != 0;
1692 public bool IsDestructor {
1694 return (flags & Flags.IsDestructor) != 0;
1698 public void SetDestructor ()
1700 flags |= Flags.IsDestructor;
1703 VariableMap param_map, local_map;
1705 public VariableMap ParameterMap {
1707 if ((flags & Flags.VariablesInitialized) == 0)
1708 throw new Exception ("Variables have not been initialized yet");
1714 public VariableMap LocalMap {
1716 if ((flags & Flags.VariablesInitialized) == 0)
1717 throw new Exception ("Variables have not been initialized yet");
1724 /// Emits the variable declarations and labels.
1727 /// tc: is our typecontainer (to resolve type references)
1728 /// ig: is the code generator:
1730 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1732 bool old_unsafe = ec.InUnsafe;
1734 // If some parent block was unsafe, we remain unsafe even if this block
1735 // isn't explicitly marked as such.
1736 ec.InUnsafe |= Unsafe;
1739 // Compute the VariableMap's.
1741 // Unfortunately, we don't know the type when adding variables with
1742 // AddVariable(), so we need to compute this info here.
1746 if (variables != null) {
1747 foreach (LocalInfo li in variables.Values)
1750 locals = new LocalInfo [variables.Count];
1751 variables.Values.CopyTo (locals, 0);
1753 locals = new LocalInfo [0];
1756 local_map = new VariableMap (Parent.LocalMap, locals);
1758 local_map = new VariableMap (locals);
1760 param_map = new VariableMap (ip);
1761 flags |= Flags.VariablesInitialized;
1763 bool old_check_state = ec.ConstantCheckState;
1764 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1767 // Process this block variables
1769 if (variables != null){
1770 foreach (DictionaryEntry de in variables){
1771 string name = (string) de.Key;
1772 LocalInfo vi = (LocalInfo) de.Value;
1774 if (vi.VariableType == null)
1777 Type variable_type = vi.VariableType;
1779 if (variable_type.IsPointer){
1781 // Am not really convinced that this test is required (Microsoft does it)
1782 // but the fact is that you would not be able to use the pointer variable
1785 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1792 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1795 // This is needed to compile on both .NET 1.x and .NET 2.x
1796 // the later introduced `DeclareLocal (Type t, bool pinned)'
1798 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1799 else if (!vi.IsThis)
1800 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1803 if (constants == null)
1806 Expression cv = (Expression) constants [name];
1810 ec.CurrentBlock = this;
1811 Expression e = cv.Resolve (ec);
1813 Constant ce = e as Constant;
1815 Report.Error (133, vi.Location,
1816 "The expression being assigned to '{0}' must be constant", name);
1820 if (e.Type != variable_type){
1821 e = Const.ChangeType (vi.Location, ce, variable_type);
1826 constants.Remove (name);
1827 constants.Add (name, e);
1830 ec.ConstantCheckState = old_check_state;
1833 // Now, handle the children
1835 if (children != null){
1836 foreach (Block b in children)
1837 b.ResolveMeta (toplevel, ec, ip);
1839 ec.InUnsafe = old_unsafe;
1843 // Emits the local variable declarations for a block
1845 public void EmitMeta (EmitContext ec)
1847 ILGenerator ig = ec.ig;
1849 if (variables != null){
1850 bool have_captured_vars = ec.HaveCapturedVariables ();
1851 bool remap_locals = ec.RemapToProxy;
1853 foreach (DictionaryEntry de in variables){
1854 LocalInfo vi = (LocalInfo) de.Value;
1856 if (have_captured_vars && ec.IsCaptured (vi))
1860 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1864 // This is needed to compile on both .NET 1.x and .NET 2.x
1865 // the later introduced `DeclareLocal (Type t, bool pinned)'
1867 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1868 else if (!vi.IsThis)
1869 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1874 if (children != null){
1875 foreach (Block b in children)
1880 void UsageWarning (FlowBranching.UsageVector vector)
1884 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1885 foreach (DictionaryEntry de in variables){
1886 LocalInfo vi = (LocalInfo) de.Value;
1891 name = (string) de.Key;
1893 if (vector.IsAssigned (vi.VariableInfo)){
1894 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1896 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1902 bool unreachable_shown;
1905 public override bool Resolve (EmitContext ec)
1907 Block prev_block = ec.CurrentBlock;
1910 int errors = Report.Errors;
1912 ec.CurrentBlock = this;
1913 ec.StartFlowBranching (this);
1915 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1918 // This flag is used to notate nested statements as unreachable from the beginning of this block.
1919 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
1920 // from the beginning of the function. The outer Resolve() that detected the unreachability is
1921 // responsible for handling the situation.
1923 int statement_count = statements.Count;
1924 for (int ix = 0; ix < statement_count; ix++){
1925 Statement s = (Statement) statements [ix];
1929 ((Block) s).unreachable = true;
1931 if (!unreachable_shown && (RootContext.WarningLevel >= 2)) {
1933 162, loc, "Unreachable code detected");
1934 unreachable_shown = true;
1938 if (!s.Resolve (ec)) {
1940 statements [ix] = EmptyStatement.Value;
1944 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1945 statements [ix] = EmptyStatement.Value;
1947 num_statements = ix + 1;
1948 if (s is LabeledStatement)
1949 unreachable = false;
1951 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1954 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1955 ec.CurrentBranching, statement_count, num_statements);
1958 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1960 ec.CurrentBlock = prev_block;
1962 // If we're a non-static `struct' constructor which doesn't have an
1963 // initializer, then we must initialize all of the struct's fields.
1964 if ((this_variable != null) &&
1965 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1966 !this_variable.IsThisAssigned (ec, loc))
1969 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1970 foreach (LabeledStatement label in labels.Values)
1971 if (!label.HasBeenReferenced)
1972 Report.Warning (164, label.Location,
1973 "This label has not been referenced");
1976 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1978 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1979 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1980 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1981 flags |= Flags.HasRet;
1983 if (ok && (errors == Report.Errors)) {
1984 if (RootContext.WarningLevel >= 3)
1985 UsageWarning (vector);
1991 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1993 unreachable_shown = true;
1996 if (warn && (RootContext.WarningLevel >= 2))
1997 Report.Warning (162, loc, "Unreachable code detected");
1999 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2000 bool ok = Resolve (ec);
2001 ec.KillFlowBranching ();
2006 protected override void DoEmit (EmitContext ec)
2008 for (int ix = 0; ix < num_statements; ix++){
2009 Statement s = (Statement) statements [ix];
2011 // Check whether we are the last statement in a
2014 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2015 ec.IsLastStatement = true;
2017 ec.IsLastStatement = false;
2023 public override void Emit (EmitContext ec)
2025 Block prev_block = ec.CurrentBlock;
2027 ec.CurrentBlock = this;
2029 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2030 bool is_lexical_block = !Implicit && (Parent != null);
2032 if (emit_debug_info) {
2033 if (is_lexical_block)
2036 if (variables != null) {
2037 foreach (DictionaryEntry de in variables) {
2038 string name = (string) de.Key;
2039 LocalInfo vi = (LocalInfo) de.Value;
2041 if (vi.LocalBuilder == null)
2044 ec.DefineLocalVariable (name, vi.LocalBuilder);
2049 ec.Mark (StartLocation, true);
2051 ec.Mark (EndLocation, true);
2053 if (emit_debug_info && is_lexical_block)
2056 ec.CurrentBlock = prev_block;
2060 // Returns true if we ar ea child of `b'.
2062 public bool IsChildOf (Block b)
2064 Block current = this;
2067 if (current.Parent == b)
2069 current = current.Parent;
2070 } while (current != null);
2074 public override string ToString ()
2076 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2081 // A toplevel block contains extra information, the split is done
2082 // only to separate information that would otherwise bloat the more
2083 // lightweight Block.
2085 // In particular, this was introduced when the support for Anonymous
2086 // Methods was implemented.
2088 public class ToplevelBlock : Block {
2090 // Pointer to the host of this anonymous method, or null
2091 // if we are the topmost block
2093 public ToplevelBlock Container;
2094 CaptureContext capture_context;
2095 FlowBranching top_level_branching;
2097 Hashtable capture_contexts;
2100 // The parameters for the block.
2102 public readonly Parameters Parameters;
2104 public void RegisterCaptureContext (CaptureContext cc)
2106 if (capture_contexts == null)
2107 capture_contexts = new Hashtable ();
2108 capture_contexts [cc] = cc;
2111 public void CompleteContexts ()
2113 if (capture_contexts == null)
2116 foreach (CaptureContext cc in capture_contexts.Keys){
2121 public CaptureContext ToplevelBlockCaptureContext {
2123 return capture_context;
2128 // Parent is only used by anonymous blocks to link back to their
2131 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2132 this (container, (Flags) 0, parameters, start)
2136 public ToplevelBlock (Parameters parameters, Location start) :
2137 this (null, (Flags) 0, parameters, start)
2141 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2142 this (null, flags, parameters, start)
2146 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2147 base (null, flags | Flags.IsToplevel, start, Location.Null)
2149 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2150 Container = container;
2153 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2157 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2159 if (capture_context == null)
2160 capture_context = new CaptureContext (this, loc, host);
2163 public CaptureContext CaptureContext {
2165 return capture_context;
2169 public FlowBranching TopLevelBranching {
2171 return top_level_branching;
2176 // Returns a `ParameterReference' for the given name, or null if there
2177 // is no such parameter
2179 public ParameterReference GetParameterReference (string name, Location loc)
2184 for (ToplevelBlock t = this; t != null; t = t.Container) {
2185 Parameters pars = t.Parameters;
2186 par = pars.GetParameterByName (name, out idx);
2188 return new ParameterReference (pars, this, idx, name, loc);
2194 // Whether the parameter named `name' is local to this block,
2195 // or false, if the parameter belongs to an encompassing block.
2197 public bool IsLocalParameter (string name)
2199 return Parameters.GetParameterByName (name) != null;
2203 // Whether the `name' is a parameter reference
2205 public bool IsParameterReference (string name)
2210 for (ToplevelBlock t = this; t != null; t = t.Container) {
2211 if (t.IsLocalParameter (name))
2217 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2219 int errors = Report.Errors;
2221 if (top_level_branching != null)
2224 ResolveMeta (this, ec, ip);
2226 top_level_branching = ec.StartFlowBranching (this);
2228 return Report.Errors == errors;
2232 public class SwitchLabel {
2235 public Location loc;
2239 Label il_label_code;
2240 bool il_label_code_set;
2243 // if expr == null, then it is the default case.
2245 public SwitchLabel (Expression expr, Location l)
2251 public Expression Label {
2257 public object Converted {
2263 public Label GetILLabel (EmitContext ec)
2266 il_label = ec.ig.DefineLabel ();
2267 il_label_set = true;
2272 public Label GetILLabelCode (EmitContext ec)
2274 if (!il_label_code_set){
2275 il_label_code = ec.ig.DefineLabel ();
2276 il_label_code_set = true;
2278 return il_label_code;
2282 // Resolves the expression, reduces it to a literal if possible
2283 // and then converts it to the requested type.
2285 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2290 Expression e = label.Resolve (ec);
2295 if (!(e is Constant)){
2296 Report.Error (150, loc, "A constant value is expected, got: " + e);
2300 if (e is StringConstant || e is NullLiteral){
2301 if (required_type == TypeManager.string_type){
2307 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2308 if (converted == null)
2315 public class SwitchSection {
2316 // An array of SwitchLabels.
2317 public readonly ArrayList Labels;
2318 public readonly Block Block;
2320 public SwitchSection (ArrayList labels, Block block)
2327 public class Switch : Statement {
2328 public readonly ArrayList Sections;
2329 public Expression Expr;
2332 /// Maps constants whose type type SwitchType to their SwitchLabels.
2334 public Hashtable Elements;
2337 /// The governing switch type
2339 public Type SwitchType;
2344 Label default_target;
2345 Expression new_expr;
2347 SwitchSection constant_section;
2348 SwitchSection default_section;
2351 // The types allowed to be implicitly cast from
2352 // on the governing type
2354 static Type [] allowed_types;
2356 public Switch (Expression e, ArrayList sects, Location l)
2363 public bool GotDefault {
2365 return default_section != null;
2369 public Label DefaultTarget {
2371 return default_target;
2376 // Determines the governing type for a switch. The returned
2377 // expression might be the expression from the switch, or an
2378 // expression that includes any potential conversions to the
2379 // integral types or to string.
2381 Expression SwitchGoverningType (EmitContext ec, Type t)
2383 if (t == TypeManager.int32_type ||
2384 t == TypeManager.uint32_type ||
2385 t == TypeManager.char_type ||
2386 t == TypeManager.byte_type ||
2387 t == TypeManager.sbyte_type ||
2388 t == TypeManager.ushort_type ||
2389 t == TypeManager.short_type ||
2390 t == TypeManager.uint64_type ||
2391 t == TypeManager.int64_type ||
2392 t == TypeManager.string_type ||
2393 t == TypeManager.bool_type ||
2394 t.IsSubclassOf (TypeManager.enum_type))
2397 if (allowed_types == null){
2398 allowed_types = new Type [] {
2399 TypeManager.int32_type,
2400 TypeManager.uint32_type,
2401 TypeManager.sbyte_type,
2402 TypeManager.byte_type,
2403 TypeManager.short_type,
2404 TypeManager.ushort_type,
2405 TypeManager.int64_type,
2406 TypeManager.uint64_type,
2407 TypeManager.char_type,
2408 TypeManager.bool_type,
2409 TypeManager.string_type
2414 // Try to find a *user* defined implicit conversion.
2416 // If there is no implicit conversion, or if there are multiple
2417 // conversions, we have to report an error
2419 Expression converted = null;
2420 foreach (Type tt in allowed_types){
2423 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2428 // Ignore over-worked ImplicitUserConversions that do
2429 // an implicit conversion in addition to the user conversion.
2432 UserCast ue = e as UserCast;
2434 if (ue.Source != Expr)
2438 if (converted != null){
2439 Report.ExtraInformation (
2441 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2442 TypeManager.CSharpName (Expr.Type)));
2451 static string Error152 {
2453 return "The label '{0}:' already occurs in this switch statement";
2458 // Performs the basic sanity checks on the switch statement
2459 // (looks for duplicate keys and non-constant expressions).
2461 // It also returns a hashtable with the keys that we will later
2462 // use to compute the switch tables
2464 bool CheckSwitch (EmitContext ec)
2468 Elements = new Hashtable ();
2470 if (TypeManager.IsEnumType (SwitchType)){
2471 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2473 compare_type = SwitchType;
2475 foreach (SwitchSection ss in Sections){
2476 foreach (SwitchLabel sl in ss.Labels){
2477 if (!sl.ResolveAndReduce (ec, SwitchType)){
2482 if (sl.Label == null){
2483 if (default_section != null){
2484 Report.Error (152, sl.loc, Error152, "default");
2487 default_section = ss;
2491 object key = sl.Converted;
2493 if (key is Constant)
2494 key = ((Constant) key).GetValue ();
2497 key = NullLiteral.Null;
2499 string lname = null;
2500 if (compare_type == TypeManager.uint64_type){
2501 ulong v = (ulong) key;
2503 if (Elements.Contains (v))
2504 lname = v.ToString ();
2506 Elements.Add (v, sl);
2507 } else if (compare_type == TypeManager.int64_type){
2508 long v = (long) key;
2510 if (Elements.Contains (v))
2511 lname = v.ToString ();
2513 Elements.Add (v, sl);
2514 } else if (compare_type == TypeManager.uint32_type){
2515 uint v = (uint) key;
2517 if (Elements.Contains (v))
2518 lname = v.ToString ();
2520 Elements.Add (v, sl);
2521 } else if (compare_type == TypeManager.char_type){
2522 char v = (char) key;
2524 if (Elements.Contains (v))
2525 lname = v.ToString ();
2527 Elements.Add (v, sl);
2528 } else if (compare_type == TypeManager.byte_type){
2529 byte v = (byte) key;
2531 if (Elements.Contains (v))
2532 lname = v.ToString ();
2534 Elements.Add (v, sl);
2535 } else if (compare_type == TypeManager.sbyte_type){
2536 sbyte v = (sbyte) key;
2538 if (Elements.Contains (v))
2539 lname = v.ToString ();
2541 Elements.Add (v, sl);
2542 } else if (compare_type == TypeManager.short_type){
2543 short v = (short) key;
2545 if (Elements.Contains (v))
2546 lname = v.ToString ();
2548 Elements.Add (v, sl);
2549 } else if (compare_type == TypeManager.ushort_type){
2550 ushort v = (ushort) key;
2552 if (Elements.Contains (v))
2553 lname = v.ToString ();
2555 Elements.Add (v, sl);
2556 } else if (compare_type == TypeManager.string_type){
2557 if (key is NullLiteral){
2558 if (Elements.Contains (NullLiteral.Null))
2561 Elements.Add (NullLiteral.Null, null);
2563 string s = (string) key;
2565 if (Elements.Contains (s))
2568 Elements.Add (s, sl);
2570 } else if (compare_type == TypeManager.int32_type) {
2573 if (Elements.Contains (v))
2574 lname = v.ToString ();
2576 Elements.Add (v, sl);
2577 } else if (compare_type == TypeManager.bool_type) {
2578 bool v = (bool) key;
2580 if (Elements.Contains (v))
2581 lname = v.ToString ();
2583 Elements.Add (v, sl);
2587 throw new Exception ("Unknown switch type!" +
2588 SwitchType + " " + compare_type);
2592 Report.Error (152, sl.loc, Error152, "case " + lname);
2603 void EmitObjectInteger (ILGenerator ig, object k)
2606 IntConstant.EmitInt (ig, (int) k);
2607 else if (k is Constant) {
2608 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2611 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2614 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2616 IntConstant.EmitInt (ig, (int) (long) k);
2617 ig.Emit (OpCodes.Conv_I8);
2620 LongConstant.EmitLong (ig, (long) k);
2622 else if (k is ulong)
2624 if ((ulong) k < (1L<<32))
2626 IntConstant.EmitInt (ig, (int) (long) k);
2627 ig.Emit (OpCodes.Conv_U8);
2631 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2635 IntConstant.EmitInt (ig, (int) ((char) k));
2636 else if (k is sbyte)
2637 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2639 IntConstant.EmitInt (ig, (int) ((byte) k));
2640 else if (k is short)
2641 IntConstant.EmitInt (ig, (int) ((short) k));
2642 else if (k is ushort)
2643 IntConstant.EmitInt (ig, (int) ((ushort) k));
2645 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2647 throw new Exception ("Unhandled case");
2650 // structure used to hold blocks of keys while calculating table switch
2651 class KeyBlock : IComparable
2653 public KeyBlock (long _nFirst)
2655 nFirst = nLast = _nFirst;
2659 public ArrayList rgKeys = null;
2660 // how many items are in the bucket
2661 public int Size = 1;
2664 get { return (int) (nLast - nFirst + 1); }
2666 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2668 return kbLast.nLast - kbFirst.nFirst + 1;
2670 public int CompareTo (object obj)
2672 KeyBlock kb = (KeyBlock) obj;
2673 int nLength = Length;
2674 int nLengthOther = kb.Length;
2675 if (nLengthOther == nLength)
2676 return (int) (kb.nFirst - nFirst);
2677 return nLength - nLengthOther;
2682 /// This method emits code for a lookup-based switch statement (non-string)
2683 /// Basically it groups the cases into blocks that are at least half full,
2684 /// and then spits out individual lookup opcodes for each block.
2685 /// It emits the longest blocks first, and short blocks are just
2686 /// handled with direct compares.
2688 /// <param name="ec"></param>
2689 /// <param name="val"></param>
2690 /// <returns></returns>
2691 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2693 int cElements = Elements.Count;
2694 object [] rgKeys = new object [cElements];
2695 Elements.Keys.CopyTo (rgKeys, 0);
2696 Array.Sort (rgKeys);
2698 // initialize the block list with one element per key
2699 ArrayList rgKeyBlocks = new ArrayList ();
2700 foreach (object key in rgKeys)
2701 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2704 // iteratively merge the blocks while they are at least half full
2705 // there's probably a really cool way to do this with a tree...
2706 while (rgKeyBlocks.Count > 1)
2708 ArrayList rgKeyBlocksNew = new ArrayList ();
2709 kbCurr = (KeyBlock) rgKeyBlocks [0];
2710 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2712 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2713 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2716 kbCurr.nLast = kb.nLast;
2717 kbCurr.Size += kb.Size;
2721 // start a new block
2722 rgKeyBlocksNew.Add (kbCurr);
2726 rgKeyBlocksNew.Add (kbCurr);
2727 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2729 rgKeyBlocks = rgKeyBlocksNew;
2732 // initialize the key lists
2733 foreach (KeyBlock kb in rgKeyBlocks)
2734 kb.rgKeys = new ArrayList ();
2736 // fill the key lists
2738 if (rgKeyBlocks.Count > 0) {
2739 kbCurr = (KeyBlock) rgKeyBlocks [0];
2740 foreach (object key in rgKeys)
2742 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2743 System.Convert.ToInt64 (key) > kbCurr.nLast;
2745 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2746 kbCurr.rgKeys.Add (key);
2750 // sort the blocks so we can tackle the largest ones first
2751 rgKeyBlocks.Sort ();
2753 // okay now we can start...
2754 ILGenerator ig = ec.ig;
2755 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2756 Label lblDefault = ig.DefineLabel ();
2758 Type typeKeys = null;
2759 if (rgKeys.Length > 0)
2760 typeKeys = rgKeys [0].GetType (); // used for conversions
2764 if (TypeManager.IsEnumType (SwitchType))
2765 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2767 compare_type = SwitchType;
2769 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2771 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2772 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2775 foreach (object key in kb.rgKeys)
2777 ig.Emit (OpCodes.Ldloc, val);
2778 EmitObjectInteger (ig, key);
2779 SwitchLabel sl = (SwitchLabel) Elements [key];
2780 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2785 // TODO: if all the keys in the block are the same and there are
2786 // no gaps/defaults then just use a range-check.
2787 if (compare_type == TypeManager.int64_type ||
2788 compare_type == TypeManager.uint64_type)
2790 // TODO: optimize constant/I4 cases
2792 // check block range (could be > 2^31)
2793 ig.Emit (OpCodes.Ldloc, val);
2794 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2795 ig.Emit (OpCodes.Blt, lblDefault);
2796 ig.Emit (OpCodes.Ldloc, val);
2797 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2798 ig.Emit (OpCodes.Bgt, lblDefault);
2801 ig.Emit (OpCodes.Ldloc, val);
2804 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2805 ig.Emit (OpCodes.Sub);
2807 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2812 ig.Emit (OpCodes.Ldloc, val);
2813 int nFirst = (int) kb.nFirst;
2816 IntConstant.EmitInt (ig, nFirst);
2817 ig.Emit (OpCodes.Sub);
2819 else if (nFirst < 0)
2821 IntConstant.EmitInt (ig, -nFirst);
2822 ig.Emit (OpCodes.Add);
2826 // first, build the list of labels for the switch
2828 int cJumps = kb.Length;
2829 Label [] rgLabels = new Label [cJumps];
2830 for (int iJump = 0; iJump < cJumps; iJump++)
2832 object key = kb.rgKeys [iKey];
2833 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2835 SwitchLabel sl = (SwitchLabel) Elements [key];
2836 rgLabels [iJump] = sl.GetILLabel (ec);
2840 rgLabels [iJump] = lblDefault;
2842 // emit the switch opcode
2843 ig.Emit (OpCodes.Switch, rgLabels);
2846 // mark the default for this block
2848 ig.MarkLabel (lblDefault);
2851 // TODO: find the default case and emit it here,
2852 // to prevent having to do the following jump.
2853 // make sure to mark other labels in the default section
2855 // the last default just goes to the end
2856 ig.Emit (OpCodes.Br, lblDefault);
2858 // now emit the code for the sections
2859 bool fFoundDefault = false;
2860 foreach (SwitchSection ss in Sections)
2862 foreach (SwitchLabel sl in ss.Labels)
2864 ig.MarkLabel (sl.GetILLabel (ec));
2865 ig.MarkLabel (sl.GetILLabelCode (ec));
2866 if (sl.Label == null)
2868 ig.MarkLabel (lblDefault);
2869 fFoundDefault = true;
2873 //ig.Emit (OpCodes.Br, lblEnd);
2876 if (!fFoundDefault) {
2877 ig.MarkLabel (lblDefault);
2879 ig.MarkLabel (lblEnd);
2882 // This simple emit switch works, but does not take advantage of the
2884 // TODO: remove non-string logic from here
2885 // TODO: binary search strings?
2887 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2889 ILGenerator ig = ec.ig;
2890 Label end_of_switch = ig.DefineLabel ();
2891 Label next_test = ig.DefineLabel ();
2892 Label null_target = ig.DefineLabel ();
2893 bool first_test = true;
2894 bool pending_goto_end = false;
2895 bool null_marked = false;
2898 ig.Emit (OpCodes.Ldloc, val);
2900 if (Elements.Contains (NullLiteral.Null)){
2901 ig.Emit (OpCodes.Brfalse, null_target);
2903 ig.Emit (OpCodes.Brfalse, default_target);
2905 ig.Emit (OpCodes.Ldloc, val);
2906 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2907 ig.Emit (OpCodes.Stloc, val);
2909 int section_count = Sections.Count;
2910 for (int section = 0; section < section_count; section++){
2911 SwitchSection ss = (SwitchSection) Sections [section];
2913 if (ss == default_section)
2916 Label sec_begin = ig.DefineLabel ();
2918 ig.Emit (OpCodes.Nop);
2920 if (pending_goto_end)
2921 ig.Emit (OpCodes.Br, end_of_switch);
2923 int label_count = ss.Labels.Count;
2925 for (int label = 0; label < label_count; label++){
2926 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2927 ig.MarkLabel (sl.GetILLabel (ec));
2930 ig.MarkLabel (next_test);
2931 next_test = ig.DefineLabel ();
2934 // If we are the default target
2936 if (sl.Label != null){
2937 object lit = sl.Converted;
2939 if (lit is NullLiteral){
2941 if (label_count == 1)
2942 ig.Emit (OpCodes.Br, next_test);
2946 StringConstant str = (StringConstant) lit;
2948 ig.Emit (OpCodes.Ldloc, val);
2949 ig.Emit (OpCodes.Ldstr, str.Value);
2950 if (label_count == 1)
2951 ig.Emit (OpCodes.Bne_Un, next_test);
2953 if (label+1 == label_count)
2954 ig.Emit (OpCodes.Bne_Un, next_test);
2956 ig.Emit (OpCodes.Beq, sec_begin);
2961 ig.MarkLabel (null_target);
2964 ig.MarkLabel (sec_begin);
2965 foreach (SwitchLabel sl in ss.Labels)
2966 ig.MarkLabel (sl.GetILLabelCode (ec));
2969 pending_goto_end = !ss.Block.HasRet;
2972 ig.MarkLabel (next_test);
2973 ig.MarkLabel (default_target);
2975 ig.MarkLabel (null_target);
2976 if (default_section != null)
2977 default_section.Block.Emit (ec);
2978 ig.MarkLabel (end_of_switch);
2981 SwitchSection FindSection (SwitchLabel label)
2983 foreach (SwitchSection ss in Sections){
2984 foreach (SwitchLabel sl in ss.Labels){
2993 public override bool Resolve (EmitContext ec)
2995 Expr = Expr.Resolve (ec);
2999 new_expr = SwitchGoverningType (ec, Expr.Type);
3000 if (new_expr == null){
3001 Report.Error (151, loc, "An integer type or string was expected for switch");
3006 SwitchType = new_expr.Type;
3008 if (!CheckSwitch (ec))
3011 Switch old_switch = ec.Switch;
3013 ec.Switch.SwitchType = SwitchType;
3015 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3016 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3018 is_constant = new_expr is Constant;
3020 object key = ((Constant) new_expr).GetValue ();
3021 SwitchLabel label = (SwitchLabel) Elements [key];
3023 constant_section = FindSection (label);
3024 if (constant_section == null)
3025 constant_section = default_section;
3029 foreach (SwitchSection ss in Sections){
3031 ec.CurrentBranching.CreateSibling (
3032 null, FlowBranching.SiblingType.SwitchSection);
3036 if (is_constant && (ss != constant_section)) {
3037 // If we're a constant switch, we're only emitting
3038 // one single section - mark all the others as
3040 ec.CurrentBranching.CurrentUsageVector.Goto ();
3041 if (!ss.Block.ResolveUnreachable (ec, true))
3044 if (!ss.Block.Resolve (ec))
3049 if (default_section == null)
3050 ec.CurrentBranching.CreateSibling (
3051 null, FlowBranching.SiblingType.SwitchSection);
3053 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3054 ec.Switch = old_switch;
3056 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3062 protected override void DoEmit (EmitContext ec)
3064 ILGenerator ig = ec.ig;
3066 // Store variable for comparission purposes
3069 value = ig.DeclareLocal (SwitchType);
3071 ig.Emit (OpCodes.Stloc, value);
3075 default_target = ig.DefineLabel ();
3078 // Setup the codegen context
3080 Label old_end = ec.LoopEnd;
3081 Switch old_switch = ec.Switch;
3083 ec.LoopEnd = ig.DefineLabel ();
3088 if (constant_section != null)
3089 constant_section.Block.Emit (ec);
3090 } else if (SwitchType == TypeManager.string_type)
3091 SimpleSwitchEmit (ec, value);
3093 TableSwitchEmit (ec, value);
3095 // Restore context state.
3096 ig.MarkLabel (ec.LoopEnd);
3099 // Restore the previous context
3101 ec.LoopEnd = old_end;
3102 ec.Switch = old_switch;
3106 public abstract class ExceptionStatement : Statement
3108 public abstract void EmitFinally (EmitContext ec);
3110 protected bool emit_finally = true;
3111 ArrayList parent_vectors;
3113 protected void DoEmitFinally (EmitContext ec)
3116 ec.ig.BeginFinallyBlock ();
3117 else if (ec.InIterator)
3118 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3122 protected void ResolveFinally (FlowBranchingException branching)
3124 emit_finally = branching.EmitFinally;
3126 branching.Parent.StealFinallyClauses (ref parent_vectors);
3130 public class Lock : ExceptionStatement {
3132 Statement Statement;
3135 public Lock (Expression expr, Statement stmt, Location l)
3142 public override bool Resolve (EmitContext ec)
3144 expr = expr.Resolve (ec);
3148 if (expr.Type.IsValueType){
3149 Error (185, "lock statement requires the expression to be " +
3150 " a reference type (type is: `{0}'",
3151 TypeManager.CSharpName (expr.Type));
3155 FlowBranchingException branching = ec.StartFlowBranching (this);
3156 bool ok = Statement.Resolve (ec);
3158 ec.KillFlowBranching ();
3162 ResolveFinally (branching);
3164 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3165 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3166 // Unfortunately, System.Reflection.Emit automatically emits
3167 // a leave to the end of the finally block.
3168 // This is a problem if `returns' is true since we may jump
3169 // to a point after the end of the method.
3170 // As a workaround, emit an explicit ret here.
3171 ec.NeedReturnLabel ();
3177 protected override void DoEmit (EmitContext ec)
3179 Type type = expr.Type;
3181 ILGenerator ig = ec.ig;
3182 temp = ig.DeclareLocal (type);
3185 ig.Emit (OpCodes.Dup);
3186 ig.Emit (OpCodes.Stloc, temp);
3187 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3191 ig.BeginExceptionBlock ();
3192 Statement.Emit (ec);
3197 ig.EndExceptionBlock ();
3200 public override void EmitFinally (EmitContext ec)
3202 ILGenerator ig = ec.ig;
3203 ig.Emit (OpCodes.Ldloc, temp);
3204 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3208 public class Unchecked : Statement {
3209 public readonly Block Block;
3211 public Unchecked (Block b)
3217 public override bool Resolve (EmitContext ec)
3219 bool previous_state = ec.CheckState;
3220 bool previous_state_const = ec.ConstantCheckState;
3222 ec.CheckState = false;
3223 ec.ConstantCheckState = false;
3224 bool ret = Block.Resolve (ec);
3225 ec.CheckState = previous_state;
3226 ec.ConstantCheckState = previous_state_const;
3231 protected override void DoEmit (EmitContext ec)
3233 bool previous_state = ec.CheckState;
3234 bool previous_state_const = ec.ConstantCheckState;
3236 ec.CheckState = false;
3237 ec.ConstantCheckState = false;
3239 ec.CheckState = previous_state;
3240 ec.ConstantCheckState = previous_state_const;
3244 public class Checked : Statement {
3245 public readonly Block Block;
3247 public Checked (Block b)
3250 b.Unchecked = false;
3253 public override bool Resolve (EmitContext ec)
3255 bool previous_state = ec.CheckState;
3256 bool previous_state_const = ec.ConstantCheckState;
3258 ec.CheckState = true;
3259 ec.ConstantCheckState = true;
3260 bool ret = Block.Resolve (ec);
3261 ec.CheckState = previous_state;
3262 ec.ConstantCheckState = previous_state_const;
3267 protected override void DoEmit (EmitContext ec)
3269 bool previous_state = ec.CheckState;
3270 bool previous_state_const = ec.ConstantCheckState;
3272 ec.CheckState = true;
3273 ec.ConstantCheckState = true;
3275 ec.CheckState = previous_state;
3276 ec.ConstantCheckState = previous_state_const;
3280 public class Unsafe : Statement {
3281 public readonly Block Block;
3283 public Unsafe (Block b)
3286 Block.Unsafe = true;
3289 public override bool Resolve (EmitContext ec)
3291 bool previous_state = ec.InUnsafe;
3295 val = Block.Resolve (ec);
3296 ec.InUnsafe = previous_state;
3301 protected override void DoEmit (EmitContext ec)
3303 bool previous_state = ec.InUnsafe;
3307 ec.InUnsafe = previous_state;
3314 public class Fixed : Statement {
3316 ArrayList declarators;
3317 Statement statement;
3322 abstract class Emitter
3324 protected LocalInfo vi;
3325 protected Expression converted;
3327 protected Emitter (Expression expr, LocalInfo li)
3333 public abstract void Emit (EmitContext ec);
3334 public abstract void EmitExit (ILGenerator ig);
3337 class ExpressionEmitter: Emitter {
3338 public ExpressionEmitter (Expression converted, LocalInfo li) :
3339 base (converted, li)
3343 public override void Emit (EmitContext ec) {
3345 // Store pointer in pinned location
3347 converted.Emit (ec);
3348 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3351 public override void EmitExit (ILGenerator ig)
3353 ig.Emit (OpCodes.Ldc_I4_0);
3354 ig.Emit (OpCodes.Conv_U);
3355 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3359 class StringEmitter: Emitter {
3360 LocalBuilder pinned_string;
3363 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3369 public override void Emit (EmitContext ec)
3371 ILGenerator ig = ec.ig;
3372 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3374 converted.Emit (ec);
3375 ig.Emit (OpCodes.Stloc, pinned_string);
3377 Expression sptr = new StringPtr (pinned_string, loc);
3378 converted = Convert.ImplicitConversionRequired (
3379 ec, sptr, vi.VariableType, loc);
3381 if (converted == null)
3384 converted.Emit (ec);
3385 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3388 public override void EmitExit(ILGenerator ig)
3390 ig.Emit (OpCodes.Ldnull);
3391 ig.Emit (OpCodes.Stloc, pinned_string);
3395 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3398 declarators = decls;
3403 public override bool Resolve (EmitContext ec)
3406 Expression.UnsafeError (loc);
3410 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3414 expr_type = texpr.Type;
3416 CheckObsolete (expr_type);
3418 if (ec.RemapToProxy){
3419 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3423 data = new Emitter [declarators.Count];
3425 if (!expr_type.IsPointer){
3426 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3431 foreach (Pair p in declarators){
3432 LocalInfo vi = (LocalInfo) p.First;
3433 Expression e = (Expression) p.Second;
3435 vi.VariableInfo.SetAssigned (ec);
3436 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3439 // The rules for the possible declarators are pretty wise,
3440 // but the production on the grammar is more concise.
3442 // So we have to enforce these rules here.
3444 // We do not resolve before doing the case 1 test,
3445 // because the grammar is explicit in that the token &
3446 // is present, so we need to test for this particular case.
3450 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3455 // Case 1: & object.
3457 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3458 Expression child = ((Unary) e).Expr;
3460 if (child is ParameterReference || child is LocalVariableReference){
3463 "No need to use fixed statement for parameters or " +
3464 "local variable declarations (address is already " +
3469 ec.InFixedInitializer = true;
3471 ec.InFixedInitializer = false;
3475 child = ((Unary) e).Expr;
3477 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3480 data [i] = new ExpressionEmitter (e, vi);
3486 ec.InFixedInitializer = true;
3488 ec.InFixedInitializer = false;
3495 if (e.Type.IsArray){
3496 Type array_type = TypeManager.GetElementType (e.Type);
3499 // Provided that array_type is unmanaged,
3501 if (!TypeManager.VerifyUnManaged (array_type, loc))
3505 // and T* is implicitly convertible to the
3506 // pointer type given in the fixed statement.
3508 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3510 Expression converted = Convert.ImplicitConversionRequired (
3511 ec, array_ptr, vi.VariableType, loc);
3512 if (converted == null)
3515 data [i] = new ExpressionEmitter (converted, vi);
3524 if (e.Type == TypeManager.string_type){
3525 data [i] = new StringEmitter (e, vi, loc);
3530 // Case 4: fixed buffer
3531 FieldExpr fe = e as FieldExpr;
3533 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3535 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3537 Expression converted = Convert.ImplicitConversionRequired (
3538 ec, fixed_buffer_ptr, vi.VariableType, loc);
3539 if (converted == null)
3542 data [i] = new ExpressionEmitter (converted, vi);
3550 // For other cases, flag a `this is already fixed expression'
3552 if (e is LocalVariableReference || e is ParameterReference ||
3553 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3555 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3559 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3563 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3565 if (!statement.Resolve (ec)) {
3566 ec.KillFlowBranching ();
3570 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3571 has_ret = reachability.IsUnreachable;
3576 protected override void DoEmit (EmitContext ec)
3578 for (int i = 0; i < data.Length; i++) {
3582 statement.Emit (ec);
3587 ILGenerator ig = ec.ig;
3590 // Clear the pinned variable
3592 for (int i = 0; i < data.Length; i++) {
3593 data [i].EmitExit (ig);
3598 public class Catch: Statement {
3599 public readonly string Name;
3600 public readonly Block Block;
3602 Expression type_expr;
3605 public Catch (Expression type, string name, Block block, Location l)
3613 public Type CatchType {
3619 public bool IsGeneral {
3621 return type_expr == null;
3625 protected override void DoEmit(EmitContext ec)
3629 public override bool Resolve (EmitContext ec)
3631 bool was_catch = ec.InCatch;
3634 if (type_expr != null) {
3635 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3639 type = te.ResolveType (ec);
3641 CheckObsolete (type);
3643 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3644 Error (155, "The type caught or thrown must be derived from System.Exception");
3650 return Block.Resolve (ec);
3653 ec.InCatch = was_catch;
3658 public class Try : ExceptionStatement {
3659 public readonly Block Fini, Block;
3660 public readonly ArrayList Specific;
3661 public readonly Catch General;
3663 bool need_exc_block;
3666 // specific, general and fini might all be null.
3668 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3670 if (specific == null && general == null){
3671 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3675 this.Specific = specific;
3676 this.General = general;
3681 public override bool Resolve (EmitContext ec)
3685 FlowBranchingException branching = ec.StartFlowBranching (this);
3687 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3689 if (!Block.Resolve (ec))
3692 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3694 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3696 Type[] prevCatches = new Type [Specific.Count];
3698 foreach (Catch c in Specific){
3699 ec.CurrentBranching.CreateSibling (
3700 c.Block, FlowBranching.SiblingType.Catch);
3702 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3704 if (c.Name != null) {
3705 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3707 throw new Exception ();
3709 vi.VariableInfo = null;
3712 if (!c.Resolve (ec))
3715 Type resolvedType = c.CatchType;
3716 for (int ii = 0; ii < last_index; ++ii) {
3717 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3718 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3723 prevCatches [last_index++] = resolvedType;
3724 need_exc_block = true;
3727 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3729 if (General != null){
3730 ec.CurrentBranching.CreateSibling (
3731 General.Block, FlowBranching.SiblingType.Catch);
3733 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3735 if (!General.Resolve (ec))
3738 need_exc_block = true;
3741 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3745 ec.CurrentBranching.CreateSibling (
3746 Fini, FlowBranching.SiblingType.Finally);
3748 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3749 bool was_finally = ec.InFinally;
3750 ec.InFinally = true;
3751 if (!Fini.Resolve (ec))
3753 ec.InFinally = was_finally;
3756 need_exc_block = true;
3759 if (ec.InIterator) {
3760 ResolveFinally (branching);
3761 need_exc_block |= emit_finally;
3763 emit_finally = Fini != null;
3765 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3767 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3769 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3771 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3772 // Unfortunately, System.Reflection.Emit automatically emits
3773 // a leave to the end of the finally block. This is a problem
3774 // if `returns' is true since we may jump to a point after the
3775 // end of the method.
3776 // As a workaround, emit an explicit ret here.
3777 ec.NeedReturnLabel ();
3783 protected override void DoEmit (EmitContext ec)
3785 ILGenerator ig = ec.ig;
3788 ig.BeginExceptionBlock ();
3791 foreach (Catch c in Specific){
3794 ig.BeginCatchBlock (c.CatchType);
3796 if (c.Name != null){
3797 vi = c.Block.GetLocalInfo (c.Name);
3799 throw new Exception ("Variable does not exist in this block");
3801 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3803 ig.Emit (OpCodes.Pop);
3808 if (General != null){
3809 ig.BeginCatchBlock (TypeManager.object_type);
3810 ig.Emit (OpCodes.Pop);
3811 General.Block.Emit (ec);
3816 ig.EndExceptionBlock ();
3819 public override void EmitFinally (EmitContext ec)
3825 public bool HasCatch
3828 return General != null || Specific.Count > 0;
3833 public class Using : ExceptionStatement {
3834 object expression_or_block;
3835 Statement Statement;
3840 Expression [] resolved_vars;
3841 Expression [] converted_vars;
3842 ExpressionStatement [] assign;
3843 LocalBuilder local_copy;
3845 public Using (object expression_or_block, Statement stmt, Location l)
3847 this.expression_or_block = expression_or_block;
3853 // Resolves for the case of using using a local variable declaration.
3855 bool ResolveLocalVariableDecls (EmitContext ec)
3859 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3863 expr_type = texpr.Type;
3866 // The type must be an IDisposable or an implicit conversion
3869 converted_vars = new Expression [var_list.Count];
3870 resolved_vars = new Expression [var_list.Count];
3871 assign = new ExpressionStatement [var_list.Count];
3873 bool need_conv = !TypeManager.ImplementsInterface (
3874 expr_type, TypeManager.idisposable_type);
3876 foreach (DictionaryEntry e in var_list){
3877 Expression var = (Expression) e.Key;
3879 var = var.ResolveLValue (ec, new EmptyExpression ());
3883 resolved_vars [i] = var;
3890 converted_vars [i] = Convert.ImplicitConversionRequired (
3891 ec, var, TypeManager.idisposable_type, loc);
3893 if (converted_vars [i] == null)
3900 foreach (DictionaryEntry e in var_list){
3901 Expression var = resolved_vars [i];
3902 Expression new_expr = (Expression) e.Value;
3905 a = new Assign (var, new_expr, loc);
3911 converted_vars [i] = var;
3912 assign [i] = (ExpressionStatement) a;
3919 bool ResolveExpression (EmitContext ec)
3921 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3922 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3923 Report.Error (1674, loc, "'{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3924 TypeManager.CSharpName (expr_type));
3933 // Emits the code for the case of using using a local variable declaration.
3935 void EmitLocalVariableDecls (EmitContext ec)
3937 ILGenerator ig = ec.ig;
3940 for (i = 0; i < assign.Length; i++) {
3941 assign [i].EmitStatement (ec);
3944 ig.BeginExceptionBlock ();
3946 Statement.Emit (ec);
3948 var_list.Reverse ();
3953 void EmitLocalVariableDeclFinally (EmitContext ec)
3955 ILGenerator ig = ec.ig;
3957 int i = assign.Length;
3958 for (int ii = 0; ii < var_list.Count; ++ii){
3959 Expression var = resolved_vars [--i];
3960 Label skip = ig.DefineLabel ();
3962 ig.BeginFinallyBlock ();
3964 if (!var.Type.IsValueType) {
3966 ig.Emit (OpCodes.Brfalse, skip);
3967 converted_vars [i].Emit (ec);
3968 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3970 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3972 if (!(ml is MethodGroupExpr)) {
3974 ig.Emit (OpCodes.Box, var.Type);
3975 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3977 MethodInfo mi = null;
3979 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3980 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3987 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3991 IMemoryLocation mloc = (IMemoryLocation) var;
3993 mloc.AddressOf (ec, AddressOp.Load);
3994 ig.Emit (OpCodes.Call, mi);
3998 ig.MarkLabel (skip);
4001 ig.EndExceptionBlock ();
4003 ig.BeginFinallyBlock ();
4008 void EmitExpression (EmitContext ec)
4011 // Make a copy of the expression and operate on that.
4013 ILGenerator ig = ec.ig;
4014 local_copy = ig.DeclareLocal (expr_type);
4019 ig.Emit (OpCodes.Stloc, local_copy);
4022 ig.BeginExceptionBlock ();
4024 Statement.Emit (ec);
4028 ig.EndExceptionBlock ();
4031 void EmitExpressionFinally (EmitContext ec)
4033 ILGenerator ig = ec.ig;
4034 if (!local_copy.LocalType.IsValueType) {
4035 Label skip = ig.DefineLabel ();
4036 ig.Emit (OpCodes.Ldloc, local_copy);
4037 ig.Emit (OpCodes.Brfalse, skip);
4038 ig.Emit (OpCodes.Ldloc, local_copy);
4039 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4040 ig.MarkLabel (skip);
4042 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4044 if (!(ml is MethodGroupExpr)) {
4045 ig.Emit (OpCodes.Ldloc, local_copy);
4046 ig.Emit (OpCodes.Box, local_copy.LocalType);
4047 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4049 MethodInfo mi = null;
4051 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4052 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4059 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4063 ig.Emit (OpCodes.Ldloca, local_copy);
4064 ig.Emit (OpCodes.Call, mi);
4069 public override bool Resolve (EmitContext ec)
4071 if (expression_or_block is DictionaryEntry){
4072 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4073 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4075 if (!ResolveLocalVariableDecls (ec))
4078 } else if (expression_or_block is Expression){
4079 expr = (Expression) expression_or_block;
4081 expr = expr.Resolve (ec);
4085 expr_type = expr.Type;
4087 if (!ResolveExpression (ec))
4091 FlowBranchingException branching = ec.StartFlowBranching (this);
4093 bool ok = Statement.Resolve (ec);
4096 ec.KillFlowBranching ();
4100 ResolveFinally (branching);
4101 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4103 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4104 // Unfortunately, System.Reflection.Emit automatically emits a leave
4105 // to the end of the finally block. This is a problem if `returns'
4106 // is true since we may jump to a point after the end of the method.
4107 // As a workaround, emit an explicit ret here.
4108 ec.NeedReturnLabel ();
4114 protected override void DoEmit (EmitContext ec)
4116 if (expression_or_block is DictionaryEntry)
4117 EmitLocalVariableDecls (ec);
4118 else if (expression_or_block is Expression)
4119 EmitExpression (ec);
4122 public override void EmitFinally (EmitContext ec)
4124 if (expression_or_block is DictionaryEntry)
4125 EmitLocalVariableDeclFinally (ec);
4126 else if (expression_or_block is Expression)
4127 EmitExpressionFinally (ec);
4132 /// Implementation of the foreach C# statement
4134 public class Foreach : ExceptionStatement {
4136 Expression variable;
4138 Statement statement;
4139 ForeachHelperMethods hm;
4140 Expression empty, conv;
4141 Type array_type, element_type;
4143 VariableStorage enumerator;
4146 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4147 Statement stmt, Location l)
4150 this.variable = var;
4156 public override bool Resolve (EmitContext ec)
4158 expr = expr.Resolve (ec);
4162 if (expr is NullLiteral) {
4163 Report.Error (186, expr.Location, "Use of null is not valid in this context");
4167 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4171 var_type = texpr.Type;
4174 // We need an instance variable. Not sure this is the best
4175 // way of doing this.
4177 // FIXME: When we implement propertyaccess, will those turn
4178 // out to return values in ExprClass? I think they should.
4180 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4181 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4182 error1579 (expr.Type);
4186 if (expr.Type.IsArray) {
4187 array_type = expr.Type;
4188 element_type = TypeManager.GetElementType (array_type);
4190 empty = new EmptyExpression (element_type);
4192 array = new ArrayForeach (type, variable, expr, statement, loc);
4193 return array.Resolve (ec);
4195 hm = ProbeCollectionType (ec, expr.Type);
4197 error1579 (expr.Type);
4201 array_type = expr.Type;
4202 element_type = hm.element_type;
4204 empty = new EmptyExpression (hm.element_type);
4209 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4210 ec.CurrentBranching.CreateSibling ();
4214 // FIXME: maybe we can apply the same trick we do in the
4215 // array handling to avoid creating empty and conv in some cases.
4217 // Although it is not as important in this case, as the type
4218 // will not likely be object (what the enumerator will return).
4220 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4224 variable = variable.ResolveLValue (ec, empty);
4225 if (variable == null)
4228 bool disposable = (hm != null) && hm.is_disposable;
4229 FlowBranchingException branching = null;
4231 branching = ec.StartFlowBranching (this);
4233 if (!statement.Resolve (ec))
4237 ResolveFinally (branching);
4238 ec.EndFlowBranching ();
4240 emit_finally = true;
4242 ec.EndFlowBranching ();
4248 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4250 static MethodInfo FetchMethodMoveNext (Type t)
4252 MemberList move_next_list;
4254 move_next_list = TypeContainer.FindMembers (
4255 t, MemberTypes.Method,
4256 BindingFlags.Public | BindingFlags.Instance,
4257 Type.FilterName, "MoveNext");
4258 if (move_next_list.Count == 0)
4261 foreach (MemberInfo m in move_next_list){
4262 MethodInfo mi = (MethodInfo) m;
4265 args = TypeManager.GetArgumentTypes (mi);
4266 if (args != null && args.Length == 0){
4267 if (TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type)
4275 // Retrieves a `public T get_Current ()' method from the Type `t'
4277 static MethodInfo FetchMethodGetCurrent (Type t)
4279 MemberList get_current_list;
4281 get_current_list = TypeContainer.FindMembers (
4282 t, MemberTypes.Method,
4283 BindingFlags.Public | BindingFlags.Instance,
4284 Type.FilterName, "get_Current");
4285 if (get_current_list.Count == 0)
4288 foreach (MemberInfo m in get_current_list){
4289 MethodInfo mi = (MethodInfo) m;
4292 args = TypeManager.GetArgumentTypes (mi);
4293 if (args != null && args.Length == 0)
4300 // Retrieves a `public void Dispose ()' method from the Type `t'
4302 static MethodInfo FetchMethodDispose (Type t)
4304 MemberList dispose_list;
4306 dispose_list = TypeContainer.FindMembers (
4307 t, MemberTypes.Method,
4308 BindingFlags.Public | BindingFlags.Instance,
4309 Type.FilterName, "Dispose");
4310 if (dispose_list.Count == 0)
4313 foreach (MemberInfo m in dispose_list){
4314 MethodInfo mi = (MethodInfo) m;
4317 args = TypeManager.GetArgumentTypes (mi);
4318 if (args != null && args.Length == 0){
4319 if (mi.ReturnType == TypeManager.void_type)
4327 // This struct records the helper methods used by the Foreach construct
4329 class ForeachHelperMethods {
4330 public EmitContext ec;
4331 public MethodInfo get_enumerator;
4332 public MethodInfo move_next;
4333 public MethodInfo get_current;
4334 public Type element_type;
4335 public Type enumerator_type;
4336 public bool is_disposable;
4338 public ForeachHelperMethods (EmitContext ec)
4341 this.element_type = TypeManager.object_type;
4342 this.enumerator_type = TypeManager.ienumerator_type;
4343 this.is_disposable = true;
4347 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4352 if (!(m is MethodInfo))
4355 if (m.Name != "GetEnumerator")
4358 MethodInfo mi = (MethodInfo) m;
4359 Type [] args = TypeManager.GetArgumentTypes (mi);
4361 if (args.Length != 0)
4364 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4366 // Check whether GetEnumerator is public
4367 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4370 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4372 // Apply the same optimization as MS: skip the GetEnumerator
4373 // returning an IEnumerator, and use the one returning a
4374 // CharEnumerator instead. This allows us to avoid the
4375 // try-finally block and the boxing.
4380 // Ok, we can access it, now make sure that we can do something
4381 // with this `GetEnumerator'
4384 Type return_type = mi.ReturnType;
4385 if (mi.ReturnType == TypeManager.ienumerator_type ||
4386 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4387 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4390 // If it is not an interface, lets try to find the methods ourselves.
4391 // For example, if we have:
4392 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4393 // We can avoid the iface call. This is a runtime perf boost.
4394 // even bigger if we have a ValueType, because we avoid the cost
4397 // We have to make sure that both methods exist for us to take
4398 // this path. If one of the methods does not exist, we will just
4399 // use the interface. Sadly, this complex if statement is the only
4400 // way I could do this without a goto
4403 if (return_type.IsInterface ||
4404 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4405 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4407 hm.move_next = TypeManager.bool_movenext_void;
4408 hm.get_current = TypeManager.object_getcurrent_void;
4415 // Ok, so they dont return an IEnumerable, we will have to
4416 // find if they support the GetEnumerator pattern.
4419 hm.move_next = FetchMethodMoveNext (return_type);
4420 if (hm.move_next == null)
4423 hm.get_current = FetchMethodGetCurrent (return_type);
4424 if (hm.get_current == null)
4428 hm.element_type = hm.get_current.ReturnType;
4429 hm.enumerator_type = return_type;
4430 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4431 TypeManager.ImplementsInterface (
4432 hm.enumerator_type, TypeManager.idisposable_type);
4438 /// This filter is used to find the GetEnumerator method
4439 /// on which IEnumerator operates
4441 static MemberFilter FilterEnumerator;
4445 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4448 void error1579 (Type t)
4450 Report.Error (1579, loc,
4451 "foreach statement cannot operate on variables of type `" +
4452 t.FullName + "' because that class does not provide a " +
4453 " GetEnumerator method or it is inaccessible");
4456 static bool TryType (Type t, ForeachHelperMethods hm)
4460 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4461 BindingFlags.Public | BindingFlags.NonPublic |
4462 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4463 FilterEnumerator, hm);
4468 hm.get_enumerator = (MethodInfo) mi [0];
4473 // Looks for a usable GetEnumerator in the Type, and if found returns
4474 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4476 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4478 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4480 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4481 if (TryType (tt, hm))
4487 // Now try to find the method in the interfaces
4490 Type [] ifaces = t.GetInterfaces ();
4492 foreach (Type i in ifaces){
4493 if (TryType (i, hm))
4498 // Since TypeBuilder.GetInterfaces only returns the interface
4499 // types for this type, we have to keep looping, but once
4500 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4501 // done, because it returns all the types
4503 if ((t is TypeBuilder))
4513 // FIXME: possible optimization.
4514 // We might be able to avoid creating `empty' if the type is the sam
4516 bool EmitCollectionForeach (EmitContext ec)
4518 ILGenerator ig = ec.ig;
4520 enumerator = new VariableStorage (ec, hm.enumerator_type);
4521 enumerator.EmitThis (ig);
4523 // Instantiate the enumerator
4525 if (expr.Type.IsValueType){
4526 IMemoryLocation ml = expr as IMemoryLocation;
4527 // Load the address of the value type.
4529 // This happens if, for example, you have a property
4530 // returning a struct which is IEnumerable
4531 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4533 ig.Emit (OpCodes.Stloc, t);
4534 ig.Emit (OpCodes.Ldloca, t);
4535 ec.FreeTemporaryLocal (t, expr.Type);
4537 ml.AddressOf (ec, AddressOp.Load);
4541 if (hm.get_enumerator.DeclaringType.IsValueType) {
4542 // the method is declared on the value type
4543 ig.Emit (OpCodes.Call, hm.get_enumerator);
4545 // it is an interface method, so we must box
4546 ig.Emit (OpCodes.Box, expr.Type);
4547 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4551 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4553 enumerator.EmitStore (ig);
4556 // Protect the code in a try/finalize block, so that
4557 // if the beast implement IDisposable, we get rid of it
4559 if (hm.is_disposable && emit_finally)
4560 ig.BeginExceptionBlock ();
4562 Label end_try = ig.DefineLabel ();
4564 ig.MarkLabel (ec.LoopBegin);
4566 enumerator.EmitCall (ig, hm.move_next);
4568 ig.Emit (OpCodes.Brfalse, end_try);
4571 ig.Emit (OpCodes.Ldarg_0);
4573 enumerator.EmitCall (ig, hm.get_current);
4577 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4579 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4581 statement.Emit (ec);
4582 ig.Emit (OpCodes.Br, ec.LoopBegin);
4583 ig.MarkLabel (end_try);
4585 // The runtime provides this for us.
4586 // ig.Emit (OpCodes.Leave, end);
4589 // Now the finally block
4591 if (hm.is_disposable) {
4594 ig.EndExceptionBlock ();
4597 ig.MarkLabel (ec.LoopEnd);
4601 public override void EmitFinally (EmitContext ec)
4603 ILGenerator ig = ec.ig;
4605 if (hm.enumerator_type.IsValueType) {
4606 enumerator.EmitThis (ig);
4608 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4610 enumerator.EmitLoadAddress (ig);
4611 ig.Emit (OpCodes.Call, mi);
4613 enumerator.EmitLoad (ig);
4614 ig.Emit (OpCodes.Box, hm.enumerator_type);
4615 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4618 Label call_dispose = ig.DefineLabel ();
4620 enumerator.EmitThis (ig);
4621 enumerator.EmitLoad (ig);
4622 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4623 ig.Emit (OpCodes.Dup);
4624 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4625 ig.Emit (OpCodes.Pop);
4627 Label end_finally = ig.DefineLabel ();
4628 ig.Emit (OpCodes.Br, end_finally);
4630 ig.MarkLabel (call_dispose);
4631 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4632 ig.MarkLabel (end_finally);
4635 ig.Emit (OpCodes.Endfinally);
4639 protected override void DoEmit (EmitContext ec)
4641 ILGenerator ig = ec.ig;
4643 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4644 ec.LoopBegin = ig.DefineLabel ();
4645 ec.LoopEnd = ig.DefineLabel ();
4648 EmitCollectionForeach (ec);
4652 ec.LoopBegin = old_begin;
4653 ec.LoopEnd = old_end;
4656 protected class TemporaryVariable : Expression
4661 public TemporaryVariable (Type type, Location loc)
4665 eclass = ExprClass.Value;
4670 public override Expression DoResolve (EmitContext ec)
4672 if (ec.InIterator) {
4674 fb = ec.CurrentIterator.MapVariable (
4675 "s_", count.ToString (), type);
4677 local = ec.ig.DeclareLocal (type);
4682 public override void Emit (EmitContext ec)
4684 ILGenerator ig = ec.ig;
4687 ig.Emit (OpCodes.Ldarg_0);
4688 ig.Emit (OpCodes.Ldfld, fb);
4690 ig.Emit (OpCodes.Ldloc, local);
4694 public void Store (EmitContext ec, Expression right_side)
4697 ec.ig.Emit (OpCodes.Ldarg_0);
4698 right_side.Emit (ec);
4700 ec.ig.Emit (OpCodes.Stloc, local);
4702 ec.ig.Emit (OpCodes.Stfld, fb);
4705 public void EmitThis (ILGenerator ig)
4708 ig.Emit (OpCodes.Ldarg_0);
4711 public void EmitStore (ILGenerator ig)
4714 ig.Emit (OpCodes.Stloc, local);
4716 ig.Emit (OpCodes.Stfld, fb);
4720 protected class ArrayCounter : TemporaryVariable
4722 public ArrayCounter (Location loc)
4723 : base (TypeManager.int32_type, loc)
4726 public void Initialize (EmitContext ec)
4729 ec.ig.Emit (OpCodes.Ldc_I4_0);
4733 public void Increment (EmitContext ec)
4737 ec.ig.Emit (OpCodes.Ldc_I4_1);
4738 ec.ig.Emit (OpCodes.Add);
4743 protected class ArrayForeach : Statement
4745 Expression type, variable, expr, conv;
4746 Statement statement;
4749 TemporaryVariable[] lengths;
4750 ArrayCounter[] counter;
4753 TemporaryVariable copy;
4756 public ArrayForeach (Expression type, Expression var,
4757 Expression expr, Statement stmt, Location l)
4760 this.variable = var;
4766 public override bool Resolve (EmitContext ec)
4768 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4772 var_type = texpr.Type;
4774 array_type = expr.Type;
4775 rank = array_type.GetArrayRank ();
4777 copy = new TemporaryVariable (array_type, loc);
4780 counter = new ArrayCounter [rank];
4781 lengths = new TemporaryVariable [rank];
4783 ArrayList list = new ArrayList ();
4784 for (int i = 0; i < rank; i++) {
4785 counter [i] = new ArrayCounter (loc);
4786 counter [i].Resolve (ec);
4788 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4789 lengths [i].Resolve (ec);
4791 list.Add (counter [i]);
4794 access = new ElementAccess (copy, list, loc).Resolve (ec);
4798 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4804 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4805 ec.CurrentBranching.CreateSibling ();
4807 variable = variable.ResolveLValue (ec, conv);
4808 if (variable == null)
4811 if (!statement.Resolve (ec))
4814 ec.EndFlowBranching ();
4819 protected override void DoEmit (EmitContext ec)
4821 ILGenerator ig = ec.ig;
4823 copy.Store (ec, expr);
4825 Label[] test = new Label [rank];
4826 Label[] loop = new Label [rank];
4828 for (int i = 0; i < rank; i++) {
4829 test [i] = ig.DefineLabel ();
4830 loop [i] = ig.DefineLabel ();
4832 lengths [i].EmitThis (ig);
4833 ((ArrayAccess) access).EmitGetLength (ec, i);
4834 lengths [i].EmitStore (ig);
4837 for (int i = 0; i < rank; i++) {
4838 counter [i].Initialize (ec);
4840 ig.Emit (OpCodes.Br, test [i]);
4841 ig.MarkLabel (loop [i]);
4844 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4846 statement.Emit (ec);
4848 ig.MarkLabel (ec.LoopBegin);
4850 for (int i = rank - 1; i >= 0; i--){
4851 counter [i].Increment (ec);
4853 ig.MarkLabel (test [i]);
4854 counter [i].Emit (ec);
4855 lengths [i].Emit (ec);
4856 ig.Emit (OpCodes.Blt, loop [i]);
4859 ig.MarkLabel (ec.LoopEnd);