2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@gnome.org)
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);
1029 VariableType = texpr.Type;
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 ILGenerator ig = ec.ig;
1750 bool old_unsafe = ec.InUnsafe;
1752 // If some parent block was unsafe, we remain unsafe even if this block
1753 // isn't explicitly marked as such.
1754 ec.InUnsafe |= Unsafe;
1757 // Compute the VariableMap's.
1759 // Unfortunately, we don't know the type when adding variables with
1760 // AddVariable(), so we need to compute this info here.
1764 if (variables != null) {
1765 foreach (LocalInfo li in variables.Values)
1768 locals = new LocalInfo [variables.Count];
1769 variables.Values.CopyTo (locals, 0);
1771 locals = new LocalInfo [0];
1774 local_map = new VariableMap (Parent.LocalMap, locals);
1776 local_map = new VariableMap (locals);
1778 param_map = new VariableMap (ip);
1779 flags |= Flags.VariablesInitialized;
1781 bool old_check_state = ec.ConstantCheckState;
1782 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1785 // Process this block variables
1787 if (variables != null){
1788 foreach (DictionaryEntry de in variables){
1789 string name = (string) de.Key;
1790 LocalInfo vi = (LocalInfo) de.Value;
1792 if (vi.VariableType == null)
1795 Type variable_type = vi.VariableType;
1797 if (variable_type.IsPointer){
1799 // Am not really convinced that this test is required (Microsoft does it)
1800 // but the fact is that you would not be able to use the pointer variable
1803 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1810 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1813 // This is needed to compile on both .NET 1.x and .NET 2.x
1814 // the later introduced `DeclareLocal (Type t, bool pinned)'
1816 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1817 else if (!vi.IsThis)
1818 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1821 if (constants == null)
1824 Expression cv = (Expression) constants [name];
1828 ec.CurrentBlock = this;
1829 Expression e = cv.Resolve (ec);
1833 Constant ce = e as Constant;
1835 Report.Error (133, vi.Location,
1836 "The expression being assigned to `" +
1837 name + "' must be constant (" + e + ")");
1841 if (e.Type != variable_type){
1842 e = Const.ChangeType (vi.Location, ce, variable_type);
1847 constants.Remove (name);
1848 constants.Add (name, e);
1851 ec.ConstantCheckState = old_check_state;
1854 // Now, handle the children
1856 if (children != null){
1857 foreach (Block b in children)
1858 b.ResolveMeta (toplevel, ec, ip);
1860 ec.InUnsafe = old_unsafe;
1864 // Emits the local variable declarations for a block
1866 public void EmitMeta (EmitContext ec)
1868 ILGenerator ig = ec.ig;
1870 if (variables != null){
1871 bool have_captured_vars = ec.HaveCapturedVariables ();
1872 bool remap_locals = ec.RemapToProxy;
1874 foreach (DictionaryEntry de in variables){
1875 LocalInfo vi = (LocalInfo) de.Value;
1877 if (have_captured_vars && ec.IsCaptured (vi))
1881 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1885 // This is needed to compile on both .NET 1.x and .NET 2.x
1886 // the later introduced `DeclareLocal (Type t, bool pinned)'
1888 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1889 else if (!vi.IsThis)
1890 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1895 if (children != null){
1896 foreach (Block b in children)
1901 void UsageWarning (FlowBranching.UsageVector vector)
1905 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1906 foreach (DictionaryEntry de in variables){
1907 LocalInfo vi = (LocalInfo) de.Value;
1912 name = (string) de.Key;
1914 if (vector.IsAssigned (vi.VariableInfo)){
1915 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1917 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1923 bool unreachable_shown;
1925 public override bool Resolve (EmitContext ec)
1927 Block prev_block = ec.CurrentBlock;
1930 int errors = Report.Errors;
1932 ec.CurrentBlock = this;
1933 ec.StartFlowBranching (this);
1935 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1937 bool unreachable = false;
1939 int statement_count = statements.Count;
1940 for (int ix = 0; ix < statement_count; ix++){
1941 Statement s = (Statement) statements [ix];
1943 if (unreachable && !(s is LabeledStatement)) {
1944 if (s == EmptyStatement.Value)
1945 s.loc = EndLocation;
1947 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1950 if (s != EmptyStatement.Value)
1951 unreachable_shown = true;
1953 s.loc = Location.Null;
1955 statements [ix] = EmptyStatement.Value;
1959 if (s.Resolve (ec) == false) {
1961 statements [ix] = EmptyStatement.Value;
1965 num_statements = ix + 1;
1967 if (s is LabeledStatement)
1968 unreachable = false;
1970 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1973 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1974 ec.CurrentBranching, statement_count, num_statements);
1977 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1979 ec.CurrentBlock = prev_block;
1981 // If we're a non-static `struct' constructor which doesn't have an
1982 // initializer, then we must initialize all of the struct's fields.
1983 if ((this_variable != null) &&
1984 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1985 !this_variable.IsThisAssigned (ec, loc))
1988 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1989 foreach (LabeledStatement label in labels.Values)
1990 if (!label.HasBeenReferenced)
1991 Report.Warning (164, label.Location,
1992 "This label has not been referenced");
1995 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1997 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1998 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1999 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2000 flags |= Flags.HasRet;
2002 if (ok && (errors == Report.Errors)) {
2003 if (RootContext.WarningLevel >= 3)
2004 UsageWarning (vector);
2010 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2012 unreachable_shown = true;
2013 return base.ResolveUnreachable (ec, warn);
2016 protected override void DoEmit (EmitContext ec)
2018 for (int ix = 0; ix < num_statements; ix++){
2019 Statement s = (Statement) statements [ix];
2021 // Check whether we are the last statement in a
2024 if ((Parent == null) && (ix+1 == num_statements))
2025 ec.IsLastStatement = true;
2027 ec.IsLastStatement = false;
2033 public override void Emit (EmitContext ec)
2035 Block prev_block = ec.CurrentBlock;
2037 ec.CurrentBlock = this;
2039 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2040 bool is_lexical_block = !Implicit && (Parent != null);
2042 if (emit_debug_info) {
2043 if (is_lexical_block)
2044 ec.ig.BeginScope ();
2046 if (variables != null) {
2047 foreach (DictionaryEntry de in variables) {
2048 string name = (string) de.Key;
2049 LocalInfo vi = (LocalInfo) de.Value;
2051 if (vi.LocalBuilder == null)
2054 ec.DefineLocalVariable (name, vi.LocalBuilder);
2059 ec.Mark (StartLocation, true);
2061 ec.Mark (EndLocation, true);
2063 if (emit_debug_info && is_lexical_block)
2066 ec.CurrentBlock = prev_block;
2069 public ToplevelBlock Toplevel {
2072 while (b.Parent != null){
2073 if ((b.flags & Flags.IsToplevel) != 0)
2078 return (ToplevelBlock) b;
2083 // Returns true if we ar ea child of `b'.
2085 public bool IsChildOf (Block b)
2087 Block current = this;
2090 if (current.Parent == b)
2092 current = current.Parent;
2093 } while (current != null);
2099 // A toplevel block contains extra information, the split is done
2100 // only to separate information that would otherwise bloat the more
2101 // lightweight Block.
2103 // In particular, this was introduced when the support for Anonymous
2104 // Methods was implemented.
2106 public class ToplevelBlock : Block {
2108 // Pointer to the host of this anonymous method, or null
2109 // if we are the topmost block
2111 public ToplevelBlock Container;
2112 CaptureContext capture_context;
2114 Hashtable capture_contexts;
2121 public void RegisterCaptureContext (CaptureContext cc)
2123 if (capture_contexts == null)
2124 capture_contexts = new Hashtable ();
2125 capture_contexts [cc] = cc;
2128 public void CompleteContexts ()
2130 if (capture_contexts == null)
2133 foreach (CaptureContext cc in capture_contexts.Keys){
2138 public CaptureContext ToplevelBlockCaptureContext {
2140 return capture_context;
2145 // Parent is only used by anonymous blocks to link back to their
2148 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2149 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2151 Container = container;
2154 public ToplevelBlock (Parameters parameters, Location start) :
2155 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2159 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2160 base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2164 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2168 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2170 if (capture_context == null)
2171 capture_context = new CaptureContext (this, loc, host);
2174 public CaptureContext CaptureContext {
2176 return capture_context;
2181 public class SwitchLabel {
2184 public Location loc;
2188 Label il_label_code;
2189 bool il_label_code_set;
2192 // if expr == null, then it is the default case.
2194 public SwitchLabel (Expression expr, Location l)
2200 public Expression Label {
2206 public object Converted {
2212 public Label GetILLabel (EmitContext ec)
2215 il_label = ec.ig.DefineLabel ();
2216 il_label_set = true;
2221 public Label GetILLabelCode (EmitContext ec)
2223 if (!il_label_code_set){
2224 il_label_code = ec.ig.DefineLabel ();
2225 il_label_code_set = true;
2227 return il_label_code;
2231 // Resolves the expression, reduces it to a literal if possible
2232 // and then converts it to the requested type.
2234 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2239 Expression e = label.Resolve (ec);
2244 if (!(e is Constant)){
2245 Report.Error (150, loc, "A constant value is expected, got: " + e);
2249 if (e is StringConstant || e is NullLiteral){
2250 if (required_type == TypeManager.string_type){
2256 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2257 if (converted == null)
2264 public class SwitchSection {
2265 // An array of SwitchLabels.
2266 public readonly ArrayList Labels;
2267 public readonly Block Block;
2269 public SwitchSection (ArrayList labels, Block block)
2276 public class Switch : Statement {
2277 public readonly ArrayList Sections;
2278 public Expression Expr;
2281 /// Maps constants whose type type SwitchType to their SwitchLabels.
2283 public Hashtable Elements;
2286 /// The governing switch type
2288 public Type SwitchType;
2294 Label default_target;
2295 Expression new_expr;
2297 SwitchSection constant_section;
2300 // The types allowed to be implicitly cast from
2301 // on the governing type
2303 static Type [] allowed_types;
2305 public Switch (Expression e, ArrayList sects, Location l)
2312 public bool GotDefault {
2318 public Label DefaultTarget {
2320 return default_target;
2325 // Determines the governing type for a switch. The returned
2326 // expression might be the expression from the switch, or an
2327 // expression that includes any potential conversions to the
2328 // integral types or to string.
2330 Expression SwitchGoverningType (EmitContext ec, Type t)
2332 if (t == TypeManager.int32_type ||
2333 t == TypeManager.uint32_type ||
2334 t == TypeManager.char_type ||
2335 t == TypeManager.byte_type ||
2336 t == TypeManager.sbyte_type ||
2337 t == TypeManager.ushort_type ||
2338 t == TypeManager.short_type ||
2339 t == TypeManager.uint64_type ||
2340 t == TypeManager.int64_type ||
2341 t == TypeManager.string_type ||
2342 t == TypeManager.bool_type ||
2343 t.IsSubclassOf (TypeManager.enum_type))
2346 if (allowed_types == null){
2347 allowed_types = new Type [] {
2348 TypeManager.int32_type,
2349 TypeManager.uint32_type,
2350 TypeManager.sbyte_type,
2351 TypeManager.byte_type,
2352 TypeManager.short_type,
2353 TypeManager.ushort_type,
2354 TypeManager.int64_type,
2355 TypeManager.uint64_type,
2356 TypeManager.char_type,
2357 TypeManager.bool_type,
2358 TypeManager.string_type
2363 // Try to find a *user* defined implicit conversion.
2365 // If there is no implicit conversion, or if there are multiple
2366 // conversions, we have to report an error
2368 Expression converted = null;
2369 foreach (Type tt in allowed_types){
2372 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2377 // Ignore over-worked ImplicitUserConversions that do
2378 // an implicit conversion in addition to the user conversion.
2381 UserCast ue = e as UserCast;
2383 if (ue.Source != Expr)
2387 if (converted != null){
2388 Report.ExtraInformation (
2390 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2391 TypeManager.CSharpName (Expr.Type)));
2400 static string Error152 {
2402 return "The label '{0}:' already occurs in this switch statement";
2407 // Performs the basic sanity checks on the switch statement
2408 // (looks for duplicate keys and non-constant expressions).
2410 // It also returns a hashtable with the keys that we will later
2411 // use to compute the switch tables
2413 bool CheckSwitch (EmitContext ec)
2417 Elements = new Hashtable ();
2419 got_default = false;
2421 if (TypeManager.IsEnumType (SwitchType)){
2422 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2424 compare_type = SwitchType;
2426 foreach (SwitchSection ss in Sections){
2427 foreach (SwitchLabel sl in ss.Labels){
2428 if (!sl.ResolveAndReduce (ec, SwitchType)){
2433 if (sl.Label == null){
2435 Report.Error (152, sl.loc, Error152, "default");
2442 object key = sl.Converted;
2444 if (key is Constant)
2445 key = ((Constant) key).GetValue ();
2448 key = NullLiteral.Null;
2450 string lname = null;
2451 if (compare_type == TypeManager.uint64_type){
2452 ulong v = (ulong) key;
2454 if (Elements.Contains (v))
2455 lname = v.ToString ();
2457 Elements.Add (v, sl);
2458 } else if (compare_type == TypeManager.int64_type){
2459 long v = (long) key;
2461 if (Elements.Contains (v))
2462 lname = v.ToString ();
2464 Elements.Add (v, sl);
2465 } else if (compare_type == TypeManager.uint32_type){
2466 uint v = (uint) key;
2468 if (Elements.Contains (v))
2469 lname = v.ToString ();
2471 Elements.Add (v, sl);
2472 } else if (compare_type == TypeManager.char_type){
2473 char v = (char) key;
2475 if (Elements.Contains (v))
2476 lname = v.ToString ();
2478 Elements.Add (v, sl);
2479 } else if (compare_type == TypeManager.byte_type){
2480 byte v = (byte) key;
2482 if (Elements.Contains (v))
2483 lname = v.ToString ();
2485 Elements.Add (v, sl);
2486 } else if (compare_type == TypeManager.sbyte_type){
2487 sbyte v = (sbyte) key;
2489 if (Elements.Contains (v))
2490 lname = v.ToString ();
2492 Elements.Add (v, sl);
2493 } else if (compare_type == TypeManager.short_type){
2494 short v = (short) key;
2496 if (Elements.Contains (v))
2497 lname = v.ToString ();
2499 Elements.Add (v, sl);
2500 } else if (compare_type == TypeManager.ushort_type){
2501 ushort v = (ushort) key;
2503 if (Elements.Contains (v))
2504 lname = v.ToString ();
2506 Elements.Add (v, sl);
2507 } else if (compare_type == TypeManager.string_type){
2508 if (key is NullLiteral){
2509 if (Elements.Contains (NullLiteral.Null))
2512 Elements.Add (NullLiteral.Null, null);
2514 string s = (string) key;
2516 if (Elements.Contains (s))
2519 Elements.Add (s, sl);
2521 } else if (compare_type == TypeManager.int32_type) {
2524 if (Elements.Contains (v))
2525 lname = v.ToString ();
2527 Elements.Add (v, sl);
2528 } else if (compare_type == TypeManager.bool_type) {
2529 bool v = (bool) key;
2531 if (Elements.Contains (v))
2532 lname = v.ToString ();
2534 Elements.Add (v, sl);
2538 throw new Exception ("Unknown switch type!" +
2539 SwitchType + " " + compare_type);
2543 Report.Error (152, sl.loc, Error152, "case " + lname);
2554 void EmitObjectInteger (ILGenerator ig, object k)
2557 IntConstant.EmitInt (ig, (int) k);
2558 else if (k is Constant) {
2559 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2562 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2565 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2567 IntConstant.EmitInt (ig, (int) (long) k);
2568 ig.Emit (OpCodes.Conv_I8);
2571 LongConstant.EmitLong (ig, (long) k);
2573 else if (k is ulong)
2575 if ((ulong) k < (1L<<32))
2577 IntConstant.EmitInt (ig, (int) (long) k);
2578 ig.Emit (OpCodes.Conv_U8);
2582 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2586 IntConstant.EmitInt (ig, (int) ((char) k));
2587 else if (k is sbyte)
2588 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2590 IntConstant.EmitInt (ig, (int) ((byte) k));
2591 else if (k is short)
2592 IntConstant.EmitInt (ig, (int) ((short) k));
2593 else if (k is ushort)
2594 IntConstant.EmitInt (ig, (int) ((ushort) k));
2596 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2598 throw new Exception ("Unhandled case");
2601 // structure used to hold blocks of keys while calculating table switch
2602 class KeyBlock : IComparable
2604 public KeyBlock (long _nFirst)
2606 nFirst = nLast = _nFirst;
2610 public ArrayList rgKeys = null;
2611 // how many items are in the bucket
2612 public int Size = 1;
2615 get { return (int) (nLast - nFirst + 1); }
2617 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2619 return kbLast.nLast - kbFirst.nFirst + 1;
2621 public int CompareTo (object obj)
2623 KeyBlock kb = (KeyBlock) obj;
2624 int nLength = Length;
2625 int nLengthOther = kb.Length;
2626 if (nLengthOther == nLength)
2627 return (int) (kb.nFirst - nFirst);
2628 return nLength - nLengthOther;
2633 /// This method emits code for a lookup-based switch statement (non-string)
2634 /// Basically it groups the cases into blocks that are at least half full,
2635 /// and then spits out individual lookup opcodes for each block.
2636 /// It emits the longest blocks first, and short blocks are just
2637 /// handled with direct compares.
2639 /// <param name="ec"></param>
2640 /// <param name="val"></param>
2641 /// <returns></returns>
2642 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2644 int cElements = Elements.Count;
2645 object [] rgKeys = new object [cElements];
2646 Elements.Keys.CopyTo (rgKeys, 0);
2647 Array.Sort (rgKeys);
2649 // initialize the block list with one element per key
2650 ArrayList rgKeyBlocks = new ArrayList ();
2651 foreach (object key in rgKeys)
2652 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2655 // iteratively merge the blocks while they are at least half full
2656 // there's probably a really cool way to do this with a tree...
2657 while (rgKeyBlocks.Count > 1)
2659 ArrayList rgKeyBlocksNew = new ArrayList ();
2660 kbCurr = (KeyBlock) rgKeyBlocks [0];
2661 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2663 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2664 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2667 kbCurr.nLast = kb.nLast;
2668 kbCurr.Size += kb.Size;
2672 // start a new block
2673 rgKeyBlocksNew.Add (kbCurr);
2677 rgKeyBlocksNew.Add (kbCurr);
2678 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2680 rgKeyBlocks = rgKeyBlocksNew;
2683 // initialize the key lists
2684 foreach (KeyBlock kb in rgKeyBlocks)
2685 kb.rgKeys = new ArrayList ();
2687 // fill the key lists
2689 if (rgKeyBlocks.Count > 0) {
2690 kbCurr = (KeyBlock) rgKeyBlocks [0];
2691 foreach (object key in rgKeys)
2693 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2694 System.Convert.ToInt64 (key) > kbCurr.nLast;
2696 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2697 kbCurr.rgKeys.Add (key);
2701 // sort the blocks so we can tackle the largest ones first
2702 rgKeyBlocks.Sort ();
2704 // okay now we can start...
2705 ILGenerator ig = ec.ig;
2706 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2707 Label lblDefault = ig.DefineLabel ();
2709 Type typeKeys = null;
2710 if (rgKeys.Length > 0)
2711 typeKeys = rgKeys [0].GetType (); // used for conversions
2715 if (TypeManager.IsEnumType (SwitchType))
2716 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2718 compare_type = SwitchType;
2720 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2722 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2723 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2726 foreach (object key in kb.rgKeys)
2728 ig.Emit (OpCodes.Ldloc, val);
2729 EmitObjectInteger (ig, key);
2730 SwitchLabel sl = (SwitchLabel) Elements [key];
2731 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2736 // TODO: if all the keys in the block are the same and there are
2737 // no gaps/defaults then just use a range-check.
2738 if (compare_type == TypeManager.int64_type ||
2739 compare_type == TypeManager.uint64_type)
2741 // TODO: optimize constant/I4 cases
2743 // check block range (could be > 2^31)
2744 ig.Emit (OpCodes.Ldloc, val);
2745 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2746 ig.Emit (OpCodes.Blt, lblDefault);
2747 ig.Emit (OpCodes.Ldloc, val);
2748 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2749 ig.Emit (OpCodes.Bgt, lblDefault);
2752 ig.Emit (OpCodes.Ldloc, val);
2755 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2756 ig.Emit (OpCodes.Sub);
2758 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2763 ig.Emit (OpCodes.Ldloc, val);
2764 int nFirst = (int) kb.nFirst;
2767 IntConstant.EmitInt (ig, nFirst);
2768 ig.Emit (OpCodes.Sub);
2770 else if (nFirst < 0)
2772 IntConstant.EmitInt (ig, -nFirst);
2773 ig.Emit (OpCodes.Add);
2777 // first, build the list of labels for the switch
2779 int cJumps = kb.Length;
2780 Label [] rgLabels = new Label [cJumps];
2781 for (int iJump = 0; iJump < cJumps; iJump++)
2783 object key = kb.rgKeys [iKey];
2784 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2786 SwitchLabel sl = (SwitchLabel) Elements [key];
2787 rgLabels [iJump] = sl.GetILLabel (ec);
2791 rgLabels [iJump] = lblDefault;
2793 // emit the switch opcode
2794 ig.Emit (OpCodes.Switch, rgLabels);
2797 // mark the default for this block
2799 ig.MarkLabel (lblDefault);
2802 // TODO: find the default case and emit it here,
2803 // to prevent having to do the following jump.
2804 // make sure to mark other labels in the default section
2806 // the last default just goes to the end
2807 ig.Emit (OpCodes.Br, lblDefault);
2809 // now emit the code for the sections
2810 bool fFoundDefault = false;
2811 foreach (SwitchSection ss in Sections)
2813 foreach (SwitchLabel sl in ss.Labels)
2815 ig.MarkLabel (sl.GetILLabel (ec));
2816 ig.MarkLabel (sl.GetILLabelCode (ec));
2817 if (sl.Label == null)
2819 ig.MarkLabel (lblDefault);
2820 fFoundDefault = true;
2824 //ig.Emit (OpCodes.Br, lblEnd);
2827 if (!fFoundDefault) {
2828 ig.MarkLabel (lblDefault);
2830 ig.MarkLabel (lblEnd);
2833 // This simple emit switch works, but does not take advantage of the
2835 // TODO: remove non-string logic from here
2836 // TODO: binary search strings?
2838 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2840 ILGenerator ig = ec.ig;
2841 Label end_of_switch = ig.DefineLabel ();
2842 Label next_test = ig.DefineLabel ();
2843 Label null_target = ig.DefineLabel ();
2844 bool default_found = false;
2845 bool first_test = true;
2846 bool pending_goto_end = false;
2848 bool default_at_end = false;
2850 ig.Emit (OpCodes.Ldloc, val);
2852 if (Elements.Contains (NullLiteral.Null)){
2853 ig.Emit (OpCodes.Brfalse, null_target);
2855 ig.Emit (OpCodes.Brfalse, default_target);
2857 ig.Emit (OpCodes.Ldloc, val);
2858 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2859 ig.Emit (OpCodes.Stloc, val);
2861 int section_count = Sections.Count;
2862 for (int section = 0; section < section_count; section++){
2863 SwitchSection ss = (SwitchSection) Sections [section];
2864 Label sec_begin = ig.DefineLabel ();
2866 if (pending_goto_end)
2867 ig.Emit (OpCodes.Br, end_of_switch);
2869 int label_count = ss.Labels.Count;
2870 bool mark_default = false;
2872 for (int label = 0; label < label_count; label++){
2873 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2874 ig.MarkLabel (sl.GetILLabel (ec));
2877 ig.MarkLabel (next_test);
2878 next_test = ig.DefineLabel ();
2881 // If we are the default target
2883 if (sl.Label == null){
2884 if (label+1 == label_count)
2885 default_at_end = true;
2886 mark_default = true;
2887 default_found = true;
2889 object lit = sl.Converted;
2891 if (lit is NullLiteral){
2893 if (label_count == 1)
2894 ig.Emit (OpCodes.Br, next_test);
2898 StringConstant str = (StringConstant) lit;
2900 ig.Emit (OpCodes.Ldloc, val);
2901 ig.Emit (OpCodes.Ldstr, str.Value);
2902 if (label_count == 1)
2903 ig.Emit (OpCodes.Bne_Un, next_test);
2905 if (label+1 == label_count)
2906 ig.Emit (OpCodes.Bne_Un, next_test);
2908 ig.Emit (OpCodes.Beq, sec_begin);
2913 ig.MarkLabel (null_target);
2914 ig.MarkLabel (sec_begin);
2915 foreach (SwitchLabel sl in ss.Labels)
2916 ig.MarkLabel (sl.GetILLabelCode (ec));
2919 ig.MarkLabel (default_target);
2921 pending_goto_end = !ss.Block.HasRet;
2924 ig.MarkLabel (next_test);
2926 if (!default_at_end)
2927 ig.Emit (OpCodes.Br, default_target);
2929 ig.MarkLabel (default_target);
2930 ig.MarkLabel (end_of_switch);
2933 SwitchSection FindSection (SwitchLabel label)
2935 foreach (SwitchSection ss in Sections){
2936 foreach (SwitchLabel sl in ss.Labels){
2945 bool ResolveConstantSwitch (EmitContext ec)
2947 object key = ((Constant) new_expr).GetValue ();
2948 SwitchLabel label = (SwitchLabel) Elements [key];
2953 constant_section = FindSection (label);
2954 if (constant_section == null)
2957 if (constant_section.Block.Resolve (ec) != true)
2963 public override bool Resolve (EmitContext ec)
2965 Expr = Expr.Resolve (ec);
2969 new_expr = SwitchGoverningType (ec, Expr.Type);
2970 if (new_expr == null){
2971 Report.Error (151, loc, "An integer type or string was expected for switch");
2976 SwitchType = new_expr.Type;
2978 if (!CheckSwitch (ec))
2981 Switch old_switch = ec.Switch;
2983 ec.Switch.SwitchType = SwitchType;
2985 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2986 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2988 is_constant = new_expr is Constant;
2990 object key = ((Constant) new_expr).GetValue ();
2991 SwitchLabel label = (SwitchLabel) Elements [key];
2993 constant_section = FindSection (label);
2997 foreach (SwitchSection ss in Sections){
2999 ec.CurrentBranching.CreateSibling (
3000 null, FlowBranching.SiblingType.SwitchSection);
3004 if (is_constant && (ss != constant_section)) {
3005 // If we're a constant switch, we're only emitting
3006 // one single section - mark all the others as
3008 ec.CurrentBranching.CurrentUsageVector.Goto ();
3009 if (!ss.Block.ResolveUnreachable (ec, true))
3012 if (!ss.Block.Resolve (ec))
3018 ec.CurrentBranching.CreateSibling (
3019 null, FlowBranching.SiblingType.SwitchSection);
3021 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3022 ec.Switch = old_switch;
3024 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3030 protected override void DoEmit (EmitContext ec)
3032 ILGenerator ig = ec.ig;
3034 // Store variable for comparission purposes
3037 value = ig.DeclareLocal (SwitchType);
3039 ig.Emit (OpCodes.Stloc, value);
3043 default_target = ig.DefineLabel ();
3046 // Setup the codegen context
3048 Label old_end = ec.LoopEnd;
3049 Switch old_switch = ec.Switch;
3051 ec.LoopEnd = ig.DefineLabel ();
3056 if (constant_section != null)
3057 constant_section.Block.Emit (ec);
3058 } else if (SwitchType == TypeManager.string_type)
3059 SimpleSwitchEmit (ec, value);
3061 TableSwitchEmit (ec, value);
3063 // Restore context state.
3064 ig.MarkLabel (ec.LoopEnd);
3067 // Restore the previous context
3069 ec.LoopEnd = old_end;
3070 ec.Switch = old_switch;
3074 public abstract class ExceptionStatement : Statement
3076 public abstract void EmitFinally (EmitContext ec);
3078 protected bool emit_finally = true;
3079 ArrayList parent_vectors;
3081 protected void DoEmitFinally (EmitContext ec)
3084 ec.ig.BeginFinallyBlock ();
3086 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3090 protected void ResolveFinally (FlowBranchingException branching)
3092 emit_finally = branching.EmitFinally;
3094 branching.Parent.StealFinallyClauses (ref parent_vectors);
3098 public class Lock : ExceptionStatement {
3100 Statement Statement;
3103 public Lock (Expression expr, Statement stmt, Location l)
3110 public override bool Resolve (EmitContext ec)
3112 expr = expr.Resolve (ec);
3116 if (expr.Type.IsValueType){
3117 Error (185, "lock statement requires the expression to be " +
3118 " a reference type (type is: `{0}'",
3119 TypeManager.CSharpName (expr.Type));
3123 FlowBranchingException branching = ec.StartFlowBranching (this);
3124 bool ok = Statement.Resolve (ec);
3126 ec.KillFlowBranching ();
3130 ResolveFinally (branching);
3132 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3133 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3134 // Unfortunately, System.Reflection.Emit automatically emits
3135 // a leave to the end of the finally block.
3136 // This is a problem if `returns' is true since we may jump
3137 // to a point after the end of the method.
3138 // As a workaround, emit an explicit ret here.
3139 ec.NeedReturnLabel ();
3145 protected override void DoEmit (EmitContext ec)
3147 Type type = expr.Type;
3149 ILGenerator ig = ec.ig;
3150 temp = ig.DeclareLocal (type);
3153 ig.Emit (OpCodes.Dup);
3154 ig.Emit (OpCodes.Stloc, temp);
3155 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3159 ig.BeginExceptionBlock ();
3160 Statement.Emit (ec);
3165 ig.EndExceptionBlock ();
3168 public override void EmitFinally (EmitContext ec)
3170 ILGenerator ig = ec.ig;
3171 ig.Emit (OpCodes.Ldloc, temp);
3172 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3176 public class Unchecked : Statement {
3177 public readonly Block Block;
3179 public Unchecked (Block b)
3185 public override bool Resolve (EmitContext ec)
3187 bool previous_state = ec.CheckState;
3188 bool previous_state_const = ec.ConstantCheckState;
3190 ec.CheckState = false;
3191 ec.ConstantCheckState = false;
3192 bool ret = Block.Resolve (ec);
3193 ec.CheckState = previous_state;
3194 ec.ConstantCheckState = previous_state_const;
3199 protected override void DoEmit (EmitContext ec)
3201 bool previous_state = ec.CheckState;
3202 bool previous_state_const = ec.ConstantCheckState;
3204 ec.CheckState = false;
3205 ec.ConstantCheckState = false;
3207 ec.CheckState = previous_state;
3208 ec.ConstantCheckState = previous_state_const;
3212 public class Checked : Statement {
3213 public readonly Block Block;
3215 public Checked (Block b)
3218 b.Unchecked = false;
3221 public override bool Resolve (EmitContext ec)
3223 bool previous_state = ec.CheckState;
3224 bool previous_state_const = ec.ConstantCheckState;
3226 ec.CheckState = true;
3227 ec.ConstantCheckState = true;
3228 bool ret = Block.Resolve (ec);
3229 ec.CheckState = previous_state;
3230 ec.ConstantCheckState = previous_state_const;
3235 protected override void DoEmit (EmitContext ec)
3237 bool previous_state = ec.CheckState;
3238 bool previous_state_const = ec.ConstantCheckState;
3240 ec.CheckState = true;
3241 ec.ConstantCheckState = true;
3243 ec.CheckState = previous_state;
3244 ec.ConstantCheckState = previous_state_const;
3248 public class Unsafe : Statement {
3249 public readonly Block Block;
3251 public Unsafe (Block b)
3254 Block.Unsafe = true;
3257 public override bool Resolve (EmitContext ec)
3259 bool previous_state = ec.InUnsafe;
3263 val = Block.Resolve (ec);
3264 ec.InUnsafe = previous_state;
3269 protected override void DoEmit (EmitContext ec)
3271 bool previous_state = ec.InUnsafe;
3275 ec.InUnsafe = previous_state;
3282 public class Fixed : Statement {
3284 ArrayList declarators;
3285 Statement statement;
3291 public bool is_object;
3292 public LocalInfo vi;
3293 public Expression expr;
3294 public Expression converted;
3297 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3300 declarators = decls;
3305 public override bool Resolve (EmitContext ec)
3308 Expression.UnsafeError (loc);
3312 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3316 expr_type = texpr.Type;
3318 CheckObsolete (expr_type);
3320 if (ec.RemapToProxy){
3321 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3325 data = new FixedData [declarators.Count];
3327 if (!expr_type.IsPointer){
3328 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3333 foreach (Pair p in declarators){
3334 LocalInfo vi = (LocalInfo) p.First;
3335 Expression e = (Expression) p.Second;
3337 vi.VariableInfo.SetAssigned (ec);
3341 // The rules for the possible declarators are pretty wise,
3342 // but the production on the grammar is more concise.
3344 // So we have to enforce these rules here.
3346 // We do not resolve before doing the case 1 test,
3347 // because the grammar is explicit in that the token &
3348 // is present, so we need to test for this particular case.
3352 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3357 // Case 1: & object.
3359 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3360 Expression child = ((Unary) e).Expr;
3362 if (child is ParameterReference || child is LocalVariableReference){
3365 "No need to use fixed statement for parameters or " +
3366 "local variable declarations (address is already " +
3371 ec.InFixedInitializer = true;
3373 ec.InFixedInitializer = false;
3377 child = ((Unary) e).Expr;
3379 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3382 data [i].is_object = true;
3384 data [i].converted = null;
3391 ec.InFixedInitializer = true;
3393 ec.InFixedInitializer = false;
3400 if (e.Type.IsArray){
3401 Type array_type = TypeManager.GetElementType (e.Type);
3404 // Provided that array_type is unmanaged,
3406 if (!TypeManager.VerifyUnManaged (array_type, loc))
3410 // and T* is implicitly convertible to the
3411 // pointer type given in the fixed statement.
3413 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3415 Expression converted = Convert.ImplicitConversionRequired (
3416 ec, array_ptr, vi.VariableType, loc);
3417 if (converted == null)
3420 data [i].is_object = false;
3422 data [i].converted = converted;
3432 if (e.Type == TypeManager.string_type){
3433 data [i].is_object = false;
3435 data [i].converted = null;
3442 // For other cases, flag a `this is already fixed expression'
3444 if (e is LocalVariableReference || e is ParameterReference ||
3445 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3447 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3451 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3455 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3457 if (!statement.Resolve (ec)) {
3458 ec.KillFlowBranching ();
3462 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3463 has_ret = reachability.IsUnreachable;
3468 protected override void DoEmit (EmitContext ec)
3470 ILGenerator ig = ec.ig;
3472 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3474 for (int i = 0; i < data.Length; i++) {
3475 LocalInfo vi = data [i].vi;
3478 // Case 1: & object.
3480 if (data [i].is_object) {
3482 // Store pointer in pinned location
3484 data [i].expr.Emit (ec);
3485 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3486 clear_list [i] = vi.LocalBuilder;
3493 if (data [i].expr.Type.IsArray){
3495 // Store pointer in pinned location
3497 data [i].converted.Emit (ec);
3499 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3500 clear_list [i] = vi.LocalBuilder;
3507 if (data [i].expr.Type == TypeManager.string_type){
3508 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3509 clear_list [i] = pinned_string;
3511 data [i].expr.Emit (ec);
3512 ig.Emit (OpCodes.Stloc, pinned_string);
3514 Expression sptr = new StringPtr (pinned_string, loc);
3515 Expression converted = Convert.ImplicitConversionRequired (
3516 ec, sptr, vi.VariableType, loc);
3518 if (converted == null)
3521 converted.Emit (ec);
3522 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3526 statement.Emit (ec);
3532 // Clear the pinned variable
3534 for (int i = 0; i < data.Length; i++) {
3535 if (data [i].is_object || data [i].expr.Type.IsArray) {
3536 ig.Emit (OpCodes.Ldc_I4_0);
3537 ig.Emit (OpCodes.Conv_U);
3538 ig.Emit (OpCodes.Stloc, clear_list [i]);
3539 } else if (data [i].expr.Type == TypeManager.string_type){
3540 ig.Emit (OpCodes.Ldnull);
3541 ig.Emit (OpCodes.Stloc, clear_list [i]);
3547 public class Catch: Statement {
3548 public readonly string Name;
3549 public readonly Block Block;
3551 Expression type_expr;
3554 public Catch (Expression type, string name, Block block, Location l)
3562 public Type CatchType {
3568 public bool IsGeneral {
3570 return type_expr == null;
3574 protected override void DoEmit(EmitContext ec)
3578 public override bool Resolve (EmitContext ec)
3580 if (type_expr != null) {
3581 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3587 CheckObsolete (type);
3589 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3590 Error (155, "The type caught or thrown must be derived from System.Exception");
3596 return Block.Resolve (ec);
3600 public class Try : ExceptionStatement {
3601 public readonly Block Fini, Block;
3602 public readonly ArrayList Specific;
3603 public readonly Catch General;
3605 bool need_exc_block;
3608 // specific, general and fini might all be null.
3610 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3612 if (specific == null && general == null){
3613 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3617 this.Specific = specific;
3618 this.General = general;
3623 public override bool Resolve (EmitContext ec)
3627 FlowBranchingException branching = ec.StartFlowBranching (this);
3629 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3631 if (!Block.Resolve (ec))
3634 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3636 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3638 Type[] prevCatches = new Type [Specific.Count];
3640 foreach (Catch c in Specific){
3641 ec.CurrentBranching.CreateSibling (
3642 c.Block, FlowBranching.SiblingType.Catch);
3644 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3646 if (c.Name != null) {
3647 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3649 throw new Exception ();
3651 vi.VariableInfo = null;
3654 if (!c.Resolve (ec))
3657 Type resolvedType = c.CatchType;
3658 for (int ii = 0; ii < last_index; ++ii) {
3659 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3660 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3665 prevCatches [last_index++] = resolvedType;
3666 need_exc_block = true;
3669 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3671 if (General != null){
3672 ec.CurrentBranching.CreateSibling (
3673 General.Block, FlowBranching.SiblingType.Catch);
3675 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3677 if (!General.Resolve (ec))
3680 need_exc_block = true;
3683 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3687 ec.CurrentBranching.CreateSibling (
3688 Fini, FlowBranching.SiblingType.Finally);
3690 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3692 if (!Fini.Resolve (ec))
3696 ResolveFinally (branching);
3697 need_exc_block |= emit_finally;
3699 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3701 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3703 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3705 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3706 // Unfortunately, System.Reflection.Emit automatically emits
3707 // a leave to the end of the finally block. This is a problem
3708 // if `returns' is true since we may jump to a point after the
3709 // end of the method.
3710 // As a workaround, emit an explicit ret here.
3711 ec.NeedReturnLabel ();
3717 protected override void DoEmit (EmitContext ec)
3719 ILGenerator ig = ec.ig;
3722 ig.BeginExceptionBlock ();
3725 foreach (Catch c in Specific){
3728 ig.BeginCatchBlock (c.CatchType);
3730 if (c.Name != null){
3731 vi = c.Block.GetLocalInfo (c.Name);
3733 throw new Exception ("Variable does not exist in this block");
3735 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3737 ig.Emit (OpCodes.Pop);
3742 if (General != null){
3743 ig.BeginCatchBlock (TypeManager.object_type);
3744 ig.Emit (OpCodes.Pop);
3745 General.Block.Emit (ec);
3750 ig.EndExceptionBlock ();
3753 public override void EmitFinally (EmitContext ec)
3761 public class Using : ExceptionStatement {
3762 object expression_or_block;
3763 Statement Statement;
3768 Expression [] resolved_vars;
3769 Expression [] converted_vars;
3770 ExpressionStatement [] assign;
3771 LocalBuilder local_copy;
3773 public Using (object expression_or_block, Statement stmt, Location l)
3775 this.expression_or_block = expression_or_block;
3781 // Resolves for the case of using using a local variable declaration.
3783 bool ResolveLocalVariableDecls (EmitContext ec)
3787 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3791 expr_type = texpr.Type;
3794 // The type must be an IDisposable or an implicit conversion
3797 converted_vars = new Expression [var_list.Count];
3798 resolved_vars = new Expression [var_list.Count];
3799 assign = new ExpressionStatement [var_list.Count];
3801 bool need_conv = !TypeManager.ImplementsInterface (
3802 expr_type, TypeManager.idisposable_type);
3804 foreach (DictionaryEntry e in var_list){
3805 Expression var = (Expression) e.Key;
3807 var = var.ResolveLValue (ec, new EmptyExpression ());
3811 resolved_vars [i] = var;
3818 converted_vars [i] = Convert.ImplicitConversionRequired (
3819 ec, var, TypeManager.idisposable_type, loc);
3821 if (converted_vars [i] == null)
3828 foreach (DictionaryEntry e in var_list){
3829 Expression var = resolved_vars [i];
3830 Expression new_expr = (Expression) e.Value;
3833 a = new Assign (var, new_expr, loc);
3839 converted_vars [i] = var;
3840 assign [i] = (ExpressionStatement) a;
3847 bool ResolveExpression (EmitContext ec)
3849 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3850 conv = Convert.ImplicitConversionRequired (
3851 ec, expr, TypeManager.idisposable_type, loc);
3861 // Emits the code for the case of using using a local variable declaration.
3863 void EmitLocalVariableDecls (EmitContext ec)
3865 ILGenerator ig = ec.ig;
3868 for (i = 0; i < assign.Length; i++) {
3869 assign [i].EmitStatement (ec);
3872 ig.BeginExceptionBlock ();
3874 Statement.Emit (ec);
3876 var_list.Reverse ();
3881 void EmitLocalVariableDeclFinally (EmitContext ec)
3883 ILGenerator ig = ec.ig;
3885 int i = assign.Length;
3886 foreach (DictionaryEntry e in var_list){
3887 Expression var = resolved_vars [--i];
3888 Label skip = ig.DefineLabel ();
3890 ig.BeginFinallyBlock ();
3892 if (!var.Type.IsValueType) {
3894 ig.Emit (OpCodes.Brfalse, skip);
3895 converted_vars [i].Emit (ec);
3896 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3898 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3900 if (!(ml is MethodGroupExpr)) {
3902 ig.Emit (OpCodes.Box, var.Type);
3903 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3905 MethodInfo mi = null;
3907 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3908 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3915 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3919 IMemoryLocation mloc = (IMemoryLocation) var;
3921 mloc.AddressOf (ec, AddressOp.Load);
3922 ig.Emit (OpCodes.Call, mi);
3926 ig.MarkLabel (skip);
3929 ig.EndExceptionBlock ();
3931 ig.BeginFinallyBlock ();
3936 void EmitExpression (EmitContext ec)
3939 // Make a copy of the expression and operate on that.
3941 ILGenerator ig = ec.ig;
3942 local_copy = ig.DeclareLocal (expr_type);
3947 ig.Emit (OpCodes.Stloc, local_copy);
3950 ig.BeginExceptionBlock ();
3952 Statement.Emit (ec);
3956 ig.EndExceptionBlock ();
3959 void EmitExpressionFinally (EmitContext ec)
3961 ILGenerator ig = ec.ig;
3962 if (!local_copy.LocalType.IsValueType) {
3963 Label skip = ig.DefineLabel ();
3964 ig.Emit (OpCodes.Ldloc, local_copy);
3965 ig.Emit (OpCodes.Brfalse, skip);
3966 ig.Emit (OpCodes.Ldloc, local_copy);
3967 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3968 ig.MarkLabel (skip);
3970 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
3972 if (!(ml is MethodGroupExpr)) {
3973 ig.Emit (OpCodes.Ldloc, local_copy);
3974 ig.Emit (OpCodes.Box, local_copy.LocalType);
3975 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3977 MethodInfo mi = null;
3979 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3980 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3987 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3991 ig.Emit (OpCodes.Ldloca, local_copy);
3992 ig.Emit (OpCodes.Call, mi);
3997 public override bool Resolve (EmitContext ec)
3999 if (expression_or_block is DictionaryEntry){
4000 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4001 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4003 if (!ResolveLocalVariableDecls (ec))
4006 } else if (expression_or_block is Expression){
4007 expr = (Expression) expression_or_block;
4009 expr = expr.Resolve (ec);
4013 expr_type = expr.Type;
4015 if (!ResolveExpression (ec))
4019 FlowBranchingException branching = ec.StartFlowBranching (this);
4021 bool ok = Statement.Resolve (ec);
4024 ec.KillFlowBranching ();
4028 ResolveFinally (branching);
4029 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4031 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4032 // Unfortunately, System.Reflection.Emit automatically emits a leave
4033 // to the end of the finally block. This is a problem if `returns'
4034 // is true since we may jump to a point after the end of the method.
4035 // As a workaround, emit an explicit ret here.
4036 ec.NeedReturnLabel ();
4042 protected override void DoEmit (EmitContext ec)
4044 if (expression_or_block is DictionaryEntry)
4045 EmitLocalVariableDecls (ec);
4046 else if (expression_or_block is Expression)
4047 EmitExpression (ec);
4050 public override void EmitFinally (EmitContext ec)
4052 if (expression_or_block is DictionaryEntry)
4053 EmitLocalVariableDeclFinally (ec);
4054 else if (expression_or_block is Expression)
4055 EmitExpressionFinally (ec);
4060 /// Implementation of the foreach C# statement
4062 public class Foreach : ExceptionStatement {
4064 Expression variable;
4066 Statement statement;
4067 ForeachHelperMethods hm;
4068 Expression empty, conv;
4069 Type array_type, element_type;
4071 VariableStorage enumerator;
4073 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4074 Statement stmt, Location l)
4077 this.variable = var;
4083 public override bool Resolve (EmitContext ec)
4085 expr = expr.Resolve (ec);
4089 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4093 var_type = texpr.Type;
4096 // We need an instance variable. Not sure this is the best
4097 // way of doing this.
4099 // FIXME: When we implement propertyaccess, will those turn
4100 // out to return values in ExprClass? I think they should.
4102 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4103 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4104 error1579 (expr.Type);
4108 if (expr.Type.IsArray) {
4109 array_type = expr.Type;
4110 element_type = TypeManager.GetElementType (array_type);
4112 empty = new EmptyExpression (element_type);
4114 hm = ProbeCollectionType (ec, expr.Type);
4116 error1579 (expr.Type);
4120 array_type = expr.Type;
4121 element_type = hm.element_type;
4123 empty = new EmptyExpression (hm.element_type);
4128 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4129 ec.CurrentBranching.CreateSibling ();
4133 // FIXME: maybe we can apply the same trick we do in the
4134 // array handling to avoid creating empty and conv in some cases.
4136 // Although it is not as important in this case, as the type
4137 // will not likely be object (what the enumerator will return).
4139 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4143 variable = variable.ResolveLValue (ec, empty);
4144 if (variable == null)
4147 bool disposable = (hm != null) && hm.is_disposable;
4148 FlowBranchingException branching = null;
4150 branching = ec.StartFlowBranching (this);
4152 if (!statement.Resolve (ec))
4156 ResolveFinally (branching);
4157 ec.EndFlowBranching ();
4159 emit_finally = true;
4161 ec.EndFlowBranching ();
4167 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4169 static MethodInfo FetchMethodMoveNext (Type t)
4171 MemberList move_next_list;
4173 move_next_list = TypeContainer.FindMembers (
4174 t, MemberTypes.Method,
4175 BindingFlags.Public | BindingFlags.Instance,
4176 Type.FilterName, "MoveNext");
4177 if (move_next_list.Count == 0)
4180 foreach (MemberInfo m in move_next_list){
4181 MethodInfo mi = (MethodInfo) m;
4184 args = TypeManager.GetArgumentTypes (mi);
4185 if (args != null && args.Length == 0){
4186 if (TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type)
4194 // Retrieves a `public T get_Current ()' method from the Type `t'
4196 static MethodInfo FetchMethodGetCurrent (Type t)
4198 MemberList get_current_list;
4200 get_current_list = TypeContainer.FindMembers (
4201 t, MemberTypes.Method,
4202 BindingFlags.Public | BindingFlags.Instance,
4203 Type.FilterName, "get_Current");
4204 if (get_current_list.Count == 0)
4207 foreach (MemberInfo m in get_current_list){
4208 MethodInfo mi = (MethodInfo) m;
4211 args = TypeManager.GetArgumentTypes (mi);
4212 if (args != null && args.Length == 0)
4219 // Retrieves a `public void Dispose ()' method from the Type `t'
4221 static MethodInfo FetchMethodDispose (Type t)
4223 MemberList dispose_list;
4225 dispose_list = TypeContainer.FindMembers (
4226 t, MemberTypes.Method,
4227 BindingFlags.Public | BindingFlags.Instance,
4228 Type.FilterName, "Dispose");
4229 if (dispose_list.Count == 0)
4232 foreach (MemberInfo m in dispose_list){
4233 MethodInfo mi = (MethodInfo) m;
4236 args = TypeManager.GetArgumentTypes (mi);
4237 if (args != null && args.Length == 0){
4238 if (mi.ReturnType == TypeManager.void_type)
4246 // This struct records the helper methods used by the Foreach construct
4248 class ForeachHelperMethods {
4249 public EmitContext ec;
4250 public MethodInfo get_enumerator;
4251 public MethodInfo move_next;
4252 public MethodInfo get_current;
4253 public Type element_type;
4254 public Type enumerator_type;
4255 public bool is_disposable;
4257 public ForeachHelperMethods (EmitContext ec)
4260 this.element_type = TypeManager.object_type;
4261 this.enumerator_type = TypeManager.ienumerator_type;
4262 this.is_disposable = true;
4266 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4271 if (!(m is MethodInfo))
4274 if (m.Name != "GetEnumerator")
4277 MethodInfo mi = (MethodInfo) m;
4278 Type [] args = TypeManager.GetArgumentTypes (mi);
4280 if (args.Length != 0)
4283 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4284 EmitContext ec = hm.ec;
4286 // Check whether GetEnumerator is public
4287 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4290 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4292 // Apply the same optimization as MS: skip the GetEnumerator
4293 // returning an IEnumerator, and use the one returning a
4294 // CharEnumerator instead. This allows us to avoid the
4295 // try-finally block and the boxing.
4300 // Ok, we can access it, now make sure that we can do something
4301 // with this `GetEnumerator'
4304 Type return_type = mi.ReturnType;
4305 if (mi.ReturnType == TypeManager.ienumerator_type ||
4306 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4307 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4310 // If it is not an interface, lets try to find the methods ourselves.
4311 // For example, if we have:
4312 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4313 // We can avoid the iface call. This is a runtime perf boost.
4314 // even bigger if we have a ValueType, because we avoid the cost
4317 // We have to make sure that both methods exist for us to take
4318 // this path. If one of the methods does not exist, we will just
4319 // use the interface. Sadly, this complex if statement is the only
4320 // way I could do this without a goto
4323 if (return_type.IsInterface ||
4324 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4325 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4327 hm.move_next = TypeManager.bool_movenext_void;
4328 hm.get_current = TypeManager.object_getcurrent_void;
4335 // Ok, so they dont return an IEnumerable, we will have to
4336 // find if they support the GetEnumerator pattern.
4339 hm.move_next = FetchMethodMoveNext (return_type);
4340 if (hm.move_next == null)
4343 hm.get_current = FetchMethodGetCurrent (return_type);
4344 if (hm.get_current == null)
4348 hm.element_type = hm.get_current.ReturnType;
4349 hm.enumerator_type = return_type;
4350 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4351 TypeManager.ImplementsInterface (
4352 hm.enumerator_type, TypeManager.idisposable_type);
4358 /// This filter is used to find the GetEnumerator method
4359 /// on which IEnumerator operates
4361 static MemberFilter FilterEnumerator;
4365 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4368 void error1579 (Type t)
4370 Report.Error (1579, loc,
4371 "foreach statement cannot operate on variables of type `" +
4372 t.FullName + "' because that class does not provide a " +
4373 " GetEnumerator method or it is inaccessible");
4376 static bool TryType (Type t, ForeachHelperMethods hm)
4380 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4381 BindingFlags.Public | BindingFlags.NonPublic |
4382 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4383 FilterEnumerator, hm);
4388 hm.get_enumerator = (MethodInfo) mi [0];
4393 // Looks for a usable GetEnumerator in the Type, and if found returns
4394 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4396 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4398 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4400 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4401 if (TryType (tt, hm))
4407 // Now try to find the method in the interfaces
4410 Type [] ifaces = t.GetInterfaces ();
4412 foreach (Type i in ifaces){
4413 if (TryType (i, hm))
4418 // Since TypeBuilder.GetInterfaces only returns the interface
4419 // types for this type, we have to keep looping, but once
4420 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4421 // done, because it returns all the types
4423 if ((t is TypeBuilder))
4433 // FIXME: possible optimization.
4434 // We might be able to avoid creating `empty' if the type is the sam
4436 bool EmitCollectionForeach (EmitContext ec)
4438 ILGenerator ig = ec.ig;
4440 enumerator = new VariableStorage (ec, hm.enumerator_type);
4441 enumerator.EmitThis (ig);
4443 // Instantiate the enumerator
4445 if (expr.Type.IsValueType){
4446 IMemoryLocation ml = expr as IMemoryLocation;
4447 // Load the address of the value type.
4449 // This happens if, for example, you have a property
4450 // returning a struct which is IEnumerable
4451 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4453 ig.Emit (OpCodes.Stloc, t);
4454 ig.Emit (OpCodes.Ldloca, t);
4455 ec.FreeTemporaryLocal (t, expr.Type);
4457 ml.AddressOf (ec, AddressOp.Load);
4461 if (hm.get_enumerator.DeclaringType.IsValueType) {
4462 // the method is declared on the value type
4463 ig.Emit (OpCodes.Call, hm.get_enumerator);
4465 // it is an interface method, so we must box
4466 ig.Emit (OpCodes.Box, expr.Type);
4467 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4471 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4473 enumerator.EmitStore (ig);
4476 // Protect the code in a try/finalize block, so that
4477 // if the beast implement IDisposable, we get rid of it
4479 if (hm.is_disposable && emit_finally)
4480 ig.BeginExceptionBlock ();
4482 Label end_try = ig.DefineLabel ();
4484 ig.MarkLabel (ec.LoopBegin);
4486 enumerator.EmitCall (ig, hm.move_next);
4488 ig.Emit (OpCodes.Brfalse, end_try);
4491 enumerator.EmitThis (ig);
4492 enumerator.EmitCall (ig, hm.get_current);
4496 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4498 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4500 statement.Emit (ec);
4501 ig.Emit (OpCodes.Br, ec.LoopBegin);
4502 ig.MarkLabel (end_try);
4504 // The runtime provides this for us.
4505 // ig.Emit (OpCodes.Leave, end);
4508 // Now the finally block
4510 if (hm.is_disposable) {
4513 ig.EndExceptionBlock ();
4516 ig.MarkLabel (ec.LoopEnd);
4520 public override void EmitFinally (EmitContext ec)
4522 ILGenerator ig = ec.ig;
4524 if (hm.enumerator_type.IsValueType) {
4525 enumerator.EmitThis (ig);
4527 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4529 enumerator.EmitLoadAddress (ig);
4530 ig.Emit (OpCodes.Call, mi);
4532 enumerator.EmitLoad (ig);
4533 ig.Emit (OpCodes.Box, hm.enumerator_type);
4534 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4537 Label call_dispose = ig.DefineLabel ();
4539 enumerator.EmitThis (ig);
4540 enumerator.EmitLoad (ig);
4541 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4542 ig.Emit (OpCodes.Dup);
4543 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4544 ig.Emit (OpCodes.Pop);
4546 Label end_finally = ig.DefineLabel ();
4547 ig.Emit (OpCodes.Br, end_finally);
4549 ig.MarkLabel (call_dispose);
4550 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4551 ig.MarkLabel (end_finally);
4554 ig.Emit (OpCodes.Endfinally);
4559 // FIXME: possible optimization.
4560 // We might be able to avoid creating `empty' if the type is the sam
4562 bool EmitArrayForeach (EmitContext ec)
4564 int rank = array_type.GetArrayRank ();
4565 ILGenerator ig = ec.ig;
4567 VariableStorage copy = new VariableStorage (ec, array_type);
4570 // Make our copy of the array
4574 copy.EmitStore (ig);
4577 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4581 counter.EmitThis (ig);
4582 ig.Emit (OpCodes.Ldc_I4_0);
4583 counter.EmitStore (ig);
4584 test = ig.DefineLabel ();
4585 ig.Emit (OpCodes.Br, test);
4587 loop = ig.DefineLabel ();
4588 ig.MarkLabel (loop);
4595 counter.EmitThis (ig);
4596 counter.EmitLoad (ig);
4599 // Load the value, we load the value using the underlying type,
4600 // then we use the variable.EmitAssign to load using the proper cast.
4602 ArrayAccess.EmitLoadOpcode (ig, element_type);
4605 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4607 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4609 statement.Emit (ec);
4611 ig.MarkLabel (ec.LoopBegin);
4612 counter.EmitThis (ig);
4613 counter.EmitThis (ig);
4614 counter.EmitLoad (ig);
4615 ig.Emit (OpCodes.Ldc_I4_1);
4616 ig.Emit (OpCodes.Add);
4617 counter.EmitStore (ig);
4619 ig.MarkLabel (test);
4620 counter.EmitThis (ig);
4621 counter.EmitLoad (ig);
4624 ig.Emit (OpCodes.Ldlen);
4625 ig.Emit (OpCodes.Conv_I4);
4626 ig.Emit (OpCodes.Blt, loop);
4628 VariableStorage [] dim_len = new VariableStorage [rank];
4629 VariableStorage [] dim_count = new VariableStorage [rank];
4630 Label [] loop = new Label [rank];
4631 Label [] test = new Label [rank];
4634 for (dim = 0; dim < rank; dim++){
4635 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4636 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4637 test [dim] = ig.DefineLabel ();
4638 loop [dim] = ig.DefineLabel ();
4641 for (dim = 0; dim < rank; dim++){
4642 dim_len [dim].EmitThis (ig);
4645 IntLiteral.EmitInt (ig, dim);
4646 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4647 dim_len [dim].EmitStore (ig);
4651 for (dim = 0; dim < rank; dim++){
4652 dim_count [dim].EmitThis (ig);
4653 ig.Emit (OpCodes.Ldc_I4_0);
4654 dim_count [dim].EmitStore (ig);
4655 ig.Emit (OpCodes.Br, test [dim]);
4656 ig.MarkLabel (loop [dim]);
4663 for (dim = 0; dim < rank; dim++){
4664 dim_count [dim].EmitThis (ig);
4665 dim_count [dim].EmitLoad (ig);
4669 // FIXME: Maybe we can cache the computation of `get'?
4671 Type [] args = new Type [rank];
4674 for (int i = 0; i < rank; i++)
4675 args [i] = TypeManager.int32_type;
4677 ModuleBuilder mb = CodeGen.Module.Builder;
4678 get = mb.GetArrayMethod (
4680 CallingConventions.HasThis| CallingConventions.Standard,
4682 ig.Emit (OpCodes.Call, get);
4685 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4687 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4688 statement.Emit (ec);
4689 ig.MarkLabel (ec.LoopBegin);
4690 for (dim = rank - 1; dim >= 0; dim--){
4691 dim_count [dim].EmitThis (ig);
4692 dim_count [dim].EmitThis (ig);
4693 dim_count [dim].EmitLoad (ig);
4694 ig.Emit (OpCodes.Ldc_I4_1);
4695 ig.Emit (OpCodes.Add);
4696 dim_count [dim].EmitStore (ig);
4698 ig.MarkLabel (test [dim]);
4699 dim_count [dim].EmitThis (ig);
4700 dim_count [dim].EmitLoad (ig);
4701 dim_len [dim].EmitThis (ig);
4702 dim_len [dim].EmitLoad (ig);
4703 ig.Emit (OpCodes.Blt, loop [dim]);
4706 ig.MarkLabel (ec.LoopEnd);
4711 protected override void DoEmit (EmitContext ec)
4713 ILGenerator ig = ec.ig;
4715 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4716 ec.LoopBegin = ig.DefineLabel ();
4717 ec.LoopEnd = ig.DefineLabel ();
4720 EmitCollectionForeach (ec);
4722 EmitArrayForeach (ec);
4724 ec.LoopBegin = old_begin;
4725 ec.LoopEnd = old_end;