2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@ximian.com)
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 if (warn && (RootContext.WarningLevel >= 2))
50 Report.Warning (162, loc, "Unreachable code detected");
52 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
53 bool ok = Resolve (ec);
54 ec.KillFlowBranching ();
59 protected void CheckObsolete (Type type)
61 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
62 if (obsolete_attr == null)
65 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
69 /// Return value indicates whether all code paths emitted return.
71 protected abstract void DoEmit (EmitContext ec);
74 /// Utility wrapper routine for Error, just to beautify the code
76 public void Error (int error, string format, params object[] args)
78 Error (error, String.Format (format, args));
81 public void Error (int error, string s)
83 if (!Location.IsNull (loc))
84 Report.Error (error, loc, s);
86 Report.Error (error, s);
90 /// Return value indicates whether all code paths emitted return.
92 public virtual void Emit (EmitContext ec)
99 public sealed class EmptyStatement : Statement {
101 private EmptyStatement () {}
103 public static readonly EmptyStatement Value = new EmptyStatement ();
105 public override bool Resolve (EmitContext ec)
110 protected override void DoEmit (EmitContext ec)
115 public class If : Statement {
117 public Statement TrueStatement;
118 public Statement FalseStatement;
122 public If (Expression expr, Statement trueStatement, Location l)
125 TrueStatement = trueStatement;
129 public If (Expression expr,
130 Statement trueStatement,
131 Statement falseStatement,
135 TrueStatement = trueStatement;
136 FalseStatement = falseStatement;
140 public override bool Resolve (EmitContext ec)
142 Report.Debug (1, "START IF BLOCK", loc);
144 expr = Expression.ResolveBoolean (ec, expr, loc);
149 Assign ass = expr as Assign;
150 if (ass != null && ass.Source is Constant) {
151 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
155 // Dead code elimination
157 if (expr is BoolConstant){
158 bool take = ((BoolConstant) expr).Value;
161 if (!TrueStatement.Resolve (ec))
164 if ((FalseStatement != null) &&
165 !FalseStatement.ResolveUnreachable (ec, true))
167 FalseStatement = null;
169 if (!TrueStatement.ResolveUnreachable (ec, true))
171 TrueStatement = null;
173 if ((FalseStatement != null) &&
174 !FalseStatement.Resolve (ec))
181 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
183 bool ok = TrueStatement.Resolve (ec);
185 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
187 ec.CurrentBranching.CreateSibling ();
189 if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
192 ec.EndFlowBranching ();
194 Report.Debug (1, "END IF BLOCK", loc);
199 protected override void DoEmit (EmitContext ec)
201 ILGenerator ig = ec.ig;
202 Label false_target = ig.DefineLabel ();
206 // If we're a boolean expression, Resolve() already
207 // eliminated dead code for us.
209 if (expr is BoolConstant){
210 bool take = ((BoolConstant) expr).Value;
213 TrueStatement.Emit (ec);
214 else if (FalseStatement != null)
215 FalseStatement.Emit (ec);
220 expr.EmitBranchable (ec, false_target, false);
222 TrueStatement.Emit (ec);
224 if (FalseStatement != null){
225 bool branch_emitted = false;
227 end = ig.DefineLabel ();
229 ig.Emit (OpCodes.Br, end);
230 branch_emitted = true;
233 ig.MarkLabel (false_target);
234 FalseStatement.Emit (ec);
239 ig.MarkLabel (false_target);
244 public class Do : Statement {
245 public Expression expr;
246 public readonly Statement EmbeddedStatement;
249 public Do (Statement statement, Expression boolExpr, Location l)
252 EmbeddedStatement = statement;
256 public override bool Resolve (EmitContext ec)
260 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
262 if (!EmbeddedStatement.Resolve (ec))
265 expr = Expression.ResolveBoolean (ec, expr, loc);
268 else if (expr is BoolConstant){
269 bool res = ((BoolConstant) expr).Value;
275 ec.CurrentBranching.Infinite = infinite;
276 ec.EndFlowBranching ();
281 protected override void DoEmit (EmitContext ec)
283 ILGenerator ig = ec.ig;
284 Label loop = ig.DefineLabel ();
285 Label old_begin = ec.LoopBegin;
286 Label old_end = ec.LoopEnd;
288 ec.LoopBegin = ig.DefineLabel ();
289 ec.LoopEnd = ig.DefineLabel ();
292 EmbeddedStatement.Emit (ec);
293 ig.MarkLabel (ec.LoopBegin);
296 // Dead code elimination
298 if (expr is BoolConstant){
299 bool res = ((BoolConstant) expr).Value;
302 ec.ig.Emit (OpCodes.Br, loop);
304 expr.EmitBranchable (ec, loop, true);
306 ig.MarkLabel (ec.LoopEnd);
308 ec.LoopBegin = old_begin;
309 ec.LoopEnd = old_end;
313 public class While : Statement {
314 public Expression expr;
315 public readonly Statement Statement;
316 bool infinite, empty;
318 public While (Expression boolExpr, Statement statement, Location l)
320 this.expr = boolExpr;
321 Statement = statement;
325 public override bool Resolve (EmitContext ec)
329 expr = Expression.ResolveBoolean (ec, expr, loc);
334 // Inform whether we are infinite or not
336 if (expr is BoolConstant){
337 BoolConstant bc = (BoolConstant) expr;
339 if (bc.Value == false){
340 if (!Statement.ResolveUnreachable (ec, true))
348 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
350 if (!Statement.Resolve (ec))
353 ec.CurrentBranching.Infinite = infinite;
354 ec.EndFlowBranching ();
359 protected override void DoEmit (EmitContext ec)
364 ILGenerator ig = ec.ig;
365 Label old_begin = ec.LoopBegin;
366 Label old_end = ec.LoopEnd;
368 ec.LoopBegin = ig.DefineLabel ();
369 ec.LoopEnd = ig.DefineLabel ();
372 // Inform whether we are infinite or not
374 if (expr is BoolConstant){
375 ig.MarkLabel (ec.LoopBegin);
377 ig.Emit (OpCodes.Br, ec.LoopBegin);
380 // Inform that we are infinite (ie, `we return'), only
381 // if we do not `break' inside the code.
383 ig.MarkLabel (ec.LoopEnd);
385 Label while_loop = ig.DefineLabel ();
387 ig.Emit (OpCodes.Br, ec.LoopBegin);
388 ig.MarkLabel (while_loop);
392 ig.MarkLabel (ec.LoopBegin);
394 expr.EmitBranchable (ec, while_loop, true);
396 ig.MarkLabel (ec.LoopEnd);
399 ec.LoopBegin = old_begin;
400 ec.LoopEnd = old_end;
404 public class For : Statement {
406 readonly Statement InitStatement;
407 readonly Statement Increment;
408 readonly Statement Statement;
409 bool infinite, empty;
411 public For (Statement initStatement,
417 InitStatement = initStatement;
419 Increment = increment;
420 Statement = statement;
424 public override bool Resolve (EmitContext ec)
428 if (InitStatement != null){
429 if (!InitStatement.Resolve (ec))
434 Test = Expression.ResolveBoolean (ec, Test, loc);
437 else if (Test is BoolConstant){
438 BoolConstant bc = (BoolConstant) Test;
440 if (bc.Value == false){
441 if (!Statement.ResolveUnreachable (ec, true))
443 if ((Increment != null) &&
444 !Increment.ResolveUnreachable (ec, false))
454 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
456 ec.CurrentBranching.CreateSibling ();
458 if (!Statement.Resolve (ec))
461 if (Increment != null){
462 if (!Increment.Resolve (ec))
466 ec.CurrentBranching.Infinite = infinite;
467 ec.EndFlowBranching ();
472 protected override void DoEmit (EmitContext ec)
477 ILGenerator ig = ec.ig;
478 Label old_begin = ec.LoopBegin;
479 Label old_end = ec.LoopEnd;
480 Label loop = ig.DefineLabel ();
481 Label test = ig.DefineLabel ();
483 if (InitStatement != null && InitStatement != EmptyStatement.Value)
484 InitStatement.Emit (ec);
486 ec.LoopBegin = ig.DefineLabel ();
487 ec.LoopEnd = ig.DefineLabel ();
489 ig.Emit (OpCodes.Br, test);
493 ig.MarkLabel (ec.LoopBegin);
494 if (Increment != EmptyStatement.Value)
499 // If test is null, there is no test, and we are just
504 // The Resolve code already catches the case for
505 // Test == BoolConstant (false) so we know that
508 if (Test is BoolConstant)
509 ig.Emit (OpCodes.Br, loop);
511 Test.EmitBranchable (ec, loop, true);
514 ig.Emit (OpCodes.Br, loop);
515 ig.MarkLabel (ec.LoopEnd);
517 ec.LoopBegin = old_begin;
518 ec.LoopEnd = old_end;
522 public class StatementExpression : Statement {
523 ExpressionStatement expr;
525 public StatementExpression (ExpressionStatement expr, Location l)
531 public override bool Resolve (EmitContext ec)
533 expr = expr.ResolveStatement (ec);
537 protected override void DoEmit (EmitContext ec)
539 expr.EmitStatement (ec);
542 public override string ToString ()
544 return "StatementExpression (" + expr + ")";
549 /// Implements the return statement
551 public class Return : Statement {
552 public Expression Expr;
554 public Return (Expression expr, Location l)
562 public override bool Resolve (EmitContext ec)
564 if (ec.ReturnType == null){
566 if (ec.CurrentAnonymousMethod != null){
567 Report.Error (1662, loc, String.Format (
568 "Anonymous method could not be converted to delegate " +
569 "since the return value does not match the delegate value"));
571 Error (127, "Return with a value not allowed here");
576 Error (126, "An object of type `{0}' is expected " +
577 "for the return statement",
578 TypeManager.CSharpName (ec.ReturnType));
582 Expr = Expr.Resolve (ec);
586 if (Expr.Type != ec.ReturnType) {
587 Expr = Convert.ImplicitConversionRequired (
588 ec, Expr, ec.ReturnType, loc);
595 Error (-206, "Return statement not allowed inside iterators");
599 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
601 if (ec.CurrentBranching.InTryOrCatch (true)) {
602 ec.CurrentBranching.AddFinallyVector (vector);
604 } else if (ec.CurrentBranching.InFinally (true)) {
605 Error (157, "Control can not leave the body of the finally block");
608 vector.CheckOutParameters (ec.CurrentBranching);
611 ec.NeedReturnLabel ();
613 ec.CurrentBranching.CurrentUsageVector.Return ();
617 protected override void DoEmit (EmitContext ec)
623 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
627 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
629 ec.ig.Emit (OpCodes.Ret);
633 public class Goto : Statement {
636 LabeledStatement label;
638 public override bool Resolve (EmitContext ec)
640 label = ec.CurrentBranching.LookupLabel (target, loc);
644 // If this is a forward goto.
645 if (!label.IsDefined)
646 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
648 ec.CurrentBranching.CurrentUsageVector.Goto ();
653 public Goto (Block parent_block, string label, Location l)
655 block = parent_block;
660 public string Target {
666 protected override void DoEmit (EmitContext ec)
668 Label l = label.LabelTarget (ec);
669 ec.ig.Emit (OpCodes.Br, l);
673 public class LabeledStatement : Statement {
674 public readonly Location Location;
679 FlowBranching.UsageVector vectors;
681 public LabeledStatement (string label_name, Location l)
686 public Label LabelTarget (EmitContext ec)
690 label = ec.ig.DefineLabel ();
696 public bool IsDefined {
702 public bool HasBeenReferenced {
708 public void AddUsageVector (FlowBranching.UsageVector vector)
710 vector = vector.Clone ();
711 vector.Next = vectors;
715 public override bool Resolve (EmitContext ec)
717 ec.CurrentBranching.Label (vectors);
724 protected override void DoEmit (EmitContext ec)
727 ec.ig.MarkLabel (label);
733 /// `goto default' statement
735 public class GotoDefault : Statement {
737 public GotoDefault (Location l)
742 public override bool Resolve (EmitContext ec)
744 ec.CurrentBranching.CurrentUsageVector.Goto ();
748 protected override void DoEmit (EmitContext ec)
750 if (ec.Switch == null){
751 Report.Error (153, loc, "goto default is only valid in a switch statement");
755 if (!ec.Switch.GotDefault){
756 Report.Error (159, loc, "No default target on switch statement");
759 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
764 /// `goto case' statement
766 public class GotoCase : Statement {
770 public GotoCase (Expression e, Location l)
776 public override bool Resolve (EmitContext ec)
778 if (ec.Switch == null){
779 Report.Error (153, loc, "goto case is only valid in a switch statement");
783 expr = expr.Resolve (ec);
787 if (!(expr is Constant)){
788 Report.Error (159, loc, "Target expression for goto case is not constant");
792 object val = Expression.ConvertIntLiteral (
793 (Constant) expr, ec.Switch.SwitchType, loc);
798 sl = (SwitchLabel) ec.Switch.Elements [val];
803 "No such label 'case " + val + "': for the goto case");
807 ec.CurrentBranching.CurrentUsageVector.Goto ();
811 protected override void DoEmit (EmitContext ec)
813 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
817 public class Throw : Statement {
820 public Throw (Expression expr, Location l)
826 public override bool Resolve (EmitContext ec)
828 ec.CurrentBranching.CurrentUsageVector.Throw ();
831 expr = expr.Resolve (ec);
835 ExprClass eclass = expr.eclass;
837 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
838 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
839 expr.Error_UnexpectedKind ("value, variable, property or indexer access ", loc);
845 if ((t != TypeManager.exception_type) &&
846 !t.IsSubclassOf (TypeManager.exception_type) &&
847 !(expr is NullLiteral)) {
849 "The type caught or thrown must be derived " +
850 "from System.Exception");
856 if (ec.CurrentBranching.InFinally (true)) {
857 Error (724, "A throw statement with no argument is only allowed in a catch clause nested inside of the innermost catch clause");
861 if (!ec.CurrentBranching.InCatch ()) {
862 Error (156, "A throw statement with no argument is only allowed in a catch clause");
868 protected override void DoEmit (EmitContext ec)
871 ec.ig.Emit (OpCodes.Rethrow);
875 ec.ig.Emit (OpCodes.Throw);
880 public class Break : Statement {
882 public Break (Location l)
889 public override bool Resolve (EmitContext ec)
891 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
892 Error (139, "No enclosing loop or switch to continue to");
894 } else if (ec.CurrentBranching.InFinally (false)) {
895 Error (157, "Control can not leave the body of the finally block");
897 } else if (ec.CurrentBranching.InTryOrCatch (false))
898 ec.CurrentBranching.AddFinallyVector (
899 ec.CurrentBranching.CurrentUsageVector);
900 else if (ec.CurrentBranching.InLoop ())
901 ec.CurrentBranching.AddBreakVector (
902 ec.CurrentBranching.CurrentUsageVector);
904 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
907 ec.NeedReturnLabel ();
909 ec.CurrentBranching.CurrentUsageVector.Break ();
913 protected override void DoEmit (EmitContext ec)
915 ILGenerator ig = ec.ig;
918 ig.Emit (OpCodes.Leave, ec.LoopEnd);
920 ig.Emit (OpCodes.Br, ec.LoopEnd);
925 public class Continue : Statement {
927 public Continue (Location l)
934 public override bool Resolve (EmitContext ec)
936 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
937 Error (139, "No enclosing loop to continue to");
939 } else if (ec.CurrentBranching.InFinally (false)) {
940 Error (157, "Control can not leave the body of the finally block");
942 } else if (ec.CurrentBranching.InTryOrCatch (false))
943 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
945 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
947 ec.CurrentBranching.CurrentUsageVector.Goto ();
951 protected override void DoEmit (EmitContext ec)
953 Label begin = ec.LoopBegin;
956 ec.ig.Emit (OpCodes.Leave, begin);
958 ec.ig.Emit (OpCodes.Br, begin);
963 // The information about a user-perceived local variable
965 public class LocalInfo {
966 public Expression Type;
969 // Most of the time a variable will be stored in a LocalBuilder
971 // But sometimes, it will be stored in a field (variables that have been
972 // hoisted by iterators or by anonymous methods). The context of the field will
973 // be stored in the EmitContext
976 public LocalBuilder LocalBuilder;
977 public FieldBuilder FieldBuilder;
979 public Type VariableType;
980 public readonly string Name;
981 public readonly Location Location;
982 public readonly Block Block;
984 public VariableInfo VariableInfo;
997 public LocalInfo (Expression type, string name, Block block, Location l)
1005 public LocalInfo (TypeContainer tc, Block block, Location l)
1007 VariableType = tc.TypeBuilder;
1012 public bool IsThisAssigned (EmitContext ec, Location loc)
1014 if (VariableInfo == null)
1015 throw new Exception ();
1017 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1020 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1023 public bool IsAssigned (EmitContext ec)
1025 if (VariableInfo == null)
1026 throw new Exception ();
1028 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1031 public bool Resolve (EmitContext ec)
1033 if (VariableType == null) {
1034 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
1038 VariableType = texpr.Type;
1041 if (VariableType == TypeManager.void_type) {
1042 Report.Error (1547, Location,
1043 "Keyword 'void' cannot be used in this context");
1047 if (VariableType.IsAbstract && VariableType.IsSealed) {
1048 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1051 // TODO: breaks the build
1052 // if (VariableType.IsPointer && !ec.InUnsafe)
1053 // Expression.UnsafeError (Location);
1059 // Whether the variable is Fixed (because its Pinned or its a value type)
1061 public bool IsFixed {
1063 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1070 public bool IsCaptured {
1072 return (flags & Flags.Captured) != 0;
1076 flags |= Flags.Captured;
1080 public bool AddressTaken {
1082 return (flags & Flags.AddressTaken) != 0;
1086 flags |= Flags.AddressTaken;
1090 public override string ToString ()
1092 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1093 Name, Type, VariableInfo, Location);
1098 return (flags & Flags.Used) != 0;
1101 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1105 public bool ReadOnly {
1107 return (flags & Flags.ReadOnly) != 0;
1110 flags = value ? (flags | Flags.ReadOnly) : (unchecked (flags & ~Flags.ReadOnly));
1115 // Whether the variable is pinned, if Pinned the variable has been
1116 // allocated in a pinned slot with DeclareLocal.
1118 public bool Pinned {
1120 return (flags & Flags.Pinned) != 0;
1123 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1127 public bool IsThis {
1129 return (flags & Flags.IsThis) != 0;
1132 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1138 /// Block represents a C# block.
1142 /// This class is used in a number of places: either to represent
1143 /// explicit blocks that the programmer places or implicit blocks.
1145 /// Implicit blocks are used as labels or to introduce variable
1148 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1149 /// they contain extra information that is not necessary on normal blocks.
1151 public class Block : Statement {
1152 public Block Parent;
1153 public readonly Location StartLocation;
1154 public Location EndLocation = Location.Null;
1161 VariablesInitialized = 8,
1170 public bool Implicit {
1172 return (flags & Flags.Implicit) != 0;
1176 public bool Unchecked {
1178 return (flags & Flags.Unchecked) != 0;
1181 flags |= Flags.Unchecked;
1185 public bool Unsafe {
1187 return (flags & Flags.Unsafe) != 0;
1190 flags |= Flags.Unsafe;
1194 public bool HasVarargs {
1197 return Parent.HasVarargs;
1199 return (flags & Flags.HasVarargs) != 0;
1202 flags |= Flags.HasVarargs;
1207 // The statements in this block
1209 ArrayList statements;
1213 // An array of Blocks. We keep track of children just
1214 // to generate the local variable declarations.
1216 // Statements and child statements are handled through the
1222 // Labels. (label, block) pairs.
1227 // Keeps track of (name, type) pairs
1229 Hashtable variables;
1232 // Keeps track of constants
1233 Hashtable constants;
1236 // The parameters for the block, this is only needed on the toplevel block really
1237 // TODO: move `parameters' into ToplevelBlock
1238 Parameters parameters;
1241 // If this is a switch section, the enclosing switch block.
1245 protected static int id;
1249 public Block (Block parent)
1250 : this (parent, (Flags) 0, Location.Null, Location.Null)
1253 public Block (Block parent, Flags flags)
1254 : this (parent, flags, Location.Null, Location.Null)
1257 public Block (Block parent, Flags flags, Parameters parameters)
1258 : this (parent, flags, parameters, Location.Null, Location.Null)
1261 public Block (Block parent, Location start, Location end)
1262 : this (parent, (Flags) 0, start, end)
1265 public Block (Block parent, Parameters parameters, Location start, Location end)
1266 : this (parent, (Flags) 0, parameters, start, end)
1269 public Block (Block parent, Flags flags, Location start, Location end)
1270 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1273 public Block (Block parent, Flags flags, Parameters parameters,
1274 Location start, Location end)
1277 parent.AddChild (this);
1279 this.Parent = parent;
1281 this.parameters = parameters;
1282 this.StartLocation = start;
1283 this.EndLocation = end;
1286 statements = new ArrayList ();
1288 if (parent != null && Implicit) {
1289 if (parent.child_variable_names == null)
1290 parent.child_variable_names = new Hashtable();
1291 // share with parent
1292 child_variable_names = parent.child_variable_names;
1297 public Block CreateSwitchBlock (Location start)
1299 Block new_block = new Block (this, start, start);
1300 new_block.switch_block = this;
1310 void AddChild (Block b)
1312 if (children == null)
1313 children = new ArrayList ();
1318 public void SetEndLocation (Location loc)
1324 /// Adds a label to the current block.
1328 /// false if the name already exists in this block. true
1332 public bool AddLabel (string name, LabeledStatement target, Location loc)
1334 if (switch_block != null)
1335 return switch_block.AddLabel (name, target, loc);
1338 while (cur != null) {
1339 if (cur.DoLookupLabel (name) != null) {
1341 140, loc, "The label '{0}' is a duplicate",
1352 while (cur != null) {
1353 if (cur.DoLookupLabel (name) != null) {
1356 "The label '{0}' shadows another label " +
1357 "by the same name in a containing scope.",
1362 if (children != null) {
1363 foreach (Block b in children) {
1364 LabeledStatement s = b.DoLookupLabel (name);
1370 "The label '{0}' shadows another " +
1371 "label by the same name in a " +
1372 "containing scope.",
1383 labels = new Hashtable ();
1385 labels.Add (name, target);
1389 public LabeledStatement LookupLabel (string name)
1391 LabeledStatement s = DoLookupLabel (name);
1395 if (children == null)
1398 foreach (Block child in children) {
1399 if (!child.Implicit)
1402 s = child.LookupLabel (name);
1410 LabeledStatement DoLookupLabel (string name)
1412 if (switch_block != null)
1413 return switch_block.LookupLabel (name);
1416 if (labels.Contains (name))
1417 return ((LabeledStatement) labels [name]);
1422 LocalInfo this_variable = null;
1425 // Returns the "this" instance variable of this block.
1426 // See AddThisVariable() for more information.
1428 public LocalInfo ThisVariable {
1430 if (this_variable != null)
1431 return this_variable;
1432 else if (Parent != null)
1433 return Parent.ThisVariable;
1439 Hashtable child_variable_names;
1442 // Marks a variable with name @name as being used in a child block.
1443 // If a variable name has been used in a child block, it's illegal to
1444 // declare a variable with the same name in the current block.
1446 public void AddChildVariableName (string name)
1448 if (child_variable_names == null)
1449 child_variable_names = new Hashtable ();
1451 child_variable_names [name] = null;
1455 // Checks whether a variable name has already been used in a child block.
1457 public bool IsVariableNameUsedInChildBlock (string name)
1459 if (child_variable_names == null)
1462 return child_variable_names.Contains (name);
1466 // This is used by non-static `struct' constructors which do not have an
1467 // initializer - in this case, the constructor must initialize all of the
1468 // struct's fields. To do this, we add a "this" variable and use the flow
1469 // analysis code to ensure that it's been fully initialized before control
1470 // leaves the constructor.
1472 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1474 if (this_variable != null)
1475 return this_variable;
1477 if (variables == null)
1478 variables = new Hashtable ();
1480 this_variable = new LocalInfo (tc, this, l);
1481 this_variable.Used = true;
1482 this_variable.IsThis = true;
1484 variables.Add ("this", this_variable);
1486 return this_variable;
1489 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1491 if (variables == null)
1492 variables = new Hashtable ();
1494 LocalInfo vi = GetLocalInfo (name);
1496 if (vi.Block != this)
1497 Report.Error (136, l, "A local variable named `" + name + "' " +
1498 "cannot be declared in this scope since it would " +
1499 "give a different meaning to `" + name + "', which " +
1500 "is already used in a `parent or current' scope to " +
1501 "denote something else");
1503 Report.Error (128, l, "A local variable `" + name + "' is already " +
1504 "defined in this scope");
1508 if (IsVariableNameUsedInChildBlock (name)) {
1509 Report.Error (136, l, "A local variable named `" + name + "' " +
1510 "cannot be declared in this scope since it would " +
1511 "give a different meaning to `" + name + "', which " +
1512 "is already used in a `child' scope to denote something " +
1519 Parameter p = pars.GetParameterByName (name, out idx);
1521 Report.Error (136, l, "A local variable named `" + name + "' " +
1522 "cannot be declared in this scope since it would " +
1523 "give a different meaning to `" + name + "', which " +
1524 "is already used in a `parent or current' scope to " +
1525 "denote something else");
1530 vi = new LocalInfo (type, name, this, l);
1532 variables.Add (name, vi);
1534 // Mark 'name' as "used by a child block" in every surrounding block
1536 while (cur != null && cur.Implicit)
1539 for (Block par = cur.Parent; par != null; par = par.Parent)
1540 par.AddChildVariableName (name);
1542 if ((flags & Flags.VariablesInitialized) != 0)
1543 throw new Exception ();
1545 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1549 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1551 if (AddVariable (type, name, pars, l) == null)
1554 if (constants == null)
1555 constants = new Hashtable ();
1557 constants.Add (name, value);
1561 public Hashtable Variables {
1567 public LocalInfo GetLocalInfo (string name)
1569 for (Block b = this; b != null; b = b.Parent) {
1570 if (b.variables != null) {
1571 LocalInfo ret = b.variables [name] as LocalInfo;
1579 public Expression GetVariableType (string name)
1581 LocalInfo vi = GetLocalInfo (name);
1589 public Expression GetConstantExpression (string name)
1591 for (Block b = this; b != null; b = b.Parent) {
1592 if (b.constants != null) {
1593 Expression ret = b.constants [name] as Expression;
1602 /// True if the variable named @name is a constant
1604 public bool IsConstant (string name)
1606 Expression e = null;
1608 e = GetConstantExpression (name);
1614 // Returns a `ParameterReference' for the given name, or null if there
1615 // is no such parameter
1617 public ParameterReference GetParameterReference (string name, Location loc)
1622 Parameters pars = b.parameters;
1628 par = pars.GetParameterByName (name, out idx);
1630 ParameterReference pr;
1632 pr = new ParameterReference (pars, this, idx, name, loc);
1637 } while (b != null);
1642 // Whether the parameter named `name' is local to this block,
1643 // or false, if the parameter belongs to an encompassing block.
1645 public bool IsLocalParameter (string name)
1648 int toplevel_count = 0;
1651 if (this is ToplevelBlock)
1654 Parameters pars = b.parameters;
1656 if (pars.GetParameterByName (name) != null)
1660 if (toplevel_count > 0)
1663 } while (b != null);
1668 // Whether the `name' is a parameter reference
1670 public bool IsParameterReference (string name)
1675 Parameters pars = b.parameters;
1678 if (pars.GetParameterByName (name) != null)
1681 } while (b != null);
1686 /// A list of labels that were not used within this block
1688 public string [] GetUnreferenced ()
1690 // FIXME: Implement me
1694 public void AddStatement (Statement s)
1697 flags |= Flags.BlockUsed;
1702 return (flags & Flags.BlockUsed) != 0;
1708 flags |= Flags.BlockUsed;
1711 public bool HasRet {
1713 return (flags & Flags.HasRet) != 0;
1717 public bool IsDestructor {
1719 return (flags & Flags.IsDestructor) != 0;
1723 public void SetDestructor ()
1725 flags |= Flags.IsDestructor;
1728 VariableMap param_map, local_map;
1730 public VariableMap ParameterMap {
1732 if ((flags & Flags.VariablesInitialized) == 0)
1733 throw new Exception ("Variables have not been initialized yet");
1739 public VariableMap LocalMap {
1741 if ((flags & Flags.VariablesInitialized) == 0)
1742 throw new Exception ("Variables have not been initialized yet");
1749 /// Emits the variable declarations and labels.
1752 /// tc: is our typecontainer (to resolve type references)
1753 /// ig: is the code generator:
1755 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1757 bool old_unsafe = ec.InUnsafe;
1759 // If some parent block was unsafe, we remain unsafe even if this block
1760 // isn't explicitly marked as such.
1761 ec.InUnsafe |= Unsafe;
1764 // Compute the VariableMap's.
1766 // Unfortunately, we don't know the type when adding variables with
1767 // AddVariable(), so we need to compute this info here.
1771 if (variables != null) {
1772 foreach (LocalInfo li in variables.Values)
1775 locals = new LocalInfo [variables.Count];
1776 variables.Values.CopyTo (locals, 0);
1778 locals = new LocalInfo [0];
1781 local_map = new VariableMap (Parent.LocalMap, locals);
1783 local_map = new VariableMap (locals);
1785 param_map = new VariableMap (ip);
1786 flags |= Flags.VariablesInitialized;
1788 bool old_check_state = ec.ConstantCheckState;
1789 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1792 // Process this block variables
1794 if (variables != null){
1795 foreach (DictionaryEntry de in variables){
1796 string name = (string) de.Key;
1797 LocalInfo vi = (LocalInfo) de.Value;
1799 if (vi.VariableType == null)
1802 Type variable_type = vi.VariableType;
1804 if (variable_type.IsPointer){
1806 // Am not really convinced that this test is required (Microsoft does it)
1807 // but the fact is that you would not be able to use the pointer variable
1810 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1817 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1820 // This is needed to compile on both .NET 1.x and .NET 2.x
1821 // the later introduced `DeclareLocal (Type t, bool pinned)'
1823 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1824 else if (!vi.IsThis)
1825 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1828 if (constants == null)
1831 Expression cv = (Expression) constants [name];
1835 ec.CurrentBlock = this;
1836 Expression e = cv.Resolve (ec);
1840 Constant ce = e as Constant;
1842 Report.Error (133, vi.Location,
1843 "The expression being assigned to `" +
1844 name + "' must be constant (" + e + ")");
1848 if (e.Type != variable_type){
1849 e = Const.ChangeType (vi.Location, ce, variable_type);
1854 constants.Remove (name);
1855 constants.Add (name, e);
1858 ec.ConstantCheckState = old_check_state;
1861 // Now, handle the children
1863 if (children != null){
1864 foreach (Block b in children)
1865 b.ResolveMeta (toplevel, ec, ip);
1867 ec.InUnsafe = old_unsafe;
1871 // Emits the local variable declarations for a block
1873 public void EmitMeta (EmitContext ec)
1875 ILGenerator ig = ec.ig;
1877 if (variables != null){
1878 bool have_captured_vars = ec.HaveCapturedVariables ();
1879 bool remap_locals = ec.RemapToProxy;
1881 foreach (DictionaryEntry de in variables){
1882 LocalInfo vi = (LocalInfo) de.Value;
1884 if (have_captured_vars && ec.IsCaptured (vi))
1888 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1892 // This is needed to compile on both .NET 1.x and .NET 2.x
1893 // the later introduced `DeclareLocal (Type t, bool pinned)'
1895 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1896 else if (!vi.IsThis)
1897 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1902 if (children != null){
1903 foreach (Block b in children)
1908 void UsageWarning (FlowBranching.UsageVector vector)
1912 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1913 foreach (DictionaryEntry de in variables){
1914 LocalInfo vi = (LocalInfo) de.Value;
1919 name = (string) de.Key;
1921 if (vector.IsAssigned (vi.VariableInfo)){
1922 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1924 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1930 bool unreachable_shown;
1932 public override bool Resolve (EmitContext ec)
1934 Block prev_block = ec.CurrentBlock;
1937 int errors = Report.Errors;
1939 ec.CurrentBlock = this;
1940 ec.StartFlowBranching (this);
1942 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1944 bool unreachable = false;
1946 int statement_count = statements.Count;
1947 for (int ix = 0; ix < statement_count; ix++){
1948 Statement s = (Statement) statements [ix];
1950 if (unreachable && !(s is LabeledStatement)) {
1951 if (s == EmptyStatement.Value)
1952 s.loc = EndLocation;
1954 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1957 if (s != EmptyStatement.Value)
1958 unreachable_shown = true;
1960 s.loc = Location.Null;
1962 statements [ix] = EmptyStatement.Value;
1966 if (s.Resolve (ec) == false) {
1968 statements [ix] = EmptyStatement.Value;
1972 num_statements = ix + 1;
1974 if (s is LabeledStatement)
1975 unreachable = false;
1977 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1980 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1981 ec.CurrentBranching, statement_count, num_statements);
1984 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1986 ec.CurrentBlock = prev_block;
1988 // If we're a non-static `struct' constructor which doesn't have an
1989 // initializer, then we must initialize all of the struct's fields.
1990 if ((this_variable != null) &&
1991 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1992 !this_variable.IsThisAssigned (ec, loc))
1995 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1996 foreach (LabeledStatement label in labels.Values)
1997 if (!label.HasBeenReferenced)
1998 Report.Warning (164, label.Location,
1999 "This label has not been referenced");
2002 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2004 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2005 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2006 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2007 flags |= Flags.HasRet;
2009 if (ok && (errors == Report.Errors)) {
2010 if (RootContext.WarningLevel >= 3)
2011 UsageWarning (vector);
2017 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2019 unreachable_shown = true;
2020 return base.ResolveUnreachable (ec, warn);
2023 protected override void DoEmit (EmitContext ec)
2025 for (int ix = 0; ix < num_statements; ix++){
2026 Statement s = (Statement) statements [ix];
2028 // Check whether we are the last statement in a
2031 if ((Parent == null) && (ix+1 == num_statements))
2032 ec.IsLastStatement = true;
2034 ec.IsLastStatement = false;
2040 public override void Emit (EmitContext ec)
2042 Block prev_block = ec.CurrentBlock;
2044 ec.CurrentBlock = this;
2046 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2047 bool is_lexical_block = !Implicit && (Parent != null);
2049 if (emit_debug_info) {
2050 if (is_lexical_block)
2051 ec.ig.BeginScope ();
2053 if (variables != null) {
2054 foreach (DictionaryEntry de in variables) {
2055 string name = (string) de.Key;
2056 LocalInfo vi = (LocalInfo) de.Value;
2058 if (vi.LocalBuilder == null)
2061 ec.DefineLocalVariable (name, vi.LocalBuilder);
2066 ec.Mark (StartLocation, true);
2068 ec.Mark (EndLocation, true);
2070 if (emit_debug_info && is_lexical_block)
2073 ec.CurrentBlock = prev_block;
2076 public ToplevelBlock Toplevel {
2079 while (b.Parent != null){
2080 if ((b.flags & Flags.IsToplevel) != 0)
2085 return (ToplevelBlock) b;
2090 // Returns true if we ar ea child of `b'.
2092 public bool IsChildOf (Block b)
2094 Block current = this;
2097 if (current.Parent == b)
2099 current = current.Parent;
2100 } while (current != null);
2106 // A toplevel block contains extra information, the split is done
2107 // only to separate information that would otherwise bloat the more
2108 // lightweight Block.
2110 // In particular, this was introduced when the support for Anonymous
2111 // Methods was implemented.
2113 public class ToplevelBlock : Block {
2115 // Pointer to the host of this anonymous method, or null
2116 // if we are the topmost block
2118 public ToplevelBlock Container;
2119 CaptureContext capture_context;
2121 Hashtable capture_contexts;
2126 public void RegisterCaptureContext (CaptureContext cc)
2128 if (capture_contexts == null)
2129 capture_contexts = new Hashtable ();
2130 capture_contexts [cc] = cc;
2133 public void CompleteContexts ()
2135 if (capture_contexts == null)
2138 foreach (CaptureContext cc in capture_contexts.Keys){
2143 public CaptureContext ToplevelBlockCaptureContext {
2145 return capture_context;
2150 // Parent is only used by anonymous blocks to link back to their
2153 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2154 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2156 Container = container;
2159 public ToplevelBlock (Parameters parameters, Location start) :
2160 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2164 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2165 base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2169 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2173 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2175 if (capture_context == null)
2176 capture_context = new CaptureContext (this, loc, host);
2179 public CaptureContext CaptureContext {
2181 return capture_context;
2186 public class SwitchLabel {
2189 public Location loc;
2193 Label il_label_code;
2194 bool il_label_code_set;
2197 // if expr == null, then it is the default case.
2199 public SwitchLabel (Expression expr, Location l)
2205 public Expression Label {
2211 public object Converted {
2217 public Label GetILLabel (EmitContext ec)
2220 il_label = ec.ig.DefineLabel ();
2221 il_label_set = true;
2226 public Label GetILLabelCode (EmitContext ec)
2228 if (!il_label_code_set){
2229 il_label_code = ec.ig.DefineLabel ();
2230 il_label_code_set = true;
2232 return il_label_code;
2236 // Resolves the expression, reduces it to a literal if possible
2237 // and then converts it to the requested type.
2239 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2244 Expression e = label.Resolve (ec);
2249 if (!(e is Constant)){
2250 Report.Error (150, loc, "A constant value is expected, got: " + e);
2254 if (e is StringConstant || e is NullLiteral){
2255 if (required_type == TypeManager.string_type){
2261 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2262 if (converted == null)
2269 public class SwitchSection {
2270 // An array of SwitchLabels.
2271 public readonly ArrayList Labels;
2272 public readonly Block Block;
2274 public SwitchSection (ArrayList labels, Block block)
2281 public class Switch : Statement {
2282 public readonly ArrayList Sections;
2283 public Expression Expr;
2286 /// Maps constants whose type type SwitchType to their SwitchLabels.
2288 public Hashtable Elements;
2291 /// The governing switch type
2293 public Type SwitchType;
2299 Label default_target;
2300 Expression new_expr;
2302 SwitchSection constant_section;
2305 // The types allowed to be implicitly cast from
2306 // on the governing type
2308 static Type [] allowed_types;
2310 public Switch (Expression e, ArrayList sects, Location l)
2317 public bool GotDefault {
2323 public Label DefaultTarget {
2325 return default_target;
2330 // Determines the governing type for a switch. The returned
2331 // expression might be the expression from the switch, or an
2332 // expression that includes any potential conversions to the
2333 // integral types or to string.
2335 Expression SwitchGoverningType (EmitContext ec, Type t)
2337 if (t == TypeManager.int32_type ||
2338 t == TypeManager.uint32_type ||
2339 t == TypeManager.char_type ||
2340 t == TypeManager.byte_type ||
2341 t == TypeManager.sbyte_type ||
2342 t == TypeManager.ushort_type ||
2343 t == TypeManager.short_type ||
2344 t == TypeManager.uint64_type ||
2345 t == TypeManager.int64_type ||
2346 t == TypeManager.string_type ||
2347 t == TypeManager.bool_type ||
2348 t.IsSubclassOf (TypeManager.enum_type))
2351 if (allowed_types == null){
2352 allowed_types = new Type [] {
2353 TypeManager.int32_type,
2354 TypeManager.uint32_type,
2355 TypeManager.sbyte_type,
2356 TypeManager.byte_type,
2357 TypeManager.short_type,
2358 TypeManager.ushort_type,
2359 TypeManager.int64_type,
2360 TypeManager.uint64_type,
2361 TypeManager.char_type,
2362 TypeManager.bool_type,
2363 TypeManager.string_type
2368 // Try to find a *user* defined implicit conversion.
2370 // If there is no implicit conversion, or if there are multiple
2371 // conversions, we have to report an error
2373 Expression converted = null;
2374 foreach (Type tt in allowed_types){
2377 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2382 // Ignore over-worked ImplicitUserConversions that do
2383 // an implicit conversion in addition to the user conversion.
2386 UserCast ue = e as UserCast;
2388 if (ue.Source != Expr)
2392 if (converted != null){
2393 Report.ExtraInformation (
2395 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2396 TypeManager.CSharpName (Expr.Type)));
2405 static string Error152 {
2407 return "The label '{0}:' already occurs in this switch statement";
2412 // Performs the basic sanity checks on the switch statement
2413 // (looks for duplicate keys and non-constant expressions).
2415 // It also returns a hashtable with the keys that we will later
2416 // use to compute the switch tables
2418 bool CheckSwitch (EmitContext ec)
2422 Elements = new Hashtable ();
2424 got_default = false;
2426 if (TypeManager.IsEnumType (SwitchType)){
2427 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2429 compare_type = SwitchType;
2431 foreach (SwitchSection ss in Sections){
2432 foreach (SwitchLabel sl in ss.Labels){
2433 if (!sl.ResolveAndReduce (ec, SwitchType)){
2438 if (sl.Label == null){
2440 Report.Error (152, sl.loc, Error152, "default");
2447 object key = sl.Converted;
2449 if (key is Constant)
2450 key = ((Constant) key).GetValue ();
2453 key = NullLiteral.Null;
2455 string lname = null;
2456 if (compare_type == TypeManager.uint64_type){
2457 ulong v = (ulong) key;
2459 if (Elements.Contains (v))
2460 lname = v.ToString ();
2462 Elements.Add (v, sl);
2463 } else if (compare_type == TypeManager.int64_type){
2464 long v = (long) key;
2466 if (Elements.Contains (v))
2467 lname = v.ToString ();
2469 Elements.Add (v, sl);
2470 } else if (compare_type == TypeManager.uint32_type){
2471 uint v = (uint) key;
2473 if (Elements.Contains (v))
2474 lname = v.ToString ();
2476 Elements.Add (v, sl);
2477 } else if (compare_type == TypeManager.char_type){
2478 char v = (char) key;
2480 if (Elements.Contains (v))
2481 lname = v.ToString ();
2483 Elements.Add (v, sl);
2484 } else if (compare_type == TypeManager.byte_type){
2485 byte v = (byte) key;
2487 if (Elements.Contains (v))
2488 lname = v.ToString ();
2490 Elements.Add (v, sl);
2491 } else if (compare_type == TypeManager.sbyte_type){
2492 sbyte v = (sbyte) key;
2494 if (Elements.Contains (v))
2495 lname = v.ToString ();
2497 Elements.Add (v, sl);
2498 } else if (compare_type == TypeManager.short_type){
2499 short v = (short) key;
2501 if (Elements.Contains (v))
2502 lname = v.ToString ();
2504 Elements.Add (v, sl);
2505 } else if (compare_type == TypeManager.ushort_type){
2506 ushort v = (ushort) key;
2508 if (Elements.Contains (v))
2509 lname = v.ToString ();
2511 Elements.Add (v, sl);
2512 } else if (compare_type == TypeManager.string_type){
2513 if (key is NullLiteral){
2514 if (Elements.Contains (NullLiteral.Null))
2517 Elements.Add (NullLiteral.Null, null);
2519 string s = (string) key;
2521 if (Elements.Contains (s))
2524 Elements.Add (s, sl);
2526 } else if (compare_type == TypeManager.int32_type) {
2529 if (Elements.Contains (v))
2530 lname = v.ToString ();
2532 Elements.Add (v, sl);
2533 } else if (compare_type == TypeManager.bool_type) {
2534 bool v = (bool) key;
2536 if (Elements.Contains (v))
2537 lname = v.ToString ();
2539 Elements.Add (v, sl);
2543 throw new Exception ("Unknown switch type!" +
2544 SwitchType + " " + compare_type);
2548 Report.Error (152, sl.loc, Error152, "case " + lname);
2559 void EmitObjectInteger (ILGenerator ig, object k)
2562 IntConstant.EmitInt (ig, (int) k);
2563 else if (k is Constant) {
2564 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2567 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2570 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2572 IntConstant.EmitInt (ig, (int) (long) k);
2573 ig.Emit (OpCodes.Conv_I8);
2576 LongConstant.EmitLong (ig, (long) k);
2578 else if (k is ulong)
2580 if ((ulong) k < (1L<<32))
2582 IntConstant.EmitInt (ig, (int) (long) k);
2583 ig.Emit (OpCodes.Conv_U8);
2587 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2591 IntConstant.EmitInt (ig, (int) ((char) k));
2592 else if (k is sbyte)
2593 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2595 IntConstant.EmitInt (ig, (int) ((byte) k));
2596 else if (k is short)
2597 IntConstant.EmitInt (ig, (int) ((short) k));
2598 else if (k is ushort)
2599 IntConstant.EmitInt (ig, (int) ((ushort) k));
2601 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2603 throw new Exception ("Unhandled case");
2606 // structure used to hold blocks of keys while calculating table switch
2607 class KeyBlock : IComparable
2609 public KeyBlock (long _nFirst)
2611 nFirst = nLast = _nFirst;
2615 public ArrayList rgKeys = null;
2616 // how many items are in the bucket
2617 public int Size = 1;
2620 get { return (int) (nLast - nFirst + 1); }
2622 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2624 return kbLast.nLast - kbFirst.nFirst + 1;
2626 public int CompareTo (object obj)
2628 KeyBlock kb = (KeyBlock) obj;
2629 int nLength = Length;
2630 int nLengthOther = kb.Length;
2631 if (nLengthOther == nLength)
2632 return (int) (kb.nFirst - nFirst);
2633 return nLength - nLengthOther;
2638 /// This method emits code for a lookup-based switch statement (non-string)
2639 /// Basically it groups the cases into blocks that are at least half full,
2640 /// and then spits out individual lookup opcodes for each block.
2641 /// It emits the longest blocks first, and short blocks are just
2642 /// handled with direct compares.
2644 /// <param name="ec"></param>
2645 /// <param name="val"></param>
2646 /// <returns></returns>
2647 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2649 int cElements = Elements.Count;
2650 object [] rgKeys = new object [cElements];
2651 Elements.Keys.CopyTo (rgKeys, 0);
2652 Array.Sort (rgKeys);
2654 // initialize the block list with one element per key
2655 ArrayList rgKeyBlocks = new ArrayList ();
2656 foreach (object key in rgKeys)
2657 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2660 // iteratively merge the blocks while they are at least half full
2661 // there's probably a really cool way to do this with a tree...
2662 while (rgKeyBlocks.Count > 1)
2664 ArrayList rgKeyBlocksNew = new ArrayList ();
2665 kbCurr = (KeyBlock) rgKeyBlocks [0];
2666 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2668 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2669 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2672 kbCurr.nLast = kb.nLast;
2673 kbCurr.Size += kb.Size;
2677 // start a new block
2678 rgKeyBlocksNew.Add (kbCurr);
2682 rgKeyBlocksNew.Add (kbCurr);
2683 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2685 rgKeyBlocks = rgKeyBlocksNew;
2688 // initialize the key lists
2689 foreach (KeyBlock kb in rgKeyBlocks)
2690 kb.rgKeys = new ArrayList ();
2692 // fill the key lists
2694 if (rgKeyBlocks.Count > 0) {
2695 kbCurr = (KeyBlock) rgKeyBlocks [0];
2696 foreach (object key in rgKeys)
2698 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2699 System.Convert.ToInt64 (key) > kbCurr.nLast;
2701 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2702 kbCurr.rgKeys.Add (key);
2706 // sort the blocks so we can tackle the largest ones first
2707 rgKeyBlocks.Sort ();
2709 // okay now we can start...
2710 ILGenerator ig = ec.ig;
2711 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2712 Label lblDefault = ig.DefineLabel ();
2714 Type typeKeys = null;
2715 if (rgKeys.Length > 0)
2716 typeKeys = rgKeys [0].GetType (); // used for conversions
2720 if (TypeManager.IsEnumType (SwitchType))
2721 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2723 compare_type = SwitchType;
2725 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2727 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2728 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2731 foreach (object key in kb.rgKeys)
2733 ig.Emit (OpCodes.Ldloc, val);
2734 EmitObjectInteger (ig, key);
2735 SwitchLabel sl = (SwitchLabel) Elements [key];
2736 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2741 // TODO: if all the keys in the block are the same and there are
2742 // no gaps/defaults then just use a range-check.
2743 if (compare_type == TypeManager.int64_type ||
2744 compare_type == TypeManager.uint64_type)
2746 // TODO: optimize constant/I4 cases
2748 // check block range (could be > 2^31)
2749 ig.Emit (OpCodes.Ldloc, val);
2750 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2751 ig.Emit (OpCodes.Blt, lblDefault);
2752 ig.Emit (OpCodes.Ldloc, val);
2753 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2754 ig.Emit (OpCodes.Bgt, lblDefault);
2757 ig.Emit (OpCodes.Ldloc, val);
2760 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2761 ig.Emit (OpCodes.Sub);
2763 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2768 ig.Emit (OpCodes.Ldloc, val);
2769 int nFirst = (int) kb.nFirst;
2772 IntConstant.EmitInt (ig, nFirst);
2773 ig.Emit (OpCodes.Sub);
2775 else if (nFirst < 0)
2777 IntConstant.EmitInt (ig, -nFirst);
2778 ig.Emit (OpCodes.Add);
2782 // first, build the list of labels for the switch
2784 int cJumps = kb.Length;
2785 Label [] rgLabels = new Label [cJumps];
2786 for (int iJump = 0; iJump < cJumps; iJump++)
2788 object key = kb.rgKeys [iKey];
2789 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2791 SwitchLabel sl = (SwitchLabel) Elements [key];
2792 rgLabels [iJump] = sl.GetILLabel (ec);
2796 rgLabels [iJump] = lblDefault;
2798 // emit the switch opcode
2799 ig.Emit (OpCodes.Switch, rgLabels);
2802 // mark the default for this block
2804 ig.MarkLabel (lblDefault);
2807 // TODO: find the default case and emit it here,
2808 // to prevent having to do the following jump.
2809 // make sure to mark other labels in the default section
2811 // the last default just goes to the end
2812 ig.Emit (OpCodes.Br, lblDefault);
2814 // now emit the code for the sections
2815 bool fFoundDefault = false;
2816 foreach (SwitchSection ss in Sections)
2818 foreach (SwitchLabel sl in ss.Labels)
2820 ig.MarkLabel (sl.GetILLabel (ec));
2821 ig.MarkLabel (sl.GetILLabelCode (ec));
2822 if (sl.Label == null)
2824 ig.MarkLabel (lblDefault);
2825 fFoundDefault = true;
2829 //ig.Emit (OpCodes.Br, lblEnd);
2832 if (!fFoundDefault) {
2833 ig.MarkLabel (lblDefault);
2835 ig.MarkLabel (lblEnd);
2838 // This simple emit switch works, but does not take advantage of the
2840 // TODO: remove non-string logic from here
2841 // TODO: binary search strings?
2843 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2845 ILGenerator ig = ec.ig;
2846 Label end_of_switch = ig.DefineLabel ();
2847 Label next_test = ig.DefineLabel ();
2848 Label null_target = ig.DefineLabel ();
2849 bool default_found = false;
2850 bool first_test = true;
2851 bool pending_goto_end = false;
2853 bool default_at_end = false;
2855 ig.Emit (OpCodes.Ldloc, val);
2857 if (Elements.Contains (NullLiteral.Null)){
2858 ig.Emit (OpCodes.Brfalse, null_target);
2860 ig.Emit (OpCodes.Brfalse, default_target);
2862 ig.Emit (OpCodes.Ldloc, val);
2863 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2864 ig.Emit (OpCodes.Stloc, val);
2866 int section_count = Sections.Count;
2867 for (int section = 0; section < section_count; section++){
2868 SwitchSection ss = (SwitchSection) Sections [section];
2869 Label sec_begin = ig.DefineLabel ();
2871 if (pending_goto_end)
2872 ig.Emit (OpCodes.Br, end_of_switch);
2874 int label_count = ss.Labels.Count;
2875 bool mark_default = false;
2877 for (int label = 0; label < label_count; label++){
2878 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2879 ig.MarkLabel (sl.GetILLabel (ec));
2882 ig.MarkLabel (next_test);
2883 next_test = ig.DefineLabel ();
2886 // If we are the default target
2888 if (sl.Label == null){
2889 if (label+1 == label_count)
2890 default_at_end = true;
2891 mark_default = true;
2892 default_found = true;
2894 object lit = sl.Converted;
2896 if (lit is NullLiteral){
2898 if (label_count == 1)
2899 ig.Emit (OpCodes.Br, next_test);
2903 StringConstant str = (StringConstant) lit;
2905 ig.Emit (OpCodes.Ldloc, val);
2906 ig.Emit (OpCodes.Ldstr, str.Value);
2907 if (label_count == 1)
2908 ig.Emit (OpCodes.Bne_Un, next_test);
2910 if (label+1 == label_count)
2911 ig.Emit (OpCodes.Bne_Un, next_test);
2913 ig.Emit (OpCodes.Beq, sec_begin);
2918 ig.MarkLabel (null_target);
2919 ig.MarkLabel (sec_begin);
2920 foreach (SwitchLabel sl in ss.Labels)
2921 ig.MarkLabel (sl.GetILLabelCode (ec));
2924 ig.MarkLabel (default_target);
2926 pending_goto_end = !ss.Block.HasRet;
2929 ig.MarkLabel (next_test);
2931 if (!default_at_end)
2932 ig.Emit (OpCodes.Br, default_target);
2934 ig.MarkLabel (default_target);
2935 ig.MarkLabel (end_of_switch);
2938 SwitchSection FindSection (SwitchLabel label)
2940 foreach (SwitchSection ss in Sections){
2941 foreach (SwitchLabel sl in ss.Labels){
2950 bool ResolveConstantSwitch (EmitContext ec)
2952 object key = ((Constant) new_expr).GetValue ();
2953 SwitchLabel label = (SwitchLabel) Elements [key];
2958 constant_section = FindSection (label);
2959 if (constant_section == null)
2962 if (constant_section.Block.Resolve (ec) != true)
2968 public override bool Resolve (EmitContext ec)
2970 Expr = Expr.Resolve (ec);
2974 new_expr = SwitchGoverningType (ec, Expr.Type);
2975 if (new_expr == null){
2976 Report.Error (151, loc, "An integer type or string was expected for switch");
2981 SwitchType = new_expr.Type;
2983 if (!CheckSwitch (ec))
2986 Switch old_switch = ec.Switch;
2988 ec.Switch.SwitchType = SwitchType;
2990 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2991 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2993 is_constant = new_expr is Constant;
2995 object key = ((Constant) new_expr).GetValue ();
2996 SwitchLabel label = (SwitchLabel) Elements [key];
2998 constant_section = FindSection (label);
3002 foreach (SwitchSection ss in Sections){
3004 ec.CurrentBranching.CreateSibling (
3005 null, FlowBranching.SiblingType.SwitchSection);
3009 if (is_constant && (ss != constant_section)) {
3010 // If we're a constant switch, we're only emitting
3011 // one single section - mark all the others as
3013 ec.CurrentBranching.CurrentUsageVector.Goto ();
3014 if (!ss.Block.ResolveUnreachable (ec, true))
3017 if (!ss.Block.Resolve (ec))
3023 ec.CurrentBranching.CreateSibling (
3024 null, FlowBranching.SiblingType.SwitchSection);
3026 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3027 ec.Switch = old_switch;
3029 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3035 protected override void DoEmit (EmitContext ec)
3037 ILGenerator ig = ec.ig;
3039 // Store variable for comparission purposes
3042 value = ig.DeclareLocal (SwitchType);
3044 ig.Emit (OpCodes.Stloc, value);
3048 default_target = ig.DefineLabel ();
3051 // Setup the codegen context
3053 Label old_end = ec.LoopEnd;
3054 Switch old_switch = ec.Switch;
3056 ec.LoopEnd = ig.DefineLabel ();
3061 if (constant_section != null)
3062 constant_section.Block.Emit (ec);
3063 } else if (SwitchType == TypeManager.string_type)
3064 SimpleSwitchEmit (ec, value);
3066 TableSwitchEmit (ec, value);
3068 // Restore context state.
3069 ig.MarkLabel (ec.LoopEnd);
3072 // Restore the previous context
3074 ec.LoopEnd = old_end;
3075 ec.Switch = old_switch;
3079 public abstract class ExceptionStatement : Statement
3081 public abstract void EmitFinally (EmitContext ec);
3083 protected bool emit_finally = true;
3084 ArrayList parent_vectors;
3086 protected void DoEmitFinally (EmitContext ec)
3089 ec.ig.BeginFinallyBlock ();
3091 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3095 protected void ResolveFinally (FlowBranchingException branching)
3097 emit_finally = branching.EmitFinally;
3099 branching.Parent.StealFinallyClauses (ref parent_vectors);
3103 public class Lock : ExceptionStatement {
3105 Statement Statement;
3108 public Lock (Expression expr, Statement stmt, Location l)
3115 public override bool Resolve (EmitContext ec)
3117 expr = expr.Resolve (ec);
3121 if (expr.Type.IsValueType){
3122 Error (185, "lock statement requires the expression to be " +
3123 " a reference type (type is: `{0}'",
3124 TypeManager.CSharpName (expr.Type));
3128 FlowBranchingException branching = ec.StartFlowBranching (this);
3129 bool ok = Statement.Resolve (ec);
3131 ec.KillFlowBranching ();
3135 ResolveFinally (branching);
3137 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3138 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3139 // Unfortunately, System.Reflection.Emit automatically emits
3140 // a leave to the end of the finally block.
3141 // This is a problem if `returns' is true since we may jump
3142 // to a point after the end of the method.
3143 // As a workaround, emit an explicit ret here.
3144 ec.NeedReturnLabel ();
3150 protected override void DoEmit (EmitContext ec)
3152 Type type = expr.Type;
3154 ILGenerator ig = ec.ig;
3155 temp = ig.DeclareLocal (type);
3158 ig.Emit (OpCodes.Dup);
3159 ig.Emit (OpCodes.Stloc, temp);
3160 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3164 ig.BeginExceptionBlock ();
3165 Statement.Emit (ec);
3170 ig.EndExceptionBlock ();
3173 public override void EmitFinally (EmitContext ec)
3175 ILGenerator ig = ec.ig;
3176 ig.Emit (OpCodes.Ldloc, temp);
3177 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3181 public class Unchecked : Statement {
3182 public readonly Block Block;
3184 public Unchecked (Block b)
3190 public override bool Resolve (EmitContext ec)
3192 bool previous_state = ec.CheckState;
3193 bool previous_state_const = ec.ConstantCheckState;
3195 ec.CheckState = false;
3196 ec.ConstantCheckState = false;
3197 bool ret = Block.Resolve (ec);
3198 ec.CheckState = previous_state;
3199 ec.ConstantCheckState = previous_state_const;
3204 protected override void DoEmit (EmitContext ec)
3206 bool previous_state = ec.CheckState;
3207 bool previous_state_const = ec.ConstantCheckState;
3209 ec.CheckState = false;
3210 ec.ConstantCheckState = false;
3212 ec.CheckState = previous_state;
3213 ec.ConstantCheckState = previous_state_const;
3217 public class Checked : Statement {
3218 public readonly Block Block;
3220 public Checked (Block b)
3223 b.Unchecked = false;
3226 public override bool Resolve (EmitContext ec)
3228 bool previous_state = ec.CheckState;
3229 bool previous_state_const = ec.ConstantCheckState;
3231 ec.CheckState = true;
3232 ec.ConstantCheckState = true;
3233 bool ret = Block.Resolve (ec);
3234 ec.CheckState = previous_state;
3235 ec.ConstantCheckState = previous_state_const;
3240 protected override void DoEmit (EmitContext ec)
3242 bool previous_state = ec.CheckState;
3243 bool previous_state_const = ec.ConstantCheckState;
3245 ec.CheckState = true;
3246 ec.ConstantCheckState = true;
3248 ec.CheckState = previous_state;
3249 ec.ConstantCheckState = previous_state_const;
3253 public class Unsafe : Statement {
3254 public readonly Block Block;
3256 public Unsafe (Block b)
3259 Block.Unsafe = true;
3262 public override bool Resolve (EmitContext ec)
3264 bool previous_state = ec.InUnsafe;
3268 val = Block.Resolve (ec);
3269 ec.InUnsafe = previous_state;
3274 protected override void DoEmit (EmitContext ec)
3276 bool previous_state = ec.InUnsafe;
3280 ec.InUnsafe = previous_state;
3287 public class Fixed : Statement {
3289 ArrayList declarators;
3290 Statement statement;
3296 public bool is_object;
3297 public LocalInfo vi;
3298 public Expression expr;
3299 public Expression converted;
3302 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3305 declarators = decls;
3310 public override bool Resolve (EmitContext ec)
3313 Expression.UnsafeError (loc);
3317 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3321 expr_type = texpr.Type;
3323 CheckObsolete (expr_type);
3325 if (ec.RemapToProxy){
3326 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3330 data = new FixedData [declarators.Count];
3332 if (!expr_type.IsPointer){
3333 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3338 foreach (Pair p in declarators){
3339 LocalInfo vi = (LocalInfo) p.First;
3340 Expression e = (Expression) p.Second;
3342 vi.VariableInfo.SetAssigned (ec);
3346 // The rules for the possible declarators are pretty wise,
3347 // but the production on the grammar is more concise.
3349 // So we have to enforce these rules here.
3351 // We do not resolve before doing the case 1 test,
3352 // because the grammar is explicit in that the token &
3353 // is present, so we need to test for this particular case.
3357 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3362 // Case 1: & object.
3364 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3365 Expression child = ((Unary) e).Expr;
3367 if (child is ParameterReference || child is LocalVariableReference){
3370 "No need to use fixed statement for parameters or " +
3371 "local variable declarations (address is already " +
3376 ec.InFixedInitializer = true;
3378 ec.InFixedInitializer = false;
3382 child = ((Unary) e).Expr;
3384 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3387 data [i].is_object = true;
3389 data [i].converted = null;
3396 ec.InFixedInitializer = true;
3398 ec.InFixedInitializer = false;
3405 if (e.Type.IsArray){
3406 Type array_type = TypeManager.GetElementType (e.Type);
3409 // Provided that array_type is unmanaged,
3411 if (!TypeManager.VerifyUnManaged (array_type, loc))
3415 // and T* is implicitly convertible to the
3416 // pointer type given in the fixed statement.
3418 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3420 Expression converted = Convert.ImplicitConversionRequired (
3421 ec, array_ptr, vi.VariableType, loc);
3422 if (converted == null)
3425 data [i].is_object = false;
3427 data [i].converted = converted;
3437 if (e.Type == TypeManager.string_type){
3438 data [i].is_object = false;
3440 data [i].converted = null;
3447 // For other cases, flag a `this is already fixed expression'
3449 if (e is LocalVariableReference || e is ParameterReference ||
3450 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3452 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3456 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3460 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3462 if (!statement.Resolve (ec)) {
3463 ec.KillFlowBranching ();
3467 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3468 has_ret = reachability.IsUnreachable;
3473 protected override void DoEmit (EmitContext ec)
3475 ILGenerator ig = ec.ig;
3477 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3479 for (int i = 0; i < data.Length; i++) {
3480 LocalInfo vi = data [i].vi;
3483 // Case 1: & object.
3485 if (data [i].is_object) {
3487 // Store pointer in pinned location
3489 data [i].expr.Emit (ec);
3490 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3491 clear_list [i] = vi.LocalBuilder;
3498 if (data [i].expr.Type.IsArray){
3500 // Store pointer in pinned location
3502 data [i].converted.Emit (ec);
3504 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3505 clear_list [i] = vi.LocalBuilder;
3512 if (data [i].expr.Type == TypeManager.string_type){
3513 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3514 clear_list [i] = pinned_string;
3516 data [i].expr.Emit (ec);
3517 ig.Emit (OpCodes.Stloc, pinned_string);
3519 Expression sptr = new StringPtr (pinned_string, loc);
3520 Expression converted = Convert.ImplicitConversionRequired (
3521 ec, sptr, vi.VariableType, loc);
3523 if (converted == null)
3526 converted.Emit (ec);
3527 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3531 statement.Emit (ec);
3537 // Clear the pinned variable
3539 for (int i = 0; i < data.Length; i++) {
3540 if (data [i].is_object || data [i].expr.Type.IsArray) {
3541 ig.Emit (OpCodes.Ldc_I4_0);
3542 ig.Emit (OpCodes.Conv_U);
3543 ig.Emit (OpCodes.Stloc, clear_list [i]);
3544 } else if (data [i].expr.Type == TypeManager.string_type){
3545 ig.Emit (OpCodes.Ldnull);
3546 ig.Emit (OpCodes.Stloc, clear_list [i]);
3552 public class Catch: Statement {
3553 public readonly string Name;
3554 public readonly Block Block;
3556 Expression type_expr;
3559 public Catch (Expression type, string name, Block block, Location l)
3567 public Type CatchType {
3573 public bool IsGeneral {
3575 return type_expr == null;
3579 protected override void DoEmit(EmitContext ec)
3583 public override bool Resolve (EmitContext ec)
3585 if (type_expr != null) {
3586 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3592 CheckObsolete (type);
3594 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3595 Error (155, "The type caught or thrown must be derived from System.Exception");
3601 return Block.Resolve (ec);
3605 public class Try : ExceptionStatement {
3606 public readonly Block Fini, Block;
3607 public readonly ArrayList Specific;
3608 public readonly Catch General;
3610 bool need_exc_block;
3613 // specific, general and fini might all be null.
3615 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3617 if (specific == null && general == null){
3618 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3622 this.Specific = specific;
3623 this.General = general;
3628 public override bool Resolve (EmitContext ec)
3632 FlowBranchingException branching = ec.StartFlowBranching (this);
3634 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3636 if (!Block.Resolve (ec))
3639 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3641 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3643 Type[] prevCatches = new Type [Specific.Count];
3645 foreach (Catch c in Specific){
3646 ec.CurrentBranching.CreateSibling (
3647 c.Block, FlowBranching.SiblingType.Catch);
3649 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3651 if (c.Name != null) {
3652 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3654 throw new Exception ();
3656 vi.VariableInfo = null;
3659 if (!c.Resolve (ec))
3662 Type resolvedType = c.CatchType;
3663 for (int ii = 0; ii < last_index; ++ii) {
3664 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3665 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3670 prevCatches [last_index++] = resolvedType;
3671 need_exc_block = true;
3674 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3676 if (General != null){
3677 ec.CurrentBranching.CreateSibling (
3678 General.Block, FlowBranching.SiblingType.Catch);
3680 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3682 if (!General.Resolve (ec))
3685 need_exc_block = true;
3688 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3692 ec.CurrentBranching.CreateSibling (
3693 Fini, FlowBranching.SiblingType.Finally);
3695 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3697 if (!Fini.Resolve (ec))
3701 ResolveFinally (branching);
3702 need_exc_block |= emit_finally;
3704 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3706 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3708 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3710 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3711 // Unfortunately, System.Reflection.Emit automatically emits
3712 // a leave to the end of the finally block. This is a problem
3713 // if `returns' is true since we may jump to a point after the
3714 // end of the method.
3715 // As a workaround, emit an explicit ret here.
3716 ec.NeedReturnLabel ();
3722 protected override void DoEmit (EmitContext ec)
3724 ILGenerator ig = ec.ig;
3727 ig.BeginExceptionBlock ();
3730 foreach (Catch c in Specific){
3733 ig.BeginCatchBlock (c.CatchType);
3735 if (c.Name != null){
3736 vi = c.Block.GetLocalInfo (c.Name);
3738 throw new Exception ("Variable does not exist in this block");
3740 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3742 ig.Emit (OpCodes.Pop);
3747 if (General != null){
3748 ig.BeginCatchBlock (TypeManager.object_type);
3749 ig.Emit (OpCodes.Pop);
3750 General.Block.Emit (ec);
3755 ig.EndExceptionBlock ();
3758 public override void EmitFinally (EmitContext ec)
3766 public class Using : ExceptionStatement {
3767 object expression_or_block;
3768 Statement Statement;
3773 Expression [] resolved_vars;
3774 Expression [] converted_vars;
3775 ExpressionStatement [] assign;
3776 LocalBuilder local_copy;
3778 public Using (object expression_or_block, Statement stmt, Location l)
3780 this.expression_or_block = expression_or_block;
3786 // Resolves for the case of using using a local variable declaration.
3788 bool ResolveLocalVariableDecls (EmitContext ec)
3792 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3796 expr_type = texpr.Type;
3799 // The type must be an IDisposable or an implicit conversion
3802 converted_vars = new Expression [var_list.Count];
3803 resolved_vars = new Expression [var_list.Count];
3804 assign = new ExpressionStatement [var_list.Count];
3806 bool need_conv = !TypeManager.ImplementsInterface (
3807 expr_type, TypeManager.idisposable_type);
3809 foreach (DictionaryEntry e in var_list){
3810 Expression var = (Expression) e.Key;
3812 var = var.ResolveLValue (ec, new EmptyExpression ());
3816 resolved_vars [i] = var;
3823 converted_vars [i] = Convert.ImplicitConversionRequired (
3824 ec, var, TypeManager.idisposable_type, loc);
3826 if (converted_vars [i] == null)
3833 foreach (DictionaryEntry e in var_list){
3834 Expression var = resolved_vars [i];
3835 Expression new_expr = (Expression) e.Value;
3838 a = new Assign (var, new_expr, loc);
3844 converted_vars [i] = var;
3845 assign [i] = (ExpressionStatement) a;
3852 bool ResolveExpression (EmitContext ec)
3854 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3855 conv = Convert.ImplicitConversionRequired (
3856 ec, expr, TypeManager.idisposable_type, loc);
3866 // Emits the code for the case of using using a local variable declaration.
3868 void EmitLocalVariableDecls (EmitContext ec)
3870 ILGenerator ig = ec.ig;
3873 for (i = 0; i < assign.Length; i++) {
3874 assign [i].EmitStatement (ec);
3877 ig.BeginExceptionBlock ();
3879 Statement.Emit (ec);
3881 var_list.Reverse ();
3886 void EmitLocalVariableDeclFinally (EmitContext ec)
3888 ILGenerator ig = ec.ig;
3890 int i = assign.Length;
3891 for (int ii = 0; ii < var_list.Count; ++ii){
3892 Expression var = resolved_vars [--i];
3893 Label skip = ig.DefineLabel ();
3895 ig.BeginFinallyBlock ();
3897 if (!var.Type.IsValueType) {
3899 ig.Emit (OpCodes.Brfalse, skip);
3900 converted_vars [i].Emit (ec);
3901 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3903 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3905 if (!(ml is MethodGroupExpr)) {
3907 ig.Emit (OpCodes.Box, var.Type);
3908 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3910 MethodInfo mi = null;
3912 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3913 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3920 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3924 IMemoryLocation mloc = (IMemoryLocation) var;
3926 mloc.AddressOf (ec, AddressOp.Load);
3927 ig.Emit (OpCodes.Call, mi);
3931 ig.MarkLabel (skip);
3934 ig.EndExceptionBlock ();
3936 ig.BeginFinallyBlock ();
3941 void EmitExpression (EmitContext ec)
3944 // Make a copy of the expression and operate on that.
3946 ILGenerator ig = ec.ig;
3947 local_copy = ig.DeclareLocal (expr_type);
3952 ig.Emit (OpCodes.Stloc, local_copy);
3955 ig.BeginExceptionBlock ();
3957 Statement.Emit (ec);
3961 ig.EndExceptionBlock ();
3964 void EmitExpressionFinally (EmitContext ec)
3966 ILGenerator ig = ec.ig;
3967 if (!local_copy.LocalType.IsValueType) {
3968 Label skip = ig.DefineLabel ();
3969 ig.Emit (OpCodes.Ldloc, local_copy);
3970 ig.Emit (OpCodes.Brfalse, skip);
3971 ig.Emit (OpCodes.Ldloc, local_copy);
3972 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3973 ig.MarkLabel (skip);
3975 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
3977 if (!(ml is MethodGroupExpr)) {
3978 ig.Emit (OpCodes.Ldloc, local_copy);
3979 ig.Emit (OpCodes.Box, local_copy.LocalType);
3980 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3982 MethodInfo mi = null;
3984 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3985 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3992 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3996 ig.Emit (OpCodes.Ldloca, local_copy);
3997 ig.Emit (OpCodes.Call, mi);
4002 public override bool Resolve (EmitContext ec)
4004 if (expression_or_block is DictionaryEntry){
4005 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4006 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4008 if (!ResolveLocalVariableDecls (ec))
4011 } else if (expression_or_block is Expression){
4012 expr = (Expression) expression_or_block;
4014 expr = expr.Resolve (ec);
4018 expr_type = expr.Type;
4020 if (!ResolveExpression (ec))
4024 FlowBranchingException branching = ec.StartFlowBranching (this);
4026 bool ok = Statement.Resolve (ec);
4029 ec.KillFlowBranching ();
4033 ResolveFinally (branching);
4034 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4036 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4037 // Unfortunately, System.Reflection.Emit automatically emits a leave
4038 // to the end of the finally block. This is a problem if `returns'
4039 // is true since we may jump to a point after the end of the method.
4040 // As a workaround, emit an explicit ret here.
4041 ec.NeedReturnLabel ();
4047 protected override void DoEmit (EmitContext ec)
4049 if (expression_or_block is DictionaryEntry)
4050 EmitLocalVariableDecls (ec);
4051 else if (expression_or_block is Expression)
4052 EmitExpression (ec);
4055 public override void EmitFinally (EmitContext ec)
4057 if (expression_or_block is DictionaryEntry)
4058 EmitLocalVariableDeclFinally (ec);
4059 else if (expression_or_block is Expression)
4060 EmitExpressionFinally (ec);
4065 /// Implementation of the foreach C# statement
4067 public class Foreach : ExceptionStatement {
4069 Expression variable;
4071 Statement statement;
4072 ForeachHelperMethods hm;
4073 Expression empty, conv;
4074 Type array_type, element_type;
4076 VariableStorage enumerator;
4078 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4079 Statement stmt, Location l)
4082 this.variable = var;
4088 public override bool Resolve (EmitContext ec)
4090 expr = expr.Resolve (ec);
4094 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4098 var_type = texpr.Type;
4101 // We need an instance variable. Not sure this is the best
4102 // way of doing this.
4104 // FIXME: When we implement propertyaccess, will those turn
4105 // out to return values in ExprClass? I think they should.
4107 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4108 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4109 error1579 (expr.Type);
4113 if (expr.Type.IsArray) {
4114 array_type = expr.Type;
4115 element_type = TypeManager.GetElementType (array_type);
4117 empty = new EmptyExpression (element_type);
4119 hm = ProbeCollectionType (ec, expr.Type);
4121 error1579 (expr.Type);
4125 array_type = expr.Type;
4126 element_type = hm.element_type;
4128 empty = new EmptyExpression (hm.element_type);
4133 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4134 ec.CurrentBranching.CreateSibling ();
4138 // FIXME: maybe we can apply the same trick we do in the
4139 // array handling to avoid creating empty and conv in some cases.
4141 // Although it is not as important in this case, as the type
4142 // will not likely be object (what the enumerator will return).
4144 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4148 variable = variable.ResolveLValue (ec, empty);
4149 if (variable == null)
4152 bool disposable = (hm != null) && hm.is_disposable;
4153 FlowBranchingException branching = null;
4155 branching = ec.StartFlowBranching (this);
4157 if (!statement.Resolve (ec))
4161 ResolveFinally (branching);
4162 ec.EndFlowBranching ();
4164 emit_finally = true;
4166 ec.EndFlowBranching ();
4172 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4174 static MethodInfo FetchMethodMoveNext (Type t)
4176 MemberList move_next_list;
4178 move_next_list = TypeContainer.FindMembers (
4179 t, MemberTypes.Method,
4180 BindingFlags.Public | BindingFlags.Instance,
4181 Type.FilterName, "MoveNext");
4182 if (move_next_list.Count == 0)
4185 foreach (MemberInfo m in move_next_list){
4186 MethodInfo mi = (MethodInfo) m;
4189 args = TypeManager.GetArgumentTypes (mi);
4190 if (args != null && args.Length == 0){
4191 if (TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type)
4199 // Retrieves a `public T get_Current ()' method from the Type `t'
4201 static MethodInfo FetchMethodGetCurrent (Type t)
4203 MemberList get_current_list;
4205 get_current_list = TypeContainer.FindMembers (
4206 t, MemberTypes.Method,
4207 BindingFlags.Public | BindingFlags.Instance,
4208 Type.FilterName, "get_Current");
4209 if (get_current_list.Count == 0)
4212 foreach (MemberInfo m in get_current_list){
4213 MethodInfo mi = (MethodInfo) m;
4216 args = TypeManager.GetArgumentTypes (mi);
4217 if (args != null && args.Length == 0)
4224 // Retrieves a `public void Dispose ()' method from the Type `t'
4226 static MethodInfo FetchMethodDispose (Type t)
4228 MemberList dispose_list;
4230 dispose_list = TypeContainer.FindMembers (
4231 t, MemberTypes.Method,
4232 BindingFlags.Public | BindingFlags.Instance,
4233 Type.FilterName, "Dispose");
4234 if (dispose_list.Count == 0)
4237 foreach (MemberInfo m in dispose_list){
4238 MethodInfo mi = (MethodInfo) m;
4241 args = TypeManager.GetArgumentTypes (mi);
4242 if (args != null && args.Length == 0){
4243 if (mi.ReturnType == TypeManager.void_type)
4251 // This struct records the helper methods used by the Foreach construct
4253 class ForeachHelperMethods {
4254 public EmitContext ec;
4255 public MethodInfo get_enumerator;
4256 public MethodInfo move_next;
4257 public MethodInfo get_current;
4258 public Type element_type;
4259 public Type enumerator_type;
4260 public bool is_disposable;
4262 public ForeachHelperMethods (EmitContext ec)
4265 this.element_type = TypeManager.object_type;
4266 this.enumerator_type = TypeManager.ienumerator_type;
4267 this.is_disposable = true;
4271 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4276 if (!(m is MethodInfo))
4279 if (m.Name != "GetEnumerator")
4282 MethodInfo mi = (MethodInfo) m;
4283 Type [] args = TypeManager.GetArgumentTypes (mi);
4285 if (args.Length != 0)
4288 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4290 // Check whether GetEnumerator is public
4291 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4294 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4296 // Apply the same optimization as MS: skip the GetEnumerator
4297 // returning an IEnumerator, and use the one returning a
4298 // CharEnumerator instead. This allows us to avoid the
4299 // try-finally block and the boxing.
4304 // Ok, we can access it, now make sure that we can do something
4305 // with this `GetEnumerator'
4308 Type return_type = mi.ReturnType;
4309 if (mi.ReturnType == TypeManager.ienumerator_type ||
4310 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4311 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4314 // If it is not an interface, lets try to find the methods ourselves.
4315 // For example, if we have:
4316 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4317 // We can avoid the iface call. This is a runtime perf boost.
4318 // even bigger if we have a ValueType, because we avoid the cost
4321 // We have to make sure that both methods exist for us to take
4322 // this path. If one of the methods does not exist, we will just
4323 // use the interface. Sadly, this complex if statement is the only
4324 // way I could do this without a goto
4327 if (return_type.IsInterface ||
4328 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4329 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4331 hm.move_next = TypeManager.bool_movenext_void;
4332 hm.get_current = TypeManager.object_getcurrent_void;
4339 // Ok, so they dont return an IEnumerable, we will have to
4340 // find if they support the GetEnumerator pattern.
4343 hm.move_next = FetchMethodMoveNext (return_type);
4344 if (hm.move_next == null)
4347 hm.get_current = FetchMethodGetCurrent (return_type);
4348 if (hm.get_current == null)
4352 hm.element_type = hm.get_current.ReturnType;
4353 hm.enumerator_type = return_type;
4354 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4355 TypeManager.ImplementsInterface (
4356 hm.enumerator_type, TypeManager.idisposable_type);
4362 /// This filter is used to find the GetEnumerator method
4363 /// on which IEnumerator operates
4365 static MemberFilter FilterEnumerator;
4369 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4372 void error1579 (Type t)
4374 Report.Error (1579, loc,
4375 "foreach statement cannot operate on variables of type `" +
4376 t.FullName + "' because that class does not provide a " +
4377 " GetEnumerator method or it is inaccessible");
4380 static bool TryType (Type t, ForeachHelperMethods hm)
4384 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4385 BindingFlags.Public | BindingFlags.NonPublic |
4386 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4387 FilterEnumerator, hm);
4392 hm.get_enumerator = (MethodInfo) mi [0];
4397 // Looks for a usable GetEnumerator in the Type, and if found returns
4398 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4400 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4402 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4404 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4405 if (TryType (tt, hm))
4411 // Now try to find the method in the interfaces
4414 Type [] ifaces = t.GetInterfaces ();
4416 foreach (Type i in ifaces){
4417 if (TryType (i, hm))
4422 // Since TypeBuilder.GetInterfaces only returns the interface
4423 // types for this type, we have to keep looping, but once
4424 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4425 // done, because it returns all the types
4427 if ((t is TypeBuilder))
4437 // FIXME: possible optimization.
4438 // We might be able to avoid creating `empty' if the type is the sam
4440 bool EmitCollectionForeach (EmitContext ec)
4442 ILGenerator ig = ec.ig;
4444 enumerator = new VariableStorage (ec, hm.enumerator_type);
4445 enumerator.EmitThis (ig);
4447 // Instantiate the enumerator
4449 if (expr.Type.IsValueType){
4450 IMemoryLocation ml = expr as IMemoryLocation;
4451 // Load the address of the value type.
4453 // This happens if, for example, you have a property
4454 // returning a struct which is IEnumerable
4455 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4457 ig.Emit (OpCodes.Stloc, t);
4458 ig.Emit (OpCodes.Ldloca, t);
4459 ec.FreeTemporaryLocal (t, expr.Type);
4461 ml.AddressOf (ec, AddressOp.Load);
4465 if (hm.get_enumerator.DeclaringType.IsValueType) {
4466 // the method is declared on the value type
4467 ig.Emit (OpCodes.Call, hm.get_enumerator);
4469 // it is an interface method, so we must box
4470 ig.Emit (OpCodes.Box, expr.Type);
4471 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4475 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4477 enumerator.EmitStore (ig);
4480 // Protect the code in a try/finalize block, so that
4481 // if the beast implement IDisposable, we get rid of it
4483 if (hm.is_disposable && emit_finally)
4484 ig.BeginExceptionBlock ();
4486 Label end_try = ig.DefineLabel ();
4488 ig.MarkLabel (ec.LoopBegin);
4490 enumerator.EmitCall (ig, hm.move_next);
4492 ig.Emit (OpCodes.Brfalse, end_try);
4495 ig.Emit (OpCodes.Ldarg_0);
4497 enumerator.EmitCall (ig, hm.get_current);
4501 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4503 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4505 statement.Emit (ec);
4506 ig.Emit (OpCodes.Br, ec.LoopBegin);
4507 ig.MarkLabel (end_try);
4509 // The runtime provides this for us.
4510 // ig.Emit (OpCodes.Leave, end);
4513 // Now the finally block
4515 if (hm.is_disposable) {
4518 ig.EndExceptionBlock ();
4521 ig.MarkLabel (ec.LoopEnd);
4525 public override void EmitFinally (EmitContext ec)
4527 ILGenerator ig = ec.ig;
4529 if (hm.enumerator_type.IsValueType) {
4530 enumerator.EmitThis (ig);
4532 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4534 enumerator.EmitLoadAddress (ig);
4535 ig.Emit (OpCodes.Call, mi);
4537 enumerator.EmitLoad (ig);
4538 ig.Emit (OpCodes.Box, hm.enumerator_type);
4539 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4542 Label call_dispose = ig.DefineLabel ();
4544 enumerator.EmitThis (ig);
4545 enumerator.EmitLoad (ig);
4546 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4547 ig.Emit (OpCodes.Dup);
4548 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4549 ig.Emit (OpCodes.Pop);
4551 Label end_finally = ig.DefineLabel ();
4552 ig.Emit (OpCodes.Br, end_finally);
4554 ig.MarkLabel (call_dispose);
4555 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4556 ig.MarkLabel (end_finally);
4559 ig.Emit (OpCodes.Endfinally);
4564 // FIXME: possible optimization.
4565 // We might be able to avoid creating `empty' if the type is the sam
4567 bool EmitArrayForeach (EmitContext ec)
4569 int rank = array_type.GetArrayRank ();
4570 ILGenerator ig = ec.ig;
4572 VariableStorage copy = new VariableStorage (ec, array_type);
4575 // Make our copy of the array
4579 copy.EmitStore (ig);
4582 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4586 counter.EmitThis (ig);
4587 ig.Emit (OpCodes.Ldc_I4_0);
4588 counter.EmitStore (ig);
4589 test = ig.DefineLabel ();
4590 ig.Emit (OpCodes.Br, test);
4592 loop = ig.DefineLabel ();
4593 ig.MarkLabel (loop);
4596 ig.Emit (OpCodes.Ldarg_0);
4600 counter.EmitThis (ig);
4601 counter.EmitLoad (ig);
4604 // Load the value, we load the value using the underlying type,
4605 // then we use the variable.EmitAssign to load using the proper cast.
4607 ArrayAccess.EmitLoadOpcode (ig, element_type);
4610 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4612 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4614 statement.Emit (ec);
4616 ig.MarkLabel (ec.LoopBegin);
4617 counter.EmitThis (ig);
4618 counter.EmitThis (ig);
4619 counter.EmitLoad (ig);
4620 ig.Emit (OpCodes.Ldc_I4_1);
4621 ig.Emit (OpCodes.Add);
4622 counter.EmitStore (ig);
4624 ig.MarkLabel (test);
4625 counter.EmitThis (ig);
4626 counter.EmitLoad (ig);
4629 ig.Emit (OpCodes.Ldlen);
4630 ig.Emit (OpCodes.Conv_I4);
4631 ig.Emit (OpCodes.Blt, loop);
4633 VariableStorage [] dim_len = new VariableStorage [rank];
4634 VariableStorage [] dim_count = new VariableStorage [rank];
4635 Label [] loop = new Label [rank];
4636 Label [] test = new Label [rank];
4639 for (dim = 0; dim < rank; dim++){
4640 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4641 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4642 test [dim] = ig.DefineLabel ();
4643 loop [dim] = ig.DefineLabel ();
4646 for (dim = 0; dim < rank; dim++){
4647 dim_len [dim].EmitThis (ig);
4650 IntLiteral.EmitInt (ig, dim);
4651 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4652 dim_len [dim].EmitStore (ig);
4656 for (dim = 0; dim < rank; dim++){
4657 dim_count [dim].EmitThis (ig);
4658 ig.Emit (OpCodes.Ldc_I4_0);
4659 dim_count [dim].EmitStore (ig);
4660 ig.Emit (OpCodes.Br, test [dim]);
4661 ig.MarkLabel (loop [dim]);
4665 ig.Emit (OpCodes.Ldarg_0);
4669 for (dim = 0; dim < rank; dim++){
4670 dim_count [dim].EmitThis (ig);
4671 dim_count [dim].EmitLoad (ig);
4675 // FIXME: Maybe we can cache the computation of `get'?
4677 Type [] args = new Type [rank];
4680 for (int i = 0; i < rank; i++)
4681 args [i] = TypeManager.int32_type;
4683 ModuleBuilder mb = CodeGen.Module.Builder;
4684 get = mb.GetArrayMethod (
4686 CallingConventions.HasThis| CallingConventions.Standard,
4688 ig.Emit (OpCodes.Call, get);
4691 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4693 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4694 statement.Emit (ec);
4695 ig.MarkLabel (ec.LoopBegin);
4696 for (dim = rank - 1; dim >= 0; dim--){
4697 dim_count [dim].EmitThis (ig);
4698 dim_count [dim].EmitThis (ig);
4699 dim_count [dim].EmitLoad (ig);
4700 ig.Emit (OpCodes.Ldc_I4_1);
4701 ig.Emit (OpCodes.Add);
4702 dim_count [dim].EmitStore (ig);
4704 ig.MarkLabel (test [dim]);
4705 dim_count [dim].EmitThis (ig);
4706 dim_count [dim].EmitLoad (ig);
4707 dim_len [dim].EmitThis (ig);
4708 dim_len [dim].EmitLoad (ig);
4709 ig.Emit (OpCodes.Blt, loop [dim]);
4712 ig.MarkLabel (ec.LoopEnd);
4717 protected override void DoEmit (EmitContext ec)
4719 ILGenerator ig = ec.ig;
4721 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4722 ec.LoopBegin = ig.DefineLabel ();
4723 ec.LoopEnd = ig.DefineLabel ();
4726 EmitCollectionForeach (ec);
4728 EmitArrayForeach (ec);
4730 ec.LoopBegin = old_begin;
4731 ec.LoopEnd = old_end;