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 child_variable_names [name] = null;
1437 // Checks whether a variable name has already been used in a child block.
1439 public bool IsVariableNameUsedInChildBlock (string name)
1441 if (child_variable_names == null)
1444 return child_variable_names.Contains (name);
1448 // This is used by non-static `struct' constructors which do not have an
1449 // initializer - in this case, the constructor must initialize all of the
1450 // struct's fields. To do this, we add a "this" variable and use the flow
1451 // analysis code to ensure that it's been fully initialized before control
1452 // leaves the constructor.
1454 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1456 if (this_variable != null)
1457 return this_variable;
1459 if (variables == null)
1460 variables = new Hashtable ();
1462 this_variable = new LocalInfo (tc, this, l);
1463 this_variable.Used = true;
1464 this_variable.IsThis = true;
1466 variables.Add ("this", this_variable);
1468 return this_variable;
1471 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1473 if (variables == null)
1474 variables = new Hashtable ();
1476 LocalInfo vi = GetLocalInfo (name);
1478 if (vi.Block != this)
1479 Report.Error (136, l, "A local variable named `" + name + "' " +
1480 "cannot be declared in this scope since it would " +
1481 "give a different meaning to `" + name + "', which " +
1482 "is already used in a `parent or current' scope to " +
1483 "denote something else");
1485 Report.Error (128, l, "A local variable `" + name + "' is already " +
1486 "defined in this scope");
1490 if (IsVariableNameUsedInChildBlock (name)) {
1491 Report.Error (136, l, "A local variable named `" + name + "' " +
1492 "cannot be declared in this scope since it would " +
1493 "give a different meaning to `" + name + "', which " +
1494 "is already used in a `child' scope to denote something " +
1501 Parameter p = pars.GetParameterByName (name, out idx);
1503 Report.Error (136, l, "A local variable named `" + name + "' " +
1504 "cannot be declared in this scope since it would " +
1505 "give a different meaning to `" + name + "', which " +
1506 "is already used in a `parent or current' scope to " +
1507 "denote something else");
1512 vi = new LocalInfo (type, name, this, l);
1514 variables.Add (name, vi);
1516 // Mark 'name' as "used by a child block" in every surrounding block
1518 while (cur != null && cur.Implicit)
1521 for (Block par = cur.Parent; par != null; par = par.Parent)
1522 par.AddChildVariableName (name);
1524 if ((flags & Flags.VariablesInitialized) != 0)
1525 throw new Exception ();
1527 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1531 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1533 if (AddVariable (type, name, pars, l) == null)
1536 if (constants == null)
1537 constants = new Hashtable ();
1539 constants.Add (name, value);
1543 public Hashtable Variables {
1549 public LocalInfo GetLocalInfo (string name)
1551 for (Block b = this; b != null; b = b.Parent) {
1552 if (b.variables != null) {
1553 LocalInfo ret = b.variables [name] as LocalInfo;
1561 public Expression GetVariableType (string name)
1563 LocalInfo vi = GetLocalInfo (name);
1571 public Expression GetConstantExpression (string name)
1573 for (Block b = this; b != null; b = b.Parent) {
1574 if (b.constants != null) {
1575 Expression ret = b.constants [name] as Expression;
1584 /// True if the variable named @name is a constant
1586 public bool IsConstant (string name)
1588 Expression e = null;
1590 e = GetConstantExpression (name);
1596 // Returns a `ParameterReference' for the given name, or null if there
1597 // is no such parameter
1599 public ParameterReference GetParameterReference (string name, Location loc)
1604 Parameters pars = b.parameters;
1610 par = pars.GetParameterByName (name, out idx);
1612 ParameterReference pr;
1614 pr = new ParameterReference (pars, this, idx, name, loc);
1619 } while (b != null);
1624 // Whether the parameter named `name' is local to this block,
1625 // or false, if the parameter belongs to an encompassing block.
1627 public bool IsLocalParameter (string name)
1630 int toplevel_count = 0;
1633 if (this is ToplevelBlock)
1636 Parameters pars = b.parameters;
1638 if (pars.GetParameterByName (name) != null)
1642 if (toplevel_count > 0)
1645 } while (b != null);
1650 // Whether the `name' is a parameter reference
1652 public bool IsParameterReference (string name)
1657 Parameters pars = b.parameters;
1660 if (pars.GetParameterByName (name) != null)
1663 } while (b != null);
1668 /// A list of labels that were not used within this block
1670 public string [] GetUnreferenced ()
1672 // FIXME: Implement me
1676 public void AddStatement (Statement s)
1679 flags |= Flags.BlockUsed;
1684 return (flags & Flags.BlockUsed) != 0;
1690 flags |= Flags.BlockUsed;
1693 public bool HasRet {
1695 return (flags & Flags.HasRet) != 0;
1699 public bool IsDestructor {
1701 return (flags & Flags.IsDestructor) != 0;
1705 public void SetDestructor ()
1707 flags |= Flags.IsDestructor;
1710 VariableMap param_map, local_map;
1712 public VariableMap ParameterMap {
1714 if ((flags & Flags.VariablesInitialized) == 0)
1715 throw new Exception ("Variables have not been initialized yet");
1721 public VariableMap LocalMap {
1723 if ((flags & Flags.VariablesInitialized) == 0)
1724 throw new Exception ("Variables have not been initialized yet");
1731 /// Emits the variable declarations and labels.
1734 /// tc: is our typecontainer (to resolve type references)
1735 /// ig: is the code generator:
1737 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1739 ILGenerator ig = ec.ig;
1741 bool old_unsafe = ec.InUnsafe;
1743 // If some parent block was unsafe, we remain unsafe even if this block
1744 // isn't explicitly marked as such.
1745 ec.InUnsafe |= Unsafe;
1748 // Compute the VariableMap's.
1750 // Unfortunately, we don't know the type when adding variables with
1751 // AddVariable(), so we need to compute this info here.
1755 if (variables != null) {
1756 foreach (LocalInfo li in variables.Values)
1759 locals = new LocalInfo [variables.Count];
1760 variables.Values.CopyTo (locals, 0);
1762 locals = new LocalInfo [0];
1765 local_map = new VariableMap (Parent.LocalMap, locals);
1767 local_map = new VariableMap (locals);
1769 param_map = new VariableMap (ip);
1770 flags |= Flags.VariablesInitialized;
1772 bool old_check_state = ec.ConstantCheckState;
1773 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1776 // Process this block variables
1778 if (variables != null){
1779 foreach (DictionaryEntry de in variables){
1780 string name = (string) de.Key;
1781 LocalInfo vi = (LocalInfo) de.Value;
1783 if (vi.VariableType == null)
1786 Type variable_type = vi.VariableType;
1788 if (variable_type.IsPointer){
1790 // Am not really convinced that this test is required (Microsoft does it)
1791 // but the fact is that you would not be able to use the pointer variable
1794 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1801 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1804 // This is needed to compile on both .NET 1.x and .NET 2.x
1805 // the later introduced `DeclareLocal (Type t, bool pinned)'
1807 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1808 else if (!vi.IsThis)
1809 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1812 if (constants == null)
1815 Expression cv = (Expression) constants [name];
1819 ec.CurrentBlock = this;
1820 Expression e = cv.Resolve (ec);
1824 Constant ce = e as Constant;
1826 Report.Error (133, vi.Location,
1827 "The expression being assigned to `" +
1828 name + "' must be constant (" + e + ")");
1832 if (e.Type != variable_type){
1833 e = Const.ChangeType (vi.Location, ce, variable_type);
1838 constants.Remove (name);
1839 constants.Add (name, e);
1842 ec.ConstantCheckState = old_check_state;
1845 // Now, handle the children
1847 if (children != null){
1848 foreach (Block b in children)
1849 b.ResolveMeta (toplevel, ec, ip);
1851 ec.InUnsafe = old_unsafe;
1855 // Emits the local variable declarations for a block
1857 public void EmitMeta (EmitContext ec)
1859 ILGenerator ig = ec.ig;
1861 if (variables != null){
1862 bool have_captured_vars = ec.HaveCapturedVariables ();
1863 bool remap_locals = ec.RemapToProxy;
1865 foreach (DictionaryEntry de in variables){
1866 LocalInfo vi = (LocalInfo) de.Value;
1868 if (have_captured_vars && ec.IsCaptured (vi))
1872 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1876 // This is needed to compile on both .NET 1.x and .NET 2.x
1877 // the later introduced `DeclareLocal (Type t, bool pinned)'
1879 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1880 else if (!vi.IsThis)
1881 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1886 if (children != null){
1887 foreach (Block b in children)
1892 void UsageWarning (FlowBranching.UsageVector vector)
1896 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1897 foreach (DictionaryEntry de in variables){
1898 LocalInfo vi = (LocalInfo) de.Value;
1903 name = (string) de.Key;
1905 if (vector.IsAssigned (vi.VariableInfo)){
1906 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1908 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1914 bool unreachable_shown;
1916 public override bool Resolve (EmitContext ec)
1918 Block prev_block = ec.CurrentBlock;
1921 int errors = Report.Errors;
1923 ec.CurrentBlock = this;
1924 ec.StartFlowBranching (this);
1926 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1928 bool unreachable = false;
1930 int statement_count = statements.Count;
1931 for (int ix = 0; ix < statement_count; ix++){
1932 Statement s = (Statement) statements [ix];
1934 if (unreachable && !(s is LabeledStatement)) {
1935 if (s == EmptyStatement.Value)
1936 s.loc = EndLocation;
1938 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1941 if (s != EmptyStatement.Value)
1942 unreachable_shown = true;
1944 s.loc = Location.Null;
1946 statements [ix] = EmptyStatement.Value;
1950 if (s.Resolve (ec) == false) {
1952 statements [ix] = EmptyStatement.Value;
1956 num_statements = ix + 1;
1958 if (s is LabeledStatement)
1959 unreachable = false;
1961 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1964 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1965 ec.CurrentBranching, statement_count, num_statements);
1968 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1970 ec.CurrentBlock = prev_block;
1972 // If we're a non-static `struct' constructor which doesn't have an
1973 // initializer, then we must initialize all of the struct's fields.
1974 if ((this_variable != null) &&
1975 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1976 !this_variable.IsThisAssigned (ec, loc))
1979 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1980 foreach (LabeledStatement label in labels.Values)
1981 if (!label.HasBeenReferenced)
1982 Report.Warning (164, label.Location,
1983 "This label has not been referenced");
1986 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1988 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1989 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1990 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1991 flags |= Flags.HasRet;
1993 if (ok && (errors == Report.Errors)) {
1994 if (RootContext.WarningLevel >= 3)
1995 UsageWarning (vector);
2001 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2003 unreachable_shown = true;
2004 return base.ResolveUnreachable (ec, warn);
2007 protected override void DoEmit (EmitContext ec)
2009 for (int ix = 0; ix < num_statements; ix++){
2010 Statement s = (Statement) statements [ix];
2012 // Check whether we are the last statement in a
2015 if ((Parent == null) && (ix+1 == num_statements))
2016 ec.IsLastStatement = true;
2018 ec.IsLastStatement = false;
2024 public override void Emit (EmitContext ec)
2026 Block prev_block = ec.CurrentBlock;
2028 ec.CurrentBlock = this;
2030 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2031 bool is_lexical_block = !Implicit && (Parent != null);
2033 if (emit_debug_info) {
2034 if (is_lexical_block)
2035 ec.ig.BeginScope ();
2037 if (variables != null) {
2038 foreach (DictionaryEntry de in variables) {
2039 string name = (string) de.Key;
2040 LocalInfo vi = (LocalInfo) de.Value;
2042 if (vi.LocalBuilder == null)
2045 ec.DefineLocalVariable (name, vi.LocalBuilder);
2050 ec.Mark (StartLocation, true);
2052 ec.Mark (EndLocation, true);
2054 if (emit_debug_info && is_lexical_block)
2057 ec.CurrentBlock = prev_block;
2060 public ToplevelBlock Toplevel {
2063 while (b.Parent != null){
2064 if ((b.flags & Flags.IsToplevel) != 0)
2069 return (ToplevelBlock) b;
2074 // Returns true if we ar ea child of `b'.
2076 public bool IsChildOf (Block b)
2078 Block current = this;
2081 if (current.Parent == b)
2083 current = current.Parent;
2084 } while (current != null);
2090 // A toplevel block contains extra information, the split is done
2091 // only to separate information that would otherwise bloat the more
2092 // lightweight Block.
2094 // In particular, this was introduced when the support for Anonymous
2095 // Methods was implemented.
2097 public class ToplevelBlock : Block {
2099 // Pointer to the host of this anonymous method, or null
2100 // if we are the topmost block
2102 public ToplevelBlock Container;
2103 CaptureContext capture_context;
2105 Hashtable capture_contexts;
2112 public void RegisterCaptureContext (CaptureContext cc)
2114 if (capture_contexts == null)
2115 capture_contexts = new Hashtable ();
2116 capture_contexts [cc] = cc;
2119 public void CompleteContexts ()
2121 if (capture_contexts == null)
2124 foreach (CaptureContext cc in capture_contexts.Keys){
2129 public CaptureContext ToplevelBlockCaptureContext {
2131 return capture_context;
2136 // Parent is only used by anonymous blocks to link back to their
2139 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2140 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2142 Container = container;
2145 public ToplevelBlock (Parameters parameters, Location start) :
2146 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2150 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2151 base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2155 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2159 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2161 if (capture_context == null)
2162 capture_context = new CaptureContext (this, loc, host);
2165 public CaptureContext CaptureContext {
2167 return capture_context;
2172 public class SwitchLabel {
2175 public Location loc;
2179 Label il_label_code;
2180 bool il_label_code_set;
2183 // if expr == null, then it is the default case.
2185 public SwitchLabel (Expression expr, Location l)
2191 public Expression Label {
2197 public object Converted {
2203 public Label GetILLabel (EmitContext ec)
2206 il_label = ec.ig.DefineLabel ();
2207 il_label_set = true;
2212 public Label GetILLabelCode (EmitContext ec)
2214 if (!il_label_code_set){
2215 il_label_code = ec.ig.DefineLabel ();
2216 il_label_code_set = true;
2218 return il_label_code;
2222 // Resolves the expression, reduces it to a literal if possible
2223 // and then converts it to the requested type.
2225 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2230 Expression e = label.Resolve (ec);
2235 if (!(e is Constant)){
2236 Report.Error (150, loc, "A constant value is expected, got: " + e);
2240 if (e is StringConstant || e is NullLiteral){
2241 if (required_type == TypeManager.string_type){
2247 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2248 if (converted == null)
2255 public class SwitchSection {
2256 // An array of SwitchLabels.
2257 public readonly ArrayList Labels;
2258 public readonly Block Block;
2260 public SwitchSection (ArrayList labels, Block block)
2267 public class Switch : Statement {
2268 public readonly ArrayList Sections;
2269 public Expression Expr;
2272 /// Maps constants whose type type SwitchType to their SwitchLabels.
2274 public Hashtable Elements;
2277 /// The governing switch type
2279 public Type SwitchType;
2285 Label default_target;
2286 Expression new_expr;
2288 SwitchSection constant_section;
2291 // The types allowed to be implicitly cast from
2292 // on the governing type
2294 static Type [] allowed_types;
2296 public Switch (Expression e, ArrayList sects, Location l)
2303 public bool GotDefault {
2309 public Label DefaultTarget {
2311 return default_target;
2316 // Determines the governing type for a switch. The returned
2317 // expression might be the expression from the switch, or an
2318 // expression that includes any potential conversions to the
2319 // integral types or to string.
2321 Expression SwitchGoverningType (EmitContext ec, Type t)
2323 if (t == TypeManager.int32_type ||
2324 t == TypeManager.uint32_type ||
2325 t == TypeManager.char_type ||
2326 t == TypeManager.byte_type ||
2327 t == TypeManager.sbyte_type ||
2328 t == TypeManager.ushort_type ||
2329 t == TypeManager.short_type ||
2330 t == TypeManager.uint64_type ||
2331 t == TypeManager.int64_type ||
2332 t == TypeManager.string_type ||
2333 t == TypeManager.bool_type ||
2334 t.IsSubclassOf (TypeManager.enum_type))
2337 if (allowed_types == null){
2338 allowed_types = new Type [] {
2339 TypeManager.sbyte_type,
2340 TypeManager.byte_type,
2341 TypeManager.short_type,
2342 TypeManager.ushort_type,
2343 TypeManager.int32_type,
2344 TypeManager.uint32_type,
2345 TypeManager.int64_type,
2346 TypeManager.uint64_type,
2347 TypeManager.char_type,
2348 TypeManager.bool_type,
2349 TypeManager.string_type
2354 // Try to find a *user* defined implicit conversion.
2356 // If there is no implicit conversion, or if there are multiple
2357 // conversions, we have to report an error
2359 Expression converted = null;
2360 foreach (Type tt in allowed_types){
2363 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2367 if (converted != null){
2368 Report.Error (-12, loc, "More than one conversion to an integral " +
2369 " type exists for type `" +
2370 TypeManager.CSharpName (Expr.Type)+"'");
2378 static string Error152 {
2380 return "The label '{0}:' already occurs in this switch statement";
2385 // Performs the basic sanity checks on the switch statement
2386 // (looks for duplicate keys and non-constant expressions).
2388 // It also returns a hashtable with the keys that we will later
2389 // use to compute the switch tables
2391 bool CheckSwitch (EmitContext ec)
2395 Elements = new Hashtable ();
2397 got_default = false;
2399 if (TypeManager.IsEnumType (SwitchType)){
2400 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2402 compare_type = SwitchType;
2404 foreach (SwitchSection ss in Sections){
2405 foreach (SwitchLabel sl in ss.Labels){
2406 if (!sl.ResolveAndReduce (ec, SwitchType)){
2411 if (sl.Label == null){
2413 Report.Error (152, sl.loc, Error152, "default");
2420 object key = sl.Converted;
2422 if (key is Constant)
2423 key = ((Constant) key).GetValue ();
2426 key = NullLiteral.Null;
2428 string lname = null;
2429 if (compare_type == TypeManager.uint64_type){
2430 ulong v = (ulong) key;
2432 if (Elements.Contains (v))
2433 lname = v.ToString ();
2435 Elements.Add (v, sl);
2436 } else if (compare_type == TypeManager.int64_type){
2437 long v = (long) key;
2439 if (Elements.Contains (v))
2440 lname = v.ToString ();
2442 Elements.Add (v, sl);
2443 } else if (compare_type == TypeManager.uint32_type){
2444 uint v = (uint) key;
2446 if (Elements.Contains (v))
2447 lname = v.ToString ();
2449 Elements.Add (v, sl);
2450 } else if (compare_type == TypeManager.char_type){
2451 char v = (char) key;
2453 if (Elements.Contains (v))
2454 lname = v.ToString ();
2456 Elements.Add (v, sl);
2457 } else if (compare_type == TypeManager.byte_type){
2458 byte v = (byte) key;
2460 if (Elements.Contains (v))
2461 lname = v.ToString ();
2463 Elements.Add (v, sl);
2464 } else if (compare_type == TypeManager.sbyte_type){
2465 sbyte v = (sbyte) key;
2467 if (Elements.Contains (v))
2468 lname = v.ToString ();
2470 Elements.Add (v, sl);
2471 } else if (compare_type == TypeManager.short_type){
2472 short v = (short) key;
2474 if (Elements.Contains (v))
2475 lname = v.ToString ();
2477 Elements.Add (v, sl);
2478 } else if (compare_type == TypeManager.ushort_type){
2479 ushort v = (ushort) key;
2481 if (Elements.Contains (v))
2482 lname = v.ToString ();
2484 Elements.Add (v, sl);
2485 } else if (compare_type == TypeManager.string_type){
2486 if (key is NullLiteral){
2487 if (Elements.Contains (NullLiteral.Null))
2490 Elements.Add (NullLiteral.Null, null);
2492 string s = (string) key;
2494 if (Elements.Contains (s))
2497 Elements.Add (s, sl);
2499 } else if (compare_type == TypeManager.int32_type) {
2502 if (Elements.Contains (v))
2503 lname = v.ToString ();
2505 Elements.Add (v, sl);
2506 } else if (compare_type == TypeManager.bool_type) {
2507 bool v = (bool) key;
2509 if (Elements.Contains (v))
2510 lname = v.ToString ();
2512 Elements.Add (v, sl);
2516 throw new Exception ("Unknown switch type!" +
2517 SwitchType + " " + compare_type);
2520 if (lname != null) {
2521 Report.Error (152, sl.loc, Error152, "case " + lname);
2532 void EmitObjectInteger (ILGenerator ig, object k)
2535 IntConstant.EmitInt (ig, (int) k);
2536 else if (k is Constant) {
2537 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2540 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2543 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2545 IntConstant.EmitInt (ig, (int) (long) k);
2546 ig.Emit (OpCodes.Conv_I8);
2549 LongConstant.EmitLong (ig, (long) k);
2551 else if (k is ulong)
2553 if ((ulong) k < (1L<<32))
2555 IntConstant.EmitInt (ig, (int) (long) k);
2556 ig.Emit (OpCodes.Conv_U8);
2560 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2564 IntConstant.EmitInt (ig, (int) ((char) k));
2565 else if (k is sbyte)
2566 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2568 IntConstant.EmitInt (ig, (int) ((byte) k));
2569 else if (k is short)
2570 IntConstant.EmitInt (ig, (int) ((short) k));
2571 else if (k is ushort)
2572 IntConstant.EmitInt (ig, (int) ((ushort) k));
2574 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2576 throw new Exception ("Unhandled case");
2579 // structure used to hold blocks of keys while calculating table switch
2580 class KeyBlock : IComparable
2582 public KeyBlock (long _nFirst)
2584 nFirst = nLast = _nFirst;
2588 public ArrayList rgKeys = null;
2589 // how many items are in the bucket
2590 public int Size = 1;
2593 get { return (int) (nLast - nFirst + 1); }
2595 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2597 return kbLast.nLast - kbFirst.nFirst + 1;
2599 public int CompareTo (object obj)
2601 KeyBlock kb = (KeyBlock) obj;
2602 int nLength = Length;
2603 int nLengthOther = kb.Length;
2604 if (nLengthOther == nLength)
2605 return (int) (kb.nFirst - nFirst);
2606 return nLength - nLengthOther;
2611 /// This method emits code for a lookup-based switch statement (non-string)
2612 /// Basically it groups the cases into blocks that are at least half full,
2613 /// and then spits out individual lookup opcodes for each block.
2614 /// It emits the longest blocks first, and short blocks are just
2615 /// handled with direct compares.
2617 /// <param name="ec"></param>
2618 /// <param name="val"></param>
2619 /// <returns></returns>
2620 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2622 int cElements = Elements.Count;
2623 object [] rgKeys = new object [cElements];
2624 Elements.Keys.CopyTo (rgKeys, 0);
2625 Array.Sort (rgKeys);
2627 // initialize the block list with one element per key
2628 ArrayList rgKeyBlocks = new ArrayList ();
2629 foreach (object key in rgKeys)
2630 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2633 // iteratively merge the blocks while they are at least half full
2634 // there's probably a really cool way to do this with a tree...
2635 while (rgKeyBlocks.Count > 1)
2637 ArrayList rgKeyBlocksNew = new ArrayList ();
2638 kbCurr = (KeyBlock) rgKeyBlocks [0];
2639 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2641 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2642 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2645 kbCurr.nLast = kb.nLast;
2646 kbCurr.Size += kb.Size;
2650 // start a new block
2651 rgKeyBlocksNew.Add (kbCurr);
2655 rgKeyBlocksNew.Add (kbCurr);
2656 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2658 rgKeyBlocks = rgKeyBlocksNew;
2661 // initialize the key lists
2662 foreach (KeyBlock kb in rgKeyBlocks)
2663 kb.rgKeys = new ArrayList ();
2665 // fill the key lists
2667 if (rgKeyBlocks.Count > 0) {
2668 kbCurr = (KeyBlock) rgKeyBlocks [0];
2669 foreach (object key in rgKeys)
2671 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2672 System.Convert.ToInt64 (key) > kbCurr.nLast;
2674 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2675 kbCurr.rgKeys.Add (key);
2679 // sort the blocks so we can tackle the largest ones first
2680 rgKeyBlocks.Sort ();
2682 // okay now we can start...
2683 ILGenerator ig = ec.ig;
2684 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2685 Label lblDefault = ig.DefineLabel ();
2687 Type typeKeys = null;
2688 if (rgKeys.Length > 0)
2689 typeKeys = rgKeys [0].GetType (); // used for conversions
2693 if (TypeManager.IsEnumType (SwitchType))
2694 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2696 compare_type = SwitchType;
2698 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2700 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2701 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2704 foreach (object key in kb.rgKeys)
2706 ig.Emit (OpCodes.Ldloc, val);
2707 EmitObjectInteger (ig, key);
2708 SwitchLabel sl = (SwitchLabel) Elements [key];
2709 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2714 // TODO: if all the keys in the block are the same and there are
2715 // no gaps/defaults then just use a range-check.
2716 if (compare_type == TypeManager.int64_type ||
2717 compare_type == TypeManager.uint64_type)
2719 // TODO: optimize constant/I4 cases
2721 // check block range (could be > 2^31)
2722 ig.Emit (OpCodes.Ldloc, val);
2723 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2724 ig.Emit (OpCodes.Blt, lblDefault);
2725 ig.Emit (OpCodes.Ldloc, val);
2726 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2727 ig.Emit (OpCodes.Bgt, lblDefault);
2730 ig.Emit (OpCodes.Ldloc, val);
2733 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2734 ig.Emit (OpCodes.Sub);
2736 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2741 ig.Emit (OpCodes.Ldloc, val);
2742 int nFirst = (int) kb.nFirst;
2745 IntConstant.EmitInt (ig, nFirst);
2746 ig.Emit (OpCodes.Sub);
2748 else if (nFirst < 0)
2750 IntConstant.EmitInt (ig, -nFirst);
2751 ig.Emit (OpCodes.Add);
2755 // first, build the list of labels for the switch
2757 int cJumps = kb.Length;
2758 Label [] rgLabels = new Label [cJumps];
2759 for (int iJump = 0; iJump < cJumps; iJump++)
2761 object key = kb.rgKeys [iKey];
2762 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2764 SwitchLabel sl = (SwitchLabel) Elements [key];
2765 rgLabels [iJump] = sl.GetILLabel (ec);
2769 rgLabels [iJump] = lblDefault;
2771 // emit the switch opcode
2772 ig.Emit (OpCodes.Switch, rgLabels);
2775 // mark the default for this block
2777 ig.MarkLabel (lblDefault);
2780 // TODO: find the default case and emit it here,
2781 // to prevent having to do the following jump.
2782 // make sure to mark other labels in the default section
2784 // the last default just goes to the end
2785 ig.Emit (OpCodes.Br, lblDefault);
2787 // now emit the code for the sections
2788 bool fFoundDefault = false;
2789 foreach (SwitchSection ss in Sections)
2791 foreach (SwitchLabel sl in ss.Labels)
2793 ig.MarkLabel (sl.GetILLabel (ec));
2794 ig.MarkLabel (sl.GetILLabelCode (ec));
2795 if (sl.Label == null)
2797 ig.MarkLabel (lblDefault);
2798 fFoundDefault = true;
2802 //ig.Emit (OpCodes.Br, lblEnd);
2805 if (!fFoundDefault) {
2806 ig.MarkLabel (lblDefault);
2808 ig.MarkLabel (lblEnd);
2811 // This simple emit switch works, but does not take advantage of the
2813 // TODO: remove non-string logic from here
2814 // TODO: binary search strings?
2816 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2818 ILGenerator ig = ec.ig;
2819 Label end_of_switch = ig.DefineLabel ();
2820 Label next_test = ig.DefineLabel ();
2821 Label null_target = ig.DefineLabel ();
2822 bool default_found = false;
2823 bool first_test = true;
2824 bool pending_goto_end = false;
2826 bool default_at_end = false;
2828 ig.Emit (OpCodes.Ldloc, val);
2830 if (Elements.Contains (NullLiteral.Null)){
2831 ig.Emit (OpCodes.Brfalse, null_target);
2833 ig.Emit (OpCodes.Brfalse, default_target);
2835 ig.Emit (OpCodes.Ldloc, val);
2836 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2837 ig.Emit (OpCodes.Stloc, val);
2839 int section_count = Sections.Count;
2840 for (int section = 0; section < section_count; section++){
2841 SwitchSection ss = (SwitchSection) Sections [section];
2842 Label sec_begin = ig.DefineLabel ();
2844 if (pending_goto_end)
2845 ig.Emit (OpCodes.Br, end_of_switch);
2847 int label_count = ss.Labels.Count;
2848 bool mark_default = false;
2850 for (int label = 0; label < label_count; label++){
2851 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2852 ig.MarkLabel (sl.GetILLabel (ec));
2855 ig.MarkLabel (next_test);
2856 next_test = ig.DefineLabel ();
2859 // If we are the default target
2861 if (sl.Label == null){
2862 if (label+1 == label_count)
2863 default_at_end = true;
2864 mark_default = true;
2865 default_found = true;
2867 object lit = sl.Converted;
2869 if (lit is NullLiteral){
2871 if (label_count == 1)
2872 ig.Emit (OpCodes.Br, next_test);
2876 StringConstant str = (StringConstant) lit;
2878 ig.Emit (OpCodes.Ldloc, val);
2879 ig.Emit (OpCodes.Ldstr, str.Value);
2880 if (label_count == 1)
2881 ig.Emit (OpCodes.Bne_Un, next_test);
2883 if (label+1 == label_count)
2884 ig.Emit (OpCodes.Bne_Un, next_test);
2886 ig.Emit (OpCodes.Beq, sec_begin);
2891 ig.MarkLabel (null_target);
2892 ig.MarkLabel (sec_begin);
2893 foreach (SwitchLabel sl in ss.Labels)
2894 ig.MarkLabel (sl.GetILLabelCode (ec));
2897 ig.MarkLabel (default_target);
2899 pending_goto_end = !ss.Block.HasRet;
2902 ig.MarkLabel (next_test);
2904 if (!default_at_end)
2905 ig.Emit (OpCodes.Br, default_target);
2907 ig.MarkLabel (default_target);
2908 ig.MarkLabel (end_of_switch);
2911 SwitchSection FindSection (SwitchLabel label)
2913 foreach (SwitchSection ss in Sections){
2914 foreach (SwitchLabel sl in ss.Labels){
2923 bool ResolveConstantSwitch (EmitContext ec)
2925 object key = ((Constant) new_expr).GetValue ();
2926 SwitchLabel label = (SwitchLabel) Elements [key];
2931 constant_section = FindSection (label);
2932 if (constant_section == null)
2935 if (constant_section.Block.Resolve (ec) != true)
2941 public override bool Resolve (EmitContext ec)
2943 Expr = Expr.Resolve (ec);
2947 new_expr = SwitchGoverningType (ec, Expr.Type);
2948 if (new_expr == null){
2949 Report.Error (151, loc, "An integer type or string was expected for switch");
2954 SwitchType = new_expr.Type;
2956 if (!CheckSwitch (ec))
2959 Switch old_switch = ec.Switch;
2961 ec.Switch.SwitchType = SwitchType;
2963 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2964 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2966 is_constant = new_expr is Constant;
2968 object key = ((Constant) new_expr).GetValue ();
2969 SwitchLabel label = (SwitchLabel) Elements [key];
2971 constant_section = FindSection (label);
2975 foreach (SwitchSection ss in Sections){
2977 ec.CurrentBranching.CreateSibling (
2978 null, FlowBranching.SiblingType.SwitchSection);
2982 if (is_constant && (ss != constant_section)) {
2983 // If we're a constant switch, we're only emitting
2984 // one single section - mark all the others as
2986 ec.CurrentBranching.CurrentUsageVector.Goto ();
2987 if (!ss.Block.ResolveUnreachable (ec, true))
2990 if (!ss.Block.Resolve (ec))
2996 ec.CurrentBranching.CreateSibling (
2997 null, FlowBranching.SiblingType.SwitchSection);
2999 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3000 ec.Switch = old_switch;
3002 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3008 protected override void DoEmit (EmitContext ec)
3010 ILGenerator ig = ec.ig;
3012 // Store variable for comparission purposes
3015 value = ig.DeclareLocal (SwitchType);
3017 ig.Emit (OpCodes.Stloc, value);
3021 default_target = ig.DefineLabel ();
3024 // Setup the codegen context
3026 Label old_end = ec.LoopEnd;
3027 Switch old_switch = ec.Switch;
3029 ec.LoopEnd = ig.DefineLabel ();
3034 if (constant_section != null)
3035 constant_section.Block.Emit (ec);
3036 } else if (SwitchType == TypeManager.string_type)
3037 SimpleSwitchEmit (ec, value);
3039 TableSwitchEmit (ec, value);
3041 // Restore context state.
3042 ig.MarkLabel (ec.LoopEnd);
3045 // Restore the previous context
3047 ec.LoopEnd = old_end;
3048 ec.Switch = old_switch;
3052 public abstract class ExceptionStatement : Statement
3054 public abstract void EmitFinally (EmitContext ec);
3056 protected bool emit_finally = true;
3057 ArrayList parent_vectors;
3059 protected void DoEmitFinally (EmitContext ec)
3062 ec.ig.BeginFinallyBlock ();
3064 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3068 protected void ResolveFinally (FlowBranchingException branching)
3070 emit_finally = branching.EmitFinally;
3072 branching.Parent.StealFinallyClauses (ref parent_vectors);
3076 public class Lock : ExceptionStatement {
3078 Statement Statement;
3081 public Lock (Expression expr, Statement stmt, Location l)
3088 public override bool Resolve (EmitContext ec)
3090 expr = expr.Resolve (ec);
3094 if (expr.Type.IsValueType){
3095 Error (185, "lock statement requires the expression to be " +
3096 " a reference type (type is: `{0}'",
3097 TypeManager.CSharpName (expr.Type));
3101 FlowBranchingException branching = ec.StartFlowBranching (this);
3102 bool ok = Statement.Resolve (ec);
3104 ec.KillFlowBranching ();
3108 ResolveFinally (branching);
3110 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3111 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3112 // Unfortunately, System.Reflection.Emit automatically emits
3113 // a leave to the end of the finally block.
3114 // This is a problem if `returns' is true since we may jump
3115 // to a point after the end of the method.
3116 // As a workaround, emit an explicit ret here.
3117 ec.NeedReturnLabel ();
3123 protected override void DoEmit (EmitContext ec)
3125 Type type = expr.Type;
3127 ILGenerator ig = ec.ig;
3128 temp = ig.DeclareLocal (type);
3131 ig.Emit (OpCodes.Dup);
3132 ig.Emit (OpCodes.Stloc, temp);
3133 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3137 ig.BeginExceptionBlock ();
3138 Statement.Emit (ec);
3143 ig.EndExceptionBlock ();
3146 public override void EmitFinally (EmitContext ec)
3148 ILGenerator ig = ec.ig;
3149 ig.Emit (OpCodes.Ldloc, temp);
3150 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3154 public class Unchecked : Statement {
3155 public readonly Block Block;
3157 public Unchecked (Block b)
3163 public override bool Resolve (EmitContext ec)
3165 bool previous_state = ec.CheckState;
3166 bool previous_state_const = ec.ConstantCheckState;
3168 ec.CheckState = false;
3169 ec.ConstantCheckState = false;
3170 bool ret = Block.Resolve (ec);
3171 ec.CheckState = previous_state;
3172 ec.ConstantCheckState = previous_state_const;
3177 protected override void DoEmit (EmitContext ec)
3179 bool previous_state = ec.CheckState;
3180 bool previous_state_const = ec.ConstantCheckState;
3182 ec.CheckState = false;
3183 ec.ConstantCheckState = false;
3185 ec.CheckState = previous_state;
3186 ec.ConstantCheckState = previous_state_const;
3190 public class Checked : Statement {
3191 public readonly Block Block;
3193 public Checked (Block b)
3196 b.Unchecked = false;
3199 public override bool Resolve (EmitContext ec)
3201 bool previous_state = ec.CheckState;
3202 bool previous_state_const = ec.ConstantCheckState;
3204 ec.CheckState = true;
3205 ec.ConstantCheckState = true;
3206 bool ret = Block.Resolve (ec);
3207 ec.CheckState = previous_state;
3208 ec.ConstantCheckState = previous_state_const;
3213 protected override void DoEmit (EmitContext ec)
3215 bool previous_state = ec.CheckState;
3216 bool previous_state_const = ec.ConstantCheckState;
3218 ec.CheckState = true;
3219 ec.ConstantCheckState = true;
3221 ec.CheckState = previous_state;
3222 ec.ConstantCheckState = previous_state_const;
3226 public class Unsafe : Statement {
3227 public readonly Block Block;
3229 public Unsafe (Block b)
3232 Block.Unsafe = true;
3235 public override bool Resolve (EmitContext ec)
3237 bool previous_state = ec.InUnsafe;
3241 val = Block.Resolve (ec);
3242 ec.InUnsafe = previous_state;
3247 protected override void DoEmit (EmitContext ec)
3249 bool previous_state = ec.InUnsafe;
3253 ec.InUnsafe = previous_state;
3260 public class Fixed : Statement {
3262 ArrayList declarators;
3263 Statement statement;
3269 public bool is_object;
3270 public LocalInfo vi;
3271 public Expression expr;
3272 public Expression converted;
3275 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3278 declarators = decls;
3283 public override bool Resolve (EmitContext ec)
3286 Expression.UnsafeError (loc);
3290 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3294 expr_type = texpr.ResolveType (ec);
3296 CheckObsolete (expr_type);
3298 if (ec.RemapToProxy){
3299 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3303 data = new FixedData [declarators.Count];
3305 if (!expr_type.IsPointer){
3306 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3311 foreach (Pair p in declarators){
3312 LocalInfo vi = (LocalInfo) p.First;
3313 Expression e = (Expression) p.Second;
3315 vi.VariableInfo.SetAssigned (ec);
3319 // The rules for the possible declarators are pretty wise,
3320 // but the production on the grammar is more concise.
3322 // So we have to enforce these rules here.
3324 // We do not resolve before doing the case 1 test,
3325 // because the grammar is explicit in that the token &
3326 // is present, so we need to test for this particular case.
3330 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3335 // Case 1: & object.
3337 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3338 Expression child = ((Unary) e).Expr;
3340 if (child is ParameterReference || child is LocalVariableReference){
3343 "No need to use fixed statement for parameters or " +
3344 "local variable declarations (address is already " +
3349 ec.InFixedInitializer = true;
3351 ec.InFixedInitializer = false;
3355 child = ((Unary) e).Expr;
3357 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3360 data [i].is_object = true;
3362 data [i].converted = null;
3369 ec.InFixedInitializer = true;
3371 ec.InFixedInitializer = false;
3378 if (e.Type.IsArray){
3379 Type array_type = TypeManager.GetElementType (e.Type);
3382 // Provided that array_type is unmanaged,
3384 if (!TypeManager.VerifyUnManaged (array_type, loc))
3388 // and T* is implicitly convertible to the
3389 // pointer type given in the fixed statement.
3391 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3393 Expression converted = Convert.ImplicitConversionRequired (
3394 ec, array_ptr, vi.VariableType, loc);
3395 if (converted == null)
3398 data [i].is_object = false;
3400 data [i].converted = converted;
3410 if (e.Type == TypeManager.string_type){
3411 data [i].is_object = false;
3413 data [i].converted = null;
3420 // For other cases, flag a `this is already fixed expression'
3422 if (e is LocalVariableReference || e is ParameterReference ||
3423 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3425 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3429 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3433 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3435 if (!statement.Resolve (ec)) {
3436 ec.KillFlowBranching ();
3440 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3441 has_ret = reachability.IsUnreachable;
3446 protected override void DoEmit (EmitContext ec)
3448 ILGenerator ig = ec.ig;
3450 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3452 for (int i = 0; i < data.Length; i++) {
3453 LocalInfo vi = data [i].vi;
3456 // Case 1: & object.
3458 if (data [i].is_object) {
3460 // Store pointer in pinned location
3462 data [i].expr.Emit (ec);
3463 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3464 clear_list [i] = vi.LocalBuilder;
3471 if (data [i].expr.Type.IsArray){
3473 // Store pointer in pinned location
3475 data [i].converted.Emit (ec);
3477 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3478 clear_list [i] = vi.LocalBuilder;
3485 if (data [i].expr.Type == TypeManager.string_type){
3486 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3487 clear_list [i] = pinned_string;
3489 data [i].expr.Emit (ec);
3490 ig.Emit (OpCodes.Stloc, pinned_string);
3492 Expression sptr = new StringPtr (pinned_string, loc);
3493 Expression converted = Convert.ImplicitConversionRequired (
3494 ec, sptr, vi.VariableType, loc);
3496 if (converted == null)
3499 converted.Emit (ec);
3500 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3504 statement.Emit (ec);
3510 // Clear the pinned variable
3512 for (int i = 0; i < data.Length; i++) {
3513 if (data [i].is_object || data [i].expr.Type.IsArray) {
3514 ig.Emit (OpCodes.Ldc_I4_0);
3515 ig.Emit (OpCodes.Conv_U);
3516 ig.Emit (OpCodes.Stloc, clear_list [i]);
3517 } else if (data [i].expr.Type == TypeManager.string_type){
3518 ig.Emit (OpCodes.Ldnull);
3519 ig.Emit (OpCodes.Stloc, clear_list [i]);
3525 public class Catch: Statement {
3526 public readonly string Name;
3527 public readonly Block Block;
3529 Expression type_expr;
3532 public Catch (Expression type, string name, Block block, Location l)
3540 public Type CatchType {
3546 public bool IsGeneral {
3548 return type_expr == null;
3552 protected override void DoEmit(EmitContext ec)
3556 public override bool Resolve (EmitContext ec)
3558 if (type_expr != null) {
3559 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3563 type = te.ResolveType (ec);
3565 CheckObsolete (type);
3567 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3568 Error (155, "The type caught or thrown must be derived from System.Exception");
3574 return Block.Resolve (ec);
3578 public class Try : ExceptionStatement {
3579 public readonly Block Fini, Block;
3580 public readonly ArrayList Specific;
3581 public readonly Catch General;
3583 bool need_exc_block;
3586 // specific, general and fini might all be null.
3588 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3590 if (specific == null && general == null){
3591 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3595 this.Specific = specific;
3596 this.General = general;
3601 public override bool Resolve (EmitContext ec)
3605 FlowBranchingException branching = ec.StartFlowBranching (this);
3607 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3609 if (!Block.Resolve (ec))
3612 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3614 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3616 Type[] prevCatches = new Type [Specific.Count];
3618 foreach (Catch c in Specific){
3619 ec.CurrentBranching.CreateSibling (
3620 c.Block, FlowBranching.SiblingType.Catch);
3622 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3624 if (c.Name != null) {
3625 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3627 throw new Exception ();
3629 vi.VariableInfo = null;
3632 if (!c.Resolve (ec))
3635 Type resolvedType = c.CatchType;
3636 for (int ii = 0; ii < last_index; ++ii) {
3637 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3638 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3643 prevCatches [last_index++] = resolvedType;
3644 need_exc_block = true;
3647 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3649 if (General != null){
3650 ec.CurrentBranching.CreateSibling (
3651 General.Block, FlowBranching.SiblingType.Catch);
3653 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3655 if (!General.Resolve (ec))
3658 need_exc_block = true;
3661 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3665 ec.CurrentBranching.CreateSibling (
3666 Fini, FlowBranching.SiblingType.Finally);
3668 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3670 if (!Fini.Resolve (ec))
3674 ResolveFinally (branching);
3675 need_exc_block |= emit_finally;
3677 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3679 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3681 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3683 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3684 // Unfortunately, System.Reflection.Emit automatically emits
3685 // a leave to the end of the finally block. This is a problem
3686 // if `returns' is true since we may jump to a point after the
3687 // end of the method.
3688 // As a workaround, emit an explicit ret here.
3689 ec.NeedReturnLabel ();
3695 protected override void DoEmit (EmitContext ec)
3697 ILGenerator ig = ec.ig;
3700 ig.BeginExceptionBlock ();
3703 foreach (Catch c in Specific){
3706 ig.BeginCatchBlock (c.CatchType);
3708 if (c.Name != null){
3709 vi = c.Block.GetLocalInfo (c.Name);
3711 throw new Exception ("Variable does not exist in this block");
3713 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3715 ig.Emit (OpCodes.Pop);
3720 if (General != null){
3721 ig.BeginCatchBlock (TypeManager.object_type);
3722 ig.Emit (OpCodes.Pop);
3723 General.Block.Emit (ec);
3728 ig.EndExceptionBlock ();
3731 public override void EmitFinally (EmitContext ec)
3739 public class Using : ExceptionStatement {
3740 object expression_or_block;
3741 Statement Statement;
3746 Expression [] resolved_vars;
3747 Expression [] converted_vars;
3748 ExpressionStatement [] assign;
3749 LocalBuilder local_copy;
3751 public Using (object expression_or_block, Statement stmt, Location l)
3753 this.expression_or_block = expression_or_block;
3759 // Resolves for the case of using using a local variable declaration.
3761 bool ResolveLocalVariableDecls (EmitContext ec)
3765 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3769 expr_type = texpr.ResolveType (ec);
3772 // The type must be an IDisposable or an implicit conversion
3775 converted_vars = new Expression [var_list.Count];
3776 resolved_vars = new Expression [var_list.Count];
3777 assign = new ExpressionStatement [var_list.Count];
3779 bool need_conv = !TypeManager.ImplementsInterface (
3780 expr_type, TypeManager.idisposable_type);
3782 foreach (DictionaryEntry e in var_list){
3783 Expression var = (Expression) e.Key;
3785 var = var.ResolveLValue (ec, new EmptyExpression ());
3789 resolved_vars [i] = var;
3796 converted_vars [i] = Convert.ImplicitConversionRequired (
3797 ec, var, TypeManager.idisposable_type, loc);
3799 if (converted_vars [i] == null)
3806 foreach (DictionaryEntry e in var_list){
3807 Expression var = resolved_vars [i];
3808 Expression new_expr = (Expression) e.Value;
3811 a = new Assign (var, new_expr, loc);
3817 converted_vars [i] = var;
3818 assign [i] = (ExpressionStatement) a;
3825 bool ResolveExpression (EmitContext ec)
3827 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3828 conv = Convert.ImplicitConversionRequired (
3829 ec, expr, TypeManager.idisposable_type, loc);
3839 // Emits the code for the case of using using a local variable declaration.
3841 void EmitLocalVariableDecls (EmitContext ec)
3843 ILGenerator ig = ec.ig;
3846 for (i = 0; i < assign.Length; i++) {
3847 assign [i].EmitStatement (ec);
3850 ig.BeginExceptionBlock ();
3852 Statement.Emit (ec);
3853 var_list.Reverse ();
3858 void EmitLocalVariableDeclFinally (EmitContext ec)
3860 ILGenerator ig = ec.ig;
3862 int i = assign.Length;
3863 foreach (DictionaryEntry e in var_list){
3864 Expression var = resolved_vars [--i];
3865 Label skip = ig.DefineLabel ();
3867 if (!var.Type.IsValueType) {
3869 ig.Emit (OpCodes.Brfalse, skip);
3870 converted_vars [i].Emit (ec);
3871 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3873 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3875 if (!(ml is MethodGroupExpr)) {
3877 ig.Emit (OpCodes.Box, var.Type);
3878 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3880 MethodInfo mi = null;
3882 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3883 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3890 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3894 IMemoryLocation mloc = (IMemoryLocation) var;
3896 mloc.AddressOf (ec, AddressOp.Load);
3897 ig.Emit (OpCodes.Call, mi);
3901 ig.MarkLabel (skip);
3904 ig.EndExceptionBlock ();
3906 ig.BeginFinallyBlock ();
3911 void EmitExpression (EmitContext ec)
3914 // Make a copy of the expression and operate on that.
3916 ILGenerator ig = ec.ig;
3917 local_copy = ig.DeclareLocal (expr_type);
3922 ig.Emit (OpCodes.Stloc, local_copy);
3925 ig.BeginExceptionBlock ();
3927 Statement.Emit (ec);
3931 ig.EndExceptionBlock ();
3934 void EmitExpressionFinally (EmitContext ec)
3936 ILGenerator ig = ec.ig;
3937 Label skip = ig.DefineLabel ();
3938 ig.Emit (OpCodes.Ldloc, local_copy);
3939 ig.Emit (OpCodes.Brfalse, skip);
3940 ig.Emit (OpCodes.Ldloc, local_copy);
3941 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3942 ig.MarkLabel (skip);
3945 public override bool Resolve (EmitContext ec)
3947 if (expression_or_block is DictionaryEntry){
3948 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3949 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3951 if (!ResolveLocalVariableDecls (ec))
3954 } else if (expression_or_block is Expression){
3955 expr = (Expression) expression_or_block;
3957 expr = expr.Resolve (ec);
3961 expr_type = expr.Type;
3963 if (!ResolveExpression (ec))
3967 FlowBranchingException branching = ec.StartFlowBranching (this);
3969 bool ok = Statement.Resolve (ec);
3972 ec.KillFlowBranching ();
3976 ResolveFinally (branching);
3977 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3979 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3980 // Unfortunately, System.Reflection.Emit automatically emits a leave
3981 // to the end of the finally block. This is a problem if `returns'
3982 // is true since we may jump to a point after the end of the method.
3983 // As a workaround, emit an explicit ret here.
3984 ec.NeedReturnLabel ();
3990 protected override void DoEmit (EmitContext ec)
3992 if (expression_or_block is DictionaryEntry)
3993 EmitLocalVariableDecls (ec);
3994 else if (expression_or_block is Expression)
3995 EmitExpression (ec);
3998 public override void EmitFinally (EmitContext ec)
4000 if (expression_or_block is DictionaryEntry)
4001 EmitLocalVariableDeclFinally (ec);
4002 else if (expression_or_block is Expression)
4003 EmitExpressionFinally (ec);
4008 /// Implementation of the foreach C# statement
4010 public class Foreach : ExceptionStatement {
4012 Expression variable;
4014 Statement statement;
4015 ForeachHelperMethods hm;
4016 Expression empty, conv;
4017 Type array_type, element_type;
4019 VariableStorage enumerator;
4021 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4022 Statement stmt, Location l)
4025 this.variable = var;
4031 public override bool Resolve (EmitContext ec)
4033 expr = expr.Resolve (ec);
4037 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4041 var_type = texpr.ResolveType (ec);
4044 // We need an instance variable. Not sure this is the best
4045 // way of doing this.
4047 // FIXME: When we implement propertyaccess, will those turn
4048 // out to return values in ExprClass? I think they should.
4050 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4051 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4052 error1579 (expr.Type);
4056 if (expr.Type.IsArray) {
4057 array_type = expr.Type;
4058 element_type = TypeManager.GetElementType (array_type);
4060 empty = new EmptyExpression (element_type);
4062 hm = ProbeCollectionType (ec, expr.Type);
4064 error1579 (expr.Type);
4068 array_type = expr.Type;
4069 element_type = hm.element_type;
4071 empty = new EmptyExpression (hm.element_type);
4076 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4077 ec.CurrentBranching.CreateSibling ();
4081 // FIXME: maybe we can apply the same trick we do in the
4082 // array handling to avoid creating empty and conv in some cases.
4084 // Although it is not as important in this case, as the type
4085 // will not likely be object (what the enumerator will return).
4087 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4091 variable = variable.ResolveLValue (ec, empty);
4092 if (variable == null)
4095 bool disposable = (hm != null) && hm.is_disposable;
4096 FlowBranchingException branching = null;
4098 branching = ec.StartFlowBranching (this);
4100 if (!statement.Resolve (ec))
4104 ResolveFinally (branching);
4105 ec.EndFlowBranching ();
4107 emit_finally = true;
4109 ec.EndFlowBranching ();
4115 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4117 static MethodInfo FetchMethodMoveNext (Type t)
4119 MemberList move_next_list;
4121 move_next_list = TypeContainer.FindMembers (
4122 t, MemberTypes.Method,
4123 BindingFlags.Public | BindingFlags.Instance,
4124 Type.FilterName, "MoveNext");
4125 if (move_next_list.Count == 0)
4128 foreach (MemberInfo m in move_next_list){
4129 MethodInfo mi = (MethodInfo) m;
4132 args = TypeManager.GetArgumentTypes (mi);
4133 if (args != null && args.Length == 0){
4134 if (mi.ReturnType == TypeManager.bool_type)
4142 // Retrieves a `public T get_Current ()' method from the Type `t'
4144 static MethodInfo FetchMethodGetCurrent (Type t)
4146 MemberList get_current_list;
4148 get_current_list = TypeContainer.FindMembers (
4149 t, MemberTypes.Method,
4150 BindingFlags.Public | BindingFlags.Instance,
4151 Type.FilterName, "get_Current");
4152 if (get_current_list.Count == 0)
4155 foreach (MemberInfo m in get_current_list){
4156 MethodInfo mi = (MethodInfo) m;
4159 args = TypeManager.GetArgumentTypes (mi);
4160 if (args != null && args.Length == 0)
4167 // Retrieves a `public void Dispose ()' method from the Type `t'
4169 static MethodInfo FetchMethodDispose (Type t)
4171 MemberList dispose_list;
4173 dispose_list = TypeContainer.FindMembers (
4174 t, MemberTypes.Method,
4175 BindingFlags.Public | BindingFlags.Instance,
4176 Type.FilterName, "Dispose");
4177 if (dispose_list.Count == 0)
4180 foreach (MemberInfo m in dispose_list){
4181 MethodInfo mi = (MethodInfo) m;
4184 args = TypeManager.GetArgumentTypes (mi);
4185 if (args != null && args.Length == 0){
4186 if (mi.ReturnType == TypeManager.void_type)
4194 // This struct records the helper methods used by the Foreach construct
4196 class ForeachHelperMethods {
4197 public EmitContext ec;
4198 public MethodInfo get_enumerator;
4199 public MethodInfo move_next;
4200 public MethodInfo get_current;
4201 public Type element_type;
4202 public Type enumerator_type;
4203 public bool is_disposable;
4205 public ForeachHelperMethods (EmitContext ec)
4208 this.element_type = TypeManager.object_type;
4209 this.enumerator_type = TypeManager.ienumerator_type;
4210 this.is_disposable = true;
4214 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4219 if (!(m is MethodInfo))
4222 if (m.Name != "GetEnumerator")
4225 MethodInfo mi = (MethodInfo) m;
4226 Type [] args = TypeManager.GetArgumentTypes (mi);
4228 if (args.Length != 0)
4231 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4232 EmitContext ec = hm.ec;
4234 // Check whether GetEnumerator is public
4235 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4238 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4240 // Apply the same optimization as MS: skip the GetEnumerator
4241 // returning an IEnumerator, and use the one returning a
4242 // CharEnumerator instead. This allows us to avoid the
4243 // try-finally block and the boxing.
4248 // Ok, we can access it, now make sure that we can do something
4249 // with this `GetEnumerator'
4252 Type return_type = mi.ReturnType;
4253 if (mi.ReturnType == TypeManager.ienumerator_type ||
4254 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4255 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4258 // If it is not an interface, lets try to find the methods ourselves.
4259 // For example, if we have:
4260 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4261 // We can avoid the iface call. This is a runtime perf boost.
4262 // even bigger if we have a ValueType, because we avoid the cost
4265 // We have to make sure that both methods exist for us to take
4266 // this path. If one of the methods does not exist, we will just
4267 // use the interface. Sadly, this complex if statement is the only
4268 // way I could do this without a goto
4271 if (return_type.IsInterface ||
4272 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4273 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4275 hm.move_next = TypeManager.bool_movenext_void;
4276 hm.get_current = TypeManager.object_getcurrent_void;
4283 // Ok, so they dont return an IEnumerable, we will have to
4284 // find if they support the GetEnumerator pattern.
4287 hm.move_next = FetchMethodMoveNext (return_type);
4288 if (hm.move_next == null)
4291 hm.get_current = FetchMethodGetCurrent (return_type);
4292 if (hm.get_current == null)
4296 hm.element_type = hm.get_current.ReturnType;
4297 hm.enumerator_type = return_type;
4298 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4299 TypeManager.ImplementsInterface (
4300 hm.enumerator_type, TypeManager.idisposable_type);
4306 /// This filter is used to find the GetEnumerator method
4307 /// on which IEnumerator operates
4309 static MemberFilter FilterEnumerator;
4313 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4316 void error1579 (Type t)
4318 Report.Error (1579, loc,
4319 "foreach statement cannot operate on variables of type `" +
4320 t.FullName + "' because that class does not provide a " +
4321 " GetEnumerator method or it is inaccessible");
4324 static bool TryType (Type t, ForeachHelperMethods hm)
4328 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4329 BindingFlags.Public | BindingFlags.NonPublic |
4330 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4331 FilterEnumerator, hm);
4336 hm.get_enumerator = (MethodInfo) mi [0];
4341 // Looks for a usable GetEnumerator in the Type, and if found returns
4342 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4344 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4346 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4348 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4349 if (TryType (tt, hm))
4355 // Now try to find the method in the interfaces
4358 Type [] ifaces = t.GetInterfaces ();
4360 foreach (Type i in ifaces){
4361 if (TryType (i, hm))
4366 // Since TypeBuilder.GetInterfaces only returns the interface
4367 // types for this type, we have to keep looping, but once
4368 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4369 // done, because it returns all the types
4371 if ((t is TypeBuilder))
4381 // FIXME: possible optimization.
4382 // We might be able to avoid creating `empty' if the type is the sam
4384 bool EmitCollectionForeach (EmitContext ec)
4386 ILGenerator ig = ec.ig;
4388 enumerator = new VariableStorage (ec, hm.enumerator_type);
4389 enumerator.EmitThis (ig);
4391 // Instantiate the enumerator
4393 if (expr.Type.IsValueType) {
4394 IMemoryLocation ml = expr as IMemoryLocation;
4395 // Load the address of the value type.
4397 // This happens if, for example, you have a property
4398 // returning a struct which is IEnumerable
4399 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4401 ig.Emit (OpCodes.Stloc, t);
4402 ig.Emit (OpCodes.Ldloca, t);
4403 ec.FreeTemporaryLocal (t, expr.Type);
4405 ml.AddressOf (ec, AddressOp.Load);
4409 if (hm.get_enumerator.DeclaringType.IsValueType) {
4410 // the method is declared on the value type
4411 ig.Emit (OpCodes.Call, hm.get_enumerator);
4413 // it is an interface method, so we must box
4414 ig.Emit (OpCodes.Box, expr.Type);
4415 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4419 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4421 enumerator.EmitStore (ig);
4424 // Protect the code in a try/finalize block, so that
4425 // if the beast implement IDisposable, we get rid of it
4427 if (hm.is_disposable && emit_finally)
4428 ig.BeginExceptionBlock ();
4430 Label end_try = ig.DefineLabel ();
4432 ig.MarkLabel (ec.LoopBegin);
4434 enumerator.EmitCall (ig, hm.move_next);
4436 ig.Emit (OpCodes.Brfalse, end_try);
4439 enumerator.EmitThis (ig);
4440 enumerator.EmitCall (ig, hm.get_current);
4444 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4446 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4448 statement.Emit (ec);
4449 ig.Emit (OpCodes.Br, ec.LoopBegin);
4450 ig.MarkLabel (end_try);
4453 // Now the finally block
4455 if (hm.is_disposable) {
4458 ig.EndExceptionBlock ();
4461 ig.MarkLabel (ec.LoopEnd);
4465 public override void EmitFinally (EmitContext ec)
4467 ILGenerator ig = ec.ig;
4469 if (hm.enumerator_type.IsValueType) {
4470 enumerator.EmitThis (ig);
4472 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4474 enumerator.EmitLoadAddress (ig);
4475 ig.Emit (OpCodes.Call, mi);
4477 enumerator.EmitLoad (ig);
4478 ig.Emit (OpCodes.Box, hm.enumerator_type);
4479 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4482 Label call_dispose = ig.DefineLabel ();
4484 enumerator.EmitThis (ig);
4485 enumerator.EmitLoad (ig);
4486 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4487 ig.Emit (OpCodes.Dup);
4488 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4489 ig.Emit (OpCodes.Pop);
4491 Label end_finally = ig.DefineLabel ();
4492 ig.Emit (OpCodes.Br, end_finally);
4494 ig.MarkLabel (call_dispose);
4495 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4496 ig.MarkLabel (end_finally);
4499 ig.Emit (OpCodes.Endfinally);
4504 // FIXME: possible optimization.
4505 // We might be able to avoid creating `empty' if the type is the sam
4507 bool EmitArrayForeach (EmitContext ec)
4509 int rank = array_type.GetArrayRank ();
4510 ILGenerator ig = ec.ig;
4512 VariableStorage copy = new VariableStorage (ec, array_type);
4515 // Make our copy of the array
4519 copy.EmitStore (ig);
4522 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4526 counter.EmitThis (ig);
4527 ig.Emit (OpCodes.Ldc_I4_0);
4528 counter.EmitStore (ig);
4529 test = ig.DefineLabel ();
4530 ig.Emit (OpCodes.Br, test);
4532 loop = ig.DefineLabel ();
4533 ig.MarkLabel (loop);
4540 counter.EmitThis (ig);
4541 counter.EmitLoad (ig);
4544 // Load the value, we load the value using the underlying type,
4545 // then we use the variable.EmitAssign to load using the proper cast.
4547 ArrayAccess.EmitLoadOpcode (ig, element_type);
4550 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4552 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4554 statement.Emit (ec);
4556 ig.MarkLabel (ec.LoopBegin);
4557 counter.EmitThis (ig);
4558 counter.EmitThis (ig);
4559 counter.EmitLoad (ig);
4560 ig.Emit (OpCodes.Ldc_I4_1);
4561 ig.Emit (OpCodes.Add);
4562 counter.EmitStore (ig);
4564 ig.MarkLabel (test);
4565 counter.EmitThis (ig);
4566 counter.EmitLoad (ig);
4569 ig.Emit (OpCodes.Ldlen);
4570 ig.Emit (OpCodes.Conv_I4);
4571 ig.Emit (OpCodes.Blt, loop);
4573 VariableStorage [] dim_len = new VariableStorage [rank];
4574 VariableStorage [] dim_count = new VariableStorage [rank];
4575 Label [] loop = new Label [rank];
4576 Label [] test = new Label [rank];
4579 for (dim = 0; dim < rank; dim++){
4580 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4581 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4582 test [dim] = ig.DefineLabel ();
4583 loop [dim] = ig.DefineLabel ();
4586 for (dim = 0; dim < rank; dim++){
4587 dim_len [dim].EmitThis (ig);
4590 IntLiteral.EmitInt (ig, dim);
4591 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4592 dim_len [dim].EmitStore (ig);
4596 for (dim = 0; dim < rank; dim++){
4597 dim_count [dim].EmitThis (ig);
4598 ig.Emit (OpCodes.Ldc_I4_0);
4599 dim_count [dim].EmitStore (ig);
4600 ig.Emit (OpCodes.Br, test [dim]);
4601 ig.MarkLabel (loop [dim]);
4608 for (dim = 0; dim < rank; dim++){
4609 dim_count [dim].EmitThis (ig);
4610 dim_count [dim].EmitLoad (ig);
4614 // FIXME: Maybe we can cache the computation of `get'?
4616 Type [] args = new Type [rank];
4619 for (int i = 0; i < rank; i++)
4620 args [i] = TypeManager.int32_type;
4622 ModuleBuilder mb = CodeGen.Module.Builder;
4623 get = mb.GetArrayMethod (
4625 CallingConventions.HasThis| CallingConventions.Standard,
4627 ig.Emit (OpCodes.Call, get);
4630 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4632 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4633 statement.Emit (ec);
4634 ig.MarkLabel (ec.LoopBegin);
4635 for (dim = rank - 1; dim >= 0; dim--){
4636 dim_count [dim].EmitThis (ig);
4637 dim_count [dim].EmitThis (ig);
4638 dim_count [dim].EmitLoad (ig);
4639 ig.Emit (OpCodes.Ldc_I4_1);
4640 ig.Emit (OpCodes.Add);
4641 dim_count [dim].EmitStore (ig);
4643 ig.MarkLabel (test [dim]);
4644 dim_count [dim].EmitThis (ig);
4645 dim_count [dim].EmitLoad (ig);
4646 dim_len [dim].EmitThis (ig);
4647 dim_len [dim].EmitLoad (ig);
4648 ig.Emit (OpCodes.Blt, loop [dim]);
4651 ig.MarkLabel (ec.LoopEnd);
4656 protected override void DoEmit (EmitContext ec)
4658 ILGenerator ig = ec.ig;
4660 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4661 ec.LoopBegin = ig.DefineLabel ();
4662 ec.LoopEnd = ig.DefineLabel ();
4665 EmitCollectionForeach (ec);
4667 EmitArrayForeach (ec);
4669 ec.LoopBegin = old_begin;
4670 ec.LoopEnd = old_end;