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;
990 public LocalInfo (Expression type, string name, Block block, Location l)
998 public LocalInfo (TypeContainer tc, Block block, Location l)
1000 VariableType = tc.TypeBuilder;
1005 public bool IsThisAssigned (EmitContext ec, Location loc)
1007 if (VariableInfo == null)
1008 throw new Exception ();
1010 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1013 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1016 public bool IsAssigned (EmitContext ec)
1018 if (VariableInfo == null)
1019 throw new Exception ();
1021 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1024 public bool Resolve (EmitContext ec)
1026 if (VariableType == null) {
1027 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1031 VariableType = texpr.ResolveType (ec);
1034 if (VariableType == TypeManager.void_type) {
1035 Report.Error (1547, Location,
1036 "Keyword 'void' cannot be used in this context");
1040 if (VariableType.IsAbstract && VariableType.IsSealed) {
1041 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1044 // TODO: breaks the build
1045 // if (VariableType.IsPointer && !ec.InUnsafe)
1046 // Expression.UnsafeError (Location);
1052 // Whether the variable is Fixed (because its Pinned or its a value type)
1054 public bool IsFixed {
1056 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1063 public bool IsCaptured {
1065 return (flags & Flags.Captured) != 0;
1069 flags |= Flags.Captured;
1073 public bool AddressTaken {
1075 return (flags & Flags.AddressTaken) != 0;
1079 flags |= Flags.AddressTaken;
1083 public override string ToString ()
1085 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1086 Name, Type, VariableInfo, Location);
1091 return (flags & Flags.Used) != 0;
1094 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1098 public bool ReadOnly {
1100 return (flags & Flags.ReadOnly) != 0;
1103 flags = value ? (flags | Flags.ReadOnly) : (unchecked (flags & ~Flags.ReadOnly));
1108 // Whether the variable is pinned, if Pinned the variable has been
1109 // allocated in a pinned slot with DeclareLocal.
1111 public bool Pinned {
1113 return (flags & Flags.Pinned) != 0;
1116 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1120 public bool IsThis {
1122 return (flags & Flags.IsThis) != 0;
1125 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1131 /// Block represents a C# block.
1135 /// This class is used in a number of places: either to represent
1136 /// explicit blocks that the programmer places or implicit blocks.
1138 /// Implicit blocks are used as labels or to introduce variable
1141 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1142 /// they contain extra information that is not necessary on normal blocks.
1144 public class Block : Statement {
1145 public Block Parent;
1146 public readonly Location StartLocation;
1147 public Location EndLocation = Location.Null;
1154 VariablesInitialized = 8,
1163 public bool Implicit {
1165 return (flags & Flags.Implicit) != 0;
1169 public bool Unchecked {
1171 return (flags & Flags.Unchecked) != 0;
1174 flags |= Flags.Unchecked;
1178 public bool Unsafe {
1180 return (flags & Flags.Unsafe) != 0;
1183 flags |= Flags.Unsafe;
1187 public bool HasVarargs {
1190 return Parent.HasVarargs;
1192 return (flags & Flags.HasVarargs) != 0;
1195 flags |= Flags.HasVarargs;
1200 // The statements in this block
1202 ArrayList statements;
1206 // An array of Blocks. We keep track of children just
1207 // to generate the local variable declarations.
1209 // Statements and child statements are handled through the
1215 // Labels. (label, block) pairs.
1220 // Keeps track of (name, type) pairs
1222 Hashtable variables;
1225 // Keeps track of constants
1226 Hashtable constants;
1229 // The parameters for the block, this is only needed on the toplevel block really
1230 // TODO: move `parameters' into ToplevelBlock
1231 Parameters parameters;
1234 // If this is a switch section, the enclosing switch block.
1238 protected static int id;
1242 public Block (Block parent)
1243 : this (parent, (Flags) 0, Location.Null, Location.Null)
1246 public Block (Block parent, Flags flags)
1247 : this (parent, flags, Location.Null, Location.Null)
1250 public Block (Block parent, Flags flags, Parameters parameters)
1251 : this (parent, flags, parameters, Location.Null, Location.Null)
1254 public Block (Block parent, Location start, Location end)
1255 : this (parent, (Flags) 0, start, end)
1258 public Block (Block parent, Parameters parameters, Location start, Location end)
1259 : this (parent, (Flags) 0, parameters, start, end)
1262 public Block (Block parent, Flags flags, Location start, Location end)
1263 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1266 public Block (Block parent, Flags flags, Parameters parameters,
1267 Location start, Location end)
1270 parent.AddChild (this);
1272 this.Parent = parent;
1274 this.parameters = parameters;
1275 this.StartLocation = start;
1276 this.EndLocation = end;
1279 statements = new ArrayList ();
1281 if (parent != null && Implicit) {
1282 if (parent.child_variable_names == null)
1283 parent.child_variable_names = new Hashtable();
1284 // share with parent
1285 child_variable_names = parent.child_variable_names;
1290 public Block CreateSwitchBlock (Location start)
1292 Block new_block = new Block (this, start, start);
1293 new_block.switch_block = this;
1303 void AddChild (Block b)
1305 if (children == null)
1306 children = new ArrayList ();
1311 public void SetEndLocation (Location loc)
1317 /// Adds a label to the current block.
1321 /// false if the name already exists in this block. true
1325 public bool AddLabel (string name, LabeledStatement target, Location loc)
1327 if (switch_block != null)
1328 return switch_block.AddLabel (name, target, loc);
1331 while (cur != null) {
1332 if (cur.DoLookupLabel (name) != null) {
1334 140, loc, "The label '{0}' is a duplicate",
1345 while (cur != null) {
1346 if (cur.DoLookupLabel (name) != null) {
1349 "The label '{0}' shadows another label " +
1350 "by the same name in a containing scope.",
1355 if (children != null) {
1356 foreach (Block b in children) {
1357 LabeledStatement s = b.DoLookupLabel (name);
1363 "The label '{0}' shadows another " +
1364 "label by the same name in a " +
1365 "containing scope.",
1376 labels = new Hashtable ();
1378 labels.Add (name, target);
1382 public LabeledStatement LookupLabel (string name)
1384 LabeledStatement s = DoLookupLabel (name);
1388 if (children == null)
1391 foreach (Block child in children) {
1392 if (!child.Implicit)
1395 s = child.LookupLabel (name);
1403 LabeledStatement DoLookupLabel (string name)
1405 if (switch_block != null)
1406 return switch_block.LookupLabel (name);
1409 if (labels.Contains (name))
1410 return ((LabeledStatement) labels [name]);
1415 LocalInfo this_variable = null;
1418 // Returns the "this" instance variable of this block.
1419 // See AddThisVariable() for more information.
1421 public LocalInfo ThisVariable {
1423 if (this_variable != null)
1424 return this_variable;
1425 else if (Parent != null)
1426 return Parent.ThisVariable;
1432 Hashtable child_variable_names;
1435 // Marks a variable with name @name as being used in a child block.
1436 // If a variable name has been used in a child block, it's illegal to
1437 // declare a variable with the same name in the current block.
1439 public void AddChildVariableName (string name)
1441 if (child_variable_names == null)
1442 child_variable_names = new Hashtable ();
1444 child_variable_names [name] = null;
1448 // Checks whether a variable name has already been used in a child block.
1450 public bool IsVariableNameUsedInChildBlock (string name)
1452 if (child_variable_names == null)
1455 return child_variable_names.Contains (name);
1459 // This is used by non-static `struct' constructors which do not have an
1460 // initializer - in this case, the constructor must initialize all of the
1461 // struct's fields. To do this, we add a "this" variable and use the flow
1462 // analysis code to ensure that it's been fully initialized before control
1463 // leaves the constructor.
1465 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1467 if (this_variable != null)
1468 return this_variable;
1470 if (variables == null)
1471 variables = new Hashtable ();
1473 this_variable = new LocalInfo (tc, this, l);
1474 this_variable.Used = true;
1475 this_variable.IsThis = true;
1477 variables.Add ("this", this_variable);
1479 return this_variable;
1482 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1484 if (variables == null)
1485 variables = new Hashtable ();
1487 LocalInfo vi = GetLocalInfo (name);
1489 if (vi.Block != this)
1490 Report.Error (136, l, "A local variable named `" + name + "' " +
1491 "cannot be declared in this scope since it would " +
1492 "give a different meaning to `" + name + "', which " +
1493 "is already used in a `parent or current' scope to " +
1494 "denote something else");
1496 Report.Error (128, l, "A local variable `" + name + "' is already " +
1497 "defined in this scope");
1501 if (IsVariableNameUsedInChildBlock (name)) {
1502 Report.Error (136, l, "A local variable named `" + name + "' " +
1503 "cannot be declared in this scope since it would " +
1504 "give a different meaning to `" + name + "', which " +
1505 "is already used in a `child' scope to denote something " +
1512 Parameter p = pars.GetParameterByName (name, out idx);
1514 Report.Error (136, l, "A local variable named `" + name + "' " +
1515 "cannot be declared in this scope since it would " +
1516 "give a different meaning to `" + name + "', which " +
1517 "is already used in a `parent or current' scope to " +
1518 "denote something else");
1523 vi = new LocalInfo (type, name, this, l);
1525 variables.Add (name, vi);
1527 // Mark 'name' as "used by a child block" in every surrounding block
1529 while (cur != null && cur.Implicit)
1532 for (Block par = cur.Parent; par != null; par = par.Parent)
1533 par.AddChildVariableName (name);
1535 if ((flags & Flags.VariablesInitialized) != 0)
1536 throw new Exception ();
1538 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1542 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1544 if (AddVariable (type, name, pars, l) == null)
1547 if (constants == null)
1548 constants = new Hashtable ();
1550 constants.Add (name, value);
1554 public Hashtable Variables {
1560 public LocalInfo GetLocalInfo (string name)
1562 for (Block b = this; b != null; b = b.Parent) {
1563 if (b.variables != null) {
1564 LocalInfo ret = b.variables [name] as LocalInfo;
1572 public Expression GetVariableType (string name)
1574 LocalInfo vi = GetLocalInfo (name);
1582 public Expression GetConstantExpression (string name)
1584 for (Block b = this; b != null; b = b.Parent) {
1585 if (b.constants != null) {
1586 Expression ret = b.constants [name] as Expression;
1595 /// True if the variable named @name is a constant
1597 public bool IsConstant (string name)
1599 Expression e = null;
1601 e = GetConstantExpression (name);
1607 // Returns a `ParameterReference' for the given name, or null if there
1608 // is no such parameter
1610 public ParameterReference GetParameterReference (string name, Location loc)
1615 Parameters pars = b.parameters;
1621 par = pars.GetParameterByName (name, out idx);
1623 ParameterReference pr;
1625 pr = new ParameterReference (pars, this, idx, name, loc);
1630 } while (b != null);
1635 // Whether the parameter named `name' is local to this block,
1636 // or false, if the parameter belongs to an encompassing block.
1638 public bool IsLocalParameter (string name)
1641 int toplevel_count = 0;
1644 if (this is ToplevelBlock)
1647 Parameters pars = b.parameters;
1649 if (pars.GetParameterByName (name) != null)
1653 if (toplevel_count > 0)
1656 } while (b != null);
1661 // Whether the `name' is a parameter reference
1663 public bool IsParameterReference (string name)
1668 Parameters pars = b.parameters;
1671 if (pars.GetParameterByName (name) != null)
1674 } while (b != null);
1679 /// A list of labels that were not used within this block
1681 public string [] GetUnreferenced ()
1683 // FIXME: Implement me
1687 public void AddStatement (Statement s)
1690 flags |= Flags.BlockUsed;
1695 return (flags & Flags.BlockUsed) != 0;
1701 flags |= Flags.BlockUsed;
1704 public bool HasRet {
1706 return (flags & Flags.HasRet) != 0;
1710 public bool IsDestructor {
1712 return (flags & Flags.IsDestructor) != 0;
1716 public void SetDestructor ()
1718 flags |= Flags.IsDestructor;
1721 VariableMap param_map, local_map;
1723 public VariableMap ParameterMap {
1725 if ((flags & Flags.VariablesInitialized) == 0)
1726 throw new Exception ("Variables have not been initialized yet");
1732 public VariableMap LocalMap {
1734 if ((flags & Flags.VariablesInitialized) == 0)
1735 throw new Exception ("Variables have not been initialized yet");
1742 /// Emits the variable declarations and labels.
1745 /// tc: is our typecontainer (to resolve type references)
1746 /// ig: is the code generator:
1748 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1750 ILGenerator ig = ec.ig;
1752 bool old_unsafe = ec.InUnsafe;
1754 // If some parent block was unsafe, we remain unsafe even if this block
1755 // isn't explicitly marked as such.
1756 ec.InUnsafe |= Unsafe;
1759 // Compute the VariableMap's.
1761 // Unfortunately, we don't know the type when adding variables with
1762 // AddVariable(), so we need to compute this info here.
1766 if (variables != null) {
1767 foreach (LocalInfo li in variables.Values)
1770 locals = new LocalInfo [variables.Count];
1771 variables.Values.CopyTo (locals, 0);
1773 locals = new LocalInfo [0];
1776 local_map = new VariableMap (Parent.LocalMap, locals);
1778 local_map = new VariableMap (locals);
1780 param_map = new VariableMap (ip);
1781 flags |= Flags.VariablesInitialized;
1783 bool old_check_state = ec.ConstantCheckState;
1784 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1787 // Process this block variables
1789 if (variables != null){
1790 foreach (DictionaryEntry de in variables){
1791 string name = (string) de.Key;
1792 LocalInfo vi = (LocalInfo) de.Value;
1794 if (vi.VariableType == null)
1797 Type variable_type = vi.VariableType;
1799 if (variable_type.IsPointer){
1801 // Am not really convinced that this test is required (Microsoft does it)
1802 // but the fact is that you would not be able to use the pointer variable
1805 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1812 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1815 // This is needed to compile on both .NET 1.x and .NET 2.x
1816 // the later introduced `DeclareLocal (Type t, bool pinned)'
1818 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1819 else if (!vi.IsThis)
1820 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1823 if (constants == null)
1826 Expression cv = (Expression) constants [name];
1830 ec.CurrentBlock = this;
1831 Expression e = cv.Resolve (ec);
1835 Constant ce = e as Constant;
1837 Report.Error (133, vi.Location,
1838 "The expression being assigned to `" +
1839 name + "' must be constant (" + e + ")");
1843 if (e.Type != variable_type){
1844 e = Const.ChangeType (vi.Location, ce, variable_type);
1849 constants.Remove (name);
1850 constants.Add (name, e);
1853 ec.ConstantCheckState = old_check_state;
1856 // Now, handle the children
1858 if (children != null){
1859 foreach (Block b in children)
1860 b.ResolveMeta (toplevel, ec, ip);
1862 ec.InUnsafe = old_unsafe;
1866 // Emits the local variable declarations for a block
1868 public void EmitMeta (EmitContext ec)
1870 ILGenerator ig = ec.ig;
1872 if (variables != null){
1873 bool have_captured_vars = ec.HaveCapturedVariables ();
1874 bool remap_locals = ec.RemapToProxy;
1876 foreach (DictionaryEntry de in variables){
1877 LocalInfo vi = (LocalInfo) de.Value;
1879 if (have_captured_vars && ec.IsCaptured (vi))
1883 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1887 // This is needed to compile on both .NET 1.x and .NET 2.x
1888 // the later introduced `DeclareLocal (Type t, bool pinned)'
1890 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1891 else if (!vi.IsThis)
1892 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1897 if (children != null){
1898 foreach (Block b in children)
1903 void UsageWarning (FlowBranching.UsageVector vector)
1907 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1908 foreach (DictionaryEntry de in variables){
1909 LocalInfo vi = (LocalInfo) de.Value;
1914 name = (string) de.Key;
1916 if (vector.IsAssigned (vi.VariableInfo)){
1917 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1919 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1925 bool unreachable_shown;
1927 public override bool Resolve (EmitContext ec)
1929 Block prev_block = ec.CurrentBlock;
1932 int errors = Report.Errors;
1934 ec.CurrentBlock = this;
1935 ec.StartFlowBranching (this);
1937 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1939 bool unreachable = false;
1941 int statement_count = statements.Count;
1942 for (int ix = 0; ix < statement_count; ix++){
1943 Statement s = (Statement) statements [ix];
1945 if (unreachable && !(s is LabeledStatement)) {
1946 if (s == EmptyStatement.Value)
1947 s.loc = EndLocation;
1949 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1952 if (s != EmptyStatement.Value)
1953 unreachable_shown = true;
1955 s.loc = Location.Null;
1957 statements [ix] = EmptyStatement.Value;
1961 if (s.Resolve (ec) == false) {
1963 statements [ix] = EmptyStatement.Value;
1967 num_statements = ix + 1;
1969 if (s is LabeledStatement)
1970 unreachable = false;
1972 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1975 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1976 ec.CurrentBranching, statement_count, num_statements);
1979 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1981 ec.CurrentBlock = prev_block;
1983 // If we're a non-static `struct' constructor which doesn't have an
1984 // initializer, then we must initialize all of the struct's fields.
1985 if ((this_variable != null) &&
1986 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1987 !this_variable.IsThisAssigned (ec, loc))
1990 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1991 foreach (LabeledStatement label in labels.Values)
1992 if (!label.HasBeenReferenced)
1993 Report.Warning (164, label.Location,
1994 "This label has not been referenced");
1997 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1999 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2000 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2001 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2002 flags |= Flags.HasRet;
2004 if (ok && (errors == Report.Errors)) {
2005 if (RootContext.WarningLevel >= 3)
2006 UsageWarning (vector);
2012 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2014 unreachable_shown = true;
2015 return base.ResolveUnreachable (ec, warn);
2018 protected override void DoEmit (EmitContext ec)
2020 for (int ix = 0; ix < num_statements; ix++){
2021 Statement s = (Statement) statements [ix];
2023 // Check whether we are the last statement in a
2026 if ((Parent == null) && (ix+1 == num_statements))
2027 ec.IsLastStatement = true;
2029 ec.IsLastStatement = false;
2035 public override void Emit (EmitContext ec)
2037 Block prev_block = ec.CurrentBlock;
2039 ec.CurrentBlock = this;
2041 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2042 bool is_lexical_block = !Implicit && (Parent != null);
2044 if (emit_debug_info) {
2045 if (is_lexical_block)
2046 ec.ig.BeginScope ();
2048 if (variables != null) {
2049 foreach (DictionaryEntry de in variables) {
2050 string name = (string) de.Key;
2051 LocalInfo vi = (LocalInfo) de.Value;
2053 if (vi.LocalBuilder == null)
2056 ec.DefineLocalVariable (name, vi.LocalBuilder);
2061 ec.Mark (StartLocation, true);
2063 ec.Mark (EndLocation, true);
2065 if (emit_debug_info && is_lexical_block)
2068 ec.CurrentBlock = prev_block;
2071 public ToplevelBlock Toplevel {
2074 while (b.Parent != null){
2075 if ((b.flags & Flags.IsToplevel) != 0)
2080 return (ToplevelBlock) b;
2085 // Returns true if we ar ea child of `b'.
2087 public bool IsChildOf (Block b)
2089 Block current = this;
2092 if (current.Parent == b)
2094 current = current.Parent;
2095 } while (current != null);
2101 // A toplevel block contains extra information, the split is done
2102 // only to separate information that would otherwise bloat the more
2103 // lightweight Block.
2105 // In particular, this was introduced when the support for Anonymous
2106 // Methods was implemented.
2108 public class ToplevelBlock : Block {
2110 // Pointer to the host of this anonymous method, or null
2111 // if we are the topmost block
2113 public ToplevelBlock Container;
2114 CaptureContext capture_context;
2116 Hashtable capture_contexts;
2123 public void RegisterCaptureContext (CaptureContext cc)
2125 if (capture_contexts == null)
2126 capture_contexts = new Hashtable ();
2127 capture_contexts [cc] = cc;
2130 public void CompleteContexts ()
2132 if (capture_contexts == null)
2135 foreach (CaptureContext cc in capture_contexts.Keys){
2140 public CaptureContext ToplevelBlockCaptureContext {
2142 return capture_context;
2147 // Parent is only used by anonymous blocks to link back to their
2150 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2151 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2153 Container = container;
2156 public ToplevelBlock (Parameters parameters, Location start) :
2157 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2161 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2162 base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2166 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2170 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2172 if (capture_context == null)
2173 capture_context = new CaptureContext (this, loc, host);
2176 public CaptureContext CaptureContext {
2178 return capture_context;
2183 public class SwitchLabel {
2186 public Location loc;
2190 Label il_label_code;
2191 bool il_label_code_set;
2194 // if expr == null, then it is the default case.
2196 public SwitchLabel (Expression expr, Location l)
2202 public Expression Label {
2208 public object Converted {
2214 public Label GetILLabel (EmitContext ec)
2217 il_label = ec.ig.DefineLabel ();
2218 il_label_set = true;
2223 public Label GetILLabelCode (EmitContext ec)
2225 if (!il_label_code_set){
2226 il_label_code = ec.ig.DefineLabel ();
2227 il_label_code_set = true;
2229 return il_label_code;
2233 // Resolves the expression, reduces it to a literal if possible
2234 // and then converts it to the requested type.
2236 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2241 Expression e = label.Resolve (ec);
2246 if (!(e is Constant)){
2247 Report.Error (150, loc, "A constant value is expected, got: " + e);
2251 if (e is StringConstant || e is NullLiteral){
2252 if (required_type == TypeManager.string_type){
2258 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2259 if (converted == null)
2266 public class SwitchSection {
2267 // An array of SwitchLabels.
2268 public readonly ArrayList Labels;
2269 public readonly Block Block;
2271 public SwitchSection (ArrayList labels, Block block)
2278 public class Switch : Statement {
2279 public readonly ArrayList Sections;
2280 public Expression Expr;
2283 /// Maps constants whose type type SwitchType to their SwitchLabels.
2285 public Hashtable Elements;
2288 /// The governing switch type
2290 public Type SwitchType;
2296 Label default_target;
2297 Expression new_expr;
2299 SwitchSection constant_section;
2302 // The types allowed to be implicitly cast from
2303 // on the governing type
2305 static Type [] allowed_types;
2307 public Switch (Expression e, ArrayList sects, Location l)
2314 public bool GotDefault {
2320 public Label DefaultTarget {
2322 return default_target;
2327 // Determines the governing type for a switch. The returned
2328 // expression might be the expression from the switch, or an
2329 // expression that includes any potential conversions to the
2330 // integral types or to string.
2332 Expression SwitchGoverningType (EmitContext ec, Type t)
2334 if (t == TypeManager.int32_type ||
2335 t == TypeManager.uint32_type ||
2336 t == TypeManager.char_type ||
2337 t == TypeManager.byte_type ||
2338 t == TypeManager.sbyte_type ||
2339 t == TypeManager.ushort_type ||
2340 t == TypeManager.short_type ||
2341 t == TypeManager.uint64_type ||
2342 t == TypeManager.int64_type ||
2343 t == TypeManager.string_type ||
2344 t == TypeManager.bool_type ||
2345 t.IsSubclassOf (TypeManager.enum_type))
2348 if (allowed_types == null){
2349 allowed_types = new Type [] {
2350 TypeManager.sbyte_type,
2351 TypeManager.byte_type,
2352 TypeManager.short_type,
2353 TypeManager.ushort_type,
2354 TypeManager.int32_type,
2355 TypeManager.uint32_type,
2356 TypeManager.int64_type,
2357 TypeManager.uint64_type,
2358 TypeManager.char_type,
2359 TypeManager.bool_type,
2360 TypeManager.string_type
2365 // Try to find a *user* defined implicit conversion.
2367 // If there is no implicit conversion, or if there are multiple
2368 // conversions, we have to report an error
2370 Expression converted = null;
2371 foreach (Type tt in allowed_types){
2374 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2378 if (converted != null){
2379 Report.Error (-12, loc, "More than one conversion to an integral " +
2380 " type exists for type `" +
2381 TypeManager.CSharpName (Expr.Type)+"'");
2389 static string Error152 {
2391 return "The label '{0}:' already occurs in this switch statement";
2396 // Performs the basic sanity checks on the switch statement
2397 // (looks for duplicate keys and non-constant expressions).
2399 // It also returns a hashtable with the keys that we will later
2400 // use to compute the switch tables
2402 bool CheckSwitch (EmitContext ec)
2406 Elements = new Hashtable ();
2408 got_default = false;
2410 if (TypeManager.IsEnumType (SwitchType)){
2411 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2413 compare_type = SwitchType;
2415 foreach (SwitchSection ss in Sections){
2416 foreach (SwitchLabel sl in ss.Labels){
2417 if (!sl.ResolveAndReduce (ec, SwitchType)){
2422 if (sl.Label == null){
2424 Report.Error (152, sl.loc, Error152, "default");
2431 object key = sl.Converted;
2433 if (key is Constant)
2434 key = ((Constant) key).GetValue ();
2437 key = NullLiteral.Null;
2439 string lname = null;
2440 if (compare_type == TypeManager.uint64_type){
2441 ulong v = (ulong) key;
2443 if (Elements.Contains (v))
2444 lname = v.ToString ();
2446 Elements.Add (v, sl);
2447 } else if (compare_type == TypeManager.int64_type){
2448 long v = (long) key;
2450 if (Elements.Contains (v))
2451 lname = v.ToString ();
2453 Elements.Add (v, sl);
2454 } else if (compare_type == TypeManager.uint32_type){
2455 uint v = (uint) key;
2457 if (Elements.Contains (v))
2458 lname = v.ToString ();
2460 Elements.Add (v, sl);
2461 } else if (compare_type == TypeManager.char_type){
2462 char v = (char) key;
2464 if (Elements.Contains (v))
2465 lname = v.ToString ();
2467 Elements.Add (v, sl);
2468 } else if (compare_type == TypeManager.byte_type){
2469 byte v = (byte) key;
2471 if (Elements.Contains (v))
2472 lname = v.ToString ();
2474 Elements.Add (v, sl);
2475 } else if (compare_type == TypeManager.sbyte_type){
2476 sbyte v = (sbyte) key;
2478 if (Elements.Contains (v))
2479 lname = v.ToString ();
2481 Elements.Add (v, sl);
2482 } else if (compare_type == TypeManager.short_type){
2483 short v = (short) key;
2485 if (Elements.Contains (v))
2486 lname = v.ToString ();
2488 Elements.Add (v, sl);
2489 } else if (compare_type == TypeManager.ushort_type){
2490 ushort v = (ushort) key;
2492 if (Elements.Contains (v))
2493 lname = v.ToString ();
2495 Elements.Add (v, sl);
2496 } else if (compare_type == TypeManager.string_type){
2497 if (key is NullLiteral){
2498 if (Elements.Contains (NullLiteral.Null))
2501 Elements.Add (NullLiteral.Null, null);
2503 string s = (string) key;
2505 if (Elements.Contains (s))
2508 Elements.Add (s, sl);
2510 } else if (compare_type == TypeManager.int32_type) {
2513 if (Elements.Contains (v))
2514 lname = v.ToString ();
2516 Elements.Add (v, sl);
2517 } else if (compare_type == TypeManager.bool_type) {
2518 bool v = (bool) key;
2520 if (Elements.Contains (v))
2521 lname = v.ToString ();
2523 Elements.Add (v, sl);
2527 throw new Exception ("Unknown switch type!" +
2528 SwitchType + " " + compare_type);
2531 if (lname != null) {
2532 Report.Error (152, sl.loc, Error152, "case " + lname);
2543 void EmitObjectInteger (ILGenerator ig, object k)
2546 IntConstant.EmitInt (ig, (int) k);
2547 else if (k is Constant) {
2548 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2551 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2554 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2556 IntConstant.EmitInt (ig, (int) (long) k);
2557 ig.Emit (OpCodes.Conv_I8);
2560 LongConstant.EmitLong (ig, (long) k);
2562 else if (k is ulong)
2564 if ((ulong) k < (1L<<32))
2566 IntConstant.EmitInt (ig, (int) (long) k);
2567 ig.Emit (OpCodes.Conv_U8);
2571 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2575 IntConstant.EmitInt (ig, (int) ((char) k));
2576 else if (k is sbyte)
2577 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2579 IntConstant.EmitInt (ig, (int) ((byte) k));
2580 else if (k is short)
2581 IntConstant.EmitInt (ig, (int) ((short) k));
2582 else if (k is ushort)
2583 IntConstant.EmitInt (ig, (int) ((ushort) k));
2585 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2587 throw new Exception ("Unhandled case");
2590 // structure used to hold blocks of keys while calculating table switch
2591 class KeyBlock : IComparable
2593 public KeyBlock (long _nFirst)
2595 nFirst = nLast = _nFirst;
2599 public ArrayList rgKeys = null;
2600 // how many items are in the bucket
2601 public int Size = 1;
2604 get { return (int) (nLast - nFirst + 1); }
2606 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2608 return kbLast.nLast - kbFirst.nFirst + 1;
2610 public int CompareTo (object obj)
2612 KeyBlock kb = (KeyBlock) obj;
2613 int nLength = Length;
2614 int nLengthOther = kb.Length;
2615 if (nLengthOther == nLength)
2616 return (int) (kb.nFirst - nFirst);
2617 return nLength - nLengthOther;
2622 /// This method emits code for a lookup-based switch statement (non-string)
2623 /// Basically it groups the cases into blocks that are at least half full,
2624 /// and then spits out individual lookup opcodes for each block.
2625 /// It emits the longest blocks first, and short blocks are just
2626 /// handled with direct compares.
2628 /// <param name="ec"></param>
2629 /// <param name="val"></param>
2630 /// <returns></returns>
2631 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2633 int cElements = Elements.Count;
2634 object [] rgKeys = new object [cElements];
2635 Elements.Keys.CopyTo (rgKeys, 0);
2636 Array.Sort (rgKeys);
2638 // initialize the block list with one element per key
2639 ArrayList rgKeyBlocks = new ArrayList ();
2640 foreach (object key in rgKeys)
2641 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2644 // iteratively merge the blocks while they are at least half full
2645 // there's probably a really cool way to do this with a tree...
2646 while (rgKeyBlocks.Count > 1)
2648 ArrayList rgKeyBlocksNew = new ArrayList ();
2649 kbCurr = (KeyBlock) rgKeyBlocks [0];
2650 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2652 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2653 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2656 kbCurr.nLast = kb.nLast;
2657 kbCurr.Size += kb.Size;
2661 // start a new block
2662 rgKeyBlocksNew.Add (kbCurr);
2666 rgKeyBlocksNew.Add (kbCurr);
2667 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2669 rgKeyBlocks = rgKeyBlocksNew;
2672 // initialize the key lists
2673 foreach (KeyBlock kb in rgKeyBlocks)
2674 kb.rgKeys = new ArrayList ();
2676 // fill the key lists
2678 if (rgKeyBlocks.Count > 0) {
2679 kbCurr = (KeyBlock) rgKeyBlocks [0];
2680 foreach (object key in rgKeys)
2682 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2683 System.Convert.ToInt64 (key) > kbCurr.nLast;
2685 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2686 kbCurr.rgKeys.Add (key);
2690 // sort the blocks so we can tackle the largest ones first
2691 rgKeyBlocks.Sort ();
2693 // okay now we can start...
2694 ILGenerator ig = ec.ig;
2695 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2696 Label lblDefault = ig.DefineLabel ();
2698 Type typeKeys = null;
2699 if (rgKeys.Length > 0)
2700 typeKeys = rgKeys [0].GetType (); // used for conversions
2704 if (TypeManager.IsEnumType (SwitchType))
2705 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2707 compare_type = SwitchType;
2709 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2711 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2712 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2715 foreach (object key in kb.rgKeys)
2717 ig.Emit (OpCodes.Ldloc, val);
2718 EmitObjectInteger (ig, key);
2719 SwitchLabel sl = (SwitchLabel) Elements [key];
2720 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2725 // TODO: if all the keys in the block are the same and there are
2726 // no gaps/defaults then just use a range-check.
2727 if (compare_type == TypeManager.int64_type ||
2728 compare_type == TypeManager.uint64_type)
2730 // TODO: optimize constant/I4 cases
2732 // check block range (could be > 2^31)
2733 ig.Emit (OpCodes.Ldloc, val);
2734 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2735 ig.Emit (OpCodes.Blt, lblDefault);
2736 ig.Emit (OpCodes.Ldloc, val);
2737 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2738 ig.Emit (OpCodes.Bgt, lblDefault);
2741 ig.Emit (OpCodes.Ldloc, val);
2744 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2745 ig.Emit (OpCodes.Sub);
2747 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2752 ig.Emit (OpCodes.Ldloc, val);
2753 int nFirst = (int) kb.nFirst;
2756 IntConstant.EmitInt (ig, nFirst);
2757 ig.Emit (OpCodes.Sub);
2759 else if (nFirst < 0)
2761 IntConstant.EmitInt (ig, -nFirst);
2762 ig.Emit (OpCodes.Add);
2766 // first, build the list of labels for the switch
2768 int cJumps = kb.Length;
2769 Label [] rgLabels = new Label [cJumps];
2770 for (int iJump = 0; iJump < cJumps; iJump++)
2772 object key = kb.rgKeys [iKey];
2773 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2775 SwitchLabel sl = (SwitchLabel) Elements [key];
2776 rgLabels [iJump] = sl.GetILLabel (ec);
2780 rgLabels [iJump] = lblDefault;
2782 // emit the switch opcode
2783 ig.Emit (OpCodes.Switch, rgLabels);
2786 // mark the default for this block
2788 ig.MarkLabel (lblDefault);
2791 // TODO: find the default case and emit it here,
2792 // to prevent having to do the following jump.
2793 // make sure to mark other labels in the default section
2795 // the last default just goes to the end
2796 ig.Emit (OpCodes.Br, lblDefault);
2798 // now emit the code for the sections
2799 bool fFoundDefault = false;
2800 foreach (SwitchSection ss in Sections)
2802 foreach (SwitchLabel sl in ss.Labels)
2804 ig.MarkLabel (sl.GetILLabel (ec));
2805 ig.MarkLabel (sl.GetILLabelCode (ec));
2806 if (sl.Label == null)
2808 ig.MarkLabel (lblDefault);
2809 fFoundDefault = true;
2813 //ig.Emit (OpCodes.Br, lblEnd);
2816 if (!fFoundDefault) {
2817 ig.MarkLabel (lblDefault);
2819 ig.MarkLabel (lblEnd);
2822 // This simple emit switch works, but does not take advantage of the
2824 // TODO: remove non-string logic from here
2825 // TODO: binary search strings?
2827 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2829 ILGenerator ig = ec.ig;
2830 Label end_of_switch = ig.DefineLabel ();
2831 Label next_test = ig.DefineLabel ();
2832 Label null_target = ig.DefineLabel ();
2833 bool default_found = false;
2834 bool first_test = true;
2835 bool pending_goto_end = false;
2837 bool default_at_end = false;
2839 ig.Emit (OpCodes.Ldloc, val);
2841 if (Elements.Contains (NullLiteral.Null)){
2842 ig.Emit (OpCodes.Brfalse, null_target);
2844 ig.Emit (OpCodes.Brfalse, default_target);
2846 ig.Emit (OpCodes.Ldloc, val);
2847 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2848 ig.Emit (OpCodes.Stloc, val);
2850 int section_count = Sections.Count;
2851 for (int section = 0; section < section_count; section++){
2852 SwitchSection ss = (SwitchSection) Sections [section];
2853 Label sec_begin = ig.DefineLabel ();
2855 if (pending_goto_end)
2856 ig.Emit (OpCodes.Br, end_of_switch);
2858 int label_count = ss.Labels.Count;
2859 bool mark_default = false;
2861 for (int label = 0; label < label_count; label++){
2862 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2863 ig.MarkLabel (sl.GetILLabel (ec));
2866 ig.MarkLabel (next_test);
2867 next_test = ig.DefineLabel ();
2870 // If we are the default target
2872 if (sl.Label == null){
2873 if (label+1 == label_count)
2874 default_at_end = true;
2875 mark_default = true;
2876 default_found = true;
2878 object lit = sl.Converted;
2880 if (lit is NullLiteral){
2882 if (label_count == 1)
2883 ig.Emit (OpCodes.Br, next_test);
2887 StringConstant str = (StringConstant) lit;
2889 ig.Emit (OpCodes.Ldloc, val);
2890 ig.Emit (OpCodes.Ldstr, str.Value);
2891 if (label_count == 1)
2892 ig.Emit (OpCodes.Bne_Un, next_test);
2894 if (label+1 == label_count)
2895 ig.Emit (OpCodes.Bne_Un, next_test);
2897 ig.Emit (OpCodes.Beq, sec_begin);
2902 ig.MarkLabel (null_target);
2903 ig.MarkLabel (sec_begin);
2904 foreach (SwitchLabel sl in ss.Labels)
2905 ig.MarkLabel (sl.GetILLabelCode (ec));
2908 ig.MarkLabel (default_target);
2910 pending_goto_end = !ss.Block.HasRet;
2913 ig.MarkLabel (next_test);
2915 if (!default_at_end)
2916 ig.Emit (OpCodes.Br, default_target);
2918 ig.MarkLabel (default_target);
2919 ig.MarkLabel (end_of_switch);
2922 SwitchSection FindSection (SwitchLabel label)
2924 foreach (SwitchSection ss in Sections){
2925 foreach (SwitchLabel sl in ss.Labels){
2934 bool ResolveConstantSwitch (EmitContext ec)
2936 object key = ((Constant) new_expr).GetValue ();
2937 SwitchLabel label = (SwitchLabel) Elements [key];
2942 constant_section = FindSection (label);
2943 if (constant_section == null)
2946 if (constant_section.Block.Resolve (ec) != true)
2952 public override bool Resolve (EmitContext ec)
2954 Expr = Expr.Resolve (ec);
2958 new_expr = SwitchGoverningType (ec, Expr.Type);
2959 if (new_expr == null){
2960 Report.Error (151, loc, "An integer type or string was expected for switch");
2965 SwitchType = new_expr.Type;
2967 if (!CheckSwitch (ec))
2970 Switch old_switch = ec.Switch;
2972 ec.Switch.SwitchType = SwitchType;
2974 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2975 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2977 is_constant = new_expr is Constant;
2979 object key = ((Constant) new_expr).GetValue ();
2980 SwitchLabel label = (SwitchLabel) Elements [key];
2982 constant_section = FindSection (label);
2986 foreach (SwitchSection ss in Sections){
2988 ec.CurrentBranching.CreateSibling (
2989 null, FlowBranching.SiblingType.SwitchSection);
2993 if (is_constant && (ss != constant_section)) {
2994 // If we're a constant switch, we're only emitting
2995 // one single section - mark all the others as
2997 ec.CurrentBranching.CurrentUsageVector.Goto ();
2998 if (!ss.Block.ResolveUnreachable (ec, true))
3001 if (!ss.Block.Resolve (ec))
3007 ec.CurrentBranching.CreateSibling (
3008 null, FlowBranching.SiblingType.SwitchSection);
3010 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3011 ec.Switch = old_switch;
3013 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3019 protected override void DoEmit (EmitContext ec)
3021 ILGenerator ig = ec.ig;
3023 // Store variable for comparission purposes
3026 value = ig.DeclareLocal (SwitchType);
3028 ig.Emit (OpCodes.Stloc, value);
3032 default_target = ig.DefineLabel ();
3035 // Setup the codegen context
3037 Label old_end = ec.LoopEnd;
3038 Switch old_switch = ec.Switch;
3040 ec.LoopEnd = ig.DefineLabel ();
3045 if (constant_section != null)
3046 constant_section.Block.Emit (ec);
3047 } else if (SwitchType == TypeManager.string_type)
3048 SimpleSwitchEmit (ec, value);
3050 TableSwitchEmit (ec, value);
3052 // Restore context state.
3053 ig.MarkLabel (ec.LoopEnd);
3056 // Restore the previous context
3058 ec.LoopEnd = old_end;
3059 ec.Switch = old_switch;
3063 public abstract class ExceptionStatement : Statement
3065 public abstract void EmitFinally (EmitContext ec);
3067 protected bool emit_finally = true;
3068 ArrayList parent_vectors;
3070 protected void DoEmitFinally (EmitContext ec)
3073 ec.ig.BeginFinallyBlock ();
3075 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3079 protected void ResolveFinally (FlowBranchingException branching)
3081 emit_finally = branching.EmitFinally;
3083 branching.Parent.StealFinallyClauses (ref parent_vectors);
3087 public class Lock : ExceptionStatement {
3089 Statement Statement;
3092 public Lock (Expression expr, Statement stmt, Location l)
3099 public override bool Resolve (EmitContext ec)
3101 expr = expr.Resolve (ec);
3105 if (expr.Type.IsValueType){
3106 Error (185, "lock statement requires the expression to be " +
3107 " a reference type (type is: `{0}'",
3108 TypeManager.CSharpName (expr.Type));
3112 FlowBranchingException branching = ec.StartFlowBranching (this);
3113 bool ok = Statement.Resolve (ec);
3115 ec.KillFlowBranching ();
3119 ResolveFinally (branching);
3121 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3122 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3123 // Unfortunately, System.Reflection.Emit automatically emits
3124 // a leave to the end of the finally block.
3125 // This is a problem if `returns' is true since we may jump
3126 // to a point after the end of the method.
3127 // As a workaround, emit an explicit ret here.
3128 ec.NeedReturnLabel ();
3134 protected override void DoEmit (EmitContext ec)
3136 Type type = expr.Type;
3138 ILGenerator ig = ec.ig;
3139 temp = ig.DeclareLocal (type);
3142 ig.Emit (OpCodes.Dup);
3143 ig.Emit (OpCodes.Stloc, temp);
3144 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3148 ig.BeginExceptionBlock ();
3149 Statement.Emit (ec);
3154 ig.EndExceptionBlock ();
3157 public override void EmitFinally (EmitContext ec)
3159 ILGenerator ig = ec.ig;
3160 ig.Emit (OpCodes.Ldloc, temp);
3161 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3165 public class Unchecked : Statement {
3166 public readonly Block Block;
3168 public Unchecked (Block b)
3174 public override bool Resolve (EmitContext ec)
3176 bool previous_state = ec.CheckState;
3177 bool previous_state_const = ec.ConstantCheckState;
3179 ec.CheckState = false;
3180 ec.ConstantCheckState = false;
3181 bool ret = Block.Resolve (ec);
3182 ec.CheckState = previous_state;
3183 ec.ConstantCheckState = previous_state_const;
3188 protected override void DoEmit (EmitContext ec)
3190 bool previous_state = ec.CheckState;
3191 bool previous_state_const = ec.ConstantCheckState;
3193 ec.CheckState = false;
3194 ec.ConstantCheckState = false;
3196 ec.CheckState = previous_state;
3197 ec.ConstantCheckState = previous_state_const;
3201 public class Checked : Statement {
3202 public readonly Block Block;
3204 public Checked (Block b)
3207 b.Unchecked = false;
3210 public override bool Resolve (EmitContext ec)
3212 bool previous_state = ec.CheckState;
3213 bool previous_state_const = ec.ConstantCheckState;
3215 ec.CheckState = true;
3216 ec.ConstantCheckState = true;
3217 bool ret = Block.Resolve (ec);
3218 ec.CheckState = previous_state;
3219 ec.ConstantCheckState = previous_state_const;
3224 protected override void DoEmit (EmitContext ec)
3226 bool previous_state = ec.CheckState;
3227 bool previous_state_const = ec.ConstantCheckState;
3229 ec.CheckState = true;
3230 ec.ConstantCheckState = true;
3232 ec.CheckState = previous_state;
3233 ec.ConstantCheckState = previous_state_const;
3237 public class Unsafe : Statement {
3238 public readonly Block Block;
3240 public Unsafe (Block b)
3243 Block.Unsafe = true;
3246 public override bool Resolve (EmitContext ec)
3248 bool previous_state = ec.InUnsafe;
3252 val = Block.Resolve (ec);
3253 ec.InUnsafe = previous_state;
3258 protected override void DoEmit (EmitContext ec)
3260 bool previous_state = ec.InUnsafe;
3264 ec.InUnsafe = previous_state;
3271 public class Fixed : Statement {
3273 ArrayList declarators;
3274 Statement statement;
3280 public bool is_object;
3281 public LocalInfo vi;
3282 public Expression expr;
3283 public Expression converted;
3286 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3289 declarators = decls;
3294 public override bool Resolve (EmitContext ec)
3297 Expression.UnsafeError (loc);
3301 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3305 expr_type = texpr.ResolveType (ec);
3307 CheckObsolete (expr_type);
3309 if (ec.RemapToProxy){
3310 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3314 data = new FixedData [declarators.Count];
3316 if (!expr_type.IsPointer){
3317 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3322 foreach (Pair p in declarators){
3323 LocalInfo vi = (LocalInfo) p.First;
3324 Expression e = (Expression) p.Second;
3326 vi.VariableInfo.SetAssigned (ec);
3330 // The rules for the possible declarators are pretty wise,
3331 // but the production on the grammar is more concise.
3333 // So we have to enforce these rules here.
3335 // We do not resolve before doing the case 1 test,
3336 // because the grammar is explicit in that the token &
3337 // is present, so we need to test for this particular case.
3341 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3346 // Case 1: & object.
3348 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3349 Expression child = ((Unary) e).Expr;
3351 if (child is ParameterReference || child is LocalVariableReference){
3354 "No need to use fixed statement for parameters or " +
3355 "local variable declarations (address is already " +
3360 ec.InFixedInitializer = true;
3362 ec.InFixedInitializer = false;
3366 child = ((Unary) e).Expr;
3368 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3371 data [i].is_object = true;
3373 data [i].converted = null;
3380 ec.InFixedInitializer = true;
3382 ec.InFixedInitializer = false;
3389 if (e.Type.IsArray){
3390 Type array_type = TypeManager.GetElementType (e.Type);
3393 // Provided that array_type is unmanaged,
3395 if (!TypeManager.VerifyUnManaged (array_type, loc))
3399 // and T* is implicitly convertible to the
3400 // pointer type given in the fixed statement.
3402 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3404 Expression converted = Convert.ImplicitConversionRequired (
3405 ec, array_ptr, vi.VariableType, loc);
3406 if (converted == null)
3409 data [i].is_object = false;
3411 data [i].converted = converted;
3421 if (e.Type == TypeManager.string_type){
3422 data [i].is_object = false;
3424 data [i].converted = null;
3431 // For other cases, flag a `this is already fixed expression'
3433 if (e is LocalVariableReference || e is ParameterReference ||
3434 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3436 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3440 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3444 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3446 if (!statement.Resolve (ec)) {
3447 ec.KillFlowBranching ();
3451 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3452 has_ret = reachability.IsUnreachable;
3457 protected override void DoEmit (EmitContext ec)
3459 ILGenerator ig = ec.ig;
3461 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3463 for (int i = 0; i < data.Length; i++) {
3464 LocalInfo vi = data [i].vi;
3467 // Case 1: & object.
3469 if (data [i].is_object) {
3471 // Store pointer in pinned location
3473 data [i].expr.Emit (ec);
3474 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3475 clear_list [i] = vi.LocalBuilder;
3482 if (data [i].expr.Type.IsArray){
3484 // Store pointer in pinned location
3486 data [i].converted.Emit (ec);
3488 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3489 clear_list [i] = vi.LocalBuilder;
3496 if (data [i].expr.Type == TypeManager.string_type){
3497 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3498 clear_list [i] = pinned_string;
3500 data [i].expr.Emit (ec);
3501 ig.Emit (OpCodes.Stloc, pinned_string);
3503 Expression sptr = new StringPtr (pinned_string, loc);
3504 Expression converted = Convert.ImplicitConversionRequired (
3505 ec, sptr, vi.VariableType, loc);
3507 if (converted == null)
3510 converted.Emit (ec);
3511 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3515 statement.Emit (ec);
3521 // Clear the pinned variable
3523 for (int i = 0; i < data.Length; i++) {
3524 if (data [i].is_object || data [i].expr.Type.IsArray) {
3525 ig.Emit (OpCodes.Ldc_I4_0);
3526 ig.Emit (OpCodes.Conv_U);
3527 ig.Emit (OpCodes.Stloc, clear_list [i]);
3528 } else if (data [i].expr.Type == TypeManager.string_type){
3529 ig.Emit (OpCodes.Ldnull);
3530 ig.Emit (OpCodes.Stloc, clear_list [i]);
3536 public class Catch: Statement {
3537 public readonly string Name;
3538 public readonly Block Block;
3540 Expression type_expr;
3543 public Catch (Expression type, string name, Block block, Location l)
3551 public Type CatchType {
3557 public bool IsGeneral {
3559 return type_expr == null;
3563 protected override void DoEmit(EmitContext ec)
3567 public override bool Resolve (EmitContext ec)
3569 if (type_expr != null) {
3570 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3574 type = te.ResolveType (ec);
3576 CheckObsolete (type);
3578 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3579 Error (155, "The type caught or thrown must be derived from System.Exception");
3585 return Block.Resolve (ec);
3589 public class Try : ExceptionStatement {
3590 public readonly Block Fini, Block;
3591 public readonly ArrayList Specific;
3592 public readonly Catch General;
3594 bool need_exc_block;
3597 // specific, general and fini might all be null.
3599 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3601 if (specific == null && general == null){
3602 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3606 this.Specific = specific;
3607 this.General = general;
3612 public override bool Resolve (EmitContext ec)
3616 FlowBranchingException branching = ec.StartFlowBranching (this);
3618 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3620 if (!Block.Resolve (ec))
3623 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3625 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3627 Type[] prevCatches = new Type [Specific.Count];
3629 foreach (Catch c in Specific){
3630 ec.CurrentBranching.CreateSibling (
3631 c.Block, FlowBranching.SiblingType.Catch);
3633 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3635 if (c.Name != null) {
3636 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3638 throw new Exception ();
3640 vi.VariableInfo = null;
3643 if (!c.Resolve (ec))
3646 Type resolvedType = c.CatchType;
3647 for (int ii = 0; ii < last_index; ++ii) {
3648 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3649 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3654 prevCatches [last_index++] = resolvedType;
3655 need_exc_block = true;
3658 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3660 if (General != null){
3661 ec.CurrentBranching.CreateSibling (
3662 General.Block, FlowBranching.SiblingType.Catch);
3664 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3666 if (!General.Resolve (ec))
3669 need_exc_block = true;
3672 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3676 ec.CurrentBranching.CreateSibling (
3677 Fini, FlowBranching.SiblingType.Finally);
3679 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3681 if (!Fini.Resolve (ec))
3685 ResolveFinally (branching);
3686 need_exc_block |= emit_finally;
3688 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3690 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3692 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3694 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3695 // Unfortunately, System.Reflection.Emit automatically emits
3696 // a leave to the end of the finally block. This is a problem
3697 // if `returns' is true since we may jump to a point after the
3698 // end of the method.
3699 // As a workaround, emit an explicit ret here.
3700 ec.NeedReturnLabel ();
3706 protected override void DoEmit (EmitContext ec)
3708 ILGenerator ig = ec.ig;
3711 ig.BeginExceptionBlock ();
3714 foreach (Catch c in Specific){
3717 ig.BeginCatchBlock (c.CatchType);
3719 if (c.Name != null){
3720 vi = c.Block.GetLocalInfo (c.Name);
3722 throw new Exception ("Variable does not exist in this block");
3724 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3726 ig.Emit (OpCodes.Pop);
3731 if (General != null){
3732 ig.BeginCatchBlock (TypeManager.object_type);
3733 ig.Emit (OpCodes.Pop);
3734 General.Block.Emit (ec);
3739 ig.EndExceptionBlock ();
3742 public override void EmitFinally (EmitContext ec)
3750 public class Using : ExceptionStatement {
3751 object expression_or_block;
3752 Statement Statement;
3757 Expression [] resolved_vars;
3758 Expression [] converted_vars;
3759 ExpressionStatement [] assign;
3760 LocalBuilder local_copy;
3762 public Using (object expression_or_block, Statement stmt, Location l)
3764 this.expression_or_block = expression_or_block;
3770 // Resolves for the case of using using a local variable declaration.
3772 bool ResolveLocalVariableDecls (EmitContext ec)
3776 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3780 expr_type = texpr.ResolveType (ec);
3783 // The type must be an IDisposable or an implicit conversion
3786 converted_vars = new Expression [var_list.Count];
3787 resolved_vars = new Expression [var_list.Count];
3788 assign = new ExpressionStatement [var_list.Count];
3790 bool need_conv = !TypeManager.ImplementsInterface (
3791 expr_type, TypeManager.idisposable_type);
3793 foreach (DictionaryEntry e in var_list){
3794 Expression var = (Expression) e.Key;
3796 var = var.ResolveLValue (ec, new EmptyExpression ());
3800 resolved_vars [i] = var;
3807 converted_vars [i] = Convert.ImplicitConversionRequired (
3808 ec, var, TypeManager.idisposable_type, loc);
3810 if (converted_vars [i] == null)
3817 foreach (DictionaryEntry e in var_list){
3818 Expression var = resolved_vars [i];
3819 Expression new_expr = (Expression) e.Value;
3822 a = new Assign (var, new_expr, loc);
3828 converted_vars [i] = var;
3829 assign [i] = (ExpressionStatement) a;
3836 bool ResolveExpression (EmitContext ec)
3838 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3839 conv = Convert.ImplicitConversionRequired (
3840 ec, expr, TypeManager.idisposable_type, loc);
3850 // Emits the code for the case of using using a local variable declaration.
3852 void EmitLocalVariableDecls (EmitContext ec)
3854 ILGenerator ig = ec.ig;
3857 for (i = 0; i < assign.Length; i++) {
3858 assign [i].EmitStatement (ec);
3861 ig.BeginExceptionBlock ();
3863 Statement.Emit (ec);
3864 var_list.Reverse ();
3869 void EmitLocalVariableDeclFinally (EmitContext ec)
3871 ILGenerator ig = ec.ig;
3873 int i = assign.Length;
3874 foreach (DictionaryEntry e in var_list){
3875 Expression var = resolved_vars [--i];
3876 Label skip = ig.DefineLabel ();
3878 if (!var.Type.IsValueType) {
3880 ig.Emit (OpCodes.Brfalse, skip);
3881 converted_vars [i].Emit (ec);
3882 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3884 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3886 if (!(ml is MethodGroupExpr)) {
3888 ig.Emit (OpCodes.Box, var.Type);
3889 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3891 MethodInfo mi = null;
3893 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3894 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3901 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3905 IMemoryLocation mloc = (IMemoryLocation) var;
3907 mloc.AddressOf (ec, AddressOp.Load);
3908 ig.Emit (OpCodes.Call, mi);
3912 ig.MarkLabel (skip);
3915 ig.EndExceptionBlock ();
3917 ig.BeginFinallyBlock ();
3922 void EmitExpression (EmitContext ec)
3925 // Make a copy of the expression and operate on that.
3927 ILGenerator ig = ec.ig;
3928 local_copy = ig.DeclareLocal (expr_type);
3933 ig.Emit (OpCodes.Stloc, local_copy);
3936 ig.BeginExceptionBlock ();
3938 Statement.Emit (ec);
3942 ig.EndExceptionBlock ();
3945 void EmitExpressionFinally (EmitContext ec)
3947 ILGenerator ig = ec.ig;
3948 Label skip = ig.DefineLabel ();
3949 ig.Emit (OpCodes.Ldloc, local_copy);
3950 ig.Emit (OpCodes.Brfalse, skip);
3951 ig.Emit (OpCodes.Ldloc, local_copy);
3952 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3953 ig.MarkLabel (skip);
3956 public override bool Resolve (EmitContext ec)
3958 if (expression_or_block is DictionaryEntry){
3959 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3960 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3962 if (!ResolveLocalVariableDecls (ec))
3965 } else if (expression_or_block is Expression){
3966 expr = (Expression) expression_or_block;
3968 expr = expr.Resolve (ec);
3972 expr_type = expr.Type;
3974 if (!ResolveExpression (ec))
3978 FlowBranchingException branching = ec.StartFlowBranching (this);
3980 bool ok = Statement.Resolve (ec);
3983 ec.KillFlowBranching ();
3987 ResolveFinally (branching);
3988 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3990 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3991 // Unfortunately, System.Reflection.Emit automatically emits a leave
3992 // to the end of the finally block. This is a problem if `returns'
3993 // is true since we may jump to a point after the end of the method.
3994 // As a workaround, emit an explicit ret here.
3995 ec.NeedReturnLabel ();
4001 protected override void DoEmit (EmitContext ec)
4003 if (expression_or_block is DictionaryEntry)
4004 EmitLocalVariableDecls (ec);
4005 else if (expression_or_block is Expression)
4006 EmitExpression (ec);
4009 public override void EmitFinally (EmitContext ec)
4011 if (expression_or_block is DictionaryEntry)
4012 EmitLocalVariableDeclFinally (ec);
4013 else if (expression_or_block is Expression)
4014 EmitExpressionFinally (ec);
4019 /// Implementation of the foreach C# statement
4021 public class Foreach : ExceptionStatement {
4023 Expression variable;
4025 Statement statement;
4026 ForeachHelperMethods hm;
4027 Expression empty, conv;
4028 Type array_type, element_type;
4030 VariableStorage enumerator;
4032 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4033 Statement stmt, Location l)
4036 this.variable = var;
4042 public override bool Resolve (EmitContext ec)
4044 expr = expr.Resolve (ec);
4048 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4052 var_type = texpr.ResolveType (ec);
4055 // We need an instance variable. Not sure this is the best
4056 // way of doing this.
4058 // FIXME: When we implement propertyaccess, will those turn
4059 // out to return values in ExprClass? I think they should.
4061 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4062 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4063 error1579 (expr.Type);
4067 if (expr.Type.IsArray) {
4068 array_type = expr.Type;
4069 element_type = TypeManager.GetElementType (array_type);
4071 empty = new EmptyExpression (element_type);
4073 hm = ProbeCollectionType (ec, expr.Type);
4075 error1579 (expr.Type);
4079 array_type = expr.Type;
4080 element_type = hm.element_type;
4082 empty = new EmptyExpression (hm.element_type);
4087 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4088 ec.CurrentBranching.CreateSibling ();
4092 // FIXME: maybe we can apply the same trick we do in the
4093 // array handling to avoid creating empty and conv in some cases.
4095 // Although it is not as important in this case, as the type
4096 // will not likely be object (what the enumerator will return).
4098 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4102 variable = variable.ResolveLValue (ec, empty);
4103 if (variable == null)
4106 bool disposable = (hm != null) && hm.is_disposable;
4107 FlowBranchingException branching = null;
4109 branching = ec.StartFlowBranching (this);
4111 if (!statement.Resolve (ec))
4115 ResolveFinally (branching);
4116 ec.EndFlowBranching ();
4118 emit_finally = true;
4120 ec.EndFlowBranching ();
4126 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4128 static MethodInfo FetchMethodMoveNext (Type t)
4130 MemberList move_next_list;
4132 move_next_list = TypeContainer.FindMembers (
4133 t, MemberTypes.Method,
4134 BindingFlags.Public | BindingFlags.Instance,
4135 Type.FilterName, "MoveNext");
4136 if (move_next_list.Count == 0)
4139 foreach (MemberInfo m in move_next_list){
4140 MethodInfo mi = (MethodInfo) m;
4143 args = TypeManager.GetArgumentTypes (mi);
4144 if (args != null && args.Length == 0){
4145 if (mi.ReturnType == TypeManager.bool_type)
4153 // Retrieves a `public T get_Current ()' method from the Type `t'
4155 static MethodInfo FetchMethodGetCurrent (Type t)
4157 MemberList get_current_list;
4159 get_current_list = TypeContainer.FindMembers (
4160 t, MemberTypes.Method,
4161 BindingFlags.Public | BindingFlags.Instance,
4162 Type.FilterName, "get_Current");
4163 if (get_current_list.Count == 0)
4166 foreach (MemberInfo m in get_current_list){
4167 MethodInfo mi = (MethodInfo) m;
4170 args = TypeManager.GetArgumentTypes (mi);
4171 if (args != null && args.Length == 0)
4178 // Retrieves a `public void Dispose ()' method from the Type `t'
4180 static MethodInfo FetchMethodDispose (Type t)
4182 MemberList dispose_list;
4184 dispose_list = TypeContainer.FindMembers (
4185 t, MemberTypes.Method,
4186 BindingFlags.Public | BindingFlags.Instance,
4187 Type.FilterName, "Dispose");
4188 if (dispose_list.Count == 0)
4191 foreach (MemberInfo m in dispose_list){
4192 MethodInfo mi = (MethodInfo) m;
4195 args = TypeManager.GetArgumentTypes (mi);
4196 if (args != null && args.Length == 0){
4197 if (mi.ReturnType == TypeManager.void_type)
4205 // This struct records the helper methods used by the Foreach construct
4207 class ForeachHelperMethods {
4208 public EmitContext ec;
4209 public MethodInfo get_enumerator;
4210 public MethodInfo move_next;
4211 public MethodInfo get_current;
4212 public Type element_type;
4213 public Type enumerator_type;
4214 public bool is_disposable;
4216 public ForeachHelperMethods (EmitContext ec)
4219 this.element_type = TypeManager.object_type;
4220 this.enumerator_type = TypeManager.ienumerator_type;
4221 this.is_disposable = true;
4225 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4230 if (!(m is MethodInfo))
4233 if (m.Name != "GetEnumerator")
4236 MethodInfo mi = (MethodInfo) m;
4237 Type [] args = TypeManager.GetArgumentTypes (mi);
4239 if (args.Length != 0)
4242 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4243 EmitContext ec = hm.ec;
4245 // Check whether GetEnumerator is public
4246 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4249 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4251 // Apply the same optimization as MS: skip the GetEnumerator
4252 // returning an IEnumerator, and use the one returning a
4253 // CharEnumerator instead. This allows us to avoid the
4254 // try-finally block and the boxing.
4259 // Ok, we can access it, now make sure that we can do something
4260 // with this `GetEnumerator'
4263 Type return_type = mi.ReturnType;
4264 if (mi.ReturnType == TypeManager.ienumerator_type ||
4265 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4266 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4269 // If it is not an interface, lets try to find the methods ourselves.
4270 // For example, if we have:
4271 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4272 // We can avoid the iface call. This is a runtime perf boost.
4273 // even bigger if we have a ValueType, because we avoid the cost
4276 // We have to make sure that both methods exist for us to take
4277 // this path. If one of the methods does not exist, we will just
4278 // use the interface. Sadly, this complex if statement is the only
4279 // way I could do this without a goto
4282 if (return_type.IsInterface ||
4283 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4284 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4286 hm.move_next = TypeManager.bool_movenext_void;
4287 hm.get_current = TypeManager.object_getcurrent_void;
4294 // Ok, so they dont return an IEnumerable, we will have to
4295 // find if they support the GetEnumerator pattern.
4298 hm.move_next = FetchMethodMoveNext (return_type);
4299 if (hm.move_next == null)
4302 hm.get_current = FetchMethodGetCurrent (return_type);
4303 if (hm.get_current == null)
4307 hm.element_type = hm.get_current.ReturnType;
4308 hm.enumerator_type = return_type;
4309 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4310 TypeManager.ImplementsInterface (
4311 hm.enumerator_type, TypeManager.idisposable_type);
4317 /// This filter is used to find the GetEnumerator method
4318 /// on which IEnumerator operates
4320 static MemberFilter FilterEnumerator;
4324 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4327 void error1579 (Type t)
4329 Report.Error (1579, loc,
4330 "foreach statement cannot operate on variables of type `" +
4331 t.FullName + "' because that class does not provide a " +
4332 " GetEnumerator method or it is inaccessible");
4335 static bool TryType (Type t, ForeachHelperMethods hm)
4339 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4340 BindingFlags.Public | BindingFlags.NonPublic |
4341 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4342 FilterEnumerator, hm);
4347 hm.get_enumerator = (MethodInfo) mi [0];
4352 // Looks for a usable GetEnumerator in the Type, and if found returns
4353 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4355 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4357 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4359 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4360 if (TryType (tt, hm))
4366 // Now try to find the method in the interfaces
4369 Type [] ifaces = t.GetInterfaces ();
4371 foreach (Type i in ifaces){
4372 if (TryType (i, hm))
4377 // Since TypeBuilder.GetInterfaces only returns the interface
4378 // types for this type, we have to keep looping, but once
4379 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4380 // done, because it returns all the types
4382 if ((t is TypeBuilder))
4392 // FIXME: possible optimization.
4393 // We might be able to avoid creating `empty' if the type is the sam
4395 bool EmitCollectionForeach (EmitContext ec)
4397 ILGenerator ig = ec.ig;
4399 enumerator = new VariableStorage (ec, hm.enumerator_type);
4400 enumerator.EmitThis (ig);
4402 // Instantiate the enumerator
4404 if (expr.Type.IsValueType) {
4405 IMemoryLocation ml = expr as IMemoryLocation;
4406 // Load the address of the value type.
4408 // This happens if, for example, you have a property
4409 // returning a struct which is IEnumerable
4410 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4412 ig.Emit (OpCodes.Stloc, t);
4413 ig.Emit (OpCodes.Ldloca, t);
4414 ec.FreeTemporaryLocal (t, expr.Type);
4416 ml.AddressOf (ec, AddressOp.Load);
4420 if (hm.get_enumerator.DeclaringType.IsValueType) {
4421 // the method is declared on the value type
4422 ig.Emit (OpCodes.Call, hm.get_enumerator);
4424 // it is an interface method, so we must box
4425 ig.Emit (OpCodes.Box, expr.Type);
4426 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4430 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4432 enumerator.EmitStore (ig);
4435 // Protect the code in a try/finalize block, so that
4436 // if the beast implement IDisposable, we get rid of it
4438 if (hm.is_disposable && emit_finally)
4439 ig.BeginExceptionBlock ();
4441 Label end_try = ig.DefineLabel ();
4443 ig.MarkLabel (ec.LoopBegin);
4445 enumerator.EmitCall (ig, hm.move_next);
4447 ig.Emit (OpCodes.Brfalse, end_try);
4450 enumerator.EmitThis (ig);
4451 enumerator.EmitCall (ig, hm.get_current);
4455 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4457 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4459 statement.Emit (ec);
4460 ig.Emit (OpCodes.Br, ec.LoopBegin);
4461 ig.MarkLabel (end_try);
4464 // Now the finally block
4466 if (hm.is_disposable) {
4469 ig.EndExceptionBlock ();
4472 ig.MarkLabel (ec.LoopEnd);
4476 public override void EmitFinally (EmitContext ec)
4478 ILGenerator ig = ec.ig;
4480 if (hm.enumerator_type.IsValueType) {
4481 enumerator.EmitThis (ig);
4483 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4485 enumerator.EmitLoadAddress (ig);
4486 ig.Emit (OpCodes.Call, mi);
4488 enumerator.EmitLoad (ig);
4489 ig.Emit (OpCodes.Box, hm.enumerator_type);
4490 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4493 Label call_dispose = ig.DefineLabel ();
4495 enumerator.EmitThis (ig);
4496 enumerator.EmitLoad (ig);
4497 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4498 ig.Emit (OpCodes.Dup);
4499 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4500 ig.Emit (OpCodes.Pop);
4502 Label end_finally = ig.DefineLabel ();
4503 ig.Emit (OpCodes.Br, end_finally);
4505 ig.MarkLabel (call_dispose);
4506 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4507 ig.MarkLabel (end_finally);
4510 ig.Emit (OpCodes.Endfinally);
4515 // FIXME: possible optimization.
4516 // We might be able to avoid creating `empty' if the type is the sam
4518 bool EmitArrayForeach (EmitContext ec)
4520 int rank = array_type.GetArrayRank ();
4521 ILGenerator ig = ec.ig;
4523 VariableStorage copy = new VariableStorage (ec, array_type);
4526 // Make our copy of the array
4530 copy.EmitStore (ig);
4533 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4537 counter.EmitThis (ig);
4538 ig.Emit (OpCodes.Ldc_I4_0);
4539 counter.EmitStore (ig);
4540 test = ig.DefineLabel ();
4541 ig.Emit (OpCodes.Br, test);
4543 loop = ig.DefineLabel ();
4544 ig.MarkLabel (loop);
4551 counter.EmitThis (ig);
4552 counter.EmitLoad (ig);
4555 // Load the value, we load the value using the underlying type,
4556 // then we use the variable.EmitAssign to load using the proper cast.
4558 ArrayAccess.EmitLoadOpcode (ig, element_type);
4561 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4563 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4565 statement.Emit (ec);
4567 ig.MarkLabel (ec.LoopBegin);
4568 counter.EmitThis (ig);
4569 counter.EmitThis (ig);
4570 counter.EmitLoad (ig);
4571 ig.Emit (OpCodes.Ldc_I4_1);
4572 ig.Emit (OpCodes.Add);
4573 counter.EmitStore (ig);
4575 ig.MarkLabel (test);
4576 counter.EmitThis (ig);
4577 counter.EmitLoad (ig);
4580 ig.Emit (OpCodes.Ldlen);
4581 ig.Emit (OpCodes.Conv_I4);
4582 ig.Emit (OpCodes.Blt, loop);
4584 VariableStorage [] dim_len = new VariableStorage [rank];
4585 VariableStorage [] dim_count = new VariableStorage [rank];
4586 Label [] loop = new Label [rank];
4587 Label [] test = new Label [rank];
4590 for (dim = 0; dim < rank; dim++){
4591 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4592 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4593 test [dim] = ig.DefineLabel ();
4594 loop [dim] = ig.DefineLabel ();
4597 for (dim = 0; dim < rank; dim++){
4598 dim_len [dim].EmitThis (ig);
4601 IntLiteral.EmitInt (ig, dim);
4602 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4603 dim_len [dim].EmitStore (ig);
4607 for (dim = 0; dim < rank; dim++){
4608 dim_count [dim].EmitThis (ig);
4609 ig.Emit (OpCodes.Ldc_I4_0);
4610 dim_count [dim].EmitStore (ig);
4611 ig.Emit (OpCodes.Br, test [dim]);
4612 ig.MarkLabel (loop [dim]);
4619 for (dim = 0; dim < rank; dim++){
4620 dim_count [dim].EmitThis (ig);
4621 dim_count [dim].EmitLoad (ig);
4625 // FIXME: Maybe we can cache the computation of `get'?
4627 Type [] args = new Type [rank];
4630 for (int i = 0; i < rank; i++)
4631 args [i] = TypeManager.int32_type;
4633 ModuleBuilder mb = CodeGen.Module.Builder;
4634 get = mb.GetArrayMethod (
4636 CallingConventions.HasThis| CallingConventions.Standard,
4638 ig.Emit (OpCodes.Call, get);
4641 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4643 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4644 statement.Emit (ec);
4645 ig.MarkLabel (ec.LoopBegin);
4646 for (dim = rank - 1; dim >= 0; dim--){
4647 dim_count [dim].EmitThis (ig);
4648 dim_count [dim].EmitThis (ig);
4649 dim_count [dim].EmitLoad (ig);
4650 ig.Emit (OpCodes.Ldc_I4_1);
4651 ig.Emit (OpCodes.Add);
4652 dim_count [dim].EmitStore (ig);
4654 ig.MarkLabel (test [dim]);
4655 dim_count [dim].EmitThis (ig);
4656 dim_count [dim].EmitLoad (ig);
4657 dim_len [dim].EmitThis (ig);
4658 dim_len [dim].EmitLoad (ig);
4659 ig.Emit (OpCodes.Blt, loop [dim]);
4662 ig.MarkLabel (ec.LoopEnd);
4667 protected override void DoEmit (EmitContext ec)
4669 ILGenerator ig = ec.ig;
4671 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4672 ec.LoopBegin = ig.DefineLabel ();
4673 ec.LoopEnd = ig.DefineLabel ();
4676 EmitCollectionForeach (ec);
4678 EmitArrayForeach (ec);
4680 ec.LoopBegin = old_begin;
4681 ec.LoopEnd = old_end;