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, false);
1065 VariableType = texpr.ResolveType (ec);
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 // Returns a `ParameterReference' for the given name, or null if there
1662 // is no such parameter
1664 public ParameterReference GetParameterReference (string name, Location loc)
1669 for (Block b = this; b != null; b = b.Toplevel.Parent) {
1670 Parameters pars = b.Toplevel.Parameters;
1671 par = pars.GetParameterByName (name, out idx);
1673 return new ParameterReference (pars, this, idx, name, loc);
1679 // Whether the parameter named `name' is local to this block,
1680 // or false, if the parameter belongs to an encompassing block.
1682 public bool IsLocalParameter (string name)
1684 return Toplevel.Parameters.GetParameterByName (name) != null;
1688 // Whether the `name' is a parameter reference
1690 public bool IsParameterReference (string name)
1695 for (Block b = this; b != null; b = b.Toplevel.Parent) {
1696 par = b.Toplevel.Parameters.GetParameterByName (name, out idx);
1704 /// A list of labels that were not used within this block
1706 public string [] GetUnreferenced ()
1708 // FIXME: Implement me
1712 public void AddStatement (Statement s)
1715 flags |= Flags.BlockUsed;
1720 return (flags & Flags.BlockUsed) != 0;
1726 flags |= Flags.BlockUsed;
1729 public bool HasRet {
1731 return (flags & Flags.HasRet) != 0;
1735 public bool IsDestructor {
1737 return (flags & Flags.IsDestructor) != 0;
1741 public void SetDestructor ()
1743 flags |= Flags.IsDestructor;
1746 VariableMap param_map, local_map;
1748 public VariableMap ParameterMap {
1750 if ((flags & Flags.VariablesInitialized) == 0)
1751 throw new Exception ("Variables have not been initialized yet");
1757 public VariableMap LocalMap {
1759 if ((flags & Flags.VariablesInitialized) == 0)
1760 throw new Exception ("Variables have not been initialized yet");
1767 /// Emits the variable declarations and labels.
1770 /// tc: is our typecontainer (to resolve type references)
1771 /// ig: is the code generator:
1773 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1775 bool old_unsafe = ec.InUnsafe;
1777 // If some parent block was unsafe, we remain unsafe even if this block
1778 // isn't explicitly marked as such.
1779 ec.InUnsafe |= Unsafe;
1782 // Compute the VariableMap's.
1784 // Unfortunately, we don't know the type when adding variables with
1785 // AddVariable(), so we need to compute this info here.
1789 if (variables != null) {
1790 foreach (LocalInfo li in variables.Values)
1793 locals = new LocalInfo [variables.Count];
1794 variables.Values.CopyTo (locals, 0);
1796 locals = new LocalInfo [0];
1799 local_map = new VariableMap (Parent.LocalMap, locals);
1801 local_map = new VariableMap (locals);
1803 param_map = new VariableMap (ip);
1804 flags |= Flags.VariablesInitialized;
1806 bool old_check_state = ec.ConstantCheckState;
1807 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1810 // Process this block variables
1812 if (variables != null){
1813 foreach (DictionaryEntry de in variables){
1814 string name = (string) de.Key;
1815 LocalInfo vi = (LocalInfo) de.Value;
1817 if (vi.VariableType == null)
1820 Type variable_type = vi.VariableType;
1822 if (variable_type.IsPointer){
1824 // Am not really convinced that this test is required (Microsoft does it)
1825 // but the fact is that you would not be able to use the pointer variable
1828 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1835 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1838 // This is needed to compile on both .NET 1.x and .NET 2.x
1839 // the later introduced `DeclareLocal (Type t, bool pinned)'
1841 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1842 else if (!vi.IsThis)
1843 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1846 if (constants == null)
1849 Expression cv = (Expression) constants [name];
1853 ec.CurrentBlock = this;
1854 Expression e = cv.Resolve (ec);
1856 Constant ce = e as Constant;
1858 Report.Error (133, vi.Location,
1859 "The expression being assigned to '{0}' must be constant", name);
1863 if (e.Type != variable_type){
1864 e = Const.ChangeType (vi.Location, ce, variable_type);
1869 constants.Remove (name);
1870 constants.Add (name, e);
1873 ec.ConstantCheckState = old_check_state;
1876 // Now, handle the children
1878 if (children != null){
1879 foreach (Block b in children)
1880 b.ResolveMeta (toplevel, ec, ip);
1882 ec.InUnsafe = old_unsafe;
1886 // Emits the local variable declarations for a block
1888 public void EmitMeta (EmitContext ec)
1890 ILGenerator ig = ec.ig;
1892 if (variables != null){
1893 bool have_captured_vars = ec.HaveCapturedVariables ();
1894 bool remap_locals = ec.RemapToProxy;
1896 foreach (DictionaryEntry de in variables){
1897 LocalInfo vi = (LocalInfo) de.Value;
1899 if (have_captured_vars && ec.IsCaptured (vi))
1903 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1907 // This is needed to compile on both .NET 1.x and .NET 2.x
1908 // the later introduced `DeclareLocal (Type t, bool pinned)'
1910 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1911 else if (!vi.IsThis)
1912 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1917 if (children != null){
1918 foreach (Block b in children)
1923 void UsageWarning (FlowBranching.UsageVector vector)
1927 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1928 foreach (DictionaryEntry de in variables){
1929 LocalInfo vi = (LocalInfo) de.Value;
1934 name = (string) de.Key;
1936 if (vector.IsAssigned (vi.VariableInfo)){
1937 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1939 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1945 bool unreachable_shown;
1948 public override bool Resolve (EmitContext ec)
1950 Block prev_block = ec.CurrentBlock;
1953 int errors = Report.Errors;
1955 ec.CurrentBlock = this;
1956 ec.StartFlowBranching (this);
1958 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1960 int statement_count = statements.Count;
1961 for (int ix = 0; ix < statement_count; ix++){
1962 Statement s = (Statement) statements [ix];
1965 // Warn if we detect unreachable code.
1969 ((Block) s).unreachable = true;
1971 if (!unreachable_shown && (RootContext.WarningLevel >= 2)) {
1973 162, loc, "Unreachable code detected");
1974 unreachable_shown = true;
1979 // Note that we're not using ResolveUnreachable() for unreachable
1980 // statements here. ResolveUnreachable() creates a temporary
1981 // flow branching and kills it afterwards. This leads to problems
1982 // if you have two unreachable statements where the first one
1983 // assigns a variable and the second one tries to access it.
1986 if (!s.Resolve (ec)) {
1988 statements [ix] = EmptyStatement.Value;
1992 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1993 statements [ix] = EmptyStatement.Value;
1995 num_statements = ix + 1;
1996 if (s is LabeledStatement)
1997 unreachable = false;
1999 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
2002 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
2003 ec.CurrentBranching, statement_count, num_statements);
2006 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
2008 ec.CurrentBlock = prev_block;
2010 // If we're a non-static `struct' constructor which doesn't have an
2011 // initializer, then we must initialize all of the struct's fields.
2012 if ((this_variable != null) &&
2013 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
2014 !this_variable.IsThisAssigned (ec, loc))
2017 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2018 foreach (LabeledStatement label in labels.Values)
2019 if (!label.HasBeenReferenced)
2020 Report.Warning (164, label.Location,
2021 "This label has not been referenced");
2024 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2026 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2027 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2028 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2029 flags |= Flags.HasRet;
2031 if (ok && (errors == Report.Errors)) {
2032 if (RootContext.WarningLevel >= 3)
2033 UsageWarning (vector);
2039 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2041 unreachable_shown = true;
2044 if (warn && (RootContext.WarningLevel >= 2))
2045 Report.Warning (162, loc, "Unreachable code detected");
2047 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2048 bool ok = Resolve (ec);
2049 ec.KillFlowBranching ();
2054 protected override void DoEmit (EmitContext ec)
2056 for (int ix = 0; ix < num_statements; ix++){
2057 Statement s = (Statement) statements [ix];
2059 // Check whether we are the last statement in a
2062 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2063 ec.IsLastStatement = true;
2065 ec.IsLastStatement = false;
2071 public override void Emit (EmitContext ec)
2073 Block prev_block = ec.CurrentBlock;
2075 ec.CurrentBlock = this;
2077 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2078 bool is_lexical_block = !Implicit && (Parent != null);
2080 if (emit_debug_info) {
2081 if (is_lexical_block)
2084 if (variables != null) {
2085 foreach (DictionaryEntry de in variables) {
2086 string name = (string) de.Key;
2087 LocalInfo vi = (LocalInfo) de.Value;
2089 if (vi.LocalBuilder == null)
2092 ec.DefineLocalVariable (name, vi.LocalBuilder);
2097 ec.Mark (StartLocation, true);
2099 ec.Mark (EndLocation, true);
2101 if (emit_debug_info && is_lexical_block)
2104 ec.CurrentBlock = prev_block;
2108 // Returns true if we ar ea child of `b'.
2110 public bool IsChildOf (Block b)
2112 Block current = this;
2115 if (current.Parent == b)
2117 current = current.Parent;
2118 } while (current != null);
2122 public override string ToString ()
2124 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2129 // A toplevel block contains extra information, the split is done
2130 // only to separate information that would otherwise bloat the more
2131 // lightweight Block.
2133 // In particular, this was introduced when the support for Anonymous
2134 // Methods was implemented.
2136 public class ToplevelBlock : Block {
2138 // Pointer to the host of this anonymous method, or null
2139 // if we are the topmost block
2141 public ToplevelBlock Container;
2142 CaptureContext capture_context;
2143 FlowBranching top_level_branching;
2145 Hashtable capture_contexts;
2148 // The parameters for the block.
2150 public readonly Parameters Parameters;
2152 public void RegisterCaptureContext (CaptureContext cc)
2154 if (capture_contexts == null)
2155 capture_contexts = new Hashtable ();
2156 capture_contexts [cc] = cc;
2159 public void CompleteContexts ()
2161 if (capture_contexts == null)
2164 foreach (CaptureContext cc in capture_contexts.Keys){
2169 public CaptureContext ToplevelBlockCaptureContext {
2171 return capture_context;
2176 // Parent is only used by anonymous blocks to link back to their
2179 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2180 this (container, (Flags) 0, parameters, start)
2184 public ToplevelBlock (Parameters parameters, Location start) :
2185 this (null, (Flags) 0, parameters, start)
2189 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2190 this (null, flags, parameters, start)
2194 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2195 base (null, flags | Flags.IsToplevel, start, Location.Null)
2197 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2198 Container = container;
2201 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2205 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2207 if (capture_context == null)
2208 capture_context = new CaptureContext (this, loc, host);
2211 public CaptureContext CaptureContext {
2213 return capture_context;
2217 public FlowBranching TopLevelBranching {
2219 return top_level_branching;
2223 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2225 int errors = Report.Errors;
2227 if (top_level_branching != null)
2230 ResolveMeta (this, ec, ip);
2232 top_level_branching = ec.StartFlowBranching (this);
2234 return Report.Errors == errors;
2238 public class SwitchLabel {
2241 public Location loc;
2245 Label il_label_code;
2246 bool il_label_code_set;
2249 // if expr == null, then it is the default case.
2251 public SwitchLabel (Expression expr, Location l)
2257 public Expression Label {
2263 public object Converted {
2269 public Label GetILLabel (EmitContext ec)
2272 il_label = ec.ig.DefineLabel ();
2273 il_label_set = true;
2278 public Label GetILLabelCode (EmitContext ec)
2280 if (!il_label_code_set){
2281 il_label_code = ec.ig.DefineLabel ();
2282 il_label_code_set = true;
2284 return il_label_code;
2288 // Resolves the expression, reduces it to a literal if possible
2289 // and then converts it to the requested type.
2291 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2296 Expression e = label.Resolve (ec);
2301 if (!(e is Constant)){
2302 Report.Error (150, loc, "A constant value is expected, got: " + e);
2306 if (e is StringConstant || e is NullLiteral){
2307 if (required_type == TypeManager.string_type){
2313 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2314 if (converted == null)
2321 public class SwitchSection {
2322 // An array of SwitchLabels.
2323 public readonly ArrayList Labels;
2324 public readonly Block Block;
2326 public SwitchSection (ArrayList labels, Block block)
2333 public class Switch : Statement {
2334 public readonly ArrayList Sections;
2335 public Expression Expr;
2338 /// Maps constants whose type type SwitchType to their SwitchLabels.
2340 public Hashtable Elements;
2343 /// The governing switch type
2345 public Type SwitchType;
2350 Label default_target;
2351 Expression new_expr;
2353 SwitchSection constant_section;
2354 SwitchSection default_section;
2357 // The types allowed to be implicitly cast from
2358 // on the governing type
2360 static Type [] allowed_types;
2362 public Switch (Expression e, ArrayList sects, Location l)
2369 public bool GotDefault {
2371 return default_section != null;
2375 public Label DefaultTarget {
2377 return default_target;
2382 // Determines the governing type for a switch. The returned
2383 // expression might be the expression from the switch, or an
2384 // expression that includes any potential conversions to the
2385 // integral types or to string.
2387 Expression SwitchGoverningType (EmitContext ec, Type t)
2389 if (t == TypeManager.int32_type ||
2390 t == TypeManager.uint32_type ||
2391 t == TypeManager.char_type ||
2392 t == TypeManager.byte_type ||
2393 t == TypeManager.sbyte_type ||
2394 t == TypeManager.ushort_type ||
2395 t == TypeManager.short_type ||
2396 t == TypeManager.uint64_type ||
2397 t == TypeManager.int64_type ||
2398 t == TypeManager.string_type ||
2399 t == TypeManager.bool_type ||
2400 t.IsSubclassOf (TypeManager.enum_type))
2403 if (allowed_types == null){
2404 allowed_types = new Type [] {
2405 TypeManager.int32_type,
2406 TypeManager.uint32_type,
2407 TypeManager.sbyte_type,
2408 TypeManager.byte_type,
2409 TypeManager.short_type,
2410 TypeManager.ushort_type,
2411 TypeManager.int64_type,
2412 TypeManager.uint64_type,
2413 TypeManager.char_type,
2414 TypeManager.bool_type,
2415 TypeManager.string_type
2420 // Try to find a *user* defined implicit conversion.
2422 // If there is no implicit conversion, or if there are multiple
2423 // conversions, we have to report an error
2425 Expression converted = null;
2426 foreach (Type tt in allowed_types){
2429 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2434 // Ignore over-worked ImplicitUserConversions that do
2435 // an implicit conversion in addition to the user conversion.
2438 UserCast ue = e as UserCast;
2440 if (ue.Source != Expr)
2444 if (converted != null){
2445 Report.ExtraInformation (
2447 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2448 TypeManager.CSharpName (Expr.Type)));
2457 static string Error152 {
2459 return "The label '{0}:' already occurs in this switch statement";
2464 // Performs the basic sanity checks on the switch statement
2465 // (looks for duplicate keys and non-constant expressions).
2467 // It also returns a hashtable with the keys that we will later
2468 // use to compute the switch tables
2470 bool CheckSwitch (EmitContext ec)
2474 Elements = new Hashtable ();
2476 if (TypeManager.IsEnumType (SwitchType)){
2477 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2479 compare_type = SwitchType;
2481 foreach (SwitchSection ss in Sections){
2482 foreach (SwitchLabel sl in ss.Labels){
2483 if (!sl.ResolveAndReduce (ec, SwitchType)){
2488 if (sl.Label == null){
2489 if (default_section != null){
2490 Report.Error (152, sl.loc, Error152, "default");
2493 default_section = ss;
2497 object key = sl.Converted;
2499 if (key is Constant)
2500 key = ((Constant) key).GetValue ();
2503 key = NullLiteral.Null;
2505 string lname = null;
2506 if (compare_type == TypeManager.uint64_type){
2507 ulong v = (ulong) key;
2509 if (Elements.Contains (v))
2510 lname = v.ToString ();
2512 Elements.Add (v, sl);
2513 } else if (compare_type == TypeManager.int64_type){
2514 long v = (long) key;
2516 if (Elements.Contains (v))
2517 lname = v.ToString ();
2519 Elements.Add (v, sl);
2520 } else if (compare_type == TypeManager.uint32_type){
2521 uint v = (uint) key;
2523 if (Elements.Contains (v))
2524 lname = v.ToString ();
2526 Elements.Add (v, sl);
2527 } else if (compare_type == TypeManager.char_type){
2528 char v = (char) key;
2530 if (Elements.Contains (v))
2531 lname = v.ToString ();
2533 Elements.Add (v, sl);
2534 } else if (compare_type == TypeManager.byte_type){
2535 byte v = (byte) key;
2537 if (Elements.Contains (v))
2538 lname = v.ToString ();
2540 Elements.Add (v, sl);
2541 } else if (compare_type == TypeManager.sbyte_type){
2542 sbyte v = (sbyte) key;
2544 if (Elements.Contains (v))
2545 lname = v.ToString ();
2547 Elements.Add (v, sl);
2548 } else if (compare_type == TypeManager.short_type){
2549 short v = (short) key;
2551 if (Elements.Contains (v))
2552 lname = v.ToString ();
2554 Elements.Add (v, sl);
2555 } else if (compare_type == TypeManager.ushort_type){
2556 ushort v = (ushort) key;
2558 if (Elements.Contains (v))
2559 lname = v.ToString ();
2561 Elements.Add (v, sl);
2562 } else if (compare_type == TypeManager.string_type){
2563 if (key is NullLiteral){
2564 if (Elements.Contains (NullLiteral.Null))
2567 Elements.Add (NullLiteral.Null, null);
2569 string s = (string) key;
2571 if (Elements.Contains (s))
2574 Elements.Add (s, sl);
2576 } else if (compare_type == TypeManager.int32_type) {
2579 if (Elements.Contains (v))
2580 lname = v.ToString ();
2582 Elements.Add (v, sl);
2583 } else if (compare_type == TypeManager.bool_type) {
2584 bool v = (bool) key;
2586 if (Elements.Contains (v))
2587 lname = v.ToString ();
2589 Elements.Add (v, sl);
2593 throw new Exception ("Unknown switch type!" +
2594 SwitchType + " " + compare_type);
2597 if (lname != null) {
2598 Report.Error (152, sl.loc, Error152, "case " + lname);
2609 void EmitObjectInteger (ILGenerator ig, object k)
2612 IntConstant.EmitInt (ig, (int) k);
2613 else if (k is Constant) {
2614 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2617 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2620 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2622 IntConstant.EmitInt (ig, (int) (long) k);
2623 ig.Emit (OpCodes.Conv_I8);
2626 LongConstant.EmitLong (ig, (long) k);
2628 else if (k is ulong)
2630 if ((ulong) k < (1L<<32))
2632 IntConstant.EmitInt (ig, (int) (long) k);
2633 ig.Emit (OpCodes.Conv_U8);
2637 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2641 IntConstant.EmitInt (ig, (int) ((char) k));
2642 else if (k is sbyte)
2643 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2645 IntConstant.EmitInt (ig, (int) ((byte) k));
2646 else if (k is short)
2647 IntConstant.EmitInt (ig, (int) ((short) k));
2648 else if (k is ushort)
2649 IntConstant.EmitInt (ig, (int) ((ushort) k));
2651 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2653 throw new Exception ("Unhandled case");
2656 // structure used to hold blocks of keys while calculating table switch
2657 class KeyBlock : IComparable
2659 public KeyBlock (long _nFirst)
2661 nFirst = nLast = _nFirst;
2665 public ArrayList rgKeys = null;
2666 // how many items are in the bucket
2667 public int Size = 1;
2670 get { return (int) (nLast - nFirst + 1); }
2672 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2674 return kbLast.nLast - kbFirst.nFirst + 1;
2676 public int CompareTo (object obj)
2678 KeyBlock kb = (KeyBlock) obj;
2679 int nLength = Length;
2680 int nLengthOther = kb.Length;
2681 if (nLengthOther == nLength)
2682 return (int) (kb.nFirst - nFirst);
2683 return nLength - nLengthOther;
2688 /// This method emits code for a lookup-based switch statement (non-string)
2689 /// Basically it groups the cases into blocks that are at least half full,
2690 /// and then spits out individual lookup opcodes for each block.
2691 /// It emits the longest blocks first, and short blocks are just
2692 /// handled with direct compares.
2694 /// <param name="ec"></param>
2695 /// <param name="val"></param>
2696 /// <returns></returns>
2697 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2699 int cElements = Elements.Count;
2700 object [] rgKeys = new object [cElements];
2701 Elements.Keys.CopyTo (rgKeys, 0);
2702 Array.Sort (rgKeys);
2704 // initialize the block list with one element per key
2705 ArrayList rgKeyBlocks = new ArrayList ();
2706 foreach (object key in rgKeys)
2707 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2710 // iteratively merge the blocks while they are at least half full
2711 // there's probably a really cool way to do this with a tree...
2712 while (rgKeyBlocks.Count > 1)
2714 ArrayList rgKeyBlocksNew = new ArrayList ();
2715 kbCurr = (KeyBlock) rgKeyBlocks [0];
2716 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2718 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2719 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2722 kbCurr.nLast = kb.nLast;
2723 kbCurr.Size += kb.Size;
2727 // start a new block
2728 rgKeyBlocksNew.Add (kbCurr);
2732 rgKeyBlocksNew.Add (kbCurr);
2733 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2735 rgKeyBlocks = rgKeyBlocksNew;
2738 // initialize the key lists
2739 foreach (KeyBlock kb in rgKeyBlocks)
2740 kb.rgKeys = new ArrayList ();
2742 // fill the key lists
2744 if (rgKeyBlocks.Count > 0) {
2745 kbCurr = (KeyBlock) rgKeyBlocks [0];
2746 foreach (object key in rgKeys)
2748 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2749 System.Convert.ToInt64 (key) > kbCurr.nLast;
2751 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2752 kbCurr.rgKeys.Add (key);
2756 // sort the blocks so we can tackle the largest ones first
2757 rgKeyBlocks.Sort ();
2759 // okay now we can start...
2760 ILGenerator ig = ec.ig;
2761 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2762 Label lblDefault = ig.DefineLabel ();
2764 Type typeKeys = null;
2765 if (rgKeys.Length > 0)
2766 typeKeys = rgKeys [0].GetType (); // used for conversions
2770 if (TypeManager.IsEnumType (SwitchType))
2771 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2773 compare_type = SwitchType;
2775 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2777 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2778 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2781 foreach (object key in kb.rgKeys)
2783 ig.Emit (OpCodes.Ldloc, val);
2784 EmitObjectInteger (ig, key);
2785 SwitchLabel sl = (SwitchLabel) Elements [key];
2786 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2791 // TODO: if all the keys in the block are the same and there are
2792 // no gaps/defaults then just use a range-check.
2793 if (compare_type == TypeManager.int64_type ||
2794 compare_type == TypeManager.uint64_type)
2796 // TODO: optimize constant/I4 cases
2798 // check block range (could be > 2^31)
2799 ig.Emit (OpCodes.Ldloc, val);
2800 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2801 ig.Emit (OpCodes.Blt, lblDefault);
2802 ig.Emit (OpCodes.Ldloc, val);
2803 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2804 ig.Emit (OpCodes.Bgt, lblDefault);
2807 ig.Emit (OpCodes.Ldloc, val);
2810 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2811 ig.Emit (OpCodes.Sub);
2813 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2818 ig.Emit (OpCodes.Ldloc, val);
2819 int nFirst = (int) kb.nFirst;
2822 IntConstant.EmitInt (ig, nFirst);
2823 ig.Emit (OpCodes.Sub);
2825 else if (nFirst < 0)
2827 IntConstant.EmitInt (ig, -nFirst);
2828 ig.Emit (OpCodes.Add);
2832 // first, build the list of labels for the switch
2834 int cJumps = kb.Length;
2835 Label [] rgLabels = new Label [cJumps];
2836 for (int iJump = 0; iJump < cJumps; iJump++)
2838 object key = kb.rgKeys [iKey];
2839 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2841 SwitchLabel sl = (SwitchLabel) Elements [key];
2842 rgLabels [iJump] = sl.GetILLabel (ec);
2846 rgLabels [iJump] = lblDefault;
2848 // emit the switch opcode
2849 ig.Emit (OpCodes.Switch, rgLabels);
2852 // mark the default for this block
2854 ig.MarkLabel (lblDefault);
2857 // TODO: find the default case and emit it here,
2858 // to prevent having to do the following jump.
2859 // make sure to mark other labels in the default section
2861 // the last default just goes to the end
2862 ig.Emit (OpCodes.Br, lblDefault);
2864 // now emit the code for the sections
2865 bool fFoundDefault = false;
2866 foreach (SwitchSection ss in Sections)
2868 foreach (SwitchLabel sl in ss.Labels)
2870 ig.MarkLabel (sl.GetILLabel (ec));
2871 ig.MarkLabel (sl.GetILLabelCode (ec));
2872 if (sl.Label == null)
2874 ig.MarkLabel (lblDefault);
2875 fFoundDefault = true;
2879 //ig.Emit (OpCodes.Br, lblEnd);
2882 if (!fFoundDefault) {
2883 ig.MarkLabel (lblDefault);
2885 ig.MarkLabel (lblEnd);
2888 // This simple emit switch works, but does not take advantage of the
2890 // TODO: remove non-string logic from here
2891 // TODO: binary search strings?
2893 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2895 ILGenerator ig = ec.ig;
2896 Label end_of_switch = ig.DefineLabel ();
2897 Label next_test = ig.DefineLabel ();
2898 Label null_target = ig.DefineLabel ();
2899 bool first_test = true;
2900 bool pending_goto_end = false;
2901 bool null_marked = false;
2904 ig.Emit (OpCodes.Ldloc, val);
2906 if (Elements.Contains (NullLiteral.Null)){
2907 ig.Emit (OpCodes.Brfalse, null_target);
2909 ig.Emit (OpCodes.Brfalse, default_target);
2911 ig.Emit (OpCodes.Ldloc, val);
2912 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2913 ig.Emit (OpCodes.Stloc, val);
2915 int section_count = Sections.Count;
2916 for (int section = 0; section < section_count; section++){
2917 SwitchSection ss = (SwitchSection) Sections [section];
2919 if (ss == default_section)
2922 Label sec_begin = ig.DefineLabel ();
2924 ig.Emit (OpCodes.Nop);
2926 if (pending_goto_end)
2927 ig.Emit (OpCodes.Br, end_of_switch);
2929 int label_count = ss.Labels.Count;
2931 for (int label = 0; label < label_count; label++){
2932 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2933 ig.MarkLabel (sl.GetILLabel (ec));
2936 ig.MarkLabel (next_test);
2937 next_test = ig.DefineLabel ();
2940 // If we are the default target
2942 if (sl.Label != null){
2943 object lit = sl.Converted;
2945 if (lit is NullLiteral){
2947 if (label_count == 1)
2948 ig.Emit (OpCodes.Br, next_test);
2952 StringConstant str = (StringConstant) lit;
2954 ig.Emit (OpCodes.Ldloc, val);
2955 ig.Emit (OpCodes.Ldstr, str.Value);
2956 if (label_count == 1)
2957 ig.Emit (OpCodes.Bne_Un, next_test);
2959 if (label+1 == label_count)
2960 ig.Emit (OpCodes.Bne_Un, next_test);
2962 ig.Emit (OpCodes.Beq, sec_begin);
2967 ig.MarkLabel (null_target);
2970 ig.MarkLabel (sec_begin);
2971 foreach (SwitchLabel sl in ss.Labels)
2972 ig.MarkLabel (sl.GetILLabelCode (ec));
2975 pending_goto_end = !ss.Block.HasRet;
2978 ig.MarkLabel (next_test);
2979 ig.MarkLabel (default_target);
2981 ig.MarkLabel (null_target);
2982 if (default_section != null)
2983 default_section.Block.Emit (ec);
2984 ig.MarkLabel (end_of_switch);
2987 SwitchSection FindSection (SwitchLabel label)
2989 foreach (SwitchSection ss in Sections){
2990 foreach (SwitchLabel sl in ss.Labels){
2999 public override bool Resolve (EmitContext ec)
3001 Expr = Expr.Resolve (ec);
3005 new_expr = SwitchGoverningType (ec, Expr.Type);
3006 if (new_expr == null){
3007 Report.Error (151, loc, "An integer type or string was expected for switch");
3012 SwitchType = new_expr.Type;
3014 if (!CheckSwitch (ec))
3017 Switch old_switch = ec.Switch;
3019 ec.Switch.SwitchType = SwitchType;
3021 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3022 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3024 is_constant = new_expr is Constant;
3026 object key = ((Constant) new_expr).GetValue ();
3027 SwitchLabel label = (SwitchLabel) Elements [key];
3029 constant_section = FindSection (label);
3030 if (constant_section == null)
3031 constant_section = default_section;
3035 foreach (SwitchSection ss in Sections){
3037 ec.CurrentBranching.CreateSibling (
3038 null, FlowBranching.SiblingType.SwitchSection);
3042 if (is_constant && (ss != constant_section)) {
3043 // If we're a constant switch, we're only emitting
3044 // one single section - mark all the others as
3046 ec.CurrentBranching.CurrentUsageVector.Goto ();
3047 if (!ss.Block.ResolveUnreachable (ec, true))
3050 if (!ss.Block.Resolve (ec))
3055 if (default_section == null)
3056 ec.CurrentBranching.CreateSibling (
3057 null, FlowBranching.SiblingType.SwitchSection);
3059 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3060 ec.Switch = old_switch;
3062 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3068 protected override void DoEmit (EmitContext ec)
3070 ILGenerator ig = ec.ig;
3072 // Store variable for comparission purposes
3075 value = ig.DeclareLocal (SwitchType);
3077 ig.Emit (OpCodes.Stloc, value);
3081 default_target = ig.DefineLabel ();
3084 // Setup the codegen context
3086 Label old_end = ec.LoopEnd;
3087 Switch old_switch = ec.Switch;
3089 ec.LoopEnd = ig.DefineLabel ();
3094 if (constant_section != null)
3095 constant_section.Block.Emit (ec);
3096 } else if (SwitchType == TypeManager.string_type)
3097 SimpleSwitchEmit (ec, value);
3099 TableSwitchEmit (ec, value);
3101 // Restore context state.
3102 ig.MarkLabel (ec.LoopEnd);
3105 // Restore the previous context
3107 ec.LoopEnd = old_end;
3108 ec.Switch = old_switch;
3112 public abstract class ExceptionStatement : Statement
3114 public abstract void EmitFinally (EmitContext ec);
3116 protected bool emit_finally = true;
3117 ArrayList parent_vectors;
3119 protected void DoEmitFinally (EmitContext ec)
3122 ec.ig.BeginFinallyBlock ();
3124 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3128 protected void ResolveFinally (FlowBranchingException branching)
3130 emit_finally = branching.EmitFinally;
3132 branching.Parent.StealFinallyClauses (ref parent_vectors);
3136 public class Lock : ExceptionStatement {
3138 Statement Statement;
3141 public Lock (Expression expr, Statement stmt, Location l)
3148 public override bool Resolve (EmitContext ec)
3150 expr = expr.Resolve (ec);
3154 if (expr.Type.IsValueType){
3155 Error (185, "lock statement requires the expression to be " +
3156 " a reference type (type is: `{0}'",
3157 TypeManager.CSharpName (expr.Type));
3161 FlowBranchingException branching = ec.StartFlowBranching (this);
3162 bool ok = Statement.Resolve (ec);
3164 ec.KillFlowBranching ();
3168 ResolveFinally (branching);
3170 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3171 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3172 // Unfortunately, System.Reflection.Emit automatically emits
3173 // a leave to the end of the finally block.
3174 // This is a problem if `returns' is true since we may jump
3175 // to a point after the end of the method.
3176 // As a workaround, emit an explicit ret here.
3177 ec.NeedReturnLabel ();
3183 protected override void DoEmit (EmitContext ec)
3185 Type type = expr.Type;
3187 ILGenerator ig = ec.ig;
3188 temp = ig.DeclareLocal (type);
3191 ig.Emit (OpCodes.Dup);
3192 ig.Emit (OpCodes.Stloc, temp);
3193 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3197 ig.BeginExceptionBlock ();
3198 Statement.Emit (ec);
3203 ig.EndExceptionBlock ();
3206 public override void EmitFinally (EmitContext ec)
3208 ILGenerator ig = ec.ig;
3209 ig.Emit (OpCodes.Ldloc, temp);
3210 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3214 public class Unchecked : Statement {
3215 public readonly Block Block;
3217 public Unchecked (Block b)
3223 public override bool Resolve (EmitContext ec)
3225 bool previous_state = ec.CheckState;
3226 bool previous_state_const = ec.ConstantCheckState;
3228 ec.CheckState = false;
3229 ec.ConstantCheckState = false;
3230 bool ret = Block.Resolve (ec);
3231 ec.CheckState = previous_state;
3232 ec.ConstantCheckState = previous_state_const;
3237 protected override void DoEmit (EmitContext ec)
3239 bool previous_state = ec.CheckState;
3240 bool previous_state_const = ec.ConstantCheckState;
3242 ec.CheckState = false;
3243 ec.ConstantCheckState = false;
3245 ec.CheckState = previous_state;
3246 ec.ConstantCheckState = previous_state_const;
3250 public class Checked : Statement {
3251 public readonly Block Block;
3253 public Checked (Block b)
3256 b.Unchecked = false;
3259 public override bool Resolve (EmitContext ec)
3261 bool previous_state = ec.CheckState;
3262 bool previous_state_const = ec.ConstantCheckState;
3264 ec.CheckState = true;
3265 ec.ConstantCheckState = true;
3266 bool ret = Block.Resolve (ec);
3267 ec.CheckState = previous_state;
3268 ec.ConstantCheckState = previous_state_const;
3273 protected override void DoEmit (EmitContext ec)
3275 bool previous_state = ec.CheckState;
3276 bool previous_state_const = ec.ConstantCheckState;
3278 ec.CheckState = true;
3279 ec.ConstantCheckState = true;
3281 ec.CheckState = previous_state;
3282 ec.ConstantCheckState = previous_state_const;
3286 public class Unsafe : Statement {
3287 public readonly Block Block;
3289 public Unsafe (Block b)
3292 Block.Unsafe = true;
3295 public override bool Resolve (EmitContext ec)
3297 bool previous_state = ec.InUnsafe;
3301 val = Block.Resolve (ec);
3302 ec.InUnsafe = previous_state;
3307 protected override void DoEmit (EmitContext ec)
3309 bool previous_state = ec.InUnsafe;
3313 ec.InUnsafe = previous_state;
3320 public class Fixed : Statement {
3322 ArrayList declarators;
3323 Statement statement;
3328 abstract class Emitter
3330 protected LocalInfo vi;
3331 protected Expression converted;
3333 protected Emitter (Expression expr, LocalInfo li)
3339 public abstract void Emit (EmitContext ec);
3340 public abstract void EmitExit (ILGenerator ig);
3343 class ExpressionEmitter: Emitter {
3344 public ExpressionEmitter (Expression converted, LocalInfo li) :
3345 base (converted, li)
3349 public override void Emit (EmitContext ec) {
3351 // Store pointer in pinned location
3353 converted.Emit (ec);
3354 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3357 public override void EmitExit (ILGenerator ig)
3359 ig.Emit (OpCodes.Ldc_I4_0);
3360 ig.Emit (OpCodes.Conv_U);
3361 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3365 class StringEmitter: Emitter {
3366 LocalBuilder pinned_string;
3369 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3375 public override void Emit (EmitContext ec)
3377 ILGenerator ig = ec.ig;
3378 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3380 converted.Emit (ec);
3381 ig.Emit (OpCodes.Stloc, pinned_string);
3383 Expression sptr = new StringPtr (pinned_string, loc);
3384 converted = Convert.ImplicitConversionRequired (
3385 ec, sptr, vi.VariableType, loc);
3387 if (converted == null)
3390 converted.Emit (ec);
3391 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3394 public override void EmitExit(ILGenerator ig)
3396 ig.Emit (OpCodes.Ldnull);
3397 ig.Emit (OpCodes.Stloc, pinned_string);
3401 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3404 declarators = decls;
3409 public override bool Resolve (EmitContext ec)
3412 Expression.UnsafeError (loc);
3416 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3420 expr_type = texpr.ResolveType (ec);
3422 CheckObsolete (expr_type);
3424 if (ec.RemapToProxy){
3425 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3429 data = new Emitter [declarators.Count];
3431 if (!expr_type.IsPointer){
3432 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3437 foreach (Pair p in declarators){
3438 LocalInfo vi = (LocalInfo) p.First;
3439 Expression e = (Expression) p.Second;
3441 vi.VariableInfo.SetAssigned (ec);
3442 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3445 // The rules for the possible declarators are pretty wise,
3446 // but the production on the grammar is more concise.
3448 // So we have to enforce these rules here.
3450 // We do not resolve before doing the case 1 test,
3451 // because the grammar is explicit in that the token &
3452 // is present, so we need to test for this particular case.
3456 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3461 // Case 1: & object.
3463 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3464 Expression child = ((Unary) e).Expr;
3466 if (child is ParameterReference || child is LocalVariableReference){
3469 "No need to use fixed statement for parameters or " +
3470 "local variable declarations (address is already " +
3475 ec.InFixedInitializer = true;
3477 ec.InFixedInitializer = false;
3481 child = ((Unary) e).Expr;
3483 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3486 data [i] = new ExpressionEmitter (e, vi);
3492 ec.InFixedInitializer = true;
3494 ec.InFixedInitializer = false;
3501 if (e.Type.IsArray){
3502 Type array_type = TypeManager.GetElementType (e.Type);
3505 // Provided that array_type is unmanaged,
3507 if (!TypeManager.VerifyUnManaged (array_type, loc))
3511 // and T* is implicitly convertible to the
3512 // pointer type given in the fixed statement.
3514 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3516 Expression converted = Convert.ImplicitConversionRequired (
3517 ec, array_ptr, vi.VariableType, loc);
3518 if (converted == null)
3521 data [i] = new ExpressionEmitter (converted, vi);
3530 if (e.Type == TypeManager.string_type){
3531 data [i] = new StringEmitter (e, vi, loc);
3536 // Case 4: fixed buffer
3537 FieldExpr fe = e as FieldExpr;
3539 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3541 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3543 Expression converted = Convert.ImplicitConversionRequired (
3544 ec, fixed_buffer_ptr, vi.VariableType, loc);
3545 if (converted == null)
3548 data [i] = new ExpressionEmitter (converted, vi);
3556 // For other cases, flag a `this is already fixed expression'
3558 if (e is LocalVariableReference || e is ParameterReference ||
3559 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3561 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3565 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3569 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3571 if (!statement.Resolve (ec)) {
3572 ec.KillFlowBranching ();
3576 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3577 has_ret = reachability.IsUnreachable;
3582 protected override void DoEmit (EmitContext ec)
3584 for (int i = 0; i < data.Length; i++) {
3588 statement.Emit (ec);
3593 ILGenerator ig = ec.ig;
3596 // Clear the pinned variable
3598 for (int i = 0; i < data.Length; i++) {
3599 data [i].EmitExit (ig);
3604 public class Catch: Statement {
3605 public readonly string Name;
3606 public readonly Block Block;
3608 Expression type_expr;
3611 public Catch (Expression type, string name, Block block, Location l)
3619 public Type CatchType {
3625 public bool IsGeneral {
3627 return type_expr == null;
3631 protected override void DoEmit(EmitContext ec)
3635 public override bool Resolve (EmitContext ec)
3637 bool was_catch = ec.InCatch;
3640 if (type_expr != null) {
3641 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3645 type = te.ResolveType (ec);
3647 CheckObsolete (type);
3649 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3650 Error (155, "The type caught or thrown must be derived from System.Exception");
3656 return Block.Resolve (ec);
3659 ec.InCatch = was_catch;
3664 public class Try : ExceptionStatement {
3665 public readonly Block Fini, Block;
3666 public readonly ArrayList Specific;
3667 public readonly Catch General;
3669 bool need_exc_block;
3672 // specific, general and fini might all be null.
3674 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3676 if (specific == null && general == null){
3677 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3681 this.Specific = specific;
3682 this.General = general;
3687 public override bool Resolve (EmitContext ec)
3691 FlowBranchingException branching = ec.StartFlowBranching (this);
3693 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3695 if (!Block.Resolve (ec))
3698 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3700 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3702 Type[] prevCatches = new Type [Specific.Count];
3704 foreach (Catch c in Specific){
3705 ec.CurrentBranching.CreateSibling (
3706 c.Block, FlowBranching.SiblingType.Catch);
3708 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3710 if (c.Name != null) {
3711 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3713 throw new Exception ();
3715 vi.VariableInfo = null;
3718 if (!c.Resolve (ec))
3721 Type resolvedType = c.CatchType;
3722 for (int ii = 0; ii < last_index; ++ii) {
3723 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3724 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3729 prevCatches [last_index++] = resolvedType;
3730 need_exc_block = true;
3733 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3735 if (General != null){
3736 ec.CurrentBranching.CreateSibling (
3737 General.Block, FlowBranching.SiblingType.Catch);
3739 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3741 if (!General.Resolve (ec))
3744 need_exc_block = true;
3747 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3751 ec.CurrentBranching.CreateSibling (
3752 Fini, FlowBranching.SiblingType.Finally);
3754 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3755 bool was_finally = ec.InFinally;
3756 ec.InFinally = true;
3757 if (!Fini.Resolve (ec))
3759 ec.InFinally = was_finally;
3762 ResolveFinally (branching);
3763 need_exc_block |= emit_finally;
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)
3826 public bool HasCatch
3829 return General != null || Specific.Count > 0;
3834 public class Using : ExceptionStatement {
3835 object expression_or_block;
3836 Statement Statement;
3841 Expression [] resolved_vars;
3842 Expression [] converted_vars;
3843 ExpressionStatement [] assign;
3844 LocalBuilder local_copy;
3846 public Using (object expression_or_block, Statement stmt, Location l)
3848 this.expression_or_block = expression_or_block;
3854 // Resolves for the case of using using a local variable declaration.
3856 bool ResolveLocalVariableDecls (EmitContext ec)
3860 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3864 expr_type = texpr.ResolveType (ec);
3867 // The type must be an IDisposable or an implicit conversion
3870 converted_vars = new Expression [var_list.Count];
3871 resolved_vars = new Expression [var_list.Count];
3872 assign = new ExpressionStatement [var_list.Count];
3874 bool need_conv = !TypeManager.ImplementsInterface (
3875 expr_type, TypeManager.idisposable_type);
3877 foreach (DictionaryEntry e in var_list){
3878 Expression var = (Expression) e.Key;
3880 var = var.ResolveLValue (ec, new EmptyExpression ());
3884 resolved_vars [i] = var;
3891 converted_vars [i] = Convert.ImplicitConversionRequired (
3892 ec, var, TypeManager.idisposable_type, loc);
3894 if (converted_vars [i] == null)
3901 foreach (DictionaryEntry e in var_list){
3902 Expression var = resolved_vars [i];
3903 Expression new_expr = (Expression) e.Value;
3906 a = new Assign (var, new_expr, loc);
3912 converted_vars [i] = var;
3913 assign [i] = (ExpressionStatement) a;
3920 bool ResolveExpression (EmitContext ec)
3922 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3923 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3924 Report.Error (1674, loc, "'{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3925 TypeManager.CSharpName (expr_type));
3934 // Emits the code for the case of using using a local variable declaration.
3936 void EmitLocalVariableDecls (EmitContext ec)
3938 ILGenerator ig = ec.ig;
3941 for (i = 0; i < assign.Length; i++) {
3942 assign [i].EmitStatement (ec);
3945 ig.BeginExceptionBlock ();
3947 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 if (!var.Type.IsValueType) {
3964 ig.Emit (OpCodes.Brfalse, skip);
3965 converted_vars [i].Emit (ec);
3966 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3968 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3970 if (!(ml is MethodGroupExpr)) {
3972 ig.Emit (OpCodes.Box, var.Type);
3973 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3975 MethodInfo mi = null;
3977 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3978 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3985 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3989 IMemoryLocation mloc = (IMemoryLocation) var;
3991 mloc.AddressOf (ec, AddressOp.Load);
3992 ig.Emit (OpCodes.Call, mi);
3996 ig.MarkLabel (skip);
3999 ig.EndExceptionBlock ();
4001 ig.BeginFinallyBlock ();
4006 void EmitExpression (EmitContext ec)
4009 // Make a copy of the expression and operate on that.
4011 ILGenerator ig = ec.ig;
4012 local_copy = ig.DeclareLocal (expr_type);
4017 ig.Emit (OpCodes.Stloc, local_copy);
4020 ig.BeginExceptionBlock ();
4022 Statement.Emit (ec);
4026 ig.EndExceptionBlock ();
4029 void EmitExpressionFinally (EmitContext ec)
4031 ILGenerator ig = ec.ig;
4032 if (!local_copy.LocalType.IsValueType) {
4033 Label skip = ig.DefineLabel ();
4034 ig.Emit (OpCodes.Ldloc, local_copy);
4035 ig.Emit (OpCodes.Brfalse, skip);
4036 ig.Emit (OpCodes.Ldloc, local_copy);
4037 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4038 ig.MarkLabel (skip);
4040 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4042 if (!(ml is MethodGroupExpr)) {
4043 ig.Emit (OpCodes.Ldloc, local_copy);
4044 ig.Emit (OpCodes.Box, local_copy.LocalType);
4045 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4047 MethodInfo mi = null;
4049 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4050 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4057 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4061 ig.Emit (OpCodes.Ldloca, local_copy);
4062 ig.Emit (OpCodes.Call, mi);
4067 public override bool Resolve (EmitContext ec)
4069 if (expression_or_block is DictionaryEntry){
4070 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4071 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4073 if (!ResolveLocalVariableDecls (ec))
4076 } else if (expression_or_block is Expression){
4077 expr = (Expression) expression_or_block;
4079 expr = expr.Resolve (ec);
4083 expr_type = expr.Type;
4085 if (!ResolveExpression (ec))
4089 FlowBranchingException branching = ec.StartFlowBranching (this);
4091 bool ok = Statement.Resolve (ec);
4094 ec.KillFlowBranching ();
4098 ResolveFinally (branching);
4099 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4101 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4102 // Unfortunately, System.Reflection.Emit automatically emits a leave
4103 // to the end of the finally block. This is a problem if `returns'
4104 // is true since we may jump to a point after the end of the method.
4105 // As a workaround, emit an explicit ret here.
4106 ec.NeedReturnLabel ();
4112 protected override void DoEmit (EmitContext ec)
4114 if (expression_or_block is DictionaryEntry)
4115 EmitLocalVariableDecls (ec);
4116 else if (expression_or_block is Expression)
4117 EmitExpression (ec);
4120 public override void EmitFinally (EmitContext ec)
4122 if (expression_or_block is DictionaryEntry)
4123 EmitLocalVariableDeclFinally (ec);
4124 else if (expression_or_block is Expression)
4125 EmitExpressionFinally (ec);
4130 /// Implementation of the foreach C# statement
4132 public class Foreach : ExceptionStatement {
4134 Expression variable;
4136 Statement statement;
4137 ForeachHelperMethods hm;
4138 Expression empty, conv;
4139 Type array_type, element_type;
4141 VariableStorage enumerator;
4144 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4145 Statement stmt, Location l)
4148 this.variable = var;
4154 public override bool Resolve (EmitContext ec)
4156 expr = expr.Resolve (ec);
4160 if (expr is NullLiteral) {
4161 Report.Error (186, expr.Location, "Use of null is not valid in this context");
4165 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4169 var_type = texpr.ResolveType (ec);
4172 // We need an instance variable. Not sure this is the best
4173 // way of doing this.
4175 // FIXME: When we implement propertyaccess, will those turn
4176 // out to return values in ExprClass? I think they should.
4178 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4179 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4180 error1579 (expr.Type);
4184 if (expr.Type.IsArray) {
4185 array_type = expr.Type;
4186 element_type = TypeManager.GetElementType (array_type);
4188 empty = new EmptyExpression (element_type);
4190 array = new ArrayForeach (type, variable, expr, statement, loc);
4191 return array.Resolve (ec);
4193 hm = ProbeCollectionType (ec, expr.Type);
4195 error1579 (expr.Type);
4199 // When ProbeCollection reported error
4200 if (hm.move_next == null)
4203 array_type = expr.Type;
4204 element_type = hm.element_type;
4206 empty = new EmptyExpression (hm.element_type);
4211 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4212 ec.CurrentBranching.CreateSibling ();
4216 // FIXME: maybe we can apply the same trick we do in the
4217 // array handling to avoid creating empty and conv in some cases.
4219 // Although it is not as important in this case, as the type
4220 // will not likely be object (what the enumerator will return).
4222 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4226 variable = variable.ResolveLValue (ec, empty);
4227 if (variable == null)
4230 bool disposable = (hm != null) && hm.is_disposable;
4231 FlowBranchingException branching = null;
4233 branching = ec.StartFlowBranching (this);
4235 if (!statement.Resolve (ec))
4239 ResolveFinally (branching);
4240 ec.EndFlowBranching ();
4242 emit_finally = true;
4244 ec.EndFlowBranching ();
4250 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4252 static MethodInfo FetchMethodMoveNext (Type t)
4254 MemberList move_next_list;
4256 move_next_list = TypeContainer.FindMembers (
4257 t, MemberTypes.Method,
4258 BindingFlags.Public | BindingFlags.Instance,
4259 Type.FilterName, "MoveNext");
4260 if (move_next_list.Count == 0)
4263 foreach (MemberInfo m in move_next_list){
4264 MethodInfo mi = (MethodInfo) m;
4267 args = TypeManager.GetArgumentTypes (mi);
4268 if (args != null && args.Length == 0){
4269 if (mi.ReturnType == TypeManager.bool_type)
4277 // Retrieves a `public T get_Current ()' method from the Type `t'
4279 static MethodInfo FetchMethodGetCurrent (Type t)
4281 MemberList get_current_list;
4283 get_current_list = TypeContainer.FindMembers (
4284 t, MemberTypes.Method,
4285 BindingFlags.Public | BindingFlags.Instance,
4286 Type.FilterName, "get_Current");
4287 if (get_current_list.Count == 0)
4290 foreach (MemberInfo m in get_current_list){
4291 MethodInfo mi = (MethodInfo) m;
4294 args = TypeManager.GetArgumentTypes (mi);
4295 if (args != null && args.Length == 0)
4302 // Retrieves a `public void Dispose ()' method from the Type `t'
4304 static MethodInfo FetchMethodDispose (Type t)
4306 MemberList dispose_list;
4308 dispose_list = TypeContainer.FindMembers (
4309 t, MemberTypes.Method,
4310 BindingFlags.Public | BindingFlags.Instance,
4311 Type.FilterName, "Dispose");
4312 if (dispose_list.Count == 0)
4315 foreach (MemberInfo m in dispose_list){
4316 MethodInfo mi = (MethodInfo) m;
4319 args = TypeManager.GetArgumentTypes (mi);
4320 if (args != null && args.Length == 0){
4321 if (mi.ReturnType == TypeManager.void_type)
4329 // This struct records the helper methods used by the Foreach construct
4331 class ForeachHelperMethods {
4332 public EmitContext ec;
4333 public MethodInfo get_enumerator;
4334 public MethodInfo move_next;
4335 public MethodInfo get_current;
4336 public Type element_type;
4337 public Type enumerator_type;
4338 public bool is_disposable;
4339 public readonly Location Location;
4341 public ForeachHelperMethods (EmitContext ec, Location loc)
4344 this.Location = loc;
4345 this.element_type = TypeManager.object_type;
4346 this.enumerator_type = TypeManager.ienumerator_type;
4347 this.is_disposable = true;
4351 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4356 if (!(m is MethodInfo))
4359 if (m.Name != "GetEnumerator")
4362 MethodInfo mi = (MethodInfo) m;
4363 Type [] args = TypeManager.GetArgumentTypes (mi);
4365 if (args.Length != 0)
4368 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4370 // Check whether GetEnumerator is public
4371 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4374 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4376 // Apply the same optimization as MS: skip the GetEnumerator
4377 // returning an IEnumerator, and use the one returning a
4378 // CharEnumerator instead. This allows us to avoid the
4379 // try-finally block and the boxing.
4384 // Ok, we can access it, now make sure that we can do something
4385 // with this `GetEnumerator'
4388 Type return_type = mi.ReturnType;
4389 if (mi.ReturnType == TypeManager.ienumerator_type ||
4390 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4391 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4394 // If it is not an interface, lets try to find the methods ourselves.
4395 // For example, if we have:
4396 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4397 // We can avoid the iface call. This is a runtime perf boost.
4398 // even bigger if we have a ValueType, because we avoid the cost
4401 // We have to make sure that both methods exist for us to take
4402 // this path. If one of the methods does not exist, we will just
4403 // use the interface. Sadly, this complex if statement is the only
4404 // way I could do this without a goto
4407 if (return_type.IsInterface ||
4408 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4409 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4411 hm.move_next = TypeManager.bool_movenext_void;
4412 hm.get_current = TypeManager.object_getcurrent_void;
4418 if (return_type.IsPointer || return_type.IsArray) {
4419 Report.SymbolRelatedToPreviousError (mi);
4420 Type t = return_type.GetElementType ();
4421 Report.SymbolRelatedToPreviousError (t);
4422 Report.Error (202, hm.Location, "foreach requires that the return type '{0}' of '{1}' must have a suitable public MoveNext method and public Current property",
4423 TypeManager.CSharpName (return_type), TypeManager.GetFullNameSignature (m));
4424 hm.get_enumerator = mi;
4429 // Ok, so they dont return an IEnumerable, we will have to
4430 // find if they support the GetEnumerator pattern.
4433 hm.move_next = FetchMethodMoveNext (return_type);
4434 if (hm.move_next == null)
4437 hm.get_current = FetchMethodGetCurrent (return_type);
4438 if (hm.get_current == null)
4442 hm.element_type = hm.get_current.ReturnType;
4443 hm.enumerator_type = return_type;
4444 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4445 TypeManager.ImplementsInterface (
4446 hm.enumerator_type, TypeManager.idisposable_type);
4452 /// This filter is used to find the GetEnumerator method
4453 /// on which IEnumerator operates
4455 static MemberFilter FilterEnumerator;
4459 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4462 void error1579 (Type t)
4464 Report.Error (1579, loc,
4465 "foreach statement cannot operate on variables of type `" +
4466 t.FullName + "' because that class does not provide a " +
4467 " GetEnumerator method or it is inaccessible");
4470 static bool TryType (Type t, ForeachHelperMethods hm)
4474 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4475 BindingFlags.Public | BindingFlags.NonPublic |
4476 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4477 FilterEnumerator, hm);
4482 hm.get_enumerator = (MethodInfo) mi [0];
4487 // Looks for a usable GetEnumerator in the Type, and if found returns
4488 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4490 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4492 ForeachHelperMethods hm = new ForeachHelperMethods (ec, loc);
4494 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4495 if (TryType (tt, hm))
4501 // Now try to find the method in the interfaces
4504 Type [] ifaces = t.GetInterfaces ();
4506 foreach (Type i in ifaces){
4507 if (TryType (i, hm))
4512 // Since TypeBuilder.GetInterfaces only returns the interface
4513 // types for this type, we have to keep looping, but once
4514 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4515 // done, because it returns all the types
4517 if ((t is TypeBuilder))
4527 // FIXME: possible optimization.
4528 // We might be able to avoid creating `empty' if the type is the sam
4530 bool EmitCollectionForeach (EmitContext ec)
4532 ILGenerator ig = ec.ig;
4534 enumerator = new VariableStorage (ec, hm.enumerator_type);
4535 enumerator.EmitThis (ig);
4537 // Instantiate the enumerator
4539 if (expr.Type.IsValueType) {
4540 IMemoryLocation ml = expr as IMemoryLocation;
4541 // Load the address of the value type.
4543 // This happens if, for example, you have a property
4544 // returning a struct which is IEnumerable
4545 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4547 ig.Emit (OpCodes.Stloc, t);
4548 ig.Emit (OpCodes.Ldloca, t);
4549 ec.FreeTemporaryLocal (t, expr.Type);
4551 ml.AddressOf (ec, AddressOp.Load);
4555 if (hm.get_enumerator.DeclaringType.IsValueType) {
4556 // the method is declared on the value type
4557 ig.Emit (OpCodes.Call, hm.get_enumerator);
4559 // it is an interface method, so we must box
4560 ig.Emit (OpCodes.Box, expr.Type);
4561 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4565 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4567 enumerator.EmitStore (ig);
4570 // Protect the code in a try/finalize block, so that
4571 // if the beast implement IDisposable, we get rid of it
4573 if (hm.is_disposable && emit_finally)
4574 ig.BeginExceptionBlock ();
4576 Label end_try = ig.DefineLabel ();
4578 ig.MarkLabel (ec.LoopBegin);
4580 enumerator.EmitCall (ig, hm.move_next);
4582 ig.Emit (OpCodes.Brfalse, end_try);
4585 ig.Emit (OpCodes.Ldarg_0);
4587 enumerator.EmitCall (ig, hm.get_current);
4591 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4593 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4595 statement.Emit (ec);
4596 ig.Emit (OpCodes.Br, ec.LoopBegin);
4597 ig.MarkLabel (end_try);
4600 // Now the finally block
4602 if (hm.is_disposable) {
4605 ig.EndExceptionBlock ();
4608 ig.MarkLabel (ec.LoopEnd);
4612 public override void EmitFinally (EmitContext ec)
4614 ILGenerator ig = ec.ig;
4616 if (hm.enumerator_type.IsValueType) {
4617 enumerator.EmitThis (ig);
4619 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4621 enumerator.EmitLoadAddress (ig);
4622 ig.Emit (OpCodes.Call, mi);
4624 enumerator.EmitLoad (ig);
4625 ig.Emit (OpCodes.Box, hm.enumerator_type);
4626 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4629 Label call_dispose = ig.DefineLabel ();
4631 enumerator.EmitThis (ig);
4632 enumerator.EmitLoad (ig);
4633 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4634 ig.Emit (OpCodes.Dup);
4635 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4636 ig.Emit (OpCodes.Pop);
4638 Label end_finally = ig.DefineLabel ();
4639 ig.Emit (OpCodes.Br, end_finally);
4641 ig.MarkLabel (call_dispose);
4642 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4643 ig.MarkLabel (end_finally);
4646 ig.Emit (OpCodes.Endfinally);
4650 protected override void DoEmit (EmitContext ec)
4652 ILGenerator ig = ec.ig;
4654 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4655 ec.LoopBegin = ig.DefineLabel ();
4656 ec.LoopEnd = ig.DefineLabel ();
4659 EmitCollectionForeach (ec);
4663 ec.LoopBegin = old_begin;
4664 ec.LoopEnd = old_end;
4667 protected class TemporaryVariable : Expression
4672 public TemporaryVariable (Type type, Location loc)
4676 eclass = ExprClass.Value;
4681 public override Expression DoResolve (EmitContext ec)
4683 if (ec.InIterator) {
4685 fb = ec.CurrentIterator.MapVariable (
4686 "s_", count.ToString (), type);
4688 local = ec.ig.DeclareLocal (type);
4693 public override void Emit (EmitContext ec)
4695 ILGenerator ig = ec.ig;
4698 ig.Emit (OpCodes.Ldarg_0);
4699 ig.Emit (OpCodes.Ldfld, fb);
4701 ig.Emit (OpCodes.Ldloc, local);
4705 public void Store (EmitContext ec, Expression right_side)
4708 ec.ig.Emit (OpCodes.Ldarg_0);
4709 right_side.Emit (ec);
4711 ec.ig.Emit (OpCodes.Stloc, local);
4713 ec.ig.Emit (OpCodes.Stfld, fb);
4716 public void EmitThis (ILGenerator ig)
4719 ig.Emit (OpCodes.Ldarg_0);
4722 public void EmitStore (ILGenerator ig)
4725 ig.Emit (OpCodes.Stloc, local);
4727 ig.Emit (OpCodes.Stfld, fb);
4731 protected class ArrayCounter : TemporaryVariable
4733 public ArrayCounter (Location loc)
4734 : base (TypeManager.int32_type, loc)
4737 public void Initialize (EmitContext ec)
4740 ec.ig.Emit (OpCodes.Ldc_I4_0);
4744 public void Increment (EmitContext ec)
4748 ec.ig.Emit (OpCodes.Ldc_I4_1);
4749 ec.ig.Emit (OpCodes.Add);
4754 protected class ArrayForeach : Statement
4756 Expression type, variable, expr, conv;
4757 Statement statement;
4758 Type array_type, element_type;
4760 TemporaryVariable[] lengths;
4761 ArrayCounter[] counter;
4764 TemporaryVariable copy;
4767 public ArrayForeach (Expression type, Expression var,
4768 Expression expr, Statement stmt, Location l)
4771 this.variable = var;
4777 public override bool Resolve (EmitContext ec)
4779 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4783 var_type = texpr.Type;
4785 array_type = expr.Type;
4786 element_type = TypeManager.GetElementType (array_type);
4787 rank = array_type.GetArrayRank ();
4789 copy = new TemporaryVariable (array_type, loc);
4792 counter = new ArrayCounter [rank];
4793 lengths = new TemporaryVariable [rank];
4795 ArrayList list = new ArrayList ();
4796 for (int i = 0; i < rank; i++) {
4797 counter [i] = new ArrayCounter (loc);
4798 counter [i].Resolve (ec);
4800 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4801 lengths [i].Resolve (ec);
4803 list.Add (counter [i]);
4806 access = new ElementAccess (copy, list, loc).Resolve (ec);
4810 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4816 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4817 ec.CurrentBranching.CreateSibling ();
4819 variable = variable.ResolveLValue (ec, conv);
4820 if (variable == null)
4823 if (!statement.Resolve (ec))
4826 ec.EndFlowBranching ();
4831 protected override void DoEmit (EmitContext ec)
4833 ILGenerator ig = ec.ig;
4835 copy.Store (ec, expr);
4837 Label[] test = new Label [rank];
4838 Label[] loop = new Label [rank];
4840 for (int i = 0; i < rank; i++) {
4841 test [i] = ig.DefineLabel ();
4842 loop [i] = ig.DefineLabel ();
4844 lengths [i].EmitThis (ig);
4845 ((ArrayAccess) access).EmitGetLength (ec, i);
4846 lengths [i].EmitStore (ig);
4849 for (int i = 0; i < rank; i++) {
4850 counter [i].Initialize (ec);
4852 ig.Emit (OpCodes.Br, test [i]);
4853 ig.MarkLabel (loop [i]);
4856 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4858 statement.Emit (ec);
4860 ig.MarkLabel (ec.LoopBegin);
4862 for (int i = rank - 1; i >= 0; i--){
4863 counter [i].Increment (ec);
4865 ig.MarkLabel (test [i]);
4866 counter [i].Emit (ec);
4867 lengths [i].Emit (ec);
4868 ig.Emit (OpCodes.Blt, loop [i]);
4871 ig.MarkLabel (ec.LoopEnd);