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 if (!child_variable_names.Contains (name))
1436 child_variable_names.Add (name, true);
1440 // Checks whether a variable name has already been used in a child block.
1442 public bool IsVariableNameUsedInChildBlock (string name)
1444 if (child_variable_names == null)
1447 return child_variable_names.Contains (name);
1451 // This is used by non-static `struct' constructors which do not have an
1452 // initializer - in this case, the constructor must initialize all of the
1453 // struct's fields. To do this, we add a "this" variable and use the flow
1454 // analysis code to ensure that it's been fully initialized before control
1455 // leaves the constructor.
1457 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1459 if (this_variable != null)
1460 return this_variable;
1462 if (variables == null)
1463 variables = new Hashtable ();
1465 this_variable = new LocalInfo (tc, this, l);
1466 this_variable.Used = true;
1467 this_variable.IsThis = true;
1469 variables.Add ("this", this_variable);
1471 return this_variable;
1474 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1476 if (variables == null)
1477 variables = new Hashtable ();
1479 LocalInfo vi = GetLocalInfo (name);
1481 if (vi.Block != this)
1482 Report.Error (136, l, "A local variable named `" + name + "' " +
1483 "cannot be declared in this scope since it would " +
1484 "give a different meaning to `" + name + "', which " +
1485 "is already used in a `parent or current' scope to " +
1486 "denote something else");
1488 Report.Error (128, l, "A local variable `" + name + "' is already " +
1489 "defined in this scope");
1493 if (IsVariableNameUsedInChildBlock (name)) {
1494 Report.Error (136, l, "A local variable named `" + name + "' " +
1495 "cannot be declared in this scope since it would " +
1496 "give a different meaning to `" + name + "', which " +
1497 "is already used in a `child' scope to denote something " +
1504 Parameter p = pars.GetParameterByName (name, out idx);
1506 Report.Error (136, l, "A local variable named `" + name + "' " +
1507 "cannot be declared in this scope since it would " +
1508 "give a different meaning to `" + name + "', which " +
1509 "is already used in a `parent or current' scope to " +
1510 "denote something else");
1515 vi = new LocalInfo (type, name, this, l);
1517 variables.Add (name, vi);
1519 // Mark 'name' as "used by a child block" in every surrounding block
1521 while (cur != null && cur.Implicit)
1524 for (Block par = cur.Parent; par != null; par = par.Parent)
1525 par.AddChildVariableName (name);
1527 if ((flags & Flags.VariablesInitialized) != 0)
1528 throw new Exception ();
1530 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1534 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1536 if (AddVariable (type, name, pars, l) == null)
1539 if (constants == null)
1540 constants = new Hashtable ();
1542 constants.Add (name, value);
1546 public Hashtable Variables {
1552 public LocalInfo GetLocalInfo (string name)
1554 for (Block b = this; b != null; b = b.Parent) {
1555 if (b.variables != null) {
1556 LocalInfo ret = b.variables [name] as LocalInfo;
1564 public Expression GetVariableType (string name)
1566 LocalInfo vi = GetLocalInfo (name);
1574 public Expression GetConstantExpression (string name)
1576 for (Block b = this; b != null; b = b.Parent) {
1577 if (b.constants != null) {
1578 Expression ret = b.constants [name] as Expression;
1587 /// True if the variable named @name is a constant
1589 public bool IsConstant (string name)
1591 Expression e = null;
1593 e = GetConstantExpression (name);
1599 // Returns a `ParameterReference' for the given name, or null if there
1600 // is no such parameter
1602 public ParameterReference GetParameterReference (string name, Location loc)
1607 Parameters pars = b.parameters;
1613 par = pars.GetParameterByName (name, out idx);
1615 ParameterReference pr;
1617 pr = new ParameterReference (pars, this, idx, name, loc);
1622 } while (b != null);
1627 // Whether the parameter named `name' is local to this block,
1628 // or false, if the parameter belongs to an encompassing block.
1630 public bool IsLocalParameter (string name)
1633 int toplevel_count = 0;
1636 if (this is ToplevelBlock)
1639 Parameters pars = b.parameters;
1641 if (pars.GetParameterByName (name) != null)
1645 if (toplevel_count > 0)
1648 } while (b != null);
1653 // Whether the `name' is a parameter reference
1655 public bool IsParameterReference (string name)
1660 Parameters pars = b.parameters;
1663 if (pars.GetParameterByName (name) != null)
1666 } while (b != null);
1671 /// A list of labels that were not used within this block
1673 public string [] GetUnreferenced ()
1675 // FIXME: Implement me
1679 public void AddStatement (Statement s)
1682 flags |= Flags.BlockUsed;
1687 return (flags & Flags.BlockUsed) != 0;
1693 flags |= Flags.BlockUsed;
1696 public bool HasRet {
1698 return (flags & Flags.HasRet) != 0;
1702 public bool IsDestructor {
1704 return (flags & Flags.IsDestructor) != 0;
1708 public void SetDestructor ()
1710 flags |= Flags.IsDestructor;
1713 VariableMap param_map, local_map;
1715 public VariableMap ParameterMap {
1717 if ((flags & Flags.VariablesInitialized) == 0)
1718 throw new Exception ("Variables have not been initialized yet");
1724 public VariableMap LocalMap {
1726 if ((flags & Flags.VariablesInitialized) == 0)
1727 throw new Exception ("Variables have not been initialized yet");
1734 /// Emits the variable declarations and labels.
1737 /// tc: is our typecontainer (to resolve type references)
1738 /// ig: is the code generator:
1740 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1742 ILGenerator ig = ec.ig;
1744 bool old_unsafe = ec.InUnsafe;
1746 // If some parent block was unsafe, we remain unsafe even if this block
1747 // isn't explicitly marked as such.
1748 ec.InUnsafe |= Unsafe;
1751 // Compute the VariableMap's.
1753 // Unfortunately, we don't know the type when adding variables with
1754 // AddVariable(), so we need to compute this info here.
1758 if (variables != null) {
1759 foreach (LocalInfo li in variables.Values)
1762 locals = new LocalInfo [variables.Count];
1763 variables.Values.CopyTo (locals, 0);
1765 locals = new LocalInfo [0];
1768 local_map = new VariableMap (Parent.LocalMap, locals);
1770 local_map = new VariableMap (locals);
1772 param_map = new VariableMap (ip);
1773 flags |= Flags.VariablesInitialized;
1775 bool old_check_state = ec.ConstantCheckState;
1776 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1779 // Process this block variables
1781 if (variables != null){
1782 foreach (DictionaryEntry de in variables){
1783 string name = (string) de.Key;
1784 LocalInfo vi = (LocalInfo) de.Value;
1786 if (vi.VariableType == null)
1789 Type variable_type = vi.VariableType;
1791 if (variable_type.IsPointer){
1793 // Am not really convinced that this test is required (Microsoft does it)
1794 // but the fact is that you would not be able to use the pointer variable
1797 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1804 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1807 // This is needed to compile on both .NET 1.x and .NET 2.x
1808 // the later introduced `DeclareLocal (Type t, bool pinned)'
1810 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1811 else if (!vi.IsThis)
1812 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1815 if (constants == null)
1818 Expression cv = (Expression) constants [name];
1822 ec.CurrentBlock = this;
1823 Expression e = cv.Resolve (ec);
1827 Constant ce = e as Constant;
1829 Report.Error (133, vi.Location,
1830 "The expression being assigned to `" +
1831 name + "' must be constant (" + e + ")");
1835 if (e.Type != variable_type){
1836 e = Const.ChangeType (vi.Location, ce, variable_type);
1841 constants.Remove (name);
1842 constants.Add (name, e);
1845 ec.ConstantCheckState = old_check_state;
1848 // Now, handle the children
1850 if (children != null){
1851 foreach (Block b in children)
1852 b.ResolveMeta (toplevel, ec, ip);
1854 ec.InUnsafe = old_unsafe;
1858 // Emits the local variable declarations for a block
1860 public void EmitMeta (EmitContext ec)
1862 ILGenerator ig = ec.ig;
1864 if (variables != null){
1865 bool have_captured_vars = ec.HaveCapturedVariables ();
1866 bool remap_locals = ec.RemapToProxy;
1868 foreach (DictionaryEntry de in variables){
1869 LocalInfo vi = (LocalInfo) de.Value;
1871 if (have_captured_vars && ec.IsCaptured (vi))
1875 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1879 // This is needed to compile on both .NET 1.x and .NET 2.x
1880 // the later introduced `DeclareLocal (Type t, bool pinned)'
1882 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1883 else if (!vi.IsThis)
1884 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1889 if (children != null){
1890 foreach (Block b in children)
1895 void UsageWarning (FlowBranching.UsageVector vector)
1899 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1900 foreach (DictionaryEntry de in variables){
1901 LocalInfo vi = (LocalInfo) de.Value;
1906 name = (string) de.Key;
1908 if (vector.IsAssigned (vi.VariableInfo)){
1909 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1911 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1917 bool unreachable_shown;
1919 public override bool Resolve (EmitContext ec)
1921 Block prev_block = ec.CurrentBlock;
1924 int errors = Report.Errors;
1926 ec.CurrentBlock = this;
1927 ec.StartFlowBranching (this);
1929 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1931 bool unreachable = false;
1933 int statement_count = statements.Count;
1934 for (int ix = 0; ix < statement_count; ix++){
1935 Statement s = (Statement) statements [ix];
1937 if (unreachable && !(s is LabeledStatement)) {
1938 if (s == EmptyStatement.Value)
1939 s.loc = EndLocation;
1941 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1944 if (s != EmptyStatement.Value)
1945 unreachable_shown = true;
1947 s.loc = Location.Null;
1949 statements [ix] = EmptyStatement.Value;
1953 if (s.Resolve (ec) == false) {
1955 statements [ix] = EmptyStatement.Value;
1959 num_statements = ix + 1;
1961 if (s is LabeledStatement)
1962 unreachable = false;
1964 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1967 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1968 ec.CurrentBranching, statement_count, num_statements);
1971 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1973 ec.CurrentBlock = prev_block;
1975 // If we're a non-static `struct' constructor which doesn't have an
1976 // initializer, then we must initialize all of the struct's fields.
1977 if ((this_variable != null) &&
1978 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1979 !this_variable.IsThisAssigned (ec, loc))
1982 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1983 foreach (LabeledStatement label in labels.Values)
1984 if (!label.HasBeenReferenced)
1985 Report.Warning (164, label.Location,
1986 "This label has not been referenced");
1989 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1991 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1992 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1993 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1994 flags |= Flags.HasRet;
1996 if (ok && (errors == Report.Errors)) {
1997 if (RootContext.WarningLevel >= 3)
1998 UsageWarning (vector);
2004 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2006 unreachable_shown = true;
2007 return base.ResolveUnreachable (ec, warn);
2010 protected override void DoEmit (EmitContext ec)
2012 for (int ix = 0; ix < num_statements; ix++){
2013 Statement s = (Statement) statements [ix];
2015 // Check whether we are the last statement in a
2018 if ((Parent == null) && (ix+1 == num_statements))
2019 ec.IsLastStatement = true;
2021 ec.IsLastStatement = false;
2027 public override void Emit (EmitContext ec)
2029 Block prev_block = ec.CurrentBlock;
2031 ec.CurrentBlock = this;
2033 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2034 bool is_lexical_block = !Implicit && (Parent != null);
2036 if (emit_debug_info) {
2037 if (is_lexical_block)
2038 ec.ig.BeginScope ();
2040 if (variables != null) {
2041 foreach (DictionaryEntry de in variables) {
2042 string name = (string) de.Key;
2043 LocalInfo vi = (LocalInfo) de.Value;
2045 if (vi.LocalBuilder == null)
2048 ec.DefineLocalVariable (name, vi.LocalBuilder);
2053 ec.Mark (StartLocation, true);
2055 ec.Mark (EndLocation, true);
2057 if (emit_debug_info && is_lexical_block)
2060 ec.CurrentBlock = prev_block;
2063 public ToplevelBlock Toplevel {
2066 while (b.Parent != null){
2067 if ((b.flags & Flags.IsToplevel) != 0)
2072 return (ToplevelBlock) b;
2077 // Returns true if we ar ea child of `b'.
2079 public bool IsChildOf (Block b)
2081 Block current = this;
2084 if (current.Parent == b)
2086 current = current.Parent;
2087 } while (current != null);
2093 // A toplevel block contains extra information, the split is done
2094 // only to separate information that would otherwise bloat the more
2095 // lightweight Block.
2097 // In particular, this was introduced when the support for Anonymous
2098 // Methods was implemented.
2100 public class ToplevelBlock : Block {
2102 // Pointer to the host of this anonymous method, or null
2103 // if we are the topmost block
2105 public ToplevelBlock Container;
2106 CaptureContext capture_context;
2108 Hashtable capture_contexts;
2115 public void RegisterCaptureContext (CaptureContext cc)
2117 if (capture_contexts == null)
2118 capture_contexts = new Hashtable ();
2119 capture_contexts [cc] = cc;
2122 public void CompleteContexts ()
2124 if (capture_contexts == null)
2127 foreach (CaptureContext cc in capture_contexts.Keys){
2132 public CaptureContext ToplevelBlockCaptureContext {
2134 return capture_context;
2139 // Parent is only used by anonymous blocks to link back to their
2142 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2143 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2145 Container = container;
2148 public ToplevelBlock (Parameters parameters, Location start) :
2149 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2153 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2154 base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2158 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2162 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2164 if (capture_context == null)
2165 capture_context = new CaptureContext (this, loc, host);
2168 public CaptureContext CaptureContext {
2170 return capture_context;
2175 public class SwitchLabel {
2178 public Location loc;
2182 Label il_label_code;
2183 bool il_label_code_set;
2186 // if expr == null, then it is the default case.
2188 public SwitchLabel (Expression expr, Location l)
2194 public Expression Label {
2200 public object Converted {
2206 public Label GetILLabel (EmitContext ec)
2209 il_label = ec.ig.DefineLabel ();
2210 il_label_set = true;
2215 public Label GetILLabelCode (EmitContext ec)
2217 if (!il_label_code_set){
2218 il_label_code = ec.ig.DefineLabel ();
2219 il_label_code_set = true;
2221 return il_label_code;
2225 // Resolves the expression, reduces it to a literal if possible
2226 // and then converts it to the requested type.
2228 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2233 Expression e = label.Resolve (ec);
2238 if (!(e is Constant)){
2239 Report.Error (150, loc, "A constant value is expected, got: " + e);
2243 if (e is StringConstant || e is NullLiteral){
2244 if (required_type == TypeManager.string_type){
2250 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2251 if (converted == null)
2258 public class SwitchSection {
2259 // An array of SwitchLabels.
2260 public readonly ArrayList Labels;
2261 public readonly Block Block;
2263 public SwitchSection (ArrayList labels, Block block)
2270 public class Switch : Statement {
2271 public readonly ArrayList Sections;
2272 public Expression Expr;
2275 /// Maps constants whose type type SwitchType to their SwitchLabels.
2277 public Hashtable Elements;
2280 /// The governing switch type
2282 public Type SwitchType;
2288 Label default_target;
2289 Expression new_expr;
2291 SwitchSection constant_section;
2294 // The types allowed to be implicitly cast from
2295 // on the governing type
2297 static Type [] allowed_types;
2299 public Switch (Expression e, ArrayList sects, Location l)
2306 public bool GotDefault {
2312 public Label DefaultTarget {
2314 return default_target;
2319 // Determines the governing type for a switch. The returned
2320 // expression might be the expression from the switch, or an
2321 // expression that includes any potential conversions to the
2322 // integral types or to string.
2324 Expression SwitchGoverningType (EmitContext ec, Type t)
2326 if (t == TypeManager.int32_type ||
2327 t == TypeManager.uint32_type ||
2328 t == TypeManager.char_type ||
2329 t == TypeManager.byte_type ||
2330 t == TypeManager.sbyte_type ||
2331 t == TypeManager.ushort_type ||
2332 t == TypeManager.short_type ||
2333 t == TypeManager.uint64_type ||
2334 t == TypeManager.int64_type ||
2335 t == TypeManager.string_type ||
2336 t == TypeManager.bool_type ||
2337 t.IsSubclassOf (TypeManager.enum_type))
2340 if (allowed_types == null){
2341 allowed_types = new Type [] {
2342 TypeManager.sbyte_type,
2343 TypeManager.byte_type,
2344 TypeManager.short_type,
2345 TypeManager.ushort_type,
2346 TypeManager.int32_type,
2347 TypeManager.uint32_type,
2348 TypeManager.int64_type,
2349 TypeManager.uint64_type,
2350 TypeManager.char_type,
2351 TypeManager.bool_type,
2352 TypeManager.string_type
2357 // Try to find a *user* defined implicit conversion.
2359 // If there is no implicit conversion, or if there are multiple
2360 // conversions, we have to report an error
2362 Expression converted = null;
2363 foreach (Type tt in allowed_types){
2366 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2370 if (converted != null){
2371 Report.Error (-12, loc, "More than one conversion to an integral " +
2372 " type exists for type `" +
2373 TypeManager.CSharpName (Expr.Type)+"'");
2381 static string Error152 {
2383 return "The label '{0}:' already occurs in this switch statement";
2388 // Performs the basic sanity checks on the switch statement
2389 // (looks for duplicate keys and non-constant expressions).
2391 // It also returns a hashtable with the keys that we will later
2392 // use to compute the switch tables
2394 bool CheckSwitch (EmitContext ec)
2398 Elements = new Hashtable ();
2400 got_default = false;
2402 if (TypeManager.IsEnumType (SwitchType)){
2403 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2405 compare_type = SwitchType;
2407 foreach (SwitchSection ss in Sections){
2408 foreach (SwitchLabel sl in ss.Labels){
2409 if (!sl.ResolveAndReduce (ec, SwitchType)){
2414 if (sl.Label == null){
2416 Report.Error (152, sl.loc, Error152, "default");
2423 object key = sl.Converted;
2425 if (key is Constant)
2426 key = ((Constant) key).GetValue ();
2429 key = NullLiteral.Null;
2431 string lname = null;
2432 if (compare_type == TypeManager.uint64_type){
2433 ulong v = (ulong) key;
2435 if (Elements.Contains (v))
2436 lname = v.ToString ();
2438 Elements.Add (v, sl);
2439 } else if (compare_type == TypeManager.int64_type){
2440 long v = (long) key;
2442 if (Elements.Contains (v))
2443 lname = v.ToString ();
2445 Elements.Add (v, sl);
2446 } else if (compare_type == TypeManager.uint32_type){
2447 uint v = (uint) key;
2449 if (Elements.Contains (v))
2450 lname = v.ToString ();
2452 Elements.Add (v, sl);
2453 } else if (compare_type == TypeManager.char_type){
2454 char v = (char) key;
2456 if (Elements.Contains (v))
2457 lname = v.ToString ();
2459 Elements.Add (v, sl);
2460 } else if (compare_type == TypeManager.byte_type){
2461 byte v = (byte) key;
2463 if (Elements.Contains (v))
2464 lname = v.ToString ();
2466 Elements.Add (v, sl);
2467 } else if (compare_type == TypeManager.sbyte_type){
2468 sbyte v = (sbyte) key;
2470 if (Elements.Contains (v))
2471 lname = v.ToString ();
2473 Elements.Add (v, sl);
2474 } else if (compare_type == TypeManager.short_type){
2475 short v = (short) key;
2477 if (Elements.Contains (v))
2478 lname = v.ToString ();
2480 Elements.Add (v, sl);
2481 } else if (compare_type == TypeManager.ushort_type){
2482 ushort v = (ushort) key;
2484 if (Elements.Contains (v))
2485 lname = v.ToString ();
2487 Elements.Add (v, sl);
2488 } else if (compare_type == TypeManager.string_type){
2489 if (key is NullLiteral){
2490 if (Elements.Contains (NullLiteral.Null))
2493 Elements.Add (NullLiteral.Null, null);
2495 string s = (string) key;
2497 if (Elements.Contains (s))
2500 Elements.Add (s, sl);
2502 } else if (compare_type == TypeManager.int32_type) {
2505 if (Elements.Contains (v))
2506 lname = v.ToString ();
2508 Elements.Add (v, sl);
2509 } else if (compare_type == TypeManager.bool_type) {
2510 bool v = (bool) key;
2512 if (Elements.Contains (v))
2513 lname = v.ToString ();
2515 Elements.Add (v, sl);
2519 throw new Exception ("Unknown switch type!" +
2520 SwitchType + " " + compare_type);
2524 Report.Error (152, sl.loc, Error152, "case " + lname);
2535 void EmitObjectInteger (ILGenerator ig, object k)
2538 IntConstant.EmitInt (ig, (int) k);
2539 else if (k is Constant) {
2540 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2543 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2546 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2548 IntConstant.EmitInt (ig, (int) (long) k);
2549 ig.Emit (OpCodes.Conv_I8);
2552 LongConstant.EmitLong (ig, (long) k);
2554 else if (k is ulong)
2556 if ((ulong) k < (1L<<32))
2558 IntConstant.EmitInt (ig, (int) (long) k);
2559 ig.Emit (OpCodes.Conv_U8);
2563 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2567 IntConstant.EmitInt (ig, (int) ((char) k));
2568 else if (k is sbyte)
2569 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2571 IntConstant.EmitInt (ig, (int) ((byte) k));
2572 else if (k is short)
2573 IntConstant.EmitInt (ig, (int) ((short) k));
2574 else if (k is ushort)
2575 IntConstant.EmitInt (ig, (int) ((ushort) k));
2577 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2579 throw new Exception ("Unhandled case");
2582 // structure used to hold blocks of keys while calculating table switch
2583 class KeyBlock : IComparable
2585 public KeyBlock (long _nFirst)
2587 nFirst = nLast = _nFirst;
2591 public ArrayList rgKeys = null;
2592 // how many items are in the bucket
2593 public int Size = 1;
2596 get { return (int) (nLast - nFirst + 1); }
2598 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2600 return kbLast.nLast - kbFirst.nFirst + 1;
2602 public int CompareTo (object obj)
2604 KeyBlock kb = (KeyBlock) obj;
2605 int nLength = Length;
2606 int nLengthOther = kb.Length;
2607 if (nLengthOther == nLength)
2608 return (int) (kb.nFirst - nFirst);
2609 return nLength - nLengthOther;
2614 /// This method emits code for a lookup-based switch statement (non-string)
2615 /// Basically it groups the cases into blocks that are at least half full,
2616 /// and then spits out individual lookup opcodes for each block.
2617 /// It emits the longest blocks first, and short blocks are just
2618 /// handled with direct compares.
2620 /// <param name="ec"></param>
2621 /// <param name="val"></param>
2622 /// <returns></returns>
2623 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2625 int cElements = Elements.Count;
2626 object [] rgKeys = new object [cElements];
2627 Elements.Keys.CopyTo (rgKeys, 0);
2628 Array.Sort (rgKeys);
2630 // initialize the block list with one element per key
2631 ArrayList rgKeyBlocks = new ArrayList ();
2632 foreach (object key in rgKeys)
2633 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2636 // iteratively merge the blocks while they are at least half full
2637 // there's probably a really cool way to do this with a tree...
2638 while (rgKeyBlocks.Count > 1)
2640 ArrayList rgKeyBlocksNew = new ArrayList ();
2641 kbCurr = (KeyBlock) rgKeyBlocks [0];
2642 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2644 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2645 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2648 kbCurr.nLast = kb.nLast;
2649 kbCurr.Size += kb.Size;
2653 // start a new block
2654 rgKeyBlocksNew.Add (kbCurr);
2658 rgKeyBlocksNew.Add (kbCurr);
2659 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2661 rgKeyBlocks = rgKeyBlocksNew;
2664 // initialize the key lists
2665 foreach (KeyBlock kb in rgKeyBlocks)
2666 kb.rgKeys = new ArrayList ();
2668 // fill the key lists
2670 if (rgKeyBlocks.Count > 0) {
2671 kbCurr = (KeyBlock) rgKeyBlocks [0];
2672 foreach (object key in rgKeys)
2674 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2675 System.Convert.ToInt64 (key) > kbCurr.nLast;
2677 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2678 kbCurr.rgKeys.Add (key);
2682 // sort the blocks so we can tackle the largest ones first
2683 rgKeyBlocks.Sort ();
2685 // okay now we can start...
2686 ILGenerator ig = ec.ig;
2687 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2688 Label lblDefault = ig.DefineLabel ();
2690 Type typeKeys = null;
2691 if (rgKeys.Length > 0)
2692 typeKeys = rgKeys [0].GetType (); // used for conversions
2696 if (TypeManager.IsEnumType (SwitchType))
2697 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2699 compare_type = SwitchType;
2701 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2703 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2704 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2707 foreach (object key in kb.rgKeys)
2709 ig.Emit (OpCodes.Ldloc, val);
2710 EmitObjectInteger (ig, key);
2711 SwitchLabel sl = (SwitchLabel) Elements [key];
2712 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2717 // TODO: if all the keys in the block are the same and there are
2718 // no gaps/defaults then just use a range-check.
2719 if (compare_type == TypeManager.int64_type ||
2720 compare_type == TypeManager.uint64_type)
2722 // TODO: optimize constant/I4 cases
2724 // check block range (could be > 2^31)
2725 ig.Emit (OpCodes.Ldloc, val);
2726 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2727 ig.Emit (OpCodes.Blt, lblDefault);
2728 ig.Emit (OpCodes.Ldloc, val);
2729 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2730 ig.Emit (OpCodes.Bgt, lblDefault);
2733 ig.Emit (OpCodes.Ldloc, val);
2736 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2737 ig.Emit (OpCodes.Sub);
2739 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2744 ig.Emit (OpCodes.Ldloc, val);
2745 int nFirst = (int) kb.nFirst;
2748 IntConstant.EmitInt (ig, nFirst);
2749 ig.Emit (OpCodes.Sub);
2751 else if (nFirst < 0)
2753 IntConstant.EmitInt (ig, -nFirst);
2754 ig.Emit (OpCodes.Add);
2758 // first, build the list of labels for the switch
2760 int cJumps = kb.Length;
2761 Label [] rgLabels = new Label [cJumps];
2762 for (int iJump = 0; iJump < cJumps; iJump++)
2764 object key = kb.rgKeys [iKey];
2765 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2767 SwitchLabel sl = (SwitchLabel) Elements [key];
2768 rgLabels [iJump] = sl.GetILLabel (ec);
2772 rgLabels [iJump] = lblDefault;
2774 // emit the switch opcode
2775 ig.Emit (OpCodes.Switch, rgLabels);
2778 // mark the default for this block
2780 ig.MarkLabel (lblDefault);
2783 // TODO: find the default case and emit it here,
2784 // to prevent having to do the following jump.
2785 // make sure to mark other labels in the default section
2787 // the last default just goes to the end
2788 ig.Emit (OpCodes.Br, lblDefault);
2790 // now emit the code for the sections
2791 bool fFoundDefault = false;
2792 foreach (SwitchSection ss in Sections)
2794 foreach (SwitchLabel sl in ss.Labels)
2796 ig.MarkLabel (sl.GetILLabel (ec));
2797 ig.MarkLabel (sl.GetILLabelCode (ec));
2798 if (sl.Label == null)
2800 ig.MarkLabel (lblDefault);
2801 fFoundDefault = true;
2805 //ig.Emit (OpCodes.Br, lblEnd);
2808 if (!fFoundDefault) {
2809 ig.MarkLabel (lblDefault);
2811 ig.MarkLabel (lblEnd);
2814 // This simple emit switch works, but does not take advantage of the
2816 // TODO: remove non-string logic from here
2817 // TODO: binary search strings?
2819 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2821 ILGenerator ig = ec.ig;
2822 Label end_of_switch = ig.DefineLabel ();
2823 Label next_test = ig.DefineLabel ();
2824 Label null_target = ig.DefineLabel ();
2825 bool default_found = false;
2826 bool first_test = true;
2827 bool pending_goto_end = false;
2829 bool default_at_end = false;
2831 ig.Emit (OpCodes.Ldloc, val);
2833 if (Elements.Contains (NullLiteral.Null)){
2834 ig.Emit (OpCodes.Brfalse, null_target);
2836 ig.Emit (OpCodes.Brfalse, default_target);
2838 ig.Emit (OpCodes.Ldloc, val);
2839 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2840 ig.Emit (OpCodes.Stloc, val);
2842 int section_count = Sections.Count;
2843 for (int section = 0; section < section_count; section++){
2844 SwitchSection ss = (SwitchSection) Sections [section];
2845 Label sec_begin = ig.DefineLabel ();
2847 if (pending_goto_end)
2848 ig.Emit (OpCodes.Br, end_of_switch);
2850 int label_count = ss.Labels.Count;
2851 bool mark_default = false;
2853 for (int label = 0; label < label_count; label++){
2854 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2855 ig.MarkLabel (sl.GetILLabel (ec));
2858 ig.MarkLabel (next_test);
2859 next_test = ig.DefineLabel ();
2862 // If we are the default target
2864 if (sl.Label == null){
2865 if (label+1 == label_count)
2866 default_at_end = true;
2867 mark_default = true;
2868 default_found = true;
2870 object lit = sl.Converted;
2872 if (lit is NullLiteral){
2874 if (label_count == 1)
2875 ig.Emit (OpCodes.Br, next_test);
2879 StringConstant str = (StringConstant) lit;
2881 ig.Emit (OpCodes.Ldloc, val);
2882 ig.Emit (OpCodes.Ldstr, str.Value);
2883 if (label_count == 1)
2884 ig.Emit (OpCodes.Bne_Un, next_test);
2886 if (label+1 == label_count)
2887 ig.Emit (OpCodes.Bne_Un, next_test);
2889 ig.Emit (OpCodes.Beq, sec_begin);
2894 ig.MarkLabel (null_target);
2895 ig.MarkLabel (sec_begin);
2896 foreach (SwitchLabel sl in ss.Labels)
2897 ig.MarkLabel (sl.GetILLabelCode (ec));
2900 ig.MarkLabel (default_target);
2902 pending_goto_end = !ss.Block.HasRet;
2905 ig.MarkLabel (next_test);
2907 if (!default_at_end)
2908 ig.Emit (OpCodes.Br, default_target);
2910 ig.MarkLabel (default_target);
2911 ig.MarkLabel (end_of_switch);
2914 SwitchSection FindSection (SwitchLabel label)
2916 foreach (SwitchSection ss in Sections){
2917 foreach (SwitchLabel sl in ss.Labels){
2926 bool ResolveConstantSwitch (EmitContext ec)
2928 object key = ((Constant) new_expr).GetValue ();
2929 SwitchLabel label = (SwitchLabel) Elements [key];
2934 constant_section = FindSection (label);
2935 if (constant_section == null)
2938 if (constant_section.Block.Resolve (ec) != true)
2944 public override bool Resolve (EmitContext ec)
2946 Expr = Expr.Resolve (ec);
2950 new_expr = SwitchGoverningType (ec, Expr.Type);
2951 if (new_expr == null){
2952 Report.Error (151, loc, "An integer type or string was expected for switch");
2957 SwitchType = new_expr.Type;
2959 if (!CheckSwitch (ec))
2962 Switch old_switch = ec.Switch;
2964 ec.Switch.SwitchType = SwitchType;
2966 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2967 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2969 is_constant = new_expr is Constant;
2971 object key = ((Constant) new_expr).GetValue ();
2972 SwitchLabel label = (SwitchLabel) Elements [key];
2974 constant_section = FindSection (label);
2978 foreach (SwitchSection ss in Sections){
2980 ec.CurrentBranching.CreateSibling (
2981 null, FlowBranching.SiblingType.SwitchSection);
2985 if (is_constant && (ss != constant_section)) {
2986 // If we're a constant switch, we're only emitting
2987 // one single section - mark all the others as
2989 ec.CurrentBranching.CurrentUsageVector.Goto ();
2990 if (!ss.Block.ResolveUnreachable (ec, true))
2993 if (!ss.Block.Resolve (ec))
2999 ec.CurrentBranching.CreateSibling (
3000 null, FlowBranching.SiblingType.SwitchSection);
3002 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3003 ec.Switch = old_switch;
3005 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3011 protected override void DoEmit (EmitContext ec)
3013 ILGenerator ig = ec.ig;
3015 // Store variable for comparission purposes
3018 value = ig.DeclareLocal (SwitchType);
3020 ig.Emit (OpCodes.Stloc, value);
3024 default_target = ig.DefineLabel ();
3027 // Setup the codegen context
3029 Label old_end = ec.LoopEnd;
3030 Switch old_switch = ec.Switch;
3032 ec.LoopEnd = ig.DefineLabel ();
3037 if (constant_section != null)
3038 constant_section.Block.Emit (ec);
3039 } else if (SwitchType == TypeManager.string_type)
3040 SimpleSwitchEmit (ec, value);
3042 TableSwitchEmit (ec, value);
3044 // Restore context state.
3045 ig.MarkLabel (ec.LoopEnd);
3048 // Restore the previous context
3050 ec.LoopEnd = old_end;
3051 ec.Switch = old_switch;
3055 public abstract class ExceptionStatement : Statement
3057 public abstract void EmitFinally (EmitContext ec);
3059 protected bool emit_finally = true;
3060 ArrayList parent_vectors;
3062 protected void DoEmitFinally (EmitContext ec)
3065 ec.ig.BeginFinallyBlock ();
3067 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3071 protected void ResolveFinally (FlowBranchingException branching)
3073 emit_finally = branching.EmitFinally;
3075 branching.Parent.StealFinallyClauses (ref parent_vectors);
3079 public class Lock : ExceptionStatement {
3081 Statement Statement;
3084 public Lock (Expression expr, Statement stmt, Location l)
3091 public override bool Resolve (EmitContext ec)
3093 expr = expr.Resolve (ec);
3097 if (expr.Type.IsValueType){
3098 Error (185, "lock statement requires the expression to be " +
3099 " a reference type (type is: `{0}'",
3100 TypeManager.CSharpName (expr.Type));
3104 FlowBranchingException branching = ec.StartFlowBranching (this);
3105 bool ok = Statement.Resolve (ec);
3107 ec.KillFlowBranching ();
3111 ResolveFinally (branching);
3113 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3114 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3115 // Unfortunately, System.Reflection.Emit automatically emits
3116 // a leave to the end of the finally block.
3117 // This is a problem if `returns' is true since we may jump
3118 // to a point after the end of the method.
3119 // As a workaround, emit an explicit ret here.
3120 ec.NeedReturnLabel ();
3126 protected override void DoEmit (EmitContext ec)
3128 Type type = expr.Type;
3130 ILGenerator ig = ec.ig;
3131 temp = ig.DeclareLocal (type);
3134 ig.Emit (OpCodes.Dup);
3135 ig.Emit (OpCodes.Stloc, temp);
3136 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3140 ig.BeginExceptionBlock ();
3141 Statement.Emit (ec);
3146 ig.EndExceptionBlock ();
3149 public override void EmitFinally (EmitContext ec)
3151 ILGenerator ig = ec.ig;
3152 ig.Emit (OpCodes.Ldloc, temp);
3153 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3157 public class Unchecked : Statement {
3158 public readonly Block Block;
3160 public Unchecked (Block b)
3166 public override bool Resolve (EmitContext ec)
3168 bool previous_state = ec.CheckState;
3169 bool previous_state_const = ec.ConstantCheckState;
3171 ec.CheckState = false;
3172 ec.ConstantCheckState = false;
3173 bool ret = Block.Resolve (ec);
3174 ec.CheckState = previous_state;
3175 ec.ConstantCheckState = previous_state_const;
3180 protected override void DoEmit (EmitContext ec)
3182 bool previous_state = ec.CheckState;
3183 bool previous_state_const = ec.ConstantCheckState;
3185 ec.CheckState = false;
3186 ec.ConstantCheckState = false;
3188 ec.CheckState = previous_state;
3189 ec.ConstantCheckState = previous_state_const;
3193 public class Checked : Statement {
3194 public readonly Block Block;
3196 public Checked (Block b)
3199 b.Unchecked = false;
3202 public override bool Resolve (EmitContext ec)
3204 bool previous_state = ec.CheckState;
3205 bool previous_state_const = ec.ConstantCheckState;
3207 ec.CheckState = true;
3208 ec.ConstantCheckState = true;
3209 bool ret = Block.Resolve (ec);
3210 ec.CheckState = previous_state;
3211 ec.ConstantCheckState = previous_state_const;
3216 protected override void DoEmit (EmitContext ec)
3218 bool previous_state = ec.CheckState;
3219 bool previous_state_const = ec.ConstantCheckState;
3221 ec.CheckState = true;
3222 ec.ConstantCheckState = true;
3224 ec.CheckState = previous_state;
3225 ec.ConstantCheckState = previous_state_const;
3229 public class Unsafe : Statement {
3230 public readonly Block Block;
3232 public Unsafe (Block b)
3235 Block.Unsafe = true;
3238 public override bool Resolve (EmitContext ec)
3240 bool previous_state = ec.InUnsafe;
3244 val = Block.Resolve (ec);
3245 ec.InUnsafe = previous_state;
3250 protected override void DoEmit (EmitContext ec)
3252 bool previous_state = ec.InUnsafe;
3256 ec.InUnsafe = previous_state;
3263 public class Fixed : Statement {
3265 ArrayList declarators;
3266 Statement statement;
3272 public bool is_object;
3273 public LocalInfo vi;
3274 public Expression expr;
3275 public Expression converted;
3278 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3281 declarators = decls;
3286 public override bool Resolve (EmitContext ec)
3289 Expression.UnsafeError (loc);
3293 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3297 expr_type = texpr.ResolveType (ec);
3299 CheckObsolete (expr_type);
3301 if (ec.RemapToProxy){
3302 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3306 data = new FixedData [declarators.Count];
3308 if (!expr_type.IsPointer){
3309 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3314 foreach (Pair p in declarators){
3315 LocalInfo vi = (LocalInfo) p.First;
3316 Expression e = (Expression) p.Second;
3318 vi.VariableInfo.SetAssigned (ec);
3322 // The rules for the possible declarators are pretty wise,
3323 // but the production on the grammar is more concise.
3325 // So we have to enforce these rules here.
3327 // We do not resolve before doing the case 1 test,
3328 // because the grammar is explicit in that the token &
3329 // is present, so we need to test for this particular case.
3333 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3338 // Case 1: & object.
3340 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3341 Expression child = ((Unary) e).Expr;
3343 if (child is ParameterReference || child is LocalVariableReference){
3346 "No need to use fixed statement for parameters or " +
3347 "local variable declarations (address is already " +
3352 ec.InFixedInitializer = true;
3354 ec.InFixedInitializer = false;
3358 child = ((Unary) e).Expr;
3360 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3363 data [i].is_object = true;
3365 data [i].converted = null;
3372 ec.InFixedInitializer = true;
3374 ec.InFixedInitializer = false;
3381 if (e.Type.IsArray){
3382 Type array_type = TypeManager.GetElementType (e.Type);
3385 // Provided that array_type is unmanaged,
3387 if (!TypeManager.VerifyUnManaged (array_type, loc))
3391 // and T* is implicitly convertible to the
3392 // pointer type given in the fixed statement.
3394 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3396 Expression converted = Convert.ImplicitConversionRequired (
3397 ec, array_ptr, vi.VariableType, loc);
3398 if (converted == null)
3401 data [i].is_object = false;
3403 data [i].converted = converted;
3413 if (e.Type == TypeManager.string_type){
3414 data [i].is_object = false;
3416 data [i].converted = null;
3423 // For other cases, flag a `this is already fixed expression'
3425 if (e is LocalVariableReference || e is ParameterReference ||
3426 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3428 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3432 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3436 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3438 if (!statement.Resolve (ec)) {
3439 ec.KillFlowBranching ();
3443 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3444 has_ret = reachability.IsUnreachable;
3449 protected override void DoEmit (EmitContext ec)
3451 ILGenerator ig = ec.ig;
3453 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3455 for (int i = 0; i < data.Length; i++) {
3456 LocalInfo vi = data [i].vi;
3459 // Case 1: & object.
3461 if (data [i].is_object) {
3463 // Store pointer in pinned location
3465 data [i].expr.Emit (ec);
3466 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3467 clear_list [i] = vi.LocalBuilder;
3474 if (data [i].expr.Type.IsArray){
3476 // Store pointer in pinned location
3478 data [i].converted.Emit (ec);
3480 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3481 clear_list [i] = vi.LocalBuilder;
3488 if (data [i].expr.Type == TypeManager.string_type){
3489 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3490 clear_list [i] = pinned_string;
3492 data [i].expr.Emit (ec);
3493 ig.Emit (OpCodes.Stloc, pinned_string);
3495 Expression sptr = new StringPtr (pinned_string, loc);
3496 Expression converted = Convert.ImplicitConversionRequired (
3497 ec, sptr, vi.VariableType, loc);
3499 if (converted == null)
3502 converted.Emit (ec);
3503 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3507 statement.Emit (ec);
3513 // Clear the pinned variable
3515 for (int i = 0; i < data.Length; i++) {
3516 if (data [i].is_object || data [i].expr.Type.IsArray) {
3517 ig.Emit (OpCodes.Ldc_I4_0);
3518 ig.Emit (OpCodes.Conv_U);
3519 ig.Emit (OpCodes.Stloc, clear_list [i]);
3520 } else if (data [i].expr.Type == TypeManager.string_type){
3521 ig.Emit (OpCodes.Ldnull);
3522 ig.Emit (OpCodes.Stloc, clear_list [i]);
3528 public class Catch: Statement {
3529 public readonly string Name;
3530 public readonly Block Block;
3532 Expression type_expr;
3535 public Catch (Expression type, string name, Block block, Location l)
3543 public Type CatchType {
3549 public bool IsGeneral {
3551 return type_expr == null;
3555 protected override void DoEmit(EmitContext ec)
3559 public override bool Resolve (EmitContext ec)
3561 if (type_expr != null) {
3562 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3566 type = te.ResolveType (ec);
3568 CheckObsolete (type);
3570 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3571 Error (155, "The type caught or thrown must be derived from System.Exception");
3577 return Block.Resolve (ec);
3581 public class Try : ExceptionStatement {
3582 public readonly Block Fini, Block;
3583 public readonly ArrayList Specific;
3584 public readonly Catch General;
3586 bool need_exc_block;
3589 // specific, general and fini might all be null.
3591 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3593 if (specific == null && general == null){
3594 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3598 this.Specific = specific;
3599 this.General = general;
3604 public override bool Resolve (EmitContext ec)
3608 FlowBranchingException branching = ec.StartFlowBranching (this);
3610 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3612 if (!Block.Resolve (ec))
3615 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3617 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3619 Type[] prevCatches = new Type [Specific.Count];
3621 foreach (Catch c in Specific){
3622 ec.CurrentBranching.CreateSibling (
3623 c.Block, FlowBranching.SiblingType.Catch);
3625 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3627 if (c.Name != null) {
3628 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3630 throw new Exception ();
3632 vi.VariableInfo = null;
3635 if (!c.Resolve (ec))
3638 Type resolvedType = c.CatchType;
3639 for (int ii = 0; ii < last_index; ++ii) {
3640 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3641 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3646 prevCatches [last_index++] = resolvedType;
3647 need_exc_block = true;
3650 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3652 if (General != null){
3653 ec.CurrentBranching.CreateSibling (
3654 General.Block, FlowBranching.SiblingType.Catch);
3656 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3658 if (!General.Resolve (ec))
3661 need_exc_block = true;
3664 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3668 ec.CurrentBranching.CreateSibling (
3669 Fini, FlowBranching.SiblingType.Finally);
3671 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3673 if (!Fini.Resolve (ec))
3677 ResolveFinally (branching);
3678 need_exc_block |= emit_finally;
3680 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3682 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3684 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3686 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3687 // Unfortunately, System.Reflection.Emit automatically emits
3688 // a leave to the end of the finally block. This is a problem
3689 // if `returns' is true since we may jump to a point after the
3690 // end of the method.
3691 // As a workaround, emit an explicit ret here.
3692 ec.NeedReturnLabel ();
3698 protected override void DoEmit (EmitContext ec)
3700 ILGenerator ig = ec.ig;
3703 ig.BeginExceptionBlock ();
3706 foreach (Catch c in Specific){
3709 ig.BeginCatchBlock (c.CatchType);
3711 if (c.Name != null){
3712 vi = c.Block.GetLocalInfo (c.Name);
3714 throw new Exception ("Variable does not exist in this block");
3716 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3718 ig.Emit (OpCodes.Pop);
3723 if (General != null){
3724 ig.BeginCatchBlock (TypeManager.object_type);
3725 ig.Emit (OpCodes.Pop);
3726 General.Block.Emit (ec);
3731 ig.EndExceptionBlock ();
3734 public override void EmitFinally (EmitContext ec)
3742 public class Using : ExceptionStatement {
3743 object expression_or_block;
3744 Statement Statement;
3749 Expression [] resolved_vars;
3750 Expression [] converted_vars;
3751 ExpressionStatement [] assign;
3752 LocalBuilder local_copy;
3754 public Using (object expression_or_block, Statement stmt, Location l)
3756 this.expression_or_block = expression_or_block;
3762 // Resolves for the case of using using a local variable declaration.
3764 bool ResolveLocalVariableDecls (EmitContext ec)
3768 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3772 expr_type = texpr.ResolveType (ec);
3775 // The type must be an IDisposable or an implicit conversion
3778 converted_vars = new Expression [var_list.Count];
3779 resolved_vars = new Expression [var_list.Count];
3780 assign = new ExpressionStatement [var_list.Count];
3782 bool need_conv = !TypeManager.ImplementsInterface (
3783 expr_type, TypeManager.idisposable_type);
3785 foreach (DictionaryEntry e in var_list){
3786 Expression var = (Expression) e.Key;
3788 var = var.ResolveLValue (ec, new EmptyExpression ());
3792 resolved_vars [i] = var;
3799 converted_vars [i] = Convert.ImplicitConversionRequired (
3800 ec, var, TypeManager.idisposable_type, loc);
3802 if (converted_vars [i] == null)
3809 foreach (DictionaryEntry e in var_list){
3810 Expression var = resolved_vars [i];
3811 Expression new_expr = (Expression) e.Value;
3814 a = new Assign (var, new_expr, loc);
3820 converted_vars [i] = var;
3821 assign [i] = (ExpressionStatement) a;
3828 bool ResolveExpression (EmitContext ec)
3830 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3831 conv = Convert.ImplicitConversionRequired (
3832 ec, expr, TypeManager.idisposable_type, loc);
3842 // Emits the code for the case of using using a local variable declaration.
3844 void EmitLocalVariableDecls (EmitContext ec)
3846 ILGenerator ig = ec.ig;
3849 for (i = 0; i < assign.Length; i++) {
3850 assign [i].EmitStatement (ec);
3853 ig.BeginExceptionBlock ();
3855 Statement.Emit (ec);
3857 var_list.Reverse ();
3862 void EmitLocalVariableDeclFinally (EmitContext ec)
3864 ILGenerator ig = ec.ig;
3866 int i = assign.Length;
3867 foreach (DictionaryEntry e in var_list){
3868 Expression var = resolved_vars [--i];
3869 Label skip = ig.DefineLabel ();
3871 ig.BeginFinallyBlock ();
3873 if (!var.Type.IsValueType) {
3875 ig.Emit (OpCodes.Brfalse, skip);
3876 converted_vars [i].Emit (ec);
3877 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3879 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3881 if (!(ml is MethodGroupExpr)) {
3883 ig.Emit (OpCodes.Box, var.Type);
3884 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3886 MethodInfo mi = null;
3888 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3889 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3896 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3900 IMemoryLocation mloc = (IMemoryLocation) var;
3902 mloc.AddressOf (ec, AddressOp.Load);
3903 ig.Emit (OpCodes.Call, mi);
3907 ig.MarkLabel (skip);
3910 ig.EndExceptionBlock ();
3912 ig.BeginFinallyBlock ();
3917 void EmitExpression (EmitContext ec)
3920 // Make a copy of the expression and operate on that.
3922 ILGenerator ig = ec.ig;
3923 local_copy = ig.DeclareLocal (expr_type);
3928 ig.Emit (OpCodes.Stloc, local_copy);
3931 ig.BeginExceptionBlock ();
3933 Statement.Emit (ec);
3937 ig.EndExceptionBlock ();
3940 void EmitExpressionFinally (EmitContext ec)
3942 ILGenerator ig = ec.ig;
3943 Label skip = ig.DefineLabel ();
3944 ig.Emit (OpCodes.Ldloc, local_copy);
3945 ig.Emit (OpCodes.Brfalse, skip);
3946 ig.Emit (OpCodes.Ldloc, local_copy);
3947 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3948 ig.MarkLabel (skip);
3951 public override bool Resolve (EmitContext ec)
3953 if (expression_or_block is DictionaryEntry){
3954 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3955 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3957 if (!ResolveLocalVariableDecls (ec))
3960 } else if (expression_or_block is Expression){
3961 expr = (Expression) expression_or_block;
3963 expr = expr.Resolve (ec);
3967 expr_type = expr.Type;
3969 if (!ResolveExpression (ec))
3973 FlowBranchingException branching = ec.StartFlowBranching (this);
3975 bool ok = Statement.Resolve (ec);
3978 ec.KillFlowBranching ();
3982 ResolveFinally (branching);
3983 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3985 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3986 // Unfortunately, System.Reflection.Emit automatically emits a leave
3987 // to the end of the finally block. This is a problem if `returns'
3988 // is true since we may jump to a point after the end of the method.
3989 // As a workaround, emit an explicit ret here.
3990 ec.NeedReturnLabel ();
3996 protected override void DoEmit (EmitContext ec)
3998 if (expression_or_block is DictionaryEntry)
3999 EmitLocalVariableDecls (ec);
4000 else if (expression_or_block is Expression)
4001 EmitExpression (ec);
4004 public override void EmitFinally (EmitContext ec)
4006 if (expression_or_block is DictionaryEntry)
4007 EmitLocalVariableDeclFinally (ec);
4008 else if (expression_or_block is Expression)
4009 EmitExpressionFinally (ec);
4014 /// Implementation of the foreach C# statement
4016 public class Foreach : ExceptionStatement {
4018 Expression variable;
4020 Statement statement;
4021 ForeachHelperMethods hm;
4022 Expression empty, conv;
4023 Type array_type, element_type;
4025 VariableStorage enumerator;
4027 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4028 Statement stmt, Location l)
4031 this.variable = var;
4037 public override bool Resolve (EmitContext ec)
4039 expr = expr.Resolve (ec);
4043 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4047 var_type = texpr.ResolveType (ec);
4050 // We need an instance variable. Not sure this is the best
4051 // way of doing this.
4053 // FIXME: When we implement propertyaccess, will those turn
4054 // out to return values in ExprClass? I think they should.
4056 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4057 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4058 error1579 (expr.Type);
4062 if (expr.Type.IsArray) {
4063 array_type = expr.Type;
4064 element_type = TypeManager.GetElementType (array_type);
4066 empty = new EmptyExpression (element_type);
4068 hm = ProbeCollectionType (ec, expr.Type);
4070 error1579 (expr.Type);
4074 array_type = expr.Type;
4075 element_type = hm.element_type;
4077 empty = new EmptyExpression (hm.element_type);
4082 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4083 ec.CurrentBranching.CreateSibling ();
4087 // FIXME: maybe we can apply the same trick we do in the
4088 // array handling to avoid creating empty and conv in some cases.
4090 // Although it is not as important in this case, as the type
4091 // will not likely be object (what the enumerator will return).
4093 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4097 variable = variable.ResolveLValue (ec, empty);
4098 if (variable == null)
4101 bool disposable = (hm != null) && hm.is_disposable;
4102 FlowBranchingException branching = null;
4104 branching = ec.StartFlowBranching (this);
4106 if (!statement.Resolve (ec))
4110 ResolveFinally (branching);
4111 ec.EndFlowBranching ();
4113 emit_finally = true;
4115 ec.EndFlowBranching ();
4121 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4123 static MethodInfo FetchMethodMoveNext (Type t)
4125 MemberList move_next_list;
4127 move_next_list = TypeContainer.FindMembers (
4128 t, MemberTypes.Method,
4129 BindingFlags.Public | BindingFlags.Instance,
4130 Type.FilterName, "MoveNext");
4131 if (move_next_list.Count == 0)
4134 foreach (MemberInfo m in move_next_list){
4135 MethodInfo mi = (MethodInfo) m;
4138 args = TypeManager.GetArgumentTypes (mi);
4139 if (args != null && args.Length == 0){
4140 if (mi.ReturnType == TypeManager.bool_type)
4148 // Retrieves a `public T get_Current ()' method from the Type `t'
4150 static MethodInfo FetchMethodGetCurrent (Type t)
4152 MemberList get_current_list;
4154 get_current_list = TypeContainer.FindMembers (
4155 t, MemberTypes.Method,
4156 BindingFlags.Public | BindingFlags.Instance,
4157 Type.FilterName, "get_Current");
4158 if (get_current_list.Count == 0)
4161 foreach (MemberInfo m in get_current_list){
4162 MethodInfo mi = (MethodInfo) m;
4165 args = TypeManager.GetArgumentTypes (mi);
4166 if (args != null && args.Length == 0)
4173 // Retrieves a `public void Dispose ()' method from the Type `t'
4175 static MethodInfo FetchMethodDispose (Type t)
4177 MemberList dispose_list;
4179 dispose_list = TypeContainer.FindMembers (
4180 t, MemberTypes.Method,
4181 BindingFlags.Public | BindingFlags.Instance,
4182 Type.FilterName, "Dispose");
4183 if (dispose_list.Count == 0)
4186 foreach (MemberInfo m in dispose_list){
4187 MethodInfo mi = (MethodInfo) m;
4190 args = TypeManager.GetArgumentTypes (mi);
4191 if (args != null && args.Length == 0){
4192 if (mi.ReturnType == TypeManager.void_type)
4200 // This struct records the helper methods used by the Foreach construct
4202 class ForeachHelperMethods {
4203 public EmitContext ec;
4204 public MethodInfo get_enumerator;
4205 public MethodInfo move_next;
4206 public MethodInfo get_current;
4207 public Type element_type;
4208 public Type enumerator_type;
4209 public bool is_disposable;
4211 public ForeachHelperMethods (EmitContext ec)
4214 this.element_type = TypeManager.object_type;
4215 this.enumerator_type = TypeManager.ienumerator_type;
4216 this.is_disposable = true;
4220 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4225 if (!(m is MethodInfo))
4228 if (m.Name != "GetEnumerator")
4231 MethodInfo mi = (MethodInfo) m;
4232 Type [] args = TypeManager.GetArgumentTypes (mi);
4234 if (args.Length != 0)
4237 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4238 EmitContext ec = hm.ec;
4240 // Check whether GetEnumerator is public
4241 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4244 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4246 // Apply the same optimization as MS: skip the GetEnumerator
4247 // returning an IEnumerator, and use the one returning a
4248 // CharEnumerator instead. This allows us to avoid the
4249 // try-finally block and the boxing.
4254 // Ok, we can access it, now make sure that we can do something
4255 // with this `GetEnumerator'
4258 Type return_type = mi.ReturnType;
4259 if (mi.ReturnType == TypeManager.ienumerator_type ||
4260 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4261 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4264 // If it is not an interface, lets try to find the methods ourselves.
4265 // For example, if we have:
4266 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4267 // We can avoid the iface call. This is a runtime perf boost.
4268 // even bigger if we have a ValueType, because we avoid the cost
4271 // We have to make sure that both methods exist for us to take
4272 // this path. If one of the methods does not exist, we will just
4273 // use the interface. Sadly, this complex if statement is the only
4274 // way I could do this without a goto
4277 if (return_type.IsInterface ||
4278 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4279 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4281 hm.move_next = TypeManager.bool_movenext_void;
4282 hm.get_current = TypeManager.object_getcurrent_void;
4289 // Ok, so they dont return an IEnumerable, we will have to
4290 // find if they support the GetEnumerator pattern.
4293 hm.move_next = FetchMethodMoveNext (return_type);
4294 if (hm.move_next == null)
4297 hm.get_current = FetchMethodGetCurrent (return_type);
4298 if (hm.get_current == null)
4302 hm.element_type = hm.get_current.ReturnType;
4303 hm.enumerator_type = return_type;
4304 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4305 TypeManager.ImplementsInterface (
4306 hm.enumerator_type, TypeManager.idisposable_type);
4312 /// This filter is used to find the GetEnumerator method
4313 /// on which IEnumerator operates
4315 static MemberFilter FilterEnumerator;
4319 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4322 void error1579 (Type t)
4324 Report.Error (1579, loc,
4325 "foreach statement cannot operate on variables of type `" +
4326 t.FullName + "' because that class does not provide a " +
4327 " GetEnumerator method or it is inaccessible");
4330 static bool TryType (Type t, ForeachHelperMethods hm)
4334 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4335 BindingFlags.Public | BindingFlags.NonPublic |
4336 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4337 FilterEnumerator, hm);
4342 hm.get_enumerator = (MethodInfo) mi [0];
4347 // Looks for a usable GetEnumerator in the Type, and if found returns
4348 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4350 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4352 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4354 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4355 if (TryType (tt, hm))
4361 // Now try to find the method in the interfaces
4364 Type [] ifaces = t.GetInterfaces ();
4366 foreach (Type i in ifaces){
4367 if (TryType (i, hm))
4372 // Since TypeBuilder.GetInterfaces only returns the interface
4373 // types for this type, we have to keep looping, but once
4374 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4375 // done, because it returns all the types
4377 if ((t is TypeBuilder))
4387 // FIXME: possible optimization.
4388 // We might be able to avoid creating `empty' if the type is the sam
4390 bool EmitCollectionForeach (EmitContext ec)
4392 ILGenerator ig = ec.ig;
4394 enumerator = new VariableStorage (ec, hm.enumerator_type);
4395 enumerator.EmitThis (ig);
4397 // Instantiate the enumerator
4399 if (expr.Type.IsValueType){
4400 IMemoryLocation ml = expr as IMemoryLocation;
4401 // Load the address of the value type.
4403 // This happens if, for example, you have a property
4404 // returning a struct which is IEnumerable
4405 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4407 ig.Emit (OpCodes.Stloc, t);
4408 ig.Emit (OpCodes.Ldloca, t);
4409 ec.FreeTemporaryLocal (t, expr.Type);
4411 ml.AddressOf (ec, AddressOp.Load);
4415 if (hm.get_enumerator.DeclaringType.IsValueType) {
4416 // the method is declared on the value type
4417 ig.Emit (OpCodes.Call, hm.get_enumerator);
4419 // it is an interface method, so we must box
4420 ig.Emit (OpCodes.Box, expr.Type);
4421 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4425 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4427 enumerator.EmitStore (ig);
4430 // Protect the code in a try/finalize block, so that
4431 // if the beast implement IDisposable, we get rid of it
4433 if (hm.is_disposable && emit_finally)
4434 ig.BeginExceptionBlock ();
4436 Label end_try = ig.DefineLabel ();
4438 ig.MarkLabel (ec.LoopBegin);
4440 enumerator.EmitCall (ig, hm.move_next);
4442 ig.Emit (OpCodes.Brfalse, end_try);
4445 enumerator.EmitThis (ig);
4446 enumerator.EmitCall (ig, hm.get_current);
4450 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4452 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4454 statement.Emit (ec);
4455 ig.Emit (OpCodes.Br, ec.LoopBegin);
4456 ig.MarkLabel (end_try);
4458 // The runtime provides this for us.
4459 // ig.Emit (OpCodes.Leave, end);
4462 // Now the finally block
4464 if (hm.is_disposable) {
4467 ig.EndExceptionBlock ();
4470 ig.MarkLabel (ec.LoopEnd);
4474 public override void EmitFinally (EmitContext ec)
4476 ILGenerator ig = ec.ig;
4478 if (hm.enumerator_type.IsValueType) {
4479 enumerator.EmitThis (ig);
4481 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4483 enumerator.EmitLoadAddress (ig);
4484 ig.Emit (OpCodes.Call, mi);
4486 enumerator.EmitLoad (ig);
4487 ig.Emit (OpCodes.Box, hm.enumerator_type);
4488 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4491 Label call_dispose = ig.DefineLabel ();
4493 enumerator.EmitThis (ig);
4494 enumerator.EmitLoad (ig);
4495 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4496 ig.Emit (OpCodes.Dup);
4497 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4498 ig.Emit (OpCodes.Pop);
4500 Label end_finally = ig.DefineLabel ();
4501 ig.Emit (OpCodes.Br, end_finally);
4503 ig.MarkLabel (call_dispose);
4504 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4505 ig.MarkLabel (end_finally);
4508 ig.Emit (OpCodes.Endfinally);
4513 // FIXME: possible optimization.
4514 // We might be able to avoid creating `empty' if the type is the sam
4516 bool EmitArrayForeach (EmitContext ec)
4518 int rank = array_type.GetArrayRank ();
4519 ILGenerator ig = ec.ig;
4521 VariableStorage copy = new VariableStorage (ec, array_type);
4524 // Make our copy of the array
4528 copy.EmitStore (ig);
4531 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4535 counter.EmitThis (ig);
4536 ig.Emit (OpCodes.Ldc_I4_0);
4537 counter.EmitStore (ig);
4538 test = ig.DefineLabel ();
4539 ig.Emit (OpCodes.Br, test);
4541 loop = ig.DefineLabel ();
4542 ig.MarkLabel (loop);
4549 counter.EmitThis (ig);
4550 counter.EmitLoad (ig);
4553 // Load the value, we load the value using the underlying type,
4554 // then we use the variable.EmitAssign to load using the proper cast.
4556 ArrayAccess.EmitLoadOpcode (ig, element_type);
4559 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4561 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4563 statement.Emit (ec);
4565 ig.MarkLabel (ec.LoopBegin);
4566 counter.EmitThis (ig);
4567 counter.EmitThis (ig);
4568 counter.EmitLoad (ig);
4569 ig.Emit (OpCodes.Ldc_I4_1);
4570 ig.Emit (OpCodes.Add);
4571 counter.EmitStore (ig);
4573 ig.MarkLabel (test);
4574 counter.EmitThis (ig);
4575 counter.EmitLoad (ig);
4578 ig.Emit (OpCodes.Ldlen);
4579 ig.Emit (OpCodes.Conv_I4);
4580 ig.Emit (OpCodes.Blt, loop);
4582 VariableStorage [] dim_len = new VariableStorage [rank];
4583 VariableStorage [] dim_count = new VariableStorage [rank];
4584 Label [] loop = new Label [rank];
4585 Label [] test = new Label [rank];
4588 for (dim = 0; dim < rank; dim++){
4589 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4590 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4591 test [dim] = ig.DefineLabel ();
4592 loop [dim] = ig.DefineLabel ();
4595 for (dim = 0; dim < rank; dim++){
4596 dim_len [dim].EmitThis (ig);
4599 IntLiteral.EmitInt (ig, dim);
4600 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4601 dim_len [dim].EmitStore (ig);
4605 for (dim = 0; dim < rank; dim++){
4606 dim_count [dim].EmitThis (ig);
4607 ig.Emit (OpCodes.Ldc_I4_0);
4608 dim_count [dim].EmitStore (ig);
4609 ig.Emit (OpCodes.Br, test [dim]);
4610 ig.MarkLabel (loop [dim]);
4617 for (dim = 0; dim < rank; dim++){
4618 dim_count [dim].EmitThis (ig);
4619 dim_count [dim].EmitLoad (ig);
4623 // FIXME: Maybe we can cache the computation of `get'?
4625 Type [] args = new Type [rank];
4628 for (int i = 0; i < rank; i++)
4629 args [i] = TypeManager.int32_type;
4631 ModuleBuilder mb = CodeGen.Module.Builder;
4632 get = mb.GetArrayMethod (
4634 CallingConventions.HasThis| CallingConventions.Standard,
4636 ig.Emit (OpCodes.Call, get);
4639 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4641 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4642 statement.Emit (ec);
4643 ig.MarkLabel (ec.LoopBegin);
4644 for (dim = rank - 1; dim >= 0; dim--){
4645 dim_count [dim].EmitThis (ig);
4646 dim_count [dim].EmitThis (ig);
4647 dim_count [dim].EmitLoad (ig);
4648 ig.Emit (OpCodes.Ldc_I4_1);
4649 ig.Emit (OpCodes.Add);
4650 dim_count [dim].EmitStore (ig);
4652 ig.MarkLabel (test [dim]);
4653 dim_count [dim].EmitThis (ig);
4654 dim_count [dim].EmitLoad (ig);
4655 dim_len [dim].EmitThis (ig);
4656 dim_len [dim].EmitLoad (ig);
4657 ig.Emit (OpCodes.Blt, loop [dim]);
4660 ig.MarkLabel (ec.LoopEnd);
4665 protected override void DoEmit (EmitContext ec)
4667 ILGenerator ig = ec.ig;
4669 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4670 ec.LoopBegin = ig.DefineLabel ();
4671 ec.LoopEnd = ig.DefineLabel ();
4674 EmitCollectionForeach (ec);
4676 EmitArrayForeach (ec);
4678 ec.LoopBegin = old_begin;
4679 ec.LoopEnd = old_end;