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)
142 Report.Debug (1, "START IF BLOCK", loc);
144 expr = Expression.ResolveBoolean (ec, expr, loc);
150 // Dead code elimination
152 if (expr is BoolConstant){
153 bool take = ((BoolConstant) expr).Value;
156 if (!TrueStatement.Resolve (ec))
159 if ((FalseStatement != null) &&
160 !FalseStatement.ResolveUnreachable (ec, true))
162 FalseStatement = null;
164 if (!TrueStatement.ResolveUnreachable (ec, true))
166 TrueStatement = null;
168 if ((FalseStatement != null) &&
169 !FalseStatement.Resolve (ec))
176 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
178 bool ok = TrueStatement.Resolve (ec);
180 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
182 ec.CurrentBranching.CreateSibling ();
184 if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
187 ec.EndFlowBranching ();
189 Report.Debug (1, "END IF BLOCK", loc);
194 protected override void DoEmit (EmitContext ec)
196 ILGenerator ig = ec.ig;
197 Label false_target = ig.DefineLabel ();
201 // If we're a boolean expression, Resolve() already
202 // eliminated dead code for us.
204 if (expr is BoolConstant){
205 bool take = ((BoolConstant) expr).Value;
208 TrueStatement.Emit (ec);
209 else if (FalseStatement != null)
210 FalseStatement.Emit (ec);
215 expr.EmitBranchable (ec, false_target, false);
217 TrueStatement.Emit (ec);
219 if (FalseStatement != null){
220 bool branch_emitted = false;
222 end = ig.DefineLabel ();
224 ig.Emit (OpCodes.Br, end);
225 branch_emitted = true;
228 ig.MarkLabel (false_target);
229 FalseStatement.Emit (ec);
234 ig.MarkLabel (false_target);
239 public class Do : Statement {
240 public Expression expr;
241 public readonly Statement EmbeddedStatement;
244 public Do (Statement statement, Expression boolExpr, Location l)
247 EmbeddedStatement = statement;
251 public override bool Resolve (EmitContext ec)
255 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
257 if (!EmbeddedStatement.Resolve (ec))
260 expr = Expression.ResolveBoolean (ec, expr, loc);
263 else if (expr is BoolConstant){
264 bool res = ((BoolConstant) expr).Value;
270 ec.CurrentBranching.Infinite = infinite;
271 ec.EndFlowBranching ();
276 protected override void DoEmit (EmitContext ec)
278 ILGenerator ig = ec.ig;
279 Label loop = ig.DefineLabel ();
280 Label old_begin = ec.LoopBegin;
281 Label old_end = ec.LoopEnd;
283 ec.LoopBegin = ig.DefineLabel ();
284 ec.LoopEnd = ig.DefineLabel ();
287 EmbeddedStatement.Emit (ec);
288 ig.MarkLabel (ec.LoopBegin);
291 // Dead code elimination
293 if (expr is BoolConstant){
294 bool res = ((BoolConstant) expr).Value;
297 ec.ig.Emit (OpCodes.Br, loop);
299 expr.EmitBranchable (ec, loop, true);
301 ig.MarkLabel (ec.LoopEnd);
303 ec.LoopBegin = old_begin;
304 ec.LoopEnd = old_end;
308 public class While : Statement {
309 public Expression expr;
310 public readonly Statement Statement;
311 bool infinite, empty;
313 public While (Expression boolExpr, Statement statement, Location l)
315 this.expr = boolExpr;
316 Statement = statement;
320 public override bool Resolve (EmitContext ec)
324 expr = Expression.ResolveBoolean (ec, expr, loc);
329 // Inform whether we are infinite or not
331 if (expr is BoolConstant){
332 BoolConstant bc = (BoolConstant) expr;
334 if (bc.Value == false){
335 if (!Statement.ResolveUnreachable (ec, true))
343 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
345 if (!Statement.Resolve (ec))
348 ec.CurrentBranching.Infinite = infinite;
349 ec.EndFlowBranching ();
354 protected override void DoEmit (EmitContext ec)
359 ILGenerator ig = ec.ig;
360 Label old_begin = ec.LoopBegin;
361 Label old_end = ec.LoopEnd;
363 ec.LoopBegin = ig.DefineLabel ();
364 ec.LoopEnd = ig.DefineLabel ();
367 // Inform whether we are infinite or not
369 if (expr is BoolConstant){
370 ig.MarkLabel (ec.LoopBegin);
372 ig.Emit (OpCodes.Br, ec.LoopBegin);
375 // Inform that we are infinite (ie, `we return'), only
376 // if we do not `break' inside the code.
378 ig.MarkLabel (ec.LoopEnd);
380 Label while_loop = ig.DefineLabel ();
382 ig.Emit (OpCodes.Br, ec.LoopBegin);
383 ig.MarkLabel (while_loop);
387 ig.MarkLabel (ec.LoopBegin);
389 expr.EmitBranchable (ec, while_loop, true);
391 ig.MarkLabel (ec.LoopEnd);
394 ec.LoopBegin = old_begin;
395 ec.LoopEnd = old_end;
399 public class For : Statement {
401 readonly Statement InitStatement;
402 readonly Statement Increment;
403 readonly Statement Statement;
404 bool infinite, empty;
406 public For (Statement initStatement,
412 InitStatement = initStatement;
414 Increment = increment;
415 Statement = statement;
419 public override bool Resolve (EmitContext ec)
423 if (InitStatement != null){
424 if (!InitStatement.Resolve (ec))
429 Test = Expression.ResolveBoolean (ec, Test, loc);
432 else if (Test is BoolConstant){
433 BoolConstant bc = (BoolConstant) Test;
435 if (bc.Value == false){
436 if (!Statement.ResolveUnreachable (ec, true))
438 if ((Increment != null) &&
439 !Increment.ResolveUnreachable (ec, false))
449 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
451 ec.CurrentBranching.CreateSibling ();
453 if (!Statement.Resolve (ec))
456 if (Increment != null){
457 if (!Increment.Resolve (ec))
461 ec.CurrentBranching.Infinite = infinite;
462 ec.EndFlowBranching ();
467 protected override void DoEmit (EmitContext ec)
472 ILGenerator ig = ec.ig;
473 Label old_begin = ec.LoopBegin;
474 Label old_end = ec.LoopEnd;
475 Label loop = ig.DefineLabel ();
476 Label test = ig.DefineLabel ();
478 if (InitStatement != null && InitStatement != EmptyStatement.Value)
479 InitStatement.Emit (ec);
481 ec.LoopBegin = ig.DefineLabel ();
482 ec.LoopEnd = ig.DefineLabel ();
484 ig.Emit (OpCodes.Br, test);
488 ig.MarkLabel (ec.LoopBegin);
489 if (Increment != EmptyStatement.Value)
494 // If test is null, there is no test, and we are just
499 // The Resolve code already catches the case for
500 // Test == BoolConstant (false) so we know that
503 if (Test is BoolConstant)
504 ig.Emit (OpCodes.Br, loop);
506 Test.EmitBranchable (ec, loop, true);
509 ig.Emit (OpCodes.Br, loop);
510 ig.MarkLabel (ec.LoopEnd);
512 ec.LoopBegin = old_begin;
513 ec.LoopEnd = old_end;
517 public class StatementExpression : Statement {
518 ExpressionStatement expr;
520 public StatementExpression (ExpressionStatement expr, Location l)
526 public override bool Resolve (EmitContext ec)
528 expr = expr.ResolveStatement (ec);
532 protected override void DoEmit (EmitContext ec)
534 expr.EmitStatement (ec);
537 public override string ToString ()
539 return "StatementExpression (" + expr + ")";
544 /// Implements the return statement
546 public class Return : Statement {
547 public Expression Expr;
549 public Return (Expression expr, Location l)
557 public override bool Resolve (EmitContext ec)
559 if (ec.ReturnType == null){
561 if (ec.CurrentAnonymousMethod != null){
562 Report.Error (1662, loc, String.Format (
563 "Anonymous method could not be converted to delegate " +
564 "since the return value does not match the delegate value"));
566 Error (127, "Return with a value not allowed here");
571 Error (126, "An object of type `{0}' is expected " +
572 "for the return statement",
573 TypeManager.CSharpName (ec.ReturnType));
577 Expr = Expr.Resolve (ec);
581 if (Expr.Type != ec.ReturnType) {
582 Expr = Convert.ImplicitConversionRequired (
583 ec, Expr, ec.ReturnType, loc);
590 Error (-206, "Return statement not allowed inside iterators");
594 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
596 if (ec.CurrentBranching.InTryOrCatch (true)) {
597 ec.CurrentBranching.AddFinallyVector (vector);
599 } else if (ec.CurrentBranching.InFinally (true)) {
600 Error (157, "Control can not leave the body of the finally block");
603 vector.CheckOutParameters (ec.CurrentBranching);
606 ec.NeedReturnLabel ();
608 ec.CurrentBranching.CurrentUsageVector.Return ();
612 protected override void DoEmit (EmitContext ec)
618 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
622 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
624 ec.ig.Emit (OpCodes.Ret);
628 public class Goto : Statement {
631 LabeledStatement label;
633 public override bool Resolve (EmitContext ec)
635 label = ec.CurrentBranching.LookupLabel (target, loc);
639 // If this is a forward goto.
640 if (!label.IsDefined)
641 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
643 ec.CurrentBranching.CurrentUsageVector.Goto ();
648 public Goto (Block parent_block, string label, Location l)
650 block = parent_block;
655 public string Target {
661 protected override void DoEmit (EmitContext ec)
663 Label l = label.LabelTarget (ec);
664 ec.ig.Emit (OpCodes.Br, l);
668 public class LabeledStatement : Statement {
669 public readonly Location Location;
674 FlowBranching.UsageVector vectors;
676 public LabeledStatement (string label_name, Location l)
681 public Label LabelTarget (EmitContext ec)
685 label = ec.ig.DefineLabel ();
691 public bool IsDefined {
697 public bool HasBeenReferenced {
703 public void AddUsageVector (FlowBranching.UsageVector vector)
705 vector = vector.Clone ();
706 vector.Next = vectors;
710 public override bool Resolve (EmitContext ec)
712 ec.CurrentBranching.Label (vectors);
719 protected override void DoEmit (EmitContext ec)
722 ec.ig.MarkLabel (label);
728 /// `goto default' statement
730 public class GotoDefault : Statement {
732 public GotoDefault (Location l)
737 public override bool Resolve (EmitContext ec)
739 ec.CurrentBranching.CurrentUsageVector.Goto ();
743 protected override void DoEmit (EmitContext ec)
745 if (ec.Switch == null){
746 Report.Error (153, loc, "goto default is only valid in a switch statement");
750 if (!ec.Switch.GotDefault){
751 Report.Error (159, loc, "No default target on switch statement");
754 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
759 /// `goto case' statement
761 public class GotoCase : Statement {
765 public GotoCase (Expression e, Location l)
771 public override bool Resolve (EmitContext ec)
773 if (ec.Switch == null){
774 Report.Error (153, loc, "goto case is only valid in a switch statement");
778 expr = expr.Resolve (ec);
782 if (!(expr is Constant)){
783 Report.Error (159, loc, "Target expression for goto case is not constant");
787 object val = Expression.ConvertIntLiteral (
788 (Constant) expr, ec.Switch.SwitchType, loc);
793 sl = (SwitchLabel) ec.Switch.Elements [val];
798 "No such label 'case " + val + "': for the goto case");
802 ec.CurrentBranching.CurrentUsageVector.Goto ();
806 protected override void DoEmit (EmitContext ec)
808 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
812 public class Throw : Statement {
815 public Throw (Expression expr, Location l)
821 public override bool Resolve (EmitContext ec)
823 bool in_catch = ec.CurrentBranching.InCatch ();
824 ec.CurrentBranching.CurrentUsageVector.Throw ();
827 expr = expr.Resolve (ec);
831 ExprClass eclass = expr.eclass;
833 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
834 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
835 expr.Error_UnexpectedKind ("value, variable, property or indexer access ", loc);
841 if ((t != TypeManager.exception_type) &&
842 !t.IsSubclassOf (TypeManager.exception_type) &&
843 !(expr is NullLiteral)) {
845 "The type caught or thrown must be derived " +
846 "from System.Exception");
852 if (ec.CurrentBranching.InFinally (true)) {
853 Error (724, "A throw statement with no argument is only allowed in a catch clause nested inside of the innermost catch clause");
857 if (!ec.CurrentBranching.InCatch ()) {
858 Error (156, "A throw statement with no argument is only allowed in a catch clause");
864 protected override void DoEmit (EmitContext ec)
867 ec.ig.Emit (OpCodes.Rethrow);
871 ec.ig.Emit (OpCodes.Throw);
876 public class Break : Statement {
878 public Break (Location l)
885 public override bool Resolve (EmitContext ec)
887 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
888 Error (139, "No enclosing loop or switch to continue to");
890 } else if (ec.CurrentBranching.InFinally (false)) {
891 Error (157, "Control can not leave the body of the finally block");
893 } else if (ec.CurrentBranching.InTryOrCatch (false))
894 ec.CurrentBranching.AddFinallyVector (
895 ec.CurrentBranching.CurrentUsageVector);
896 else if (ec.CurrentBranching.InLoop ())
897 ec.CurrentBranching.AddBreakVector (
898 ec.CurrentBranching.CurrentUsageVector);
900 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
903 ec.NeedReturnLabel ();
905 ec.CurrentBranching.CurrentUsageVector.Break ();
909 protected override void DoEmit (EmitContext ec)
911 ILGenerator ig = ec.ig;
914 ig.Emit (OpCodes.Leave, ec.LoopEnd);
916 ig.Emit (OpCodes.Br, ec.LoopEnd);
921 public class Continue : Statement {
923 public Continue (Location l)
930 public override bool Resolve (EmitContext ec)
932 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
933 Error (139, "No enclosing loop to continue to");
935 } else if (ec.CurrentBranching.InFinally (false)) {
936 Error (157, "Control can not leave the body of the finally block");
938 } else if (ec.CurrentBranching.InTryOrCatch (false))
939 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
941 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
943 ec.CurrentBranching.CurrentUsageVector.Goto ();
947 protected override void DoEmit (EmitContext ec)
949 Label begin = ec.LoopBegin;
952 ec.ig.Emit (OpCodes.Leave, begin);
954 ec.ig.Emit (OpCodes.Br, begin);
959 // The information about a user-perceived local variable
961 public class LocalInfo {
962 public Expression Type;
965 // Most of the time a variable will be stored in a LocalBuilder
967 // But sometimes, it will be stored in a field (variables that have been
968 // hoisted by iterators or by anonymous methods). The context of the field will
969 // be stored in the EmitContext
972 public LocalBuilder LocalBuilder;
973 public FieldBuilder FieldBuilder;
975 public Type VariableType;
976 public readonly string Name;
977 public readonly Location Location;
978 public readonly Block Block;
980 public VariableInfo VariableInfo;
993 public LocalInfo (Expression type, string name, Block block, Location l)
1001 public LocalInfo (TypeContainer tc, Block block, Location l)
1003 VariableType = tc.TypeBuilder;
1008 public bool IsThisAssigned (EmitContext ec, Location loc)
1010 if (VariableInfo == null)
1011 throw new Exception ();
1013 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1016 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1019 public bool IsAssigned (EmitContext ec)
1021 if (VariableInfo == null)
1022 throw new Exception ();
1024 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1027 public bool Resolve (EmitContext ec)
1029 if (VariableType == null) {
1030 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1034 VariableType = texpr.ResolveType (ec);
1037 if (VariableType == TypeManager.void_type) {
1038 Report.Error (1547, Location,
1039 "Keyword 'void' cannot be used in this context");
1043 if (VariableType.IsAbstract && VariableType.IsSealed) {
1044 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1047 // TODO: breaks the build
1048 // if (VariableType.IsPointer && !ec.InUnsafe)
1049 // Expression.UnsafeError (Location);
1055 // Whether the variable is Fixed (because its Pinned or its a value type)
1057 public bool IsFixed {
1059 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1066 public bool IsCaptured {
1068 return (flags & Flags.Captured) != 0;
1072 flags |= Flags.Captured;
1076 public bool AddressTaken {
1078 return (flags & Flags.AddressTaken) != 0;
1082 flags |= Flags.AddressTaken;
1086 public override string ToString ()
1088 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1089 Name, Type, VariableInfo, Location);
1094 return (flags & Flags.Used) != 0;
1097 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1101 public bool ReadOnly {
1103 return (flags & Flags.ReadOnly) != 0;
1106 flags = value ? (flags | Flags.ReadOnly) : (unchecked (flags & ~Flags.ReadOnly));
1111 // Whether the variable is pinned, if Pinned the variable has been
1112 // allocated in a pinned slot with DeclareLocal.
1114 public bool Pinned {
1116 return (flags & Flags.Pinned) != 0;
1119 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1123 public bool IsThis {
1125 return (flags & Flags.IsThis) != 0;
1128 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1134 /// Block represents a C# block.
1138 /// This class is used in a number of places: either to represent
1139 /// explicit blocks that the programmer places or implicit blocks.
1141 /// Implicit blocks are used as labels or to introduce variable
1144 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1145 /// they contain extra information that is not necessary on normal blocks.
1147 public class Block : Statement {
1148 public Block Parent;
1149 public readonly Location StartLocation;
1150 public Location EndLocation = Location.Null;
1157 VariablesInitialized = 8,
1166 public bool Implicit {
1168 return (flags & Flags.Implicit) != 0;
1172 public bool Unchecked {
1174 return (flags & Flags.Unchecked) != 0;
1177 flags |= Flags.Unchecked;
1181 public bool Unsafe {
1183 return (flags & Flags.Unsafe) != 0;
1186 flags |= Flags.Unsafe;
1190 public bool HasVarargs {
1193 return Parent.HasVarargs;
1195 return (flags & Flags.HasVarargs) != 0;
1198 flags |= Flags.HasVarargs;
1203 // The statements in this block
1205 ArrayList statements;
1209 // An array of Blocks. We keep track of children just
1210 // to generate the local variable declarations.
1212 // Statements and child statements are handled through the
1218 // Labels. (label, block) pairs.
1223 // Keeps track of (name, type) pairs
1225 Hashtable variables;
1228 // Keeps track of constants
1229 Hashtable constants;
1232 // The parameters for the block, this is only needed on the toplevel block really
1233 // TODO: move `parameters' into ToplevelBlock
1234 Parameters parameters;
1237 // If this is a switch section, the enclosing switch block.
1241 protected static int id;
1245 public Block (Block parent)
1246 : this (parent, (Flags) 0, Location.Null, Location.Null)
1249 public Block (Block parent, Flags flags)
1250 : this (parent, flags, Location.Null, Location.Null)
1253 public Block (Block parent, Flags flags, Parameters parameters)
1254 : this (parent, flags, parameters, Location.Null, Location.Null)
1257 public Block (Block parent, Location start, Location end)
1258 : this (parent, (Flags) 0, start, end)
1261 public Block (Block parent, Parameters parameters, Location start, Location end)
1262 : this (parent, (Flags) 0, parameters, start, end)
1265 public Block (Block parent, Flags flags, Location start, Location end)
1266 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1269 public Block (Block parent, Flags flags, Parameters parameters,
1270 Location start, Location end)
1273 parent.AddChild (this);
1275 this.Parent = parent;
1277 this.parameters = parameters;
1278 this.StartLocation = start;
1279 this.EndLocation = end;
1282 statements = new ArrayList ();
1284 if (parent != null && Implicit) {
1285 if (parent.child_variable_names == null)
1286 parent.child_variable_names = new Hashtable();
1287 // share with parent
1288 child_variable_names = parent.child_variable_names;
1293 public Block CreateSwitchBlock (Location start)
1295 Block new_block = new Block (this, start, start);
1296 new_block.switch_block = this;
1306 void AddChild (Block b)
1308 if (children == null)
1309 children = new ArrayList ();
1314 public void SetEndLocation (Location loc)
1320 /// Adds a label to the current block.
1324 /// false if the name already exists in this block. true
1328 public bool AddLabel (string name, LabeledStatement target, Location loc)
1330 if (switch_block != null)
1331 return switch_block.AddLabel (name, target, loc);
1334 while (cur != null) {
1335 if (cur.DoLookupLabel (name) != null) {
1337 140, loc, "The label '{0}' is a duplicate",
1348 while (cur != null) {
1349 if (cur.DoLookupLabel (name) != null) {
1352 "The label '{0}' shadows another label " +
1353 "by the same name in a containing scope.",
1358 if (children != null) {
1359 foreach (Block b in children) {
1360 LabeledStatement s = b.DoLookupLabel (name);
1366 "The label '{0}' shadows another " +
1367 "label by the same name in a " +
1368 "containing scope.",
1379 labels = new Hashtable ();
1381 labels.Add (name, target);
1385 public LabeledStatement LookupLabel (string name)
1387 LabeledStatement s = DoLookupLabel (name);
1391 if (children == null)
1394 foreach (Block child in children) {
1395 if (!child.Implicit)
1398 s = child.LookupLabel (name);
1406 LabeledStatement DoLookupLabel (string name)
1408 if (switch_block != null)
1409 return switch_block.LookupLabel (name);
1412 if (labels.Contains (name))
1413 return ((LabeledStatement) labels [name]);
1418 LocalInfo this_variable = null;
1421 // Returns the "this" instance variable of this block.
1422 // See AddThisVariable() for more information.
1424 public LocalInfo ThisVariable {
1426 if (this_variable != null)
1427 return this_variable;
1428 else if (Parent != null)
1429 return Parent.ThisVariable;
1435 Hashtable child_variable_names;
1438 // Marks a variable with name @name as being used in a child block.
1439 // If a variable name has been used in a child block, it's illegal to
1440 // declare a variable with the same name in the current block.
1442 public void AddChildVariableName (string name)
1444 if (child_variable_names == null)
1445 child_variable_names = new Hashtable ();
1447 child_variable_names [name] = null;
1451 // Checks whether a variable name has already been used in a child block.
1453 public bool IsVariableNameUsedInChildBlock (string name)
1455 if (child_variable_names == null)
1458 return child_variable_names.Contains (name);
1462 // This is used by non-static `struct' constructors which do not have an
1463 // initializer - in this case, the constructor must initialize all of the
1464 // struct's fields. To do this, we add a "this" variable and use the flow
1465 // analysis code to ensure that it's been fully initialized before control
1466 // leaves the constructor.
1468 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1470 if (this_variable != null)
1471 return this_variable;
1473 if (variables == null)
1474 variables = new Hashtable ();
1476 this_variable = new LocalInfo (tc, this, l);
1477 this_variable.Used = true;
1478 this_variable.IsThis = true;
1480 variables.Add ("this", this_variable);
1482 return this_variable;
1485 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1487 if (variables == null)
1488 variables = new Hashtable ();
1490 LocalInfo vi = GetLocalInfo (name);
1492 if (vi.Block != this)
1493 Report.Error (136, l, "A local variable named `" + name + "' " +
1494 "cannot be declared in this scope since it would " +
1495 "give a different meaning to `" + name + "', which " +
1496 "is already used in a `parent or current' scope to " +
1497 "denote something else");
1499 Report.Error (128, l, "A local variable `" + name + "' is already " +
1500 "defined in this scope");
1504 if (IsVariableNameUsedInChildBlock (name)) {
1505 Report.Error (136, l, "A local variable named `" + name + "' " +
1506 "cannot be declared in this scope since it would " +
1507 "give a different meaning to `" + name + "', which " +
1508 "is already used in a `child' scope to denote something " +
1515 Parameter p = pars.GetParameterByName (name, out idx);
1517 Report.Error (136, l, "A local variable named `" + name + "' " +
1518 "cannot be declared in this scope since it would " +
1519 "give a different meaning to `" + name + "', which " +
1520 "is already used in a `parent or current' scope to " +
1521 "denote something else");
1526 vi = new LocalInfo (type, name, this, l);
1528 variables.Add (name, vi);
1530 // Mark 'name' as "used by a child block" in every surrounding block
1532 while (cur != null && cur.Implicit)
1535 for (Block par = cur.Parent; par != null; par = par.Parent)
1536 par.AddChildVariableName (name);
1538 if ((flags & Flags.VariablesInitialized) != 0)
1539 throw new Exception ();
1541 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1545 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1547 if (AddVariable (type, name, pars, l) == null)
1550 if (constants == null)
1551 constants = new Hashtable ();
1553 constants.Add (name, value);
1557 public Hashtable Variables {
1563 public LocalInfo GetLocalInfo (string name)
1565 for (Block b = this; b != null; b = b.Parent) {
1566 if (b.variables != null) {
1567 LocalInfo ret = b.variables [name] as LocalInfo;
1575 public Expression GetVariableType (string name)
1577 LocalInfo vi = GetLocalInfo (name);
1585 public Expression GetConstantExpression (string name)
1587 for (Block b = this; b != null; b = b.Parent) {
1588 if (b.constants != null) {
1589 Expression ret = b.constants [name] as Expression;
1598 /// True if the variable named @name is a constant
1600 public bool IsConstant (string name)
1602 Expression e = null;
1604 e = GetConstantExpression (name);
1610 // Returns a `ParameterReference' for the given name, or null if there
1611 // is no such parameter
1613 public ParameterReference GetParameterReference (string name, Location loc)
1618 Parameters pars = b.parameters;
1624 par = pars.GetParameterByName (name, out idx);
1626 ParameterReference pr;
1628 pr = new ParameterReference (pars, this, idx, name, loc);
1633 } while (b != null);
1638 // Whether the parameter named `name' is local to this block,
1639 // or false, if the parameter belongs to an encompassing block.
1641 public bool IsLocalParameter (string name)
1644 int toplevel_count = 0;
1647 if (this is ToplevelBlock)
1650 Parameters pars = b.parameters;
1652 if (pars.GetParameterByName (name) != null)
1656 if (toplevel_count > 0)
1659 } while (b != null);
1664 // Whether the `name' is a parameter reference
1666 public bool IsParameterReference (string name)
1671 Parameters pars = b.parameters;
1674 if (pars.GetParameterByName (name) != null)
1677 } while (b != null);
1682 /// A list of labels that were not used within this block
1684 public string [] GetUnreferenced ()
1686 // FIXME: Implement me
1690 public void AddStatement (Statement s)
1693 flags |= Flags.BlockUsed;
1698 return (flags & Flags.BlockUsed) != 0;
1704 flags |= Flags.BlockUsed;
1707 public bool HasRet {
1709 return (flags & Flags.HasRet) != 0;
1713 public bool IsDestructor {
1715 return (flags & Flags.IsDestructor) != 0;
1719 public void SetDestructor ()
1721 flags |= Flags.IsDestructor;
1724 VariableMap param_map, local_map;
1726 public VariableMap ParameterMap {
1728 if ((flags & Flags.VariablesInitialized) == 0)
1729 throw new Exception ("Variables have not been initialized yet");
1735 public VariableMap LocalMap {
1737 if ((flags & Flags.VariablesInitialized) == 0)
1738 throw new Exception ("Variables have not been initialized yet");
1745 /// Emits the variable declarations and labels.
1748 /// tc: is our typecontainer (to resolve type references)
1749 /// ig: is the code generator:
1751 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1753 bool old_unsafe = ec.InUnsafe;
1755 // If some parent block was unsafe, we remain unsafe even if this block
1756 // isn't explicitly marked as such.
1757 ec.InUnsafe |= Unsafe;
1760 // Compute the VariableMap's.
1762 // Unfortunately, we don't know the type when adding variables with
1763 // AddVariable(), so we need to compute this info here.
1767 if (variables != null) {
1768 foreach (LocalInfo li in variables.Values)
1771 locals = new LocalInfo [variables.Count];
1772 variables.Values.CopyTo (locals, 0);
1774 locals = new LocalInfo [0];
1777 local_map = new VariableMap (Parent.LocalMap, locals);
1779 local_map = new VariableMap (locals);
1781 param_map = new VariableMap (ip);
1782 flags |= Flags.VariablesInitialized;
1784 bool old_check_state = ec.ConstantCheckState;
1785 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1788 // Process this block variables
1790 if (variables != null){
1791 foreach (DictionaryEntry de in variables){
1792 string name = (string) de.Key;
1793 LocalInfo vi = (LocalInfo) de.Value;
1795 if (vi.VariableType == null)
1798 Type variable_type = vi.VariableType;
1800 if (variable_type.IsPointer){
1802 // Am not really convinced that this test is required (Microsoft does it)
1803 // but the fact is that you would not be able to use the pointer variable
1806 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1813 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1816 // This is needed to compile on both .NET 1.x and .NET 2.x
1817 // the later introduced `DeclareLocal (Type t, bool pinned)'
1819 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1820 else if (!vi.IsThis)
1821 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1824 if (constants == null)
1827 Expression cv = (Expression) constants [name];
1831 ec.CurrentBlock = this;
1832 Expression e = cv.Resolve (ec);
1836 Constant ce = e as Constant;
1838 Report.Error (133, vi.Location,
1839 "The expression being assigned to `" +
1840 name + "' must be constant (" + e + ")");
1844 if (e.Type != variable_type){
1845 e = Const.ChangeType (vi.Location, ce, variable_type);
1850 constants.Remove (name);
1851 constants.Add (name, e);
1854 ec.ConstantCheckState = old_check_state;
1857 // Now, handle the children
1859 if (children != null){
1860 foreach (Block b in children)
1861 b.ResolveMeta (toplevel, ec, ip);
1863 ec.InUnsafe = old_unsafe;
1867 // Emits the local variable declarations for a block
1869 public void EmitMeta (EmitContext ec)
1871 ILGenerator ig = ec.ig;
1873 if (variables != null){
1874 bool have_captured_vars = ec.HaveCapturedVariables ();
1875 bool remap_locals = ec.RemapToProxy;
1877 foreach (DictionaryEntry de in variables){
1878 LocalInfo vi = (LocalInfo) de.Value;
1880 if (have_captured_vars && ec.IsCaptured (vi))
1884 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1888 // This is needed to compile on both .NET 1.x and .NET 2.x
1889 // the later introduced `DeclareLocal (Type t, bool pinned)'
1891 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1892 else if (!vi.IsThis)
1893 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1898 if (children != null){
1899 foreach (Block b in children)
1904 void UsageWarning (FlowBranching.UsageVector vector)
1908 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1909 foreach (DictionaryEntry de in variables){
1910 LocalInfo vi = (LocalInfo) de.Value;
1915 name = (string) de.Key;
1917 if (vector.IsAssigned (vi.VariableInfo)){
1918 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1920 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1926 bool unreachable_shown;
1928 public override bool Resolve (EmitContext ec)
1930 Block prev_block = ec.CurrentBlock;
1933 int errors = Report.Errors;
1935 ec.CurrentBlock = this;
1936 ec.StartFlowBranching (this);
1938 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1940 bool unreachable = false;
1942 int statement_count = statements.Count;
1943 for (int ix = 0; ix < statement_count; ix++){
1944 Statement s = (Statement) statements [ix];
1946 if (unreachable && !(s is LabeledStatement)) {
1947 if (s == EmptyStatement.Value)
1948 s.loc = EndLocation;
1950 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1953 if (s != EmptyStatement.Value)
1954 unreachable_shown = true;
1956 s.loc = Location.Null;
1958 statements [ix] = EmptyStatement.Value;
1962 if (s.Resolve (ec) == false) {
1964 statements [ix] = EmptyStatement.Value;
1968 num_statements = ix + 1;
1970 if (s is LabeledStatement)
1971 unreachable = false;
1973 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1976 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1977 ec.CurrentBranching, statement_count, num_statements);
1980 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1982 ec.CurrentBlock = prev_block;
1984 // If we're a non-static `struct' constructor which doesn't have an
1985 // initializer, then we must initialize all of the struct's fields.
1986 if ((this_variable != null) &&
1987 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1988 !this_variable.IsThisAssigned (ec, loc))
1991 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1992 foreach (LabeledStatement label in labels.Values)
1993 if (!label.HasBeenReferenced)
1994 Report.Warning (164, label.Location,
1995 "This label has not been referenced");
1998 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2000 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2001 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2002 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2003 flags |= Flags.HasRet;
2005 if (ok && (errors == Report.Errors)) {
2006 if (RootContext.WarningLevel >= 3)
2007 UsageWarning (vector);
2013 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2015 unreachable_shown = true;
2016 return base.ResolveUnreachable (ec, warn);
2019 protected override void DoEmit (EmitContext ec)
2021 for (int ix = 0; ix < num_statements; ix++){
2022 Statement s = (Statement) statements [ix];
2024 // Check whether we are the last statement in a
2027 if ((Parent == null) && (ix+1 == num_statements))
2028 ec.IsLastStatement = true;
2030 ec.IsLastStatement = false;
2036 public override void Emit (EmitContext ec)
2038 Block prev_block = ec.CurrentBlock;
2040 ec.CurrentBlock = this;
2042 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2043 bool is_lexical_block = !Implicit && (Parent != null);
2045 if (emit_debug_info) {
2046 if (is_lexical_block)
2047 ec.ig.BeginScope ();
2049 if (variables != null) {
2050 foreach (DictionaryEntry de in variables) {
2051 string name = (string) de.Key;
2052 LocalInfo vi = (LocalInfo) de.Value;
2054 if (vi.LocalBuilder == null)
2057 ec.DefineLocalVariable (name, vi.LocalBuilder);
2062 ec.Mark (StartLocation, true);
2064 ec.Mark (EndLocation, true);
2066 if (emit_debug_info && is_lexical_block)
2069 ec.CurrentBlock = prev_block;
2072 public ToplevelBlock Toplevel {
2075 while (b.Parent != null){
2076 if ((b.flags & Flags.IsToplevel) != 0)
2081 return (ToplevelBlock) b;
2086 // Returns true if we ar ea child of `b'.
2088 public bool IsChildOf (Block b)
2090 Block current = this;
2093 if (current.Parent == b)
2095 current = current.Parent;
2096 } while (current != null);
2102 // A toplevel block contains extra information, the split is done
2103 // only to separate information that would otherwise bloat the more
2104 // lightweight Block.
2106 // In particular, this was introduced when the support for Anonymous
2107 // Methods was implemented.
2109 public class ToplevelBlock : Block {
2111 // Pointer to the host of this anonymous method, or null
2112 // if we are the topmost block
2114 public ToplevelBlock Container;
2115 CaptureContext capture_context;
2117 Hashtable capture_contexts;
2122 public void RegisterCaptureContext (CaptureContext cc)
2124 if (capture_contexts == null)
2125 capture_contexts = new Hashtable ();
2126 capture_contexts [cc] = cc;
2129 public void CompleteContexts ()
2131 if (capture_contexts == null)
2134 foreach (CaptureContext cc in capture_contexts.Keys){
2139 public CaptureContext ToplevelBlockCaptureContext {
2141 return capture_context;
2146 // Parent is only used by anonymous blocks to link back to their
2149 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2150 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2152 Container = container;
2155 public ToplevelBlock (Parameters parameters, Location start) :
2156 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2160 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2161 base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2165 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2169 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2171 if (capture_context == null)
2172 capture_context = new CaptureContext (this, loc, host);
2175 public CaptureContext CaptureContext {
2177 return capture_context;
2182 public class SwitchLabel {
2185 public Location loc;
2189 Label il_label_code;
2190 bool il_label_code_set;
2193 // if expr == null, then it is the default case.
2195 public SwitchLabel (Expression expr, Location l)
2201 public Expression Label {
2207 public object Converted {
2213 public Label GetILLabel (EmitContext ec)
2216 il_label = ec.ig.DefineLabel ();
2217 il_label_set = true;
2222 public Label GetILLabelCode (EmitContext ec)
2224 if (!il_label_code_set){
2225 il_label_code = ec.ig.DefineLabel ();
2226 il_label_code_set = true;
2228 return il_label_code;
2232 // Resolves the expression, reduces it to a literal if possible
2233 // and then converts it to the requested type.
2235 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2240 Expression e = label.Resolve (ec);
2245 if (!(e is Constant)){
2246 Report.Error (150, loc, "A constant value is expected, got: " + e);
2250 if (e is StringConstant || e is NullLiteral){
2251 if (required_type == TypeManager.string_type){
2257 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2258 if (converted == null)
2265 public class SwitchSection {
2266 // An array of SwitchLabels.
2267 public readonly ArrayList Labels;
2268 public readonly Block Block;
2270 public SwitchSection (ArrayList labels, Block block)
2277 public class Switch : Statement {
2278 public readonly ArrayList Sections;
2279 public Expression Expr;
2282 /// Maps constants whose type type SwitchType to their SwitchLabels.
2284 public Hashtable Elements;
2287 /// The governing switch type
2289 public Type SwitchType;
2295 Label default_target;
2296 Expression new_expr;
2298 SwitchSection constant_section;
2301 // The types allowed to be implicitly cast from
2302 // on the governing type
2304 static Type [] allowed_types;
2306 public Switch (Expression e, ArrayList sects, Location l)
2313 public bool GotDefault {
2319 public Label DefaultTarget {
2321 return default_target;
2326 // Determines the governing type for a switch. The returned
2327 // expression might be the expression from the switch, or an
2328 // expression that includes any potential conversions to the
2329 // integral types or to string.
2331 Expression SwitchGoverningType (EmitContext ec, Type t)
2333 if (t == TypeManager.int32_type ||
2334 t == TypeManager.uint32_type ||
2335 t == TypeManager.char_type ||
2336 t == TypeManager.byte_type ||
2337 t == TypeManager.sbyte_type ||
2338 t == TypeManager.ushort_type ||
2339 t == TypeManager.short_type ||
2340 t == TypeManager.uint64_type ||
2341 t == TypeManager.int64_type ||
2342 t == TypeManager.string_type ||
2343 t == TypeManager.bool_type ||
2344 t.IsSubclassOf (TypeManager.enum_type))
2347 if (allowed_types == null){
2348 allowed_types = new Type [] {
2349 TypeManager.int32_type,
2350 TypeManager.uint32_type,
2351 TypeManager.sbyte_type,
2352 TypeManager.byte_type,
2353 TypeManager.short_type,
2354 TypeManager.ushort_type,
2355 TypeManager.int64_type,
2356 TypeManager.uint64_type,
2357 TypeManager.char_type,
2358 TypeManager.bool_type,
2359 TypeManager.string_type
2364 // Try to find a *user* defined implicit conversion.
2366 // If there is no implicit conversion, or if there are multiple
2367 // conversions, we have to report an error
2369 Expression converted = null;
2370 foreach (Type tt in allowed_types){
2373 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2378 // Ignore over-worked ImplicitUserConversions that do
2379 // an implicit conversion in addition to the user conversion.
2382 UserCast ue = e as UserCast;
2384 if (ue.Source != Expr)
2388 if (converted != null){
2389 Report.ExtraInformation (
2391 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2392 TypeManager.CSharpName (Expr.Type)));
2401 static string Error152 {
2403 return "The label '{0}:' already occurs in this switch statement";
2408 // Performs the basic sanity checks on the switch statement
2409 // (looks for duplicate keys and non-constant expressions).
2411 // It also returns a hashtable with the keys that we will later
2412 // use to compute the switch tables
2414 bool CheckSwitch (EmitContext ec)
2418 Elements = new Hashtable ();
2420 got_default = false;
2422 if (TypeManager.IsEnumType (SwitchType)){
2423 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2425 compare_type = SwitchType;
2427 foreach (SwitchSection ss in Sections){
2428 foreach (SwitchLabel sl in ss.Labels){
2429 if (!sl.ResolveAndReduce (ec, SwitchType)){
2434 if (sl.Label == null){
2436 Report.Error (152, sl.loc, Error152, "default");
2443 object key = sl.Converted;
2445 if (key is Constant)
2446 key = ((Constant) key).GetValue ();
2449 key = NullLiteral.Null;
2451 string lname = null;
2452 if (compare_type == TypeManager.uint64_type){
2453 ulong v = (ulong) key;
2455 if (Elements.Contains (v))
2456 lname = v.ToString ();
2458 Elements.Add (v, sl);
2459 } else if (compare_type == TypeManager.int64_type){
2460 long v = (long) key;
2462 if (Elements.Contains (v))
2463 lname = v.ToString ();
2465 Elements.Add (v, sl);
2466 } else if (compare_type == TypeManager.uint32_type){
2467 uint v = (uint) key;
2469 if (Elements.Contains (v))
2470 lname = v.ToString ();
2472 Elements.Add (v, sl);
2473 } else if (compare_type == TypeManager.char_type){
2474 char v = (char) key;
2476 if (Elements.Contains (v))
2477 lname = v.ToString ();
2479 Elements.Add (v, sl);
2480 } else if (compare_type == TypeManager.byte_type){
2481 byte v = (byte) key;
2483 if (Elements.Contains (v))
2484 lname = v.ToString ();
2486 Elements.Add (v, sl);
2487 } else if (compare_type == TypeManager.sbyte_type){
2488 sbyte v = (sbyte) key;
2490 if (Elements.Contains (v))
2491 lname = v.ToString ();
2493 Elements.Add (v, sl);
2494 } else if (compare_type == TypeManager.short_type){
2495 short v = (short) key;
2497 if (Elements.Contains (v))
2498 lname = v.ToString ();
2500 Elements.Add (v, sl);
2501 } else if (compare_type == TypeManager.ushort_type){
2502 ushort v = (ushort) key;
2504 if (Elements.Contains (v))
2505 lname = v.ToString ();
2507 Elements.Add (v, sl);
2508 } else if (compare_type == TypeManager.string_type){
2509 if (key is NullLiteral){
2510 if (Elements.Contains (NullLiteral.Null))
2513 Elements.Add (NullLiteral.Null, null);
2515 string s = (string) key;
2517 if (Elements.Contains (s))
2520 Elements.Add (s, sl);
2522 } else if (compare_type == TypeManager.int32_type) {
2525 if (Elements.Contains (v))
2526 lname = v.ToString ();
2528 Elements.Add (v, sl);
2529 } else if (compare_type == TypeManager.bool_type) {
2530 bool v = (bool) key;
2532 if (Elements.Contains (v))
2533 lname = v.ToString ();
2535 Elements.Add (v, sl);
2539 throw new Exception ("Unknown switch type!" +
2540 SwitchType + " " + compare_type);
2543 if (lname != null) {
2544 Report.Error (152, sl.loc, Error152, "case " + lname);
2555 void EmitObjectInteger (ILGenerator ig, object k)
2558 IntConstant.EmitInt (ig, (int) k);
2559 else if (k is Constant) {
2560 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2563 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2566 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2568 IntConstant.EmitInt (ig, (int) (long) k);
2569 ig.Emit (OpCodes.Conv_I8);
2572 LongConstant.EmitLong (ig, (long) k);
2574 else if (k is ulong)
2576 if ((ulong) k < (1L<<32))
2578 IntConstant.EmitInt (ig, (int) (long) k);
2579 ig.Emit (OpCodes.Conv_U8);
2583 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2587 IntConstant.EmitInt (ig, (int) ((char) k));
2588 else if (k is sbyte)
2589 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2591 IntConstant.EmitInt (ig, (int) ((byte) k));
2592 else if (k is short)
2593 IntConstant.EmitInt (ig, (int) ((short) k));
2594 else if (k is ushort)
2595 IntConstant.EmitInt (ig, (int) ((ushort) k));
2597 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2599 throw new Exception ("Unhandled case");
2602 // structure used to hold blocks of keys while calculating table switch
2603 class KeyBlock : IComparable
2605 public KeyBlock (long _nFirst)
2607 nFirst = nLast = _nFirst;
2611 public ArrayList rgKeys = null;
2612 // how many items are in the bucket
2613 public int Size = 1;
2616 get { return (int) (nLast - nFirst + 1); }
2618 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2620 return kbLast.nLast - kbFirst.nFirst + 1;
2622 public int CompareTo (object obj)
2624 KeyBlock kb = (KeyBlock) obj;
2625 int nLength = Length;
2626 int nLengthOther = kb.Length;
2627 if (nLengthOther == nLength)
2628 return (int) (kb.nFirst - nFirst);
2629 return nLength - nLengthOther;
2634 /// This method emits code for a lookup-based switch statement (non-string)
2635 /// Basically it groups the cases into blocks that are at least half full,
2636 /// and then spits out individual lookup opcodes for each block.
2637 /// It emits the longest blocks first, and short blocks are just
2638 /// handled with direct compares.
2640 /// <param name="ec"></param>
2641 /// <param name="val"></param>
2642 /// <returns></returns>
2643 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2645 int cElements = Elements.Count;
2646 object [] rgKeys = new object [cElements];
2647 Elements.Keys.CopyTo (rgKeys, 0);
2648 Array.Sort (rgKeys);
2650 // initialize the block list with one element per key
2651 ArrayList rgKeyBlocks = new ArrayList ();
2652 foreach (object key in rgKeys)
2653 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2656 // iteratively merge the blocks while they are at least half full
2657 // there's probably a really cool way to do this with a tree...
2658 while (rgKeyBlocks.Count > 1)
2660 ArrayList rgKeyBlocksNew = new ArrayList ();
2661 kbCurr = (KeyBlock) rgKeyBlocks [0];
2662 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2664 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2665 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2668 kbCurr.nLast = kb.nLast;
2669 kbCurr.Size += kb.Size;
2673 // start a new block
2674 rgKeyBlocksNew.Add (kbCurr);
2678 rgKeyBlocksNew.Add (kbCurr);
2679 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2681 rgKeyBlocks = rgKeyBlocksNew;
2684 // initialize the key lists
2685 foreach (KeyBlock kb in rgKeyBlocks)
2686 kb.rgKeys = new ArrayList ();
2688 // fill the key lists
2690 if (rgKeyBlocks.Count > 0) {
2691 kbCurr = (KeyBlock) rgKeyBlocks [0];
2692 foreach (object key in rgKeys)
2694 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2695 System.Convert.ToInt64 (key) > kbCurr.nLast;
2697 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2698 kbCurr.rgKeys.Add (key);
2702 // sort the blocks so we can tackle the largest ones first
2703 rgKeyBlocks.Sort ();
2705 // okay now we can start...
2706 ILGenerator ig = ec.ig;
2707 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2708 Label lblDefault = ig.DefineLabel ();
2710 Type typeKeys = null;
2711 if (rgKeys.Length > 0)
2712 typeKeys = rgKeys [0].GetType (); // used for conversions
2716 if (TypeManager.IsEnumType (SwitchType))
2717 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2719 compare_type = SwitchType;
2721 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2723 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2724 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2727 foreach (object key in kb.rgKeys)
2729 ig.Emit (OpCodes.Ldloc, val);
2730 EmitObjectInteger (ig, key);
2731 SwitchLabel sl = (SwitchLabel) Elements [key];
2732 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2737 // TODO: if all the keys in the block are the same and there are
2738 // no gaps/defaults then just use a range-check.
2739 if (compare_type == TypeManager.int64_type ||
2740 compare_type == TypeManager.uint64_type)
2742 // TODO: optimize constant/I4 cases
2744 // check block range (could be > 2^31)
2745 ig.Emit (OpCodes.Ldloc, val);
2746 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2747 ig.Emit (OpCodes.Blt, lblDefault);
2748 ig.Emit (OpCodes.Ldloc, val);
2749 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2750 ig.Emit (OpCodes.Bgt, lblDefault);
2753 ig.Emit (OpCodes.Ldloc, val);
2756 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2757 ig.Emit (OpCodes.Sub);
2759 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2764 ig.Emit (OpCodes.Ldloc, val);
2765 int nFirst = (int) kb.nFirst;
2768 IntConstant.EmitInt (ig, nFirst);
2769 ig.Emit (OpCodes.Sub);
2771 else if (nFirst < 0)
2773 IntConstant.EmitInt (ig, -nFirst);
2774 ig.Emit (OpCodes.Add);
2778 // first, build the list of labels for the switch
2780 int cJumps = kb.Length;
2781 Label [] rgLabels = new Label [cJumps];
2782 for (int iJump = 0; iJump < cJumps; iJump++)
2784 object key = kb.rgKeys [iKey];
2785 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2787 SwitchLabel sl = (SwitchLabel) Elements [key];
2788 rgLabels [iJump] = sl.GetILLabel (ec);
2792 rgLabels [iJump] = lblDefault;
2794 // emit the switch opcode
2795 ig.Emit (OpCodes.Switch, rgLabels);
2798 // mark the default for this block
2800 ig.MarkLabel (lblDefault);
2803 // TODO: find the default case and emit it here,
2804 // to prevent having to do the following jump.
2805 // make sure to mark other labels in the default section
2807 // the last default just goes to the end
2808 ig.Emit (OpCodes.Br, lblDefault);
2810 // now emit the code for the sections
2811 bool fFoundDefault = false;
2812 foreach (SwitchSection ss in Sections)
2814 foreach (SwitchLabel sl in ss.Labels)
2816 ig.MarkLabel (sl.GetILLabel (ec));
2817 ig.MarkLabel (sl.GetILLabelCode (ec));
2818 if (sl.Label == null)
2820 ig.MarkLabel (lblDefault);
2821 fFoundDefault = true;
2825 //ig.Emit (OpCodes.Br, lblEnd);
2828 if (!fFoundDefault) {
2829 ig.MarkLabel (lblDefault);
2831 ig.MarkLabel (lblEnd);
2834 // This simple emit switch works, but does not take advantage of the
2836 // TODO: remove non-string logic from here
2837 // TODO: binary search strings?
2839 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2841 ILGenerator ig = ec.ig;
2842 Label end_of_switch = ig.DefineLabel ();
2843 Label next_test = ig.DefineLabel ();
2844 Label null_target = ig.DefineLabel ();
2845 bool default_found = false;
2846 bool first_test = true;
2847 bool pending_goto_end = false;
2849 bool default_at_end = false;
2851 ig.Emit (OpCodes.Ldloc, val);
2853 if (Elements.Contains (NullLiteral.Null)){
2854 ig.Emit (OpCodes.Brfalse, null_target);
2856 ig.Emit (OpCodes.Brfalse, default_target);
2858 ig.Emit (OpCodes.Ldloc, val);
2859 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2860 ig.Emit (OpCodes.Stloc, val);
2862 int section_count = Sections.Count;
2863 for (int section = 0; section < section_count; section++){
2864 SwitchSection ss = (SwitchSection) Sections [section];
2865 Label sec_begin = ig.DefineLabel ();
2867 if (pending_goto_end)
2868 ig.Emit (OpCodes.Br, end_of_switch);
2870 int label_count = ss.Labels.Count;
2871 bool mark_default = false;
2873 for (int label = 0; label < label_count; label++){
2874 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2875 ig.MarkLabel (sl.GetILLabel (ec));
2878 ig.MarkLabel (next_test);
2879 next_test = ig.DefineLabel ();
2882 // If we are the default target
2884 if (sl.Label == null){
2885 if (label+1 == label_count)
2886 default_at_end = true;
2887 mark_default = true;
2888 default_found = true;
2890 object lit = sl.Converted;
2892 if (lit is NullLiteral){
2894 if (label_count == 1)
2895 ig.Emit (OpCodes.Br, next_test);
2899 StringConstant str = (StringConstant) lit;
2901 ig.Emit (OpCodes.Ldloc, val);
2902 ig.Emit (OpCodes.Ldstr, str.Value);
2903 if (label_count == 1)
2904 ig.Emit (OpCodes.Bne_Un, next_test);
2906 if (label+1 == label_count)
2907 ig.Emit (OpCodes.Bne_Un, next_test);
2909 ig.Emit (OpCodes.Beq, sec_begin);
2914 ig.MarkLabel (null_target);
2915 ig.MarkLabel (sec_begin);
2916 foreach (SwitchLabel sl in ss.Labels)
2917 ig.MarkLabel (sl.GetILLabelCode (ec));
2920 ig.MarkLabel (default_target);
2922 pending_goto_end = !ss.Block.HasRet;
2925 ig.MarkLabel (next_test);
2927 if (!default_at_end)
2928 ig.Emit (OpCodes.Br, default_target);
2930 ig.MarkLabel (default_target);
2931 ig.MarkLabel (end_of_switch);
2934 SwitchSection FindSection (SwitchLabel label)
2936 foreach (SwitchSection ss in Sections){
2937 foreach (SwitchLabel sl in ss.Labels){
2946 bool ResolveConstantSwitch (EmitContext ec)
2948 object key = ((Constant) new_expr).GetValue ();
2949 SwitchLabel label = (SwitchLabel) Elements [key];
2954 constant_section = FindSection (label);
2955 if (constant_section == null)
2958 if (constant_section.Block.Resolve (ec) != true)
2964 public override bool Resolve (EmitContext ec)
2966 Expr = Expr.Resolve (ec);
2970 new_expr = SwitchGoverningType (ec, Expr.Type);
2971 if (new_expr == null){
2972 Report.Error (151, loc, "An integer type or string was expected for switch");
2977 SwitchType = new_expr.Type;
2979 if (!CheckSwitch (ec))
2982 Switch old_switch = ec.Switch;
2984 ec.Switch.SwitchType = SwitchType;
2986 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2987 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2989 is_constant = new_expr is Constant;
2991 object key = ((Constant) new_expr).GetValue ();
2992 SwitchLabel label = (SwitchLabel) Elements [key];
2994 constant_section = FindSection (label);
2998 foreach (SwitchSection ss in Sections){
3000 ec.CurrentBranching.CreateSibling (
3001 null, FlowBranching.SiblingType.SwitchSection);
3005 if (is_constant && (ss != constant_section)) {
3006 // If we're a constant switch, we're only emitting
3007 // one single section - mark all the others as
3009 ec.CurrentBranching.CurrentUsageVector.Goto ();
3010 if (!ss.Block.ResolveUnreachable (ec, true))
3013 if (!ss.Block.Resolve (ec))
3019 ec.CurrentBranching.CreateSibling (
3020 null, FlowBranching.SiblingType.SwitchSection);
3022 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3023 ec.Switch = old_switch;
3025 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3031 protected override void DoEmit (EmitContext ec)
3033 ILGenerator ig = ec.ig;
3035 // Store variable for comparission purposes
3038 value = ig.DeclareLocal (SwitchType);
3040 ig.Emit (OpCodes.Stloc, value);
3044 default_target = ig.DefineLabel ();
3047 // Setup the codegen context
3049 Label old_end = ec.LoopEnd;
3050 Switch old_switch = ec.Switch;
3052 ec.LoopEnd = ig.DefineLabel ();
3057 if (constant_section != null)
3058 constant_section.Block.Emit (ec);
3059 } else if (SwitchType == TypeManager.string_type)
3060 SimpleSwitchEmit (ec, value);
3062 TableSwitchEmit (ec, value);
3064 // Restore context state.
3065 ig.MarkLabel (ec.LoopEnd);
3068 // Restore the previous context
3070 ec.LoopEnd = old_end;
3071 ec.Switch = old_switch;
3075 public abstract class ExceptionStatement : Statement
3077 public abstract void EmitFinally (EmitContext ec);
3079 protected bool emit_finally = true;
3080 ArrayList parent_vectors;
3082 protected void DoEmitFinally (EmitContext ec)
3085 ec.ig.BeginFinallyBlock ();
3087 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3091 protected void ResolveFinally (FlowBranchingException branching)
3093 emit_finally = branching.EmitFinally;
3095 branching.Parent.StealFinallyClauses (ref parent_vectors);
3099 public class Lock : ExceptionStatement {
3101 Statement Statement;
3104 public Lock (Expression expr, Statement stmt, Location l)
3111 public override bool Resolve (EmitContext ec)
3113 expr = expr.Resolve (ec);
3117 if (expr.Type.IsValueType){
3118 Error (185, "lock statement requires the expression to be " +
3119 " a reference type (type is: `{0}'",
3120 TypeManager.CSharpName (expr.Type));
3124 FlowBranchingException branching = ec.StartFlowBranching (this);
3125 bool ok = Statement.Resolve (ec);
3127 ec.KillFlowBranching ();
3131 ResolveFinally (branching);
3133 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3134 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3135 // Unfortunately, System.Reflection.Emit automatically emits
3136 // a leave to the end of the finally block.
3137 // This is a problem if `returns' is true since we may jump
3138 // to a point after the end of the method.
3139 // As a workaround, emit an explicit ret here.
3140 ec.NeedReturnLabel ();
3146 protected override void DoEmit (EmitContext ec)
3148 Type type = expr.Type;
3150 ILGenerator ig = ec.ig;
3151 temp = ig.DeclareLocal (type);
3154 ig.Emit (OpCodes.Dup);
3155 ig.Emit (OpCodes.Stloc, temp);
3156 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3160 ig.BeginExceptionBlock ();
3161 Statement.Emit (ec);
3166 ig.EndExceptionBlock ();
3169 public override void EmitFinally (EmitContext ec)
3171 ILGenerator ig = ec.ig;
3172 ig.Emit (OpCodes.Ldloc, temp);
3173 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3177 public class Unchecked : Statement {
3178 public readonly Block Block;
3180 public Unchecked (Block b)
3186 public override bool Resolve (EmitContext ec)
3188 bool previous_state = ec.CheckState;
3189 bool previous_state_const = ec.ConstantCheckState;
3191 ec.CheckState = false;
3192 ec.ConstantCheckState = false;
3193 bool ret = Block.Resolve (ec);
3194 ec.CheckState = previous_state;
3195 ec.ConstantCheckState = previous_state_const;
3200 protected override void DoEmit (EmitContext ec)
3202 bool previous_state = ec.CheckState;
3203 bool previous_state_const = ec.ConstantCheckState;
3205 ec.CheckState = false;
3206 ec.ConstantCheckState = false;
3208 ec.CheckState = previous_state;
3209 ec.ConstantCheckState = previous_state_const;
3213 public class Checked : Statement {
3214 public readonly Block Block;
3216 public Checked (Block b)
3219 b.Unchecked = false;
3222 public override bool Resolve (EmitContext ec)
3224 bool previous_state = ec.CheckState;
3225 bool previous_state_const = ec.ConstantCheckState;
3227 ec.CheckState = true;
3228 ec.ConstantCheckState = true;
3229 bool ret = Block.Resolve (ec);
3230 ec.CheckState = previous_state;
3231 ec.ConstantCheckState = previous_state_const;
3236 protected override void DoEmit (EmitContext ec)
3238 bool previous_state = ec.CheckState;
3239 bool previous_state_const = ec.ConstantCheckState;
3241 ec.CheckState = true;
3242 ec.ConstantCheckState = true;
3244 ec.CheckState = previous_state;
3245 ec.ConstantCheckState = previous_state_const;
3249 public class Unsafe : Statement {
3250 public readonly Block Block;
3252 public Unsafe (Block b)
3255 Block.Unsafe = true;
3258 public override bool Resolve (EmitContext ec)
3260 bool previous_state = ec.InUnsafe;
3264 val = Block.Resolve (ec);
3265 ec.InUnsafe = previous_state;
3270 protected override void DoEmit (EmitContext ec)
3272 bool previous_state = ec.InUnsafe;
3276 ec.InUnsafe = previous_state;
3283 public class Fixed : Statement {
3285 ArrayList declarators;
3286 Statement statement;
3292 public bool is_object;
3293 public LocalInfo vi;
3294 public Expression expr;
3295 public Expression converted;
3298 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3301 declarators = decls;
3306 public override bool Resolve (EmitContext ec)
3309 Expression.UnsafeError (loc);
3313 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3317 expr_type = texpr.ResolveType (ec);
3319 CheckObsolete (expr_type);
3321 if (ec.RemapToProxy){
3322 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3326 data = new FixedData [declarators.Count];
3328 if (!expr_type.IsPointer){
3329 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3334 foreach (Pair p in declarators){
3335 LocalInfo vi = (LocalInfo) p.First;
3336 Expression e = (Expression) p.Second;
3338 vi.VariableInfo.SetAssigned (ec);
3342 // The rules for the possible declarators are pretty wise,
3343 // but the production on the grammar is more concise.
3345 // So we have to enforce these rules here.
3347 // We do not resolve before doing the case 1 test,
3348 // because the grammar is explicit in that the token &
3349 // is present, so we need to test for this particular case.
3353 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3358 // Case 1: & object.
3360 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3361 Expression child = ((Unary) e).Expr;
3363 if (child is ParameterReference || child is LocalVariableReference){
3366 "No need to use fixed statement for parameters or " +
3367 "local variable declarations (address is already " +
3372 ec.InFixedInitializer = true;
3374 ec.InFixedInitializer = false;
3378 child = ((Unary) e).Expr;
3380 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3383 data [i].is_object = true;
3385 data [i].converted = null;
3392 ec.InFixedInitializer = true;
3394 ec.InFixedInitializer = false;
3401 if (e.Type.IsArray){
3402 Type array_type = TypeManager.GetElementType (e.Type);
3405 // Provided that array_type is unmanaged,
3407 if (!TypeManager.VerifyUnManaged (array_type, loc))
3411 // and T* is implicitly convertible to the
3412 // pointer type given in the fixed statement.
3414 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3416 Expression converted = Convert.ImplicitConversionRequired (
3417 ec, array_ptr, vi.VariableType, loc);
3418 if (converted == null)
3421 data [i].is_object = false;
3423 data [i].converted = converted;
3433 if (e.Type == TypeManager.string_type){
3434 data [i].is_object = false;
3436 data [i].converted = null;
3443 // For other cases, flag a `this is already fixed expression'
3445 if (e is LocalVariableReference || e is ParameterReference ||
3446 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3448 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3452 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3456 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3458 if (!statement.Resolve (ec)) {
3459 ec.KillFlowBranching ();
3463 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3464 has_ret = reachability.IsUnreachable;
3469 protected override void DoEmit (EmitContext ec)
3471 ILGenerator ig = ec.ig;
3473 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3475 for (int i = 0; i < data.Length; i++) {
3476 LocalInfo vi = data [i].vi;
3479 // Case 1: & object.
3481 if (data [i].is_object) {
3483 // Store pointer in pinned location
3485 data [i].expr.Emit (ec);
3486 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3487 clear_list [i] = vi.LocalBuilder;
3494 if (data [i].expr.Type.IsArray){
3496 // Store pointer in pinned location
3498 data [i].converted.Emit (ec);
3500 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3501 clear_list [i] = vi.LocalBuilder;
3508 if (data [i].expr.Type == TypeManager.string_type){
3509 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3510 clear_list [i] = pinned_string;
3512 data [i].expr.Emit (ec);
3513 ig.Emit (OpCodes.Stloc, pinned_string);
3515 Expression sptr = new StringPtr (pinned_string, loc);
3516 Expression converted = Convert.ImplicitConversionRequired (
3517 ec, sptr, vi.VariableType, loc);
3519 if (converted == null)
3522 converted.Emit (ec);
3523 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3527 statement.Emit (ec);
3533 // Clear the pinned variable
3535 for (int i = 0; i < data.Length; i++) {
3536 if (data [i].is_object || data [i].expr.Type.IsArray) {
3537 ig.Emit (OpCodes.Ldc_I4_0);
3538 ig.Emit (OpCodes.Conv_U);
3539 ig.Emit (OpCodes.Stloc, clear_list [i]);
3540 } else if (data [i].expr.Type == TypeManager.string_type){
3541 ig.Emit (OpCodes.Ldnull);
3542 ig.Emit (OpCodes.Stloc, clear_list [i]);
3548 public class Catch: Statement {
3549 public readonly string Name;
3550 public readonly Block Block;
3552 Expression type_expr;
3555 public Catch (Expression type, string name, Block block, Location l)
3563 public Type CatchType {
3569 public bool IsGeneral {
3571 return type_expr == null;
3575 protected override void DoEmit(EmitContext ec)
3579 public override bool Resolve (EmitContext ec)
3581 if (type_expr != null) {
3582 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3586 type = te.ResolveType (ec);
3588 CheckObsolete (type);
3590 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3591 Error (155, "The type caught or thrown must be derived from System.Exception");
3597 return Block.Resolve (ec);
3601 public class Try : ExceptionStatement {
3602 public readonly Block Fini, Block;
3603 public readonly ArrayList Specific;
3604 public readonly Catch General;
3606 bool need_exc_block;
3609 // specific, general and fini might all be null.
3611 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3613 if (specific == null && general == null){
3614 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3618 this.Specific = specific;
3619 this.General = general;
3624 public override bool Resolve (EmitContext ec)
3628 FlowBranchingException branching = ec.StartFlowBranching (this);
3630 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3632 if (!Block.Resolve (ec))
3635 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3637 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3639 Type[] prevCatches = new Type [Specific.Count];
3641 foreach (Catch c in Specific){
3642 ec.CurrentBranching.CreateSibling (
3643 c.Block, FlowBranching.SiblingType.Catch);
3645 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3647 if (c.Name != null) {
3648 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3650 throw new Exception ();
3652 vi.VariableInfo = null;
3655 if (!c.Resolve (ec))
3658 Type resolvedType = c.CatchType;
3659 for (int ii = 0; ii < last_index; ++ii) {
3660 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3661 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3666 prevCatches [last_index++] = resolvedType;
3667 need_exc_block = true;
3670 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3672 if (General != null){
3673 ec.CurrentBranching.CreateSibling (
3674 General.Block, FlowBranching.SiblingType.Catch);
3676 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3678 if (!General.Resolve (ec))
3681 need_exc_block = true;
3684 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3688 ec.CurrentBranching.CreateSibling (
3689 Fini, FlowBranching.SiblingType.Finally);
3691 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3693 if (!Fini.Resolve (ec))
3697 ResolveFinally (branching);
3698 need_exc_block |= emit_finally;
3700 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3702 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3704 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3706 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3707 // Unfortunately, System.Reflection.Emit automatically emits
3708 // a leave to the end of the finally block. This is a problem
3709 // if `returns' is true since we may jump to a point after the
3710 // end of the method.
3711 // As a workaround, emit an explicit ret here.
3712 ec.NeedReturnLabel ();
3718 protected override void DoEmit (EmitContext ec)
3720 ILGenerator ig = ec.ig;
3723 ig.BeginExceptionBlock ();
3726 foreach (Catch c in Specific){
3729 ig.BeginCatchBlock (c.CatchType);
3731 if (c.Name != null){
3732 vi = c.Block.GetLocalInfo (c.Name);
3734 throw new Exception ("Variable does not exist in this block");
3736 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3738 ig.Emit (OpCodes.Pop);
3743 if (General != null){
3744 ig.BeginCatchBlock (TypeManager.object_type);
3745 ig.Emit (OpCodes.Pop);
3746 General.Block.Emit (ec);
3751 ig.EndExceptionBlock ();
3754 public override void EmitFinally (EmitContext ec)
3762 public class Using : ExceptionStatement {
3763 object expression_or_block;
3764 Statement Statement;
3769 Expression [] resolved_vars;
3770 Expression [] converted_vars;
3771 ExpressionStatement [] assign;
3772 LocalBuilder local_copy;
3774 public Using (object expression_or_block, Statement stmt, Location l)
3776 this.expression_or_block = expression_or_block;
3782 // Resolves for the case of using using a local variable declaration.
3784 bool ResolveLocalVariableDecls (EmitContext ec)
3788 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3792 expr_type = texpr.ResolveType (ec);
3795 // The type must be an IDisposable or an implicit conversion
3798 converted_vars = new Expression [var_list.Count];
3799 resolved_vars = new Expression [var_list.Count];
3800 assign = new ExpressionStatement [var_list.Count];
3802 bool need_conv = !TypeManager.ImplementsInterface (
3803 expr_type, TypeManager.idisposable_type);
3805 foreach (DictionaryEntry e in var_list){
3806 Expression var = (Expression) e.Key;
3808 var = var.ResolveLValue (ec, new EmptyExpression ());
3812 resolved_vars [i] = var;
3819 converted_vars [i] = Convert.ImplicitConversionRequired (
3820 ec, var, TypeManager.idisposable_type, loc);
3822 if (converted_vars [i] == null)
3829 foreach (DictionaryEntry e in var_list){
3830 Expression var = resolved_vars [i];
3831 Expression new_expr = (Expression) e.Value;
3834 a = new Assign (var, new_expr, loc);
3840 converted_vars [i] = var;
3841 assign [i] = (ExpressionStatement) a;
3848 bool ResolveExpression (EmitContext ec)
3850 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3851 conv = Convert.ImplicitConversionRequired (
3852 ec, expr, TypeManager.idisposable_type, loc);
3862 // Emits the code for the case of using using a local variable declaration.
3864 void EmitLocalVariableDecls (EmitContext ec)
3866 ILGenerator ig = ec.ig;
3869 for (i = 0; i < assign.Length; i++) {
3870 assign [i].EmitStatement (ec);
3873 ig.BeginExceptionBlock ();
3875 Statement.Emit (ec);
3876 var_list.Reverse ();
3881 void EmitLocalVariableDeclFinally (EmitContext ec)
3883 ILGenerator ig = ec.ig;
3885 int i = assign.Length;
3886 for (int ii = 0; ii < var_list.Count; ++ii){
3887 Expression var = resolved_vars [--i];
3888 Label skip = ig.DefineLabel ();
3890 if (!var.Type.IsValueType) {
3892 ig.Emit (OpCodes.Brfalse, skip);
3893 converted_vars [i].Emit (ec);
3894 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3896 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3898 if (!(ml is MethodGroupExpr)) {
3900 ig.Emit (OpCodes.Box, var.Type);
3901 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3903 MethodInfo mi = null;
3905 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3906 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3913 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3917 IMemoryLocation mloc = (IMemoryLocation) var;
3919 mloc.AddressOf (ec, AddressOp.Load);
3920 ig.Emit (OpCodes.Call, mi);
3924 ig.MarkLabel (skip);
3927 ig.EndExceptionBlock ();
3929 ig.BeginFinallyBlock ();
3934 void EmitExpression (EmitContext ec)
3937 // Make a copy of the expression and operate on that.
3939 ILGenerator ig = ec.ig;
3940 local_copy = ig.DeclareLocal (expr_type);
3945 ig.Emit (OpCodes.Stloc, local_copy);
3948 ig.BeginExceptionBlock ();
3950 Statement.Emit (ec);
3954 ig.EndExceptionBlock ();
3957 void EmitExpressionFinally (EmitContext ec)
3959 ILGenerator ig = ec.ig;
3960 if (!local_copy.LocalType.IsValueType) {
3961 Label skip = ig.DefineLabel ();
3962 ig.Emit (OpCodes.Ldloc, local_copy);
3963 ig.Emit (OpCodes.Brfalse, skip);
3964 ig.Emit (OpCodes.Ldloc, local_copy);
3965 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3966 ig.MarkLabel (skip);
3968 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
3970 if (!(ml is MethodGroupExpr)) {
3971 ig.Emit (OpCodes.Ldloc, local_copy);
3972 ig.Emit (OpCodes.Box, local_copy.LocalType);
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 ig.Emit (OpCodes.Ldloca, local_copy);
3990 ig.Emit (OpCodes.Call, mi);
3995 public override bool Resolve (EmitContext ec)
3997 if (expression_or_block is DictionaryEntry){
3998 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3999 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4001 if (!ResolveLocalVariableDecls (ec))
4004 } else if (expression_or_block is Expression){
4005 expr = (Expression) expression_or_block;
4007 expr = expr.Resolve (ec);
4011 expr_type = expr.Type;
4013 if (!ResolveExpression (ec))
4017 FlowBranchingException branching = ec.StartFlowBranching (this);
4019 bool ok = Statement.Resolve (ec);
4022 ec.KillFlowBranching ();
4026 ResolveFinally (branching);
4027 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4029 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4030 // Unfortunately, System.Reflection.Emit automatically emits a leave
4031 // to the end of the finally block. This is a problem if `returns'
4032 // is true since we may jump to a point after the end of the method.
4033 // As a workaround, emit an explicit ret here.
4034 ec.NeedReturnLabel ();
4040 protected override void DoEmit (EmitContext ec)
4042 if (expression_or_block is DictionaryEntry)
4043 EmitLocalVariableDecls (ec);
4044 else if (expression_or_block is Expression)
4045 EmitExpression (ec);
4048 public override void EmitFinally (EmitContext ec)
4050 if (expression_or_block is DictionaryEntry)
4051 EmitLocalVariableDeclFinally (ec);
4052 else if (expression_or_block is Expression)
4053 EmitExpressionFinally (ec);
4058 /// Implementation of the foreach C# statement
4060 public class Foreach : ExceptionStatement {
4062 Expression variable;
4064 Statement statement;
4065 ForeachHelperMethods hm;
4066 Expression empty, conv;
4067 Type array_type, element_type;
4069 VariableStorage enumerator;
4071 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4072 Statement stmt, Location l)
4075 this.variable = var;
4081 public override bool Resolve (EmitContext ec)
4083 expr = expr.Resolve (ec);
4087 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4091 var_type = texpr.ResolveType (ec);
4094 // We need an instance variable. Not sure this is the best
4095 // way of doing this.
4097 // FIXME: When we implement propertyaccess, will those turn
4098 // out to return values in ExprClass? I think they should.
4100 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4101 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4102 error1579 (expr.Type);
4106 if (expr.Type.IsArray) {
4107 array_type = expr.Type;
4108 element_type = TypeManager.GetElementType (array_type);
4110 empty = new EmptyExpression (element_type);
4112 hm = ProbeCollectionType (ec, expr.Type);
4114 error1579 (expr.Type);
4118 // When ProbeCollection reported error
4119 if (hm.move_next == null)
4122 array_type = expr.Type;
4123 element_type = hm.element_type;
4125 empty = new EmptyExpression (hm.element_type);
4130 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4131 ec.CurrentBranching.CreateSibling ();
4135 // FIXME: maybe we can apply the same trick we do in the
4136 // array handling to avoid creating empty and conv in some cases.
4138 // Although it is not as important in this case, as the type
4139 // will not likely be object (what the enumerator will return).
4141 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4145 variable = variable.ResolveLValue (ec, empty);
4146 if (variable == null)
4149 bool disposable = (hm != null) && hm.is_disposable;
4150 FlowBranchingException branching = null;
4152 branching = ec.StartFlowBranching (this);
4154 if (!statement.Resolve (ec))
4158 ResolveFinally (branching);
4159 ec.EndFlowBranching ();
4161 emit_finally = true;
4163 ec.EndFlowBranching ();
4169 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4171 static MethodInfo FetchMethodMoveNext (Type t)
4173 MemberList move_next_list;
4175 move_next_list = TypeContainer.FindMembers (
4176 t, MemberTypes.Method,
4177 BindingFlags.Public | BindingFlags.Instance,
4178 Type.FilterName, "MoveNext");
4179 if (move_next_list.Count == 0)
4182 foreach (MemberInfo m in move_next_list){
4183 MethodInfo mi = (MethodInfo) m;
4186 args = TypeManager.GetArgumentTypes (mi);
4187 if (args != null && args.Length == 0){
4188 if (mi.ReturnType == TypeManager.bool_type)
4196 // Retrieves a `public T get_Current ()' method from the Type `t'
4198 static MethodInfo FetchMethodGetCurrent (Type t)
4200 MemberList get_current_list;
4202 get_current_list = TypeContainer.FindMembers (
4203 t, MemberTypes.Method,
4204 BindingFlags.Public | BindingFlags.Instance,
4205 Type.FilterName, "get_Current");
4206 if (get_current_list.Count == 0)
4209 foreach (MemberInfo m in get_current_list){
4210 MethodInfo mi = (MethodInfo) m;
4213 args = TypeManager.GetArgumentTypes (mi);
4214 if (args != null && args.Length == 0)
4221 // Retrieves a `public void Dispose ()' method from the Type `t'
4223 static MethodInfo FetchMethodDispose (Type t)
4225 MemberList dispose_list;
4227 dispose_list = TypeContainer.FindMembers (
4228 t, MemberTypes.Method,
4229 BindingFlags.Public | BindingFlags.Instance,
4230 Type.FilterName, "Dispose");
4231 if (dispose_list.Count == 0)
4234 foreach (MemberInfo m in dispose_list){
4235 MethodInfo mi = (MethodInfo) m;
4238 args = TypeManager.GetArgumentTypes (mi);
4239 if (args != null && args.Length == 0){
4240 if (mi.ReturnType == TypeManager.void_type)
4248 // This struct records the helper methods used by the Foreach construct
4250 class ForeachHelperMethods {
4251 public EmitContext ec;
4252 public MethodInfo get_enumerator;
4253 public MethodInfo move_next;
4254 public MethodInfo get_current;
4255 public Type element_type;
4256 public Type enumerator_type;
4257 public bool is_disposable;
4258 public readonly Location Location;
4260 public ForeachHelperMethods (EmitContext ec, Location loc)
4263 this.Location = loc;
4264 this.element_type = TypeManager.object_type;
4265 this.enumerator_type = TypeManager.ienumerator_type;
4266 this.is_disposable = true;
4270 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4275 if (!(m is MethodInfo))
4278 if (m.Name != "GetEnumerator")
4281 MethodInfo mi = (MethodInfo) m;
4282 Type [] args = TypeManager.GetArgumentTypes (mi);
4284 if (args.Length != 0)
4287 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4289 // Check whether GetEnumerator is public
4290 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4293 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4295 // Apply the same optimization as MS: skip the GetEnumerator
4296 // returning an IEnumerator, and use the one returning a
4297 // CharEnumerator instead. This allows us to avoid the
4298 // try-finally block and the boxing.
4303 // Ok, we can access it, now make sure that we can do something
4304 // with this `GetEnumerator'
4307 Type return_type = mi.ReturnType;
4308 if (mi.ReturnType == TypeManager.ienumerator_type ||
4309 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4310 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4313 // If it is not an interface, lets try to find the methods ourselves.
4314 // For example, if we have:
4315 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4316 // We can avoid the iface call. This is a runtime perf boost.
4317 // even bigger if we have a ValueType, because we avoid the cost
4320 // We have to make sure that both methods exist for us to take
4321 // this path. If one of the methods does not exist, we will just
4322 // use the interface. Sadly, this complex if statement is the only
4323 // way I could do this without a goto
4326 if (return_type.IsInterface ||
4327 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4328 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4330 hm.move_next = TypeManager.bool_movenext_void;
4331 hm.get_current = TypeManager.object_getcurrent_void;
4337 if (return_type.IsPointer || return_type.IsArray) {
4338 Report.SymbolRelatedToPreviousError (mi);
4339 Type t = return_type.GetElementType ();
4340 Report.SymbolRelatedToPreviousError (t);
4341 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",
4342 TypeManager.CSharpName (return_type), TypeManager.GetFullNameSignature (m));
4343 hm.get_enumerator = mi;
4348 // Ok, so they dont return an IEnumerable, we will have to
4349 // find if they support the GetEnumerator pattern.
4352 hm.move_next = FetchMethodMoveNext (return_type);
4353 if (hm.move_next == null)
4356 hm.get_current = FetchMethodGetCurrent (return_type);
4357 if (hm.get_current == null)
4361 hm.element_type = hm.get_current.ReturnType;
4362 hm.enumerator_type = return_type;
4363 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4364 TypeManager.ImplementsInterface (
4365 hm.enumerator_type, TypeManager.idisposable_type);
4371 /// This filter is used to find the GetEnumerator method
4372 /// on which IEnumerator operates
4374 static MemberFilter FilterEnumerator;
4378 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4381 void error1579 (Type t)
4383 Report.Error (1579, loc,
4384 "foreach statement cannot operate on variables of type `" +
4385 t.FullName + "' because that class does not provide a " +
4386 " GetEnumerator method or it is inaccessible");
4389 static bool TryType (Type t, ForeachHelperMethods hm)
4393 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4394 BindingFlags.Public | BindingFlags.NonPublic |
4395 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4396 FilterEnumerator, hm);
4401 hm.get_enumerator = (MethodInfo) mi [0];
4406 // Looks for a usable GetEnumerator in the Type, and if found returns
4407 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4409 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4411 ForeachHelperMethods hm = new ForeachHelperMethods (ec, loc);
4413 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4414 if (TryType (tt, hm))
4420 // Now try to find the method in the interfaces
4423 Type [] ifaces = t.GetInterfaces ();
4425 foreach (Type i in ifaces){
4426 if (TryType (i, hm))
4431 // Since TypeBuilder.GetInterfaces only returns the interface
4432 // types for this type, we have to keep looping, but once
4433 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4434 // done, because it returns all the types
4436 if ((t is TypeBuilder))
4446 // FIXME: possible optimization.
4447 // We might be able to avoid creating `empty' if the type is the sam
4449 bool EmitCollectionForeach (EmitContext ec)
4451 ILGenerator ig = ec.ig;
4453 enumerator = new VariableStorage (ec, hm.enumerator_type);
4454 enumerator.EmitThis (ig);
4456 // Instantiate the enumerator
4458 if (expr.Type.IsValueType) {
4459 IMemoryLocation ml = expr as IMemoryLocation;
4460 // Load the address of the value type.
4462 // This happens if, for example, you have a property
4463 // returning a struct which is IEnumerable
4464 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4466 ig.Emit (OpCodes.Stloc, t);
4467 ig.Emit (OpCodes.Ldloca, t);
4468 ec.FreeTemporaryLocal (t, expr.Type);
4470 ml.AddressOf (ec, AddressOp.Load);
4474 if (hm.get_enumerator.DeclaringType.IsValueType) {
4475 // the method is declared on the value type
4476 ig.Emit (OpCodes.Call, hm.get_enumerator);
4478 // it is an interface method, so we must box
4479 ig.Emit (OpCodes.Box, expr.Type);
4480 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4484 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4486 enumerator.EmitStore (ig);
4489 // Protect the code in a try/finalize block, so that
4490 // if the beast implement IDisposable, we get rid of it
4492 if (hm.is_disposable && emit_finally)
4493 ig.BeginExceptionBlock ();
4495 Label end_try = ig.DefineLabel ();
4497 ig.MarkLabel (ec.LoopBegin);
4499 enumerator.EmitCall (ig, hm.move_next);
4501 ig.Emit (OpCodes.Brfalse, end_try);
4504 enumerator.EmitThis (ig);
4505 enumerator.EmitCall (ig, hm.get_current);
4509 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4511 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4513 statement.Emit (ec);
4514 ig.Emit (OpCodes.Br, ec.LoopBegin);
4515 ig.MarkLabel (end_try);
4518 // Now the finally block
4520 if (hm.is_disposable) {
4523 ig.EndExceptionBlock ();
4526 ig.MarkLabel (ec.LoopEnd);
4530 public override void EmitFinally (EmitContext ec)
4532 ILGenerator ig = ec.ig;
4534 if (hm.enumerator_type.IsValueType) {
4535 enumerator.EmitThis (ig);
4537 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4539 enumerator.EmitLoadAddress (ig);
4540 ig.Emit (OpCodes.Call, mi);
4542 enumerator.EmitLoad (ig);
4543 ig.Emit (OpCodes.Box, hm.enumerator_type);
4544 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4547 Label call_dispose = ig.DefineLabel ();
4549 enumerator.EmitThis (ig);
4550 enumerator.EmitLoad (ig);
4551 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4552 ig.Emit (OpCodes.Dup);
4553 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4554 ig.Emit (OpCodes.Pop);
4556 Label end_finally = ig.DefineLabel ();
4557 ig.Emit (OpCodes.Br, end_finally);
4559 ig.MarkLabel (call_dispose);
4560 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4561 ig.MarkLabel (end_finally);
4564 ig.Emit (OpCodes.Endfinally);
4569 // FIXME: possible optimization.
4570 // We might be able to avoid creating `empty' if the type is the sam
4572 bool EmitArrayForeach (EmitContext ec)
4574 int rank = array_type.GetArrayRank ();
4575 ILGenerator ig = ec.ig;
4577 VariableStorage copy = new VariableStorage (ec, array_type);
4580 // Make our copy of the array
4584 copy.EmitStore (ig);
4587 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4591 counter.EmitThis (ig);
4592 ig.Emit (OpCodes.Ldc_I4_0);
4593 counter.EmitStore (ig);
4594 test = ig.DefineLabel ();
4595 ig.Emit (OpCodes.Br, test);
4597 loop = ig.DefineLabel ();
4598 ig.MarkLabel (loop);
4605 counter.EmitThis (ig);
4606 counter.EmitLoad (ig);
4609 // Load the value, we load the value using the underlying type,
4610 // then we use the variable.EmitAssign to load using the proper cast.
4612 ArrayAccess.EmitLoadOpcode (ig, element_type);
4615 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4617 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4619 statement.Emit (ec);
4621 ig.MarkLabel (ec.LoopBegin);
4622 counter.EmitThis (ig);
4623 counter.EmitThis (ig);
4624 counter.EmitLoad (ig);
4625 ig.Emit (OpCodes.Ldc_I4_1);
4626 ig.Emit (OpCodes.Add);
4627 counter.EmitStore (ig);
4629 ig.MarkLabel (test);
4630 counter.EmitThis (ig);
4631 counter.EmitLoad (ig);
4634 ig.Emit (OpCodes.Ldlen);
4635 ig.Emit (OpCodes.Conv_I4);
4636 ig.Emit (OpCodes.Blt, loop);
4638 VariableStorage [] dim_len = new VariableStorage [rank];
4639 VariableStorage [] dim_count = new VariableStorage [rank];
4640 Label [] loop = new Label [rank];
4641 Label [] test = new Label [rank];
4644 for (dim = 0; dim < rank; dim++){
4645 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4646 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4647 test [dim] = ig.DefineLabel ();
4648 loop [dim] = ig.DefineLabel ();
4651 for (dim = 0; dim < rank; dim++){
4652 dim_len [dim].EmitThis (ig);
4655 IntLiteral.EmitInt (ig, dim);
4656 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4657 dim_len [dim].EmitStore (ig);
4661 for (dim = 0; dim < rank; dim++){
4662 dim_count [dim].EmitThis (ig);
4663 ig.Emit (OpCodes.Ldc_I4_0);
4664 dim_count [dim].EmitStore (ig);
4665 ig.Emit (OpCodes.Br, test [dim]);
4666 ig.MarkLabel (loop [dim]);
4673 for (dim = 0; dim < rank; dim++){
4674 dim_count [dim].EmitThis (ig);
4675 dim_count [dim].EmitLoad (ig);
4679 // FIXME: Maybe we can cache the computation of `get'?
4681 Type [] args = new Type [rank];
4684 for (int i = 0; i < rank; i++)
4685 args [i] = TypeManager.int32_type;
4687 ModuleBuilder mb = CodeGen.Module.Builder;
4688 get = mb.GetArrayMethod (
4690 CallingConventions.HasThis| CallingConventions.Standard,
4692 ig.Emit (OpCodes.Call, get);
4695 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4697 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4698 statement.Emit (ec);
4699 ig.MarkLabel (ec.LoopBegin);
4700 for (dim = rank - 1; dim >= 0; dim--){
4701 dim_count [dim].EmitThis (ig);
4702 dim_count [dim].EmitThis (ig);
4703 dim_count [dim].EmitLoad (ig);
4704 ig.Emit (OpCodes.Ldc_I4_1);
4705 ig.Emit (OpCodes.Add);
4706 dim_count [dim].EmitStore (ig);
4708 ig.MarkLabel (test [dim]);
4709 dim_count [dim].EmitThis (ig);
4710 dim_count [dim].EmitLoad (ig);
4711 dim_len [dim].EmitThis (ig);
4712 dim_len [dim].EmitLoad (ig);
4713 ig.Emit (OpCodes.Blt, loop [dim]);
4716 ig.MarkLabel (ec.LoopEnd);
4721 protected override void DoEmit (EmitContext ec)
4723 ILGenerator ig = ec.ig;
4725 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4726 ec.LoopBegin = ig.DefineLabel ();
4727 ec.LoopEnd = ig.DefineLabel ();
4730 EmitCollectionForeach (ec);
4732 EmitArrayForeach (ec);
4734 ec.LoopBegin = old_begin;
4735 ec.LoopEnd = old_end;