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");
849 } else if (!in_catch) {
851 "A throw statement with no argument is only " +
852 "allowed in a catch clause");
859 protected override void DoEmit (EmitContext ec)
862 ec.ig.Emit (OpCodes.Rethrow);
866 ec.ig.Emit (OpCodes.Throw);
871 public class Break : Statement {
873 public Break (Location l)
880 public override bool Resolve (EmitContext ec)
882 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
883 Error (139, "No enclosing loop or switch to continue to");
885 } else if (ec.CurrentBranching.InFinally (false)) {
886 Error (157, "Control can not leave the body of the finally block");
888 } else if (ec.CurrentBranching.InTryOrCatch (false))
889 ec.CurrentBranching.AddFinallyVector (
890 ec.CurrentBranching.CurrentUsageVector);
891 else if (ec.CurrentBranching.InLoop ())
892 ec.CurrentBranching.AddBreakVector (
893 ec.CurrentBranching.CurrentUsageVector);
895 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
898 ec.NeedReturnLabel ();
900 ec.CurrentBranching.CurrentUsageVector.Break ();
904 protected override void DoEmit (EmitContext ec)
906 ILGenerator ig = ec.ig;
909 ig.Emit (OpCodes.Leave, ec.LoopEnd);
911 ig.Emit (OpCodes.Br, ec.LoopEnd);
916 public class Continue : Statement {
918 public Continue (Location l)
925 public override bool Resolve (EmitContext ec)
927 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
928 Error (139, "No enclosing loop to continue to");
930 } else if (ec.CurrentBranching.InFinally (false)) {
931 Error (157, "Control can not leave the body of the finally block");
933 } else if (ec.CurrentBranching.InTryOrCatch (false))
934 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
936 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
938 ec.CurrentBranching.CurrentUsageVector.Goto ();
942 protected override void DoEmit (EmitContext ec)
944 Label begin = ec.LoopBegin;
947 ec.ig.Emit (OpCodes.Leave, begin);
949 ec.ig.Emit (OpCodes.Br, begin);
954 // The information about a user-perceived local variable
956 public class LocalInfo {
957 public Expression Type;
960 // Most of the time a variable will be stored in a LocalBuilder
962 // But sometimes, it will be stored in a field (variables that have been
963 // hoisted by iterators or by anonymous methods). The context of the field will
964 // be stored in the EmitContext
967 public LocalBuilder LocalBuilder;
968 public FieldBuilder FieldBuilder;
970 public Type VariableType;
971 public readonly string Name;
972 public readonly Location Location;
973 public readonly Block Block;
975 public VariableInfo VariableInfo;
988 public LocalInfo (Expression type, string name, Block block, Location l)
996 public LocalInfo (TypeContainer tc, Block block, Location l)
998 VariableType = tc.TypeBuilder;
1003 public bool IsThisAssigned (EmitContext ec, Location loc)
1005 if (VariableInfo == null)
1006 throw new Exception ();
1008 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1011 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1014 public bool IsAssigned (EmitContext ec)
1016 if (VariableInfo == null)
1017 throw new Exception ();
1019 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1022 public bool Resolve (EmitContext ec)
1024 if (VariableType == null) {
1025 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1029 VariableType = texpr.ResolveType (ec);
1032 if (VariableType == TypeManager.void_type) {
1033 Report.Error (1547, Location,
1034 "Keyword 'void' cannot be used in this context");
1038 if (VariableType.IsAbstract && VariableType.IsSealed) {
1039 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1042 // TODO: breaks the build
1043 // if (VariableType.IsPointer && !ec.InUnsafe)
1044 // Expression.UnsafeError (Location);
1050 // Whether the variable is Fixed (because its Pinned or its a value type)
1052 public bool IsFixed {
1054 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1061 public bool IsCaptured {
1063 return (flags & Flags.Captured) != 0;
1067 flags |= Flags.Captured;
1071 public bool AddressTaken {
1073 return (flags & Flags.AddressTaken) != 0;
1077 flags |= Flags.AddressTaken;
1081 public override string ToString ()
1083 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1084 Name, Type, VariableInfo, Location);
1089 return (flags & Flags.Used) != 0;
1092 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1096 public bool ReadOnly {
1098 return (flags & Flags.ReadOnly) != 0;
1101 flags = value ? (flags | Flags.ReadOnly) : (unchecked (flags & ~Flags.ReadOnly));
1106 // Whether the variable is pinned, if Pinned the variable has been
1107 // allocated in a pinned slot with DeclareLocal.
1109 public bool Pinned {
1111 return (flags & Flags.Pinned) != 0;
1114 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1118 public bool IsThis {
1120 return (flags & Flags.IsThis) != 0;
1123 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1129 /// Block represents a C# block.
1133 /// This class is used in a number of places: either to represent
1134 /// explicit blocks that the programmer places or implicit blocks.
1136 /// Implicit blocks are used as labels or to introduce variable
1139 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1140 /// they contain extra information that is not necessary on normal blocks.
1142 public class Block : Statement {
1143 public Block Parent;
1144 public readonly Location StartLocation;
1145 public Location EndLocation = Location.Null;
1152 VariablesInitialized = 8,
1161 public bool Implicit {
1163 return (flags & Flags.Implicit) != 0;
1167 public bool Unchecked {
1169 return (flags & Flags.Unchecked) != 0;
1172 flags |= Flags.Unchecked;
1176 public bool Unsafe {
1178 return (flags & Flags.Unsafe) != 0;
1181 flags |= Flags.Unsafe;
1185 public bool HasVarargs {
1188 return Parent.HasVarargs;
1190 return (flags & Flags.HasVarargs) != 0;
1193 flags |= Flags.HasVarargs;
1198 // The statements in this block
1200 ArrayList statements;
1204 // An array of Blocks. We keep track of children just
1205 // to generate the local variable declarations.
1207 // Statements and child statements are handled through the
1213 // Labels. (label, block) pairs.
1218 // Keeps track of (name, type) pairs
1220 Hashtable variables;
1223 // Keeps track of constants
1224 Hashtable constants;
1227 // The parameters for the block, this is only needed on the toplevel block really
1228 // TODO: move `parameters' into ToplevelBlock
1229 Parameters parameters;
1232 // If this is a switch section, the enclosing switch block.
1236 protected static int id;
1240 public Block (Block parent)
1241 : this (parent, (Flags) 0, Location.Null, Location.Null)
1244 public Block (Block parent, Flags flags)
1245 : this (parent, flags, Location.Null, Location.Null)
1248 public Block (Block parent, Flags flags, Parameters parameters)
1249 : this (parent, flags, parameters, Location.Null, Location.Null)
1252 public Block (Block parent, Location start, Location end)
1253 : this (parent, (Flags) 0, start, end)
1256 public Block (Block parent, Parameters parameters, Location start, Location end)
1257 : this (parent, (Flags) 0, parameters, start, end)
1260 public Block (Block parent, Flags flags, Location start, Location end)
1261 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1264 public Block (Block parent, Flags flags, Parameters parameters,
1265 Location start, Location end)
1268 parent.AddChild (this);
1270 this.Parent = parent;
1272 this.parameters = parameters;
1273 this.StartLocation = start;
1274 this.EndLocation = end;
1277 statements = new ArrayList ();
1279 if (parent != null && Implicit) {
1280 if (parent.child_variable_names == null)
1281 parent.child_variable_names = new Hashtable();
1282 // share with parent
1283 child_variable_names = parent.child_variable_names;
1288 public Block CreateSwitchBlock (Location start)
1290 Block new_block = new Block (this, start, start);
1291 new_block.switch_block = this;
1301 void AddChild (Block b)
1303 if (children == null)
1304 children = new ArrayList ();
1309 public void SetEndLocation (Location loc)
1315 /// Adds a label to the current block.
1319 /// false if the name already exists in this block. true
1323 public bool AddLabel (string name, LabeledStatement target, Location loc)
1325 if (switch_block != null)
1326 return switch_block.AddLabel (name, target, loc);
1329 while (cur != null) {
1330 if (cur.DoLookupLabel (name) != null) {
1332 140, loc, "The label '{0}' is a duplicate",
1343 while (cur != null) {
1344 if (cur.DoLookupLabel (name) != null) {
1347 "The label '{0}' shadows another label " +
1348 "by the same name in a containing scope.",
1353 if (children != null) {
1354 foreach (Block b in children) {
1355 LabeledStatement s = b.DoLookupLabel (name);
1361 "The label '{0}' shadows another " +
1362 "label by the same name in a " +
1363 "containing scope.",
1374 labels = new Hashtable ();
1376 labels.Add (name, target);
1380 public LabeledStatement LookupLabel (string name)
1382 LabeledStatement s = DoLookupLabel (name);
1386 if (children == null)
1389 foreach (Block child in children) {
1390 if (!child.Implicit)
1393 s = child.LookupLabel (name);
1401 LabeledStatement DoLookupLabel (string name)
1403 if (switch_block != null)
1404 return switch_block.LookupLabel (name);
1407 if (labels.Contains (name))
1408 return ((LabeledStatement) labels [name]);
1413 LocalInfo this_variable = null;
1416 // Returns the "this" instance variable of this block.
1417 // See AddThisVariable() for more information.
1419 public LocalInfo ThisVariable {
1421 if (this_variable != null)
1422 return this_variable;
1423 else if (Parent != null)
1424 return Parent.ThisVariable;
1430 Hashtable child_variable_names;
1433 // Marks a variable with name @name as being used in a child block.
1434 // If a variable name has been used in a child block, it's illegal to
1435 // declare a variable with the same name in the current block.
1437 public void AddChildVariableName (string name)
1439 if (child_variable_names == null)
1440 child_variable_names = new Hashtable ();
1442 child_variable_names [name] = null;
1446 // Checks whether a variable name has already been used in a child block.
1448 public bool IsVariableNameUsedInChildBlock (string name)
1450 if (child_variable_names == null)
1453 return child_variable_names.Contains (name);
1457 // This is used by non-static `struct' constructors which do not have an
1458 // initializer - in this case, the constructor must initialize all of the
1459 // struct's fields. To do this, we add a "this" variable and use the flow
1460 // analysis code to ensure that it's been fully initialized before control
1461 // leaves the constructor.
1463 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1465 if (this_variable != null)
1466 return this_variable;
1468 if (variables == null)
1469 variables = new Hashtable ();
1471 this_variable = new LocalInfo (tc, this, l);
1472 this_variable.Used = true;
1473 this_variable.IsThis = true;
1475 variables.Add ("this", this_variable);
1477 return this_variable;
1480 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1482 if (variables == null)
1483 variables = new Hashtable ();
1485 LocalInfo vi = GetLocalInfo (name);
1487 if (vi.Block != this)
1488 Report.Error (136, l, "A local variable named `" + name + "' " +
1489 "cannot be declared in this scope since it would " +
1490 "give a different meaning to `" + name + "', which " +
1491 "is already used in a `parent or current' scope to " +
1492 "denote something else");
1494 Report.Error (128, l, "A local variable `" + name + "' is already " +
1495 "defined in this scope");
1499 if (IsVariableNameUsedInChildBlock (name)) {
1500 Report.Error (136, l, "A local variable named `" + name + "' " +
1501 "cannot be declared in this scope since it would " +
1502 "give a different meaning to `" + name + "', which " +
1503 "is already used in a `child' scope to denote something " +
1510 Parameter p = pars.GetParameterByName (name, out idx);
1512 Report.Error (136, l, "A local variable named `" + name + "' " +
1513 "cannot be declared in this scope since it would " +
1514 "give a different meaning to `" + name + "', which " +
1515 "is already used in a `parent or current' scope to " +
1516 "denote something else");
1521 vi = new LocalInfo (type, name, this, l);
1523 variables.Add (name, vi);
1525 // Mark 'name' as "used by a child block" in every surrounding block
1527 while (cur != null && cur.Implicit)
1530 for (Block par = cur.Parent; par != null; par = par.Parent)
1531 par.AddChildVariableName (name);
1533 if ((flags & Flags.VariablesInitialized) != 0)
1534 throw new Exception ();
1536 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1540 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1542 if (AddVariable (type, name, pars, l) == null)
1545 if (constants == null)
1546 constants = new Hashtable ();
1548 constants.Add (name, value);
1552 public Hashtable Variables {
1558 public LocalInfo GetLocalInfo (string name)
1560 for (Block b = this; b != null; b = b.Parent) {
1561 if (b.variables != null) {
1562 LocalInfo ret = b.variables [name] as LocalInfo;
1570 public Expression GetVariableType (string name)
1572 LocalInfo vi = GetLocalInfo (name);
1580 public Expression GetConstantExpression (string name)
1582 for (Block b = this; b != null; b = b.Parent) {
1583 if (b.constants != null) {
1584 Expression ret = b.constants [name] as Expression;
1593 /// True if the variable named @name is a constant
1595 public bool IsConstant (string name)
1597 Expression e = null;
1599 e = GetConstantExpression (name);
1605 // Returns a `ParameterReference' for the given name, or null if there
1606 // is no such parameter
1608 public ParameterReference GetParameterReference (string name, Location loc)
1613 Parameters pars = b.parameters;
1619 par = pars.GetParameterByName (name, out idx);
1621 ParameterReference pr;
1623 pr = new ParameterReference (pars, this, idx, name, loc);
1628 } while (b != null);
1633 // Whether the parameter named `name' is local to this block,
1634 // or false, if the parameter belongs to an encompassing block.
1636 public bool IsLocalParameter (string name)
1639 int toplevel_count = 0;
1642 if (this is ToplevelBlock)
1645 Parameters pars = b.parameters;
1647 if (pars.GetParameterByName (name) != null)
1651 if (toplevel_count > 0)
1654 } while (b != null);
1659 // Whether the `name' is a parameter reference
1661 public bool IsParameterReference (string name)
1666 Parameters pars = b.parameters;
1669 if (pars.GetParameterByName (name) != null)
1672 } while (b != null);
1677 /// A list of labels that were not used within this block
1679 public string [] GetUnreferenced ()
1681 // FIXME: Implement me
1685 public void AddStatement (Statement s)
1688 flags |= Flags.BlockUsed;
1693 return (flags & Flags.BlockUsed) != 0;
1699 flags |= Flags.BlockUsed;
1702 public bool HasRet {
1704 return (flags & Flags.HasRet) != 0;
1708 public bool IsDestructor {
1710 return (flags & Flags.IsDestructor) != 0;
1714 public void SetDestructor ()
1716 flags |= Flags.IsDestructor;
1719 VariableMap param_map, local_map;
1721 public VariableMap ParameterMap {
1723 if ((flags & Flags.VariablesInitialized) == 0)
1724 throw new Exception ("Variables have not been initialized yet");
1730 public VariableMap LocalMap {
1732 if ((flags & Flags.VariablesInitialized) == 0)
1733 throw new Exception ("Variables have not been initialized yet");
1740 /// Emits the variable declarations and labels.
1743 /// tc: is our typecontainer (to resolve type references)
1744 /// ig: is the code generator:
1746 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1748 bool old_unsafe = ec.InUnsafe;
1750 // If some parent block was unsafe, we remain unsafe even if this block
1751 // isn't explicitly marked as such.
1752 ec.InUnsafe |= Unsafe;
1755 // Compute the VariableMap's.
1757 // Unfortunately, we don't know the type when adding variables with
1758 // AddVariable(), so we need to compute this info here.
1762 if (variables != null) {
1763 foreach (LocalInfo li in variables.Values)
1766 locals = new LocalInfo [variables.Count];
1767 variables.Values.CopyTo (locals, 0);
1769 locals = new LocalInfo [0];
1772 local_map = new VariableMap (Parent.LocalMap, locals);
1774 local_map = new VariableMap (locals);
1776 param_map = new VariableMap (ip);
1777 flags |= Flags.VariablesInitialized;
1779 bool old_check_state = ec.ConstantCheckState;
1780 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1783 // Process this block variables
1785 if (variables != null){
1786 foreach (DictionaryEntry de in variables){
1787 string name = (string) de.Key;
1788 LocalInfo vi = (LocalInfo) de.Value;
1790 if (vi.VariableType == null)
1793 Type variable_type = vi.VariableType;
1795 if (variable_type.IsPointer){
1797 // Am not really convinced that this test is required (Microsoft does it)
1798 // but the fact is that you would not be able to use the pointer variable
1801 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1808 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1811 // This is needed to compile on both .NET 1.x and .NET 2.x
1812 // the later introduced `DeclareLocal (Type t, bool pinned)'
1814 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1815 else if (!vi.IsThis)
1816 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1819 if (constants == null)
1822 Expression cv = (Expression) constants [name];
1826 ec.CurrentBlock = this;
1827 Expression e = cv.Resolve (ec);
1831 Constant ce = e as Constant;
1833 Report.Error (133, vi.Location,
1834 "The expression being assigned to `" +
1835 name + "' must be constant (" + e + ")");
1839 if (e.Type != variable_type){
1840 e = Const.ChangeType (vi.Location, ce, variable_type);
1845 constants.Remove (name);
1846 constants.Add (name, e);
1849 ec.ConstantCheckState = old_check_state;
1852 // Now, handle the children
1854 if (children != null){
1855 foreach (Block b in children)
1856 b.ResolveMeta (toplevel, ec, ip);
1858 ec.InUnsafe = old_unsafe;
1862 // Emits the local variable declarations for a block
1864 public void EmitMeta (EmitContext ec)
1866 ILGenerator ig = ec.ig;
1868 if (variables != null){
1869 bool have_captured_vars = ec.HaveCapturedVariables ();
1870 bool remap_locals = ec.RemapToProxy;
1872 foreach (DictionaryEntry de in variables){
1873 LocalInfo vi = (LocalInfo) de.Value;
1875 if (have_captured_vars && ec.IsCaptured (vi))
1879 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1883 // This is needed to compile on both .NET 1.x and .NET 2.x
1884 // the later introduced `DeclareLocal (Type t, bool pinned)'
1886 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1887 else if (!vi.IsThis)
1888 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1893 if (children != null){
1894 foreach (Block b in children)
1899 void UsageWarning (FlowBranching.UsageVector vector)
1903 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1904 foreach (DictionaryEntry de in variables){
1905 LocalInfo vi = (LocalInfo) de.Value;
1910 name = (string) de.Key;
1912 if (vector.IsAssigned (vi.VariableInfo)){
1913 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1915 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1921 bool unreachable_shown;
1923 public override bool Resolve (EmitContext ec)
1925 Block prev_block = ec.CurrentBlock;
1928 int errors = Report.Errors;
1930 ec.CurrentBlock = this;
1931 ec.StartFlowBranching (this);
1933 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1935 bool unreachable = false;
1937 int statement_count = statements.Count;
1938 for (int ix = 0; ix < statement_count; ix++){
1939 Statement s = (Statement) statements [ix];
1941 if (unreachable && !(s is LabeledStatement)) {
1942 if (s == EmptyStatement.Value)
1943 s.loc = EndLocation;
1945 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1948 if (s != EmptyStatement.Value)
1949 unreachable_shown = true;
1951 s.loc = Location.Null;
1953 statements [ix] = EmptyStatement.Value;
1957 if (s.Resolve (ec) == false) {
1959 statements [ix] = EmptyStatement.Value;
1963 num_statements = ix + 1;
1965 if (s is LabeledStatement)
1966 unreachable = false;
1968 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1971 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1972 ec.CurrentBranching, statement_count, num_statements);
1975 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1977 ec.CurrentBlock = prev_block;
1979 // If we're a non-static `struct' constructor which doesn't have an
1980 // initializer, then we must initialize all of the struct's fields.
1981 if ((this_variable != null) &&
1982 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1983 !this_variable.IsThisAssigned (ec, loc))
1986 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1987 foreach (LabeledStatement label in labels.Values)
1988 if (!label.HasBeenReferenced)
1989 Report.Warning (164, label.Location,
1990 "This label has not been referenced");
1993 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1995 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1996 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1997 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1998 flags |= Flags.HasRet;
2000 if (ok && (errors == Report.Errors)) {
2001 if (RootContext.WarningLevel >= 3)
2002 UsageWarning (vector);
2008 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2010 unreachable_shown = true;
2011 return base.ResolveUnreachable (ec, warn);
2014 protected override void DoEmit (EmitContext ec)
2016 for (int ix = 0; ix < num_statements; ix++){
2017 Statement s = (Statement) statements [ix];
2019 // Check whether we are the last statement in a
2022 if ((Parent == null) && (ix+1 == num_statements))
2023 ec.IsLastStatement = true;
2025 ec.IsLastStatement = false;
2031 public override void Emit (EmitContext ec)
2033 Block prev_block = ec.CurrentBlock;
2035 ec.CurrentBlock = this;
2037 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2038 bool is_lexical_block = !Implicit && (Parent != null);
2040 if (emit_debug_info) {
2041 if (is_lexical_block)
2042 ec.ig.BeginScope ();
2044 if (variables != null) {
2045 foreach (DictionaryEntry de in variables) {
2046 string name = (string) de.Key;
2047 LocalInfo vi = (LocalInfo) de.Value;
2049 if (vi.LocalBuilder == null)
2052 ec.DefineLocalVariable (name, vi.LocalBuilder);
2057 ec.Mark (StartLocation, true);
2059 ec.Mark (EndLocation, true);
2061 if (emit_debug_info && is_lexical_block)
2064 ec.CurrentBlock = prev_block;
2067 public ToplevelBlock Toplevel {
2070 while (b.Parent != null){
2071 if ((b.flags & Flags.IsToplevel) != 0)
2076 return (ToplevelBlock) b;
2081 // Returns true if we ar ea child of `b'.
2083 public bool IsChildOf (Block b)
2085 Block current = this;
2088 if (current.Parent == b)
2090 current = current.Parent;
2091 } while (current != null);
2097 // A toplevel block contains extra information, the split is done
2098 // only to separate information that would otherwise bloat the more
2099 // lightweight Block.
2101 // In particular, this was introduced when the support for Anonymous
2102 // Methods was implemented.
2104 public class ToplevelBlock : Block {
2106 // Pointer to the host of this anonymous method, or null
2107 // if we are the topmost block
2109 public ToplevelBlock Container;
2110 CaptureContext capture_context;
2112 Hashtable capture_contexts;
2117 public void RegisterCaptureContext (CaptureContext cc)
2119 if (capture_contexts == null)
2120 capture_contexts = new Hashtable ();
2121 capture_contexts [cc] = cc;
2124 public void CompleteContexts ()
2126 if (capture_contexts == null)
2129 foreach (CaptureContext cc in capture_contexts.Keys){
2134 public CaptureContext ToplevelBlockCaptureContext {
2136 return capture_context;
2141 // Parent is only used by anonymous blocks to link back to their
2144 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2145 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2147 Container = container;
2150 public ToplevelBlock (Parameters parameters, Location start) :
2151 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2155 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2156 base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2160 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2164 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2166 if (capture_context == null)
2167 capture_context = new CaptureContext (this, loc, host);
2170 public CaptureContext CaptureContext {
2172 return capture_context;
2177 public class SwitchLabel {
2180 public Location loc;
2184 Label il_label_code;
2185 bool il_label_code_set;
2188 // if expr == null, then it is the default case.
2190 public SwitchLabel (Expression expr, Location l)
2196 public Expression Label {
2202 public object Converted {
2208 public Label GetILLabel (EmitContext ec)
2211 il_label = ec.ig.DefineLabel ();
2212 il_label_set = true;
2217 public Label GetILLabelCode (EmitContext ec)
2219 if (!il_label_code_set){
2220 il_label_code = ec.ig.DefineLabel ();
2221 il_label_code_set = true;
2223 return il_label_code;
2227 // Resolves the expression, reduces it to a literal if possible
2228 // and then converts it to the requested type.
2230 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2235 Expression e = label.Resolve (ec);
2240 if (!(e is Constant)){
2241 Report.Error (150, loc, "A constant value is expected, got: " + e);
2245 if (e is StringConstant || e is NullLiteral){
2246 if (required_type == TypeManager.string_type){
2252 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2253 if (converted == null)
2260 public class SwitchSection {
2261 // An array of SwitchLabels.
2262 public readonly ArrayList Labels;
2263 public readonly Block Block;
2265 public SwitchSection (ArrayList labels, Block block)
2272 public class Switch : Statement {
2273 public readonly ArrayList Sections;
2274 public Expression Expr;
2277 /// Maps constants whose type type SwitchType to their SwitchLabels.
2279 public Hashtable Elements;
2282 /// The governing switch type
2284 public Type SwitchType;
2290 Label default_target;
2291 Expression new_expr;
2293 SwitchSection constant_section;
2296 // The types allowed to be implicitly cast from
2297 // on the governing type
2299 static Type [] allowed_types;
2301 public Switch (Expression e, ArrayList sects, Location l)
2308 public bool GotDefault {
2314 public Label DefaultTarget {
2316 return default_target;
2321 // Determines the governing type for a switch. The returned
2322 // expression might be the expression from the switch, or an
2323 // expression that includes any potential conversions to the
2324 // integral types or to string.
2326 Expression SwitchGoverningType (EmitContext ec, Type t)
2328 if (t == TypeManager.int32_type ||
2329 t == TypeManager.uint32_type ||
2330 t == TypeManager.char_type ||
2331 t == TypeManager.byte_type ||
2332 t == TypeManager.sbyte_type ||
2333 t == TypeManager.ushort_type ||
2334 t == TypeManager.short_type ||
2335 t == TypeManager.uint64_type ||
2336 t == TypeManager.int64_type ||
2337 t == TypeManager.string_type ||
2338 t == TypeManager.bool_type ||
2339 t.IsSubclassOf (TypeManager.enum_type))
2342 if (allowed_types == null){
2343 allowed_types = new Type [] {
2344 TypeManager.int32_type,
2345 TypeManager.uint32_type,
2346 TypeManager.sbyte_type,
2347 TypeManager.byte_type,
2348 TypeManager.short_type,
2349 TypeManager.ushort_type,
2350 TypeManager.int64_type,
2351 TypeManager.uint64_type,
2352 TypeManager.char_type,
2353 TypeManager.bool_type,
2354 TypeManager.string_type
2359 // Try to find a *user* defined implicit conversion.
2361 // If there is no implicit conversion, or if there are multiple
2362 // conversions, we have to report an error
2364 Expression converted = null;
2365 foreach (Type tt in allowed_types){
2368 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2373 // Ignore over-worked ImplicitUserConversions that do
2374 // an implicit conversion in addition to the user conversion.
2377 UserCast ue = e as UserCast;
2379 if (ue.Source != Expr)
2383 if (converted != null){
2384 Report.ExtraInformation (
2386 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2387 TypeManager.CSharpName (Expr.Type)));
2396 static string Error152 {
2398 return "The label '{0}:' already occurs in this switch statement";
2403 // Performs the basic sanity checks on the switch statement
2404 // (looks for duplicate keys and non-constant expressions).
2406 // It also returns a hashtable with the keys that we will later
2407 // use to compute the switch tables
2409 bool CheckSwitch (EmitContext ec)
2413 Elements = new Hashtable ();
2415 got_default = false;
2417 if (TypeManager.IsEnumType (SwitchType)){
2418 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2420 compare_type = SwitchType;
2422 foreach (SwitchSection ss in Sections){
2423 foreach (SwitchLabel sl in ss.Labels){
2424 if (!sl.ResolveAndReduce (ec, SwitchType)){
2429 if (sl.Label == null){
2431 Report.Error (152, sl.loc, Error152, "default");
2438 object key = sl.Converted;
2440 if (key is Constant)
2441 key = ((Constant) key).GetValue ();
2444 key = NullLiteral.Null;
2446 string lname = null;
2447 if (compare_type == TypeManager.uint64_type){
2448 ulong v = (ulong) key;
2450 if (Elements.Contains (v))
2451 lname = v.ToString ();
2453 Elements.Add (v, sl);
2454 } else if (compare_type == TypeManager.int64_type){
2455 long v = (long) key;
2457 if (Elements.Contains (v))
2458 lname = v.ToString ();
2460 Elements.Add (v, sl);
2461 } else if (compare_type == TypeManager.uint32_type){
2462 uint v = (uint) key;
2464 if (Elements.Contains (v))
2465 lname = v.ToString ();
2467 Elements.Add (v, sl);
2468 } else if (compare_type == TypeManager.char_type){
2469 char v = (char) key;
2471 if (Elements.Contains (v))
2472 lname = v.ToString ();
2474 Elements.Add (v, sl);
2475 } else if (compare_type == TypeManager.byte_type){
2476 byte v = (byte) key;
2478 if (Elements.Contains (v))
2479 lname = v.ToString ();
2481 Elements.Add (v, sl);
2482 } else if (compare_type == TypeManager.sbyte_type){
2483 sbyte v = (sbyte) key;
2485 if (Elements.Contains (v))
2486 lname = v.ToString ();
2488 Elements.Add (v, sl);
2489 } else if (compare_type == TypeManager.short_type){
2490 short v = (short) key;
2492 if (Elements.Contains (v))
2493 lname = v.ToString ();
2495 Elements.Add (v, sl);
2496 } else if (compare_type == TypeManager.ushort_type){
2497 ushort v = (ushort) key;
2499 if (Elements.Contains (v))
2500 lname = v.ToString ();
2502 Elements.Add (v, sl);
2503 } else if (compare_type == TypeManager.string_type){
2504 if (key is NullLiteral){
2505 if (Elements.Contains (NullLiteral.Null))
2508 Elements.Add (NullLiteral.Null, null);
2510 string s = (string) key;
2512 if (Elements.Contains (s))
2515 Elements.Add (s, sl);
2517 } else if (compare_type == TypeManager.int32_type) {
2520 if (Elements.Contains (v))
2521 lname = v.ToString ();
2523 Elements.Add (v, sl);
2524 } else if (compare_type == TypeManager.bool_type) {
2525 bool v = (bool) key;
2527 if (Elements.Contains (v))
2528 lname = v.ToString ();
2530 Elements.Add (v, sl);
2534 throw new Exception ("Unknown switch type!" +
2535 SwitchType + " " + compare_type);
2538 if (lname != null) {
2539 Report.Error (152, sl.loc, Error152, "case " + lname);
2550 void EmitObjectInteger (ILGenerator ig, object k)
2553 IntConstant.EmitInt (ig, (int) k);
2554 else if (k is Constant) {
2555 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2558 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2561 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2563 IntConstant.EmitInt (ig, (int) (long) k);
2564 ig.Emit (OpCodes.Conv_I8);
2567 LongConstant.EmitLong (ig, (long) k);
2569 else if (k is ulong)
2571 if ((ulong) k < (1L<<32))
2573 IntConstant.EmitInt (ig, (int) (long) k);
2574 ig.Emit (OpCodes.Conv_U8);
2578 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2582 IntConstant.EmitInt (ig, (int) ((char) k));
2583 else if (k is sbyte)
2584 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2586 IntConstant.EmitInt (ig, (int) ((byte) k));
2587 else if (k is short)
2588 IntConstant.EmitInt (ig, (int) ((short) k));
2589 else if (k is ushort)
2590 IntConstant.EmitInt (ig, (int) ((ushort) k));
2592 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2594 throw new Exception ("Unhandled case");
2597 // structure used to hold blocks of keys while calculating table switch
2598 class KeyBlock : IComparable
2600 public KeyBlock (long _nFirst)
2602 nFirst = nLast = _nFirst;
2606 public ArrayList rgKeys = null;
2607 // how many items are in the bucket
2608 public int Size = 1;
2611 get { return (int) (nLast - nFirst + 1); }
2613 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2615 return kbLast.nLast - kbFirst.nFirst + 1;
2617 public int CompareTo (object obj)
2619 KeyBlock kb = (KeyBlock) obj;
2620 int nLength = Length;
2621 int nLengthOther = kb.Length;
2622 if (nLengthOther == nLength)
2623 return (int) (kb.nFirst - nFirst);
2624 return nLength - nLengthOther;
2629 /// This method emits code for a lookup-based switch statement (non-string)
2630 /// Basically it groups the cases into blocks that are at least half full,
2631 /// and then spits out individual lookup opcodes for each block.
2632 /// It emits the longest blocks first, and short blocks are just
2633 /// handled with direct compares.
2635 /// <param name="ec"></param>
2636 /// <param name="val"></param>
2637 /// <returns></returns>
2638 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2640 int cElements = Elements.Count;
2641 object [] rgKeys = new object [cElements];
2642 Elements.Keys.CopyTo (rgKeys, 0);
2643 Array.Sort (rgKeys);
2645 // initialize the block list with one element per key
2646 ArrayList rgKeyBlocks = new ArrayList ();
2647 foreach (object key in rgKeys)
2648 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2651 // iteratively merge the blocks while they are at least half full
2652 // there's probably a really cool way to do this with a tree...
2653 while (rgKeyBlocks.Count > 1)
2655 ArrayList rgKeyBlocksNew = new ArrayList ();
2656 kbCurr = (KeyBlock) rgKeyBlocks [0];
2657 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2659 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2660 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2663 kbCurr.nLast = kb.nLast;
2664 kbCurr.Size += kb.Size;
2668 // start a new block
2669 rgKeyBlocksNew.Add (kbCurr);
2673 rgKeyBlocksNew.Add (kbCurr);
2674 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2676 rgKeyBlocks = rgKeyBlocksNew;
2679 // initialize the key lists
2680 foreach (KeyBlock kb in rgKeyBlocks)
2681 kb.rgKeys = new ArrayList ();
2683 // fill the key lists
2685 if (rgKeyBlocks.Count > 0) {
2686 kbCurr = (KeyBlock) rgKeyBlocks [0];
2687 foreach (object key in rgKeys)
2689 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2690 System.Convert.ToInt64 (key) > kbCurr.nLast;
2692 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2693 kbCurr.rgKeys.Add (key);
2697 // sort the blocks so we can tackle the largest ones first
2698 rgKeyBlocks.Sort ();
2700 // okay now we can start...
2701 ILGenerator ig = ec.ig;
2702 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2703 Label lblDefault = ig.DefineLabel ();
2705 Type typeKeys = null;
2706 if (rgKeys.Length > 0)
2707 typeKeys = rgKeys [0].GetType (); // used for conversions
2711 if (TypeManager.IsEnumType (SwitchType))
2712 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2714 compare_type = SwitchType;
2716 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2718 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2719 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2722 foreach (object key in kb.rgKeys)
2724 ig.Emit (OpCodes.Ldloc, val);
2725 EmitObjectInteger (ig, key);
2726 SwitchLabel sl = (SwitchLabel) Elements [key];
2727 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2732 // TODO: if all the keys in the block are the same and there are
2733 // no gaps/defaults then just use a range-check.
2734 if (compare_type == TypeManager.int64_type ||
2735 compare_type == TypeManager.uint64_type)
2737 // TODO: optimize constant/I4 cases
2739 // check block range (could be > 2^31)
2740 ig.Emit (OpCodes.Ldloc, val);
2741 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2742 ig.Emit (OpCodes.Blt, lblDefault);
2743 ig.Emit (OpCodes.Ldloc, val);
2744 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2745 ig.Emit (OpCodes.Bgt, lblDefault);
2748 ig.Emit (OpCodes.Ldloc, val);
2751 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2752 ig.Emit (OpCodes.Sub);
2754 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2759 ig.Emit (OpCodes.Ldloc, val);
2760 int nFirst = (int) kb.nFirst;
2763 IntConstant.EmitInt (ig, nFirst);
2764 ig.Emit (OpCodes.Sub);
2766 else if (nFirst < 0)
2768 IntConstant.EmitInt (ig, -nFirst);
2769 ig.Emit (OpCodes.Add);
2773 // first, build the list of labels for the switch
2775 int cJumps = kb.Length;
2776 Label [] rgLabels = new Label [cJumps];
2777 for (int iJump = 0; iJump < cJumps; iJump++)
2779 object key = kb.rgKeys [iKey];
2780 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2782 SwitchLabel sl = (SwitchLabel) Elements [key];
2783 rgLabels [iJump] = sl.GetILLabel (ec);
2787 rgLabels [iJump] = lblDefault;
2789 // emit the switch opcode
2790 ig.Emit (OpCodes.Switch, rgLabels);
2793 // mark the default for this block
2795 ig.MarkLabel (lblDefault);
2798 // TODO: find the default case and emit it here,
2799 // to prevent having to do the following jump.
2800 // make sure to mark other labels in the default section
2802 // the last default just goes to the end
2803 ig.Emit (OpCodes.Br, lblDefault);
2805 // now emit the code for the sections
2806 bool fFoundDefault = false;
2807 foreach (SwitchSection ss in Sections)
2809 foreach (SwitchLabel sl in ss.Labels)
2811 ig.MarkLabel (sl.GetILLabel (ec));
2812 ig.MarkLabel (sl.GetILLabelCode (ec));
2813 if (sl.Label == null)
2815 ig.MarkLabel (lblDefault);
2816 fFoundDefault = true;
2820 //ig.Emit (OpCodes.Br, lblEnd);
2823 if (!fFoundDefault) {
2824 ig.MarkLabel (lblDefault);
2826 ig.MarkLabel (lblEnd);
2829 // This simple emit switch works, but does not take advantage of the
2831 // TODO: remove non-string logic from here
2832 // TODO: binary search strings?
2834 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2836 ILGenerator ig = ec.ig;
2837 Label end_of_switch = ig.DefineLabel ();
2838 Label next_test = ig.DefineLabel ();
2839 Label null_target = ig.DefineLabel ();
2840 bool default_found = false;
2841 bool first_test = true;
2842 bool pending_goto_end = false;
2844 bool default_at_end = false;
2846 ig.Emit (OpCodes.Ldloc, val);
2848 if (Elements.Contains (NullLiteral.Null)){
2849 ig.Emit (OpCodes.Brfalse, null_target);
2851 ig.Emit (OpCodes.Brfalse, default_target);
2853 ig.Emit (OpCodes.Ldloc, val);
2854 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2855 ig.Emit (OpCodes.Stloc, val);
2857 int section_count = Sections.Count;
2858 for (int section = 0; section < section_count; section++){
2859 SwitchSection ss = (SwitchSection) Sections [section];
2860 Label sec_begin = ig.DefineLabel ();
2862 if (pending_goto_end)
2863 ig.Emit (OpCodes.Br, end_of_switch);
2865 int label_count = ss.Labels.Count;
2866 bool mark_default = false;
2868 for (int label = 0; label < label_count; label++){
2869 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2870 ig.MarkLabel (sl.GetILLabel (ec));
2873 ig.MarkLabel (next_test);
2874 next_test = ig.DefineLabel ();
2877 // If we are the default target
2879 if (sl.Label == null){
2880 if (label+1 == label_count)
2881 default_at_end = true;
2882 mark_default = true;
2883 default_found = true;
2885 object lit = sl.Converted;
2887 if (lit is NullLiteral){
2889 if (label_count == 1)
2890 ig.Emit (OpCodes.Br, next_test);
2894 StringConstant str = (StringConstant) lit;
2896 ig.Emit (OpCodes.Ldloc, val);
2897 ig.Emit (OpCodes.Ldstr, str.Value);
2898 if (label_count == 1)
2899 ig.Emit (OpCodes.Bne_Un, next_test);
2901 if (label+1 == label_count)
2902 ig.Emit (OpCodes.Bne_Un, next_test);
2904 ig.Emit (OpCodes.Beq, sec_begin);
2909 ig.MarkLabel (null_target);
2910 ig.MarkLabel (sec_begin);
2911 foreach (SwitchLabel sl in ss.Labels)
2912 ig.MarkLabel (sl.GetILLabelCode (ec));
2915 ig.MarkLabel (default_target);
2917 pending_goto_end = !ss.Block.HasRet;
2920 ig.MarkLabel (next_test);
2922 if (!default_at_end)
2923 ig.Emit (OpCodes.Br, default_target);
2925 ig.MarkLabel (default_target);
2926 ig.MarkLabel (end_of_switch);
2929 SwitchSection FindSection (SwitchLabel label)
2931 foreach (SwitchSection ss in Sections){
2932 foreach (SwitchLabel sl in ss.Labels){
2941 bool ResolveConstantSwitch (EmitContext ec)
2943 object key = ((Constant) new_expr).GetValue ();
2944 SwitchLabel label = (SwitchLabel) Elements [key];
2949 constant_section = FindSection (label);
2950 if (constant_section == null)
2953 if (constant_section.Block.Resolve (ec) != true)
2959 public override bool Resolve (EmitContext ec)
2961 Expr = Expr.Resolve (ec);
2965 new_expr = SwitchGoverningType (ec, Expr.Type);
2966 if (new_expr == null){
2967 Report.Error (151, loc, "An integer type or string was expected for switch");
2972 SwitchType = new_expr.Type;
2974 if (!CheckSwitch (ec))
2977 Switch old_switch = ec.Switch;
2979 ec.Switch.SwitchType = SwitchType;
2981 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2982 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2984 is_constant = new_expr is Constant;
2986 object key = ((Constant) new_expr).GetValue ();
2987 SwitchLabel label = (SwitchLabel) Elements [key];
2989 constant_section = FindSection (label);
2993 foreach (SwitchSection ss in Sections){
2995 ec.CurrentBranching.CreateSibling (
2996 null, FlowBranching.SiblingType.SwitchSection);
3000 if (is_constant && (ss != constant_section)) {
3001 // If we're a constant switch, we're only emitting
3002 // one single section - mark all the others as
3004 ec.CurrentBranching.CurrentUsageVector.Goto ();
3005 if (!ss.Block.ResolveUnreachable (ec, true))
3008 if (!ss.Block.Resolve (ec))
3014 ec.CurrentBranching.CreateSibling (
3015 null, FlowBranching.SiblingType.SwitchSection);
3017 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3018 ec.Switch = old_switch;
3020 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3026 protected override void DoEmit (EmitContext ec)
3028 ILGenerator ig = ec.ig;
3030 // Store variable for comparission purposes
3033 value = ig.DeclareLocal (SwitchType);
3035 ig.Emit (OpCodes.Stloc, value);
3039 default_target = ig.DefineLabel ();
3042 // Setup the codegen context
3044 Label old_end = ec.LoopEnd;
3045 Switch old_switch = ec.Switch;
3047 ec.LoopEnd = ig.DefineLabel ();
3052 if (constant_section != null)
3053 constant_section.Block.Emit (ec);
3054 } else if (SwitchType == TypeManager.string_type)
3055 SimpleSwitchEmit (ec, value);
3057 TableSwitchEmit (ec, value);
3059 // Restore context state.
3060 ig.MarkLabel (ec.LoopEnd);
3063 // Restore the previous context
3065 ec.LoopEnd = old_end;
3066 ec.Switch = old_switch;
3070 public abstract class ExceptionStatement : Statement
3072 public abstract void EmitFinally (EmitContext ec);
3074 protected bool emit_finally = true;
3075 ArrayList parent_vectors;
3077 protected void DoEmitFinally (EmitContext ec)
3080 ec.ig.BeginFinallyBlock ();
3082 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3086 protected void ResolveFinally (FlowBranchingException branching)
3088 emit_finally = branching.EmitFinally;
3090 branching.Parent.StealFinallyClauses (ref parent_vectors);
3094 public class Lock : ExceptionStatement {
3096 Statement Statement;
3099 public Lock (Expression expr, Statement stmt, Location l)
3106 public override bool Resolve (EmitContext ec)
3108 expr = expr.Resolve (ec);
3112 if (expr.Type.IsValueType){
3113 Error (185, "lock statement requires the expression to be " +
3114 " a reference type (type is: `{0}'",
3115 TypeManager.CSharpName (expr.Type));
3119 FlowBranchingException branching = ec.StartFlowBranching (this);
3120 bool ok = Statement.Resolve (ec);
3122 ec.KillFlowBranching ();
3126 ResolveFinally (branching);
3128 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3129 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3130 // Unfortunately, System.Reflection.Emit automatically emits
3131 // a leave to the end of the finally block.
3132 // This is a problem if `returns' is true since we may jump
3133 // to a point after the end of the method.
3134 // As a workaround, emit an explicit ret here.
3135 ec.NeedReturnLabel ();
3141 protected override void DoEmit (EmitContext ec)
3143 Type type = expr.Type;
3145 ILGenerator ig = ec.ig;
3146 temp = ig.DeclareLocal (type);
3149 ig.Emit (OpCodes.Dup);
3150 ig.Emit (OpCodes.Stloc, temp);
3151 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3155 ig.BeginExceptionBlock ();
3156 Statement.Emit (ec);
3161 ig.EndExceptionBlock ();
3164 public override void EmitFinally (EmitContext ec)
3166 ILGenerator ig = ec.ig;
3167 ig.Emit (OpCodes.Ldloc, temp);
3168 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3172 public class Unchecked : Statement {
3173 public readonly Block Block;
3175 public Unchecked (Block b)
3181 public override bool Resolve (EmitContext ec)
3183 bool previous_state = ec.CheckState;
3184 bool previous_state_const = ec.ConstantCheckState;
3186 ec.CheckState = false;
3187 ec.ConstantCheckState = false;
3188 bool ret = Block.Resolve (ec);
3189 ec.CheckState = previous_state;
3190 ec.ConstantCheckState = previous_state_const;
3195 protected override void DoEmit (EmitContext ec)
3197 bool previous_state = ec.CheckState;
3198 bool previous_state_const = ec.ConstantCheckState;
3200 ec.CheckState = false;
3201 ec.ConstantCheckState = false;
3203 ec.CheckState = previous_state;
3204 ec.ConstantCheckState = previous_state_const;
3208 public class Checked : Statement {
3209 public readonly Block Block;
3211 public Checked (Block b)
3214 b.Unchecked = false;
3217 public override bool Resolve (EmitContext ec)
3219 bool previous_state = ec.CheckState;
3220 bool previous_state_const = ec.ConstantCheckState;
3222 ec.CheckState = true;
3223 ec.ConstantCheckState = true;
3224 bool ret = Block.Resolve (ec);
3225 ec.CheckState = previous_state;
3226 ec.ConstantCheckState = previous_state_const;
3231 protected override void DoEmit (EmitContext ec)
3233 bool previous_state = ec.CheckState;
3234 bool previous_state_const = ec.ConstantCheckState;
3236 ec.CheckState = true;
3237 ec.ConstantCheckState = true;
3239 ec.CheckState = previous_state;
3240 ec.ConstantCheckState = previous_state_const;
3244 public class Unsafe : Statement {
3245 public readonly Block Block;
3247 public Unsafe (Block b)
3250 Block.Unsafe = true;
3253 public override bool Resolve (EmitContext ec)
3255 bool previous_state = ec.InUnsafe;
3259 val = Block.Resolve (ec);
3260 ec.InUnsafe = previous_state;
3265 protected override void DoEmit (EmitContext ec)
3267 bool previous_state = ec.InUnsafe;
3271 ec.InUnsafe = previous_state;
3278 public class Fixed : Statement {
3280 ArrayList declarators;
3281 Statement statement;
3287 public bool is_object;
3288 public LocalInfo vi;
3289 public Expression expr;
3290 public Expression converted;
3293 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3296 declarators = decls;
3301 public override bool Resolve (EmitContext ec)
3304 Expression.UnsafeError (loc);
3308 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3312 expr_type = texpr.ResolveType (ec);
3314 CheckObsolete (expr_type);
3316 if (ec.RemapToProxy){
3317 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3321 data = new FixedData [declarators.Count];
3323 if (!expr_type.IsPointer){
3324 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3329 foreach (Pair p in declarators){
3330 LocalInfo vi = (LocalInfo) p.First;
3331 Expression e = (Expression) p.Second;
3333 vi.VariableInfo.SetAssigned (ec);
3337 // The rules for the possible declarators are pretty wise,
3338 // but the production on the grammar is more concise.
3340 // So we have to enforce these rules here.
3342 // We do not resolve before doing the case 1 test,
3343 // because the grammar is explicit in that the token &
3344 // is present, so we need to test for this particular case.
3348 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3353 // Case 1: & object.
3355 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3356 Expression child = ((Unary) e).Expr;
3358 if (child is ParameterReference || child is LocalVariableReference){
3361 "No need to use fixed statement for parameters or " +
3362 "local variable declarations (address is already " +
3367 ec.InFixedInitializer = true;
3369 ec.InFixedInitializer = false;
3373 child = ((Unary) e).Expr;
3375 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3378 data [i].is_object = true;
3380 data [i].converted = null;
3387 ec.InFixedInitializer = true;
3389 ec.InFixedInitializer = false;
3396 if (e.Type.IsArray){
3397 Type array_type = TypeManager.GetElementType (e.Type);
3400 // Provided that array_type is unmanaged,
3402 if (!TypeManager.VerifyUnManaged (array_type, loc))
3406 // and T* is implicitly convertible to the
3407 // pointer type given in the fixed statement.
3409 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3411 Expression converted = Convert.ImplicitConversionRequired (
3412 ec, array_ptr, vi.VariableType, loc);
3413 if (converted == null)
3416 data [i].is_object = false;
3418 data [i].converted = converted;
3428 if (e.Type == TypeManager.string_type){
3429 data [i].is_object = false;
3431 data [i].converted = null;
3438 // For other cases, flag a `this is already fixed expression'
3440 if (e is LocalVariableReference || e is ParameterReference ||
3441 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3443 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3447 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3451 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3453 if (!statement.Resolve (ec)) {
3454 ec.KillFlowBranching ();
3458 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3459 has_ret = reachability.IsUnreachable;
3464 protected override void DoEmit (EmitContext ec)
3466 ILGenerator ig = ec.ig;
3468 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3470 for (int i = 0; i < data.Length; i++) {
3471 LocalInfo vi = data [i].vi;
3474 // Case 1: & object.
3476 if (data [i].is_object) {
3478 // Store pointer in pinned location
3480 data [i].expr.Emit (ec);
3481 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3482 clear_list [i] = vi.LocalBuilder;
3489 if (data [i].expr.Type.IsArray){
3491 // Store pointer in pinned location
3493 data [i].converted.Emit (ec);
3495 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3496 clear_list [i] = vi.LocalBuilder;
3503 if (data [i].expr.Type == TypeManager.string_type){
3504 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3505 clear_list [i] = pinned_string;
3507 data [i].expr.Emit (ec);
3508 ig.Emit (OpCodes.Stloc, pinned_string);
3510 Expression sptr = new StringPtr (pinned_string, loc);
3511 Expression converted = Convert.ImplicitConversionRequired (
3512 ec, sptr, vi.VariableType, loc);
3514 if (converted == null)
3517 converted.Emit (ec);
3518 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3522 statement.Emit (ec);
3528 // Clear the pinned variable
3530 for (int i = 0; i < data.Length; i++) {
3531 if (data [i].is_object || data [i].expr.Type.IsArray) {
3532 ig.Emit (OpCodes.Ldc_I4_0);
3533 ig.Emit (OpCodes.Conv_U);
3534 ig.Emit (OpCodes.Stloc, clear_list [i]);
3535 } else if (data [i].expr.Type == TypeManager.string_type){
3536 ig.Emit (OpCodes.Ldnull);
3537 ig.Emit (OpCodes.Stloc, clear_list [i]);
3543 public class Catch: Statement {
3544 public readonly string Name;
3545 public readonly Block Block;
3547 Expression type_expr;
3550 public Catch (Expression type, string name, Block block, Location l)
3558 public Type CatchType {
3564 public bool IsGeneral {
3566 return type_expr == null;
3570 protected override void DoEmit(EmitContext ec)
3574 public override bool Resolve (EmitContext ec)
3576 if (type_expr != null) {
3577 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3581 type = te.ResolveType (ec);
3583 CheckObsolete (type);
3585 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3586 Error (155, "The type caught or thrown must be derived from System.Exception");
3592 return Block.Resolve (ec);
3596 public class Try : ExceptionStatement {
3597 public readonly Block Fini, Block;
3598 public readonly ArrayList Specific;
3599 public readonly Catch General;
3601 bool need_exc_block;
3604 // specific, general and fini might all be null.
3606 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3608 if (specific == null && general == null){
3609 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3613 this.Specific = specific;
3614 this.General = general;
3619 public override bool Resolve (EmitContext ec)
3623 FlowBranchingException branching = ec.StartFlowBranching (this);
3625 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3627 if (!Block.Resolve (ec))
3630 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3632 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3634 Type[] prevCatches = new Type [Specific.Count];
3636 foreach (Catch c in Specific){
3637 ec.CurrentBranching.CreateSibling (
3638 c.Block, FlowBranching.SiblingType.Catch);
3640 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3642 if (c.Name != null) {
3643 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3645 throw new Exception ();
3647 vi.VariableInfo = null;
3650 if (!c.Resolve (ec))
3653 Type resolvedType = c.CatchType;
3654 for (int ii = 0; ii < last_index; ++ii) {
3655 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3656 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3661 prevCatches [last_index++] = resolvedType;
3662 need_exc_block = true;
3665 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3667 if (General != null){
3668 ec.CurrentBranching.CreateSibling (
3669 General.Block, FlowBranching.SiblingType.Catch);
3671 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3673 if (!General.Resolve (ec))
3676 need_exc_block = true;
3679 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3683 ec.CurrentBranching.CreateSibling (
3684 Fini, FlowBranching.SiblingType.Finally);
3686 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3688 if (!Fini.Resolve (ec))
3692 ResolveFinally (branching);
3693 need_exc_block |= emit_finally;
3695 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3697 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3699 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3701 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3702 // Unfortunately, System.Reflection.Emit automatically emits
3703 // a leave to the end of the finally block. This is a problem
3704 // if `returns' is true since we may jump to a point after the
3705 // end of the method.
3706 // As a workaround, emit an explicit ret here.
3707 ec.NeedReturnLabel ();
3713 protected override void DoEmit (EmitContext ec)
3715 ILGenerator ig = ec.ig;
3718 ig.BeginExceptionBlock ();
3721 foreach (Catch c in Specific){
3724 ig.BeginCatchBlock (c.CatchType);
3726 if (c.Name != null){
3727 vi = c.Block.GetLocalInfo (c.Name);
3729 throw new Exception ("Variable does not exist in this block");
3731 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3733 ig.Emit (OpCodes.Pop);
3738 if (General != null){
3739 ig.BeginCatchBlock (TypeManager.object_type);
3740 ig.Emit (OpCodes.Pop);
3741 General.Block.Emit (ec);
3746 ig.EndExceptionBlock ();
3749 public override void EmitFinally (EmitContext ec)
3757 public class Using : ExceptionStatement {
3758 object expression_or_block;
3759 Statement Statement;
3764 Expression [] resolved_vars;
3765 Expression [] converted_vars;
3766 ExpressionStatement [] assign;
3767 LocalBuilder local_copy;
3769 public Using (object expression_or_block, Statement stmt, Location l)
3771 this.expression_or_block = expression_or_block;
3777 // Resolves for the case of using using a local variable declaration.
3779 bool ResolveLocalVariableDecls (EmitContext ec)
3783 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3787 expr_type = texpr.ResolveType (ec);
3790 // The type must be an IDisposable or an implicit conversion
3793 converted_vars = new Expression [var_list.Count];
3794 resolved_vars = new Expression [var_list.Count];
3795 assign = new ExpressionStatement [var_list.Count];
3797 bool need_conv = !TypeManager.ImplementsInterface (
3798 expr_type, TypeManager.idisposable_type);
3800 foreach (DictionaryEntry e in var_list){
3801 Expression var = (Expression) e.Key;
3803 var = var.ResolveLValue (ec, new EmptyExpression ());
3807 resolved_vars [i] = var;
3814 converted_vars [i] = Convert.ImplicitConversionRequired (
3815 ec, var, TypeManager.idisposable_type, loc);
3817 if (converted_vars [i] == null)
3824 foreach (DictionaryEntry e in var_list){
3825 Expression var = resolved_vars [i];
3826 Expression new_expr = (Expression) e.Value;
3829 a = new Assign (var, new_expr, loc);
3835 converted_vars [i] = var;
3836 assign [i] = (ExpressionStatement) a;
3843 bool ResolveExpression (EmitContext ec)
3845 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3846 conv = Convert.ImplicitConversionRequired (
3847 ec, expr, TypeManager.idisposable_type, loc);
3857 // Emits the code for the case of using using a local variable declaration.
3859 void EmitLocalVariableDecls (EmitContext ec)
3861 ILGenerator ig = ec.ig;
3864 for (i = 0; i < assign.Length; i++) {
3865 assign [i].EmitStatement (ec);
3868 ig.BeginExceptionBlock ();
3870 Statement.Emit (ec);
3871 var_list.Reverse ();
3876 void EmitLocalVariableDeclFinally (EmitContext ec)
3878 ILGenerator ig = ec.ig;
3880 int i = assign.Length;
3881 for (int ii = 0; ii < var_list.Count; ++ii){
3882 Expression var = resolved_vars [--i];
3883 Label skip = ig.DefineLabel ();
3885 if (!var.Type.IsValueType) {
3887 ig.Emit (OpCodes.Brfalse, skip);
3888 converted_vars [i].Emit (ec);
3889 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3891 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3893 if (!(ml is MethodGroupExpr)) {
3895 ig.Emit (OpCodes.Box, var.Type);
3896 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3898 MethodInfo mi = null;
3900 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3901 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3908 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3912 IMemoryLocation mloc = (IMemoryLocation) var;
3914 mloc.AddressOf (ec, AddressOp.Load);
3915 ig.Emit (OpCodes.Call, mi);
3919 ig.MarkLabel (skip);
3922 ig.EndExceptionBlock ();
3924 ig.BeginFinallyBlock ();
3929 void EmitExpression (EmitContext ec)
3932 // Make a copy of the expression and operate on that.
3934 ILGenerator ig = ec.ig;
3935 local_copy = ig.DeclareLocal (expr_type);
3940 ig.Emit (OpCodes.Stloc, local_copy);
3943 ig.BeginExceptionBlock ();
3945 Statement.Emit (ec);
3949 ig.EndExceptionBlock ();
3952 void EmitExpressionFinally (EmitContext ec)
3954 ILGenerator ig = ec.ig;
3955 if (!local_copy.LocalType.IsValueType) {
3956 Label skip = ig.DefineLabel ();
3957 ig.Emit (OpCodes.Ldloc, local_copy);
3958 ig.Emit (OpCodes.Brfalse, skip);
3959 ig.Emit (OpCodes.Ldloc, local_copy);
3960 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3961 ig.MarkLabel (skip);
3963 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
3965 if (!(ml is MethodGroupExpr)) {
3966 ig.Emit (OpCodes.Ldloc, local_copy);
3967 ig.Emit (OpCodes.Box, local_copy.LocalType);
3968 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3970 MethodInfo mi = null;
3972 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3973 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3980 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3984 ig.Emit (OpCodes.Ldloca, local_copy);
3985 ig.Emit (OpCodes.Call, mi);
3990 public override bool Resolve (EmitContext ec)
3992 if (expression_or_block is DictionaryEntry){
3993 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3994 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3996 if (!ResolveLocalVariableDecls (ec))
3999 } else if (expression_or_block is Expression){
4000 expr = (Expression) expression_or_block;
4002 expr = expr.Resolve (ec);
4006 expr_type = expr.Type;
4008 if (!ResolveExpression (ec))
4012 FlowBranchingException branching = ec.StartFlowBranching (this);
4014 bool ok = Statement.Resolve (ec);
4017 ec.KillFlowBranching ();
4021 ResolveFinally (branching);
4022 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4024 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4025 // Unfortunately, System.Reflection.Emit automatically emits a leave
4026 // to the end of the finally block. This is a problem if `returns'
4027 // is true since we may jump to a point after the end of the method.
4028 // As a workaround, emit an explicit ret here.
4029 ec.NeedReturnLabel ();
4035 protected override void DoEmit (EmitContext ec)
4037 if (expression_or_block is DictionaryEntry)
4038 EmitLocalVariableDecls (ec);
4039 else if (expression_or_block is Expression)
4040 EmitExpression (ec);
4043 public override void EmitFinally (EmitContext ec)
4045 if (expression_or_block is DictionaryEntry)
4046 EmitLocalVariableDeclFinally (ec);
4047 else if (expression_or_block is Expression)
4048 EmitExpressionFinally (ec);
4053 /// Implementation of the foreach C# statement
4055 public class Foreach : ExceptionStatement {
4057 Expression variable;
4059 Statement statement;
4060 ForeachHelperMethods hm;
4061 Expression empty, conv;
4062 Type array_type, element_type;
4064 VariableStorage enumerator;
4066 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4067 Statement stmt, Location l)
4070 this.variable = var;
4076 public override bool Resolve (EmitContext ec)
4078 expr = expr.Resolve (ec);
4082 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4086 var_type = texpr.ResolveType (ec);
4089 // We need an instance variable. Not sure this is the best
4090 // way of doing this.
4092 // FIXME: When we implement propertyaccess, will those turn
4093 // out to return values in ExprClass? I think they should.
4095 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4096 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4097 error1579 (expr.Type);
4101 if (expr.Type.IsArray) {
4102 array_type = expr.Type;
4103 element_type = TypeManager.GetElementType (array_type);
4105 empty = new EmptyExpression (element_type);
4107 hm = ProbeCollectionType (ec, expr.Type);
4109 error1579 (expr.Type);
4113 // When ProbeCollection reported error
4114 if (hm.move_next == null)
4117 array_type = expr.Type;
4118 element_type = hm.element_type;
4120 empty = new EmptyExpression (hm.element_type);
4125 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4126 ec.CurrentBranching.CreateSibling ();
4130 // FIXME: maybe we can apply the same trick we do in the
4131 // array handling to avoid creating empty and conv in some cases.
4133 // Although it is not as important in this case, as the type
4134 // will not likely be object (what the enumerator will return).
4136 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4140 variable = variable.ResolveLValue (ec, empty);
4141 if (variable == null)
4144 bool disposable = (hm != null) && hm.is_disposable;
4145 FlowBranchingException branching = null;
4147 branching = ec.StartFlowBranching (this);
4149 if (!statement.Resolve (ec))
4153 ResolveFinally (branching);
4154 ec.EndFlowBranching ();
4156 emit_finally = true;
4158 ec.EndFlowBranching ();
4164 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4166 static MethodInfo FetchMethodMoveNext (Type t)
4168 MemberList move_next_list;
4170 move_next_list = TypeContainer.FindMembers (
4171 t, MemberTypes.Method,
4172 BindingFlags.Public | BindingFlags.Instance,
4173 Type.FilterName, "MoveNext");
4174 if (move_next_list.Count == 0)
4177 foreach (MemberInfo m in move_next_list){
4178 MethodInfo mi = (MethodInfo) m;
4181 args = TypeManager.GetArgumentTypes (mi);
4182 if (args != null && args.Length == 0){
4183 if (mi.ReturnType == TypeManager.bool_type)
4191 // Retrieves a `public T get_Current ()' method from the Type `t'
4193 static MethodInfo FetchMethodGetCurrent (Type t)
4195 MemberList get_current_list;
4197 get_current_list = TypeContainer.FindMembers (
4198 t, MemberTypes.Method,
4199 BindingFlags.Public | BindingFlags.Instance,
4200 Type.FilterName, "get_Current");
4201 if (get_current_list.Count == 0)
4204 foreach (MemberInfo m in get_current_list){
4205 MethodInfo mi = (MethodInfo) m;
4208 args = TypeManager.GetArgumentTypes (mi);
4209 if (args != null && args.Length == 0)
4216 // Retrieves a `public void Dispose ()' method from the Type `t'
4218 static MethodInfo FetchMethodDispose (Type t)
4220 MemberList dispose_list;
4222 dispose_list = TypeContainer.FindMembers (
4223 t, MemberTypes.Method,
4224 BindingFlags.Public | BindingFlags.Instance,
4225 Type.FilterName, "Dispose");
4226 if (dispose_list.Count == 0)
4229 foreach (MemberInfo m in dispose_list){
4230 MethodInfo mi = (MethodInfo) m;
4233 args = TypeManager.GetArgumentTypes (mi);
4234 if (args != null && args.Length == 0){
4235 if (mi.ReturnType == TypeManager.void_type)
4243 // This struct records the helper methods used by the Foreach construct
4245 class ForeachHelperMethods {
4246 public EmitContext ec;
4247 public MethodInfo get_enumerator;
4248 public MethodInfo move_next;
4249 public MethodInfo get_current;
4250 public Type element_type;
4251 public Type enumerator_type;
4252 public bool is_disposable;
4253 public readonly Location Location;
4255 public ForeachHelperMethods (EmitContext ec, Location loc)
4258 this.Location = loc;
4259 this.element_type = TypeManager.object_type;
4260 this.enumerator_type = TypeManager.ienumerator_type;
4261 this.is_disposable = true;
4265 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4270 if (!(m is MethodInfo))
4273 if (m.Name != "GetEnumerator")
4276 MethodInfo mi = (MethodInfo) m;
4277 Type [] args = TypeManager.GetArgumentTypes (mi);
4279 if (args.Length != 0)
4282 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4284 // Check whether GetEnumerator is public
4285 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4288 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4290 // Apply the same optimization as MS: skip the GetEnumerator
4291 // returning an IEnumerator, and use the one returning a
4292 // CharEnumerator instead. This allows us to avoid the
4293 // try-finally block and the boxing.
4298 // Ok, we can access it, now make sure that we can do something
4299 // with this `GetEnumerator'
4302 Type return_type = mi.ReturnType;
4303 if (mi.ReturnType == TypeManager.ienumerator_type ||
4304 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4305 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4308 // If it is not an interface, lets try to find the methods ourselves.
4309 // For example, if we have:
4310 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4311 // We can avoid the iface call. This is a runtime perf boost.
4312 // even bigger if we have a ValueType, because we avoid the cost
4315 // We have to make sure that both methods exist for us to take
4316 // this path. If one of the methods does not exist, we will just
4317 // use the interface. Sadly, this complex if statement is the only
4318 // way I could do this without a goto
4321 if (return_type.IsInterface ||
4322 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4323 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4325 hm.move_next = TypeManager.bool_movenext_void;
4326 hm.get_current = TypeManager.object_getcurrent_void;
4332 if (return_type.IsPointer || return_type.IsArray) {
4333 Report.SymbolRelatedToPreviousError (mi);
4334 Type t = return_type.GetElementType ();
4335 Report.SymbolRelatedToPreviousError (t);
4336 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",
4337 TypeManager.CSharpName (return_type), TypeManager.GetFullNameSignature (m));
4338 hm.get_enumerator = mi;
4343 // Ok, so they dont return an IEnumerable, we will have to
4344 // find if they support the GetEnumerator pattern.
4347 hm.move_next = FetchMethodMoveNext (return_type);
4348 if (hm.move_next == null)
4351 hm.get_current = FetchMethodGetCurrent (return_type);
4352 if (hm.get_current == null)
4356 hm.element_type = hm.get_current.ReturnType;
4357 hm.enumerator_type = return_type;
4358 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4359 TypeManager.ImplementsInterface (
4360 hm.enumerator_type, TypeManager.idisposable_type);
4366 /// This filter is used to find the GetEnumerator method
4367 /// on which IEnumerator operates
4369 static MemberFilter FilterEnumerator;
4373 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4376 void error1579 (Type t)
4378 Report.Error (1579, loc,
4379 "foreach statement cannot operate on variables of type `" +
4380 t.FullName + "' because that class does not provide a " +
4381 " GetEnumerator method or it is inaccessible");
4384 static bool TryType (Type t, ForeachHelperMethods hm)
4388 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4389 BindingFlags.Public | BindingFlags.NonPublic |
4390 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4391 FilterEnumerator, hm);
4396 hm.get_enumerator = (MethodInfo) mi [0];
4401 // Looks for a usable GetEnumerator in the Type, and if found returns
4402 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4404 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4406 ForeachHelperMethods hm = new ForeachHelperMethods (ec, loc);
4408 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4409 if (TryType (tt, hm))
4415 // Now try to find the method in the interfaces
4418 Type [] ifaces = t.GetInterfaces ();
4420 foreach (Type i in ifaces){
4421 if (TryType (i, hm))
4426 // Since TypeBuilder.GetInterfaces only returns the interface
4427 // types for this type, we have to keep looping, but once
4428 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4429 // done, because it returns all the types
4431 if ((t is TypeBuilder))
4441 // FIXME: possible optimization.
4442 // We might be able to avoid creating `empty' if the type is the sam
4444 bool EmitCollectionForeach (EmitContext ec)
4446 ILGenerator ig = ec.ig;
4448 enumerator = new VariableStorage (ec, hm.enumerator_type);
4449 enumerator.EmitThis (ig);
4451 // Instantiate the enumerator
4453 if (expr.Type.IsValueType) {
4454 IMemoryLocation ml = expr as IMemoryLocation;
4455 // Load the address of the value type.
4457 // This happens if, for example, you have a property
4458 // returning a struct which is IEnumerable
4459 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4461 ig.Emit (OpCodes.Stloc, t);
4462 ig.Emit (OpCodes.Ldloca, t);
4463 ec.FreeTemporaryLocal (t, expr.Type);
4465 ml.AddressOf (ec, AddressOp.Load);
4469 if (hm.get_enumerator.DeclaringType.IsValueType) {
4470 // the method is declared on the value type
4471 ig.Emit (OpCodes.Call, hm.get_enumerator);
4473 // it is an interface method, so we must box
4474 ig.Emit (OpCodes.Box, expr.Type);
4475 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4479 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4481 enumerator.EmitStore (ig);
4484 // Protect the code in a try/finalize block, so that
4485 // if the beast implement IDisposable, we get rid of it
4487 if (hm.is_disposable && emit_finally)
4488 ig.BeginExceptionBlock ();
4490 Label end_try = ig.DefineLabel ();
4492 ig.MarkLabel (ec.LoopBegin);
4494 enumerator.EmitCall (ig, hm.move_next);
4496 ig.Emit (OpCodes.Brfalse, end_try);
4499 enumerator.EmitThis (ig);
4500 enumerator.EmitCall (ig, hm.get_current);
4504 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4506 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4508 statement.Emit (ec);
4509 ig.Emit (OpCodes.Br, ec.LoopBegin);
4510 ig.MarkLabel (end_try);
4513 // Now the finally block
4515 if (hm.is_disposable) {
4518 ig.EndExceptionBlock ();
4521 ig.MarkLabel (ec.LoopEnd);
4525 public override void EmitFinally (EmitContext ec)
4527 ILGenerator ig = ec.ig;
4529 if (hm.enumerator_type.IsValueType) {
4530 enumerator.EmitThis (ig);
4532 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4534 enumerator.EmitLoadAddress (ig);
4535 ig.Emit (OpCodes.Call, mi);
4537 enumerator.EmitLoad (ig);
4538 ig.Emit (OpCodes.Box, hm.enumerator_type);
4539 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4542 Label call_dispose = ig.DefineLabel ();
4544 enumerator.EmitThis (ig);
4545 enumerator.EmitLoad (ig);
4546 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4547 ig.Emit (OpCodes.Dup);
4548 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4549 ig.Emit (OpCodes.Pop);
4551 Label end_finally = ig.DefineLabel ();
4552 ig.Emit (OpCodes.Br, end_finally);
4554 ig.MarkLabel (call_dispose);
4555 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4556 ig.MarkLabel (end_finally);
4559 ig.Emit (OpCodes.Endfinally);
4564 // FIXME: possible optimization.
4565 // We might be able to avoid creating `empty' if the type is the sam
4567 bool EmitArrayForeach (EmitContext ec)
4569 int rank = array_type.GetArrayRank ();
4570 ILGenerator ig = ec.ig;
4572 VariableStorage copy = new VariableStorage (ec, array_type);
4575 // Make our copy of the array
4579 copy.EmitStore (ig);
4582 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4586 counter.EmitThis (ig);
4587 ig.Emit (OpCodes.Ldc_I4_0);
4588 counter.EmitStore (ig);
4589 test = ig.DefineLabel ();
4590 ig.Emit (OpCodes.Br, test);
4592 loop = ig.DefineLabel ();
4593 ig.MarkLabel (loop);
4600 counter.EmitThis (ig);
4601 counter.EmitLoad (ig);
4604 // Load the value, we load the value using the underlying type,
4605 // then we use the variable.EmitAssign to load using the proper cast.
4607 ArrayAccess.EmitLoadOpcode (ig, element_type);
4610 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4612 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4614 statement.Emit (ec);
4616 ig.MarkLabel (ec.LoopBegin);
4617 counter.EmitThis (ig);
4618 counter.EmitThis (ig);
4619 counter.EmitLoad (ig);
4620 ig.Emit (OpCodes.Ldc_I4_1);
4621 ig.Emit (OpCodes.Add);
4622 counter.EmitStore (ig);
4624 ig.MarkLabel (test);
4625 counter.EmitThis (ig);
4626 counter.EmitLoad (ig);
4629 ig.Emit (OpCodes.Ldlen);
4630 ig.Emit (OpCodes.Conv_I4);
4631 ig.Emit (OpCodes.Blt, loop);
4633 VariableStorage [] dim_len = new VariableStorage [rank];
4634 VariableStorage [] dim_count = new VariableStorage [rank];
4635 Label [] loop = new Label [rank];
4636 Label [] test = new Label [rank];
4639 for (dim = 0; dim < rank; dim++){
4640 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4641 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4642 test [dim] = ig.DefineLabel ();
4643 loop [dim] = ig.DefineLabel ();
4646 for (dim = 0; dim < rank; dim++){
4647 dim_len [dim].EmitThis (ig);
4650 IntLiteral.EmitInt (ig, dim);
4651 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4652 dim_len [dim].EmitStore (ig);
4656 for (dim = 0; dim < rank; dim++){
4657 dim_count [dim].EmitThis (ig);
4658 ig.Emit (OpCodes.Ldc_I4_0);
4659 dim_count [dim].EmitStore (ig);
4660 ig.Emit (OpCodes.Br, test [dim]);
4661 ig.MarkLabel (loop [dim]);
4668 for (dim = 0; dim < rank; dim++){
4669 dim_count [dim].EmitThis (ig);
4670 dim_count [dim].EmitLoad (ig);
4674 // FIXME: Maybe we can cache the computation of `get'?
4676 Type [] args = new Type [rank];
4679 for (int i = 0; i < rank; i++)
4680 args [i] = TypeManager.int32_type;
4682 ModuleBuilder mb = CodeGen.Module.Builder;
4683 get = mb.GetArrayMethod (
4685 CallingConventions.HasThis| CallingConventions.Standard,
4687 ig.Emit (OpCodes.Call, get);
4690 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4692 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4693 statement.Emit (ec);
4694 ig.MarkLabel (ec.LoopBegin);
4695 for (dim = rank - 1; dim >= 0; dim--){
4696 dim_count [dim].EmitThis (ig);
4697 dim_count [dim].EmitThis (ig);
4698 dim_count [dim].EmitLoad (ig);
4699 ig.Emit (OpCodes.Ldc_I4_1);
4700 ig.Emit (OpCodes.Add);
4701 dim_count [dim].EmitStore (ig);
4703 ig.MarkLabel (test [dim]);
4704 dim_count [dim].EmitThis (ig);
4705 dim_count [dim].EmitLoad (ig);
4706 dim_len [dim].EmitThis (ig);
4707 dim_len [dim].EmitLoad (ig);
4708 ig.Emit (OpCodes.Blt, loop [dim]);
4711 ig.MarkLabel (ec.LoopEnd);
4716 protected override void DoEmit (EmitContext ec)
4718 ILGenerator ig = ec.ig;
4720 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4721 ec.LoopBegin = ig.DefineLabel ();
4722 ec.LoopEnd = ig.DefineLabel ();
4725 EmitCollectionForeach (ec);
4727 EmitArrayForeach (ec);
4729 ec.LoopBegin = old_begin;
4730 ec.LoopEnd = old_end;