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);
1031 if (VariableType == null)
1035 if (VariableType == TypeManager.void_type) {
1036 Report.Error (1547, Location,
1037 "Keyword 'void' cannot be used in this context");
1041 if (VariableType.IsAbstract && VariableType.IsSealed) {
1042 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1045 // TODO: breaks the build
1046 // if (VariableType.IsPointer && !ec.InUnsafe)
1047 // Expression.UnsafeError (Location);
1053 // Whether the variable is Fixed (because its Pinned or its a value type)
1055 public bool IsFixed {
1057 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1064 public bool IsCaptured {
1066 return (flags & Flags.Captured) != 0;
1070 flags |= Flags.Captured;
1074 public override string ToString ()
1076 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1077 Name, Type, VariableInfo, Location);
1082 return (flags & Flags.Used) != 0;
1085 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1089 public bool ReadOnly {
1091 return (flags & Flags.ReadOnly) != 0;
1094 flags = value ? (flags | Flags.ReadOnly) : (unchecked (flags & ~Flags.ReadOnly));
1099 // Whether the variable is pinned, if Pinned the variable has been
1100 // allocated in a pinned slot with DeclareLocal.
1102 public bool Pinned {
1104 return (flags & Flags.Pinned) != 0;
1107 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1111 public bool IsThis {
1113 return (flags & Flags.IsThis) != 0;
1116 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1122 /// Block represents a C# block.
1126 /// This class is used in a number of places: either to represent
1127 /// explicit blocks that the programmer places or implicit blocks.
1129 /// Implicit blocks are used as labels or to introduce variable
1132 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1133 /// they contain extra information that is not necessary on normal blocks.
1135 public class Block : Statement {
1136 public Block Parent;
1137 public readonly Location StartLocation;
1138 public Location EndLocation = Location.Null;
1145 VariablesInitialized = 8,
1154 public bool Implicit {
1156 return (flags & Flags.Implicit) != 0;
1160 public bool Unchecked {
1162 return (flags & Flags.Unchecked) != 0;
1165 flags |= Flags.Unchecked;
1169 public bool Unsafe {
1171 return (flags & Flags.Unsafe) != 0;
1174 flags |= Flags.Unsafe;
1178 public bool HasVarargs {
1181 return Parent.HasVarargs;
1183 return (flags & Flags.HasVarargs) != 0;
1186 flags |= Flags.HasVarargs;
1191 // The statements in this block
1193 ArrayList statements;
1197 // An array of Blocks. We keep track of children just
1198 // to generate the local variable declarations.
1200 // Statements and child statements are handled through the
1206 // Labels. (label, block) pairs.
1211 // Keeps track of (name, type) pairs
1213 Hashtable variables;
1216 // Keeps track of constants
1217 Hashtable constants;
1220 // The parameters for the block, this is only needed on the toplevel block really
1221 // TODO: move `parameters' into ToplevelBlock
1222 Parameters parameters;
1225 // If this is a switch section, the enclosing switch block.
1229 protected static int id;
1233 public Block (Block parent)
1234 : this (parent, (Flags) 0, Location.Null, Location.Null)
1237 public Block (Block parent, Flags flags)
1238 : this (parent, flags, Location.Null, Location.Null)
1241 public Block (Block parent, Flags flags, Parameters parameters)
1242 : this (parent, flags, parameters, Location.Null, Location.Null)
1245 public Block (Block parent, Location start, Location end)
1246 : this (parent, (Flags) 0, start, end)
1249 public Block (Block parent, Parameters parameters, Location start, Location end)
1250 : this (parent, (Flags) 0, parameters, start, end)
1253 public Block (Block parent, Flags flags, Location start, Location end)
1254 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1257 public Block (Block parent, Flags flags, Parameters parameters,
1258 Location start, Location end)
1261 parent.AddChild (this);
1263 this.Parent = parent;
1265 this.parameters = parameters;
1266 this.StartLocation = start;
1267 this.EndLocation = end;
1270 statements = new ArrayList ();
1272 if (parent != null && Implicit) {
1273 if (parent.child_variable_names == null)
1274 parent.child_variable_names = new Hashtable();
1275 // share with parent
1276 child_variable_names = parent.child_variable_names;
1281 public Block CreateSwitchBlock (Location start)
1283 Block new_block = new Block (this, start, start);
1284 new_block.switch_block = this;
1294 void AddChild (Block b)
1296 if (children == null)
1297 children = new ArrayList ();
1302 public void SetEndLocation (Location loc)
1308 /// Adds a label to the current block.
1312 /// false if the name already exists in this block. true
1316 public bool AddLabel (string name, LabeledStatement target, Location loc)
1318 if (switch_block != null)
1319 return switch_block.AddLabel (name, target, loc);
1322 while (cur != null) {
1323 if (cur.DoLookupLabel (name) != null) {
1325 140, loc, "The label '{0}' is a duplicate",
1336 while (cur != null) {
1337 if (cur.DoLookupLabel (name) != null) {
1340 "The label '{0}' shadows another label " +
1341 "by the same name in a containing scope.",
1346 if (children != null) {
1347 foreach (Block b in children) {
1348 LabeledStatement s = b.DoLookupLabel (name);
1354 "The label '{0}' shadows another " +
1355 "label by the same name in a " +
1356 "containing scope.",
1367 labels = new Hashtable ();
1369 labels.Add (name, target);
1373 public LabeledStatement LookupLabel (string name)
1375 LabeledStatement s = DoLookupLabel (name);
1379 if (children == null)
1382 foreach (Block child in children) {
1383 if (!child.Implicit)
1386 s = child.LookupLabel (name);
1394 LabeledStatement DoLookupLabel (string name)
1396 if (switch_block != null)
1397 return switch_block.LookupLabel (name);
1400 if (labels.Contains (name))
1401 return ((LabeledStatement) labels [name]);
1406 LocalInfo this_variable = null;
1409 // Returns the "this" instance variable of this block.
1410 // See AddThisVariable() for more information.
1412 public LocalInfo ThisVariable {
1414 if (this_variable != null)
1415 return this_variable;
1416 else if (Parent != null)
1417 return Parent.ThisVariable;
1423 Hashtable child_variable_names;
1426 // Marks a variable with name @name as being used in a child block.
1427 // If a variable name has been used in a child block, it's illegal to
1428 // declare a variable with the same name in the current block.
1430 public void AddChildVariableName (string name)
1432 if (child_variable_names == null)
1433 child_variable_names = new Hashtable ();
1435 child_variable_names [name] = null;
1439 // Checks whether a variable name has already been used in a child block.
1441 public bool IsVariableNameUsedInChildBlock (string name)
1443 if (child_variable_names == null)
1446 return child_variable_names.Contains (name);
1450 // This is used by non-static `struct' constructors which do not have an
1451 // initializer - in this case, the constructor must initialize all of the
1452 // struct's fields. To do this, we add a "this" variable and use the flow
1453 // analysis code to ensure that it's been fully initialized before control
1454 // leaves the constructor.
1456 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1458 if (this_variable != null)
1459 return this_variable;
1461 if (variables == null)
1462 variables = new Hashtable ();
1464 this_variable = new LocalInfo (tc, this, l);
1465 this_variable.Used = true;
1466 this_variable.IsThis = true;
1468 variables.Add ("this", this_variable);
1470 return this_variable;
1473 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1475 if (variables == null)
1476 variables = new Hashtable ();
1478 LocalInfo vi = GetLocalInfo (name);
1480 if (vi.Block != this)
1481 Report.Error (136, l, "A local variable named `" + name + "' " +
1482 "cannot be declared in this scope since it would " +
1483 "give a different meaning to `" + name + "', which " +
1484 "is already used in a `parent or current' scope to " +
1485 "denote something else");
1487 Report.Error (128, l, "A local variable `" + name + "' is already " +
1488 "defined in this scope");
1492 if (IsVariableNameUsedInChildBlock (name)) {
1493 Report.Error (136, l, "A local variable named `" + name + "' " +
1494 "cannot be declared in this scope since it would " +
1495 "give a different meaning to `" + name + "', which " +
1496 "is already used in a `child' scope to denote something " +
1503 Parameter p = pars.GetParameterByName (name, out idx);
1505 Report.Error (136, l, "A local variable named `" + name + "' " +
1506 "cannot be declared in this scope since it would " +
1507 "give a different meaning to `" + name + "', which " +
1508 "is already used in a `parent or current' scope to " +
1509 "denote something else");
1514 vi = new LocalInfo (type, name, this, l);
1516 variables.Add (name, vi);
1518 // Mark 'name' as "used by a child block" in every surrounding block
1520 while (cur != null && cur.Implicit)
1523 for (Block par = cur.Parent; par != null; par = par.Parent)
1524 par.AddChildVariableName (name);
1526 if ((flags & Flags.VariablesInitialized) != 0)
1527 throw new Exception ();
1529 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1533 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1535 if (AddVariable (type, name, pars, l) == null)
1538 if (constants == null)
1539 constants = new Hashtable ();
1541 constants.Add (name, value);
1545 public Hashtable Variables {
1551 public LocalInfo GetLocalInfo (string name)
1553 for (Block b = this; b != null; b = b.Parent) {
1554 if (b.variables != null) {
1555 LocalInfo ret = b.variables [name] as LocalInfo;
1563 public Expression GetVariableType (string name)
1565 LocalInfo vi = GetLocalInfo (name);
1573 public Expression GetConstantExpression (string name)
1575 for (Block b = this; b != null; b = b.Parent) {
1576 if (b.constants != null) {
1577 Expression ret = b.constants [name] as Expression;
1586 /// True if the variable named @name is a constant
1588 public bool IsConstant (string name)
1590 Expression e = null;
1592 e = GetConstantExpression (name);
1598 // Returns a `ParameterReference' for the given name, or null if there
1599 // is no such parameter
1601 public ParameterReference GetParameterReference (string name, Location loc)
1606 Parameters pars = b.parameters;
1612 par = pars.GetParameterByName (name, out idx);
1614 ParameterReference pr;
1616 pr = new ParameterReference (pars, this, idx, name, loc);
1621 } while (b != null);
1626 // Whether the parameter named `name' is local to this block,
1627 // or false, if the parameter belongs to an encompassing block.
1629 public bool IsLocalParameter (string name)
1632 int toplevel_count = 0;
1635 if (this is ToplevelBlock)
1638 Parameters pars = b.parameters;
1640 if (pars.GetParameterByName (name) != null)
1644 if (toplevel_count > 0)
1647 } while (b != null);
1652 // Whether the `name' is a parameter reference
1654 public bool IsParameterReference (string name)
1659 Parameters pars = b.parameters;
1662 if (pars.GetParameterByName (name) != null)
1665 } while (b != null);
1670 /// A list of labels that were not used within this block
1672 public string [] GetUnreferenced ()
1674 // FIXME: Implement me
1678 public void AddStatement (Statement s)
1681 flags |= Flags.BlockUsed;
1686 return (flags & Flags.BlockUsed) != 0;
1692 flags |= Flags.BlockUsed;
1695 public bool HasRet {
1697 return (flags & Flags.HasRet) != 0;
1701 public bool IsDestructor {
1703 return (flags & Flags.IsDestructor) != 0;
1707 public void SetDestructor ()
1709 flags |= Flags.IsDestructor;
1712 VariableMap param_map, local_map;
1714 public VariableMap ParameterMap {
1716 if ((flags & Flags.VariablesInitialized) == 0)
1717 throw new Exception ("Variables have not been initialized yet");
1723 public VariableMap LocalMap {
1725 if ((flags & Flags.VariablesInitialized) == 0)
1726 throw new Exception ("Variables have not been initialized yet");
1733 /// Emits the variable declarations and labels.
1736 /// tc: is our typecontainer (to resolve type references)
1737 /// ig: is the code generator:
1739 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1741 ILGenerator ig = ec.ig;
1743 bool old_unsafe = ec.InUnsafe;
1745 // If some parent block was unsafe, we remain unsafe even if this block
1746 // isn't explicitly marked as such.
1747 ec.InUnsafe |= Unsafe;
1750 // Compute the VariableMap's.
1752 // Unfortunately, we don't know the type when adding variables with
1753 // AddVariable(), so we need to compute this info here.
1757 if (variables != null) {
1758 foreach (LocalInfo li in variables.Values)
1761 locals = new LocalInfo [variables.Count];
1762 variables.Values.CopyTo (locals, 0);
1764 locals = new LocalInfo [0];
1767 local_map = new VariableMap (Parent.LocalMap, locals);
1769 local_map = new VariableMap (locals);
1771 param_map = new VariableMap (ip);
1772 flags |= Flags.VariablesInitialized;
1774 bool old_check_state = ec.ConstantCheckState;
1775 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1778 // Process this block variables
1780 if (variables != null){
1781 foreach (DictionaryEntry de in variables){
1782 string name = (string) de.Key;
1783 LocalInfo vi = (LocalInfo) de.Value;
1785 if (vi.VariableType == null)
1788 Type variable_type = vi.VariableType;
1790 if (variable_type.IsPointer){
1792 // Am not really convinced that this test is required (Microsoft does it)
1793 // but the fact is that you would not be able to use the pointer variable
1796 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1803 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1806 // This is needed to compile on both .NET 1.x and .NET 2.x
1807 // the later introduced `DeclareLocal (Type t, bool pinned)'
1809 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1810 else if (!vi.IsThis)
1811 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1814 if (constants == null)
1817 Expression cv = (Expression) constants [name];
1821 ec.CurrentBlock = this;
1822 Expression e = cv.Resolve (ec);
1826 Constant ce = e as Constant;
1828 Report.Error (133, vi.Location,
1829 "The expression being assigned to `" +
1830 name + "' must be constant (" + e + ")");
1834 if (e.Type != variable_type){
1835 e = Const.ChangeType (vi.Location, ce, variable_type);
1840 constants.Remove (name);
1841 constants.Add (name, e);
1844 ec.ConstantCheckState = old_check_state;
1847 // Now, handle the children
1849 if (children != null){
1850 foreach (Block b in children)
1851 b.ResolveMeta (toplevel, ec, ip);
1853 ec.InUnsafe = old_unsafe;
1857 // Emits the local variable declarations for a block
1859 public void EmitMeta (EmitContext ec)
1861 ILGenerator ig = ec.ig;
1863 if (variables != null){
1864 bool have_captured_vars = ec.HaveCapturedVariables ();
1865 bool remap_locals = ec.RemapToProxy;
1867 foreach (DictionaryEntry de in variables){
1868 LocalInfo vi = (LocalInfo) de.Value;
1870 if (have_captured_vars && ec.IsCaptured (vi))
1874 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1878 // This is needed to compile on both .NET 1.x and .NET 2.x
1879 // the later introduced `DeclareLocal (Type t, bool pinned)'
1881 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1882 else if (!vi.IsThis)
1883 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1888 if (children != null){
1889 foreach (Block b in children)
1894 void UsageWarning (FlowBranching.UsageVector vector)
1898 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1899 foreach (DictionaryEntry de in variables){
1900 LocalInfo vi = (LocalInfo) de.Value;
1905 name = (string) de.Key;
1907 if (vector.IsAssigned (vi.VariableInfo)){
1908 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1910 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1916 bool unreachable_shown;
1918 public override bool Resolve (EmitContext ec)
1920 Block prev_block = ec.CurrentBlock;
1923 int errors = Report.Errors;
1925 ec.CurrentBlock = this;
1926 ec.StartFlowBranching (this);
1928 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1930 bool unreachable = false;
1932 int statement_count = statements.Count;
1933 for (int ix = 0; ix < statement_count; ix++){
1934 Statement s = (Statement) statements [ix];
1936 if (unreachable && !(s is LabeledStatement)) {
1937 if (s == EmptyStatement.Value)
1938 s.loc = EndLocation;
1940 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1943 if (s != EmptyStatement.Value)
1944 unreachable_shown = true;
1946 s.loc = Location.Null;
1948 statements [ix] = EmptyStatement.Value;
1952 if (s.Resolve (ec) == false) {
1954 statements [ix] = EmptyStatement.Value;
1958 num_statements = ix + 1;
1960 if (s is LabeledStatement)
1961 unreachable = false;
1963 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1966 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1967 ec.CurrentBranching, statement_count, num_statements);
1970 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1972 ec.CurrentBlock = prev_block;
1974 // If we're a non-static `struct' constructor which doesn't have an
1975 // initializer, then we must initialize all of the struct's fields.
1976 if ((this_variable != null) &&
1977 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1978 !this_variable.IsThisAssigned (ec, loc))
1981 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1982 foreach (LabeledStatement label in labels.Values)
1983 if (!label.HasBeenReferenced)
1984 Report.Warning (164, label.Location,
1985 "This label has not been referenced");
1988 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1990 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1991 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1992 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1993 flags |= Flags.HasRet;
1995 if (ok && (errors == Report.Errors)) {
1996 if (RootContext.WarningLevel >= 3)
1997 UsageWarning (vector);
2003 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2005 unreachable_shown = true;
2006 return base.ResolveUnreachable (ec, warn);
2009 protected override void DoEmit (EmitContext ec)
2011 for (int ix = 0; ix < num_statements; ix++){
2012 Statement s = (Statement) statements [ix];
2014 // Check whether we are the last statement in a
2017 if ((Parent == null) && (ix+1 == num_statements))
2018 ec.IsLastStatement = true;
2020 ec.IsLastStatement = false;
2026 public override void Emit (EmitContext ec)
2028 Block prev_block = ec.CurrentBlock;
2030 ec.CurrentBlock = this;
2032 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2033 bool is_lexical_block = !Implicit && (Parent != null);
2035 if (emit_debug_info) {
2036 if (is_lexical_block)
2037 ec.ig.BeginScope ();
2039 if (variables != null) {
2040 foreach (DictionaryEntry de in variables) {
2041 string name = (string) de.Key;
2042 LocalInfo vi = (LocalInfo) de.Value;
2044 if (vi.LocalBuilder == null)
2047 ec.DefineLocalVariable (name, vi.LocalBuilder);
2052 ec.Mark (StartLocation, true);
2054 ec.Mark (EndLocation, true);
2056 if (emit_debug_info && is_lexical_block)
2059 ec.CurrentBlock = prev_block;
2062 public ToplevelBlock Toplevel {
2065 while (b.Parent != null){
2066 if ((b.flags & Flags.IsToplevel) != 0)
2071 return (ToplevelBlock) b;
2076 // Returns true if we ar ea child of `b'.
2078 public bool IsChildOf (Block b)
2080 Block current = this;
2083 if (current.Parent == b)
2085 current = current.Parent;
2086 } while (current != null);
2092 // A toplevel block contains extra information, the split is done
2093 // only to separate information that would otherwise bloat the more
2094 // lightweight Block.
2096 // In particular, this was introduced when the support for Anonymous
2097 // Methods was implemented.
2099 public class ToplevelBlock : Block {
2101 // Pointer to the host of this anonymous method, or null
2102 // if we are the topmost block
2104 public ToplevelBlock Container;
2105 CaptureContext capture_context;
2107 Hashtable capture_contexts;
2114 public void RegisterCaptureContext (CaptureContext cc)
2116 if (capture_contexts == null)
2117 capture_contexts = new Hashtable ();
2118 capture_contexts [cc] = cc;
2121 public void CompleteContexts ()
2123 if (capture_contexts == null)
2126 foreach (CaptureContext cc in capture_contexts.Keys){
2131 public CaptureContext ToplevelBlockCaptureContext {
2133 return capture_context;
2138 // Parent is only used by anonymous blocks to link back to their
2141 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2142 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2144 Container = container;
2147 public ToplevelBlock (Parameters parameters, Location start) :
2148 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2152 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2153 base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2157 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2161 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2163 if (capture_context == null)
2164 capture_context = new CaptureContext (this, loc, host);
2167 public CaptureContext CaptureContext {
2169 return capture_context;
2174 public class SwitchLabel {
2177 public Location loc;
2181 Label il_label_code;
2182 bool il_label_code_set;
2185 // if expr == null, then it is the default case.
2187 public SwitchLabel (Expression expr, Location l)
2193 public Expression Label {
2199 public object Converted {
2205 public Label GetILLabel (EmitContext ec)
2208 il_label = ec.ig.DefineLabel ();
2209 il_label_set = true;
2214 public Label GetILLabelCode (EmitContext ec)
2216 if (!il_label_code_set){
2217 il_label_code = ec.ig.DefineLabel ();
2218 il_label_code_set = true;
2220 return il_label_code;
2224 // Resolves the expression, reduces it to a literal if possible
2225 // and then converts it to the requested type.
2227 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2232 Expression e = label.Resolve (ec);
2237 if (!(e is Constant)){
2238 Report.Error (150, loc, "A constant value is expected, got: " + e);
2242 if (e is StringConstant || e is NullLiteral){
2243 if (required_type == TypeManager.string_type){
2249 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2250 if (converted == null)
2257 public class SwitchSection {
2258 // An array of SwitchLabels.
2259 public readonly ArrayList Labels;
2260 public readonly Block Block;
2262 public SwitchSection (ArrayList labels, Block block)
2269 public class Switch : Statement {
2270 public readonly ArrayList Sections;
2271 public Expression Expr;
2274 /// Maps constants whose type type SwitchType to their SwitchLabels.
2276 public Hashtable Elements;
2279 /// The governing switch type
2281 public Type SwitchType;
2287 Label default_target;
2288 Expression new_expr;
2290 SwitchSection constant_section;
2293 // The types allowed to be implicitly cast from
2294 // on the governing type
2296 static Type [] allowed_types;
2298 public Switch (Expression e, ArrayList sects, Location l)
2305 public bool GotDefault {
2311 public Label DefaultTarget {
2313 return default_target;
2318 // Determines the governing type for a switch. The returned
2319 // expression might be the expression from the switch, or an
2320 // expression that includes any potential conversions to the
2321 // integral types or to string.
2323 Expression SwitchGoverningType (EmitContext ec, Type t)
2325 if (t == TypeManager.int32_type ||
2326 t == TypeManager.uint32_type ||
2327 t == TypeManager.char_type ||
2328 t == TypeManager.byte_type ||
2329 t == TypeManager.sbyte_type ||
2330 t == TypeManager.ushort_type ||
2331 t == TypeManager.short_type ||
2332 t == TypeManager.uint64_type ||
2333 t == TypeManager.int64_type ||
2334 t == TypeManager.string_type ||
2335 t == TypeManager.bool_type ||
2336 t.IsSubclassOf (TypeManager.enum_type))
2339 if (allowed_types == null){
2340 allowed_types = new Type [] {
2341 TypeManager.sbyte_type,
2342 TypeManager.byte_type,
2343 TypeManager.short_type,
2344 TypeManager.ushort_type,
2345 TypeManager.int32_type,
2346 TypeManager.uint32_type,
2347 TypeManager.int64_type,
2348 TypeManager.uint64_type,
2349 TypeManager.char_type,
2350 TypeManager.bool_type,
2351 TypeManager.string_type
2356 // Try to find a *user* defined implicit conversion.
2358 // If there is no implicit conversion, or if there are multiple
2359 // conversions, we have to report an error
2361 Expression converted = null;
2362 foreach (Type tt in allowed_types){
2365 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2369 if (converted != null){
2370 Report.Error (-12, loc, "More than one conversion to an integral " +
2371 " type exists for type `" +
2372 TypeManager.CSharpName (Expr.Type)+"'");
2380 static string Error152 {
2382 return "The label '{0}:' already occurs in this switch statement";
2387 // Performs the basic sanity checks on the switch statement
2388 // (looks for duplicate keys and non-constant expressions).
2390 // It also returns a hashtable with the keys that we will later
2391 // use to compute the switch tables
2393 bool CheckSwitch (EmitContext ec)
2397 Elements = new Hashtable ();
2399 got_default = false;
2401 if (TypeManager.IsEnumType (SwitchType)){
2402 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2404 compare_type = SwitchType;
2406 foreach (SwitchSection ss in Sections){
2407 foreach (SwitchLabel sl in ss.Labels){
2408 if (!sl.ResolveAndReduce (ec, SwitchType)){
2413 if (sl.Label == null){
2415 Report.Error (152, sl.loc, Error152, "default");
2422 object key = sl.Converted;
2424 if (key is Constant)
2425 key = ((Constant) key).GetValue ();
2428 key = NullLiteral.Null;
2430 string lname = null;
2431 if (compare_type == TypeManager.uint64_type){
2432 ulong v = (ulong) key;
2434 if (Elements.Contains (v))
2435 lname = v.ToString ();
2437 Elements.Add (v, sl);
2438 } else if (compare_type == TypeManager.int64_type){
2439 long v = (long) key;
2441 if (Elements.Contains (v))
2442 lname = v.ToString ();
2444 Elements.Add (v, sl);
2445 } else if (compare_type == TypeManager.uint32_type){
2446 uint v = (uint) key;
2448 if (Elements.Contains (v))
2449 lname = v.ToString ();
2451 Elements.Add (v, sl);
2452 } else if (compare_type == TypeManager.char_type){
2453 char v = (char) key;
2455 if (Elements.Contains (v))
2456 lname = v.ToString ();
2458 Elements.Add (v, sl);
2459 } else if (compare_type == TypeManager.byte_type){
2460 byte v = (byte) key;
2462 if (Elements.Contains (v))
2463 lname = v.ToString ();
2465 Elements.Add (v, sl);
2466 } else if (compare_type == TypeManager.sbyte_type){
2467 sbyte v = (sbyte) key;
2469 if (Elements.Contains (v))
2470 lname = v.ToString ();
2472 Elements.Add (v, sl);
2473 } else if (compare_type == TypeManager.short_type){
2474 short v = (short) key;
2476 if (Elements.Contains (v))
2477 lname = v.ToString ();
2479 Elements.Add (v, sl);
2480 } else if (compare_type == TypeManager.ushort_type){
2481 ushort v = (ushort) key;
2483 if (Elements.Contains (v))
2484 lname = v.ToString ();
2486 Elements.Add (v, sl);
2487 } else if (compare_type == TypeManager.string_type){
2488 if (key is NullLiteral){
2489 if (Elements.Contains (NullLiteral.Null))
2492 Elements.Add (NullLiteral.Null, null);
2494 string s = (string) key;
2496 if (Elements.Contains (s))
2499 Elements.Add (s, sl);
2501 } else if (compare_type == TypeManager.int32_type) {
2504 if (Elements.Contains (v))
2505 lname = v.ToString ();
2507 Elements.Add (v, sl);
2508 } else if (compare_type == TypeManager.bool_type) {
2509 bool v = (bool) key;
2511 if (Elements.Contains (v))
2512 lname = v.ToString ();
2514 Elements.Add (v, sl);
2518 throw new Exception ("Unknown switch type!" +
2519 SwitchType + " " + compare_type);
2523 Report.Error (152, sl.loc, Error152, "case " + lname);
2534 void EmitObjectInteger (ILGenerator ig, object k)
2537 IntConstant.EmitInt (ig, (int) k);
2538 else if (k is Constant) {
2539 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2542 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2545 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2547 IntConstant.EmitInt (ig, (int) (long) k);
2548 ig.Emit (OpCodes.Conv_I8);
2551 LongConstant.EmitLong (ig, (long) k);
2553 else if (k is ulong)
2555 if ((ulong) k < (1L<<32))
2557 IntConstant.EmitInt (ig, (int) (long) k);
2558 ig.Emit (OpCodes.Conv_U8);
2562 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2566 IntConstant.EmitInt (ig, (int) ((char) k));
2567 else if (k is sbyte)
2568 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2570 IntConstant.EmitInt (ig, (int) ((byte) k));
2571 else if (k is short)
2572 IntConstant.EmitInt (ig, (int) ((short) k));
2573 else if (k is ushort)
2574 IntConstant.EmitInt (ig, (int) ((ushort) k));
2576 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2578 throw new Exception ("Unhandled case");
2581 // structure used to hold blocks of keys while calculating table switch
2582 class KeyBlock : IComparable
2584 public KeyBlock (long _nFirst)
2586 nFirst = nLast = _nFirst;
2590 public ArrayList rgKeys = null;
2591 // how many items are in the bucket
2592 public int Size = 1;
2595 get { return (int) (nLast - nFirst + 1); }
2597 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2599 return kbLast.nLast - kbFirst.nFirst + 1;
2601 public int CompareTo (object obj)
2603 KeyBlock kb = (KeyBlock) obj;
2604 int nLength = Length;
2605 int nLengthOther = kb.Length;
2606 if (nLengthOther == nLength)
2607 return (int) (kb.nFirst - nFirst);
2608 return nLength - nLengthOther;
2613 /// This method emits code for a lookup-based switch statement (non-string)
2614 /// Basically it groups the cases into blocks that are at least half full,
2615 /// and then spits out individual lookup opcodes for each block.
2616 /// It emits the longest blocks first, and short blocks are just
2617 /// handled with direct compares.
2619 /// <param name="ec"></param>
2620 /// <param name="val"></param>
2621 /// <returns></returns>
2622 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2624 int cElements = Elements.Count;
2625 object [] rgKeys = new object [cElements];
2626 Elements.Keys.CopyTo (rgKeys, 0);
2627 Array.Sort (rgKeys);
2629 // initialize the block list with one element per key
2630 ArrayList rgKeyBlocks = new ArrayList ();
2631 foreach (object key in rgKeys)
2632 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2635 // iteratively merge the blocks while they are at least half full
2636 // there's probably a really cool way to do this with a tree...
2637 while (rgKeyBlocks.Count > 1)
2639 ArrayList rgKeyBlocksNew = new ArrayList ();
2640 kbCurr = (KeyBlock) rgKeyBlocks [0];
2641 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2643 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2644 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2647 kbCurr.nLast = kb.nLast;
2648 kbCurr.Size += kb.Size;
2652 // start a new block
2653 rgKeyBlocksNew.Add (kbCurr);
2657 rgKeyBlocksNew.Add (kbCurr);
2658 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2660 rgKeyBlocks = rgKeyBlocksNew;
2663 // initialize the key lists
2664 foreach (KeyBlock kb in rgKeyBlocks)
2665 kb.rgKeys = new ArrayList ();
2667 // fill the key lists
2669 if (rgKeyBlocks.Count > 0) {
2670 kbCurr = (KeyBlock) rgKeyBlocks [0];
2671 foreach (object key in rgKeys)
2673 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2674 System.Convert.ToInt64 (key) > kbCurr.nLast;
2676 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2677 kbCurr.rgKeys.Add (key);
2681 // sort the blocks so we can tackle the largest ones first
2682 rgKeyBlocks.Sort ();
2684 // okay now we can start...
2685 ILGenerator ig = ec.ig;
2686 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2687 Label lblDefault = ig.DefineLabel ();
2689 Type typeKeys = null;
2690 if (rgKeys.Length > 0)
2691 typeKeys = rgKeys [0].GetType (); // used for conversions
2695 if (TypeManager.IsEnumType (SwitchType))
2696 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2698 compare_type = SwitchType;
2700 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2702 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2703 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2706 foreach (object key in kb.rgKeys)
2708 ig.Emit (OpCodes.Ldloc, val);
2709 EmitObjectInteger (ig, key);
2710 SwitchLabel sl = (SwitchLabel) Elements [key];
2711 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2716 // TODO: if all the keys in the block are the same and there are
2717 // no gaps/defaults then just use a range-check.
2718 if (compare_type == TypeManager.int64_type ||
2719 compare_type == TypeManager.uint64_type)
2721 // TODO: optimize constant/I4 cases
2723 // check block range (could be > 2^31)
2724 ig.Emit (OpCodes.Ldloc, val);
2725 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2726 ig.Emit (OpCodes.Blt, lblDefault);
2727 ig.Emit (OpCodes.Ldloc, val);
2728 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2729 ig.Emit (OpCodes.Bgt, lblDefault);
2732 ig.Emit (OpCodes.Ldloc, val);
2735 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2736 ig.Emit (OpCodes.Sub);
2738 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2743 ig.Emit (OpCodes.Ldloc, val);
2744 int nFirst = (int) kb.nFirst;
2747 IntConstant.EmitInt (ig, nFirst);
2748 ig.Emit (OpCodes.Sub);
2750 else if (nFirst < 0)
2752 IntConstant.EmitInt (ig, -nFirst);
2753 ig.Emit (OpCodes.Add);
2757 // first, build the list of labels for the switch
2759 int cJumps = kb.Length;
2760 Label [] rgLabels = new Label [cJumps];
2761 for (int iJump = 0; iJump < cJumps; iJump++)
2763 object key = kb.rgKeys [iKey];
2764 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2766 SwitchLabel sl = (SwitchLabel) Elements [key];
2767 rgLabels [iJump] = sl.GetILLabel (ec);
2771 rgLabels [iJump] = lblDefault;
2773 // emit the switch opcode
2774 ig.Emit (OpCodes.Switch, rgLabels);
2777 // mark the default for this block
2779 ig.MarkLabel (lblDefault);
2782 // TODO: find the default case and emit it here,
2783 // to prevent having to do the following jump.
2784 // make sure to mark other labels in the default section
2786 // the last default just goes to the end
2787 ig.Emit (OpCodes.Br, lblDefault);
2789 // now emit the code for the sections
2790 bool fFoundDefault = false;
2791 foreach (SwitchSection ss in Sections)
2793 foreach (SwitchLabel sl in ss.Labels)
2795 ig.MarkLabel (sl.GetILLabel (ec));
2796 ig.MarkLabel (sl.GetILLabelCode (ec));
2797 if (sl.Label == null)
2799 ig.MarkLabel (lblDefault);
2800 fFoundDefault = true;
2804 //ig.Emit (OpCodes.Br, lblEnd);
2807 if (!fFoundDefault) {
2808 ig.MarkLabel (lblDefault);
2810 ig.MarkLabel (lblEnd);
2813 // This simple emit switch works, but does not take advantage of the
2815 // TODO: remove non-string logic from here
2816 // TODO: binary search strings?
2818 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2820 ILGenerator ig = ec.ig;
2821 Label end_of_switch = ig.DefineLabel ();
2822 Label next_test = ig.DefineLabel ();
2823 Label null_target = ig.DefineLabel ();
2824 bool default_found = false;
2825 bool first_test = true;
2826 bool pending_goto_end = false;
2828 bool default_at_end = false;
2830 ig.Emit (OpCodes.Ldloc, val);
2832 if (Elements.Contains (NullLiteral.Null)){
2833 ig.Emit (OpCodes.Brfalse, null_target);
2835 ig.Emit (OpCodes.Brfalse, default_target);
2837 ig.Emit (OpCodes.Ldloc, val);
2838 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2839 ig.Emit (OpCodes.Stloc, val);
2841 int section_count = Sections.Count;
2842 for (int section = 0; section < section_count; section++){
2843 SwitchSection ss = (SwitchSection) Sections [section];
2844 Label sec_begin = ig.DefineLabel ();
2846 if (pending_goto_end)
2847 ig.Emit (OpCodes.Br, end_of_switch);
2849 int label_count = ss.Labels.Count;
2850 bool mark_default = false;
2852 for (int label = 0; label < label_count; label++){
2853 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2854 ig.MarkLabel (sl.GetILLabel (ec));
2857 ig.MarkLabel (next_test);
2858 next_test = ig.DefineLabel ();
2861 // If we are the default target
2863 if (sl.Label == null){
2864 if (label+1 == label_count)
2865 default_at_end = true;
2866 mark_default = true;
2867 default_found = true;
2869 object lit = sl.Converted;
2871 if (lit is NullLiteral){
2873 if (label_count == 1)
2874 ig.Emit (OpCodes.Br, next_test);
2878 StringConstant str = (StringConstant) lit;
2880 ig.Emit (OpCodes.Ldloc, val);
2881 ig.Emit (OpCodes.Ldstr, str.Value);
2882 if (label_count == 1)
2883 ig.Emit (OpCodes.Bne_Un, next_test);
2885 if (label+1 == label_count)
2886 ig.Emit (OpCodes.Bne_Un, next_test);
2888 ig.Emit (OpCodes.Beq, sec_begin);
2893 ig.MarkLabel (null_target);
2894 ig.MarkLabel (sec_begin);
2895 foreach (SwitchLabel sl in ss.Labels)
2896 ig.MarkLabel (sl.GetILLabelCode (ec));
2899 ig.MarkLabel (default_target);
2901 pending_goto_end = !ss.Block.HasRet;
2904 ig.MarkLabel (next_test);
2906 if (!default_at_end)
2907 ig.Emit (OpCodes.Br, default_target);
2909 ig.MarkLabel (default_target);
2910 ig.MarkLabel (end_of_switch);
2913 SwitchSection FindSection (SwitchLabel label)
2915 foreach (SwitchSection ss in Sections){
2916 foreach (SwitchLabel sl in ss.Labels){
2925 bool ResolveConstantSwitch (EmitContext ec)
2927 object key = ((Constant) new_expr).GetValue ();
2928 SwitchLabel label = (SwitchLabel) Elements [key];
2933 constant_section = FindSection (label);
2934 if (constant_section == null)
2937 if (constant_section.Block.Resolve (ec) != true)
2943 public override bool Resolve (EmitContext ec)
2945 Expr = Expr.Resolve (ec);
2949 new_expr = SwitchGoverningType (ec, Expr.Type);
2950 if (new_expr == null){
2951 Report.Error (151, loc, "An integer type or string was expected for switch");
2956 SwitchType = new_expr.Type;
2958 if (!CheckSwitch (ec))
2961 Switch old_switch = ec.Switch;
2963 ec.Switch.SwitchType = SwitchType;
2965 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2966 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2968 is_constant = new_expr is Constant;
2970 object key = ((Constant) new_expr).GetValue ();
2971 SwitchLabel label = (SwitchLabel) Elements [key];
2973 constant_section = FindSection (label);
2977 foreach (SwitchSection ss in Sections){
2979 ec.CurrentBranching.CreateSibling (
2980 null, FlowBranching.SiblingType.SwitchSection);
2984 if (is_constant && (ss != constant_section)) {
2985 // If we're a constant switch, we're only emitting
2986 // one single section - mark all the others as
2988 ec.CurrentBranching.CurrentUsageVector.Goto ();
2989 if (!ss.Block.ResolveUnreachable (ec, true))
2992 if (!ss.Block.Resolve (ec))
2998 ec.CurrentBranching.CreateSibling (
2999 null, FlowBranching.SiblingType.SwitchSection);
3001 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3002 ec.Switch = old_switch;
3004 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3010 protected override void DoEmit (EmitContext ec)
3012 ILGenerator ig = ec.ig;
3014 // Store variable for comparission purposes
3017 value = ig.DeclareLocal (SwitchType);
3019 ig.Emit (OpCodes.Stloc, value);
3023 default_target = ig.DefineLabel ();
3026 // Setup the codegen context
3028 Label old_end = ec.LoopEnd;
3029 Switch old_switch = ec.Switch;
3031 ec.LoopEnd = ig.DefineLabel ();
3036 if (constant_section != null)
3037 constant_section.Block.Emit (ec);
3038 } else if (SwitchType == TypeManager.string_type)
3039 SimpleSwitchEmit (ec, value);
3041 TableSwitchEmit (ec, value);
3043 // Restore context state.
3044 ig.MarkLabel (ec.LoopEnd);
3047 // Restore the previous context
3049 ec.LoopEnd = old_end;
3050 ec.Switch = old_switch;
3054 public abstract class ExceptionStatement : Statement
3056 public abstract void EmitFinally (EmitContext ec);
3058 protected bool emit_finally = true;
3059 ArrayList parent_vectors;
3061 protected void DoEmitFinally (EmitContext ec)
3064 ec.ig.BeginFinallyBlock ();
3066 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3070 protected void ResolveFinally (FlowBranchingException branching)
3072 emit_finally = branching.EmitFinally;
3074 branching.Parent.StealFinallyClauses (ref parent_vectors);
3078 public class Lock : ExceptionStatement {
3080 Statement Statement;
3083 public Lock (Expression expr, Statement stmt, Location l)
3090 public override bool Resolve (EmitContext ec)
3092 expr = expr.Resolve (ec);
3096 if (expr.Type.IsValueType){
3097 Error (185, "lock statement requires the expression to be " +
3098 " a reference type (type is: `{0}'",
3099 TypeManager.CSharpName (expr.Type));
3103 FlowBranchingException branching = ec.StartFlowBranching (this);
3104 bool ok = Statement.Resolve (ec);
3106 ec.KillFlowBranching ();
3110 ResolveFinally (branching);
3112 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3113 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3114 // Unfortunately, System.Reflection.Emit automatically emits
3115 // a leave to the end of the finally block.
3116 // This is a problem if `returns' is true since we may jump
3117 // to a point after the end of the method.
3118 // As a workaround, emit an explicit ret here.
3119 ec.NeedReturnLabel ();
3125 protected override void DoEmit (EmitContext ec)
3127 Type type = expr.Type;
3129 ILGenerator ig = ec.ig;
3130 temp = ig.DeclareLocal (type);
3133 ig.Emit (OpCodes.Dup);
3134 ig.Emit (OpCodes.Stloc, temp);
3135 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3139 ig.BeginExceptionBlock ();
3140 Statement.Emit (ec);
3145 ig.EndExceptionBlock ();
3148 public override void EmitFinally (EmitContext ec)
3150 ILGenerator ig = ec.ig;
3151 ig.Emit (OpCodes.Ldloc, temp);
3152 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3156 public class Unchecked : Statement {
3157 public readonly Block Block;
3159 public Unchecked (Block b)
3165 public override bool Resolve (EmitContext ec)
3167 bool previous_state = ec.CheckState;
3168 bool previous_state_const = ec.ConstantCheckState;
3170 ec.CheckState = false;
3171 ec.ConstantCheckState = false;
3172 bool ret = Block.Resolve (ec);
3173 ec.CheckState = previous_state;
3174 ec.ConstantCheckState = previous_state_const;
3179 protected override void DoEmit (EmitContext ec)
3181 bool previous_state = ec.CheckState;
3182 bool previous_state_const = ec.ConstantCheckState;
3184 ec.CheckState = false;
3185 ec.ConstantCheckState = false;
3187 ec.CheckState = previous_state;
3188 ec.ConstantCheckState = previous_state_const;
3192 public class Checked : Statement {
3193 public readonly Block Block;
3195 public Checked (Block b)
3198 b.Unchecked = false;
3201 public override bool Resolve (EmitContext ec)
3203 bool previous_state = ec.CheckState;
3204 bool previous_state_const = ec.ConstantCheckState;
3206 ec.CheckState = true;
3207 ec.ConstantCheckState = true;
3208 bool ret = Block.Resolve (ec);
3209 ec.CheckState = previous_state;
3210 ec.ConstantCheckState = previous_state_const;
3215 protected override void DoEmit (EmitContext ec)
3217 bool previous_state = ec.CheckState;
3218 bool previous_state_const = ec.ConstantCheckState;
3220 ec.CheckState = true;
3221 ec.ConstantCheckState = true;
3223 ec.CheckState = previous_state;
3224 ec.ConstantCheckState = previous_state_const;
3228 public class Unsafe : Statement {
3229 public readonly Block Block;
3231 public Unsafe (Block b)
3234 Block.Unsafe = true;
3237 public override bool Resolve (EmitContext ec)
3239 bool previous_state = ec.InUnsafe;
3243 val = Block.Resolve (ec);
3244 ec.InUnsafe = previous_state;
3249 protected override void DoEmit (EmitContext ec)
3251 bool previous_state = ec.InUnsafe;
3255 ec.InUnsafe = previous_state;
3262 public class Fixed : Statement {
3264 ArrayList declarators;
3265 Statement statement;
3271 public bool is_object;
3272 public LocalInfo vi;
3273 public Expression expr;
3274 public Expression converted;
3277 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3280 declarators = decls;
3285 public override bool Resolve (EmitContext ec)
3288 Expression.UnsafeError (loc);
3292 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3296 expr_type = texpr.ResolveType (ec);
3298 CheckObsolete (expr_type);
3300 if (ec.RemapToProxy){
3301 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3305 data = new FixedData [declarators.Count];
3307 if (!expr_type.IsPointer){
3308 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3313 foreach (Pair p in declarators){
3314 LocalInfo vi = (LocalInfo) p.First;
3315 Expression e = (Expression) p.Second;
3317 vi.VariableInfo.SetAssigned (ec);
3321 // The rules for the possible declarators are pretty wise,
3322 // but the production on the grammar is more concise.
3324 // So we have to enforce these rules here.
3326 // We do not resolve before doing the case 1 test,
3327 // because the grammar is explicit in that the token &
3328 // is present, so we need to test for this particular case.
3332 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3337 // Case 1: & object.
3339 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3340 Expression child = ((Unary) e).Expr;
3342 if (child is ParameterReference || child is LocalVariableReference){
3345 "No need to use fixed statement for parameters or " +
3346 "local variable declarations (address is already " +
3351 ec.InFixedInitializer = true;
3353 ec.InFixedInitializer = false;
3357 child = ((Unary) e).Expr;
3359 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3362 data [i].is_object = true;
3364 data [i].converted = null;
3371 ec.InFixedInitializer = true;
3373 ec.InFixedInitializer = false;
3380 if (e.Type.IsArray){
3381 Type array_type = TypeManager.GetElementType (e.Type);
3384 // Provided that array_type is unmanaged,
3386 if (!TypeManager.VerifyUnManaged (array_type, loc))
3390 // and T* is implicitly convertible to the
3391 // pointer type given in the fixed statement.
3393 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3395 Expression converted = Convert.ImplicitConversionRequired (
3396 ec, array_ptr, vi.VariableType, loc);
3397 if (converted == null)
3400 data [i].is_object = false;
3402 data [i].converted = converted;
3412 if (e.Type == TypeManager.string_type){
3413 data [i].is_object = false;
3415 data [i].converted = null;
3422 // For other cases, flag a `this is already fixed expression'
3424 if (e is LocalVariableReference || e is ParameterReference ||
3425 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3427 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3431 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3435 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3437 if (!statement.Resolve (ec)) {
3438 ec.KillFlowBranching ();
3442 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3443 has_ret = reachability.IsUnreachable;
3448 protected override void DoEmit (EmitContext ec)
3450 ILGenerator ig = ec.ig;
3452 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3454 for (int i = 0; i < data.Length; i++) {
3455 LocalInfo vi = data [i].vi;
3458 // Case 1: & object.
3460 if (data [i].is_object) {
3462 // Store pointer in pinned location
3464 data [i].expr.Emit (ec);
3465 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3466 clear_list [i] = vi.LocalBuilder;
3473 if (data [i].expr.Type.IsArray){
3475 // Store pointer in pinned location
3477 data [i].converted.Emit (ec);
3479 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3480 clear_list [i] = vi.LocalBuilder;
3487 if (data [i].expr.Type == TypeManager.string_type){
3488 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3489 clear_list [i] = pinned_string;
3491 data [i].expr.Emit (ec);
3492 ig.Emit (OpCodes.Stloc, pinned_string);
3494 Expression sptr = new StringPtr (pinned_string, loc);
3495 Expression converted = Convert.ImplicitConversionRequired (
3496 ec, sptr, vi.VariableType, loc);
3498 if (converted == null)
3501 converted.Emit (ec);
3502 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3506 statement.Emit (ec);
3512 // Clear the pinned variable
3514 for (int i = 0; i < data.Length; i++) {
3515 if (data [i].is_object || data [i].expr.Type.IsArray) {
3516 ig.Emit (OpCodes.Ldc_I4_0);
3517 ig.Emit (OpCodes.Conv_U);
3518 ig.Emit (OpCodes.Stloc, clear_list [i]);
3519 } else if (data [i].expr.Type == TypeManager.string_type){
3520 ig.Emit (OpCodes.Ldnull);
3521 ig.Emit (OpCodes.Stloc, clear_list [i]);
3527 public class Catch: Statement {
3528 public readonly string Name;
3529 public readonly Block Block;
3531 Expression type_expr;
3534 public Catch (Expression type, string name, Block block, Location l)
3542 public Type CatchType {
3548 public bool IsGeneral {
3550 return type_expr == null;
3554 protected override void DoEmit(EmitContext ec)
3558 public override bool Resolve (EmitContext ec)
3560 if (type_expr != null) {
3561 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3565 type = te.ResolveType (ec);
3567 CheckObsolete (type);
3569 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3570 Error (155, "The type caught or thrown must be derived from System.Exception");
3576 return Block.Resolve (ec);
3580 public class Try : ExceptionStatement {
3581 public readonly Block Fini, Block;
3582 public readonly ArrayList Specific;
3583 public readonly Catch General;
3585 bool need_exc_block;
3588 // specific, general and fini might all be null.
3590 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3592 if (specific == null && general == null){
3593 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3597 this.Specific = specific;
3598 this.General = general;
3603 public override bool Resolve (EmitContext ec)
3607 FlowBranchingException branching = ec.StartFlowBranching (this);
3609 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3611 if (!Block.Resolve (ec))
3614 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3616 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3618 Type[] prevCatches = new Type [Specific.Count];
3620 foreach (Catch c in Specific){
3621 ec.CurrentBranching.CreateSibling (
3622 c.Block, FlowBranching.SiblingType.Catch);
3624 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3626 if (c.Name != null) {
3627 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3629 throw new Exception ();
3631 vi.VariableInfo = null;
3634 if (!c.Resolve (ec))
3637 Type resolvedType = c.CatchType;
3638 for (int ii = 0; ii < last_index; ++ii) {
3639 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3640 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3645 prevCatches [last_index++] = resolvedType;
3646 need_exc_block = true;
3649 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3651 if (General != null){
3652 ec.CurrentBranching.CreateSibling (
3653 General.Block, FlowBranching.SiblingType.Catch);
3655 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3657 if (!General.Resolve (ec))
3660 need_exc_block = true;
3663 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3667 ec.CurrentBranching.CreateSibling (
3668 Fini, FlowBranching.SiblingType.Finally);
3670 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3672 if (!Fini.Resolve (ec))
3676 ResolveFinally (branching);
3677 need_exc_block |= emit_finally;
3679 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3681 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3683 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3685 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3686 // Unfortunately, System.Reflection.Emit automatically emits
3687 // a leave to the end of the finally block. This is a problem
3688 // if `returns' is true since we may jump to a point after the
3689 // end of the method.
3690 // As a workaround, emit an explicit ret here.
3691 ec.NeedReturnLabel ();
3697 protected override void DoEmit (EmitContext ec)
3699 ILGenerator ig = ec.ig;
3702 ig.BeginExceptionBlock ();
3705 foreach (Catch c in Specific){
3708 ig.BeginCatchBlock (c.CatchType);
3710 if (c.Name != null){
3711 vi = c.Block.GetLocalInfo (c.Name);
3713 throw new Exception ("Variable does not exist in this block");
3715 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3717 ig.Emit (OpCodes.Pop);
3722 if (General != null){
3723 ig.BeginCatchBlock (TypeManager.object_type);
3724 ig.Emit (OpCodes.Pop);
3725 General.Block.Emit (ec);
3730 ig.EndExceptionBlock ();
3733 public override void EmitFinally (EmitContext ec)
3741 public class Using : ExceptionStatement {
3742 object expression_or_block;
3743 Statement Statement;
3748 Expression [] resolved_vars;
3749 Expression [] converted_vars;
3750 ExpressionStatement [] assign;
3751 LocalBuilder local_copy;
3753 public Using (object expression_or_block, Statement stmt, Location l)
3755 this.expression_or_block = expression_or_block;
3761 // Resolves for the case of using using a local variable declaration.
3763 bool ResolveLocalVariableDecls (EmitContext ec)
3767 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3771 expr_type = texpr.ResolveType (ec);
3774 // The type must be an IDisposable or an implicit conversion
3777 converted_vars = new Expression [var_list.Count];
3778 resolved_vars = new Expression [var_list.Count];
3779 assign = new ExpressionStatement [var_list.Count];
3781 bool need_conv = !TypeManager.ImplementsInterface (
3782 expr_type, TypeManager.idisposable_type);
3784 foreach (DictionaryEntry e in var_list){
3785 Expression var = (Expression) e.Key;
3787 var = var.ResolveLValue (ec, new EmptyExpression ());
3791 resolved_vars [i] = var;
3798 converted_vars [i] = Convert.ImplicitConversionRequired (
3799 ec, var, TypeManager.idisposable_type, loc);
3801 if (converted_vars [i] == null)
3808 foreach (DictionaryEntry e in var_list){
3809 Expression var = resolved_vars [i];
3810 Expression new_expr = (Expression) e.Value;
3813 a = new Assign (var, new_expr, loc);
3819 converted_vars [i] = var;
3820 assign [i] = (ExpressionStatement) a;
3827 bool ResolveExpression (EmitContext ec)
3829 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3830 conv = Convert.ImplicitConversionRequired (
3831 ec, expr, TypeManager.idisposable_type, loc);
3841 // Emits the code for the case of using using a local variable declaration.
3843 void EmitLocalVariableDecls (EmitContext ec)
3845 ILGenerator ig = ec.ig;
3848 for (i = 0; i < assign.Length; i++) {
3849 assign [i].EmitStatement (ec);
3852 ig.BeginExceptionBlock ();
3854 Statement.Emit (ec);
3856 var_list.Reverse ();
3861 void EmitLocalVariableDeclFinally (EmitContext ec)
3863 ILGenerator ig = ec.ig;
3865 int i = assign.Length;
3866 foreach (DictionaryEntry e in var_list){
3867 Expression var = resolved_vars [--i];
3868 Label skip = ig.DefineLabel ();
3870 ig.BeginFinallyBlock ();
3872 if (!var.Type.IsValueType) {
3874 ig.Emit (OpCodes.Brfalse, skip);
3875 converted_vars [i].Emit (ec);
3876 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3878 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3880 if (!(ml is MethodGroupExpr)) {
3882 ig.Emit (OpCodes.Box, var.Type);
3883 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3885 MethodInfo mi = null;
3887 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3888 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3895 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3899 IMemoryLocation mloc = (IMemoryLocation) var;
3901 mloc.AddressOf (ec, AddressOp.Load);
3902 ig.Emit (OpCodes.Call, mi);
3906 ig.MarkLabel (skip);
3909 ig.EndExceptionBlock ();
3911 ig.BeginFinallyBlock ();
3916 void EmitExpression (EmitContext ec)
3919 // Make a copy of the expression and operate on that.
3921 ILGenerator ig = ec.ig;
3922 local_copy = ig.DeclareLocal (expr_type);
3927 ig.Emit (OpCodes.Stloc, local_copy);
3930 ig.BeginExceptionBlock ();
3932 Statement.Emit (ec);
3936 ig.EndExceptionBlock ();
3939 void EmitExpressionFinally (EmitContext ec)
3941 ILGenerator ig = ec.ig;
3942 Label skip = ig.DefineLabel ();
3943 ig.Emit (OpCodes.Ldloc, local_copy);
3944 ig.Emit (OpCodes.Brfalse, skip);
3945 ig.Emit (OpCodes.Ldloc, local_copy);
3946 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3947 ig.MarkLabel (skip);
3950 public override bool Resolve (EmitContext ec)
3952 if (expression_or_block is DictionaryEntry){
3953 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3954 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3956 if (!ResolveLocalVariableDecls (ec))
3959 } else if (expression_or_block is Expression){
3960 expr = (Expression) expression_or_block;
3962 expr = expr.Resolve (ec);
3966 expr_type = expr.Type;
3968 if (!ResolveExpression (ec))
3972 FlowBranchingException branching = ec.StartFlowBranching (this);
3974 bool ok = Statement.Resolve (ec);
3977 ec.KillFlowBranching ();
3981 ResolveFinally (branching);
3982 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3984 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3985 // Unfortunately, System.Reflection.Emit automatically emits a leave
3986 // to the end of the finally block. This is a problem if `returns'
3987 // is true since we may jump to a point after the end of the method.
3988 // As a workaround, emit an explicit ret here.
3989 ec.NeedReturnLabel ();
3995 protected override void DoEmit (EmitContext ec)
3997 if (expression_or_block is DictionaryEntry)
3998 EmitLocalVariableDecls (ec);
3999 else if (expression_or_block is Expression)
4000 EmitExpression (ec);
4003 public override void EmitFinally (EmitContext ec)
4005 if (expression_or_block is DictionaryEntry)
4006 EmitLocalVariableDeclFinally (ec);
4007 else if (expression_or_block is Expression)
4008 EmitExpressionFinally (ec);
4013 /// Implementation of the foreach C# statement
4015 public class Foreach : ExceptionStatement {
4017 Expression variable;
4019 Statement statement;
4020 ForeachHelperMethods hm;
4021 Expression empty, conv;
4022 Type array_type, element_type;
4024 VariableStorage enumerator;
4026 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4027 Statement stmt, Location l)
4030 this.variable = var;
4036 public override bool Resolve (EmitContext ec)
4038 expr = expr.Resolve (ec);
4042 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4046 var_type = texpr.ResolveType (ec);
4049 // We need an instance variable. Not sure this is the best
4050 // way of doing this.
4052 // FIXME: When we implement propertyaccess, will those turn
4053 // out to return values in ExprClass? I think they should.
4055 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4056 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4057 error1579 (expr.Type);
4061 if (expr.Type.IsArray) {
4062 array_type = expr.Type;
4063 element_type = TypeManager.GetElementType (array_type);
4065 empty = new EmptyExpression (element_type);
4067 hm = ProbeCollectionType (ec, expr.Type);
4069 error1579 (expr.Type);
4073 array_type = expr.Type;
4074 element_type = hm.element_type;
4076 empty = new EmptyExpression (hm.element_type);
4081 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4082 ec.CurrentBranching.CreateSibling ();
4086 // FIXME: maybe we can apply the same trick we do in the
4087 // array handling to avoid creating empty and conv in some cases.
4089 // Although it is not as important in this case, as the type
4090 // will not likely be object (what the enumerator will return).
4092 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4096 variable = variable.ResolveLValue (ec, empty);
4097 if (variable == null)
4100 bool disposable = (hm != null) && hm.is_disposable;
4101 FlowBranchingException branching = null;
4103 branching = ec.StartFlowBranching (this);
4105 if (!statement.Resolve (ec))
4109 ResolveFinally (branching);
4110 ec.EndFlowBranching ();
4112 emit_finally = true;
4114 ec.EndFlowBranching ();
4120 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4122 static MethodInfo FetchMethodMoveNext (Type t)
4124 MemberList move_next_list;
4126 move_next_list = TypeContainer.FindMembers (
4127 t, MemberTypes.Method,
4128 BindingFlags.Public | BindingFlags.Instance,
4129 Type.FilterName, "MoveNext");
4130 if (move_next_list.Count == 0)
4133 foreach (MemberInfo m in move_next_list){
4134 MethodInfo mi = (MethodInfo) m;
4137 args = TypeManager.GetArgumentTypes (mi);
4138 if (args != null && args.Length == 0){
4139 if (mi.ReturnType == TypeManager.bool_type)
4147 // Retrieves a `public T get_Current ()' method from the Type `t'
4149 static MethodInfo FetchMethodGetCurrent (Type t)
4151 MemberList get_current_list;
4153 get_current_list = TypeContainer.FindMembers (
4154 t, MemberTypes.Method,
4155 BindingFlags.Public | BindingFlags.Instance,
4156 Type.FilterName, "get_Current");
4157 if (get_current_list.Count == 0)
4160 foreach (MemberInfo m in get_current_list){
4161 MethodInfo mi = (MethodInfo) m;
4164 args = TypeManager.GetArgumentTypes (mi);
4165 if (args != null && args.Length == 0)
4172 // Retrieves a `public void Dispose ()' method from the Type `t'
4174 static MethodInfo FetchMethodDispose (Type t)
4176 MemberList dispose_list;
4178 dispose_list = TypeContainer.FindMembers (
4179 t, MemberTypes.Method,
4180 BindingFlags.Public | BindingFlags.Instance,
4181 Type.FilterName, "Dispose");
4182 if (dispose_list.Count == 0)
4185 foreach (MemberInfo m in dispose_list){
4186 MethodInfo mi = (MethodInfo) m;
4189 args = TypeManager.GetArgumentTypes (mi);
4190 if (args != null && args.Length == 0){
4191 if (mi.ReturnType == TypeManager.void_type)
4199 // This struct records the helper methods used by the Foreach construct
4201 class ForeachHelperMethods {
4202 public EmitContext ec;
4203 public MethodInfo get_enumerator;
4204 public MethodInfo move_next;
4205 public MethodInfo get_current;
4206 public Type element_type;
4207 public Type enumerator_type;
4208 public bool is_disposable;
4210 public ForeachHelperMethods (EmitContext ec)
4213 this.element_type = TypeManager.object_type;
4214 this.enumerator_type = TypeManager.ienumerator_type;
4215 this.is_disposable = true;
4219 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4224 if (!(m is MethodInfo))
4227 if (m.Name != "GetEnumerator")
4230 MethodInfo mi = (MethodInfo) m;
4231 Type [] args = TypeManager.GetArgumentTypes (mi);
4233 if (args.Length != 0)
4236 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4237 EmitContext ec = hm.ec;
4239 // Check whether GetEnumerator is public
4240 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4243 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4245 // Apply the same optimization as MS: skip the GetEnumerator
4246 // returning an IEnumerator, and use the one returning a
4247 // CharEnumerator instead. This allows us to avoid the
4248 // try-finally block and the boxing.
4253 // Ok, we can access it, now make sure that we can do something
4254 // with this `GetEnumerator'
4257 Type return_type = mi.ReturnType;
4258 if (mi.ReturnType == TypeManager.ienumerator_type ||
4259 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4260 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4263 // If it is not an interface, lets try to find the methods ourselves.
4264 // For example, if we have:
4265 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4266 // We can avoid the iface call. This is a runtime perf boost.
4267 // even bigger if we have a ValueType, because we avoid the cost
4270 // We have to make sure that both methods exist for us to take
4271 // this path. If one of the methods does not exist, we will just
4272 // use the interface. Sadly, this complex if statement is the only
4273 // way I could do this without a goto
4276 if (return_type.IsInterface ||
4277 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4278 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4280 hm.move_next = TypeManager.bool_movenext_void;
4281 hm.get_current = TypeManager.object_getcurrent_void;
4288 // Ok, so they dont return an IEnumerable, we will have to
4289 // find if they support the GetEnumerator pattern.
4292 hm.move_next = FetchMethodMoveNext (return_type);
4293 if (hm.move_next == null)
4296 hm.get_current = FetchMethodGetCurrent (return_type);
4297 if (hm.get_current == null)
4301 hm.element_type = hm.get_current.ReturnType;
4302 hm.enumerator_type = return_type;
4303 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4304 TypeManager.ImplementsInterface (
4305 hm.enumerator_type, TypeManager.idisposable_type);
4311 /// This filter is used to find the GetEnumerator method
4312 /// on which IEnumerator operates
4314 static MemberFilter FilterEnumerator;
4318 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4321 void error1579 (Type t)
4323 Report.Error (1579, loc,
4324 "foreach statement cannot operate on variables of type `" +
4325 t.FullName + "' because that class does not provide a " +
4326 " GetEnumerator method or it is inaccessible");
4329 static bool TryType (Type t, ForeachHelperMethods hm)
4333 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4334 BindingFlags.Public | BindingFlags.NonPublic |
4335 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4336 FilterEnumerator, hm);
4341 hm.get_enumerator = (MethodInfo) mi [0];
4346 // Looks for a usable GetEnumerator in the Type, and if found returns
4347 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4349 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4351 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4353 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4354 if (TryType (tt, hm))
4360 // Now try to find the method in the interfaces
4363 Type [] ifaces = t.GetInterfaces ();
4365 foreach (Type i in ifaces){
4366 if (TryType (i, hm))
4371 // Since TypeBuilder.GetInterfaces only returns the interface
4372 // types for this type, we have to keep looping, but once
4373 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4374 // done, because it returns all the types
4376 if ((t is TypeBuilder))
4386 // FIXME: possible optimization.
4387 // We might be able to avoid creating `empty' if the type is the sam
4389 bool EmitCollectionForeach (EmitContext ec)
4391 ILGenerator ig = ec.ig;
4393 enumerator = new VariableStorage (ec, hm.enumerator_type);
4394 enumerator.EmitThis (ig);
4396 // Instantiate the enumerator
4398 if (expr.Type.IsValueType){
4399 IMemoryLocation ml = expr as IMemoryLocation;
4400 // Load the address of the value type.
4402 // This happens if, for example, you have a property
4403 // returning a struct which is IEnumerable
4404 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4406 ig.Emit (OpCodes.Stloc, t);
4407 ig.Emit (OpCodes.Ldloca, t);
4408 ec.FreeTemporaryLocal (t, expr.Type);
4410 ml.AddressOf (ec, AddressOp.Load);
4414 if (hm.get_enumerator.DeclaringType.IsValueType) {
4415 // the method is declared on the value type
4416 ig.Emit (OpCodes.Call, hm.get_enumerator);
4418 // it is an interface method, so we must box
4419 ig.Emit (OpCodes.Box, expr.Type);
4420 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4424 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4426 enumerator.EmitStore (ig);
4429 // Protect the code in a try/finalize block, so that
4430 // if the beast implement IDisposable, we get rid of it
4432 if (hm.is_disposable && emit_finally)
4433 ig.BeginExceptionBlock ();
4435 Label end_try = ig.DefineLabel ();
4437 ig.MarkLabel (ec.LoopBegin);
4439 enumerator.EmitCall (ig, hm.move_next);
4441 ig.Emit (OpCodes.Brfalse, end_try);
4444 enumerator.EmitThis (ig);
4445 enumerator.EmitCall (ig, hm.get_current);
4449 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4451 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4453 statement.Emit (ec);
4454 ig.Emit (OpCodes.Br, ec.LoopBegin);
4455 ig.MarkLabel (end_try);
4457 // The runtime provides this for us.
4458 // ig.Emit (OpCodes.Leave, end);
4461 // Now the finally block
4463 if (hm.is_disposable) {
4466 ig.EndExceptionBlock ();
4469 ig.MarkLabel (ec.LoopEnd);
4473 public override void EmitFinally (EmitContext ec)
4475 ILGenerator ig = ec.ig;
4477 if (hm.enumerator_type.IsValueType) {
4478 enumerator.EmitThis (ig);
4480 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4482 enumerator.EmitLoadAddress (ig);
4483 ig.Emit (OpCodes.Call, mi);
4485 enumerator.EmitLoad (ig);
4486 ig.Emit (OpCodes.Box, hm.enumerator_type);
4487 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4490 Label call_dispose = ig.DefineLabel ();
4492 enumerator.EmitThis (ig);
4493 enumerator.EmitLoad (ig);
4494 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4495 ig.Emit (OpCodes.Dup);
4496 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4497 ig.Emit (OpCodes.Pop);
4499 Label end_finally = ig.DefineLabel ();
4500 ig.Emit (OpCodes.Br, end_finally);
4502 ig.MarkLabel (call_dispose);
4503 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4504 ig.MarkLabel (end_finally);
4507 ig.Emit (OpCodes.Endfinally);
4512 // FIXME: possible optimization.
4513 // We might be able to avoid creating `empty' if the type is the sam
4515 bool EmitArrayForeach (EmitContext ec)
4517 int rank = array_type.GetArrayRank ();
4518 ILGenerator ig = ec.ig;
4520 VariableStorage copy = new VariableStorage (ec, array_type);
4523 // Make our copy of the array
4527 copy.EmitStore (ig);
4530 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4534 counter.EmitThis (ig);
4535 ig.Emit (OpCodes.Ldc_I4_0);
4536 counter.EmitStore (ig);
4537 test = ig.DefineLabel ();
4538 ig.Emit (OpCodes.Br, test);
4540 loop = ig.DefineLabel ();
4541 ig.MarkLabel (loop);
4548 counter.EmitThis (ig);
4549 counter.EmitLoad (ig);
4552 // Load the value, we load the value using the underlying type,
4553 // then we use the variable.EmitAssign to load using the proper cast.
4555 ArrayAccess.EmitLoadOpcode (ig, element_type);
4558 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4560 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4562 statement.Emit (ec);
4564 ig.MarkLabel (ec.LoopBegin);
4565 counter.EmitThis (ig);
4566 counter.EmitThis (ig);
4567 counter.EmitLoad (ig);
4568 ig.Emit (OpCodes.Ldc_I4_1);
4569 ig.Emit (OpCodes.Add);
4570 counter.EmitStore (ig);
4572 ig.MarkLabel (test);
4573 counter.EmitThis (ig);
4574 counter.EmitLoad (ig);
4577 ig.Emit (OpCodes.Ldlen);
4578 ig.Emit (OpCodes.Conv_I4);
4579 ig.Emit (OpCodes.Blt, loop);
4581 VariableStorage [] dim_len = new VariableStorage [rank];
4582 VariableStorage [] dim_count = new VariableStorage [rank];
4583 Label [] loop = new Label [rank];
4584 Label [] test = new Label [rank];
4587 for (dim = 0; dim < rank; dim++){
4588 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4589 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4590 test [dim] = ig.DefineLabel ();
4591 loop [dim] = ig.DefineLabel ();
4594 for (dim = 0; dim < rank; dim++){
4595 dim_len [dim].EmitThis (ig);
4598 IntLiteral.EmitInt (ig, dim);
4599 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4600 dim_len [dim].EmitStore (ig);
4604 for (dim = 0; dim < rank; dim++){
4605 dim_count [dim].EmitThis (ig);
4606 ig.Emit (OpCodes.Ldc_I4_0);
4607 dim_count [dim].EmitStore (ig);
4608 ig.Emit (OpCodes.Br, test [dim]);
4609 ig.MarkLabel (loop [dim]);
4616 for (dim = 0; dim < rank; dim++){
4617 dim_count [dim].EmitThis (ig);
4618 dim_count [dim].EmitLoad (ig);
4622 // FIXME: Maybe we can cache the computation of `get'?
4624 Type [] args = new Type [rank];
4627 for (int i = 0; i < rank; i++)
4628 args [i] = TypeManager.int32_type;
4630 ModuleBuilder mb = CodeGen.Module.Builder;
4631 get = mb.GetArrayMethod (
4633 CallingConventions.HasThis| CallingConventions.Standard,
4635 ig.Emit (OpCodes.Call, get);
4638 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4640 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4641 statement.Emit (ec);
4642 ig.MarkLabel (ec.LoopBegin);
4643 for (dim = rank - 1; dim >= 0; dim--){
4644 dim_count [dim].EmitThis (ig);
4645 dim_count [dim].EmitThis (ig);
4646 dim_count [dim].EmitLoad (ig);
4647 ig.Emit (OpCodes.Ldc_I4_1);
4648 ig.Emit (OpCodes.Add);
4649 dim_count [dim].EmitStore (ig);
4651 ig.MarkLabel (test [dim]);
4652 dim_count [dim].EmitThis (ig);
4653 dim_count [dim].EmitLoad (ig);
4654 dim_len [dim].EmitThis (ig);
4655 dim_len [dim].EmitLoad (ig);
4656 ig.Emit (OpCodes.Blt, loop [dim]);
4659 ig.MarkLabel (ec.LoopEnd);
4664 protected override void DoEmit (EmitContext ec)
4666 ILGenerator ig = ec.ig;
4668 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4669 ec.LoopBegin = ig.DefineLabel ();
4670 ec.LoopEnd = ig.DefineLabel ();
4673 EmitCollectionForeach (ec);
4675 EmitArrayForeach (ec);
4677 ec.LoopBegin = old_begin;
4678 ec.LoopEnd = old_end;