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);
1031 VariableType = texpr.Type;
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.int32_type,
2351 TypeManager.uint32_type,
2352 TypeManager.sbyte_type,
2353 TypeManager.byte_type,
2354 TypeManager.short_type,
2355 TypeManager.ushort_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);
2379 // Ignore over-worked ImplicitUserConversions that do
2380 // an implicit conversion in addition to the user conversion.
2383 UserCast ue = e as UserCast;
2385 if (ue.Source != Expr)
2389 if (converted != null){
2390 Report.ExtraInformation (
2392 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2393 TypeManager.CSharpName (Expr.Type)));
2402 static string Error152 {
2404 return "The label '{0}:' already occurs in this switch statement";
2409 // Performs the basic sanity checks on the switch statement
2410 // (looks for duplicate keys and non-constant expressions).
2412 // It also returns a hashtable with the keys that we will later
2413 // use to compute the switch tables
2415 bool CheckSwitch (EmitContext ec)
2419 Elements = new Hashtable ();
2421 got_default = false;
2423 if (TypeManager.IsEnumType (SwitchType)){
2424 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2426 compare_type = SwitchType;
2428 foreach (SwitchSection ss in Sections){
2429 foreach (SwitchLabel sl in ss.Labels){
2430 if (!sl.ResolveAndReduce (ec, SwitchType)){
2435 if (sl.Label == null){
2437 Report.Error (152, sl.loc, Error152, "default");
2444 object key = sl.Converted;
2446 if (key is Constant)
2447 key = ((Constant) key).GetValue ();
2450 key = NullLiteral.Null;
2452 string lname = null;
2453 if (compare_type == TypeManager.uint64_type){
2454 ulong v = (ulong) key;
2456 if (Elements.Contains (v))
2457 lname = v.ToString ();
2459 Elements.Add (v, sl);
2460 } else if (compare_type == TypeManager.int64_type){
2461 long v = (long) key;
2463 if (Elements.Contains (v))
2464 lname = v.ToString ();
2466 Elements.Add (v, sl);
2467 } else if (compare_type == TypeManager.uint32_type){
2468 uint v = (uint) key;
2470 if (Elements.Contains (v))
2471 lname = v.ToString ();
2473 Elements.Add (v, sl);
2474 } else if (compare_type == TypeManager.char_type){
2475 char v = (char) key;
2477 if (Elements.Contains (v))
2478 lname = v.ToString ();
2480 Elements.Add (v, sl);
2481 } else if (compare_type == TypeManager.byte_type){
2482 byte v = (byte) key;
2484 if (Elements.Contains (v))
2485 lname = v.ToString ();
2487 Elements.Add (v, sl);
2488 } else if (compare_type == TypeManager.sbyte_type){
2489 sbyte v = (sbyte) key;
2491 if (Elements.Contains (v))
2492 lname = v.ToString ();
2494 Elements.Add (v, sl);
2495 } else if (compare_type == TypeManager.short_type){
2496 short v = (short) key;
2498 if (Elements.Contains (v))
2499 lname = v.ToString ();
2501 Elements.Add (v, sl);
2502 } else if (compare_type == TypeManager.ushort_type){
2503 ushort v = (ushort) key;
2505 if (Elements.Contains (v))
2506 lname = v.ToString ();
2508 Elements.Add (v, sl);
2509 } else if (compare_type == TypeManager.string_type){
2510 if (key is NullLiteral){
2511 if (Elements.Contains (NullLiteral.Null))
2514 Elements.Add (NullLiteral.Null, null);
2516 string s = (string) key;
2518 if (Elements.Contains (s))
2521 Elements.Add (s, sl);
2523 } else if (compare_type == TypeManager.int32_type) {
2526 if (Elements.Contains (v))
2527 lname = v.ToString ();
2529 Elements.Add (v, sl);
2530 } else if (compare_type == TypeManager.bool_type) {
2531 bool v = (bool) key;
2533 if (Elements.Contains (v))
2534 lname = v.ToString ();
2536 Elements.Add (v, sl);
2540 throw new Exception ("Unknown switch type!" +
2541 SwitchType + " " + compare_type);
2545 Report.Error (152, sl.loc, Error152, "case " + lname);
2556 void EmitObjectInteger (ILGenerator ig, object k)
2559 IntConstant.EmitInt (ig, (int) k);
2560 else if (k is Constant) {
2561 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2564 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2567 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2569 IntConstant.EmitInt (ig, (int) (long) k);
2570 ig.Emit (OpCodes.Conv_I8);
2573 LongConstant.EmitLong (ig, (long) k);
2575 else if (k is ulong)
2577 if ((ulong) k < (1L<<32))
2579 IntConstant.EmitInt (ig, (int) (long) k);
2580 ig.Emit (OpCodes.Conv_U8);
2584 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2588 IntConstant.EmitInt (ig, (int) ((char) k));
2589 else if (k is sbyte)
2590 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2592 IntConstant.EmitInt (ig, (int) ((byte) k));
2593 else if (k is short)
2594 IntConstant.EmitInt (ig, (int) ((short) k));
2595 else if (k is ushort)
2596 IntConstant.EmitInt (ig, (int) ((ushort) k));
2598 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2600 throw new Exception ("Unhandled case");
2603 // structure used to hold blocks of keys while calculating table switch
2604 class KeyBlock : IComparable
2606 public KeyBlock (long _nFirst)
2608 nFirst = nLast = _nFirst;
2612 public ArrayList rgKeys = null;
2613 // how many items are in the bucket
2614 public int Size = 1;
2617 get { return (int) (nLast - nFirst + 1); }
2619 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2621 return kbLast.nLast - kbFirst.nFirst + 1;
2623 public int CompareTo (object obj)
2625 KeyBlock kb = (KeyBlock) obj;
2626 int nLength = Length;
2627 int nLengthOther = kb.Length;
2628 if (nLengthOther == nLength)
2629 return (int) (kb.nFirst - nFirst);
2630 return nLength - nLengthOther;
2635 /// This method emits code for a lookup-based switch statement (non-string)
2636 /// Basically it groups the cases into blocks that are at least half full,
2637 /// and then spits out individual lookup opcodes for each block.
2638 /// It emits the longest blocks first, and short blocks are just
2639 /// handled with direct compares.
2641 /// <param name="ec"></param>
2642 /// <param name="val"></param>
2643 /// <returns></returns>
2644 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2646 int cElements = Elements.Count;
2647 object [] rgKeys = new object [cElements];
2648 Elements.Keys.CopyTo (rgKeys, 0);
2649 Array.Sort (rgKeys);
2651 // initialize the block list with one element per key
2652 ArrayList rgKeyBlocks = new ArrayList ();
2653 foreach (object key in rgKeys)
2654 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2657 // iteratively merge the blocks while they are at least half full
2658 // there's probably a really cool way to do this with a tree...
2659 while (rgKeyBlocks.Count > 1)
2661 ArrayList rgKeyBlocksNew = new ArrayList ();
2662 kbCurr = (KeyBlock) rgKeyBlocks [0];
2663 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2665 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2666 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2669 kbCurr.nLast = kb.nLast;
2670 kbCurr.Size += kb.Size;
2674 // start a new block
2675 rgKeyBlocksNew.Add (kbCurr);
2679 rgKeyBlocksNew.Add (kbCurr);
2680 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2682 rgKeyBlocks = rgKeyBlocksNew;
2685 // initialize the key lists
2686 foreach (KeyBlock kb in rgKeyBlocks)
2687 kb.rgKeys = new ArrayList ();
2689 // fill the key lists
2691 if (rgKeyBlocks.Count > 0) {
2692 kbCurr = (KeyBlock) rgKeyBlocks [0];
2693 foreach (object key in rgKeys)
2695 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2696 System.Convert.ToInt64 (key) > kbCurr.nLast;
2698 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2699 kbCurr.rgKeys.Add (key);
2703 // sort the blocks so we can tackle the largest ones first
2704 rgKeyBlocks.Sort ();
2706 // okay now we can start...
2707 ILGenerator ig = ec.ig;
2708 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2709 Label lblDefault = ig.DefineLabel ();
2711 Type typeKeys = null;
2712 if (rgKeys.Length > 0)
2713 typeKeys = rgKeys [0].GetType (); // used for conversions
2717 if (TypeManager.IsEnumType (SwitchType))
2718 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2720 compare_type = SwitchType;
2722 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2724 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2725 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2728 foreach (object key in kb.rgKeys)
2730 ig.Emit (OpCodes.Ldloc, val);
2731 EmitObjectInteger (ig, key);
2732 SwitchLabel sl = (SwitchLabel) Elements [key];
2733 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2738 // TODO: if all the keys in the block are the same and there are
2739 // no gaps/defaults then just use a range-check.
2740 if (compare_type == TypeManager.int64_type ||
2741 compare_type == TypeManager.uint64_type)
2743 // TODO: optimize constant/I4 cases
2745 // check block range (could be > 2^31)
2746 ig.Emit (OpCodes.Ldloc, val);
2747 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2748 ig.Emit (OpCodes.Blt, lblDefault);
2749 ig.Emit (OpCodes.Ldloc, val);
2750 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2751 ig.Emit (OpCodes.Bgt, lblDefault);
2754 ig.Emit (OpCodes.Ldloc, val);
2757 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2758 ig.Emit (OpCodes.Sub);
2760 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2765 ig.Emit (OpCodes.Ldloc, val);
2766 int nFirst = (int) kb.nFirst;
2769 IntConstant.EmitInt (ig, nFirst);
2770 ig.Emit (OpCodes.Sub);
2772 else if (nFirst < 0)
2774 IntConstant.EmitInt (ig, -nFirst);
2775 ig.Emit (OpCodes.Add);
2779 // first, build the list of labels for the switch
2781 int cJumps = kb.Length;
2782 Label [] rgLabels = new Label [cJumps];
2783 for (int iJump = 0; iJump < cJumps; iJump++)
2785 object key = kb.rgKeys [iKey];
2786 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2788 SwitchLabel sl = (SwitchLabel) Elements [key];
2789 rgLabels [iJump] = sl.GetILLabel (ec);
2793 rgLabels [iJump] = lblDefault;
2795 // emit the switch opcode
2796 ig.Emit (OpCodes.Switch, rgLabels);
2799 // mark the default for this block
2801 ig.MarkLabel (lblDefault);
2804 // TODO: find the default case and emit it here,
2805 // to prevent having to do the following jump.
2806 // make sure to mark other labels in the default section
2808 // the last default just goes to the end
2809 ig.Emit (OpCodes.Br, lblDefault);
2811 // now emit the code for the sections
2812 bool fFoundDefault = false;
2813 foreach (SwitchSection ss in Sections)
2815 foreach (SwitchLabel sl in ss.Labels)
2817 ig.MarkLabel (sl.GetILLabel (ec));
2818 ig.MarkLabel (sl.GetILLabelCode (ec));
2819 if (sl.Label == null)
2821 ig.MarkLabel (lblDefault);
2822 fFoundDefault = true;
2826 //ig.Emit (OpCodes.Br, lblEnd);
2829 if (!fFoundDefault) {
2830 ig.MarkLabel (lblDefault);
2832 ig.MarkLabel (lblEnd);
2835 // This simple emit switch works, but does not take advantage of the
2837 // TODO: remove non-string logic from here
2838 // TODO: binary search strings?
2840 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2842 ILGenerator ig = ec.ig;
2843 Label end_of_switch = ig.DefineLabel ();
2844 Label next_test = ig.DefineLabel ();
2845 Label null_target = ig.DefineLabel ();
2846 bool default_found = false;
2847 bool first_test = true;
2848 bool pending_goto_end = false;
2850 bool default_at_end = false;
2852 ig.Emit (OpCodes.Ldloc, val);
2854 if (Elements.Contains (NullLiteral.Null)){
2855 ig.Emit (OpCodes.Brfalse, null_target);
2857 ig.Emit (OpCodes.Brfalse, default_target);
2859 ig.Emit (OpCodes.Ldloc, val);
2860 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2861 ig.Emit (OpCodes.Stloc, val);
2863 int section_count = Sections.Count;
2864 for (int section = 0; section < section_count; section++){
2865 SwitchSection ss = (SwitchSection) Sections [section];
2866 Label sec_begin = ig.DefineLabel ();
2868 if (pending_goto_end)
2869 ig.Emit (OpCodes.Br, end_of_switch);
2871 int label_count = ss.Labels.Count;
2872 bool mark_default = false;
2874 for (int label = 0; label < label_count; label++){
2875 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2876 ig.MarkLabel (sl.GetILLabel (ec));
2879 ig.MarkLabel (next_test);
2880 next_test = ig.DefineLabel ();
2883 // If we are the default target
2885 if (sl.Label == null){
2886 if (label+1 == label_count)
2887 default_at_end = true;
2888 mark_default = true;
2889 default_found = true;
2891 object lit = sl.Converted;
2893 if (lit is NullLiteral){
2895 if (label_count == 1)
2896 ig.Emit (OpCodes.Br, next_test);
2900 StringConstant str = (StringConstant) lit;
2902 ig.Emit (OpCodes.Ldloc, val);
2903 ig.Emit (OpCodes.Ldstr, str.Value);
2904 if (label_count == 1)
2905 ig.Emit (OpCodes.Bne_Un, next_test);
2907 if (label+1 == label_count)
2908 ig.Emit (OpCodes.Bne_Un, next_test);
2910 ig.Emit (OpCodes.Beq, sec_begin);
2915 ig.MarkLabel (null_target);
2916 ig.MarkLabel (sec_begin);
2917 foreach (SwitchLabel sl in ss.Labels)
2918 ig.MarkLabel (sl.GetILLabelCode (ec));
2921 ig.MarkLabel (default_target);
2923 pending_goto_end = !ss.Block.HasRet;
2926 ig.MarkLabel (next_test);
2928 if (!default_at_end)
2929 ig.Emit (OpCodes.Br, default_target);
2931 ig.MarkLabel (default_target);
2932 ig.MarkLabel (end_of_switch);
2935 SwitchSection FindSection (SwitchLabel label)
2937 foreach (SwitchSection ss in Sections){
2938 foreach (SwitchLabel sl in ss.Labels){
2947 bool ResolveConstantSwitch (EmitContext ec)
2949 object key = ((Constant) new_expr).GetValue ();
2950 SwitchLabel label = (SwitchLabel) Elements [key];
2955 constant_section = FindSection (label);
2956 if (constant_section == null)
2959 if (constant_section.Block.Resolve (ec) != true)
2965 public override bool Resolve (EmitContext ec)
2967 Expr = Expr.Resolve (ec);
2971 new_expr = SwitchGoverningType (ec, Expr.Type);
2972 if (new_expr == null){
2973 Report.Error (151, loc, "An integer type or string was expected for switch");
2978 SwitchType = new_expr.Type;
2980 if (!CheckSwitch (ec))
2983 Switch old_switch = ec.Switch;
2985 ec.Switch.SwitchType = SwitchType;
2987 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2988 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2990 is_constant = new_expr is Constant;
2992 object key = ((Constant) new_expr).GetValue ();
2993 SwitchLabel label = (SwitchLabel) Elements [key];
2995 constant_section = FindSection (label);
2999 foreach (SwitchSection ss in Sections){
3001 ec.CurrentBranching.CreateSibling (
3002 null, FlowBranching.SiblingType.SwitchSection);
3006 if (is_constant && (ss != constant_section)) {
3007 // If we're a constant switch, we're only emitting
3008 // one single section - mark all the others as
3010 ec.CurrentBranching.CurrentUsageVector.Goto ();
3011 if (!ss.Block.ResolveUnreachable (ec, true))
3014 if (!ss.Block.Resolve (ec))
3020 ec.CurrentBranching.CreateSibling (
3021 null, FlowBranching.SiblingType.SwitchSection);
3023 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3024 ec.Switch = old_switch;
3026 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3032 protected override void DoEmit (EmitContext ec)
3034 ILGenerator ig = ec.ig;
3036 // Store variable for comparission purposes
3039 value = ig.DeclareLocal (SwitchType);
3041 ig.Emit (OpCodes.Stloc, value);
3045 default_target = ig.DefineLabel ();
3048 // Setup the codegen context
3050 Label old_end = ec.LoopEnd;
3051 Switch old_switch = ec.Switch;
3053 ec.LoopEnd = ig.DefineLabel ();
3058 if (constant_section != null)
3059 constant_section.Block.Emit (ec);
3060 } else if (SwitchType == TypeManager.string_type)
3061 SimpleSwitchEmit (ec, value);
3063 TableSwitchEmit (ec, value);
3065 // Restore context state.
3066 ig.MarkLabel (ec.LoopEnd);
3069 // Restore the previous context
3071 ec.LoopEnd = old_end;
3072 ec.Switch = old_switch;
3076 public abstract class ExceptionStatement : Statement
3078 public abstract void EmitFinally (EmitContext ec);
3080 protected bool emit_finally = true;
3081 ArrayList parent_vectors;
3083 protected void DoEmitFinally (EmitContext ec)
3086 ec.ig.BeginFinallyBlock ();
3088 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3092 protected void ResolveFinally (FlowBranchingException branching)
3094 emit_finally = branching.EmitFinally;
3096 branching.Parent.StealFinallyClauses (ref parent_vectors);
3100 public class Lock : ExceptionStatement {
3102 Statement Statement;
3105 public Lock (Expression expr, Statement stmt, Location l)
3112 public override bool Resolve (EmitContext ec)
3114 expr = expr.Resolve (ec);
3118 if (expr.Type.IsValueType){
3119 Error (185, "lock statement requires the expression to be " +
3120 " a reference type (type is: `{0}'",
3121 TypeManager.CSharpName (expr.Type));
3125 FlowBranchingException branching = ec.StartFlowBranching (this);
3126 bool ok = Statement.Resolve (ec);
3128 ec.KillFlowBranching ();
3132 ResolveFinally (branching);
3134 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3135 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3136 // Unfortunately, System.Reflection.Emit automatically emits
3137 // a leave to the end of the finally block.
3138 // This is a problem if `returns' is true since we may jump
3139 // to a point after the end of the method.
3140 // As a workaround, emit an explicit ret here.
3141 ec.NeedReturnLabel ();
3147 protected override void DoEmit (EmitContext ec)
3149 Type type = expr.Type;
3151 ILGenerator ig = ec.ig;
3152 temp = ig.DeclareLocal (type);
3155 ig.Emit (OpCodes.Dup);
3156 ig.Emit (OpCodes.Stloc, temp);
3157 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3161 ig.BeginExceptionBlock ();
3162 Statement.Emit (ec);
3167 ig.EndExceptionBlock ();
3170 public override void EmitFinally (EmitContext ec)
3172 ILGenerator ig = ec.ig;
3173 ig.Emit (OpCodes.Ldloc, temp);
3174 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3178 public class Unchecked : Statement {
3179 public readonly Block Block;
3181 public Unchecked (Block b)
3187 public override bool Resolve (EmitContext ec)
3189 bool previous_state = ec.CheckState;
3190 bool previous_state_const = ec.ConstantCheckState;
3192 ec.CheckState = false;
3193 ec.ConstantCheckState = false;
3194 bool ret = Block.Resolve (ec);
3195 ec.CheckState = previous_state;
3196 ec.ConstantCheckState = previous_state_const;
3201 protected override void DoEmit (EmitContext ec)
3203 bool previous_state = ec.CheckState;
3204 bool previous_state_const = ec.ConstantCheckState;
3206 ec.CheckState = false;
3207 ec.ConstantCheckState = false;
3209 ec.CheckState = previous_state;
3210 ec.ConstantCheckState = previous_state_const;
3214 public class Checked : Statement {
3215 public readonly Block Block;
3217 public Checked (Block b)
3220 b.Unchecked = false;
3223 public override bool Resolve (EmitContext ec)
3225 bool previous_state = ec.CheckState;
3226 bool previous_state_const = ec.ConstantCheckState;
3228 ec.CheckState = true;
3229 ec.ConstantCheckState = true;
3230 bool ret = Block.Resolve (ec);
3231 ec.CheckState = previous_state;
3232 ec.ConstantCheckState = previous_state_const;
3237 protected override void DoEmit (EmitContext ec)
3239 bool previous_state = ec.CheckState;
3240 bool previous_state_const = ec.ConstantCheckState;
3242 ec.CheckState = true;
3243 ec.ConstantCheckState = true;
3245 ec.CheckState = previous_state;
3246 ec.ConstantCheckState = previous_state_const;
3250 public class Unsafe : Statement {
3251 public readonly Block Block;
3253 public Unsafe (Block b)
3256 Block.Unsafe = true;
3259 public override bool Resolve (EmitContext ec)
3261 bool previous_state = ec.InUnsafe;
3265 val = Block.Resolve (ec);
3266 ec.InUnsafe = previous_state;
3271 protected override void DoEmit (EmitContext ec)
3273 bool previous_state = ec.InUnsafe;
3277 ec.InUnsafe = previous_state;
3284 public class Fixed : Statement {
3286 ArrayList declarators;
3287 Statement statement;
3293 public bool is_object;
3294 public LocalInfo vi;
3295 public Expression expr;
3296 public Expression converted;
3299 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3302 declarators = decls;
3307 public override bool Resolve (EmitContext ec)
3310 Expression.UnsafeError (loc);
3314 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3318 expr_type = texpr.Type;
3320 CheckObsolete (expr_type);
3322 if (ec.RemapToProxy){
3323 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3327 data = new FixedData [declarators.Count];
3329 if (!expr_type.IsPointer){
3330 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3335 foreach (Pair p in declarators){
3336 LocalInfo vi = (LocalInfo) p.First;
3337 Expression e = (Expression) p.Second;
3339 vi.VariableInfo.SetAssigned (ec);
3343 // The rules for the possible declarators are pretty wise,
3344 // but the production on the grammar is more concise.
3346 // So we have to enforce these rules here.
3348 // We do not resolve before doing the case 1 test,
3349 // because the grammar is explicit in that the token &
3350 // is present, so we need to test for this particular case.
3354 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3359 // Case 1: & object.
3361 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3362 Expression child = ((Unary) e).Expr;
3364 if (child is ParameterReference || child is LocalVariableReference){
3367 "No need to use fixed statement for parameters or " +
3368 "local variable declarations (address is already " +
3373 ec.InFixedInitializer = true;
3375 ec.InFixedInitializer = false;
3379 child = ((Unary) e).Expr;
3381 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3384 data [i].is_object = true;
3386 data [i].converted = null;
3393 ec.InFixedInitializer = true;
3395 ec.InFixedInitializer = false;
3402 if (e.Type.IsArray){
3403 Type array_type = TypeManager.GetElementType (e.Type);
3406 // Provided that array_type is unmanaged,
3408 if (!TypeManager.VerifyUnManaged (array_type, loc))
3412 // and T* is implicitly convertible to the
3413 // pointer type given in the fixed statement.
3415 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3417 Expression converted = Convert.ImplicitConversionRequired (
3418 ec, array_ptr, vi.VariableType, loc);
3419 if (converted == null)
3422 data [i].is_object = false;
3424 data [i].converted = converted;
3434 if (e.Type == TypeManager.string_type){
3435 data [i].is_object = false;
3437 data [i].converted = null;
3444 // For other cases, flag a `this is already fixed expression'
3446 if (e is LocalVariableReference || e is ParameterReference ||
3447 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3449 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3453 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3457 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3459 if (!statement.Resolve (ec)) {
3460 ec.KillFlowBranching ();
3464 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3465 has_ret = reachability.IsUnreachable;
3470 protected override void DoEmit (EmitContext ec)
3472 ILGenerator ig = ec.ig;
3474 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3476 for (int i = 0; i < data.Length; i++) {
3477 LocalInfo vi = data [i].vi;
3480 // Case 1: & object.
3482 if (data [i].is_object) {
3484 // Store pointer in pinned location
3486 data [i].expr.Emit (ec);
3487 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3488 clear_list [i] = vi.LocalBuilder;
3495 if (data [i].expr.Type.IsArray){
3497 // Store pointer in pinned location
3499 data [i].converted.Emit (ec);
3501 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3502 clear_list [i] = vi.LocalBuilder;
3509 if (data [i].expr.Type == TypeManager.string_type){
3510 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3511 clear_list [i] = pinned_string;
3513 data [i].expr.Emit (ec);
3514 ig.Emit (OpCodes.Stloc, pinned_string);
3516 Expression sptr = new StringPtr (pinned_string, loc);
3517 Expression converted = Convert.ImplicitConversionRequired (
3518 ec, sptr, vi.VariableType, loc);
3520 if (converted == null)
3523 converted.Emit (ec);
3524 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3528 statement.Emit (ec);
3534 // Clear the pinned variable
3536 for (int i = 0; i < data.Length; i++) {
3537 if (data [i].is_object || data [i].expr.Type.IsArray) {
3538 ig.Emit (OpCodes.Ldc_I4_0);
3539 ig.Emit (OpCodes.Conv_U);
3540 ig.Emit (OpCodes.Stloc, clear_list [i]);
3541 } else if (data [i].expr.Type == TypeManager.string_type){
3542 ig.Emit (OpCodes.Ldnull);
3543 ig.Emit (OpCodes.Stloc, clear_list [i]);
3549 public class Catch: Statement {
3550 public readonly string Name;
3551 public readonly Block Block;
3553 Expression type_expr;
3556 public Catch (Expression type, string name, Block block, Location l)
3564 public Type CatchType {
3570 public bool IsGeneral {
3572 return type_expr == null;
3576 protected override void DoEmit(EmitContext ec)
3580 public override bool Resolve (EmitContext ec)
3582 if (type_expr != null) {
3583 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3589 CheckObsolete (type);
3591 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3592 Error (155, "The type caught or thrown must be derived from System.Exception");
3598 return Block.Resolve (ec);
3602 public class Try : ExceptionStatement {
3603 public readonly Block Fini, Block;
3604 public readonly ArrayList Specific;
3605 public readonly Catch General;
3607 bool need_exc_block;
3610 // specific, general and fini might all be null.
3612 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3614 if (specific == null && general == null){
3615 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3619 this.Specific = specific;
3620 this.General = general;
3625 public override bool Resolve (EmitContext ec)
3629 FlowBranchingException branching = ec.StartFlowBranching (this);
3631 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3633 if (!Block.Resolve (ec))
3636 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3638 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3640 Type[] prevCatches = new Type [Specific.Count];
3642 foreach (Catch c in Specific){
3643 ec.CurrentBranching.CreateSibling (
3644 c.Block, FlowBranching.SiblingType.Catch);
3646 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3648 if (c.Name != null) {
3649 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3651 throw new Exception ();
3653 vi.VariableInfo = null;
3656 if (!c.Resolve (ec))
3659 Type resolvedType = c.CatchType;
3660 for (int ii = 0; ii < last_index; ++ii) {
3661 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3662 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3667 prevCatches [last_index++] = resolvedType;
3668 need_exc_block = true;
3671 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3673 if (General != null){
3674 ec.CurrentBranching.CreateSibling (
3675 General.Block, FlowBranching.SiblingType.Catch);
3677 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3679 if (!General.Resolve (ec))
3682 need_exc_block = true;
3685 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3689 ec.CurrentBranching.CreateSibling (
3690 Fini, FlowBranching.SiblingType.Finally);
3692 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3694 if (!Fini.Resolve (ec))
3698 ResolveFinally (branching);
3699 need_exc_block |= emit_finally;
3701 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3703 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3705 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3707 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3708 // Unfortunately, System.Reflection.Emit automatically emits
3709 // a leave to the end of the finally block. This is a problem
3710 // if `returns' is true since we may jump to a point after the
3711 // end of the method.
3712 // As a workaround, emit an explicit ret here.
3713 ec.NeedReturnLabel ();
3719 protected override void DoEmit (EmitContext ec)
3721 ILGenerator ig = ec.ig;
3724 ig.BeginExceptionBlock ();
3727 foreach (Catch c in Specific){
3730 ig.BeginCatchBlock (c.CatchType);
3732 if (c.Name != null){
3733 vi = c.Block.GetLocalInfo (c.Name);
3735 throw new Exception ("Variable does not exist in this block");
3737 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3739 ig.Emit (OpCodes.Pop);
3744 if (General != null){
3745 ig.BeginCatchBlock (TypeManager.object_type);
3746 ig.Emit (OpCodes.Pop);
3747 General.Block.Emit (ec);
3752 ig.EndExceptionBlock ();
3755 public override void EmitFinally (EmitContext ec)
3763 public class Using : ExceptionStatement {
3764 object expression_or_block;
3765 Statement Statement;
3770 Expression [] resolved_vars;
3771 Expression [] converted_vars;
3772 ExpressionStatement [] assign;
3773 LocalBuilder local_copy;
3775 public Using (object expression_or_block, Statement stmt, Location l)
3777 this.expression_or_block = expression_or_block;
3783 // Resolves for the case of using using a local variable declaration.
3785 bool ResolveLocalVariableDecls (EmitContext ec)
3789 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3793 expr_type = texpr.Type;
3796 // The type must be an IDisposable or an implicit conversion
3799 converted_vars = new Expression [var_list.Count];
3800 resolved_vars = new Expression [var_list.Count];
3801 assign = new ExpressionStatement [var_list.Count];
3803 bool need_conv = !TypeManager.ImplementsInterface (
3804 expr_type, TypeManager.idisposable_type);
3806 foreach (DictionaryEntry e in var_list){
3807 Expression var = (Expression) e.Key;
3809 var = var.ResolveLValue (ec, new EmptyExpression ());
3813 resolved_vars [i] = var;
3820 converted_vars [i] = Convert.ImplicitConversionRequired (
3821 ec, var, TypeManager.idisposable_type, loc);
3823 if (converted_vars [i] == null)
3830 foreach (DictionaryEntry e in var_list){
3831 Expression var = resolved_vars [i];
3832 Expression new_expr = (Expression) e.Value;
3835 a = new Assign (var, new_expr, loc);
3841 converted_vars [i] = var;
3842 assign [i] = (ExpressionStatement) a;
3849 bool ResolveExpression (EmitContext ec)
3851 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3852 conv = Convert.ImplicitConversionRequired (
3853 ec, expr, TypeManager.idisposable_type, loc);
3863 // Emits the code for the case of using using a local variable declaration.
3865 void EmitLocalVariableDecls (EmitContext ec)
3867 ILGenerator ig = ec.ig;
3870 for (i = 0; i < assign.Length; i++) {
3871 assign [i].EmitStatement (ec);
3874 ig.BeginExceptionBlock ();
3876 Statement.Emit (ec);
3878 var_list.Reverse ();
3883 void EmitLocalVariableDeclFinally (EmitContext ec)
3885 ILGenerator ig = ec.ig;
3887 int i = assign.Length;
3888 foreach (DictionaryEntry e in var_list){
3889 Expression var = resolved_vars [--i];
3890 Label skip = ig.DefineLabel ();
3892 ig.BeginFinallyBlock ();
3894 if (!var.Type.IsValueType) {
3896 ig.Emit (OpCodes.Brfalse, skip);
3897 converted_vars [i].Emit (ec);
3898 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3900 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3902 if (!(ml is MethodGroupExpr)) {
3904 ig.Emit (OpCodes.Box, var.Type);
3905 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3907 MethodInfo mi = null;
3909 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3910 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3917 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3921 IMemoryLocation mloc = (IMemoryLocation) var;
3923 mloc.AddressOf (ec, AddressOp.Load);
3924 ig.Emit (OpCodes.Call, mi);
3928 ig.MarkLabel (skip);
3931 ig.EndExceptionBlock ();
3933 ig.BeginFinallyBlock ();
3938 void EmitExpression (EmitContext ec)
3941 // Make a copy of the expression and operate on that.
3943 ILGenerator ig = ec.ig;
3944 local_copy = ig.DeclareLocal (expr_type);
3949 ig.Emit (OpCodes.Stloc, local_copy);
3952 ig.BeginExceptionBlock ();
3954 Statement.Emit (ec);
3958 ig.EndExceptionBlock ();
3961 void EmitExpressionFinally (EmitContext ec)
3963 ILGenerator ig = ec.ig;
3964 if (!local_copy.LocalType.IsValueType) {
3965 Label skip = ig.DefineLabel ();
3966 ig.Emit (OpCodes.Ldloc, local_copy);
3967 ig.Emit (OpCodes.Brfalse, skip);
3968 ig.Emit (OpCodes.Ldloc, local_copy);
3969 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3970 ig.MarkLabel (skip);
3972 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
3974 if (!(ml is MethodGroupExpr)) {
3975 ig.Emit (OpCodes.Ldloc, local_copy);
3976 ig.Emit (OpCodes.Box, local_copy.LocalType);
3977 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3979 MethodInfo mi = null;
3981 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3982 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3989 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3993 ig.Emit (OpCodes.Ldloca, local_copy);
3994 ig.Emit (OpCodes.Call, mi);
3999 public override bool Resolve (EmitContext ec)
4001 if (expression_or_block is DictionaryEntry){
4002 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4003 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4005 if (!ResolveLocalVariableDecls (ec))
4008 } else if (expression_or_block is Expression){
4009 expr = (Expression) expression_or_block;
4011 expr = expr.Resolve (ec);
4015 expr_type = expr.Type;
4017 if (!ResolveExpression (ec))
4021 FlowBranchingException branching = ec.StartFlowBranching (this);
4023 bool ok = Statement.Resolve (ec);
4026 ec.KillFlowBranching ();
4030 ResolveFinally (branching);
4031 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4033 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4034 // Unfortunately, System.Reflection.Emit automatically emits a leave
4035 // to the end of the finally block. This is a problem if `returns'
4036 // is true since we may jump to a point after the end of the method.
4037 // As a workaround, emit an explicit ret here.
4038 ec.NeedReturnLabel ();
4044 protected override void DoEmit (EmitContext ec)
4046 if (expression_or_block is DictionaryEntry)
4047 EmitLocalVariableDecls (ec);
4048 else if (expression_or_block is Expression)
4049 EmitExpression (ec);
4052 public override void EmitFinally (EmitContext ec)
4054 if (expression_or_block is DictionaryEntry)
4055 EmitLocalVariableDeclFinally (ec);
4056 else if (expression_or_block is Expression)
4057 EmitExpressionFinally (ec);
4062 /// Implementation of the foreach C# statement
4064 public class Foreach : ExceptionStatement {
4066 Expression variable;
4068 Statement statement;
4069 ForeachHelperMethods hm;
4070 Expression empty, conv;
4071 Type array_type, element_type;
4073 VariableStorage enumerator;
4075 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4076 Statement stmt, Location l)
4079 this.variable = var;
4085 public override bool Resolve (EmitContext ec)
4087 expr = expr.Resolve (ec);
4091 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4095 var_type = texpr.Type;
4098 // We need an instance variable. Not sure this is the best
4099 // way of doing this.
4101 // FIXME: When we implement propertyaccess, will those turn
4102 // out to return values in ExprClass? I think they should.
4104 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4105 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4106 error1579 (expr.Type);
4110 if (expr.Type.IsArray) {
4111 array_type = expr.Type;
4112 element_type = TypeManager.GetElementType (array_type);
4114 empty = new EmptyExpression (element_type);
4116 hm = ProbeCollectionType (ec, expr.Type);
4118 error1579 (expr.Type);
4122 array_type = expr.Type;
4123 element_type = hm.element_type;
4125 empty = new EmptyExpression (hm.element_type);
4130 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4131 ec.CurrentBranching.CreateSibling ();
4135 // FIXME: maybe we can apply the same trick we do in the
4136 // array handling to avoid creating empty and conv in some cases.
4138 // Although it is not as important in this case, as the type
4139 // will not likely be object (what the enumerator will return).
4141 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4145 variable = variable.ResolveLValue (ec, empty);
4146 if (variable == null)
4149 bool disposable = (hm != null) && hm.is_disposable;
4150 FlowBranchingException branching = null;
4152 branching = ec.StartFlowBranching (this);
4154 if (!statement.Resolve (ec))
4158 ResolveFinally (branching);
4159 ec.EndFlowBranching ();
4161 emit_finally = true;
4163 ec.EndFlowBranching ();
4169 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4171 static MethodInfo FetchMethodMoveNext (Type t)
4173 MemberList move_next_list;
4175 move_next_list = TypeContainer.FindMembers (
4176 t, MemberTypes.Method,
4177 BindingFlags.Public | BindingFlags.Instance,
4178 Type.FilterName, "MoveNext");
4179 if (move_next_list.Count == 0)
4182 foreach (MemberInfo m in move_next_list){
4183 MethodInfo mi = (MethodInfo) m;
4186 args = TypeManager.GetArgumentTypes (mi);
4187 if (args != null && args.Length == 0){
4188 if (TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type)
4196 // Retrieves a `public T get_Current ()' method from the Type `t'
4198 static MethodInfo FetchMethodGetCurrent (Type t)
4200 MemberList get_current_list;
4202 get_current_list = TypeContainer.FindMembers (
4203 t, MemberTypes.Method,
4204 BindingFlags.Public | BindingFlags.Instance,
4205 Type.FilterName, "get_Current");
4206 if (get_current_list.Count == 0)
4209 foreach (MemberInfo m in get_current_list){
4210 MethodInfo mi = (MethodInfo) m;
4213 args = TypeManager.GetArgumentTypes (mi);
4214 if (args != null && args.Length == 0)
4221 // Retrieves a `public void Dispose ()' method from the Type `t'
4223 static MethodInfo FetchMethodDispose (Type t)
4225 MemberList dispose_list;
4227 dispose_list = TypeContainer.FindMembers (
4228 t, MemberTypes.Method,
4229 BindingFlags.Public | BindingFlags.Instance,
4230 Type.FilterName, "Dispose");
4231 if (dispose_list.Count == 0)
4234 foreach (MemberInfo m in dispose_list){
4235 MethodInfo mi = (MethodInfo) m;
4238 args = TypeManager.GetArgumentTypes (mi);
4239 if (args != null && args.Length == 0){
4240 if (mi.ReturnType == TypeManager.void_type)
4248 // This struct records the helper methods used by the Foreach construct
4250 class ForeachHelperMethods {
4251 public EmitContext ec;
4252 public MethodInfo get_enumerator;
4253 public MethodInfo move_next;
4254 public MethodInfo get_current;
4255 public Type element_type;
4256 public Type enumerator_type;
4257 public bool is_disposable;
4259 public ForeachHelperMethods (EmitContext ec)
4262 this.element_type = TypeManager.object_type;
4263 this.enumerator_type = TypeManager.ienumerator_type;
4264 this.is_disposable = true;
4268 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4273 if (!(m is MethodInfo))
4276 if (m.Name != "GetEnumerator")
4279 MethodInfo mi = (MethodInfo) m;
4280 Type [] args = TypeManager.GetArgumentTypes (mi);
4282 if (args.Length != 0)
4285 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4286 EmitContext ec = hm.ec;
4288 // Check whether GetEnumerator is public
4289 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4292 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4294 // Apply the same optimization as MS: skip the GetEnumerator
4295 // returning an IEnumerator, and use the one returning a
4296 // CharEnumerator instead. This allows us to avoid the
4297 // try-finally block and the boxing.
4302 // Ok, we can access it, now make sure that we can do something
4303 // with this `GetEnumerator'
4306 Type return_type = mi.ReturnType;
4307 if (mi.ReturnType == TypeManager.ienumerator_type ||
4308 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4309 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4312 // If it is not an interface, lets try to find the methods ourselves.
4313 // For example, if we have:
4314 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4315 // We can avoid the iface call. This is a runtime perf boost.
4316 // even bigger if we have a ValueType, because we avoid the cost
4319 // We have to make sure that both methods exist for us to take
4320 // this path. If one of the methods does not exist, we will just
4321 // use the interface. Sadly, this complex if statement is the only
4322 // way I could do this without a goto
4325 if (return_type.IsInterface ||
4326 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4327 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4329 hm.move_next = TypeManager.bool_movenext_void;
4330 hm.get_current = TypeManager.object_getcurrent_void;
4337 // Ok, so they dont return an IEnumerable, we will have to
4338 // find if they support the GetEnumerator pattern.
4341 hm.move_next = FetchMethodMoveNext (return_type);
4342 if (hm.move_next == null)
4345 hm.get_current = FetchMethodGetCurrent (return_type);
4346 if (hm.get_current == null)
4350 hm.element_type = hm.get_current.ReturnType;
4351 hm.enumerator_type = return_type;
4352 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4353 TypeManager.ImplementsInterface (
4354 hm.enumerator_type, TypeManager.idisposable_type);
4360 /// This filter is used to find the GetEnumerator method
4361 /// on which IEnumerator operates
4363 static MemberFilter FilterEnumerator;
4367 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4370 void error1579 (Type t)
4372 Report.Error (1579, loc,
4373 "foreach statement cannot operate on variables of type `" +
4374 t.FullName + "' because that class does not provide a " +
4375 " GetEnumerator method or it is inaccessible");
4378 static bool TryType (Type t, ForeachHelperMethods hm)
4382 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4383 BindingFlags.Public | BindingFlags.NonPublic |
4384 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4385 FilterEnumerator, hm);
4390 hm.get_enumerator = (MethodInfo) mi [0];
4395 // Looks for a usable GetEnumerator in the Type, and if found returns
4396 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4398 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4400 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4402 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4403 if (TryType (tt, hm))
4409 // Now try to find the method in the interfaces
4412 Type [] ifaces = t.GetInterfaces ();
4414 foreach (Type i in ifaces){
4415 if (TryType (i, hm))
4420 // Since TypeBuilder.GetInterfaces only returns the interface
4421 // types for this type, we have to keep looping, but once
4422 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4423 // done, because it returns all the types
4425 if ((t is TypeBuilder))
4435 // FIXME: possible optimization.
4436 // We might be able to avoid creating `empty' if the type is the sam
4438 bool EmitCollectionForeach (EmitContext ec)
4440 ILGenerator ig = ec.ig;
4442 enumerator = new VariableStorage (ec, hm.enumerator_type);
4443 enumerator.EmitThis (ig);
4445 // Instantiate the enumerator
4447 if (expr.Type.IsValueType){
4448 IMemoryLocation ml = expr as IMemoryLocation;
4449 // Load the address of the value type.
4451 // This happens if, for example, you have a property
4452 // returning a struct which is IEnumerable
4453 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4455 ig.Emit (OpCodes.Stloc, t);
4456 ig.Emit (OpCodes.Ldloca, t);
4457 ec.FreeTemporaryLocal (t, expr.Type);
4459 ml.AddressOf (ec, AddressOp.Load);
4463 if (hm.get_enumerator.DeclaringType.IsValueType) {
4464 // the method is declared on the value type
4465 ig.Emit (OpCodes.Call, hm.get_enumerator);
4467 // it is an interface method, so we must box
4468 ig.Emit (OpCodes.Box, expr.Type);
4469 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4473 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4475 enumerator.EmitStore (ig);
4478 // Protect the code in a try/finalize block, so that
4479 // if the beast implement IDisposable, we get rid of it
4481 if (hm.is_disposable && emit_finally)
4482 ig.BeginExceptionBlock ();
4484 Label end_try = ig.DefineLabel ();
4486 ig.MarkLabel (ec.LoopBegin);
4488 enumerator.EmitCall (ig, hm.move_next);
4490 ig.Emit (OpCodes.Brfalse, end_try);
4493 enumerator.EmitThis (ig);
4494 enumerator.EmitCall (ig, hm.get_current);
4498 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4500 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4502 statement.Emit (ec);
4503 ig.Emit (OpCodes.Br, ec.LoopBegin);
4504 ig.MarkLabel (end_try);
4506 // The runtime provides this for us.
4507 // ig.Emit (OpCodes.Leave, end);
4510 // Now the finally block
4512 if (hm.is_disposable) {
4515 ig.EndExceptionBlock ();
4518 ig.MarkLabel (ec.LoopEnd);
4522 public override void EmitFinally (EmitContext ec)
4524 ILGenerator ig = ec.ig;
4526 if (hm.enumerator_type.IsValueType) {
4527 enumerator.EmitThis (ig);
4529 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4531 enumerator.EmitLoadAddress (ig);
4532 ig.Emit (OpCodes.Call, mi);
4534 enumerator.EmitLoad (ig);
4535 ig.Emit (OpCodes.Box, hm.enumerator_type);
4536 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4539 Label call_dispose = ig.DefineLabel ();
4541 enumerator.EmitThis (ig);
4542 enumerator.EmitLoad (ig);
4543 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4544 ig.Emit (OpCodes.Dup);
4545 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4546 ig.Emit (OpCodes.Pop);
4548 Label end_finally = ig.DefineLabel ();
4549 ig.Emit (OpCodes.Br, end_finally);
4551 ig.MarkLabel (call_dispose);
4552 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4553 ig.MarkLabel (end_finally);
4556 ig.Emit (OpCodes.Endfinally);
4561 // FIXME: possible optimization.
4562 // We might be able to avoid creating `empty' if the type is the sam
4564 bool EmitArrayForeach (EmitContext ec)
4566 int rank = array_type.GetArrayRank ();
4567 ILGenerator ig = ec.ig;
4569 VariableStorage copy = new VariableStorage (ec, array_type);
4572 // Make our copy of the array
4576 copy.EmitStore (ig);
4579 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4583 counter.EmitThis (ig);
4584 ig.Emit (OpCodes.Ldc_I4_0);
4585 counter.EmitStore (ig);
4586 test = ig.DefineLabel ();
4587 ig.Emit (OpCodes.Br, test);
4589 loop = ig.DefineLabel ();
4590 ig.MarkLabel (loop);
4597 counter.EmitThis (ig);
4598 counter.EmitLoad (ig);
4601 // Load the value, we load the value using the underlying type,
4602 // then we use the variable.EmitAssign to load using the proper cast.
4604 ArrayAccess.EmitLoadOpcode (ig, element_type);
4607 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4609 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4611 statement.Emit (ec);
4613 ig.MarkLabel (ec.LoopBegin);
4614 counter.EmitThis (ig);
4615 counter.EmitThis (ig);
4616 counter.EmitLoad (ig);
4617 ig.Emit (OpCodes.Ldc_I4_1);
4618 ig.Emit (OpCodes.Add);
4619 counter.EmitStore (ig);
4621 ig.MarkLabel (test);
4622 counter.EmitThis (ig);
4623 counter.EmitLoad (ig);
4626 ig.Emit (OpCodes.Ldlen);
4627 ig.Emit (OpCodes.Conv_I4);
4628 ig.Emit (OpCodes.Blt, loop);
4630 VariableStorage [] dim_len = new VariableStorage [rank];
4631 VariableStorage [] dim_count = new VariableStorage [rank];
4632 Label [] loop = new Label [rank];
4633 Label [] test = new Label [rank];
4636 for (dim = 0; dim < rank; dim++){
4637 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4638 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4639 test [dim] = ig.DefineLabel ();
4640 loop [dim] = ig.DefineLabel ();
4643 for (dim = 0; dim < rank; dim++){
4644 dim_len [dim].EmitThis (ig);
4647 IntLiteral.EmitInt (ig, dim);
4648 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4649 dim_len [dim].EmitStore (ig);
4653 for (dim = 0; dim < rank; dim++){
4654 dim_count [dim].EmitThis (ig);
4655 ig.Emit (OpCodes.Ldc_I4_0);
4656 dim_count [dim].EmitStore (ig);
4657 ig.Emit (OpCodes.Br, test [dim]);
4658 ig.MarkLabel (loop [dim]);
4665 for (dim = 0; dim < rank; dim++){
4666 dim_count [dim].EmitThis (ig);
4667 dim_count [dim].EmitLoad (ig);
4671 // FIXME: Maybe we can cache the computation of `get'?
4673 Type [] args = new Type [rank];
4676 for (int i = 0; i < rank; i++)
4677 args [i] = TypeManager.int32_type;
4679 ModuleBuilder mb = CodeGen.Module.Builder;
4680 get = mb.GetArrayMethod (
4682 CallingConventions.HasThis| CallingConventions.Standard,
4684 ig.Emit (OpCodes.Call, get);
4687 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4689 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4690 statement.Emit (ec);
4691 ig.MarkLabel (ec.LoopBegin);
4692 for (dim = rank - 1; dim >= 0; dim--){
4693 dim_count [dim].EmitThis (ig);
4694 dim_count [dim].EmitThis (ig);
4695 dim_count [dim].EmitLoad (ig);
4696 ig.Emit (OpCodes.Ldc_I4_1);
4697 ig.Emit (OpCodes.Add);
4698 dim_count [dim].EmitStore (ig);
4700 ig.MarkLabel (test [dim]);
4701 dim_count [dim].EmitThis (ig);
4702 dim_count [dim].EmitLoad (ig);
4703 dim_len [dim].EmitThis (ig);
4704 dim_len [dim].EmitLoad (ig);
4705 ig.Emit (OpCodes.Blt, loop [dim]);
4708 ig.MarkLabel (ec.LoopEnd);
4713 protected override void DoEmit (EmitContext ec)
4715 ILGenerator ig = ec.ig;
4717 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4718 ec.LoopBegin = ig.DefineLabel ();
4719 ec.LoopEnd = ig.DefineLabel ();
4722 EmitCollectionForeach (ec);
4724 EmitArrayForeach (ec);
4726 ec.LoopBegin = old_begin;
4727 ec.LoopEnd = old_end;