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 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
50 bool ok = Resolve (ec);
51 ec.KillFlowBranching ();
56 if (warn && (RootContext.WarningLevel >= 2))
57 Report.Warning (162, loc, "Unreachable code detected");
61 protected void CheckObsolete (Type type)
63 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
64 if (obsolete_attr == null)
67 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
71 /// Return value indicates whether all code paths emitted return.
73 protected abstract void DoEmit (EmitContext ec);
76 /// Utility wrapper routine for Error, just to beautify the code
78 public void Error (int error, string format, params object[] args)
80 Error (error, String.Format (format, args));
83 public void Error (int error, string s)
85 if (!Location.IsNull (loc))
86 Report.Error (error, loc, s);
88 Report.Error (error, s);
92 /// Return value indicates whether all code paths emitted return.
94 public virtual void Emit (EmitContext ec)
101 public sealed class EmptyStatement : Statement {
103 private EmptyStatement () {}
105 public static readonly EmptyStatement Value = new EmptyStatement ();
107 public override bool Resolve (EmitContext ec)
112 protected override void DoEmit (EmitContext ec)
117 public class If : Statement {
119 public Statement TrueStatement;
120 public Statement FalseStatement;
124 public If (Expression expr, Statement trueStatement, Location l)
127 TrueStatement = trueStatement;
131 public If (Expression expr,
132 Statement trueStatement,
133 Statement falseStatement,
137 TrueStatement = trueStatement;
138 FalseStatement = falseStatement;
142 public override bool Resolve (EmitContext ec)
144 Report.Debug (1, "START IF BLOCK", loc);
146 expr = Expression.ResolveBoolean (ec, expr, loc);
152 // Dead code elimination
154 if (expr is BoolConstant){
155 bool take = ((BoolConstant) expr).Value;
158 if (!TrueStatement.Resolve (ec))
161 if ((FalseStatement != null) &&
162 !FalseStatement.ResolveUnreachable (ec, true))
164 FalseStatement = null;
166 if (!TrueStatement.ResolveUnreachable (ec, true))
168 TrueStatement = null;
170 if ((FalseStatement != null) &&
171 !FalseStatement.Resolve (ec))
178 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
180 bool ok = TrueStatement.Resolve (ec);
182 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
184 ec.CurrentBranching.CreateSibling ();
186 if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
189 ec.EndFlowBranching ();
191 Report.Debug (1, "END IF BLOCK", loc);
196 protected override void DoEmit (EmitContext ec)
198 ILGenerator ig = ec.ig;
199 Label false_target = ig.DefineLabel ();
203 // If we're a boolean expression, Resolve() already
204 // eliminated dead code for us.
206 if (expr is BoolConstant){
207 bool take = ((BoolConstant) expr).Value;
210 TrueStatement.Emit (ec);
211 else if (FalseStatement != null)
212 FalseStatement.Emit (ec);
217 expr.EmitBranchable (ec, false_target, false);
219 TrueStatement.Emit (ec);
221 if (FalseStatement != null){
222 bool branch_emitted = false;
224 end = ig.DefineLabel ();
226 ig.Emit (OpCodes.Br, end);
227 branch_emitted = true;
230 ig.MarkLabel (false_target);
231 FalseStatement.Emit (ec);
236 ig.MarkLabel (false_target);
241 public class Do : Statement {
242 public Expression expr;
243 public readonly Statement EmbeddedStatement;
246 public Do (Statement statement, Expression boolExpr, Location l)
249 EmbeddedStatement = statement;
253 public override bool Resolve (EmitContext ec)
257 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
259 if (!EmbeddedStatement.Resolve (ec))
262 expr = Expression.ResolveBoolean (ec, expr, loc);
265 else if (expr is BoolConstant){
266 bool res = ((BoolConstant) expr).Value;
272 ec.CurrentBranching.Infinite = infinite;
273 ec.EndFlowBranching ();
278 protected override void DoEmit (EmitContext ec)
280 ILGenerator ig = ec.ig;
281 Label loop = ig.DefineLabel ();
282 Label old_begin = ec.LoopBegin;
283 Label old_end = ec.LoopEnd;
285 ec.LoopBegin = ig.DefineLabel ();
286 ec.LoopEnd = ig.DefineLabel ();
289 EmbeddedStatement.Emit (ec);
290 ig.MarkLabel (ec.LoopBegin);
293 // Dead code elimination
295 if (expr is BoolConstant){
296 bool res = ((BoolConstant) expr).Value;
299 ec.ig.Emit (OpCodes.Br, loop);
301 expr.EmitBranchable (ec, loop, true);
303 ig.MarkLabel (ec.LoopEnd);
305 ec.LoopBegin = old_begin;
306 ec.LoopEnd = old_end;
310 public class While : Statement {
311 public Expression expr;
312 public readonly Statement Statement;
313 bool infinite, empty;
315 public While (Expression boolExpr, Statement statement, Location l)
317 this.expr = boolExpr;
318 Statement = statement;
322 public override bool Resolve (EmitContext ec)
326 expr = Expression.ResolveBoolean (ec, expr, loc);
331 // Inform whether we are infinite or not
333 if (expr is BoolConstant){
334 BoolConstant bc = (BoolConstant) expr;
336 if (bc.Value == false){
337 if (!Statement.ResolveUnreachable (ec, true))
345 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
347 if (!Statement.Resolve (ec))
350 ec.CurrentBranching.Infinite = infinite;
351 ec.EndFlowBranching ();
356 protected override void DoEmit (EmitContext ec)
361 ILGenerator ig = ec.ig;
362 Label old_begin = ec.LoopBegin;
363 Label old_end = ec.LoopEnd;
365 ec.LoopBegin = ig.DefineLabel ();
366 ec.LoopEnd = ig.DefineLabel ();
369 // Inform whether we are infinite or not
371 if (expr is BoolConstant){
372 ig.MarkLabel (ec.LoopBegin);
374 ig.Emit (OpCodes.Br, ec.LoopBegin);
377 // Inform that we are infinite (ie, `we return'), only
378 // if we do not `break' inside the code.
380 ig.MarkLabel (ec.LoopEnd);
382 Label while_loop = ig.DefineLabel ();
384 ig.Emit (OpCodes.Br, ec.LoopBegin);
385 ig.MarkLabel (while_loop);
389 ig.MarkLabel (ec.LoopBegin);
391 expr.EmitBranchable (ec, while_loop, true);
393 ig.MarkLabel (ec.LoopEnd);
396 ec.LoopBegin = old_begin;
397 ec.LoopEnd = old_end;
401 public class For : Statement {
403 readonly Statement InitStatement;
404 readonly Statement Increment;
405 readonly Statement Statement;
406 bool infinite, empty;
408 public For (Statement initStatement,
414 InitStatement = initStatement;
416 Increment = increment;
417 Statement = statement;
421 public override bool Resolve (EmitContext ec)
425 if (InitStatement != null){
426 if (!InitStatement.Resolve (ec))
431 Test = Expression.ResolveBoolean (ec, Test, loc);
434 else if (Test is BoolConstant){
435 BoolConstant bc = (BoolConstant) Test;
437 if (bc.Value == false){
438 if (!Statement.ResolveUnreachable (ec, true))
440 if ((Increment != null) &&
441 !Increment.ResolveUnreachable (ec, false))
451 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
453 ec.CurrentBranching.CreateSibling ();
455 if (!Statement.Resolve (ec))
458 if (Increment != null){
459 if (!Increment.Resolve (ec))
463 ec.CurrentBranching.Infinite = infinite;
464 ec.EndFlowBranching ();
469 protected override void DoEmit (EmitContext ec)
474 ILGenerator ig = ec.ig;
475 Label old_begin = ec.LoopBegin;
476 Label old_end = ec.LoopEnd;
477 Label loop = ig.DefineLabel ();
478 Label test = ig.DefineLabel ();
480 if (InitStatement != null && InitStatement != EmptyStatement.Value)
481 InitStatement.Emit (ec);
483 ec.LoopBegin = ig.DefineLabel ();
484 ec.LoopEnd = ig.DefineLabel ();
486 ig.Emit (OpCodes.Br, test);
490 ig.MarkLabel (ec.LoopBegin);
491 if (Increment != EmptyStatement.Value)
496 // If test is null, there is no test, and we are just
501 // The Resolve code already catches the case for
502 // Test == BoolConstant (false) so we know that
505 if (Test is BoolConstant)
506 ig.Emit (OpCodes.Br, loop);
508 Test.EmitBranchable (ec, loop, true);
511 ig.Emit (OpCodes.Br, loop);
512 ig.MarkLabel (ec.LoopEnd);
514 ec.LoopBegin = old_begin;
515 ec.LoopEnd = old_end;
519 public class StatementExpression : Statement {
520 ExpressionStatement expr;
522 public StatementExpression (ExpressionStatement expr, Location l)
528 public override bool Resolve (EmitContext ec)
530 expr = expr.ResolveStatement (ec);
534 protected override void DoEmit (EmitContext ec)
536 expr.EmitStatement (ec);
539 public override string ToString ()
541 return "StatementExpression (" + expr + ")";
546 /// Implements the return statement
548 public class Return : Statement {
549 public Expression Expr;
551 public Return (Expression expr, Location l)
559 public override bool Resolve (EmitContext ec)
561 if (ec.ReturnType == null){
563 if (ec.CurrentAnonymousMethod != null){
564 Report.Error (1662, loc, String.Format (
565 "Anonymous method could not be converted to delegate " +
566 "since the return value does not match the delegate value"));
568 Error (127, "Return with a value not allowed here");
573 Error (126, "An object of type `{0}' is expected " +
574 "for the return statement",
575 TypeManager.CSharpName (ec.ReturnType));
579 Expr = Expr.Resolve (ec);
583 if (Expr.Type != ec.ReturnType) {
584 Expr = Convert.ImplicitConversionRequired (
585 ec, Expr, ec.ReturnType, loc);
592 Error (-206, "Return statement not allowed inside iterators");
596 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
598 if (ec.CurrentBranching.InTryOrCatch (true)) {
599 ec.CurrentBranching.AddFinallyVector (vector);
601 } else if (ec.CurrentBranching.InFinally (true)) {
602 Error (157, "Control can not leave the body of the finally block");
605 vector.CheckOutParameters (ec.CurrentBranching);
608 ec.NeedReturnLabel ();
610 ec.CurrentBranching.CurrentUsageVector.Return ();
614 protected override void DoEmit (EmitContext ec)
620 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
624 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
626 ec.ig.Emit (OpCodes.Ret);
630 public class Goto : Statement {
633 LabeledStatement label;
635 public override bool Resolve (EmitContext ec)
637 label = ec.CurrentBranching.LookupLabel (target, loc);
641 // If this is a forward goto.
642 if (!label.IsDefined)
643 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
645 ec.CurrentBranching.CurrentUsageVector.Goto ();
650 public Goto (Block parent_block, string label, Location l)
652 block = parent_block;
657 public string Target {
663 protected override void DoEmit (EmitContext ec)
665 Label l = label.LabelTarget (ec);
666 ec.ig.Emit (OpCodes.Br, l);
670 public class LabeledStatement : Statement {
671 public readonly Location Location;
676 FlowBranching.UsageVector vectors;
678 public LabeledStatement (string label_name, Location l)
683 public Label LabelTarget (EmitContext ec)
687 label = ec.ig.DefineLabel ();
693 public bool IsDefined {
699 public bool HasBeenReferenced {
705 public void AddUsageVector (FlowBranching.UsageVector vector)
707 vector = vector.Clone ();
708 vector.Next = vectors;
712 public override bool Resolve (EmitContext ec)
714 ec.CurrentBranching.Label (vectors);
721 protected override void DoEmit (EmitContext ec)
724 ec.ig.MarkLabel (label);
730 /// `goto default' statement
732 public class GotoDefault : Statement {
734 public GotoDefault (Location l)
739 public override bool Resolve (EmitContext ec)
741 ec.CurrentBranching.CurrentUsageVector.Goto ();
745 protected override void DoEmit (EmitContext ec)
747 if (ec.Switch == null){
748 Report.Error (153, loc, "goto default is only valid in a switch statement");
752 if (!ec.Switch.GotDefault){
753 Report.Error (159, loc, "No default target on switch statement");
756 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
761 /// `goto case' statement
763 public class GotoCase : Statement {
767 public GotoCase (Expression e, Location l)
773 public override bool Resolve (EmitContext ec)
775 if (ec.Switch == null){
776 Report.Error (153, loc, "goto case is only valid in a switch statement");
780 expr = expr.Resolve (ec);
784 if (!(expr is Constant)){
785 Report.Error (159, loc, "Target expression for goto case is not constant");
789 object val = Expression.ConvertIntLiteral (
790 (Constant) expr, ec.Switch.SwitchType, loc);
795 sl = (SwitchLabel) ec.Switch.Elements [val];
800 "No such label 'case " + val + "': for the goto case");
804 ec.CurrentBranching.CurrentUsageVector.Goto ();
808 protected override void DoEmit (EmitContext ec)
810 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
814 public class Throw : Statement {
817 public Throw (Expression expr, Location l)
823 public override bool Resolve (EmitContext ec)
825 bool in_catch = ec.CurrentBranching.InCatch ();
826 ec.CurrentBranching.CurrentUsageVector.Throw ();
829 expr = expr.Resolve (ec);
833 ExprClass eclass = expr.eclass;
835 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
836 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
837 expr.Error_UnexpectedKind ("value, variable, property or indexer access ", loc);
843 if ((t != TypeManager.exception_type) &&
844 !t.IsSubclassOf (TypeManager.exception_type) &&
845 !(expr is NullLiteral)) {
847 "The type caught or thrown must be derived " +
848 "from System.Exception");
851 } else if (!in_catch) {
853 "A throw statement with no argument is only " +
854 "allowed in a catch clause");
861 protected override void DoEmit (EmitContext ec)
864 ec.ig.Emit (OpCodes.Rethrow);
868 ec.ig.Emit (OpCodes.Throw);
873 public class Break : Statement {
875 public Break (Location l)
882 public override bool Resolve (EmitContext ec)
884 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
885 Error (139, "No enclosing loop or switch to continue to");
887 } else if (ec.CurrentBranching.InFinally (false)) {
888 Error (157, "Control can not leave the body of the finally block");
890 } else if (ec.CurrentBranching.InTryOrCatch (false))
891 ec.CurrentBranching.AddFinallyVector (
892 ec.CurrentBranching.CurrentUsageVector);
893 else if (ec.CurrentBranching.InLoop ())
894 ec.CurrentBranching.AddBreakVector (
895 ec.CurrentBranching.CurrentUsageVector);
897 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
900 ec.NeedReturnLabel ();
902 ec.CurrentBranching.CurrentUsageVector.Break ();
906 protected override void DoEmit (EmitContext ec)
908 ILGenerator ig = ec.ig;
911 ig.Emit (OpCodes.Leave, ec.LoopEnd);
913 ig.Emit (OpCodes.Br, ec.LoopEnd);
918 public class Continue : Statement {
920 public Continue (Location l)
927 public override bool Resolve (EmitContext ec)
929 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
930 Error (139, "No enclosing loop to continue to");
932 } else if (ec.CurrentBranching.InFinally (false)) {
933 Error (157, "Control can not leave the body of the finally block");
935 } else if (ec.CurrentBranching.InTryOrCatch (false))
936 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
938 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
940 ec.CurrentBranching.CurrentUsageVector.Goto ();
944 protected override void DoEmit (EmitContext ec)
946 Label begin = ec.LoopBegin;
949 ec.ig.Emit (OpCodes.Leave, begin);
951 ec.ig.Emit (OpCodes.Br, begin);
956 // The information about a user-perceived local variable
958 public class LocalInfo {
959 public Expression Type;
962 // Most of the time a variable will be stored in a LocalBuilder
964 // But sometimes, it will be stored in a field (variables that have been
965 // hoisted by iterators or by anonymous methods). The context of the field will
966 // be stored in the EmitContext
969 public LocalBuilder LocalBuilder;
970 public FieldBuilder FieldBuilder;
972 public Type VariableType;
973 public readonly string Name;
974 public readonly Location Location;
975 public readonly Block Block;
977 public VariableInfo VariableInfo;
989 public LocalInfo (Expression type, string name, Block block, Location l)
997 public LocalInfo (TypeContainer tc, Block block, Location l)
999 VariableType = tc.TypeBuilder;
1004 public bool IsThisAssigned (EmitContext ec, Location loc)
1006 if (VariableInfo == null)
1007 throw new Exception ();
1009 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1012 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1015 public bool IsAssigned (EmitContext ec)
1017 if (VariableInfo == null)
1018 throw new Exception ();
1020 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1023 public bool Resolve (EmitContext ec)
1025 if (VariableType == null) {
1026 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1030 VariableType = texpr.ResolveType (ec);
1033 if (VariableType == TypeManager.void_type) {
1034 Report.Error (1547, Location,
1035 "Keyword 'void' cannot be used in this context");
1039 if (VariableType.IsAbstract && VariableType.IsSealed) {
1040 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1043 // TODO: breaks the build
1044 // if (VariableType.IsPointer && !ec.InUnsafe)
1045 // Expression.UnsafeError (Location);
1051 // Whether the variable is Fixed (because its Pinned or its a value type)
1053 public bool IsFixed {
1055 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1062 public bool IsCaptured {
1064 return (flags & Flags.Captured) != 0;
1068 flags |= Flags.Captured;
1072 public override string ToString ()
1074 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1075 Name, Type, VariableInfo, Location);
1080 return (flags & Flags.Used) != 0;
1083 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1087 public bool ReadOnly {
1089 return (flags & Flags.ReadOnly) != 0;
1092 flags = value ? (flags | Flags.ReadOnly) : (unchecked (flags & ~Flags.ReadOnly));
1097 // Whether the variable is pinned, if Pinned the variable has been
1098 // allocated in a pinned slot with DeclareLocal.
1100 public bool Pinned {
1102 return (flags & Flags.Pinned) != 0;
1105 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1109 public bool IsThis {
1111 return (flags & Flags.IsThis) != 0;
1114 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1120 /// Block represents a C# block.
1124 /// This class is used in a number of places: either to represent
1125 /// explicit blocks that the programmer places or implicit blocks.
1127 /// Implicit blocks are used as labels or to introduce variable
1130 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1131 /// they contain extra information that is not necessary on normal blocks.
1133 public class Block : Statement {
1134 public Block Parent;
1135 public readonly Location StartLocation;
1136 public Location EndLocation = Location.Null;
1143 VariablesInitialized = 8,
1152 public bool Implicit {
1154 return (flags & Flags.Implicit) != 0;
1158 public bool Unchecked {
1160 return (flags & Flags.Unchecked) != 0;
1163 flags |= Flags.Unchecked;
1167 public bool Unsafe {
1169 return (flags & Flags.Unsafe) != 0;
1172 flags |= Flags.Unsafe;
1176 public bool HasVarargs {
1179 return Parent.HasVarargs;
1181 return (flags & Flags.HasVarargs) != 0;
1184 flags |= Flags.HasVarargs;
1189 // The statements in this block
1191 ArrayList statements;
1195 // An array of Blocks. We keep track of children just
1196 // to generate the local variable declarations.
1198 // Statements and child statements are handled through the
1204 // Labels. (label, block) pairs.
1209 // Keeps track of (name, type) pairs
1211 Hashtable variables;
1214 // Keeps track of constants
1215 Hashtable constants;
1218 // The parameters for the block, this is only needed on the toplevel block really
1219 // TODO: move `parameters' into ToplevelBlock
1220 Parameters parameters;
1223 // If this is a switch section, the enclosing switch block.
1227 protected static int id;
1231 public Block (Block parent)
1232 : this (parent, (Flags) 0, Location.Null, Location.Null)
1235 public Block (Block parent, Flags flags)
1236 : this (parent, flags, Location.Null, Location.Null)
1239 public Block (Block parent, Flags flags, Parameters parameters)
1240 : this (parent, flags, parameters, Location.Null, Location.Null)
1243 public Block (Block parent, Location start, Location end)
1244 : this (parent, (Flags) 0, start, end)
1247 public Block (Block parent, Parameters parameters, Location start, Location end)
1248 : this (parent, (Flags) 0, parameters, start, end)
1251 public Block (Block parent, Flags flags, Location start, Location end)
1252 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1255 public Block (Block parent, Flags flags, Parameters parameters,
1256 Location start, Location end)
1259 parent.AddChild (this);
1261 this.Parent = parent;
1263 this.parameters = parameters;
1264 this.StartLocation = start;
1265 this.EndLocation = end;
1268 statements = new ArrayList ();
1270 if (parent != null && Implicit) {
1271 if (parent.child_variable_names == null)
1272 parent.child_variable_names = new Hashtable();
1273 // share with parent
1274 child_variable_names = parent.child_variable_names;
1279 public Block CreateSwitchBlock (Location start)
1281 Block new_block = new Block (this, start, start);
1282 new_block.switch_block = this;
1292 void AddChild (Block b)
1294 if (children == null)
1295 children = new ArrayList ();
1300 public void SetEndLocation (Location loc)
1306 /// Adds a label to the current block.
1310 /// false if the name already exists in this block. true
1314 public bool AddLabel (string name, LabeledStatement target, Location loc)
1316 if (switch_block != null)
1317 return switch_block.AddLabel (name, target, loc);
1320 while (cur != null) {
1321 if (cur.DoLookupLabel (name) != null) {
1323 140, loc, "The label '{0}' is a duplicate",
1334 while (cur != null) {
1335 if (cur.DoLookupLabel (name) != null) {
1338 "The label '{0}' shadows another label " +
1339 "by the same name in a containing scope.",
1344 if (children != null) {
1345 foreach (Block b in children) {
1346 LabeledStatement s = b.DoLookupLabel (name);
1352 "The label '{0}' shadows another " +
1353 "label by the same name in a " +
1354 "containing scope.",
1365 labels = new Hashtable ();
1367 labels.Add (name, target);
1371 public LabeledStatement LookupLabel (string name)
1373 LabeledStatement s = DoLookupLabel (name);
1377 if (children == null)
1380 foreach (Block child in children) {
1381 if (!child.Implicit)
1384 s = child.LookupLabel (name);
1392 LabeledStatement DoLookupLabel (string name)
1394 if (switch_block != null)
1395 return switch_block.LookupLabel (name);
1398 if (labels.Contains (name))
1399 return ((LabeledStatement) labels [name]);
1404 LocalInfo this_variable = null;
1407 // Returns the "this" instance variable of this block.
1408 // See AddThisVariable() for more information.
1410 public LocalInfo ThisVariable {
1412 if (this_variable != null)
1413 return this_variable;
1414 else if (Parent != null)
1415 return Parent.ThisVariable;
1421 Hashtable child_variable_names;
1424 // Marks a variable with name @name as being used in a child block.
1425 // If a variable name has been used in a child block, it's illegal to
1426 // declare a variable with the same name in the current block.
1428 public void AddChildVariableName (string name)
1430 if (child_variable_names == null)
1431 child_variable_names = new Hashtable ();
1433 if (!child_variable_names.Contains (name))
1434 child_variable_names.Add (name, true);
1438 // Checks whether a variable name has already been used in a child block.
1440 public bool IsVariableNameUsedInChildBlock (string name)
1442 if (child_variable_names == null)
1445 return child_variable_names.Contains (name);
1449 // This is used by non-static `struct' constructors which do not have an
1450 // initializer - in this case, the constructor must initialize all of the
1451 // struct's fields. To do this, we add a "this" variable and use the flow
1452 // analysis code to ensure that it's been fully initialized before control
1453 // leaves the constructor.
1455 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1457 if (this_variable != null)
1458 return this_variable;
1460 if (variables == null)
1461 variables = new Hashtable ();
1463 this_variable = new LocalInfo (tc, this, l);
1464 this_variable.Used = true;
1465 this_variable.IsThis = true;
1467 variables.Add ("this", this_variable);
1469 return this_variable;
1472 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1474 if (variables == null)
1475 variables = new Hashtable ();
1477 LocalInfo vi = GetLocalInfo (name);
1479 if (vi.Block != this)
1480 Report.Error (136, l, "A local variable named `" + name + "' " +
1481 "cannot be declared in this scope since it would " +
1482 "give a different meaning to `" + name + "', which " +
1483 "is already used in a `parent or current' scope to " +
1484 "denote something else");
1486 Report.Error (128, l, "A local variable `" + name + "' is already " +
1487 "defined in this scope");
1491 if (IsVariableNameUsedInChildBlock (name)) {
1492 Report.Error (136, l, "A local variable named `" + name + "' " +
1493 "cannot be declared in this scope since it would " +
1494 "give a different meaning to `" + name + "', which " +
1495 "is already used in a `child' scope to denote something " +
1502 Parameter p = pars.GetParameterByName (name, out idx);
1504 Report.Error (136, l, "A local variable named `" + name + "' " +
1505 "cannot be declared in this scope since it would " +
1506 "give a different meaning to `" + name + "', which " +
1507 "is already used in a `parent or current' scope to " +
1508 "denote something else");
1513 vi = new LocalInfo (type, name, this, l);
1515 variables.Add (name, vi);
1517 // Mark 'name' as "used by a child block" in every surrounding block
1519 while (cur != null && cur.Implicit)
1522 for (Block par = cur.Parent; par != null; par = par.Parent)
1523 par.AddChildVariableName (name);
1525 if ((flags & Flags.VariablesInitialized) != 0)
1526 throw new Exception ();
1528 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1532 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1534 if (AddVariable (type, name, pars, l) == null)
1537 if (constants == null)
1538 constants = new Hashtable ();
1540 constants.Add (name, value);
1544 public Hashtable Variables {
1550 public LocalInfo GetLocalInfo (string name)
1552 for (Block b = this; b != null; b = b.Parent) {
1553 if (b.variables != null) {
1554 LocalInfo ret = b.variables [name] as LocalInfo;
1562 public Expression GetVariableType (string name)
1564 LocalInfo vi = GetLocalInfo (name);
1572 public Expression GetConstantExpression (string name)
1574 for (Block b = this; b != null; b = b.Parent) {
1575 if (b.constants != null) {
1576 Expression ret = b.constants [name] as Expression;
1585 /// True if the variable named @name is a constant
1587 public bool IsConstant (string name)
1589 Expression e = null;
1591 e = GetConstantExpression (name);
1597 // Returns a `ParameterReference' for the given name, or null if there
1598 // is no such parameter
1600 public ParameterReference GetParameterReference (string name, Location loc)
1605 Parameters pars = b.parameters;
1611 par = pars.GetParameterByName (name, out idx);
1613 ParameterReference pr;
1615 pr = new ParameterReference (pars, this, idx, name, loc);
1620 } while (b != null);
1625 // Whether the parameter named `name' is local to this block,
1626 // or false, if the parameter belongs to an encompassing block.
1628 public bool IsLocalParameter (string name)
1631 int toplevel_count = 0;
1634 if (this is ToplevelBlock)
1637 Parameters pars = b.parameters;
1639 if (pars.GetParameterByName (name) != null)
1643 if (toplevel_count > 0)
1646 } while (b != null);
1651 // Whether the `name' is a parameter reference
1653 public bool IsParameterReference (string name)
1658 Parameters pars = b.parameters;
1661 if (pars.GetParameterByName (name) != null)
1664 } while (b != null);
1669 /// A list of labels that were not used within this block
1671 public string [] GetUnreferenced ()
1673 // FIXME: Implement me
1677 public void AddStatement (Statement s)
1680 flags |= Flags.BlockUsed;
1685 return (flags & Flags.BlockUsed) != 0;
1691 flags |= Flags.BlockUsed;
1694 public bool HasRet {
1696 return (flags & Flags.HasRet) != 0;
1700 public bool IsDestructor {
1702 return (flags & Flags.IsDestructor) != 0;
1706 public void SetDestructor ()
1708 flags |= Flags.IsDestructor;
1711 VariableMap param_map, local_map;
1713 public VariableMap ParameterMap {
1715 if ((flags & Flags.VariablesInitialized) == 0)
1716 throw new Exception ("Variables have not been initialized yet");
1722 public VariableMap LocalMap {
1724 if ((flags & Flags.VariablesInitialized) == 0)
1725 throw new Exception ("Variables have not been initialized yet");
1732 /// Emits the variable declarations and labels.
1735 /// tc: is our typecontainer (to resolve type references)
1736 /// ig: is the code generator:
1738 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1740 ILGenerator ig = ec.ig;
1742 bool old_unsafe = ec.InUnsafe;
1744 // If some parent block was unsafe, we remain unsafe even if this block
1745 // isn't explicitly marked as such.
1746 ec.InUnsafe |= Unsafe;
1749 // Compute the VariableMap's.
1751 // Unfortunately, we don't know the type when adding variables with
1752 // AddVariable(), so we need to compute this info here.
1756 if (variables != null) {
1757 foreach (LocalInfo li in variables.Values)
1760 locals = new LocalInfo [variables.Count];
1761 variables.Values.CopyTo (locals, 0);
1763 locals = new LocalInfo [0];
1766 local_map = new VariableMap (Parent.LocalMap, locals);
1768 local_map = new VariableMap (locals);
1770 param_map = new VariableMap (ip);
1771 flags |= Flags.VariablesInitialized;
1773 bool old_check_state = ec.ConstantCheckState;
1774 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1777 // Process this block variables
1779 if (variables != null){
1780 foreach (DictionaryEntry de in variables){
1781 string name = (string) de.Key;
1782 LocalInfo vi = (LocalInfo) de.Value;
1784 if (vi.VariableType == null)
1787 Type variable_type = vi.VariableType;
1789 if (variable_type.IsPointer){
1791 // Am not really convinced that this test is required (Microsoft does it)
1792 // but the fact is that you would not be able to use the pointer variable
1795 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1802 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1805 // This is needed to compile on both .NET 1.x and .NET 2.x
1806 // the later introduced `DeclareLocal (Type t, bool pinned)'
1808 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1809 else if (!vi.IsThis)
1810 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1813 if (constants == null)
1816 Expression cv = (Expression) constants [name];
1820 ec.CurrentBlock = this;
1821 Expression e = cv.Resolve (ec);
1825 Constant ce = e as Constant;
1827 Report.Error (133, vi.Location,
1828 "The expression being assigned to `" +
1829 name + "' must be constant (" + e + ")");
1833 if (e.Type != variable_type){
1834 e = Const.ChangeType (vi.Location, ce, variable_type);
1839 constants.Remove (name);
1840 constants.Add (name, e);
1843 ec.ConstantCheckState = old_check_state;
1846 // Now, handle the children
1848 if (children != null){
1849 foreach (Block b in children)
1850 b.ResolveMeta (toplevel, ec, ip);
1852 ec.InUnsafe = old_unsafe;
1856 // Emits the local variable declarations for a block
1858 public void EmitMeta (EmitContext ec)
1860 ILGenerator ig = ec.ig;
1862 if (variables != null){
1863 bool have_captured_vars = ec.HaveCapturedVariables ();
1864 bool remap_locals = ec.RemapToProxy;
1866 foreach (DictionaryEntry de in variables){
1867 LocalInfo vi = (LocalInfo) de.Value;
1869 if (have_captured_vars && ec.IsCaptured (vi))
1873 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1877 // This is needed to compile on both .NET 1.x and .NET 2.x
1878 // the later introduced `DeclareLocal (Type t, bool pinned)'
1880 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1881 else if (!vi.IsThis)
1882 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1887 if (children != null){
1888 foreach (Block b in children)
1893 void UsageWarning (FlowBranching.UsageVector vector)
1897 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1898 foreach (DictionaryEntry de in variables){
1899 LocalInfo vi = (LocalInfo) de.Value;
1904 name = (string) de.Key;
1906 if (vector.IsAssigned (vi.VariableInfo)){
1907 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1909 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1915 bool unreachable_shown;
1917 public override bool Resolve (EmitContext ec)
1919 Block prev_block = ec.CurrentBlock;
1922 int errors = Report.Errors;
1924 ec.CurrentBlock = this;
1925 ec.StartFlowBranching (this);
1927 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1929 bool unreachable = false;
1931 int statement_count = statements.Count;
1932 for (int ix = 0; ix < statement_count; ix++){
1933 Statement s = (Statement) statements [ix];
1935 if (unreachable && !(s is LabeledStatement)) {
1936 if (s == EmptyStatement.Value)
1937 s.loc = EndLocation;
1939 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1942 if (s != EmptyStatement.Value)
1943 unreachable_shown = true;
1945 s.loc = Location.Null;
1947 statements [ix] = EmptyStatement.Value;
1951 if (s.Resolve (ec) == false) {
1953 statements [ix] = EmptyStatement.Value;
1957 num_statements = ix + 1;
1959 if (s is LabeledStatement)
1960 unreachable = false;
1962 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1965 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1966 ec.CurrentBranching, statement_count, num_statements);
1969 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1971 ec.CurrentBlock = prev_block;
1973 // If we're a non-static `struct' constructor which doesn't have an
1974 // initializer, then we must initialize all of the struct's fields.
1975 if ((this_variable != null) &&
1976 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1977 !this_variable.IsThisAssigned (ec, loc))
1980 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1981 foreach (LabeledStatement label in labels.Values)
1982 if (!label.HasBeenReferenced)
1983 Report.Warning (164, label.Location,
1984 "This label has not been referenced");
1987 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1989 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1990 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1991 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1992 flags |= Flags.HasRet;
1994 if (ok && (errors == Report.Errors)) {
1995 if (RootContext.WarningLevel >= 3)
1996 UsageWarning (vector);
2002 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2004 unreachable_shown = true;
2005 return base.ResolveUnreachable (ec, warn);
2008 protected override void DoEmit (EmitContext ec)
2010 for (int ix = 0; ix < num_statements; ix++){
2011 Statement s = (Statement) statements [ix];
2013 // Check whether we are the last statement in a
2016 if ((Parent == null) && (ix+1 == num_statements))
2017 ec.IsLastStatement = true;
2019 ec.IsLastStatement = false;
2025 public override void Emit (EmitContext ec)
2027 Block prev_block = ec.CurrentBlock;
2029 ec.CurrentBlock = this;
2031 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2032 bool is_lexical_block = !Implicit && (Parent != null);
2034 if (emit_debug_info) {
2035 if (is_lexical_block)
2036 ec.ig.BeginScope ();
2038 if (variables != null) {
2039 foreach (DictionaryEntry de in variables) {
2040 string name = (string) de.Key;
2041 LocalInfo vi = (LocalInfo) de.Value;
2043 if (vi.LocalBuilder == null)
2046 ec.DefineLocalVariable (name, vi.LocalBuilder);
2051 ec.Mark (StartLocation, true);
2053 ec.Mark (EndLocation, true);
2055 if (emit_debug_info && is_lexical_block)
2058 ec.CurrentBlock = prev_block;
2061 public ToplevelBlock Toplevel {
2064 while (b.Parent != null){
2065 if ((b.flags & Flags.IsToplevel) != 0)
2070 return (ToplevelBlock) b;
2075 // Returns true if we ar ea child of `b'.
2077 public bool IsChildOf (Block b)
2079 Block current = this;
2082 if (current.Parent == b)
2084 current = current.Parent;
2085 } while (current != null);
2091 // A toplevel block contains extra information, the split is done
2092 // only to separate information that would otherwise bloat the more
2093 // lightweight Block.
2095 // In particular, this was introduced when the support for Anonymous
2096 // Methods was implemented.
2098 public class ToplevelBlock : Block {
2100 // Pointer to the host of this anonymous method, or null
2101 // if we are the topmost block
2103 public ToplevelBlock Container;
2104 CaptureContext capture_context;
2106 Hashtable capture_contexts;
2113 public void RegisterCaptureContext (CaptureContext cc)
2115 if (capture_contexts == null)
2116 capture_contexts = new Hashtable ();
2117 capture_contexts [cc] = cc;
2120 public void CompleteContexts ()
2122 if (capture_contexts == null)
2125 foreach (CaptureContext cc in capture_contexts.Keys){
2130 public CaptureContext ToplevelBlockCaptureContext {
2132 return capture_context;
2137 // Parent is only used by anonymous blocks to link back to their
2140 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2141 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2143 Container = container;
2146 public ToplevelBlock (Parameters parameters, Location start) :
2147 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2151 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2152 base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2156 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2160 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2162 if (capture_context == null)
2163 capture_context = new CaptureContext (this, loc, host);
2166 public CaptureContext CaptureContext {
2168 return capture_context;
2173 public class SwitchLabel {
2176 public Location loc;
2180 Label il_label_code;
2181 bool il_label_code_set;
2184 // if expr == null, then it is the default case.
2186 public SwitchLabel (Expression expr, Location l)
2192 public Expression Label {
2198 public object Converted {
2204 public Label GetILLabel (EmitContext ec)
2207 il_label = ec.ig.DefineLabel ();
2208 il_label_set = true;
2213 public Label GetILLabelCode (EmitContext ec)
2215 if (!il_label_code_set){
2216 il_label_code = ec.ig.DefineLabel ();
2217 il_label_code_set = true;
2219 return il_label_code;
2223 // Resolves the expression, reduces it to a literal if possible
2224 // and then converts it to the requested type.
2226 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2231 Expression e = label.Resolve (ec);
2236 if (!(e is Constant)){
2237 Report.Error (150, loc, "A constant value is expected, got: " + e);
2241 if (e is StringConstant || e is NullLiteral){
2242 if (required_type == TypeManager.string_type){
2248 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2249 if (converted == null)
2256 public class SwitchSection {
2257 // An array of SwitchLabels.
2258 public readonly ArrayList Labels;
2259 public readonly Block Block;
2261 public SwitchSection (ArrayList labels, Block block)
2268 public class Switch : Statement {
2269 public readonly ArrayList Sections;
2270 public Expression Expr;
2273 /// Maps constants whose type type SwitchType to their SwitchLabels.
2275 public Hashtable Elements;
2278 /// The governing switch type
2280 public Type SwitchType;
2286 Label default_target;
2287 Expression new_expr;
2289 SwitchSection constant_section;
2292 // The types allowed to be implicitly cast from
2293 // on the governing type
2295 static Type [] allowed_types;
2297 public Switch (Expression e, ArrayList sects, Location l)
2304 public bool GotDefault {
2310 public Label DefaultTarget {
2312 return default_target;
2317 // Determines the governing type for a switch. The returned
2318 // expression might be the expression from the switch, or an
2319 // expression that includes any potential conversions to the
2320 // integral types or to string.
2322 Expression SwitchGoverningType (EmitContext ec, Type t)
2324 if (t == TypeManager.int32_type ||
2325 t == TypeManager.uint32_type ||
2326 t == TypeManager.char_type ||
2327 t == TypeManager.byte_type ||
2328 t == TypeManager.sbyte_type ||
2329 t == TypeManager.ushort_type ||
2330 t == TypeManager.short_type ||
2331 t == TypeManager.uint64_type ||
2332 t == TypeManager.int64_type ||
2333 t == TypeManager.string_type ||
2334 t == TypeManager.bool_type ||
2335 t.IsSubclassOf (TypeManager.enum_type))
2338 if (allowed_types == null){
2339 allowed_types = new Type [] {
2340 TypeManager.sbyte_type,
2341 TypeManager.byte_type,
2342 TypeManager.short_type,
2343 TypeManager.ushort_type,
2344 TypeManager.int32_type,
2345 TypeManager.uint32_type,
2346 TypeManager.int64_type,
2347 TypeManager.uint64_type,
2348 TypeManager.char_type,
2349 TypeManager.bool_type,
2350 TypeManager.string_type
2355 // Try to find a *user* defined implicit conversion.
2357 // If there is no implicit conversion, or if there are multiple
2358 // conversions, we have to report an error
2360 Expression converted = null;
2361 foreach (Type tt in allowed_types){
2364 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2368 if (converted != null){
2369 Report.Error (-12, loc, "More than one conversion to an integral " +
2370 " type exists for type `" +
2371 TypeManager.CSharpName (Expr.Type)+"'");
2379 static string Error152 {
2381 return "The label '{0}:' already occurs in this switch statement";
2386 // Performs the basic sanity checks on the switch statement
2387 // (looks for duplicate keys and non-constant expressions).
2389 // It also returns a hashtable with the keys that we will later
2390 // use to compute the switch tables
2392 bool CheckSwitch (EmitContext ec)
2396 Elements = new Hashtable ();
2398 got_default = false;
2400 if (TypeManager.IsEnumType (SwitchType)){
2401 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2403 compare_type = SwitchType;
2405 foreach (SwitchSection ss in Sections){
2406 foreach (SwitchLabel sl in ss.Labels){
2407 if (!sl.ResolveAndReduce (ec, SwitchType)){
2412 if (sl.Label == null){
2414 Report.Error (152, sl.loc, Error152, "default");
2421 object key = sl.Converted;
2423 if (key is Constant)
2424 key = ((Constant) key).GetValue ();
2427 key = NullLiteral.Null;
2429 string lname = null;
2430 if (compare_type == TypeManager.uint64_type){
2431 ulong v = (ulong) key;
2433 if (Elements.Contains (v))
2434 lname = v.ToString ();
2436 Elements.Add (v, sl);
2437 } else if (compare_type == TypeManager.int64_type){
2438 long v = (long) key;
2440 if (Elements.Contains (v))
2441 lname = v.ToString ();
2443 Elements.Add (v, sl);
2444 } else if (compare_type == TypeManager.uint32_type){
2445 uint v = (uint) key;
2447 if (Elements.Contains (v))
2448 lname = v.ToString ();
2450 Elements.Add (v, sl);
2451 } else if (compare_type == TypeManager.char_type){
2452 char v = (char) key;
2454 if (Elements.Contains (v))
2455 lname = v.ToString ();
2457 Elements.Add (v, sl);
2458 } else if (compare_type == TypeManager.byte_type){
2459 byte v = (byte) key;
2461 if (Elements.Contains (v))
2462 lname = v.ToString ();
2464 Elements.Add (v, sl);
2465 } else if (compare_type == TypeManager.sbyte_type){
2466 sbyte v = (sbyte) key;
2468 if (Elements.Contains (v))
2469 lname = v.ToString ();
2471 Elements.Add (v, sl);
2472 } else if (compare_type == TypeManager.short_type){
2473 short v = (short) key;
2475 if (Elements.Contains (v))
2476 lname = v.ToString ();
2478 Elements.Add (v, sl);
2479 } else if (compare_type == TypeManager.ushort_type){
2480 ushort v = (ushort) key;
2482 if (Elements.Contains (v))
2483 lname = v.ToString ();
2485 Elements.Add (v, sl);
2486 } else if (compare_type == TypeManager.string_type){
2487 if (key is NullLiteral){
2488 if (Elements.Contains (NullLiteral.Null))
2491 Elements.Add (NullLiteral.Null, null);
2493 string s = (string) key;
2495 if (Elements.Contains (s))
2498 Elements.Add (s, sl);
2500 } else if (compare_type == TypeManager.int32_type) {
2503 if (Elements.Contains (v))
2504 lname = v.ToString ();
2506 Elements.Add (v, sl);
2507 } else if (compare_type == TypeManager.bool_type) {
2508 bool v = (bool) key;
2510 if (Elements.Contains (v))
2511 lname = v.ToString ();
2513 Elements.Add (v, sl);
2517 throw new Exception ("Unknown switch type!" +
2518 SwitchType + " " + compare_type);
2521 if (lname != null) {
2522 Report.Error (152, sl.loc, Error152, "case " + lname);
2533 void EmitObjectInteger (ILGenerator ig, object k)
2536 IntConstant.EmitInt (ig, (int) k);
2537 else if (k is Constant) {
2538 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2541 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2544 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2546 IntConstant.EmitInt (ig, (int) (long) k);
2547 ig.Emit (OpCodes.Conv_I8);
2550 LongConstant.EmitLong (ig, (long) k);
2552 else if (k is ulong)
2554 if ((ulong) k < (1L<<32))
2556 IntConstant.EmitInt (ig, (int) (long) k);
2557 ig.Emit (OpCodes.Conv_U8);
2561 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2565 IntConstant.EmitInt (ig, (int) ((char) k));
2566 else if (k is sbyte)
2567 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2569 IntConstant.EmitInt (ig, (int) ((byte) k));
2570 else if (k is short)
2571 IntConstant.EmitInt (ig, (int) ((short) k));
2572 else if (k is ushort)
2573 IntConstant.EmitInt (ig, (int) ((ushort) k));
2575 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2577 throw new Exception ("Unhandled case");
2580 // structure used to hold blocks of keys while calculating table switch
2581 class KeyBlock : IComparable
2583 public KeyBlock (long _nFirst)
2585 nFirst = nLast = _nFirst;
2589 public ArrayList rgKeys = null;
2590 // how many items are in the bucket
2591 public int Size = 1;
2594 get { return (int) (nLast - nFirst + 1); }
2596 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2598 return kbLast.nLast - kbFirst.nFirst + 1;
2600 public int CompareTo (object obj)
2602 KeyBlock kb = (KeyBlock) obj;
2603 int nLength = Length;
2604 int nLengthOther = kb.Length;
2605 if (nLengthOther == nLength)
2606 return (int) (kb.nFirst - nFirst);
2607 return nLength - nLengthOther;
2612 /// This method emits code for a lookup-based switch statement (non-string)
2613 /// Basically it groups the cases into blocks that are at least half full,
2614 /// and then spits out individual lookup opcodes for each block.
2615 /// It emits the longest blocks first, and short blocks are just
2616 /// handled with direct compares.
2618 /// <param name="ec"></param>
2619 /// <param name="val"></param>
2620 /// <returns></returns>
2621 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2623 int cElements = Elements.Count;
2624 object [] rgKeys = new object [cElements];
2625 Elements.Keys.CopyTo (rgKeys, 0);
2626 Array.Sort (rgKeys);
2628 // initialize the block list with one element per key
2629 ArrayList rgKeyBlocks = new ArrayList ();
2630 foreach (object key in rgKeys)
2631 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2634 // iteratively merge the blocks while they are at least half full
2635 // there's probably a really cool way to do this with a tree...
2636 while (rgKeyBlocks.Count > 1)
2638 ArrayList rgKeyBlocksNew = new ArrayList ();
2639 kbCurr = (KeyBlock) rgKeyBlocks [0];
2640 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2642 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2643 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2646 kbCurr.nLast = kb.nLast;
2647 kbCurr.Size += kb.Size;
2651 // start a new block
2652 rgKeyBlocksNew.Add (kbCurr);
2656 rgKeyBlocksNew.Add (kbCurr);
2657 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2659 rgKeyBlocks = rgKeyBlocksNew;
2662 // initialize the key lists
2663 foreach (KeyBlock kb in rgKeyBlocks)
2664 kb.rgKeys = new ArrayList ();
2666 // fill the key lists
2668 if (rgKeyBlocks.Count > 0) {
2669 kbCurr = (KeyBlock) rgKeyBlocks [0];
2670 foreach (object key in rgKeys)
2672 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2673 System.Convert.ToInt64 (key) > kbCurr.nLast;
2675 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2676 kbCurr.rgKeys.Add (key);
2680 // sort the blocks so we can tackle the largest ones first
2681 rgKeyBlocks.Sort ();
2683 // okay now we can start...
2684 ILGenerator ig = ec.ig;
2685 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2686 Label lblDefault = ig.DefineLabel ();
2688 Type typeKeys = null;
2689 if (rgKeys.Length > 0)
2690 typeKeys = rgKeys [0].GetType (); // used for conversions
2694 if (TypeManager.IsEnumType (SwitchType))
2695 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2697 compare_type = SwitchType;
2699 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2701 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2702 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2705 foreach (object key in kb.rgKeys)
2707 ig.Emit (OpCodes.Ldloc, val);
2708 EmitObjectInteger (ig, key);
2709 SwitchLabel sl = (SwitchLabel) Elements [key];
2710 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2715 // TODO: if all the keys in the block are the same and there are
2716 // no gaps/defaults then just use a range-check.
2717 if (compare_type == TypeManager.int64_type ||
2718 compare_type == TypeManager.uint64_type)
2720 // TODO: optimize constant/I4 cases
2722 // check block range (could be > 2^31)
2723 ig.Emit (OpCodes.Ldloc, val);
2724 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2725 ig.Emit (OpCodes.Blt, lblDefault);
2726 ig.Emit (OpCodes.Ldloc, val);
2727 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2728 ig.Emit (OpCodes.Bgt, lblDefault);
2731 ig.Emit (OpCodes.Ldloc, val);
2734 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2735 ig.Emit (OpCodes.Sub);
2737 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2742 ig.Emit (OpCodes.Ldloc, val);
2743 int nFirst = (int) kb.nFirst;
2746 IntConstant.EmitInt (ig, nFirst);
2747 ig.Emit (OpCodes.Sub);
2749 else if (nFirst < 0)
2751 IntConstant.EmitInt (ig, -nFirst);
2752 ig.Emit (OpCodes.Add);
2756 // first, build the list of labels for the switch
2758 int cJumps = kb.Length;
2759 Label [] rgLabels = new Label [cJumps];
2760 for (int iJump = 0; iJump < cJumps; iJump++)
2762 object key = kb.rgKeys [iKey];
2763 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2765 SwitchLabel sl = (SwitchLabel) Elements [key];
2766 rgLabels [iJump] = sl.GetILLabel (ec);
2770 rgLabels [iJump] = lblDefault;
2772 // emit the switch opcode
2773 ig.Emit (OpCodes.Switch, rgLabels);
2776 // mark the default for this block
2778 ig.MarkLabel (lblDefault);
2781 // TODO: find the default case and emit it here,
2782 // to prevent having to do the following jump.
2783 // make sure to mark other labels in the default section
2785 // the last default just goes to the end
2786 ig.Emit (OpCodes.Br, lblDefault);
2788 // now emit the code for the sections
2789 bool fFoundDefault = false;
2790 foreach (SwitchSection ss in Sections)
2792 foreach (SwitchLabel sl in ss.Labels)
2794 ig.MarkLabel (sl.GetILLabel (ec));
2795 ig.MarkLabel (sl.GetILLabelCode (ec));
2796 if (sl.Label == null)
2798 ig.MarkLabel (lblDefault);
2799 fFoundDefault = true;
2803 //ig.Emit (OpCodes.Br, lblEnd);
2806 if (!fFoundDefault) {
2807 ig.MarkLabel (lblDefault);
2809 ig.MarkLabel (lblEnd);
2812 // This simple emit switch works, but does not take advantage of the
2814 // TODO: remove non-string logic from here
2815 // TODO: binary search strings?
2817 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2819 ILGenerator ig = ec.ig;
2820 Label end_of_switch = ig.DefineLabel ();
2821 Label next_test = ig.DefineLabel ();
2822 Label null_target = ig.DefineLabel ();
2823 bool default_found = false;
2824 bool first_test = true;
2825 bool pending_goto_end = false;
2827 bool default_at_end = false;
2829 ig.Emit (OpCodes.Ldloc, val);
2831 if (Elements.Contains (NullLiteral.Null)){
2832 ig.Emit (OpCodes.Brfalse, null_target);
2834 ig.Emit (OpCodes.Brfalse, default_target);
2836 ig.Emit (OpCodes.Ldloc, val);
2837 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2838 ig.Emit (OpCodes.Stloc, val);
2840 int section_count = Sections.Count;
2841 for (int section = 0; section < section_count; section++){
2842 SwitchSection ss = (SwitchSection) Sections [section];
2843 Label sec_begin = ig.DefineLabel ();
2845 if (pending_goto_end)
2846 ig.Emit (OpCodes.Br, end_of_switch);
2848 int label_count = ss.Labels.Count;
2849 bool mark_default = false;
2851 for (int label = 0; label < label_count; label++){
2852 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2853 ig.MarkLabel (sl.GetILLabel (ec));
2856 ig.MarkLabel (next_test);
2857 next_test = ig.DefineLabel ();
2860 // If we are the default target
2862 if (sl.Label == null){
2863 if (label+1 == label_count)
2864 default_at_end = true;
2865 mark_default = true;
2866 default_found = true;
2868 object lit = sl.Converted;
2870 if (lit is NullLiteral){
2872 if (label_count == 1)
2873 ig.Emit (OpCodes.Br, next_test);
2877 StringConstant str = (StringConstant) lit;
2879 ig.Emit (OpCodes.Ldloc, val);
2880 ig.Emit (OpCodes.Ldstr, str.Value);
2881 if (label_count == 1)
2882 ig.Emit (OpCodes.Bne_Un, next_test);
2884 if (label+1 == label_count)
2885 ig.Emit (OpCodes.Bne_Un, next_test);
2887 ig.Emit (OpCodes.Beq, sec_begin);
2892 ig.MarkLabel (null_target);
2893 ig.MarkLabel (sec_begin);
2894 foreach (SwitchLabel sl in ss.Labels)
2895 ig.MarkLabel (sl.GetILLabelCode (ec));
2898 ig.MarkLabel (default_target);
2900 pending_goto_end = !ss.Block.HasRet;
2903 ig.MarkLabel (next_test);
2905 if (!default_at_end)
2906 ig.Emit (OpCodes.Br, default_target);
2908 ig.MarkLabel (default_target);
2909 ig.MarkLabel (end_of_switch);
2912 SwitchSection FindSection (SwitchLabel label)
2914 foreach (SwitchSection ss in Sections){
2915 foreach (SwitchLabel sl in ss.Labels){
2924 bool ResolveConstantSwitch (EmitContext ec)
2926 object key = ((Constant) new_expr).GetValue ();
2927 SwitchLabel label = (SwitchLabel) Elements [key];
2932 constant_section = FindSection (label);
2933 if (constant_section == null)
2936 if (constant_section.Block.Resolve (ec) != true)
2942 public override bool Resolve (EmitContext ec)
2944 Expr = Expr.Resolve (ec);
2948 new_expr = SwitchGoverningType (ec, Expr.Type);
2949 if (new_expr == null){
2950 Report.Error (151, loc, "An integer type or string was expected for switch");
2955 SwitchType = new_expr.Type;
2957 if (!CheckSwitch (ec))
2960 Switch old_switch = ec.Switch;
2962 ec.Switch.SwitchType = SwitchType;
2964 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2965 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2967 is_constant = new_expr is Constant;
2969 object key = ((Constant) new_expr).GetValue ();
2970 SwitchLabel label = (SwitchLabel) Elements [key];
2972 constant_section = FindSection (label);
2976 foreach (SwitchSection ss in Sections){
2978 ec.CurrentBranching.CreateSibling (
2979 null, FlowBranching.SiblingType.SwitchSection);
2983 if (is_constant && (ss != constant_section)) {
2984 // If we're a constant switch, we're only emitting
2985 // one single section - mark all the others as
2987 ec.CurrentBranching.CurrentUsageVector.Goto ();
2988 if (!ss.Block.ResolveUnreachable (ec, true))
2991 if (!ss.Block.Resolve (ec))
2997 ec.CurrentBranching.CreateSibling (
2998 null, FlowBranching.SiblingType.SwitchSection);
3000 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3001 ec.Switch = old_switch;
3003 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3009 protected override void DoEmit (EmitContext ec)
3011 ILGenerator ig = ec.ig;
3013 // Store variable for comparission purposes
3016 value = ig.DeclareLocal (SwitchType);
3018 ig.Emit (OpCodes.Stloc, value);
3022 default_target = ig.DefineLabel ();
3025 // Setup the codegen context
3027 Label old_end = ec.LoopEnd;
3028 Switch old_switch = ec.Switch;
3030 ec.LoopEnd = ig.DefineLabel ();
3035 if (constant_section != null)
3036 constant_section.Block.Emit (ec);
3037 } else if (SwitchType == TypeManager.string_type)
3038 SimpleSwitchEmit (ec, value);
3040 TableSwitchEmit (ec, value);
3042 // Restore context state.
3043 ig.MarkLabel (ec.LoopEnd);
3046 // Restore the previous context
3048 ec.LoopEnd = old_end;
3049 ec.Switch = old_switch;
3053 public abstract class ExceptionStatement : Statement
3055 public abstract void EmitFinally (EmitContext ec);
3057 protected bool emit_finally = true;
3058 ArrayList parent_vectors;
3060 protected void DoEmitFinally (EmitContext ec)
3063 ec.ig.BeginFinallyBlock ();
3065 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3069 protected void ResolveFinally (FlowBranchingException branching)
3071 emit_finally = branching.EmitFinally;
3073 branching.Parent.StealFinallyClauses (ref parent_vectors);
3077 public class Lock : ExceptionStatement {
3079 Statement Statement;
3082 public Lock (Expression expr, Statement stmt, Location l)
3089 public override bool Resolve (EmitContext ec)
3091 expr = expr.Resolve (ec);
3095 if (expr.Type.IsValueType){
3096 Error (185, "lock statement requires the expression to be " +
3097 " a reference type (type is: `{0}'",
3098 TypeManager.CSharpName (expr.Type));
3102 FlowBranchingException branching = ec.StartFlowBranching (this);
3103 bool ok = Statement.Resolve (ec);
3105 ec.KillFlowBranching ();
3109 ResolveFinally (branching);
3111 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3112 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3113 // Unfortunately, System.Reflection.Emit automatically emits
3114 // a leave to the end of the finally block.
3115 // This is a problem if `returns' is true since we may jump
3116 // to a point after the end of the method.
3117 // As a workaround, emit an explicit ret here.
3118 ec.NeedReturnLabel ();
3124 protected override void DoEmit (EmitContext ec)
3126 Type type = expr.Type;
3128 ILGenerator ig = ec.ig;
3129 temp = ig.DeclareLocal (type);
3132 ig.Emit (OpCodes.Dup);
3133 ig.Emit (OpCodes.Stloc, temp);
3134 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3138 ig.BeginExceptionBlock ();
3139 Statement.Emit (ec);
3144 ig.EndExceptionBlock ();
3147 public override void EmitFinally (EmitContext ec)
3149 ILGenerator ig = ec.ig;
3150 ig.Emit (OpCodes.Ldloc, temp);
3151 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3155 public class Unchecked : Statement {
3156 public readonly Block Block;
3158 public Unchecked (Block b)
3164 public override bool Resolve (EmitContext ec)
3166 bool previous_state = ec.CheckState;
3167 bool previous_state_const = ec.ConstantCheckState;
3169 ec.CheckState = false;
3170 ec.ConstantCheckState = false;
3171 bool ret = Block.Resolve (ec);
3172 ec.CheckState = previous_state;
3173 ec.ConstantCheckState = previous_state_const;
3178 protected override void DoEmit (EmitContext ec)
3180 bool previous_state = ec.CheckState;
3181 bool previous_state_const = ec.ConstantCheckState;
3183 ec.CheckState = false;
3184 ec.ConstantCheckState = false;
3186 ec.CheckState = previous_state;
3187 ec.ConstantCheckState = previous_state_const;
3191 public class Checked : Statement {
3192 public readonly Block Block;
3194 public Checked (Block b)
3197 b.Unchecked = false;
3200 public override bool Resolve (EmitContext ec)
3202 bool previous_state = ec.CheckState;
3203 bool previous_state_const = ec.ConstantCheckState;
3205 ec.CheckState = true;
3206 ec.ConstantCheckState = true;
3207 bool ret = Block.Resolve (ec);
3208 ec.CheckState = previous_state;
3209 ec.ConstantCheckState = previous_state_const;
3214 protected override void DoEmit (EmitContext ec)
3216 bool previous_state = ec.CheckState;
3217 bool previous_state_const = ec.ConstantCheckState;
3219 ec.CheckState = true;
3220 ec.ConstantCheckState = true;
3222 ec.CheckState = previous_state;
3223 ec.ConstantCheckState = previous_state_const;
3227 public class Unsafe : Statement {
3228 public readonly Block Block;
3230 public Unsafe (Block b)
3233 Block.Unsafe = true;
3236 public override bool Resolve (EmitContext ec)
3238 bool previous_state = ec.InUnsafe;
3242 val = Block.Resolve (ec);
3243 ec.InUnsafe = previous_state;
3248 protected override void DoEmit (EmitContext ec)
3250 bool previous_state = ec.InUnsafe;
3254 ec.InUnsafe = previous_state;
3261 public class Fixed : Statement {
3263 ArrayList declarators;
3264 Statement statement;
3270 public bool is_object;
3271 public LocalInfo vi;
3272 public Expression expr;
3273 public Expression converted;
3276 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3279 declarators = decls;
3284 public override bool Resolve (EmitContext ec)
3287 Expression.UnsafeError (loc);
3291 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3295 expr_type = texpr.ResolveType (ec);
3297 CheckObsolete (expr_type);
3299 if (ec.RemapToProxy){
3300 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3304 data = new FixedData [declarators.Count];
3306 if (!expr_type.IsPointer){
3307 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3312 foreach (Pair p in declarators){
3313 LocalInfo vi = (LocalInfo) p.First;
3314 Expression e = (Expression) p.Second;
3316 vi.VariableInfo.SetAssigned (ec);
3320 // The rules for the possible declarators are pretty wise,
3321 // but the production on the grammar is more concise.
3323 // So we have to enforce these rules here.
3325 // We do not resolve before doing the case 1 test,
3326 // because the grammar is explicit in that the token &
3327 // is present, so we need to test for this particular case.
3331 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3336 // Case 1: & object.
3338 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3339 Expression child = ((Unary) e).Expr;
3341 if (child is ParameterReference || child is LocalVariableReference){
3344 "No need to use fixed statement for parameters or " +
3345 "local variable declarations (address is already " +
3350 ec.InFixedInitializer = true;
3352 ec.InFixedInitializer = false;
3356 child = ((Unary) e).Expr;
3358 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3361 data [i].is_object = true;
3363 data [i].converted = null;
3370 ec.InFixedInitializer = true;
3372 ec.InFixedInitializer = false;
3379 if (e.Type.IsArray){
3380 Type array_type = TypeManager.GetElementType (e.Type);
3383 // Provided that array_type is unmanaged,
3385 if (!TypeManager.VerifyUnManaged (array_type, loc))
3389 // and T* is implicitly convertible to the
3390 // pointer type given in the fixed statement.
3392 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3394 Expression converted = Convert.ImplicitConversionRequired (
3395 ec, array_ptr, vi.VariableType, loc);
3396 if (converted == null)
3399 data [i].is_object = false;
3401 data [i].converted = converted;
3411 if (e.Type == TypeManager.string_type){
3412 data [i].is_object = false;
3414 data [i].converted = null;
3421 // For other cases, flag a `this is already fixed expression'
3423 if (e is LocalVariableReference || e is ParameterReference ||
3424 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3426 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3430 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3434 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3436 if (!statement.Resolve (ec)) {
3437 ec.KillFlowBranching ();
3441 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3442 has_ret = reachability.IsUnreachable;
3447 protected override void DoEmit (EmitContext ec)
3449 ILGenerator ig = ec.ig;
3451 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3453 for (int i = 0; i < data.Length; i++) {
3454 LocalInfo vi = data [i].vi;
3457 // Case 1: & object.
3459 if (data [i].is_object) {
3461 // Store pointer in pinned location
3463 data [i].expr.Emit (ec);
3464 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3465 clear_list [i] = vi.LocalBuilder;
3472 if (data [i].expr.Type.IsArray){
3474 // Store pointer in pinned location
3476 data [i].converted.Emit (ec);
3478 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3479 clear_list [i] = vi.LocalBuilder;
3486 if (data [i].expr.Type == TypeManager.string_type){
3487 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3488 clear_list [i] = pinned_string;
3490 data [i].expr.Emit (ec);
3491 ig.Emit (OpCodes.Stloc, pinned_string);
3493 Expression sptr = new StringPtr (pinned_string, loc);
3494 Expression converted = Convert.ImplicitConversionRequired (
3495 ec, sptr, vi.VariableType, loc);
3497 if (converted == null)
3500 converted.Emit (ec);
3501 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3505 statement.Emit (ec);
3511 // Clear the pinned variable
3513 for (int i = 0; i < data.Length; i++) {
3514 if (data [i].is_object || data [i].expr.Type.IsArray) {
3515 ig.Emit (OpCodes.Ldc_I4_0);
3516 ig.Emit (OpCodes.Conv_U);
3517 ig.Emit (OpCodes.Stloc, clear_list [i]);
3518 } else if (data [i].expr.Type == TypeManager.string_type){
3519 ig.Emit (OpCodes.Ldnull);
3520 ig.Emit (OpCodes.Stloc, clear_list [i]);
3526 public class Catch: Statement {
3527 public readonly string Name;
3528 public readonly Block Block;
3530 Expression type_expr;
3533 public Catch (Expression type, string name, Block block, Location l)
3541 public Type CatchType {
3547 public bool IsGeneral {
3549 return type_expr == null;
3553 protected override void DoEmit(EmitContext ec)
3557 public override bool Resolve (EmitContext ec)
3559 if (type_expr != null) {
3560 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3564 type = te.ResolveType (ec);
3566 CheckObsolete (type);
3568 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3569 Error (155, "The type caught or thrown must be derived from System.Exception");
3575 return Block.Resolve (ec);
3579 public class Try : ExceptionStatement {
3580 public readonly Block Fini, Block;
3581 public readonly ArrayList Specific;
3582 public readonly Catch General;
3584 bool need_exc_block;
3587 // specific, general and fini might all be null.
3589 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3591 if (specific == null && general == null){
3592 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3596 this.Specific = specific;
3597 this.General = general;
3602 public override bool Resolve (EmitContext ec)
3606 FlowBranchingException branching = ec.StartFlowBranching (this);
3608 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3610 if (!Block.Resolve (ec))
3613 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3615 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3617 Type[] prevCatches = new Type [Specific.Count];
3619 foreach (Catch c in Specific){
3620 ec.CurrentBranching.CreateSibling (
3621 c.Block, FlowBranching.SiblingType.Catch);
3623 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3625 if (c.Name != null) {
3626 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3628 throw new Exception ();
3630 vi.VariableInfo = null;
3633 if (!c.Resolve (ec))
3636 Type resolvedType = c.CatchType;
3637 for (int ii = 0; ii < last_index; ++ii) {
3638 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3639 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3644 prevCatches [last_index++] = resolvedType;
3645 need_exc_block = true;
3648 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3650 if (General != null){
3651 ec.CurrentBranching.CreateSibling (
3652 General.Block, FlowBranching.SiblingType.Catch);
3654 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3656 if (!General.Resolve (ec))
3659 need_exc_block = true;
3662 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3666 ec.CurrentBranching.CreateSibling (
3667 Fini, FlowBranching.SiblingType.Finally);
3669 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3671 if (!Fini.Resolve (ec))
3675 ResolveFinally (branching);
3676 need_exc_block |= emit_finally;
3678 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3680 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3682 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3684 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3685 // Unfortunately, System.Reflection.Emit automatically emits
3686 // a leave to the end of the finally block. This is a problem
3687 // if `returns' is true since we may jump to a point after the
3688 // end of the method.
3689 // As a workaround, emit an explicit ret here.
3690 ec.NeedReturnLabel ();
3696 protected override void DoEmit (EmitContext ec)
3698 ILGenerator ig = ec.ig;
3701 ig.BeginExceptionBlock ();
3704 foreach (Catch c in Specific){
3707 ig.BeginCatchBlock (c.CatchType);
3709 if (c.Name != null){
3710 vi = c.Block.GetLocalInfo (c.Name);
3712 throw new Exception ("Variable does not exist in this block");
3714 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3716 ig.Emit (OpCodes.Pop);
3721 if (General != null){
3722 ig.BeginCatchBlock (TypeManager.object_type);
3723 ig.Emit (OpCodes.Pop);
3724 General.Block.Emit (ec);
3729 ig.EndExceptionBlock ();
3732 public override void EmitFinally (EmitContext ec)
3740 public class Using : ExceptionStatement {
3741 object expression_or_block;
3742 Statement Statement;
3747 Expression [] resolved_vars;
3748 Expression [] converted_vars;
3749 ExpressionStatement [] assign;
3750 LocalBuilder local_copy;
3752 public Using (object expression_or_block, Statement stmt, Location l)
3754 this.expression_or_block = expression_or_block;
3760 // Resolves for the case of using using a local variable declaration.
3762 bool ResolveLocalVariableDecls (EmitContext ec)
3766 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3770 expr_type = texpr.ResolveType (ec);
3773 // The type must be an IDisposable or an implicit conversion
3776 converted_vars = new Expression [var_list.Count];
3777 resolved_vars = new Expression [var_list.Count];
3778 assign = new ExpressionStatement [var_list.Count];
3780 bool need_conv = !TypeManager.ImplementsInterface (
3781 expr_type, TypeManager.idisposable_type);
3783 foreach (DictionaryEntry e in var_list){
3784 Expression var = (Expression) e.Key;
3786 var = var.ResolveLValue (ec, new EmptyExpression ());
3790 resolved_vars [i] = var;
3797 converted_vars [i] = Convert.ImplicitConversionRequired (
3798 ec, var, TypeManager.idisposable_type, loc);
3800 if (converted_vars [i] == null)
3807 foreach (DictionaryEntry e in var_list){
3808 Expression var = resolved_vars [i];
3809 Expression new_expr = (Expression) e.Value;
3812 a = new Assign (var, new_expr, loc);
3818 converted_vars [i] = var;
3819 assign [i] = (ExpressionStatement) a;
3826 bool ResolveExpression (EmitContext ec)
3828 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3829 conv = Convert.ImplicitConversionRequired (
3830 ec, expr, TypeManager.idisposable_type, loc);
3840 // Emits the code for the case of using using a local variable declaration.
3842 void EmitLocalVariableDecls (EmitContext ec)
3844 ILGenerator ig = ec.ig;
3847 for (i = 0; i < assign.Length; i++) {
3848 assign [i].EmitStatement (ec);
3851 ig.BeginExceptionBlock ();
3853 Statement.Emit (ec);
3854 var_list.Reverse ();
3859 void EmitLocalVariableDeclFinally (EmitContext ec)
3861 ILGenerator ig = ec.ig;
3863 int i = assign.Length;
3864 foreach (DictionaryEntry e in var_list){
3865 Expression var = resolved_vars [--i];
3866 Label skip = ig.DefineLabel ();
3868 if (!var.Type.IsValueType) {
3870 ig.Emit (OpCodes.Brfalse, skip);
3871 converted_vars [i].Emit (ec);
3872 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3874 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3876 if (!(ml is MethodGroupExpr)) {
3878 ig.Emit (OpCodes.Box, var.Type);
3879 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3881 MethodInfo mi = null;
3883 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3884 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3891 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3895 IMemoryLocation mloc = (IMemoryLocation) var;
3897 mloc.AddressOf (ec, AddressOp.Load);
3898 ig.Emit (OpCodes.Call, mi);
3902 ig.MarkLabel (skip);
3905 ig.EndExceptionBlock ();
3907 ig.BeginFinallyBlock ();
3912 void EmitExpression (EmitContext ec)
3915 // Make a copy of the expression and operate on that.
3917 ILGenerator ig = ec.ig;
3918 local_copy = ig.DeclareLocal (expr_type);
3923 ig.Emit (OpCodes.Stloc, local_copy);
3926 ig.BeginExceptionBlock ();
3928 Statement.Emit (ec);
3932 ig.EndExceptionBlock ();
3935 void EmitExpressionFinally (EmitContext ec)
3937 ILGenerator ig = ec.ig;
3938 Label skip = ig.DefineLabel ();
3939 ig.Emit (OpCodes.Ldloc, local_copy);
3940 ig.Emit (OpCodes.Brfalse, skip);
3941 ig.Emit (OpCodes.Ldloc, local_copy);
3942 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3943 ig.MarkLabel (skip);
3946 public override bool Resolve (EmitContext ec)
3948 if (expression_or_block is DictionaryEntry){
3949 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3950 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3952 if (!ResolveLocalVariableDecls (ec))
3955 } else if (expression_or_block is Expression){
3956 expr = (Expression) expression_or_block;
3958 expr = expr.Resolve (ec);
3962 expr_type = expr.Type;
3964 if (!ResolveExpression (ec))
3968 FlowBranchingException branching = ec.StartFlowBranching (this);
3970 bool ok = Statement.Resolve (ec);
3973 ec.KillFlowBranching ();
3977 ResolveFinally (branching);
3978 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3980 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3981 // Unfortunately, System.Reflection.Emit automatically emits a leave
3982 // to the end of the finally block. This is a problem if `returns'
3983 // is true since we may jump to a point after the end of the method.
3984 // As a workaround, emit an explicit ret here.
3985 ec.NeedReturnLabel ();
3991 protected override void DoEmit (EmitContext ec)
3993 if (expression_or_block is DictionaryEntry)
3994 EmitLocalVariableDecls (ec);
3995 else if (expression_or_block is Expression)
3996 EmitExpression (ec);
3999 public override void EmitFinally (EmitContext ec)
4001 if (expression_or_block is DictionaryEntry)
4002 EmitLocalVariableDeclFinally (ec);
4003 else if (expression_or_block is Expression)
4004 EmitExpressionFinally (ec);
4009 /// Implementation of the foreach C# statement
4011 public class Foreach : ExceptionStatement {
4013 Expression variable;
4015 Statement statement;
4016 ForeachHelperMethods hm;
4017 Expression empty, conv;
4018 Type array_type, element_type;
4020 VariableStorage enumerator;
4022 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4023 Statement stmt, Location l)
4026 this.variable = var;
4032 public override bool Resolve (EmitContext ec)
4034 expr = expr.Resolve (ec);
4038 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4042 var_type = texpr.ResolveType (ec);
4045 // We need an instance variable. Not sure this is the best
4046 // way of doing this.
4048 // FIXME: When we implement propertyaccess, will those turn
4049 // out to return values in ExprClass? I think they should.
4051 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4052 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4053 error1579 (expr.Type);
4057 if (expr.Type.IsArray) {
4058 array_type = expr.Type;
4059 element_type = TypeManager.GetElementType (array_type);
4061 empty = new EmptyExpression (element_type);
4063 hm = ProbeCollectionType (ec, expr.Type);
4065 error1579 (expr.Type);
4069 array_type = expr.Type;
4070 element_type = hm.element_type;
4072 empty = new EmptyExpression (hm.element_type);
4077 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4078 ec.CurrentBranching.CreateSibling ();
4082 // FIXME: maybe we can apply the same trick we do in the
4083 // array handling to avoid creating empty and conv in some cases.
4085 // Although it is not as important in this case, as the type
4086 // will not likely be object (what the enumerator will return).
4088 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4092 variable = variable.ResolveLValue (ec, empty);
4093 if (variable == null)
4096 bool disposable = (hm != null) && hm.is_disposable;
4097 FlowBranchingException branching = null;
4099 branching = ec.StartFlowBranching (this);
4101 if (!statement.Resolve (ec))
4105 ResolveFinally (branching);
4106 ec.EndFlowBranching ();
4108 emit_finally = true;
4110 ec.EndFlowBranching ();
4116 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4118 static MethodInfo FetchMethodMoveNext (Type t)
4120 MemberList move_next_list;
4122 move_next_list = TypeContainer.FindMembers (
4123 t, MemberTypes.Method,
4124 BindingFlags.Public | BindingFlags.Instance,
4125 Type.FilterName, "MoveNext");
4126 if (move_next_list.Count == 0)
4129 foreach (MemberInfo m in move_next_list){
4130 MethodInfo mi = (MethodInfo) m;
4133 args = TypeManager.GetArgumentTypes (mi);
4134 if (args != null && args.Length == 0){
4135 if (mi.ReturnType == TypeManager.bool_type)
4143 // Retrieves a `public T get_Current ()' method from the Type `t'
4145 static MethodInfo FetchMethodGetCurrent (Type t)
4147 MemberList get_current_list;
4149 get_current_list = TypeContainer.FindMembers (
4150 t, MemberTypes.Method,
4151 BindingFlags.Public | BindingFlags.Instance,
4152 Type.FilterName, "get_Current");
4153 if (get_current_list.Count == 0)
4156 foreach (MemberInfo m in get_current_list){
4157 MethodInfo mi = (MethodInfo) m;
4160 args = TypeManager.GetArgumentTypes (mi);
4161 if (args != null && args.Length == 0)
4168 // Retrieves a `public void Dispose ()' method from the Type `t'
4170 static MethodInfo FetchMethodDispose (Type t)
4172 MemberList dispose_list;
4174 dispose_list = TypeContainer.FindMembers (
4175 t, MemberTypes.Method,
4176 BindingFlags.Public | BindingFlags.Instance,
4177 Type.FilterName, "Dispose");
4178 if (dispose_list.Count == 0)
4181 foreach (MemberInfo m in dispose_list){
4182 MethodInfo mi = (MethodInfo) m;
4185 args = TypeManager.GetArgumentTypes (mi);
4186 if (args != null && args.Length == 0){
4187 if (mi.ReturnType == TypeManager.void_type)
4195 // This struct records the helper methods used by the Foreach construct
4197 class ForeachHelperMethods {
4198 public EmitContext ec;
4199 public MethodInfo get_enumerator;
4200 public MethodInfo move_next;
4201 public MethodInfo get_current;
4202 public Type element_type;
4203 public Type enumerator_type;
4204 public bool is_disposable;
4206 public ForeachHelperMethods (EmitContext ec)
4209 this.element_type = TypeManager.object_type;
4210 this.enumerator_type = TypeManager.ienumerator_type;
4211 this.is_disposable = true;
4215 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4220 if (!(m is MethodInfo))
4223 if (m.Name != "GetEnumerator")
4226 MethodInfo mi = (MethodInfo) m;
4227 Type [] args = TypeManager.GetArgumentTypes (mi);
4229 if (args.Length != 0)
4232 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4233 EmitContext ec = hm.ec;
4235 // Check whether GetEnumerator is public
4236 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4239 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4241 // Apply the same optimization as MS: skip the GetEnumerator
4242 // returning an IEnumerator, and use the one returning a
4243 // CharEnumerator instead. This allows us to avoid the
4244 // try-finally block and the boxing.
4249 // Ok, we can access it, now make sure that we can do something
4250 // with this `GetEnumerator'
4253 Type return_type = mi.ReturnType;
4254 if (mi.ReturnType == TypeManager.ienumerator_type ||
4255 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4256 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4259 // If it is not an interface, lets try to find the methods ourselves.
4260 // For example, if we have:
4261 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4262 // We can avoid the iface call. This is a runtime perf boost.
4263 // even bigger if we have a ValueType, because we avoid the cost
4266 // We have to make sure that both methods exist for us to take
4267 // this path. If one of the methods does not exist, we will just
4268 // use the interface. Sadly, this complex if statement is the only
4269 // way I could do this without a goto
4272 if (return_type.IsInterface ||
4273 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4274 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4276 hm.move_next = TypeManager.bool_movenext_void;
4277 hm.get_current = TypeManager.object_getcurrent_void;
4284 // Ok, so they dont return an IEnumerable, we will have to
4285 // find if they support the GetEnumerator pattern.
4288 hm.move_next = FetchMethodMoveNext (return_type);
4289 if (hm.move_next == null)
4292 hm.get_current = FetchMethodGetCurrent (return_type);
4293 if (hm.get_current == null)
4297 hm.element_type = hm.get_current.ReturnType;
4298 hm.enumerator_type = return_type;
4299 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4300 TypeManager.ImplementsInterface (
4301 hm.enumerator_type, TypeManager.idisposable_type);
4307 /// This filter is used to find the GetEnumerator method
4308 /// on which IEnumerator operates
4310 static MemberFilter FilterEnumerator;
4314 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4317 void error1579 (Type t)
4319 Report.Error (1579, loc,
4320 "foreach statement cannot operate on variables of type `" +
4321 t.FullName + "' because that class does not provide a " +
4322 " GetEnumerator method or it is inaccessible");
4325 static bool TryType (Type t, ForeachHelperMethods hm)
4329 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4330 BindingFlags.Public | BindingFlags.NonPublic |
4331 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4332 FilterEnumerator, hm);
4337 hm.get_enumerator = (MethodInfo) mi [0];
4342 // Looks for a usable GetEnumerator in the Type, and if found returns
4343 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4345 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4347 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4349 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4350 if (TryType (tt, hm))
4356 // Now try to find the method in the interfaces
4359 Type [] ifaces = t.GetInterfaces ();
4361 foreach (Type i in ifaces){
4362 if (TryType (i, hm))
4367 // Since TypeBuilder.GetInterfaces only returns the interface
4368 // types for this type, we have to keep looping, but once
4369 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4370 // done, because it returns all the types
4372 if ((t is TypeBuilder))
4382 // FIXME: possible optimization.
4383 // We might be able to avoid creating `empty' if the type is the sam
4385 bool EmitCollectionForeach (EmitContext ec)
4387 ILGenerator ig = ec.ig;
4389 enumerator = new VariableStorage (ec, hm.enumerator_type);
4390 enumerator.EmitThis (ig);
4392 // Instantiate the enumerator
4394 if (expr.Type.IsValueType) {
4395 IMemoryLocation ml = expr as IMemoryLocation;
4396 // Load the address of the value type.
4398 // This happens if, for example, you have a property
4399 // returning a struct which is IEnumerable
4400 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4402 ig.Emit (OpCodes.Stloc, t);
4403 ig.Emit (OpCodes.Ldloca, t);
4404 ec.FreeTemporaryLocal (t, expr.Type);
4406 ml.AddressOf (ec, AddressOp.Load);
4410 if (hm.get_enumerator.DeclaringType.IsValueType) {
4411 // the method is declared on the value type
4412 ig.Emit (OpCodes.Call, hm.get_enumerator);
4414 // it is an interface method, so we must box
4415 ig.Emit (OpCodes.Box, expr.Type);
4416 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4420 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4422 enumerator.EmitStore (ig);
4425 // Protect the code in a try/finalize block, so that
4426 // if the beast implement IDisposable, we get rid of it
4428 if (hm.is_disposable && emit_finally)
4429 ig.BeginExceptionBlock ();
4431 Label end_try = ig.DefineLabel ();
4433 ig.MarkLabel (ec.LoopBegin);
4435 enumerator.EmitCall (ig, hm.move_next);
4437 ig.Emit (OpCodes.Brfalse, end_try);
4440 enumerator.EmitThis (ig);
4441 enumerator.EmitCall (ig, hm.get_current);
4445 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4447 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4449 statement.Emit (ec);
4450 ig.Emit (OpCodes.Br, ec.LoopBegin);
4451 ig.MarkLabel (end_try);
4454 // Now the finally block
4456 if (hm.is_disposable) {
4459 ig.EndExceptionBlock ();
4462 ig.MarkLabel (ec.LoopEnd);
4466 public override void EmitFinally (EmitContext ec)
4468 ILGenerator ig = ec.ig;
4470 if (hm.enumerator_type.IsValueType) {
4471 enumerator.EmitThis (ig);
4473 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4475 enumerator.EmitLoadAddress (ig);
4476 ig.Emit (OpCodes.Call, mi);
4478 enumerator.EmitLoad (ig);
4479 ig.Emit (OpCodes.Box, hm.enumerator_type);
4480 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4483 Label call_dispose = ig.DefineLabel ();
4485 enumerator.EmitThis (ig);
4486 enumerator.EmitLoad (ig);
4487 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4488 ig.Emit (OpCodes.Dup);
4489 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4490 ig.Emit (OpCodes.Pop);
4492 Label end_finally = ig.DefineLabel ();
4493 ig.Emit (OpCodes.Br, end_finally);
4495 ig.MarkLabel (call_dispose);
4496 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4497 ig.MarkLabel (end_finally);
4500 ig.Emit (OpCodes.Endfinally);
4505 // FIXME: possible optimization.
4506 // We might be able to avoid creating `empty' if the type is the sam
4508 bool EmitArrayForeach (EmitContext ec)
4510 int rank = array_type.GetArrayRank ();
4511 ILGenerator ig = ec.ig;
4513 VariableStorage copy = new VariableStorage (ec, array_type);
4516 // Make our copy of the array
4520 copy.EmitStore (ig);
4523 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4527 counter.EmitThis (ig);
4528 ig.Emit (OpCodes.Ldc_I4_0);
4529 counter.EmitStore (ig);
4530 test = ig.DefineLabel ();
4531 ig.Emit (OpCodes.Br, test);
4533 loop = ig.DefineLabel ();
4534 ig.MarkLabel (loop);
4541 counter.EmitThis (ig);
4542 counter.EmitLoad (ig);
4545 // Load the value, we load the value using the underlying type,
4546 // then we use the variable.EmitAssign to load using the proper cast.
4548 ArrayAccess.EmitLoadOpcode (ig, element_type);
4551 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4553 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4555 statement.Emit (ec);
4557 ig.MarkLabel (ec.LoopBegin);
4558 counter.EmitThis (ig);
4559 counter.EmitThis (ig);
4560 counter.EmitLoad (ig);
4561 ig.Emit (OpCodes.Ldc_I4_1);
4562 ig.Emit (OpCodes.Add);
4563 counter.EmitStore (ig);
4565 ig.MarkLabel (test);
4566 counter.EmitThis (ig);
4567 counter.EmitLoad (ig);
4570 ig.Emit (OpCodes.Ldlen);
4571 ig.Emit (OpCodes.Conv_I4);
4572 ig.Emit (OpCodes.Blt, loop);
4574 VariableStorage [] dim_len = new VariableStorage [rank];
4575 VariableStorage [] dim_count = new VariableStorage [rank];
4576 Label [] loop = new Label [rank];
4577 Label [] test = new Label [rank];
4580 for (dim = 0; dim < rank; dim++){
4581 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4582 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4583 test [dim] = ig.DefineLabel ();
4584 loop [dim] = ig.DefineLabel ();
4587 for (dim = 0; dim < rank; dim++){
4588 dim_len [dim].EmitThis (ig);
4591 IntLiteral.EmitInt (ig, dim);
4592 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4593 dim_len [dim].EmitStore (ig);
4597 for (dim = 0; dim < rank; dim++){
4598 dim_count [dim].EmitThis (ig);
4599 ig.Emit (OpCodes.Ldc_I4_0);
4600 dim_count [dim].EmitStore (ig);
4601 ig.Emit (OpCodes.Br, test [dim]);
4602 ig.MarkLabel (loop [dim]);
4609 for (dim = 0; dim < rank; dim++){
4610 dim_count [dim].EmitThis (ig);
4611 dim_count [dim].EmitLoad (ig);
4615 // FIXME: Maybe we can cache the computation of `get'?
4617 Type [] args = new Type [rank];
4620 for (int i = 0; i < rank; i++)
4621 args [i] = TypeManager.int32_type;
4623 ModuleBuilder mb = CodeGen.Module.Builder;
4624 get = mb.GetArrayMethod (
4626 CallingConventions.HasThis| CallingConventions.Standard,
4628 ig.Emit (OpCodes.Call, get);
4631 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4633 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4634 statement.Emit (ec);
4635 ig.MarkLabel (ec.LoopBegin);
4636 for (dim = rank - 1; dim >= 0; dim--){
4637 dim_count [dim].EmitThis (ig);
4638 dim_count [dim].EmitThis (ig);
4639 dim_count [dim].EmitLoad (ig);
4640 ig.Emit (OpCodes.Ldc_I4_1);
4641 ig.Emit (OpCodes.Add);
4642 dim_count [dim].EmitStore (ig);
4644 ig.MarkLabel (test [dim]);
4645 dim_count [dim].EmitThis (ig);
4646 dim_count [dim].EmitLoad (ig);
4647 dim_len [dim].EmitThis (ig);
4648 dim_len [dim].EmitLoad (ig);
4649 ig.Emit (OpCodes.Blt, loop [dim]);
4652 ig.MarkLabel (ec.LoopEnd);
4657 protected override void DoEmit (EmitContext ec)
4659 ILGenerator ig = ec.ig;
4661 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4662 ec.LoopBegin = ig.DefineLabel ();
4663 ec.LoopEnd = ig.DefineLabel ();
4666 EmitCollectionForeach (ec);
4668 EmitArrayForeach (ec);
4670 ec.LoopBegin = old_begin;
4671 ec.LoopEnd = old_end;