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 public 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.WideningConversionRequired (
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 ();
649 label.AddReference ();
654 public Goto (Block parent_block, string label, Location l)
656 block = parent_block;
661 public string Target {
667 protected override void DoEmit (EmitContext ec)
669 Label l = label.LabelTarget (ec);
670 ec.ig.Emit (OpCodes.Br, l);
674 public class LabeledStatement : Statement {
675 public readonly Location Location;
681 FlowBranching.UsageVector vectors;
683 public LabeledStatement (string label_name, Location l)
688 public Label LabelTarget (EmitContext ec)
693 label = ec.ig.DefineLabel ();
699 public bool IsDefined {
705 public bool HasBeenReferenced {
711 public void AddUsageVector (FlowBranching.UsageVector vector)
713 vector = vector.Clone ();
714 vector.Next = vectors;
718 public override bool Resolve (EmitContext ec)
720 ec.CurrentBranching.Label (vectors);
726 protected override void DoEmit (EmitContext ec)
728 if (ig != null && ig != ec.ig) {
729 Report.Error (1632, "Control cannot leave body of anonymous method");
733 ec.ig.MarkLabel (label);
736 public void AddReference ()
744 /// `goto default' statement
746 public class GotoDefault : Statement {
748 public GotoDefault (Location l)
753 public override bool Resolve (EmitContext ec)
755 ec.CurrentBranching.CurrentUsageVector.Goto ();
759 protected override void DoEmit (EmitContext ec)
761 if (ec.Switch == null){
762 Report.Error (153, loc, "goto default is only valid in a switch statement");
766 if (!ec.Switch.GotDefault){
767 Report.Error (159, loc, "No default target on switch statement");
770 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
775 /// `goto case' statement
777 public class GotoCase : Statement {
781 public GotoCase (Expression e, Location l)
787 public override bool Resolve (EmitContext ec)
789 if (ec.Switch == null){
790 Report.Error (153, loc, "goto case is only valid in a switch statement");
794 expr = expr.Resolve (ec);
798 if (!(expr is Constant)){
799 Report.Error (159, loc, "Target expression for goto case is not constant");
803 object val = Expression.ConvertIntLiteral (
804 (Constant) expr, ec.Switch.SwitchType, loc);
809 sl = (SwitchLabel) ec.Switch.Elements [val];
814 "No such label 'case " + val + "': for the goto case");
818 ec.CurrentBranching.CurrentUsageVector.Goto ();
822 protected override void DoEmit (EmitContext ec)
824 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
828 public class Throw : Statement {
831 public Throw (Expression expr, Location l)
837 public override bool Resolve (EmitContext ec)
839 ec.CurrentBranching.CurrentUsageVector.Throw ();
842 expr = expr.Resolve (ec);
846 ExprClass eclass = expr.eclass;
848 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
849 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
850 expr.Error_UnexpectedKind ("value, variable, property or indexer access ", loc);
856 if ((t != TypeManager.exception_type) &&
857 !t.IsSubclassOf (TypeManager.exception_type) &&
858 !(expr is NullLiteral)) {
860 "The type caught or thrown must be derived " +
861 "from System.Exception");
867 if (ec.CurrentBranching.InFinally (true)) {
868 Error (724, "A throw statement with no argument is only allowed in a catch clause nested inside of the innermost catch clause");
872 if (!ec.CurrentBranching.InCatch ()) {
873 Error (156, "A throw statement with no argument is only allowed in a catch clause");
879 protected override void DoEmit (EmitContext ec)
882 ec.ig.Emit (OpCodes.Rethrow);
886 ec.ig.Emit (OpCodes.Throw);
891 public class Break : Statement {
893 public Break (Location l)
900 public override bool Resolve (EmitContext ec)
902 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
903 Error (139, "No enclosing loop or switch to continue to");
905 } else if (ec.CurrentBranching.InFinally (false)) {
906 Error (157, "Control can not leave the body of the finally block");
908 } else if (ec.CurrentBranching.InTryOrCatch (false))
909 ec.CurrentBranching.AddFinallyVector (
910 ec.CurrentBranching.CurrentUsageVector);
911 else if (ec.CurrentBranching.InLoop ())
912 ec.CurrentBranching.AddBreakVector (
913 ec.CurrentBranching.CurrentUsageVector);
915 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
918 ec.NeedReturnLabel ();
920 ec.CurrentBranching.CurrentUsageVector.Break ();
924 protected override void DoEmit (EmitContext ec)
926 ILGenerator ig = ec.ig;
929 ig.Emit (OpCodes.Leave, ec.LoopEnd);
931 ig.Emit (OpCodes.Br, ec.LoopEnd);
936 public class Continue : Statement {
938 public Continue (Location l)
945 public override bool Resolve (EmitContext ec)
947 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
948 Error (139, "No enclosing loop to continue to");
950 } else if (ec.CurrentBranching.InFinally (false)) {
951 Error (157, "Control can not leave the body of the finally block");
953 } else if (ec.CurrentBranching.InTryOrCatch (false))
954 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
956 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
958 ec.CurrentBranching.CurrentUsageVector.Goto ();
962 protected override void DoEmit (EmitContext ec)
964 Label begin = ec.LoopBegin;
967 ec.ig.Emit (OpCodes.Leave, begin);
969 ec.ig.Emit (OpCodes.Br, begin);
974 // The information about a user-perceived local variable
976 public class LocalInfo {
977 public Expression Type;
980 // Most of the time a variable will be stored in a LocalBuilder
982 // But sometimes, it will be stored in a field (variables that have been
983 // hoisted by iterators or by anonymous methods). The context of the field will
984 // be stored in the EmitContext
987 public LocalBuilder LocalBuilder;
988 public FieldBuilder FieldBuilder;
990 public Type VariableType;
991 public readonly string Name;
992 public readonly Location Location;
993 public readonly Block Block;
995 public VariableInfo VariableInfo;
1008 public LocalInfo (Expression type, string name, Block block, Location l)
1016 public LocalInfo (TypeContainer tc, Block block, Location l)
1018 VariableType = tc.TypeBuilder;
1023 public bool IsThisAssigned (EmitContext ec, Location loc)
1025 if (VariableInfo == null)
1026 throw new Exception ();
1028 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1031 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1034 public bool IsAssigned (EmitContext ec)
1036 if (VariableInfo == null)
1037 throw new Exception ();
1039 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1042 public bool Resolve (EmitContext ec)
1044 if (VariableType == null) {
1045 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
1049 VariableType = texpr.Type;
1052 if (VariableType == TypeManager.void_type) {
1053 Report.Error (1547, Location,
1054 "Keyword 'void' cannot be used in this context");
1058 if (VariableType.IsAbstract && VariableType.IsSealed) {
1059 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1062 // TODO: breaks the build
1063 // if (VariableType.IsPointer && !ec.InUnsafe)
1064 // Expression.UnsafeError (Location);
1070 // Whether the variable is Fixed (because its Pinned or its a value type)
1072 public bool IsFixed {
1074 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1081 public bool IsCaptured {
1083 return (flags & Flags.Captured) != 0;
1087 flags |= Flags.Captured;
1091 public bool AddressTaken {
1093 return (flags & Flags.AddressTaken) != 0;
1097 flags |= Flags.AddressTaken;
1101 public override string ToString ()
1103 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1104 Name, Type, VariableInfo, Location);
1109 return (flags & Flags.Used) != 0;
1112 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1116 public bool ReadOnly {
1118 return (flags & Flags.ReadOnly) != 0;
1121 flags = value ? (flags | Flags.ReadOnly) : (unchecked (flags & ~Flags.ReadOnly));
1126 // Whether the variable is pinned, if Pinned the variable has been
1127 // allocated in a pinned slot with DeclareLocal.
1129 public bool Pinned {
1131 return (flags & Flags.Pinned) != 0;
1134 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1138 public bool IsThis {
1140 return (flags & Flags.IsThis) != 0;
1143 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1149 /// Block represents a C# block.
1153 /// This class is used in a number of places: either to represent
1154 /// explicit blocks that the programmer places or implicit blocks.
1156 /// Implicit blocks are used as labels or to introduce variable
1159 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1160 /// they contain extra information that is not necessary on normal blocks.
1162 public class Block : Statement {
1163 public Block Parent;
1164 public readonly Location StartLocation;
1165 public Location EndLocation = Location.Null;
1172 VariablesInitialized = 8,
1181 public bool Implicit {
1183 return (flags & Flags.Implicit) != 0;
1187 public bool Unchecked {
1189 return (flags & Flags.Unchecked) != 0;
1192 flags |= Flags.Unchecked;
1196 public bool Unsafe {
1198 return (flags & Flags.Unsafe) != 0;
1201 flags |= Flags.Unsafe;
1205 public bool HasVarargs {
1208 return Parent.HasVarargs;
1210 return (flags & Flags.HasVarargs) != 0;
1213 flags |= Flags.HasVarargs;
1218 // The statements in this block
1220 public ArrayList statements;
1224 // An array of Blocks. We keep track of children just
1225 // to generate the local variable declarations.
1227 // Statements and child statements are handled through the
1233 // Labels. (label, block) pairs.
1238 // Keeps track of (name, type) pairs
1240 Hashtable variables;
1243 // Keeps track of constants
1244 Hashtable constants;
1247 // The parameters for the block, this is only needed on the toplevel block really
1248 // TODO: move `parameters' into ToplevelBlock
1249 Parameters parameters;
1252 // If this is a switch section, the enclosing switch block.
1256 protected static int id;
1260 public Block (Block parent)
1261 : this (parent, (Flags) 0, Location.Null, Location.Null)
1264 public Block (Block parent, Flags flags)
1265 : this (parent, flags, Location.Null, Location.Null)
1268 public Block (Block parent, Flags flags, Parameters parameters)
1269 : this (parent, flags, parameters, Location.Null, Location.Null)
1272 public Block (Block parent, Location start, Location end)
1273 : this (parent, (Flags) 0, start, end)
1276 public Block (Block parent, Parameters parameters, Location start, Location end)
1277 : this (parent, (Flags) 0, parameters, start, end)
1280 public Block (Block parent, Flags flags, Location start, Location end)
1281 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1284 public Block (Block parent, Flags flags, Parameters parameters,
1285 Location start, Location end)
1288 parent.AddChild (this);
1290 this.Parent = parent;
1292 this.parameters = parameters;
1293 this.StartLocation = start;
1294 this.EndLocation = end;
1297 statements = new ArrayList ();
1299 if (parent != null && Implicit) {
1300 if (parent.child_variable_names == null)
1301 parent.child_variable_names = new Hashtable();
1302 // share with parent
1303 child_variable_names = parent.child_variable_names;
1308 public Block CreateSwitchBlock (Location start)
1310 Block new_block = new Block (this, start, start);
1311 new_block.switch_block = this;
1321 void AddChild (Block b)
1323 if (children == null)
1324 children = new ArrayList ();
1329 public void SetEndLocation (Location loc)
1335 /// Adds a label to the current block.
1339 /// false if the name already exists in this block. true
1343 public bool AddLabel (string name, LabeledStatement target, Location loc)
1345 if (switch_block != null)
1346 return switch_block.AddLabel (name, target, loc);
1349 while (cur != null) {
1350 if (cur.DoLookupLabel (name) != null) {
1352 140, loc, "The label '{0}' is a duplicate",
1363 while (cur != null) {
1364 if (cur.DoLookupLabel (name) != null) {
1367 "The label '{0}' shadows another label " +
1368 "by the same name in a containing scope.",
1373 if (children != null) {
1374 foreach (Block b in children) {
1375 LabeledStatement s = b.DoLookupLabel (name);
1381 "The label '{0}' shadows another " +
1382 "label by the same name in a " +
1383 "containing scope.",
1394 labels = new Hashtable ();
1396 labels.Add (name, target);
1400 public LabeledStatement LookupLabel (string name)
1402 LabeledStatement s = DoLookupLabel (name);
1406 if (children == null)
1409 foreach (Block child in children) {
1410 if (!child.Implicit)
1413 s = child.LookupLabel (name);
1421 LabeledStatement DoLookupLabel (string name)
1423 if (switch_block != null)
1424 return switch_block.LookupLabel (name);
1427 if (labels.Contains (name))
1428 return ((LabeledStatement) labels [name]);
1433 LocalInfo this_variable = null;
1436 // Returns the "this" instance variable of this block.
1437 // See AddThisVariable() for more information.
1439 public LocalInfo ThisVariable {
1441 for (Block b = this; b != null; b = b.Parent) {
1442 if (b.this_variable != null)
1443 return b.this_variable;
1450 Hashtable child_variable_names;
1453 // Marks a variable with name @name as being used in a child block.
1454 // If a variable name has been used in a child block, it's illegal to
1455 // declare a variable with the same name in the current block.
1457 public void AddChildVariableName (string name)
1459 if (child_variable_names == null)
1460 child_variable_names = new Hashtable ();
1462 child_variable_names [name] = null;
1466 // Checks whether a variable name has already been used in a child block.
1468 public bool IsVariableNameUsedInChildBlock (string name)
1470 if (child_variable_names == null)
1473 return child_variable_names.Contains (name);
1477 // This is used by non-static `struct' constructors which do not have an
1478 // initializer - in this case, the constructor must initialize all of the
1479 // struct's fields. To do this, we add a "this" variable and use the flow
1480 // analysis code to ensure that it's been fully initialized before control
1481 // leaves the constructor.
1483 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1485 if (this_variable != null)
1486 return this_variable;
1488 if (variables == null)
1489 variables = new Hashtable ();
1491 this_variable = new LocalInfo (tc, this, l);
1492 this_variable.Used = true;
1493 this_variable.IsThis = true;
1495 variables.Add ("this", this_variable);
1497 return this_variable;
1500 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1502 if (variables == null)
1503 variables = new Hashtable ();
1505 LocalInfo vi = GetLocalInfo (name);
1507 if (vi.Block != this)
1508 Report.Error (136, l, "A local variable named `" + name + "' " +
1509 "cannot be declared in this scope since it would " +
1510 "give a different meaning to `" + name + "', which " +
1511 "is already used in a `parent or current' scope to " +
1512 "denote something else");
1514 Report.Error (128, l, "A local variable `" + name + "' is already " +
1515 "defined in this scope");
1519 if (IsVariableNameUsedInChildBlock (name)) {
1520 Report.Error (136, l, "A local variable named `" + name + "' " +
1521 "cannot be declared in this scope since it would " +
1522 "give a different meaning to `" + name + "', which " +
1523 "is already used in a `child' scope to denote something " +
1530 Parameter p = pars.GetParameterByName (name, out idx);
1532 Report.Error (136, l, "A local variable named `" + name + "' " +
1533 "cannot be declared in this scope since it would " +
1534 "give a different meaning to `" + name + "', which " +
1535 "is already used in a `parent or current' scope to " +
1536 "denote something else");
1541 vi = new LocalInfo (type, name, this, l);
1543 variables.Add (name, vi);
1545 // Mark 'name' as "used by a child block" in every surrounding block
1547 while (cur != null && cur.Implicit)
1550 for (Block par = cur.Parent; par != null; par = par.Parent)
1551 par.AddChildVariableName (name);
1553 if ((flags & Flags.VariablesInitialized) != 0)
1554 throw new Exception ();
1556 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1560 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1562 if (AddVariable (type, name, pars, l) == null)
1565 if (constants == null)
1566 constants = new Hashtable ();
1568 constants.Add (name, value);
1572 public Hashtable Variables {
1578 public LocalInfo GetLocalInfo (string name)
1580 for (Block b = this; b != null; b = b.Parent) {
1581 if (b.variables != null) {
1582 LocalInfo ret = b.variables [name] as LocalInfo;
1590 public Expression GetVariableType (string name)
1592 LocalInfo vi = GetLocalInfo (name);
1600 public Expression GetConstantExpression (string name)
1602 for (Block b = this; b != null; b = b.Parent) {
1603 if (b.constants != null) {
1604 Expression ret = b.constants [name] as Expression;
1613 /// True if the variable named @name is a constant
1615 public bool IsConstant (string name)
1617 Expression e = null;
1619 e = GetConstantExpression (name);
1625 // Returns a `ParameterReference' for the given name, or null if there
1626 // is no such parameter
1628 public ParameterReference GetParameterReference (string name, Location loc)
1633 Parameters pars = b.parameters;
1639 par = pars.GetParameterByName (name, out idx);
1641 ParameterReference pr;
1643 pr = new ParameterReference (pars, this, idx, name, loc);
1648 } while (b != null);
1653 // Whether the parameter named `name' is local to this block,
1654 // or false, if the parameter belongs to an encompassing block.
1656 public bool IsLocalParameter (string name)
1659 int toplevel_count = 0;
1662 if (this is ToplevelBlock)
1665 Parameters pars = b.parameters;
1667 if (pars.GetParameterByName (name) != null)
1671 if (toplevel_count > 0)
1674 } while (b != null);
1679 // Whether the `name' is a parameter reference
1681 public bool IsParameterReference (string name)
1686 Parameters pars = b.parameters;
1689 if (pars.GetParameterByName (name) != null)
1692 } while (b != null);
1697 /// A list of labels that were not used within this block
1699 public string [] GetUnreferenced ()
1701 // FIXME: Implement me
1705 public void AddStatement (Statement s)
1708 flags |= Flags.BlockUsed;
1713 return (flags & Flags.BlockUsed) != 0;
1719 flags |= Flags.BlockUsed;
1722 public bool HasRet {
1724 return (flags & Flags.HasRet) != 0;
1728 public bool IsDestructor {
1730 return (flags & Flags.IsDestructor) != 0;
1734 public void SetDestructor ()
1736 flags |= Flags.IsDestructor;
1739 VariableMap param_map, local_map;
1741 public VariableMap ParameterMap {
1743 if ((flags & Flags.VariablesInitialized) == 0)
1744 throw new Exception ("Variables have not been initialized yet");
1750 public VariableMap LocalMap {
1752 if ((flags & Flags.VariablesInitialized) == 0)
1753 throw new Exception ("Variables have not been initialized yet");
1760 /// Emits the variable declarations and labels.
1763 /// tc: is our typecontainer (to resolve type references)
1764 /// ig: is the code generator:
1766 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1768 bool old_unsafe = ec.InUnsafe;
1770 // If some parent block was unsafe, we remain unsafe even if this block
1771 // isn't explicitly marked as such.
1772 ec.InUnsafe |= Unsafe;
1775 // Compute the VariableMap's.
1777 // Unfortunately, we don't know the type when adding variables with
1778 // AddVariable(), so we need to compute this info here.
1782 if (variables != null) {
1783 foreach (LocalInfo li in variables.Values)
1786 locals = new LocalInfo [variables.Count];
1787 variables.Values.CopyTo (locals, 0);
1789 locals = new LocalInfo [0];
1792 local_map = new VariableMap (Parent.LocalMap, locals);
1794 local_map = new VariableMap (locals);
1796 param_map = new VariableMap (ip);
1797 flags |= Flags.VariablesInitialized;
1799 bool old_check_state = ec.ConstantCheckState;
1800 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1803 // Process this block variables
1805 if (variables != null){
1806 foreach (DictionaryEntry de in variables){
1807 string name = (string) de.Key;
1808 LocalInfo vi = (LocalInfo) de.Value;
1810 if (vi.VariableType == null)
1813 Type variable_type = vi.VariableType;
1815 if (variable_type.IsPointer){
1817 // Am not really convinced that this test is required (Microsoft does it)
1818 // but the fact is that you would not be able to use the pointer variable
1821 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1828 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1831 // This is needed to compile on both .NET 1.x and .NET 2.x
1832 // the later introduced `DeclareLocal (Type t, bool pinned)'
1834 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1835 else if (!vi.IsThis)
1836 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1839 if (constants == null)
1842 Expression cv = (Expression) constants [name];
1846 ec.CurrentBlock = this;
1847 Expression e = cv.Resolve (ec);
1851 Constant ce = e as Constant;
1853 Report.Error (133, vi.Location,
1854 "The expression being assigned to `" +
1855 name + "' must be constant (" + e + ")");
1859 if (e.Type != variable_type){
1860 e = Const.ChangeType (vi.Location, ce, variable_type);
1865 constants.Remove (name);
1866 constants.Add (name, e);
1869 ec.ConstantCheckState = old_check_state;
1872 // Now, handle the children
1874 if (children != null){
1875 foreach (Block b in children)
1876 b.ResolveMeta (toplevel, ec, ip);
1878 ec.InUnsafe = old_unsafe;
1882 // Emits the local variable declarations for a block
1884 public void EmitMeta (EmitContext ec)
1886 ILGenerator ig = ec.ig;
1888 if (variables != null){
1889 bool have_captured_vars = ec.HaveCapturedVariables ();
1890 bool remap_locals = ec.RemapToProxy;
1892 foreach (DictionaryEntry de in variables){
1893 LocalInfo vi = (LocalInfo) de.Value;
1895 if (have_captured_vars && ec.IsCaptured (vi))
1899 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1903 // This is needed to compile on both .NET 1.x and .NET 2.x
1904 // the later introduced `DeclareLocal (Type t, bool pinned)'
1906 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1907 else if (!vi.IsThis)
1908 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1913 if (children != null){
1914 foreach (Block b in children)
1919 void UsageWarning (FlowBranching.UsageVector vector)
1923 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1924 foreach (DictionaryEntry de in variables){
1925 LocalInfo vi = (LocalInfo) de.Value;
1930 name = (string) de.Key;
1932 if (vector.IsAssigned (vi.VariableInfo)){
1933 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1935 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1941 bool unreachable_shown;
1943 public override bool Resolve (EmitContext ec)
1945 Block prev_block = ec.CurrentBlock;
1948 int errors = Report.Errors;
1950 ec.CurrentBlock = this;
1951 ec.StartFlowBranching (this);
1953 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1955 bool unreachable = unreachable_shown;
1957 int statement_count = statements.Count;
1958 for (int ix = 0; ix < statement_count; ix++){
1959 Statement s = (Statement) statements [ix];
1961 if (unreachable && !(s is LabeledStatement)) {
1962 if (s == EmptyStatement.Value)
1963 s.loc = EndLocation;
1965 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1968 if (s != EmptyStatement.Value)
1969 unreachable_shown = true;
1971 s.loc = Location.Null;
1973 if (ok && !(s is Block)) {
1974 statements [ix] = EmptyStatement.Value;
1979 if (s.Resolve (ec) == false) {
1981 statements [ix] = EmptyStatement.Value;
1985 num_statements = ix + 1;
1987 if (s is LabeledStatement)
1988 unreachable = false;
1990 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1993 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1994 ec.CurrentBranching, statement_count, num_statements);
1997 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1999 ec.CurrentBlock = prev_block;
2001 // If we're a non-static `struct' constructor which doesn't have an
2002 // initializer, then we must initialize all of the struct's fields.
2003 if ((this_variable != null) &&
2004 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
2005 !this_variable.IsThisAssigned (ec, loc))
2008 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2009 foreach (LabeledStatement label in labels.Values)
2010 if (!label.HasBeenReferenced)
2011 Report.Warning (164, label.Location,
2012 "This label has not been referenced");
2015 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2017 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2018 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2019 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2020 flags |= Flags.HasRet;
2022 if (ok && (errors == Report.Errors)) {
2023 if (RootContext.WarningLevel >= 3)
2024 UsageWarning (vector);
2030 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2032 unreachable_shown = true;
2034 if (warn && (RootContext.WarningLevel >= 2))
2035 Report.Warning (162, loc, "Unreachable code detected");
2038 return Resolve (ec);
2040 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2041 bool ok = Resolve (ec);
2042 ec.KillFlowBranching ();
2047 protected override void DoEmit (EmitContext ec)
2049 for (int ix = 0; ix < num_statements; ix++){
2050 Statement s = (Statement) statements [ix];
2052 // Check whether we are the last statement in a
2055 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2056 ec.IsLastStatement = true;
2058 ec.IsLastStatement = false;
2064 public override void Emit (EmitContext ec)
2066 Block prev_block = ec.CurrentBlock;
2068 ec.CurrentBlock = this;
2070 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2071 bool is_lexical_block = !Implicit && (Parent != null);
2073 if (emit_debug_info) {
2074 if (is_lexical_block)
2075 ec.ig.BeginScope ();
2077 if (variables != null) {
2078 foreach (DictionaryEntry de in variables) {
2079 string name = (string) de.Key;
2080 LocalInfo vi = (LocalInfo) de.Value;
2082 if (vi.LocalBuilder == null)
2085 ec.DefineLocalVariable (name, vi.LocalBuilder);
2090 ec.Mark (StartLocation, true);
2092 ec.Mark (EndLocation, true);
2094 if (emit_debug_info && is_lexical_block)
2097 ec.CurrentBlock = prev_block;
2100 public ToplevelBlock Toplevel {
2103 while (b.Parent != null){
2104 if ((b.flags & Flags.IsToplevel) != 0)
2109 return (ToplevelBlock) b;
2114 // Returns true if we ar ea child of `b'.
2116 public bool IsChildOf (Block b)
2118 Block current = this;
2121 if (current.Parent == b)
2123 current = current.Parent;
2124 } while (current != null);
2130 // A toplevel block contains extra information, the split is done
2131 // only to separate information that would otherwise bloat the more
2132 // lightweight Block.
2134 // In particular, this was introduced when the support for Anonymous
2135 // Methods was implemented.
2137 public class ToplevelBlock : Block {
2139 // Pointer to the host of this anonymous method, or null
2140 // if we are the topmost block
2142 public ToplevelBlock Container;
2143 CaptureContext capture_context;
2145 Hashtable capture_contexts;
2150 public void RegisterCaptureContext (CaptureContext cc)
2152 if (capture_contexts == null)
2153 capture_contexts = new Hashtable ();
2154 capture_contexts [cc] = cc;
2157 public void CompleteContexts ()
2159 if (capture_contexts == null)
2162 foreach (CaptureContext cc in capture_contexts.Keys){
2167 public CaptureContext ToplevelBlockCaptureContext {
2169 return capture_context;
2174 // Parent is only used by anonymous blocks to link back to their
2177 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2178 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2180 Container = container;
2183 public ToplevelBlock (Parameters parameters, Location start) :
2184 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2188 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2189 base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2193 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2197 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2199 if (capture_context == null)
2200 capture_context = new CaptureContext (this, loc, host);
2203 public CaptureContext CaptureContext {
2205 return capture_context;
2210 public class SwitchLabel {
2213 public Location loc;
2217 Label il_label_code;
2218 bool il_label_code_set;
2221 // if expr == null, then it is the default case.
2223 public SwitchLabel (Expression expr, Location l)
2229 public Expression Label {
2235 public object Converted {
2241 public Label GetILLabel (EmitContext ec)
2244 il_label = ec.ig.DefineLabel ();
2245 il_label_set = true;
2250 public Label GetILLabelCode (EmitContext ec)
2252 if (!il_label_code_set){
2253 il_label_code = ec.ig.DefineLabel ();
2254 il_label_code_set = true;
2256 return il_label_code;
2260 // Resolves the expression, reduces it to a literal if possible
2261 // and then converts it to the requested type.
2263 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2268 Expression e = label.Resolve (ec);
2273 if (!(e is Constant)){
2274 Report.Error (150, loc, "A constant value is expected, got: " + e);
2278 if (e is StringConstant || e is NullLiteral){
2279 if (required_type == TypeManager.string_type){
2285 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2286 if (converted == null)
2293 public class SwitchSection {
2294 // An array of SwitchLabels.
2295 public readonly ArrayList Labels;
2296 public readonly Block Block;
2298 public SwitchSection (ArrayList labels, Block block)
2305 public class Switch : Statement {
2306 public readonly ArrayList Sections;
2307 public Expression Expr;
2310 /// Maps constants whose type type SwitchType to their SwitchLabels.
2312 public Hashtable Elements;
2315 /// The governing switch type
2317 public Type SwitchType;
2323 Label default_target;
2324 Expression new_expr;
2326 SwitchSection constant_section;
2329 // The types allowed to be implicitly cast from
2330 // on the governing type
2332 static Type [] allowed_types;
2334 public Switch (Expression e, ArrayList sects, Location l)
2341 public bool GotDefault {
2347 public Label DefaultTarget {
2349 return default_target;
2354 // Determines the governing type for a switch. The returned
2355 // expression might be the expression from the switch, or an
2356 // expression that includes any potential conversions to the
2357 // integral types or to string.
2359 Expression SwitchGoverningType (EmitContext ec, Type t)
2361 if (t == TypeManager.int32_type ||
2362 t == TypeManager.uint32_type ||
2363 t == TypeManager.char_type ||
2364 t == TypeManager.byte_type ||
2365 t == TypeManager.sbyte_type ||
2366 t == TypeManager.ushort_type ||
2367 t == TypeManager.short_type ||
2368 t == TypeManager.uint64_type ||
2369 t == TypeManager.int64_type ||
2370 t == TypeManager.string_type ||
2371 t == TypeManager.bool_type ||
2372 t.IsSubclassOf (TypeManager.enum_type))
2375 if (allowed_types == null){
2376 allowed_types = new Type [] {
2377 TypeManager.int32_type,
2378 TypeManager.uint32_type,
2379 TypeManager.sbyte_type,
2380 TypeManager.byte_type,
2381 TypeManager.short_type,
2382 TypeManager.ushort_type,
2383 TypeManager.int64_type,
2384 TypeManager.uint64_type,
2385 TypeManager.char_type,
2386 TypeManager.bool_type,
2387 TypeManager.string_type
2392 // Try to find a *user* defined implicit conversion.
2394 // If there is no implicit conversion, or if there are multiple
2395 // conversions, we have to report an error
2397 Expression converted = null;
2400 // VB.NET has no notion of User defined conversions
2403 // foreach (Type tt in allowed_types){
2406 // e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2411 // // Ignore over-worked ImplicitUserConversions that do
2412 // // an implicit conversion in addition to the user conversion.
2414 // if (e is UserCast){
2415 // UserCast ue = e as UserCast;
2417 // if (ue.Source != Expr)
2421 // if (converted != null){
2422 // Report.ExtraInformation (
2424 // String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2425 // TypeManager.CSharpName (Expr.Type)));
2434 static string Error152 {
2436 return "The label '{0}:' already occurs in this switch statement";
2441 // Performs the basic sanity checks on the switch statement
2442 // (looks for duplicate keys and non-constant expressions).
2444 // It also returns a hashtable with the keys that we will later
2445 // use to compute the switch tables
2447 bool CheckSwitch (EmitContext ec)
2451 Elements = new Hashtable ();
2453 got_default = false;
2455 if (TypeManager.IsEnumType (SwitchType)){
2456 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2458 compare_type = SwitchType;
2460 foreach (SwitchSection ss in Sections){
2461 foreach (SwitchLabel sl in ss.Labels){
2462 if (!sl.ResolveAndReduce (ec, SwitchType)){
2467 if (sl.Label == null){
2469 Report.Error (152, sl.loc, Error152, "default");
2476 object key = sl.Converted;
2478 if (key is Constant)
2479 key = ((Constant) key).GetValue ();
2482 key = NullLiteral.Null;
2484 string lname = null;
2485 if (compare_type == TypeManager.uint64_type){
2486 ulong v = (ulong) key;
2488 if (Elements.Contains (v))
2489 lname = v.ToString ();
2491 Elements.Add (v, sl);
2492 } else if (compare_type == TypeManager.int64_type){
2493 long v = (long) key;
2495 if (Elements.Contains (v))
2496 lname = v.ToString ();
2498 Elements.Add (v, sl);
2499 } else if (compare_type == TypeManager.uint32_type){
2500 uint v = (uint) key;
2502 if (Elements.Contains (v))
2503 lname = v.ToString ();
2505 Elements.Add (v, sl);
2506 } else if (compare_type == TypeManager.char_type){
2507 char v = (char) key;
2509 if (Elements.Contains (v))
2510 lname = v.ToString ();
2512 Elements.Add (v, sl);
2513 } else if (compare_type == TypeManager.byte_type){
2514 byte v = (byte) key;
2516 if (Elements.Contains (v))
2517 lname = v.ToString ();
2519 Elements.Add (v, sl);
2520 } else if (compare_type == TypeManager.sbyte_type){
2521 sbyte v = (sbyte) key;
2523 if (Elements.Contains (v))
2524 lname = v.ToString ();
2526 Elements.Add (v, sl);
2527 } else if (compare_type == TypeManager.short_type){
2528 short v = (short) key;
2530 if (Elements.Contains (v))
2531 lname = v.ToString ();
2533 Elements.Add (v, sl);
2534 } else if (compare_type == TypeManager.ushort_type){
2535 ushort v = (ushort) key;
2537 if (Elements.Contains (v))
2538 lname = v.ToString ();
2540 Elements.Add (v, sl);
2541 } else if (compare_type == TypeManager.string_type){
2542 if (key is NullLiteral){
2543 if (Elements.Contains (NullLiteral.Null))
2546 Elements.Add (NullLiteral.Null, null);
2548 string s = (string) key;
2550 if (Elements.Contains (s))
2553 Elements.Add (s, sl);
2555 } else if (compare_type == TypeManager.int32_type) {
2558 if (Elements.Contains (v))
2559 lname = v.ToString ();
2561 Elements.Add (v, sl);
2562 } else if (compare_type == TypeManager.bool_type) {
2563 bool v = (bool) key;
2565 if (Elements.Contains (v))
2566 lname = v.ToString ();
2568 Elements.Add (v, sl);
2572 throw new Exception ("Unknown switch type!" +
2573 SwitchType + " " + compare_type);
2577 Report.Error (152, sl.loc, Error152, "case " + lname);
2588 void EmitObjectInteger (ILGenerator ig, object k)
2591 IntConstant.EmitInt (ig, (int) k);
2592 else if (k is Constant) {
2593 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2596 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2599 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2601 IntConstant.EmitInt (ig, (int) (long) k);
2602 ig.Emit (OpCodes.Conv_I8);
2605 LongConstant.EmitLong (ig, (long) k);
2607 else if (k is ulong)
2609 if ((ulong) k < (1L<<32))
2611 IntConstant.EmitInt (ig, (int) (long) k);
2612 ig.Emit (OpCodes.Conv_U8);
2616 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2620 IntConstant.EmitInt (ig, (int) ((char) k));
2621 else if (k is sbyte)
2622 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2624 IntConstant.EmitInt (ig, (int) ((byte) k));
2625 else if (k is short)
2626 IntConstant.EmitInt (ig, (int) ((short) k));
2627 else if (k is ushort)
2628 IntConstant.EmitInt (ig, (int) ((ushort) k));
2630 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2632 throw new Exception ("Unhandled case");
2635 // structure used to hold blocks of keys while calculating table switch
2636 class KeyBlock : IComparable
2638 public KeyBlock (long _nFirst)
2640 nFirst = nLast = _nFirst;
2644 public ArrayList rgKeys = null;
2645 // how many items are in the bucket
2646 public int Size = 1;
2649 get { return (int) (nLast - nFirst + 1); }
2651 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2653 return kbLast.nLast - kbFirst.nFirst + 1;
2655 public int CompareTo (object obj)
2657 KeyBlock kb = (KeyBlock) obj;
2658 int nLength = Length;
2659 int nLengthOther = kb.Length;
2660 if (nLengthOther == nLength)
2661 return (int) (kb.nFirst - nFirst);
2662 return nLength - nLengthOther;
2667 /// This method emits code for a lookup-based switch statement (non-string)
2668 /// Basically it groups the cases into blocks that are at least half full,
2669 /// and then spits out individual lookup opcodes for each block.
2670 /// It emits the longest blocks first, and short blocks are just
2671 /// handled with direct compares.
2673 /// <param name="ec"></param>
2674 /// <param name="val"></param>
2675 /// <returns></returns>
2676 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2678 int cElements = Elements.Count;
2679 object [] rgKeys = new object [cElements];
2680 Elements.Keys.CopyTo (rgKeys, 0);
2681 Array.Sort (rgKeys);
2683 // initialize the block list with one element per key
2684 ArrayList rgKeyBlocks = new ArrayList ();
2685 foreach (object key in rgKeys)
2686 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2689 // iteratively merge the blocks while they are at least half full
2690 // there's probably a really cool way to do this with a tree...
2691 while (rgKeyBlocks.Count > 1)
2693 ArrayList rgKeyBlocksNew = new ArrayList ();
2694 kbCurr = (KeyBlock) rgKeyBlocks [0];
2695 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2697 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2698 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2701 kbCurr.nLast = kb.nLast;
2702 kbCurr.Size += kb.Size;
2706 // start a new block
2707 rgKeyBlocksNew.Add (kbCurr);
2711 rgKeyBlocksNew.Add (kbCurr);
2712 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2714 rgKeyBlocks = rgKeyBlocksNew;
2717 // initialize the key lists
2718 foreach (KeyBlock kb in rgKeyBlocks)
2719 kb.rgKeys = new ArrayList ();
2721 // fill the key lists
2723 if (rgKeyBlocks.Count > 0) {
2724 kbCurr = (KeyBlock) rgKeyBlocks [0];
2725 foreach (object key in rgKeys)
2727 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2728 System.Convert.ToInt64 (key) > kbCurr.nLast;
2730 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2731 kbCurr.rgKeys.Add (key);
2735 // sort the blocks so we can tackle the largest ones first
2736 rgKeyBlocks.Sort ();
2738 // okay now we can start...
2739 ILGenerator ig = ec.ig;
2740 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2741 Label lblDefault = ig.DefineLabel ();
2743 Type typeKeys = null;
2744 if (rgKeys.Length > 0)
2745 typeKeys = rgKeys [0].GetType (); // used for conversions
2749 if (TypeManager.IsEnumType (SwitchType))
2750 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2752 compare_type = SwitchType;
2754 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2756 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2757 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2760 foreach (object key in kb.rgKeys)
2762 ig.Emit (OpCodes.Ldloc, val);
2763 EmitObjectInteger (ig, key);
2764 SwitchLabel sl = (SwitchLabel) Elements [key];
2765 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2770 // TODO: if all the keys in the block are the same and there are
2771 // no gaps/defaults then just use a range-check.
2772 if (compare_type == TypeManager.int64_type ||
2773 compare_type == TypeManager.uint64_type)
2775 // TODO: optimize constant/I4 cases
2777 // check block range (could be > 2^31)
2778 ig.Emit (OpCodes.Ldloc, val);
2779 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2780 ig.Emit (OpCodes.Blt, lblDefault);
2781 ig.Emit (OpCodes.Ldloc, val);
2782 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2783 ig.Emit (OpCodes.Bgt, lblDefault);
2786 ig.Emit (OpCodes.Ldloc, val);
2789 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2790 ig.Emit (OpCodes.Sub);
2792 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2797 ig.Emit (OpCodes.Ldloc, val);
2798 int nFirst = (int) kb.nFirst;
2801 IntConstant.EmitInt (ig, nFirst);
2802 ig.Emit (OpCodes.Sub);
2804 else if (nFirst < 0)
2806 IntConstant.EmitInt (ig, -nFirst);
2807 ig.Emit (OpCodes.Add);
2811 // first, build the list of labels for the switch
2813 int cJumps = kb.Length;
2814 Label [] rgLabels = new Label [cJumps];
2815 for (int iJump = 0; iJump < cJumps; iJump++)
2817 object key = kb.rgKeys [iKey];
2818 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2820 SwitchLabel sl = (SwitchLabel) Elements [key];
2821 rgLabels [iJump] = sl.GetILLabel (ec);
2825 rgLabels [iJump] = lblDefault;
2827 // emit the switch opcode
2828 ig.Emit (OpCodes.Switch, rgLabels);
2831 // mark the default for this block
2833 ig.MarkLabel (lblDefault);
2836 // TODO: find the default case and emit it here,
2837 // to prevent having to do the following jump.
2838 // make sure to mark other labels in the default section
2840 // the last default just goes to the end
2841 ig.Emit (OpCodes.Br, lblDefault);
2843 // now emit the code for the sections
2844 bool fFoundDefault = false;
2845 foreach (SwitchSection ss in Sections)
2847 foreach (SwitchLabel sl in ss.Labels)
2849 ig.MarkLabel (sl.GetILLabel (ec));
2850 ig.MarkLabel (sl.GetILLabelCode (ec));
2851 if (sl.Label == null)
2853 ig.MarkLabel (lblDefault);
2854 fFoundDefault = true;
2858 //ig.Emit (OpCodes.Br, lblEnd);
2861 if (!fFoundDefault) {
2862 ig.MarkLabel (lblDefault);
2864 ig.MarkLabel (lblEnd);
2867 // This simple emit switch works, but does not take advantage of the
2869 // TODO: remove non-string logic from here
2870 // TODO: binary search strings?
2872 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2874 ILGenerator ig = ec.ig;
2875 Label end_of_switch = ig.DefineLabel ();
2876 Label next_test = ig.DefineLabel ();
2877 Label null_target = ig.DefineLabel ();
2878 bool default_found = false;
2879 bool first_test = true;
2880 bool pending_goto_end = false;
2882 bool default_at_end = false;
2884 ig.Emit (OpCodes.Ldloc, val);
2886 if (Elements.Contains (NullLiteral.Null)){
2887 ig.Emit (OpCodes.Brfalse, null_target);
2889 ig.Emit (OpCodes.Brfalse, default_target);
2891 ig.Emit (OpCodes.Ldloc, val);
2892 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2893 ig.Emit (OpCodes.Stloc, val);
2895 int section_count = Sections.Count;
2896 for (int section = 0; section < section_count; section++){
2897 SwitchSection ss = (SwitchSection) Sections [section];
2898 Label sec_begin = ig.DefineLabel ();
2900 if (pending_goto_end)
2901 ig.Emit (OpCodes.Br, end_of_switch);
2903 int label_count = ss.Labels.Count;
2904 bool mark_default = false;
2906 for (int label = 0; label < label_count; label++){
2907 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2908 ig.MarkLabel (sl.GetILLabel (ec));
2911 ig.MarkLabel (next_test);
2912 next_test = ig.DefineLabel ();
2915 // If we are the default target
2917 if (sl.Label == null){
2918 if (label+1 == label_count)
2919 default_at_end = true;
2920 mark_default = true;
2921 default_found = true;
2923 object lit = sl.Converted;
2925 if (lit is NullLiteral){
2927 if (label_count == 1)
2928 ig.Emit (OpCodes.Br, next_test);
2932 StringConstant str = (StringConstant) lit;
2934 ig.Emit (OpCodes.Ldloc, val);
2935 ig.Emit (OpCodes.Ldstr, str.Value);
2936 if (label_count == 1)
2937 ig.Emit (OpCodes.Bne_Un, next_test);
2939 if (label+1 == label_count)
2940 ig.Emit (OpCodes.Bne_Un, next_test);
2942 ig.Emit (OpCodes.Beq, sec_begin);
2947 ig.MarkLabel (null_target);
2948 ig.MarkLabel (sec_begin);
2949 foreach (SwitchLabel sl in ss.Labels)
2950 ig.MarkLabel (sl.GetILLabelCode (ec));
2953 ig.MarkLabel (default_target);
2955 pending_goto_end = !ss.Block.HasRet;
2958 ig.MarkLabel (next_test);
2960 if (!default_at_end)
2961 ig.Emit (OpCodes.Br, default_target);
2963 ig.MarkLabel (default_target);
2964 ig.MarkLabel (end_of_switch);
2967 SwitchSection FindSection (SwitchLabel label)
2969 foreach (SwitchSection ss in Sections){
2970 foreach (SwitchLabel sl in ss.Labels){
2979 bool ResolveConstantSwitch (EmitContext ec)
2981 object key = ((Constant) new_expr).GetValue ();
2982 SwitchLabel label = (SwitchLabel) Elements [key];
2987 constant_section = FindSection (label);
2988 if (constant_section == null)
2991 if (constant_section.Block.Resolve (ec) != true)
2997 public override bool Resolve (EmitContext ec)
2999 Expr = Expr.Resolve (ec);
3003 new_expr = SwitchGoverningType (ec, Expr.Type);
3004 if (new_expr == null){
3005 Report.Error (151, loc, "An integer type or string was expected for switch");
3010 SwitchType = new_expr.Type;
3012 if (!CheckSwitch (ec))
3015 Switch old_switch = ec.Switch;
3017 ec.Switch.SwitchType = SwitchType;
3019 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3020 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3022 is_constant = new_expr is Constant;
3024 object key = ((Constant) new_expr).GetValue ();
3025 SwitchLabel label = (SwitchLabel) Elements [key];
3027 constant_section = FindSection (label);
3031 foreach (SwitchSection ss in Sections){
3033 ec.CurrentBranching.CreateSibling (
3034 null, FlowBranching.SiblingType.SwitchSection);
3038 if (is_constant && (ss != constant_section)) {
3039 // If we're a constant switch, we're only emitting
3040 // one single section - mark all the others as
3042 ec.CurrentBranching.CurrentUsageVector.Goto ();
3043 if (!ss.Block.ResolveUnreachable (ec, true))
3046 if (!ss.Block.Resolve (ec))
3052 ec.CurrentBranching.CreateSibling (
3053 null, FlowBranching.SiblingType.SwitchSection);
3055 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3056 ec.Switch = old_switch;
3058 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3064 protected override void DoEmit (EmitContext ec)
3066 ILGenerator ig = ec.ig;
3068 // Store variable for comparission purposes
3071 value = ig.DeclareLocal (SwitchType);
3073 ig.Emit (OpCodes.Stloc, value);
3077 default_target = ig.DefineLabel ();
3080 // Setup the codegen context
3082 Label old_end = ec.LoopEnd;
3083 Switch old_switch = ec.Switch;
3085 ec.LoopEnd = ig.DefineLabel ();
3090 if (constant_section != null)
3091 constant_section.Block.Emit (ec);
3092 } else if (SwitchType == TypeManager.string_type)
3093 SimpleSwitchEmit (ec, value);
3095 TableSwitchEmit (ec, value);
3097 // Restore context state.
3098 ig.MarkLabel (ec.LoopEnd);
3101 // Restore the previous context
3103 ec.LoopEnd = old_end;
3104 ec.Switch = old_switch;
3108 public abstract class ExceptionStatement : Statement
3110 public abstract void EmitFinally (EmitContext ec);
3112 protected bool emit_finally = true;
3113 ArrayList parent_vectors;
3115 protected void DoEmitFinally (EmitContext ec)
3118 ec.ig.BeginFinallyBlock ();
3120 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3124 protected void ResolveFinally (FlowBranchingException branching)
3126 emit_finally = branching.EmitFinally;
3128 branching.Parent.StealFinallyClauses (ref parent_vectors);
3132 public class Lock : ExceptionStatement {
3134 Statement Statement;
3137 public Lock (Expression expr, Statement stmt, Location l)
3144 public override bool Resolve (EmitContext ec)
3146 expr = expr.Resolve (ec);
3150 if (expr.Type.IsValueType){
3151 Error (185, "lock statement requires the expression to be " +
3152 " a reference type (type is: `{0}'",
3153 TypeManager.CSharpName (expr.Type));
3157 FlowBranchingException branching = ec.StartFlowBranching (this);
3158 bool ok = Statement.Resolve (ec);
3160 ec.KillFlowBranching ();
3164 ResolveFinally (branching);
3166 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3167 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3168 // Unfortunately, System.Reflection.Emit automatically emits
3169 // a leave to the end of the finally block.
3170 // This is a problem if `returns' is true since we may jump
3171 // to a point after the end of the method.
3172 // As a workaround, emit an explicit ret here.
3173 ec.NeedReturnLabel ();
3179 protected override void DoEmit (EmitContext ec)
3181 Type type = expr.Type;
3183 ILGenerator ig = ec.ig;
3184 temp = ig.DeclareLocal (type);
3187 ig.Emit (OpCodes.Dup);
3188 ig.Emit (OpCodes.Stloc, temp);
3189 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3193 ig.BeginExceptionBlock ();
3194 Statement.Emit (ec);
3199 ig.EndExceptionBlock ();
3202 public override void EmitFinally (EmitContext ec)
3204 ILGenerator ig = ec.ig;
3205 ig.Emit (OpCodes.Ldloc, temp);
3206 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3210 public class Unchecked : Statement {
3211 public readonly Block Block;
3213 public Unchecked (Block b)
3219 public override bool Resolve (EmitContext ec)
3221 bool previous_state = ec.CheckState;
3222 bool previous_state_const = ec.ConstantCheckState;
3224 ec.CheckState = false;
3225 ec.ConstantCheckState = false;
3226 bool ret = Block.Resolve (ec);
3227 ec.CheckState = previous_state;
3228 ec.ConstantCheckState = previous_state_const;
3233 protected override void DoEmit (EmitContext ec)
3235 bool previous_state = ec.CheckState;
3236 bool previous_state_const = ec.ConstantCheckState;
3238 ec.CheckState = false;
3239 ec.ConstantCheckState = false;
3241 ec.CheckState = previous_state;
3242 ec.ConstantCheckState = previous_state_const;
3246 public class Checked : Statement {
3247 public readonly Block Block;
3249 public Checked (Block b)
3252 b.Unchecked = false;
3255 public override bool Resolve (EmitContext ec)
3257 bool previous_state = ec.CheckState;
3258 bool previous_state_const = ec.ConstantCheckState;
3260 ec.CheckState = true;
3261 ec.ConstantCheckState = true;
3262 bool ret = Block.Resolve (ec);
3263 ec.CheckState = previous_state;
3264 ec.ConstantCheckState = previous_state_const;
3269 protected override void DoEmit (EmitContext ec)
3271 bool previous_state = ec.CheckState;
3272 bool previous_state_const = ec.ConstantCheckState;
3274 ec.CheckState = true;
3275 ec.ConstantCheckState = true;
3277 ec.CheckState = previous_state;
3278 ec.ConstantCheckState = previous_state_const;
3282 public class Unsafe : Statement {
3283 public readonly Block Block;
3285 public Unsafe (Block b)
3288 Block.Unsafe = true;
3291 public override bool Resolve (EmitContext ec)
3293 bool previous_state = ec.InUnsafe;
3297 val = Block.Resolve (ec);
3298 ec.InUnsafe = previous_state;
3303 protected override void DoEmit (EmitContext ec)
3305 bool previous_state = ec.InUnsafe;
3309 ec.InUnsafe = previous_state;
3316 public class Fixed : Statement {
3318 ArrayList declarators;
3319 Statement statement;
3325 public bool is_object;
3326 public LocalInfo vi;
3327 public Expression expr;
3328 public Expression converted;
3331 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3334 declarators = decls;
3339 public override bool Resolve (EmitContext ec)
3342 Expression.UnsafeError (loc);
3346 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3350 expr_type = texpr.Type;
3352 CheckObsolete (expr_type);
3354 if (ec.RemapToProxy){
3355 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3359 data = new FixedData [declarators.Count];
3361 if (!expr_type.IsPointer){
3362 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3367 foreach (Pair p in declarators){
3368 LocalInfo vi = (LocalInfo) p.First;
3369 Expression e = (Expression) p.Second;
3371 vi.VariableInfo.SetAssigned (ec);
3375 // The rules for the possible declarators are pretty wise,
3376 // but the production on the grammar is more concise.
3378 // So we have to enforce these rules here.
3380 // We do not resolve before doing the case 1 test,
3381 // because the grammar is explicit in that the token &
3382 // is present, so we need to test for this particular case.
3386 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3391 // Case 1: & object.
3393 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3394 Expression child = ((Unary) e).Expr;
3396 if (child is ParameterReference || child is LocalVariableReference){
3399 "No need to use fixed statement for parameters or " +
3400 "local variable declarations (address is already " +
3405 ec.InFixedInitializer = true;
3407 ec.InFixedInitializer = false;
3411 child = ((Unary) e).Expr;
3413 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3416 data [i].is_object = true;
3418 data [i].converted = null;
3425 ec.InFixedInitializer = true;
3427 ec.InFixedInitializer = false;
3434 if (e.Type.IsArray){
3435 Type array_type = TypeManager.GetElementType (e.Type);
3438 // Provided that array_type is unmanaged,
3440 if (!TypeManager.VerifyUnManaged (array_type, loc))
3444 // and T* is implicitly convertible to the
3445 // pointer type given in the fixed statement.
3447 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3449 Expression converted = Convert.WideningConversionRequired (
3450 ec, array_ptr, vi.VariableType, loc);
3451 if (converted == null)
3454 data [i].is_object = false;
3456 data [i].converted = converted;
3466 if (e.Type == TypeManager.string_type){
3467 data [i].is_object = false;
3469 data [i].converted = null;
3476 // For other cases, flag a `this is already fixed expression'
3478 if (e is LocalVariableReference || e is ParameterReference ||
3479 Convert.WideningConversionExists (ec, e, vi.VariableType)){
3481 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3485 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3489 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3491 if (!statement.Resolve (ec)) {
3492 ec.KillFlowBranching ();
3496 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3497 has_ret = reachability.IsUnreachable;
3502 protected override void DoEmit (EmitContext ec)
3504 ILGenerator ig = ec.ig;
3506 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3508 for (int i = 0; i < data.Length; i++) {
3509 LocalInfo vi = data [i].vi;
3512 // Case 1: & object.
3514 if (data [i].is_object) {
3516 // Store pointer in pinned location
3518 data [i].expr.Emit (ec);
3519 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3520 clear_list [i] = vi.LocalBuilder;
3527 if (data [i].expr.Type.IsArray){
3529 // Store pointer in pinned location
3531 data [i].converted.Emit (ec);
3533 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3534 clear_list [i] = vi.LocalBuilder;
3541 if (data [i].expr.Type == TypeManager.string_type){
3542 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3543 clear_list [i] = pinned_string;
3545 data [i].expr.Emit (ec);
3546 ig.Emit (OpCodes.Stloc, pinned_string);
3548 Expression sptr = new StringPtr (pinned_string, loc);
3549 Expression converted = Convert.WideningConversionRequired (
3550 ec, sptr, vi.VariableType, loc);
3552 if (converted == null)
3555 converted.Emit (ec);
3556 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3560 statement.Emit (ec);
3566 // Clear the pinned variable
3568 for (int i = 0; i < data.Length; i++) {
3569 if (data [i].is_object || data [i].expr.Type.IsArray) {
3570 ig.Emit (OpCodes.Ldc_I4_0);
3571 ig.Emit (OpCodes.Conv_U);
3572 ig.Emit (OpCodes.Stloc, clear_list [i]);
3573 } else if (data [i].expr.Type == TypeManager.string_type){
3574 ig.Emit (OpCodes.Ldnull);
3575 ig.Emit (OpCodes.Stloc, clear_list [i]);
3581 public class Catch: Statement {
3582 public readonly string Name;
3583 public readonly Block Block;
3585 Expression type_expr;
3588 public Catch (Expression type, string name, Block block, Location l)
3596 public Type CatchType {
3602 public bool IsGeneral {
3604 return type_expr == null;
3608 protected override void DoEmit(EmitContext ec)
3612 public override bool Resolve (EmitContext ec)
3614 if (type_expr != null) {
3615 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3621 CheckObsolete (type);
3623 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3624 Error (155, "The type caught or thrown must be derived from System.Exception");
3630 return Block.Resolve (ec);
3634 public class Try : ExceptionStatement {
3635 public readonly Block Fini, Block;
3636 public readonly ArrayList Specific;
3637 public readonly Catch General;
3639 bool need_exc_block;
3642 // specific, general and fini might all be null.
3644 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3646 if (specific == null && general == null){
3647 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3651 this.Specific = specific;
3652 this.General = general;
3657 public override bool Resolve (EmitContext ec)
3661 FlowBranchingException branching = ec.StartFlowBranching (this);
3663 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3665 if (!Block.Resolve (ec))
3668 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3670 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3672 Type[] prevCatches = new Type [Specific.Count];
3674 foreach (Catch c in Specific){
3675 ec.CurrentBranching.CreateSibling (
3676 c.Block, FlowBranching.SiblingType.Catch);
3678 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3680 if (c.Name != null) {
3681 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3683 throw new Exception ();
3685 vi.VariableInfo = null;
3688 if (!c.Resolve (ec))
3691 Type resolvedType = c.CatchType;
3692 for (int ii = 0; ii < last_index; ++ii) {
3693 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3694 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3699 prevCatches [last_index++] = resolvedType;
3700 need_exc_block = true;
3703 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3705 if (General != null){
3706 ec.CurrentBranching.CreateSibling (
3707 General.Block, FlowBranching.SiblingType.Catch);
3709 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3711 if (!General.Resolve (ec))
3714 need_exc_block = true;
3717 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3721 ec.CurrentBranching.CreateSibling (
3722 Fini, FlowBranching.SiblingType.Finally);
3724 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3726 if (!Fini.Resolve (ec))
3730 ResolveFinally (branching);
3731 need_exc_block |= emit_finally;
3733 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3735 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3737 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3739 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3740 // Unfortunately, System.Reflection.Emit automatically emits
3741 // a leave to the end of the finally block. This is a problem
3742 // if `returns' is true since we may jump to a point after the
3743 // end of the method.
3744 // As a workaround, emit an explicit ret here.
3745 ec.NeedReturnLabel ();
3751 protected override void DoEmit (EmitContext ec)
3753 ILGenerator ig = ec.ig;
3756 ig.BeginExceptionBlock ();
3759 foreach (Catch c in Specific){
3762 ig.BeginCatchBlock (c.CatchType);
3764 if (c.Name != null){
3765 vi = c.Block.GetLocalInfo (c.Name);
3767 throw new Exception ("Variable does not exist in this block");
3769 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3771 ig.Emit (OpCodes.Pop);
3776 if (General != null){
3777 ig.BeginCatchBlock (TypeManager.object_type);
3778 ig.Emit (OpCodes.Pop);
3779 General.Block.Emit (ec);
3784 ig.EndExceptionBlock ();
3787 public override void EmitFinally (EmitContext ec)
3795 public class Using : ExceptionStatement {
3796 object expression_or_block;
3797 Statement Statement;
3802 Expression [] resolved_vars;
3803 Expression [] converted_vars;
3804 ExpressionStatement [] assign;
3805 LocalBuilder local_copy;
3807 public Using (object expression_or_block, Statement stmt, Location l)
3809 this.expression_or_block = expression_or_block;
3815 // Resolves for the case of using using a local variable declaration.
3817 bool ResolveLocalVariableDecls (EmitContext ec)
3821 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3825 expr_type = texpr.Type;
3828 // The type must be an IDisposable or an implicit conversion
3831 converted_vars = new Expression [var_list.Count];
3832 resolved_vars = new Expression [var_list.Count];
3833 assign = new ExpressionStatement [var_list.Count];
3835 bool need_conv = !TypeManager.ImplementsInterface (
3836 expr_type, TypeManager.idisposable_type);
3838 foreach (DictionaryEntry e in var_list){
3839 Expression var = (Expression) e.Key;
3841 var = var.ResolveLValue (ec, new EmptyExpression ());
3845 resolved_vars [i] = var;
3852 converted_vars [i] = Convert.WideningConversionRequired (
3853 ec, var, TypeManager.idisposable_type, loc);
3855 if (converted_vars [i] == null)
3862 foreach (DictionaryEntry e in var_list){
3863 Expression var = resolved_vars [i];
3864 Expression new_expr = (Expression) e.Value;
3867 a = new Assign (var, new_expr, loc);
3873 converted_vars [i] = var;
3874 assign [i] = (ExpressionStatement) a;
3881 bool ResolveExpression (EmitContext ec)
3883 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3884 conv = Convert.WideningConversionRequired (
3885 ec, expr, TypeManager.idisposable_type, loc);
3895 // Emits the code for the case of using using a local variable declaration.
3897 void EmitLocalVariableDecls (EmitContext ec)
3899 ILGenerator ig = ec.ig;
3902 for (i = 0; i < assign.Length; i++) {
3903 assign [i].EmitStatement (ec);
3906 ig.BeginExceptionBlock ();
3908 Statement.Emit (ec);
3910 var_list.Reverse ();
3915 void EmitLocalVariableDeclFinally (EmitContext ec)
3917 ILGenerator ig = ec.ig;
3919 int i = assign.Length;
3920 for (int ii = 0; ii < var_list.Count; ++ii){
3921 Expression var = resolved_vars [--i];
3922 Label skip = ig.DefineLabel ();
3924 ig.BeginFinallyBlock ();
3926 if (!var.Type.IsValueType) {
3928 ig.Emit (OpCodes.Brfalse, skip);
3929 converted_vars [i].Emit (ec);
3930 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3932 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3934 if (!(ml is MethodGroupExpr)) {
3936 ig.Emit (OpCodes.Box, var.Type);
3937 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3939 MethodInfo mi = null;
3941 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3942 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3949 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3953 IMemoryLocation mloc = (IMemoryLocation) var;
3955 mloc.AddressOf (ec, AddressOp.Load);
3956 ig.Emit (OpCodes.Call, mi);
3960 ig.MarkLabel (skip);
3963 ig.EndExceptionBlock ();
3965 ig.BeginFinallyBlock ();
3970 void EmitExpression (EmitContext ec)
3973 // Make a copy of the expression and operate on that.
3975 ILGenerator ig = ec.ig;
3976 local_copy = ig.DeclareLocal (expr_type);
3981 ig.Emit (OpCodes.Stloc, local_copy);
3984 ig.BeginExceptionBlock ();
3986 Statement.Emit (ec);
3990 ig.EndExceptionBlock ();
3993 void EmitExpressionFinally (EmitContext ec)
3995 ILGenerator ig = ec.ig;
3996 if (!local_copy.LocalType.IsValueType) {
3997 Label skip = ig.DefineLabel ();
3998 ig.Emit (OpCodes.Ldloc, local_copy);
3999 ig.Emit (OpCodes.Brfalse, skip);
4000 ig.Emit (OpCodes.Ldloc, local_copy);
4001 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4002 ig.MarkLabel (skip);
4004 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4006 if (!(ml is MethodGroupExpr)) {
4007 ig.Emit (OpCodes.Ldloc, local_copy);
4008 ig.Emit (OpCodes.Box, local_copy.LocalType);
4009 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4011 MethodInfo mi = null;
4013 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4014 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4021 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4025 ig.Emit (OpCodes.Ldloca, local_copy);
4026 ig.Emit (OpCodes.Call, mi);
4031 public override bool Resolve (EmitContext ec)
4033 if (expression_or_block is DictionaryEntry){
4034 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4035 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4037 if (!ResolveLocalVariableDecls (ec))
4040 } else if (expression_or_block is Expression){
4041 expr = (Expression) expression_or_block;
4043 expr = expr.Resolve (ec);
4047 expr_type = expr.Type;
4049 if (!ResolveExpression (ec))
4053 FlowBranchingException branching = ec.StartFlowBranching (this);
4055 bool ok = Statement.Resolve (ec);
4058 ec.KillFlowBranching ();
4062 ResolveFinally (branching);
4063 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4065 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4066 // Unfortunately, System.Reflection.Emit automatically emits a leave
4067 // to the end of the finally block. This is a problem if `returns'
4068 // is true since we may jump to a point after the end of the method.
4069 // As a workaround, emit an explicit ret here.
4070 ec.NeedReturnLabel ();
4076 protected override void DoEmit (EmitContext ec)
4078 if (expression_or_block is DictionaryEntry)
4079 EmitLocalVariableDecls (ec);
4080 else if (expression_or_block is Expression)
4081 EmitExpression (ec);
4084 public override void EmitFinally (EmitContext ec)
4086 if (expression_or_block is DictionaryEntry)
4087 EmitLocalVariableDeclFinally (ec);
4088 else if (expression_or_block is Expression)
4089 EmitExpressionFinally (ec);
4094 /// Implementation of the foreach C# statement
4096 public class Foreach : ExceptionStatement {
4098 Expression variable;
4100 Statement statement;
4101 ForeachHelperMethods hm;
4102 Expression empty, conv;
4103 Type array_type, element_type;
4105 VariableStorage enumerator;
4107 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4108 Statement stmt, Location l)
4111 this.variable = var;
4117 public override bool Resolve (EmitContext ec)
4119 expr = expr.Resolve (ec);
4123 if (expr is NullLiteral) {
4124 Report.Error (186, expr.Location, "Use of null is not valid in this context");
4128 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4132 var_type = texpr.Type;
4135 // We need an instance variable. Not sure this is the best
4136 // way of doing this.
4138 // FIXME: When we implement propertyaccess, will those turn
4139 // out to return values in ExprClass? I think they should.
4141 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4142 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4143 error1579 (expr.Type);
4147 if (expr.Type.IsArray) {
4148 array_type = expr.Type;
4149 element_type = TypeManager.GetElementType (array_type);
4151 empty = new EmptyExpression (element_type);
4153 hm = ProbeCollectionType (ec, expr.Type);
4155 error1579 (expr.Type);
4159 array_type = expr.Type;
4160 element_type = hm.element_type;
4162 empty = new EmptyExpression (hm.element_type);
4167 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4168 ec.CurrentBranching.CreateSibling ();
4172 // FIXME: maybe we can apply the same trick we do in the
4173 // array handling to avoid creating empty and conv in some cases.
4175 // Although it is not as important in this case, as the type
4176 // will not likely be object (what the enumerator will return).
4178 conv = Convert.WideningAndNarrowingConversion (ec, empty, var_type, loc);
4182 variable = variable.ResolveLValue (ec, empty);
4183 if (variable == null)
4186 bool disposable = (hm != null) && hm.is_disposable;
4187 FlowBranchingException branching = null;
4189 branching = ec.StartFlowBranching (this);
4191 if (!statement.Resolve (ec))
4195 ResolveFinally (branching);
4196 ec.EndFlowBranching ();
4198 emit_finally = true;
4200 ec.EndFlowBranching ();
4206 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4208 static MethodInfo FetchMethodMoveNext (Type t)
4210 MemberList move_next_list;
4212 move_next_list = TypeContainer.FindMembers (
4213 t, MemberTypes.Method,
4214 BindingFlags.Public | BindingFlags.Instance,
4215 Type.FilterName, "MoveNext");
4216 if (move_next_list.Count == 0)
4219 foreach (MemberInfo m in move_next_list){
4220 MethodInfo mi = (MethodInfo) m;
4223 args = TypeManager.GetArgumentTypes (mi);
4224 if (args != null && args.Length == 0){
4225 if (TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type)
4233 // Retrieves a `public T get_Current ()' method from the Type `t'
4235 static MethodInfo FetchMethodGetCurrent (Type t)
4237 MemberList get_current_list;
4239 get_current_list = TypeContainer.FindMembers (
4240 t, MemberTypes.Method,
4241 BindingFlags.Public | BindingFlags.Instance,
4242 Type.FilterName, "get_Current");
4243 if (get_current_list.Count == 0)
4246 foreach (MemberInfo m in get_current_list){
4247 MethodInfo mi = (MethodInfo) m;
4250 args = TypeManager.GetArgumentTypes (mi);
4251 if (args != null && args.Length == 0)
4258 // Retrieves a `public void Dispose ()' method from the Type `t'
4260 static MethodInfo FetchMethodDispose (Type t)
4262 MemberList dispose_list;
4264 dispose_list = TypeContainer.FindMembers (
4265 t, MemberTypes.Method,
4266 BindingFlags.Public | BindingFlags.Instance,
4267 Type.FilterName, "Dispose");
4268 if (dispose_list.Count == 0)
4271 foreach (MemberInfo m in dispose_list){
4272 MethodInfo mi = (MethodInfo) m;
4275 args = TypeManager.GetArgumentTypes (mi);
4276 if (args != null && args.Length == 0){
4277 if (mi.ReturnType == TypeManager.void_type)
4285 // This struct records the helper methods used by the Foreach construct
4287 class ForeachHelperMethods {
4288 public EmitContext ec;
4289 public MethodInfo get_enumerator;
4290 public MethodInfo move_next;
4291 public MethodInfo get_current;
4292 public Type element_type;
4293 public Type enumerator_type;
4294 public bool is_disposable;
4296 public ForeachHelperMethods (EmitContext ec)
4299 this.element_type = TypeManager.object_type;
4300 this.enumerator_type = TypeManager.ienumerator_type;
4301 this.is_disposable = true;
4305 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4310 if (!(m is MethodInfo))
4313 if (m.Name != "GetEnumerator")
4316 MethodInfo mi = (MethodInfo) m;
4317 Type [] args = TypeManager.GetArgumentTypes (mi);
4319 if (args.Length != 0)
4322 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4324 // Check whether GetEnumerator is public
4325 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4328 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4330 // Apply the same optimization as MS: skip the GetEnumerator
4331 // returning an IEnumerator, and use the one returning a
4332 // CharEnumerator instead. This allows us to avoid the
4333 // try-finally block and the boxing.
4338 // Ok, we can access it, now make sure that we can do something
4339 // with this `GetEnumerator'
4342 Type return_type = mi.ReturnType;
4343 if (mi.ReturnType == TypeManager.ienumerator_type ||
4344 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4345 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4348 // If it is not an interface, lets try to find the methods ourselves.
4349 // For example, if we have:
4350 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4351 // We can avoid the iface call. This is a runtime perf boost.
4352 // even bigger if we have a ValueType, because we avoid the cost
4355 // We have to make sure that both methods exist for us to take
4356 // this path. If one of the methods does not exist, we will just
4357 // use the interface. Sadly, this complex if statement is the only
4358 // way I could do this without a goto
4361 if (return_type.IsInterface ||
4362 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4363 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4365 hm.move_next = TypeManager.bool_movenext_void;
4366 hm.get_current = TypeManager.object_getcurrent_void;
4373 // Ok, so they dont return an IEnumerable, we will have to
4374 // find if they support the GetEnumerator pattern.
4377 hm.move_next = FetchMethodMoveNext (return_type);
4378 if (hm.move_next == null)
4381 hm.get_current = FetchMethodGetCurrent (return_type);
4382 if (hm.get_current == null)
4386 hm.element_type = hm.get_current.ReturnType;
4387 hm.enumerator_type = return_type;
4388 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4389 TypeManager.ImplementsInterface (
4390 hm.enumerator_type, TypeManager.idisposable_type);
4396 /// This filter is used to find the GetEnumerator method
4397 /// on which IEnumerator operates
4399 static MemberFilter FilterEnumerator;
4403 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4406 void error1579 (Type t)
4408 Report.Error (1579, loc,
4409 "foreach statement cannot operate on variables of type `" +
4410 t.FullName + "' because that class does not provide a " +
4411 " GetEnumerator method or it is inaccessible");
4414 static bool TryType (Type t, ForeachHelperMethods hm)
4418 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4419 BindingFlags.Public | BindingFlags.NonPublic |
4420 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4421 FilterEnumerator, hm);
4426 hm.get_enumerator = (MethodInfo) mi [0];
4431 // Looks for a usable GetEnumerator in the Type, and if found returns
4432 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4434 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4436 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4438 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4439 if (TryType (tt, hm))
4445 // Now try to find the method in the interfaces
4448 Type [] ifaces = t.GetInterfaces ();
4450 foreach (Type i in ifaces){
4451 if (TryType (i, hm))
4456 // Since TypeBuilder.GetInterfaces only returns the interface
4457 // types for this type, we have to keep looping, but once
4458 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4459 // done, because it returns all the types
4461 if ((t is TypeBuilder))
4471 // FIXME: possible optimization.
4472 // We might be able to avoid creating `empty' if the type is the sam
4474 bool EmitCollectionForeach (EmitContext ec)
4476 ILGenerator ig = ec.ig;
4478 enumerator = new VariableStorage (ec, hm.enumerator_type);
4479 enumerator.EmitThis (ig);
4481 // Instantiate the enumerator
4483 if (expr.Type.IsValueType){
4484 IMemoryLocation ml = expr as IMemoryLocation;
4485 // Load the address of the value type.
4487 // This happens if, for example, you have a property
4488 // returning a struct which is IEnumerable
4489 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4491 ig.Emit (OpCodes.Stloc, t);
4492 ig.Emit (OpCodes.Ldloca, t);
4493 ec.FreeTemporaryLocal (t, expr.Type);
4495 ml.AddressOf (ec, AddressOp.Load);
4499 if (hm.get_enumerator.DeclaringType.IsValueType) {
4500 // the method is declared on the value type
4501 ig.Emit (OpCodes.Call, hm.get_enumerator);
4503 // it is an interface method, so we must box
4504 ig.Emit (OpCodes.Box, expr.Type);
4505 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4509 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4511 enumerator.EmitStore (ig);
4514 // Protect the code in a try/finalize block, so that
4515 // if the beast implement IDisposable, we get rid of it
4517 if (hm.is_disposable && emit_finally)
4518 ig.BeginExceptionBlock ();
4520 Label end_try = ig.DefineLabel ();
4522 ig.MarkLabel (ec.LoopBegin);
4524 enumerator.EmitCall (ig, hm.move_next);
4526 ig.Emit (OpCodes.Brfalse, end_try);
4529 ig.Emit (OpCodes.Ldarg_0);
4531 enumerator.EmitCall (ig, hm.get_current);
4535 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4537 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4539 statement.Emit (ec);
4540 ig.Emit (OpCodes.Br, ec.LoopBegin);
4541 ig.MarkLabel (end_try);
4543 // The runtime provides this for us.
4544 // ig.Emit (OpCodes.Leave, end);
4547 // Now the finally block
4549 if (hm.is_disposable) {
4552 ig.EndExceptionBlock ();
4555 ig.MarkLabel (ec.LoopEnd);
4559 public override void EmitFinally (EmitContext ec)
4561 ILGenerator ig = ec.ig;
4563 if (hm.enumerator_type.IsValueType) {
4564 enumerator.EmitThis (ig);
4566 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4568 enumerator.EmitLoadAddress (ig);
4569 ig.Emit (OpCodes.Call, mi);
4571 enumerator.EmitLoad (ig);
4572 ig.Emit (OpCodes.Box, hm.enumerator_type);
4573 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4576 Label call_dispose = ig.DefineLabel ();
4578 enumerator.EmitThis (ig);
4579 enumerator.EmitLoad (ig);
4580 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4581 ig.Emit (OpCodes.Dup);
4582 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4583 ig.Emit (OpCodes.Pop);
4585 Label end_finally = ig.DefineLabel ();
4586 ig.Emit (OpCodes.Br, end_finally);
4588 ig.MarkLabel (call_dispose);
4589 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4590 ig.MarkLabel (end_finally);
4593 ig.Emit (OpCodes.Endfinally);
4598 // FIXME: possible optimization.
4599 // We might be able to avoid creating `empty' if the type is the sam
4601 bool EmitArrayForeach (EmitContext ec)
4603 int rank = array_type.GetArrayRank ();
4604 ILGenerator ig = ec.ig;
4606 VariableStorage copy = new VariableStorage (ec, array_type);
4609 // Make our copy of the array
4613 copy.EmitStore (ig);
4616 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4620 counter.EmitThis (ig);
4621 ig.Emit (OpCodes.Ldc_I4_0);
4622 counter.EmitStore (ig);
4623 test = ig.DefineLabel ();
4624 ig.Emit (OpCodes.Br, test);
4626 loop = ig.DefineLabel ();
4627 ig.MarkLabel (loop);
4630 ig.Emit (OpCodes.Ldarg_0);
4634 counter.EmitThis (ig);
4635 counter.EmitLoad (ig);
4638 // Load the value, we load the value using the underlying type,
4639 // then we use the variable.EmitAssign to load using the proper cast.
4641 ArrayAccess.EmitLoadOpcode (ig, element_type);
4644 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4646 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4648 statement.Emit (ec);
4650 ig.MarkLabel (ec.LoopBegin);
4651 counter.EmitThis (ig);
4652 counter.EmitThis (ig);
4653 counter.EmitLoad (ig);
4654 ig.Emit (OpCodes.Ldc_I4_1);
4655 ig.Emit (OpCodes.Add);
4656 counter.EmitStore (ig);
4658 ig.MarkLabel (test);
4659 counter.EmitThis (ig);
4660 counter.EmitLoad (ig);
4663 ig.Emit (OpCodes.Ldlen);
4664 ig.Emit (OpCodes.Conv_I4);
4665 ig.Emit (OpCodes.Blt, loop);
4667 VariableStorage [] dim_len = new VariableStorage [rank];
4668 VariableStorage [] dim_count = new VariableStorage [rank];
4669 Label [] loop = new Label [rank];
4670 Label [] test = new Label [rank];
4673 for (dim = 0; dim < rank; dim++){
4674 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4675 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4676 test [dim] = ig.DefineLabel ();
4677 loop [dim] = ig.DefineLabel ();
4680 for (dim = 0; dim < rank; dim++){
4681 dim_len [dim].EmitThis (ig);
4684 IntLiteral.EmitInt (ig, dim);
4685 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4686 dim_len [dim].EmitStore (ig);
4690 for (dim = 0; dim < rank; dim++){
4691 dim_count [dim].EmitThis (ig);
4692 ig.Emit (OpCodes.Ldc_I4_0);
4693 dim_count [dim].EmitStore (ig);
4694 ig.Emit (OpCodes.Br, test [dim]);
4695 ig.MarkLabel (loop [dim]);
4699 ig.Emit (OpCodes.Ldarg_0);
4703 for (dim = 0; dim < rank; dim++){
4704 dim_count [dim].EmitThis (ig);
4705 dim_count [dim].EmitLoad (ig);
4709 // FIXME: Maybe we can cache the computation of `get'?
4711 Type [] args = new Type [rank];
4714 for (int i = 0; i < rank; i++)
4715 args [i] = TypeManager.int32_type;
4717 ModuleBuilder mb = CodeGen.Module.Builder;
4718 get = mb.GetArrayMethod (
4720 CallingConventions.HasThis| CallingConventions.Standard,
4722 ig.Emit (OpCodes.Call, get);
4725 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4727 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4728 statement.Emit (ec);
4729 ig.MarkLabel (ec.LoopBegin);
4730 for (dim = rank - 1; dim >= 0; dim--){
4731 dim_count [dim].EmitThis (ig);
4732 dim_count [dim].EmitThis (ig);
4733 dim_count [dim].EmitLoad (ig);
4734 ig.Emit (OpCodes.Ldc_I4_1);
4735 ig.Emit (OpCodes.Add);
4736 dim_count [dim].EmitStore (ig);
4738 ig.MarkLabel (test [dim]);
4739 dim_count [dim].EmitThis (ig);
4740 dim_count [dim].EmitLoad (ig);
4741 dim_len [dim].EmitThis (ig);
4742 dim_len [dim].EmitLoad (ig);
4743 ig.Emit (OpCodes.Blt, loop [dim]);
4746 ig.MarkLabel (ec.LoopEnd);
4751 protected override void DoEmit (EmitContext ec)
4753 ILGenerator ig = ec.ig;
4755 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4756 ec.LoopBegin = ig.DefineLabel ();
4757 ec.LoopEnd = ig.DefineLabel ();
4760 EmitCollectionForeach (ec);
4762 EmitArrayForeach (ec);
4764 ec.LoopBegin = old_begin;
4765 ec.LoopEnd = old_end;