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);
725 protected override void DoEmit (EmitContext ec)
727 if (ig != null && ig != ec.ig) {
728 Report.Error (1632, "Control cannot leave body of anonymous method");
732 ec.ig.MarkLabel (label);
735 public void AddReference ()
743 /// `goto default' statement
745 public class GotoDefault : Statement {
747 public GotoDefault (Location l)
752 public override bool Resolve (EmitContext ec)
754 ec.CurrentBranching.CurrentUsageVector.Goto ();
758 protected override void DoEmit (EmitContext ec)
760 if (ec.Switch == null){
761 Report.Error (153, loc, "goto default is only valid in a switch statement");
765 if (!ec.Switch.GotDefault){
766 Report.Error (159, loc, "No default target on switch statement");
769 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
774 /// `goto case' statement
776 public class GotoCase : Statement {
780 public GotoCase (Expression e, Location l)
786 public override bool Resolve (EmitContext ec)
788 if (ec.Switch == null){
789 Report.Error (153, loc, "goto case is only valid in a switch statement");
793 expr = expr.Resolve (ec);
797 if (!(expr is Constant)){
798 Report.Error (159, loc, "Target expression for goto case is not constant");
802 object val = Expression.ConvertIntLiteral (
803 (Constant) expr, ec.Switch.SwitchType, loc);
808 sl = (SwitchLabel) ec.Switch.Elements [val];
813 "No such label 'case " + val + "': for the goto case");
817 ec.CurrentBranching.CurrentUsageVector.Goto ();
821 protected override void DoEmit (EmitContext ec)
823 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
827 public class Throw : Statement {
830 public Throw (Expression expr, Location l)
836 public override bool Resolve (EmitContext ec)
838 ec.CurrentBranching.CurrentUsageVector.Throw ();
841 expr = expr.Resolve (ec);
845 ExprClass eclass = expr.eclass;
847 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
848 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
849 expr.Error_UnexpectedKind ("value, variable, property or indexer access ", loc);
855 if ((t != TypeManager.exception_type) &&
856 !t.IsSubclassOf (TypeManager.exception_type) &&
857 !(expr is NullLiteral)) {
859 "The type caught or thrown must be derived " +
860 "from System.Exception");
866 if (ec.CurrentBranching.InFinally (true)) {
867 Error (724, "A throw statement with no argument is only allowed in a catch clause nested inside of the innermost catch clause");
871 if (!ec.CurrentBranching.InCatch ()) {
872 Error (156, "A throw statement with no argument is only allowed in a catch clause");
878 protected override void DoEmit (EmitContext ec)
881 ec.ig.Emit (OpCodes.Rethrow);
885 ec.ig.Emit (OpCodes.Throw);
890 public class Break : Statement {
892 public Break (Location l)
899 public override bool Resolve (EmitContext ec)
901 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
902 Error (139, "No enclosing loop or switch to continue to");
904 } else if (ec.CurrentBranching.InFinally (false)) {
905 Error (157, "Control can not leave the body of the finally block");
907 } else if (ec.CurrentBranching.InTryOrCatch (false))
908 ec.CurrentBranching.AddFinallyVector (
909 ec.CurrentBranching.CurrentUsageVector);
910 else if (ec.CurrentBranching.InLoop ())
911 ec.CurrentBranching.AddBreakVector (
912 ec.CurrentBranching.CurrentUsageVector);
914 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
917 ec.NeedReturnLabel ();
919 ec.CurrentBranching.CurrentUsageVector.Break ();
923 protected override void DoEmit (EmitContext ec)
925 ILGenerator ig = ec.ig;
928 ig.Emit (OpCodes.Leave, ec.LoopEnd);
930 ig.Emit (OpCodes.Br, ec.LoopEnd);
935 public class Continue : Statement {
937 public Continue (Location l)
944 public override bool Resolve (EmitContext ec)
946 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
947 Error (139, "No enclosing loop to continue to");
949 } else if (ec.CurrentBranching.InFinally (false)) {
950 Error (157, "Control can not leave the body of the finally block");
952 } else if (ec.CurrentBranching.InTryOrCatch (false))
953 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
955 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
957 ec.CurrentBranching.CurrentUsageVector.Goto ();
961 protected override void DoEmit (EmitContext ec)
963 Label begin = ec.LoopBegin;
966 ec.ig.Emit (OpCodes.Leave, begin);
968 ec.ig.Emit (OpCodes.Br, begin);
973 // The information about a user-perceived local variable
975 public class LocalInfo {
976 public Expression Type;
979 // Most of the time a variable will be stored in a LocalBuilder
981 // But sometimes, it will be stored in a field (variables that have been
982 // hoisted by iterators or by anonymous methods). The context of the field will
983 // be stored in the EmitContext
986 public LocalBuilder LocalBuilder;
987 public FieldBuilder FieldBuilder;
989 public Type VariableType;
990 public readonly string Name;
991 public readonly Location Location;
992 public readonly Block Block;
994 public VariableInfo VariableInfo;
1007 public LocalInfo (Expression type, string name, Block block, Location l)
1015 public LocalInfo (TypeContainer tc, Block block, Location l)
1017 VariableType = tc.TypeBuilder;
1022 public bool IsThisAssigned (EmitContext ec, Location loc)
1024 if (VariableInfo == null)
1025 throw new Exception ();
1027 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1030 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1033 public bool IsAssigned (EmitContext ec)
1035 if (VariableInfo == null)
1036 throw new Exception ();
1038 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1041 public bool Resolve (EmitContext ec)
1043 if (VariableType == null) {
1044 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
1048 VariableType = texpr.Type;
1051 if (VariableType == TypeManager.void_type) {
1052 Report.Error (1547, Location,
1053 "Keyword 'void' cannot be used in this context");
1057 if (VariableType.IsAbstract && VariableType.IsSealed) {
1058 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1061 // TODO: breaks the build
1062 // if (VariableType.IsPointer && !ec.InUnsafe)
1063 // Expression.UnsafeError (Location);
1069 // Whether the variable is Fixed (because its Pinned or its a value type)
1071 public bool IsFixed {
1073 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1080 public bool IsCaptured {
1082 return (flags & Flags.Captured) != 0;
1086 flags |= Flags.Captured;
1090 public bool AddressTaken {
1092 return (flags & Flags.AddressTaken) != 0;
1096 flags |= Flags.AddressTaken;
1100 public override string ToString ()
1102 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1103 Name, Type, VariableInfo, Location);
1108 return (flags & Flags.Used) != 0;
1111 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1115 public bool ReadOnly {
1117 return (flags & Flags.ReadOnly) != 0;
1120 flags = value ? (flags | Flags.ReadOnly) : (unchecked (flags & ~Flags.ReadOnly));
1125 // Whether the variable is pinned, if Pinned the variable has been
1126 // allocated in a pinned slot with DeclareLocal.
1128 public bool Pinned {
1130 return (flags & Flags.Pinned) != 0;
1133 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1137 public bool IsThis {
1139 return (flags & Flags.IsThis) != 0;
1142 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1148 /// Block represents a C# block.
1152 /// This class is used in a number of places: either to represent
1153 /// explicit blocks that the programmer places or implicit blocks.
1155 /// Implicit blocks are used as labels or to introduce variable
1158 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1159 /// they contain extra information that is not necessary on normal blocks.
1161 public class Block : Statement {
1162 public Block Parent;
1163 public readonly Location StartLocation;
1164 public Location EndLocation = Location.Null;
1171 VariablesInitialized = 8,
1180 public bool Implicit {
1182 return (flags & Flags.Implicit) != 0;
1186 public bool Unchecked {
1188 return (flags & Flags.Unchecked) != 0;
1191 flags |= Flags.Unchecked;
1195 public bool Unsafe {
1197 return (flags & Flags.Unsafe) != 0;
1200 flags |= Flags.Unsafe;
1204 public bool HasVarargs {
1207 return Parent.HasVarargs;
1209 return (flags & Flags.HasVarargs) != 0;
1212 flags |= Flags.HasVarargs;
1217 // The statements in this block
1219 public ArrayList statements;
1223 // An array of Blocks. We keep track of children just
1224 // to generate the local variable declarations.
1226 // Statements and child statements are handled through the
1232 // Labels. (label, block) pairs.
1237 // Keeps track of (name, type) pairs
1239 Hashtable variables;
1242 // Keeps track of constants
1243 Hashtable constants;
1246 // The parameters for the block, this is only needed on the toplevel block really
1247 // TODO: move `parameters' into ToplevelBlock
1248 Parameters parameters;
1251 // If this is a switch section, the enclosing switch block.
1255 protected static int id;
1259 public Block (Block parent)
1260 : this (parent, (Flags) 0, Location.Null, Location.Null)
1263 public Block (Block parent, Flags flags)
1264 : this (parent, flags, Location.Null, Location.Null)
1267 public Block (Block parent, Flags flags, Parameters parameters)
1268 : this (parent, flags, parameters, Location.Null, Location.Null)
1271 public Block (Block parent, Location start, Location end)
1272 : this (parent, (Flags) 0, start, end)
1275 public Block (Block parent, Parameters parameters, Location start, Location end)
1276 : this (parent, (Flags) 0, parameters, start, end)
1279 public Block (Block parent, Flags flags, Location start, Location end)
1280 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1283 public Block (Block parent, Flags flags, Parameters parameters,
1284 Location start, Location end)
1287 parent.AddChild (this);
1289 this.Parent = parent;
1291 this.parameters = parameters;
1292 this.StartLocation = start;
1293 this.EndLocation = end;
1296 statements = new ArrayList ();
1298 if (parent != null && Implicit) {
1299 if (parent.child_variable_names == null)
1300 parent.child_variable_names = new Hashtable();
1301 // share with parent
1302 child_variable_names = parent.child_variable_names;
1307 public Block CreateSwitchBlock (Location start)
1309 Block new_block = new Block (this, start, start);
1310 new_block.switch_block = this;
1320 void AddChild (Block b)
1322 if (children == null)
1323 children = new ArrayList ();
1328 public void SetEndLocation (Location loc)
1334 /// Adds a label to the current block.
1338 /// false if the name already exists in this block. true
1342 public bool AddLabel (string name, LabeledStatement target, Location loc)
1344 if (switch_block != null)
1345 return switch_block.AddLabel (name, target, loc);
1348 while (cur != null) {
1349 if (cur.DoLookupLabel (name) != null) {
1351 140, loc, "The label '{0}' is a duplicate",
1362 while (cur != null) {
1363 if (cur.DoLookupLabel (name) != null) {
1366 "The label '{0}' shadows another label " +
1367 "by the same name in a containing scope.",
1372 if (children != null) {
1373 foreach (Block b in children) {
1374 LabeledStatement s = b.DoLookupLabel (name);
1380 "The label '{0}' shadows another " +
1381 "label by the same name in a " +
1382 "containing scope.",
1393 labels = new Hashtable ();
1395 labels.Add (name, target);
1399 public LabeledStatement LookupLabel (string name)
1401 LabeledStatement s = DoLookupLabel (name);
1405 if (children == null)
1408 foreach (Block child in children) {
1409 if (!child.Implicit)
1412 s = child.LookupLabel (name);
1420 LabeledStatement DoLookupLabel (string name)
1422 if (switch_block != null)
1423 return switch_block.LookupLabel (name);
1426 if (labels.Contains (name))
1427 return ((LabeledStatement) labels [name]);
1432 LocalInfo this_variable = null;
1435 // Returns the "this" instance variable of this block.
1436 // See AddThisVariable() for more information.
1438 public LocalInfo ThisVariable {
1440 for (Block b = this; b != null; b = b.Parent) {
1441 if (b.this_variable != null)
1442 return b.this_variable;
1449 Hashtable child_variable_names;
1452 // Marks a variable with name @name as being used in a child block.
1453 // If a variable name has been used in a child block, it's illegal to
1454 // declare a variable with the same name in the current block.
1456 public void AddChildVariableName (string name)
1458 if (child_variable_names == null)
1459 child_variable_names = new Hashtable ();
1461 child_variable_names [name] = null;
1465 // Checks whether a variable name has already been used in a child block.
1467 public bool IsVariableNameUsedInChildBlock (string name)
1469 if (child_variable_names == null)
1472 return child_variable_names.Contains (name);
1476 // This is used by non-static `struct' constructors which do not have an
1477 // initializer - in this case, the constructor must initialize all of the
1478 // struct's fields. To do this, we add a "this" variable and use the flow
1479 // analysis code to ensure that it's been fully initialized before control
1480 // leaves the constructor.
1482 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1484 if (this_variable != null)
1485 return this_variable;
1487 if (variables == null)
1488 variables = new Hashtable ();
1490 this_variable = new LocalInfo (tc, this, l);
1491 this_variable.Used = true;
1492 this_variable.IsThis = true;
1494 variables.Add ("this", this_variable);
1496 return this_variable;
1499 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1501 if (variables == null)
1502 variables = new Hashtable ();
1504 LocalInfo vi = GetLocalInfo (name);
1506 if (vi.Block != this)
1507 Report.Error (136, l, "A local variable named `" + name + "' " +
1508 "cannot be declared in this scope since it would " +
1509 "give a different meaning to `" + name + "', which " +
1510 "is already used in a `parent or current' scope to " +
1511 "denote something else");
1513 Report.Error (128, l, "A local variable `" + name + "' is already " +
1514 "defined in this scope");
1518 if (IsVariableNameUsedInChildBlock (name)) {
1519 Report.Error (136, l, "A local variable named `" + name + "' " +
1520 "cannot be declared in this scope since it would " +
1521 "give a different meaning to `" + name + "', which " +
1522 "is already used in a `child' scope to denote something " +
1529 Parameter p = pars.GetParameterByName (name, out idx);
1531 Report.Error (136, l, "A local variable named `" + name + "' " +
1532 "cannot be declared in this scope since it would " +
1533 "give a different meaning to `" + name + "', which " +
1534 "is already used in a `parent or current' scope to " +
1535 "denote something else");
1540 vi = new LocalInfo (type, name, this, l);
1542 variables.Add (name, vi);
1544 // Mark 'name' as "used by a child block" in every surrounding block
1546 while (cur != null && cur.Implicit)
1549 for (Block par = cur.Parent; par != null; par = par.Parent)
1550 par.AddChildVariableName (name);
1552 if ((flags & Flags.VariablesInitialized) != 0)
1553 throw new Exception ();
1555 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1559 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1561 if (AddVariable (type, name, pars, l) == null)
1564 if (constants == null)
1565 constants = new Hashtable ();
1567 constants.Add (name, value);
1571 public Hashtable Variables {
1577 public LocalInfo GetLocalInfo (string name)
1579 for (Block b = this; b != null; b = b.Parent) {
1580 if (b.variables != null) {
1581 LocalInfo ret = b.variables [name] as LocalInfo;
1589 public Expression GetVariableType (string name)
1591 LocalInfo vi = GetLocalInfo (name);
1599 public Expression GetConstantExpression (string name)
1601 for (Block b = this; b != null; b = b.Parent) {
1602 if (b.constants != null) {
1603 Expression ret = b.constants [name] as Expression;
1612 /// True if the variable named @name is a constant
1614 public bool IsConstant (string name)
1616 Expression e = null;
1618 e = GetConstantExpression (name);
1624 // Returns a `ParameterReference' for the given name, or null if there
1625 // is no such parameter
1627 public ParameterReference GetParameterReference (string name, Location loc)
1632 Parameters pars = b.parameters;
1638 par = pars.GetParameterByName (name, out idx);
1640 ParameterReference pr;
1642 pr = new ParameterReference (pars, this, idx, name, loc);
1647 } while (b != null);
1652 // Whether the parameter named `name' is local to this block,
1653 // or false, if the parameter belongs to an encompassing block.
1655 public bool IsLocalParameter (string name)
1658 int toplevel_count = 0;
1661 if (this is ToplevelBlock)
1664 Parameters pars = b.parameters;
1666 if (pars.GetParameterByName (name) != null)
1670 if (toplevel_count > 0)
1673 } while (b != null);
1678 // Whether the `name' is a parameter reference
1680 public bool IsParameterReference (string name)
1685 Parameters pars = b.parameters;
1688 if (pars.GetParameterByName (name) != null)
1691 } while (b != null);
1696 /// A list of labels that were not used within this block
1698 public string [] GetUnreferenced ()
1700 // FIXME: Implement me
1704 public void AddStatement (Statement s)
1707 flags |= Flags.BlockUsed;
1712 return (flags & Flags.BlockUsed) != 0;
1718 flags |= Flags.BlockUsed;
1721 public bool HasRet {
1723 return (flags & Flags.HasRet) != 0;
1727 public bool IsDestructor {
1729 return (flags & Flags.IsDestructor) != 0;
1733 public void SetDestructor ()
1735 flags |= Flags.IsDestructor;
1738 VariableMap param_map, local_map;
1740 public VariableMap ParameterMap {
1742 if ((flags & Flags.VariablesInitialized) == 0)
1743 throw new Exception ("Variables have not been initialized yet");
1749 public VariableMap LocalMap {
1751 if ((flags & Flags.VariablesInitialized) == 0)
1752 throw new Exception ("Variables have not been initialized yet");
1759 /// Emits the variable declarations and labels.
1762 /// tc: is our typecontainer (to resolve type references)
1763 /// ig: is the code generator:
1765 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1767 bool old_unsafe = ec.InUnsafe;
1769 // If some parent block was unsafe, we remain unsafe even if this block
1770 // isn't explicitly marked as such.
1771 ec.InUnsafe |= Unsafe;
1774 // Compute the VariableMap's.
1776 // Unfortunately, we don't know the type when adding variables with
1777 // AddVariable(), so we need to compute this info here.
1781 if (variables != null) {
1782 foreach (LocalInfo li in variables.Values)
1785 locals = new LocalInfo [variables.Count];
1786 variables.Values.CopyTo (locals, 0);
1788 locals = new LocalInfo [0];
1791 local_map = new VariableMap (Parent.LocalMap, locals);
1793 local_map = new VariableMap (locals);
1795 param_map = new VariableMap (ip);
1796 flags |= Flags.VariablesInitialized;
1798 bool old_check_state = ec.ConstantCheckState;
1799 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1802 // Process this block variables
1804 if (variables != null){
1805 foreach (DictionaryEntry de in variables){
1806 string name = (string) de.Key;
1807 LocalInfo vi = (LocalInfo) de.Value;
1809 if (vi.VariableType == null)
1812 Type variable_type = vi.VariableType;
1814 if (variable_type.IsPointer){
1816 // Am not really convinced that this test is required (Microsoft does it)
1817 // but the fact is that you would not be able to use the pointer variable
1820 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1827 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1830 // This is needed to compile on both .NET 1.x and .NET 2.x
1831 // the later introduced `DeclareLocal (Type t, bool pinned)'
1833 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1834 else if (!vi.IsThis)
1835 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1838 if (constants == null)
1841 Expression cv = (Expression) constants [name];
1845 ec.CurrentBlock = this;
1846 Expression e = cv.Resolve (ec);
1850 Constant ce = e as Constant;
1852 Report.Error (133, vi.Location,
1853 "The expression being assigned to `" +
1854 name + "' must be constant (" + e + ")");
1858 if (e.Type != variable_type){
1859 e = Const.ChangeType (vi.Location, ce, variable_type);
1864 constants.Remove (name);
1865 constants.Add (name, e);
1868 ec.ConstantCheckState = old_check_state;
1871 // Now, handle the children
1873 if (children != null){
1874 foreach (Block b in children)
1875 b.ResolveMeta (toplevel, ec, ip);
1877 ec.InUnsafe = old_unsafe;
1881 // Emits the local variable declarations for a block
1883 public void EmitMeta (EmitContext ec)
1885 ILGenerator ig = ec.ig;
1887 if (variables != null){
1888 bool have_captured_vars = ec.HaveCapturedVariables ();
1889 bool remap_locals = ec.RemapToProxy;
1891 foreach (DictionaryEntry de in variables){
1892 LocalInfo vi = (LocalInfo) de.Value;
1894 if (have_captured_vars && ec.IsCaptured (vi))
1898 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1902 // This is needed to compile on both .NET 1.x and .NET 2.x
1903 // the later introduced `DeclareLocal (Type t, bool pinned)'
1905 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1906 else if (!vi.IsThis)
1907 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1912 if (children != null){
1913 foreach (Block b in children)
1918 void UsageWarning (FlowBranching.UsageVector vector)
1922 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1923 foreach (DictionaryEntry de in variables){
1924 LocalInfo vi = (LocalInfo) de.Value;
1929 name = (string) de.Key;
1931 if (vector.IsAssigned (vi.VariableInfo)){
1932 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1934 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1940 bool unreachable_shown;
1942 public override bool Resolve (EmitContext ec)
1944 Block prev_block = ec.CurrentBlock;
1947 int errors = Report.Errors;
1949 ec.CurrentBlock = this;
1950 ec.StartFlowBranching (this);
1952 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1954 bool unreachable = unreachable_shown;
1956 int statement_count = statements.Count;
1957 for (int ix = 0; ix < statement_count; ix++){
1958 Statement s = (Statement) statements [ix];
1960 if (unreachable && !(s is LabeledStatement)) {
1961 if (s == EmptyStatement.Value)
1962 s.loc = EndLocation;
1964 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1967 if (s != EmptyStatement.Value)
1968 unreachable_shown = true;
1970 s.loc = Location.Null;
1972 if (ok && !(s is Block)) {
1973 statements [ix] = EmptyStatement.Value;
1978 if (s.Resolve (ec) == false) {
1980 statements [ix] = EmptyStatement.Value;
1984 num_statements = ix + 1;
1986 if (s is LabeledStatement)
1987 unreachable = false;
1989 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1992 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1993 ec.CurrentBranching, statement_count, num_statements);
1996 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1998 ec.CurrentBlock = prev_block;
2000 // If we're a non-static `struct' constructor which doesn't have an
2001 // initializer, then we must initialize all of the struct's fields.
2002 if ((this_variable != null) &&
2003 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
2004 !this_variable.IsThisAssigned (ec, loc))
2007 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2008 foreach (LabeledStatement label in labels.Values)
2009 if (!label.HasBeenReferenced)
2010 Report.Warning (164, label.Location,
2011 "This label has not been referenced");
2014 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2016 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2017 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2018 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2019 flags |= Flags.HasRet;
2021 if (ok && (errors == Report.Errors)) {
2022 if (RootContext.WarningLevel >= 3)
2023 UsageWarning (vector);
2029 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2031 unreachable_shown = true;
2033 if (warn && (RootContext.WarningLevel >= 2))
2034 Report.Warning (162, loc, "Unreachable code detected");
2037 return Resolve (ec);
2039 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2040 bool ok = Resolve (ec);
2041 ec.KillFlowBranching ();
2046 protected override void DoEmit (EmitContext ec)
2048 for (int ix = 0; ix < num_statements; ix++){
2049 Statement s = (Statement) statements [ix];
2051 // Check whether we are the last statement in a
2054 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2055 ec.IsLastStatement = true;
2057 ec.IsLastStatement = false;
2063 public override void Emit (EmitContext ec)
2065 Block prev_block = ec.CurrentBlock;
2067 ec.CurrentBlock = this;
2069 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2070 bool is_lexical_block = !Implicit && (Parent != null);
2072 if (emit_debug_info) {
2073 if (is_lexical_block)
2074 ec.ig.BeginScope ();
2076 if (variables != null) {
2077 foreach (DictionaryEntry de in variables) {
2078 string name = (string) de.Key;
2079 LocalInfo vi = (LocalInfo) de.Value;
2081 if (vi.LocalBuilder == null)
2084 ec.DefineLocalVariable (name, vi.LocalBuilder);
2089 ec.Mark (StartLocation, true);
2091 ec.Mark (EndLocation, true);
2093 if (emit_debug_info && is_lexical_block)
2096 ec.CurrentBlock = prev_block;
2099 public ToplevelBlock Toplevel {
2102 while (b.Parent != null){
2103 if ((b.flags & Flags.IsToplevel) != 0)
2108 return (ToplevelBlock) b;
2113 // Returns true if we ar ea child of `b'.
2115 public bool IsChildOf (Block b)
2117 Block current = this;
2120 if (current.Parent == b)
2122 current = current.Parent;
2123 } while (current != null);
2129 // A toplevel block contains extra information, the split is done
2130 // only to separate information that would otherwise bloat the more
2131 // lightweight Block.
2133 // In particular, this was introduced when the support for Anonymous
2134 // Methods was implemented.
2136 public class ToplevelBlock : Block {
2138 // Pointer to the host of this anonymous method, or null
2139 // if we are the topmost block
2141 public ToplevelBlock Container;
2142 CaptureContext capture_context;
2144 Hashtable capture_contexts;
2149 public void RegisterCaptureContext (CaptureContext cc)
2151 if (capture_contexts == null)
2152 capture_contexts = new Hashtable ();
2153 capture_contexts [cc] = cc;
2156 public void CompleteContexts ()
2158 if (capture_contexts == null)
2161 foreach (CaptureContext cc in capture_contexts.Keys){
2166 public CaptureContext ToplevelBlockCaptureContext {
2168 return capture_context;
2173 // Parent is only used by anonymous blocks to link back to their
2176 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2177 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2179 Container = container;
2182 public ToplevelBlock (Parameters parameters, Location start) :
2183 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2187 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2188 base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2192 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2196 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2198 if (capture_context == null)
2199 capture_context = new CaptureContext (this, loc, host);
2202 public CaptureContext CaptureContext {
2204 return capture_context;
2209 public class SwitchLabel {
2212 public Location loc;
2216 Label il_label_code;
2217 bool il_label_code_set;
2220 // if expr == null, then it is the default case.
2222 public SwitchLabel (Expression expr, Location l)
2228 public Expression Label {
2234 public object Converted {
2240 public Label GetILLabel (EmitContext ec)
2243 il_label = ec.ig.DefineLabel ();
2244 il_label_set = true;
2249 public Label GetILLabelCode (EmitContext ec)
2251 if (!il_label_code_set){
2252 il_label_code = ec.ig.DefineLabel ();
2253 il_label_code_set = true;
2255 return il_label_code;
2259 // Resolves the expression, reduces it to a literal if possible
2260 // and then converts it to the requested type.
2262 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2267 Expression e = label.Resolve (ec);
2272 if (!(e is Constant)){
2273 Report.Error (150, loc, "A constant value is expected, got: " + e);
2277 if (e is StringConstant || e is NullLiteral){
2278 if (required_type == TypeManager.string_type){
2284 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2285 if (converted == null)
2292 public class SwitchSection {
2293 // An array of SwitchLabels.
2294 public readonly ArrayList Labels;
2295 public readonly Block Block;
2297 public SwitchSection (ArrayList labels, Block block)
2304 public class Switch : Statement {
2305 public readonly ArrayList Sections;
2306 public Expression Expr;
2309 /// Maps constants whose type type SwitchType to their SwitchLabels.
2311 public Hashtable Elements;
2314 /// The governing switch type
2316 public Type SwitchType;
2322 Label default_target;
2323 Expression new_expr;
2325 SwitchSection constant_section;
2328 // The types allowed to be implicitly cast from
2329 // on the governing type
2331 static Type [] allowed_types;
2333 public Switch (Expression e, ArrayList sects, Location l)
2340 public bool GotDefault {
2346 public Label DefaultTarget {
2348 return default_target;
2353 // Determines the governing type for a switch. The returned
2354 // expression might be the expression from the switch, or an
2355 // expression that includes any potential conversions to the
2356 // integral types or to string.
2358 Expression SwitchGoverningType (EmitContext ec, Type t)
2360 if (t == TypeManager.int32_type ||
2361 t == TypeManager.uint32_type ||
2362 t == TypeManager.char_type ||
2363 t == TypeManager.byte_type ||
2364 t == TypeManager.sbyte_type ||
2365 t == TypeManager.ushort_type ||
2366 t == TypeManager.short_type ||
2367 t == TypeManager.uint64_type ||
2368 t == TypeManager.int64_type ||
2369 t == TypeManager.string_type ||
2370 t == TypeManager.bool_type ||
2371 t.IsSubclassOf (TypeManager.enum_type))
2374 if (allowed_types == null){
2375 allowed_types = new Type [] {
2376 TypeManager.int32_type,
2377 TypeManager.uint32_type,
2378 TypeManager.sbyte_type,
2379 TypeManager.byte_type,
2380 TypeManager.short_type,
2381 TypeManager.ushort_type,
2382 TypeManager.int64_type,
2383 TypeManager.uint64_type,
2384 TypeManager.char_type,
2385 TypeManager.bool_type,
2386 TypeManager.string_type
2391 // Try to find a *user* defined implicit conversion.
2393 // If there is no implicit conversion, or if there are multiple
2394 // conversions, we have to report an error
2396 Expression converted = null;
2399 // VB.NET has no notion of User defined conversions
2402 // foreach (Type tt in allowed_types){
2405 // e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2410 // // Ignore over-worked ImplicitUserConversions that do
2411 // // an implicit conversion in addition to the user conversion.
2413 // if (e is UserCast){
2414 // UserCast ue = e as UserCast;
2416 // if (ue.Source != Expr)
2420 // if (converted != null){
2421 // Report.ExtraInformation (
2423 // String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2424 // TypeManager.CSharpName (Expr.Type)));
2433 static string Error152 {
2435 return "The label '{0}:' already occurs in this switch statement";
2440 // Performs the basic sanity checks on the switch statement
2441 // (looks for duplicate keys and non-constant expressions).
2443 // It also returns a hashtable with the keys that we will later
2444 // use to compute the switch tables
2446 bool CheckSwitch (EmitContext ec)
2450 Elements = new Hashtable ();
2452 got_default = false;
2454 if (TypeManager.IsEnumType (SwitchType)){
2455 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2457 compare_type = SwitchType;
2459 foreach (SwitchSection ss in Sections){
2460 foreach (SwitchLabel sl in ss.Labels){
2461 if (!sl.ResolveAndReduce (ec, SwitchType)){
2466 if (sl.Label == null){
2468 Report.Error (152, sl.loc, Error152, "default");
2475 object key = sl.Converted;
2477 if (key is Constant)
2478 key = ((Constant) key).GetValue ();
2481 key = NullLiteral.Null;
2483 string lname = null;
2484 if (compare_type == TypeManager.uint64_type){
2485 ulong v = (ulong) key;
2487 if (Elements.Contains (v))
2488 lname = v.ToString ();
2490 Elements.Add (v, sl);
2491 } else if (compare_type == TypeManager.int64_type){
2492 long v = (long) key;
2494 if (Elements.Contains (v))
2495 lname = v.ToString ();
2497 Elements.Add (v, sl);
2498 } else if (compare_type == TypeManager.uint32_type){
2499 uint v = (uint) key;
2501 if (Elements.Contains (v))
2502 lname = v.ToString ();
2504 Elements.Add (v, sl);
2505 } else if (compare_type == TypeManager.char_type){
2506 char v = (char) key;
2508 if (Elements.Contains (v))
2509 lname = v.ToString ();
2511 Elements.Add (v, sl);
2512 } else if (compare_type == TypeManager.byte_type){
2513 byte v = (byte) key;
2515 if (Elements.Contains (v))
2516 lname = v.ToString ();
2518 Elements.Add (v, sl);
2519 } else if (compare_type == TypeManager.sbyte_type){
2520 sbyte v = (sbyte) key;
2522 if (Elements.Contains (v))
2523 lname = v.ToString ();
2525 Elements.Add (v, sl);
2526 } else if (compare_type == TypeManager.short_type){
2527 short v = (short) key;
2529 if (Elements.Contains (v))
2530 lname = v.ToString ();
2532 Elements.Add (v, sl);
2533 } else if (compare_type == TypeManager.ushort_type){
2534 ushort v = (ushort) key;
2536 if (Elements.Contains (v))
2537 lname = v.ToString ();
2539 Elements.Add (v, sl);
2540 } else if (compare_type == TypeManager.string_type){
2541 if (key is NullLiteral){
2542 if (Elements.Contains (NullLiteral.Null))
2545 Elements.Add (NullLiteral.Null, null);
2547 string s = (string) key;
2549 if (Elements.Contains (s))
2552 Elements.Add (s, sl);
2554 } else if (compare_type == TypeManager.int32_type) {
2557 if (Elements.Contains (v))
2558 lname = v.ToString ();
2560 Elements.Add (v, sl);
2561 } else if (compare_type == TypeManager.bool_type) {
2562 bool v = (bool) key;
2564 if (Elements.Contains (v))
2565 lname = v.ToString ();
2567 Elements.Add (v, sl);
2571 throw new Exception ("Unknown switch type!" +
2572 SwitchType + " " + compare_type);
2576 Report.Error (152, sl.loc, Error152, "case " + lname);
2587 void EmitObjectInteger (ILGenerator ig, object k)
2590 IntConstant.EmitInt (ig, (int) k);
2591 else if (k is Constant) {
2592 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2595 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2598 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2600 IntConstant.EmitInt (ig, (int) (long) k);
2601 ig.Emit (OpCodes.Conv_I8);
2604 LongConstant.EmitLong (ig, (long) k);
2606 else if (k is ulong)
2608 if ((ulong) k < (1L<<32))
2610 IntConstant.EmitInt (ig, (int) (long) k);
2611 ig.Emit (OpCodes.Conv_U8);
2615 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2619 IntConstant.EmitInt (ig, (int) ((char) k));
2620 else if (k is sbyte)
2621 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2623 IntConstant.EmitInt (ig, (int) ((byte) k));
2624 else if (k is short)
2625 IntConstant.EmitInt (ig, (int) ((short) k));
2626 else if (k is ushort)
2627 IntConstant.EmitInt (ig, (int) ((ushort) k));
2629 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2631 throw new Exception ("Unhandled case");
2634 // structure used to hold blocks of keys while calculating table switch
2635 class KeyBlock : IComparable
2637 public KeyBlock (long _nFirst)
2639 nFirst = nLast = _nFirst;
2643 public ArrayList rgKeys = null;
2644 // how many items are in the bucket
2645 public int Size = 1;
2648 get { return (int) (nLast - nFirst + 1); }
2650 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2652 return kbLast.nLast - kbFirst.nFirst + 1;
2654 public int CompareTo (object obj)
2656 KeyBlock kb = (KeyBlock) obj;
2657 int nLength = Length;
2658 int nLengthOther = kb.Length;
2659 if (nLengthOther == nLength)
2660 return (int) (kb.nFirst - nFirst);
2661 return nLength - nLengthOther;
2666 /// This method emits code for a lookup-based switch statement (non-string)
2667 /// Basically it groups the cases into blocks that are at least half full,
2668 /// and then spits out individual lookup opcodes for each block.
2669 /// It emits the longest blocks first, and short blocks are just
2670 /// handled with direct compares.
2672 /// <param name="ec"></param>
2673 /// <param name="val"></param>
2674 /// <returns></returns>
2675 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2677 int cElements = Elements.Count;
2678 object [] rgKeys = new object [cElements];
2679 Elements.Keys.CopyTo (rgKeys, 0);
2680 Array.Sort (rgKeys);
2682 // initialize the block list with one element per key
2683 ArrayList rgKeyBlocks = new ArrayList ();
2684 foreach (object key in rgKeys)
2685 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2688 // iteratively merge the blocks while they are at least half full
2689 // there's probably a really cool way to do this with a tree...
2690 while (rgKeyBlocks.Count > 1)
2692 ArrayList rgKeyBlocksNew = new ArrayList ();
2693 kbCurr = (KeyBlock) rgKeyBlocks [0];
2694 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2696 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2697 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2700 kbCurr.nLast = kb.nLast;
2701 kbCurr.Size += kb.Size;
2705 // start a new block
2706 rgKeyBlocksNew.Add (kbCurr);
2710 rgKeyBlocksNew.Add (kbCurr);
2711 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2713 rgKeyBlocks = rgKeyBlocksNew;
2716 // initialize the key lists
2717 foreach (KeyBlock kb in rgKeyBlocks)
2718 kb.rgKeys = new ArrayList ();
2720 // fill the key lists
2722 if (rgKeyBlocks.Count > 0) {
2723 kbCurr = (KeyBlock) rgKeyBlocks [0];
2724 foreach (object key in rgKeys)
2726 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2727 System.Convert.ToInt64 (key) > kbCurr.nLast;
2729 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2730 kbCurr.rgKeys.Add (key);
2734 // sort the blocks so we can tackle the largest ones first
2735 rgKeyBlocks.Sort ();
2737 // okay now we can start...
2738 ILGenerator ig = ec.ig;
2739 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2740 Label lblDefault = ig.DefineLabel ();
2742 Type typeKeys = null;
2743 if (rgKeys.Length > 0)
2744 typeKeys = rgKeys [0].GetType (); // used for conversions
2748 if (TypeManager.IsEnumType (SwitchType))
2749 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2751 compare_type = SwitchType;
2753 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2755 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2756 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2759 foreach (object key in kb.rgKeys)
2761 ig.Emit (OpCodes.Ldloc, val);
2762 EmitObjectInteger (ig, key);
2763 SwitchLabel sl = (SwitchLabel) Elements [key];
2764 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2769 // TODO: if all the keys in the block are the same and there are
2770 // no gaps/defaults then just use a range-check.
2771 if (compare_type == TypeManager.int64_type ||
2772 compare_type == TypeManager.uint64_type)
2774 // TODO: optimize constant/I4 cases
2776 // check block range (could be > 2^31)
2777 ig.Emit (OpCodes.Ldloc, val);
2778 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2779 ig.Emit (OpCodes.Blt, lblDefault);
2780 ig.Emit (OpCodes.Ldloc, val);
2781 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2782 ig.Emit (OpCodes.Bgt, lblDefault);
2785 ig.Emit (OpCodes.Ldloc, val);
2788 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2789 ig.Emit (OpCodes.Sub);
2791 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2796 ig.Emit (OpCodes.Ldloc, val);
2797 int nFirst = (int) kb.nFirst;
2800 IntConstant.EmitInt (ig, nFirst);
2801 ig.Emit (OpCodes.Sub);
2803 else if (nFirst < 0)
2805 IntConstant.EmitInt (ig, -nFirst);
2806 ig.Emit (OpCodes.Add);
2810 // first, build the list of labels for the switch
2812 int cJumps = kb.Length;
2813 Label [] rgLabels = new Label [cJumps];
2814 for (int iJump = 0; iJump < cJumps; iJump++)
2816 object key = kb.rgKeys [iKey];
2817 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2819 SwitchLabel sl = (SwitchLabel) Elements [key];
2820 rgLabels [iJump] = sl.GetILLabel (ec);
2824 rgLabels [iJump] = lblDefault;
2826 // emit the switch opcode
2827 ig.Emit (OpCodes.Switch, rgLabels);
2830 // mark the default for this block
2832 ig.MarkLabel (lblDefault);
2835 // TODO: find the default case and emit it here,
2836 // to prevent having to do the following jump.
2837 // make sure to mark other labels in the default section
2839 // the last default just goes to the end
2840 ig.Emit (OpCodes.Br, lblDefault);
2842 // now emit the code for the sections
2843 bool fFoundDefault = false;
2844 foreach (SwitchSection ss in Sections)
2846 foreach (SwitchLabel sl in ss.Labels)
2848 ig.MarkLabel (sl.GetILLabel (ec));
2849 ig.MarkLabel (sl.GetILLabelCode (ec));
2850 if (sl.Label == null)
2852 ig.MarkLabel (lblDefault);
2853 fFoundDefault = true;
2857 //ig.Emit (OpCodes.Br, lblEnd);
2860 if (!fFoundDefault) {
2861 ig.MarkLabel (lblDefault);
2863 ig.MarkLabel (lblEnd);
2866 // This simple emit switch works, but does not take advantage of the
2868 // TODO: remove non-string logic from here
2869 // TODO: binary search strings?
2871 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2873 ILGenerator ig = ec.ig;
2874 Label end_of_switch = ig.DefineLabel ();
2875 Label next_test = ig.DefineLabel ();
2876 Label null_target = ig.DefineLabel ();
2877 bool default_found = false;
2878 bool first_test = true;
2879 bool pending_goto_end = false;
2881 bool default_at_end = false;
2883 ig.Emit (OpCodes.Ldloc, val);
2885 if (Elements.Contains (NullLiteral.Null)){
2886 ig.Emit (OpCodes.Brfalse, null_target);
2888 ig.Emit (OpCodes.Brfalse, default_target);
2890 ig.Emit (OpCodes.Ldloc, val);
2891 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2892 ig.Emit (OpCodes.Stloc, val);
2894 int section_count = Sections.Count;
2895 for (int section = 0; section < section_count; section++){
2896 SwitchSection ss = (SwitchSection) Sections [section];
2897 Label sec_begin = ig.DefineLabel ();
2899 if (pending_goto_end)
2900 ig.Emit (OpCodes.Br, end_of_switch);
2902 int label_count = ss.Labels.Count;
2903 bool mark_default = false;
2905 for (int label = 0; label < label_count; label++){
2906 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2907 ig.MarkLabel (sl.GetILLabel (ec));
2910 ig.MarkLabel (next_test);
2911 next_test = ig.DefineLabel ();
2914 // If we are the default target
2916 if (sl.Label == null){
2917 if (label+1 == label_count)
2918 default_at_end = true;
2919 mark_default = true;
2920 default_found = true;
2922 object lit = sl.Converted;
2924 if (lit is NullLiteral){
2926 if (label_count == 1)
2927 ig.Emit (OpCodes.Br, next_test);
2931 StringConstant str = (StringConstant) lit;
2933 ig.Emit (OpCodes.Ldloc, val);
2934 ig.Emit (OpCodes.Ldstr, str.Value);
2935 if (label_count == 1)
2936 ig.Emit (OpCodes.Bne_Un, next_test);
2938 if (label+1 == label_count)
2939 ig.Emit (OpCodes.Bne_Un, next_test);
2941 ig.Emit (OpCodes.Beq, sec_begin);
2946 ig.MarkLabel (null_target);
2947 ig.MarkLabel (sec_begin);
2948 foreach (SwitchLabel sl in ss.Labels)
2949 ig.MarkLabel (sl.GetILLabelCode (ec));
2952 ig.MarkLabel (default_target);
2954 pending_goto_end = !ss.Block.HasRet;
2957 ig.MarkLabel (next_test);
2959 if (!default_at_end)
2960 ig.Emit (OpCodes.Br, default_target);
2962 ig.MarkLabel (default_target);
2963 ig.MarkLabel (end_of_switch);
2966 SwitchSection FindSection (SwitchLabel label)
2968 foreach (SwitchSection ss in Sections){
2969 foreach (SwitchLabel sl in ss.Labels){
2978 bool ResolveConstantSwitch (EmitContext ec)
2980 object key = ((Constant) new_expr).GetValue ();
2981 SwitchLabel label = (SwitchLabel) Elements [key];
2986 constant_section = FindSection (label);
2987 if (constant_section == null)
2990 if (constant_section.Block.Resolve (ec) != true)
2996 public override bool Resolve (EmitContext ec)
2998 Expr = Expr.Resolve (ec);
3002 new_expr = SwitchGoverningType (ec, Expr.Type);
3003 if (new_expr == null){
3004 Report.Error (151, loc, "An integer type or string was expected for switch");
3009 SwitchType = new_expr.Type;
3011 if (!CheckSwitch (ec))
3014 Switch old_switch = ec.Switch;
3016 ec.Switch.SwitchType = SwitchType;
3018 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3019 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3021 is_constant = new_expr is Constant;
3023 object key = ((Constant) new_expr).GetValue ();
3024 SwitchLabel label = (SwitchLabel) Elements [key];
3026 constant_section = FindSection (label);
3030 foreach (SwitchSection ss in Sections){
3032 ec.CurrentBranching.CreateSibling (
3033 null, FlowBranching.SiblingType.SwitchSection);
3037 if (is_constant && (ss != constant_section)) {
3038 // If we're a constant switch, we're only emitting
3039 // one single section - mark all the others as
3041 ec.CurrentBranching.CurrentUsageVector.Goto ();
3042 if (!ss.Block.ResolveUnreachable (ec, true))
3045 if (!ss.Block.Resolve (ec))
3051 ec.CurrentBranching.CreateSibling (
3052 null, FlowBranching.SiblingType.SwitchSection);
3054 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3055 ec.Switch = old_switch;
3057 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3063 protected override void DoEmit (EmitContext ec)
3065 ILGenerator ig = ec.ig;
3067 // Store variable for comparission purposes
3070 value = ig.DeclareLocal (SwitchType);
3072 ig.Emit (OpCodes.Stloc, value);
3076 default_target = ig.DefineLabel ();
3079 // Setup the codegen context
3081 Label old_end = ec.LoopEnd;
3082 Switch old_switch = ec.Switch;
3084 ec.LoopEnd = ig.DefineLabel ();
3089 if (constant_section != null)
3090 constant_section.Block.Emit (ec);
3091 } else if (SwitchType == TypeManager.string_type)
3092 SimpleSwitchEmit (ec, value);
3094 TableSwitchEmit (ec, value);
3096 // Restore context state.
3097 ig.MarkLabel (ec.LoopEnd);
3100 // Restore the previous context
3102 ec.LoopEnd = old_end;
3103 ec.Switch = old_switch;
3107 public abstract class ExceptionStatement : Statement
3109 public abstract void EmitFinally (EmitContext ec);
3111 protected bool emit_finally = true;
3112 ArrayList parent_vectors;
3114 protected void DoEmitFinally (EmitContext ec)
3117 ec.ig.BeginFinallyBlock ();
3119 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3123 protected void ResolveFinally (FlowBranchingException branching)
3125 emit_finally = branching.EmitFinally;
3127 branching.Parent.StealFinallyClauses (ref parent_vectors);
3131 public class Lock : ExceptionStatement {
3133 Statement Statement;
3136 public Lock (Expression expr, Statement stmt, Location l)
3143 public override bool Resolve (EmitContext ec)
3145 expr = expr.Resolve (ec);
3149 if (expr.Type.IsValueType){
3150 Error (185, "lock statement requires the expression to be " +
3151 " a reference type (type is: `{0}'",
3152 TypeManager.CSharpName (expr.Type));
3156 FlowBranchingException branching = ec.StartFlowBranching (this);
3157 bool ok = Statement.Resolve (ec);
3159 ec.KillFlowBranching ();
3163 ResolveFinally (branching);
3165 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3166 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3167 // Unfortunately, System.Reflection.Emit automatically emits
3168 // a leave to the end of the finally block.
3169 // This is a problem if `returns' is true since we may jump
3170 // to a point after the end of the method.
3171 // As a workaround, emit an explicit ret here.
3172 ec.NeedReturnLabel ();
3178 protected override void DoEmit (EmitContext ec)
3180 Type type = expr.Type;
3182 ILGenerator ig = ec.ig;
3183 temp = ig.DeclareLocal (type);
3186 ig.Emit (OpCodes.Dup);
3187 ig.Emit (OpCodes.Stloc, temp);
3188 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3192 ig.BeginExceptionBlock ();
3193 Statement.Emit (ec);
3198 ig.EndExceptionBlock ();
3201 public override void EmitFinally (EmitContext ec)
3203 ILGenerator ig = ec.ig;
3204 ig.Emit (OpCodes.Ldloc, temp);
3205 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3209 public class Unchecked : Statement {
3210 public readonly Block Block;
3212 public Unchecked (Block b)
3218 public override bool Resolve (EmitContext ec)
3220 bool previous_state = ec.CheckState;
3221 bool previous_state_const = ec.ConstantCheckState;
3223 ec.CheckState = false;
3224 ec.ConstantCheckState = false;
3225 bool ret = Block.Resolve (ec);
3226 ec.CheckState = previous_state;
3227 ec.ConstantCheckState = previous_state_const;
3232 protected override void DoEmit (EmitContext ec)
3234 bool previous_state = ec.CheckState;
3235 bool previous_state_const = ec.ConstantCheckState;
3237 ec.CheckState = false;
3238 ec.ConstantCheckState = false;
3240 ec.CheckState = previous_state;
3241 ec.ConstantCheckState = previous_state_const;
3245 public class Checked : Statement {
3246 public readonly Block Block;
3248 public Checked (Block b)
3251 b.Unchecked = false;
3254 public override bool Resolve (EmitContext ec)
3256 bool previous_state = ec.CheckState;
3257 bool previous_state_const = ec.ConstantCheckState;
3259 ec.CheckState = true;
3260 ec.ConstantCheckState = true;
3261 bool ret = Block.Resolve (ec);
3262 ec.CheckState = previous_state;
3263 ec.ConstantCheckState = previous_state_const;
3268 protected override void DoEmit (EmitContext ec)
3270 bool previous_state = ec.CheckState;
3271 bool previous_state_const = ec.ConstantCheckState;
3273 ec.CheckState = true;
3274 ec.ConstantCheckState = true;
3276 ec.CheckState = previous_state;
3277 ec.ConstantCheckState = previous_state_const;
3281 public class Unsafe : Statement {
3282 public readonly Block Block;
3284 public Unsafe (Block b)
3287 Block.Unsafe = true;
3290 public override bool Resolve (EmitContext ec)
3292 bool previous_state = ec.InUnsafe;
3296 val = Block.Resolve (ec);
3297 ec.InUnsafe = previous_state;
3302 protected override void DoEmit (EmitContext ec)
3304 bool previous_state = ec.InUnsafe;
3308 ec.InUnsafe = previous_state;
3315 public class Fixed : Statement {
3317 ArrayList declarators;
3318 Statement statement;
3324 public bool is_object;
3325 public LocalInfo vi;
3326 public Expression expr;
3327 public Expression converted;
3330 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3333 declarators = decls;
3338 public override bool Resolve (EmitContext ec)
3341 Expression.UnsafeError (loc);
3345 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3349 expr_type = texpr.Type;
3351 CheckObsolete (expr_type);
3353 if (ec.RemapToProxy){
3354 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3358 data = new FixedData [declarators.Count];
3360 if (!expr_type.IsPointer){
3361 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3366 foreach (Pair p in declarators){
3367 LocalInfo vi = (LocalInfo) p.First;
3368 Expression e = (Expression) p.Second;
3370 vi.VariableInfo.SetAssigned (ec);
3374 // The rules for the possible declarators are pretty wise,
3375 // but the production on the grammar is more concise.
3377 // So we have to enforce these rules here.
3379 // We do not resolve before doing the case 1 test,
3380 // because the grammar is explicit in that the token &
3381 // is present, so we need to test for this particular case.
3385 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3390 // Case 1: & object.
3392 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3393 Expression child = ((Unary) e).Expr;
3395 if (child is ParameterReference || child is LocalVariableReference){
3398 "No need to use fixed statement for parameters or " +
3399 "local variable declarations (address is already " +
3404 ec.InFixedInitializer = true;
3406 ec.InFixedInitializer = false;
3410 child = ((Unary) e).Expr;
3412 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3415 data [i].is_object = true;
3417 data [i].converted = null;
3424 ec.InFixedInitializer = true;
3426 ec.InFixedInitializer = false;
3433 if (e.Type.IsArray){
3434 Type array_type = TypeManager.GetElementType (e.Type);
3437 // Provided that array_type is unmanaged,
3439 if (!TypeManager.VerifyUnManaged (array_type, loc))
3443 // and T* is implicitly convertible to the
3444 // pointer type given in the fixed statement.
3446 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3448 Expression converted = Convert.WideningConversionRequired (
3449 ec, array_ptr, vi.VariableType, loc);
3450 if (converted == null)
3453 data [i].is_object = false;
3455 data [i].converted = converted;
3465 if (e.Type == TypeManager.string_type){
3466 data [i].is_object = false;
3468 data [i].converted = null;
3475 // For other cases, flag a `this is already fixed expression'
3477 if (e is LocalVariableReference || e is ParameterReference ||
3478 Convert.WideningConversionExists (ec, e, vi.VariableType)){
3480 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3484 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3488 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3490 if (!statement.Resolve (ec)) {
3491 ec.KillFlowBranching ();
3495 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3496 has_ret = reachability.IsUnreachable;
3501 protected override void DoEmit (EmitContext ec)
3503 ILGenerator ig = ec.ig;
3505 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3507 for (int i = 0; i < data.Length; i++) {
3508 LocalInfo vi = data [i].vi;
3511 // Case 1: & object.
3513 if (data [i].is_object) {
3515 // Store pointer in pinned location
3517 data [i].expr.Emit (ec);
3518 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3519 clear_list [i] = vi.LocalBuilder;
3526 if (data [i].expr.Type.IsArray){
3528 // Store pointer in pinned location
3530 data [i].converted.Emit (ec);
3532 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3533 clear_list [i] = vi.LocalBuilder;
3540 if (data [i].expr.Type == TypeManager.string_type){
3541 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3542 clear_list [i] = pinned_string;
3544 data [i].expr.Emit (ec);
3545 ig.Emit (OpCodes.Stloc, pinned_string);
3547 Expression sptr = new StringPtr (pinned_string, loc);
3548 Expression converted = Convert.WideningConversionRequired (
3549 ec, sptr, vi.VariableType, loc);
3551 if (converted == null)
3554 converted.Emit (ec);
3555 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3559 statement.Emit (ec);
3565 // Clear the pinned variable
3567 for (int i = 0; i < data.Length; i++) {
3568 if (data [i].is_object || data [i].expr.Type.IsArray) {
3569 ig.Emit (OpCodes.Ldc_I4_0);
3570 ig.Emit (OpCodes.Conv_U);
3571 ig.Emit (OpCodes.Stloc, clear_list [i]);
3572 } else if (data [i].expr.Type == TypeManager.string_type){
3573 ig.Emit (OpCodes.Ldnull);
3574 ig.Emit (OpCodes.Stloc, clear_list [i]);
3580 public class Catch: Statement {
3581 public readonly string Name;
3582 public readonly Block Block;
3584 Expression type_expr;
3587 public Catch (Expression type, string name, Block block, Location l)
3595 public Type CatchType {
3601 public bool IsGeneral {
3603 return type_expr == null;
3607 protected override void DoEmit(EmitContext ec)
3611 public override bool Resolve (EmitContext ec)
3613 if (type_expr != null) {
3614 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3620 CheckObsolete (type);
3622 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3623 Error (155, "The type caught or thrown must be derived from System.Exception");
3629 return Block.Resolve (ec);
3633 public class Try : ExceptionStatement {
3634 public readonly Block Fini, Block;
3635 public readonly ArrayList Specific;
3636 public readonly Catch General;
3638 bool need_exc_block;
3641 // specific, general and fini might all be null.
3643 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3645 if (specific == null && general == null){
3646 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3650 this.Specific = specific;
3651 this.General = general;
3656 public override bool Resolve (EmitContext ec)
3660 FlowBranchingException branching = ec.StartFlowBranching (this);
3662 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3664 if (!Block.Resolve (ec))
3667 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3669 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3671 Type[] prevCatches = new Type [Specific.Count];
3673 foreach (Catch c in Specific){
3674 ec.CurrentBranching.CreateSibling (
3675 c.Block, FlowBranching.SiblingType.Catch);
3677 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3679 if (c.Name != null) {
3680 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3682 throw new Exception ();
3684 vi.VariableInfo = null;
3687 if (!c.Resolve (ec))
3690 Type resolvedType = c.CatchType;
3691 for (int ii = 0; ii < last_index; ++ii) {
3692 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3693 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3698 prevCatches [last_index++] = resolvedType;
3699 need_exc_block = true;
3702 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3704 if (General != null){
3705 ec.CurrentBranching.CreateSibling (
3706 General.Block, FlowBranching.SiblingType.Catch);
3708 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3710 if (!General.Resolve (ec))
3713 need_exc_block = true;
3716 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3720 ec.CurrentBranching.CreateSibling (
3721 Fini, FlowBranching.SiblingType.Finally);
3723 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3725 if (!Fini.Resolve (ec))
3729 ResolveFinally (branching);
3730 need_exc_block |= emit_finally;
3732 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3734 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3736 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3738 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3739 // Unfortunately, System.Reflection.Emit automatically emits
3740 // a leave to the end of the finally block. This is a problem
3741 // if `returns' is true since we may jump to a point after the
3742 // end of the method.
3743 // As a workaround, emit an explicit ret here.
3744 ec.NeedReturnLabel ();
3750 protected override void DoEmit (EmitContext ec)
3752 ILGenerator ig = ec.ig;
3755 ig.BeginExceptionBlock ();
3758 foreach (Catch c in Specific){
3761 ig.BeginCatchBlock (c.CatchType);
3763 if (c.Name != null){
3764 vi = c.Block.GetLocalInfo (c.Name);
3766 throw new Exception ("Variable does not exist in this block");
3768 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3770 ig.Emit (OpCodes.Pop);
3775 if (General != null){
3776 ig.BeginCatchBlock (TypeManager.object_type);
3777 ig.Emit (OpCodes.Pop);
3778 General.Block.Emit (ec);
3783 ig.EndExceptionBlock ();
3786 public override void EmitFinally (EmitContext ec)
3794 public class Using : ExceptionStatement {
3795 object expression_or_block;
3796 Statement Statement;
3801 Expression [] resolved_vars;
3802 Expression [] converted_vars;
3803 ExpressionStatement [] assign;
3804 LocalBuilder local_copy;
3806 public Using (object expression_or_block, Statement stmt, Location l)
3808 this.expression_or_block = expression_or_block;
3814 // Resolves for the case of using using a local variable declaration.
3816 bool ResolveLocalVariableDecls (EmitContext ec)
3820 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3824 expr_type = texpr.Type;
3827 // The type must be an IDisposable or an implicit conversion
3830 converted_vars = new Expression [var_list.Count];
3831 resolved_vars = new Expression [var_list.Count];
3832 assign = new ExpressionStatement [var_list.Count];
3834 bool need_conv = !TypeManager.ImplementsInterface (
3835 expr_type, TypeManager.idisposable_type);
3837 foreach (DictionaryEntry e in var_list){
3838 Expression var = (Expression) e.Key;
3840 var = var.ResolveLValue (ec, new EmptyExpression ());
3844 resolved_vars [i] = var;
3851 converted_vars [i] = Convert.WideningConversionRequired (
3852 ec, var, TypeManager.idisposable_type, loc);
3854 if (converted_vars [i] == null)
3861 foreach (DictionaryEntry e in var_list){
3862 Expression var = resolved_vars [i];
3863 Expression new_expr = (Expression) e.Value;
3866 a = new Assign (var, new_expr, loc);
3872 converted_vars [i] = var;
3873 assign [i] = (ExpressionStatement) a;
3880 bool ResolveExpression (EmitContext ec)
3882 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3883 conv = Convert.WideningConversionRequired (
3884 ec, expr, TypeManager.idisposable_type, loc);
3894 // Emits the code for the case of using using a local variable declaration.
3896 void EmitLocalVariableDecls (EmitContext ec)
3898 ILGenerator ig = ec.ig;
3901 for (i = 0; i < assign.Length; i++) {
3902 assign [i].EmitStatement (ec);
3905 ig.BeginExceptionBlock ();
3907 Statement.Emit (ec);
3909 var_list.Reverse ();
3914 void EmitLocalVariableDeclFinally (EmitContext ec)
3916 ILGenerator ig = ec.ig;
3918 int i = assign.Length;
3919 for (int ii = 0; ii < var_list.Count; ++ii){
3920 Expression var = resolved_vars [--i];
3921 Label skip = ig.DefineLabel ();
3923 ig.BeginFinallyBlock ();
3925 if (!var.Type.IsValueType) {
3927 ig.Emit (OpCodes.Brfalse, skip);
3928 converted_vars [i].Emit (ec);
3929 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3931 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3933 if (!(ml is MethodGroupExpr)) {
3935 ig.Emit (OpCodes.Box, var.Type);
3936 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3938 MethodInfo mi = null;
3940 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3941 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3948 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3952 IMemoryLocation mloc = (IMemoryLocation) var;
3954 mloc.AddressOf (ec, AddressOp.Load);
3955 ig.Emit (OpCodes.Call, mi);
3959 ig.MarkLabel (skip);
3962 ig.EndExceptionBlock ();
3964 ig.BeginFinallyBlock ();
3969 void EmitExpression (EmitContext ec)
3972 // Make a copy of the expression and operate on that.
3974 ILGenerator ig = ec.ig;
3975 local_copy = ig.DeclareLocal (expr_type);
3980 ig.Emit (OpCodes.Stloc, local_copy);
3983 ig.BeginExceptionBlock ();
3985 Statement.Emit (ec);
3989 ig.EndExceptionBlock ();
3992 void EmitExpressionFinally (EmitContext ec)
3994 ILGenerator ig = ec.ig;
3995 if (!local_copy.LocalType.IsValueType) {
3996 Label skip = ig.DefineLabel ();
3997 ig.Emit (OpCodes.Ldloc, local_copy);
3998 ig.Emit (OpCodes.Brfalse, skip);
3999 ig.Emit (OpCodes.Ldloc, local_copy);
4000 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4001 ig.MarkLabel (skip);
4003 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4005 if (!(ml is MethodGroupExpr)) {
4006 ig.Emit (OpCodes.Ldloc, local_copy);
4007 ig.Emit (OpCodes.Box, local_copy.LocalType);
4008 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4010 MethodInfo mi = null;
4012 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4013 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4020 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4024 ig.Emit (OpCodes.Ldloca, local_copy);
4025 ig.Emit (OpCodes.Call, mi);
4030 public override bool Resolve (EmitContext ec)
4032 if (expression_or_block is DictionaryEntry){
4033 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4034 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4036 if (!ResolveLocalVariableDecls (ec))
4039 } else if (expression_or_block is Expression){
4040 expr = (Expression) expression_or_block;
4042 expr = expr.Resolve (ec);
4046 expr_type = expr.Type;
4048 if (!ResolveExpression (ec))
4052 FlowBranchingException branching = ec.StartFlowBranching (this);
4054 bool ok = Statement.Resolve (ec);
4057 ec.KillFlowBranching ();
4061 ResolveFinally (branching);
4062 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4064 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4065 // Unfortunately, System.Reflection.Emit automatically emits a leave
4066 // to the end of the finally block. This is a problem if `returns'
4067 // is true since we may jump to a point after the end of the method.
4068 // As a workaround, emit an explicit ret here.
4069 ec.NeedReturnLabel ();
4075 protected override void DoEmit (EmitContext ec)
4077 if (expression_or_block is DictionaryEntry)
4078 EmitLocalVariableDecls (ec);
4079 else if (expression_or_block is Expression)
4080 EmitExpression (ec);
4083 public override void EmitFinally (EmitContext ec)
4085 if (expression_or_block is DictionaryEntry)
4086 EmitLocalVariableDeclFinally (ec);
4087 else if (expression_or_block is Expression)
4088 EmitExpressionFinally (ec);
4093 /// Implementation of the foreach C# statement
4095 public class Foreach : ExceptionStatement {
4097 Expression variable;
4099 Statement statement;
4100 ForeachHelperMethods hm;
4101 Expression empty, conv;
4102 Type array_type, element_type;
4104 VariableStorage enumerator;
4106 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4107 Statement stmt, Location l)
4110 this.variable = var;
4116 public override bool Resolve (EmitContext ec)
4118 expr = expr.Resolve (ec);
4122 if (expr is NullLiteral) {
4123 Report.Error (186, expr.Location, "Use of null is not valid in this context");
4127 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4131 var_type = texpr.Type;
4134 // We need an instance variable. Not sure this is the best
4135 // way of doing this.
4137 // FIXME: When we implement propertyaccess, will those turn
4138 // out to return values in ExprClass? I think they should.
4140 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4141 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4142 error1579 (expr.Type);
4146 if (expr.Type.IsArray) {
4147 array_type = expr.Type;
4148 element_type = TypeManager.GetElementType (array_type);
4150 empty = new EmptyExpression (element_type);
4152 hm = ProbeCollectionType (ec, expr.Type);
4154 error1579 (expr.Type);
4158 array_type = expr.Type;
4159 element_type = hm.element_type;
4161 empty = new EmptyExpression (hm.element_type);
4166 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4167 ec.CurrentBranching.CreateSibling ();
4171 // FIXME: maybe we can apply the same trick we do in the
4172 // array handling to avoid creating empty and conv in some cases.
4174 // Although it is not as important in this case, as the type
4175 // will not likely be object (what the enumerator will return).
4177 conv = Convert.WideningAndNarrowingConversion (ec, empty, var_type, loc);
4181 variable = variable.ResolveLValue (ec, empty);
4182 if (variable == null)
4185 bool disposable = (hm != null) && hm.is_disposable;
4186 FlowBranchingException branching = null;
4188 branching = ec.StartFlowBranching (this);
4190 if (!statement.Resolve (ec))
4194 ResolveFinally (branching);
4195 ec.EndFlowBranching ();
4197 emit_finally = true;
4199 ec.EndFlowBranching ();
4205 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4207 static MethodInfo FetchMethodMoveNext (Type t)
4209 MemberList move_next_list;
4211 move_next_list = TypeContainer.FindMembers (
4212 t, MemberTypes.Method,
4213 BindingFlags.Public | BindingFlags.Instance,
4214 Type.FilterName, "MoveNext");
4215 if (move_next_list.Count == 0)
4218 foreach (MemberInfo m in move_next_list){
4219 MethodInfo mi = (MethodInfo) m;
4222 args = TypeManager.GetArgumentTypes (mi);
4223 if (args != null && args.Length == 0){
4224 if (TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type)
4232 // Retrieves a `public T get_Current ()' method from the Type `t'
4234 static MethodInfo FetchMethodGetCurrent (Type t)
4236 MemberList get_current_list;
4238 get_current_list = TypeContainer.FindMembers (
4239 t, MemberTypes.Method,
4240 BindingFlags.Public | BindingFlags.Instance,
4241 Type.FilterName, "get_Current");
4242 if (get_current_list.Count == 0)
4245 foreach (MemberInfo m in get_current_list){
4246 MethodInfo mi = (MethodInfo) m;
4249 args = TypeManager.GetArgumentTypes (mi);
4250 if (args != null && args.Length == 0)
4257 // Retrieves a `public void Dispose ()' method from the Type `t'
4259 static MethodInfo FetchMethodDispose (Type t)
4261 MemberList dispose_list;
4263 dispose_list = TypeContainer.FindMembers (
4264 t, MemberTypes.Method,
4265 BindingFlags.Public | BindingFlags.Instance,
4266 Type.FilterName, "Dispose");
4267 if (dispose_list.Count == 0)
4270 foreach (MemberInfo m in dispose_list){
4271 MethodInfo mi = (MethodInfo) m;
4274 args = TypeManager.GetArgumentTypes (mi);
4275 if (args != null && args.Length == 0){
4276 if (mi.ReturnType == TypeManager.void_type)
4284 // This struct records the helper methods used by the Foreach construct
4286 class ForeachHelperMethods {
4287 public EmitContext ec;
4288 public MethodInfo get_enumerator;
4289 public MethodInfo move_next;
4290 public MethodInfo get_current;
4291 public Type element_type;
4292 public Type enumerator_type;
4293 public bool is_disposable;
4295 public ForeachHelperMethods (EmitContext ec)
4298 this.element_type = TypeManager.object_type;
4299 this.enumerator_type = TypeManager.ienumerator_type;
4300 this.is_disposable = true;
4304 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4309 if (!(m is MethodInfo))
4312 if (m.Name != "GetEnumerator")
4315 MethodInfo mi = (MethodInfo) m;
4316 Type [] args = TypeManager.GetArgumentTypes (mi);
4318 if (args.Length != 0)
4321 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4323 // Check whether GetEnumerator is public
4324 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4327 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4329 // Apply the same optimization as MS: skip the GetEnumerator
4330 // returning an IEnumerator, and use the one returning a
4331 // CharEnumerator instead. This allows us to avoid the
4332 // try-finally block and the boxing.
4337 // Ok, we can access it, now make sure that we can do something
4338 // with this `GetEnumerator'
4341 Type return_type = mi.ReturnType;
4342 if (mi.ReturnType == TypeManager.ienumerator_type ||
4343 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4344 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4347 // If it is not an interface, lets try to find the methods ourselves.
4348 // For example, if we have:
4349 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4350 // We can avoid the iface call. This is a runtime perf boost.
4351 // even bigger if we have a ValueType, because we avoid the cost
4354 // We have to make sure that both methods exist for us to take
4355 // this path. If one of the methods does not exist, we will just
4356 // use the interface. Sadly, this complex if statement is the only
4357 // way I could do this without a goto
4360 if (return_type.IsInterface ||
4361 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4362 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4364 hm.move_next = TypeManager.bool_movenext_void;
4365 hm.get_current = TypeManager.object_getcurrent_void;
4372 // Ok, so they dont return an IEnumerable, we will have to
4373 // find if they support the GetEnumerator pattern.
4376 hm.move_next = FetchMethodMoveNext (return_type);
4377 if (hm.move_next == null)
4380 hm.get_current = FetchMethodGetCurrent (return_type);
4381 if (hm.get_current == null)
4385 hm.element_type = hm.get_current.ReturnType;
4386 hm.enumerator_type = return_type;
4387 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4388 TypeManager.ImplementsInterface (
4389 hm.enumerator_type, TypeManager.idisposable_type);
4395 /// This filter is used to find the GetEnumerator method
4396 /// on which IEnumerator operates
4398 static MemberFilter FilterEnumerator;
4402 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4405 void error1579 (Type t)
4407 Report.Error (1579, loc,
4408 "foreach statement cannot operate on variables of type `" +
4409 t.FullName + "' because that class does not provide a " +
4410 " GetEnumerator method or it is inaccessible");
4413 static bool TryType (Type t, ForeachHelperMethods hm)
4417 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4418 BindingFlags.Public | BindingFlags.NonPublic |
4419 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4420 FilterEnumerator, hm);
4425 hm.get_enumerator = (MethodInfo) mi [0];
4430 // Looks for a usable GetEnumerator in the Type, and if found returns
4431 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4433 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4435 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4437 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4438 if (TryType (tt, hm))
4444 // Now try to find the method in the interfaces
4447 Type [] ifaces = t.GetInterfaces ();
4449 foreach (Type i in ifaces){
4450 if (TryType (i, hm))
4455 // Since TypeBuilder.GetInterfaces only returns the interface
4456 // types for this type, we have to keep looping, but once
4457 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4458 // done, because it returns all the types
4460 if ((t is TypeBuilder))
4470 // FIXME: possible optimization.
4471 // We might be able to avoid creating `empty' if the type is the sam
4473 bool EmitCollectionForeach (EmitContext ec)
4475 ILGenerator ig = ec.ig;
4477 enumerator = new VariableStorage (ec, hm.enumerator_type);
4478 enumerator.EmitThis (ig);
4480 // Instantiate the enumerator
4482 if (expr.Type.IsValueType){
4483 IMemoryLocation ml = expr as IMemoryLocation;
4484 // Load the address of the value type.
4486 // This happens if, for example, you have a property
4487 // returning a struct which is IEnumerable
4488 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4490 ig.Emit (OpCodes.Stloc, t);
4491 ig.Emit (OpCodes.Ldloca, t);
4492 ec.FreeTemporaryLocal (t, expr.Type);
4494 ml.AddressOf (ec, AddressOp.Load);
4498 if (hm.get_enumerator.DeclaringType.IsValueType) {
4499 // the method is declared on the value type
4500 ig.Emit (OpCodes.Call, hm.get_enumerator);
4502 // it is an interface method, so we must box
4503 ig.Emit (OpCodes.Box, expr.Type);
4504 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4508 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4510 enumerator.EmitStore (ig);
4513 // Protect the code in a try/finalize block, so that
4514 // if the beast implement IDisposable, we get rid of it
4516 if (hm.is_disposable && emit_finally)
4517 ig.BeginExceptionBlock ();
4519 Label end_try = ig.DefineLabel ();
4521 ig.MarkLabel (ec.LoopBegin);
4523 enumerator.EmitCall (ig, hm.move_next);
4525 ig.Emit (OpCodes.Brfalse, end_try);
4528 ig.Emit (OpCodes.Ldarg_0);
4530 enumerator.EmitCall (ig, hm.get_current);
4534 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4536 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4538 statement.Emit (ec);
4539 ig.Emit (OpCodes.Br, ec.LoopBegin);
4540 ig.MarkLabel (end_try);
4542 // The runtime provides this for us.
4543 // ig.Emit (OpCodes.Leave, end);
4546 // Now the finally block
4548 if (hm.is_disposable) {
4551 ig.EndExceptionBlock ();
4554 ig.MarkLabel (ec.LoopEnd);
4558 public override void EmitFinally (EmitContext ec)
4560 ILGenerator ig = ec.ig;
4562 if (hm.enumerator_type.IsValueType) {
4563 enumerator.EmitThis (ig);
4565 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4567 enumerator.EmitLoadAddress (ig);
4568 ig.Emit (OpCodes.Call, mi);
4570 enumerator.EmitLoad (ig);
4571 ig.Emit (OpCodes.Box, hm.enumerator_type);
4572 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4575 Label call_dispose = ig.DefineLabel ();
4577 enumerator.EmitThis (ig);
4578 enumerator.EmitLoad (ig);
4579 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4580 ig.Emit (OpCodes.Dup);
4581 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4582 ig.Emit (OpCodes.Pop);
4584 Label end_finally = ig.DefineLabel ();
4585 ig.Emit (OpCodes.Br, end_finally);
4587 ig.MarkLabel (call_dispose);
4588 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4589 ig.MarkLabel (end_finally);
4592 ig.Emit (OpCodes.Endfinally);
4597 // FIXME: possible optimization.
4598 // We might be able to avoid creating `empty' if the type is the sam
4600 bool EmitArrayForeach (EmitContext ec)
4602 int rank = array_type.GetArrayRank ();
4603 ILGenerator ig = ec.ig;
4605 VariableStorage copy = new VariableStorage (ec, array_type);
4608 // Make our copy of the array
4612 copy.EmitStore (ig);
4615 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4619 counter.EmitThis (ig);
4620 ig.Emit (OpCodes.Ldc_I4_0);
4621 counter.EmitStore (ig);
4622 test = ig.DefineLabel ();
4623 ig.Emit (OpCodes.Br, test);
4625 loop = ig.DefineLabel ();
4626 ig.MarkLabel (loop);
4629 ig.Emit (OpCodes.Ldarg_0);
4633 counter.EmitThis (ig);
4634 counter.EmitLoad (ig);
4637 // Load the value, we load the value using the underlying type,
4638 // then we use the variable.EmitAssign to load using the proper cast.
4640 ArrayAccess.EmitLoadOpcode (ig, element_type);
4643 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4645 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4647 statement.Emit (ec);
4649 ig.MarkLabel (ec.LoopBegin);
4650 counter.EmitThis (ig);
4651 counter.EmitThis (ig);
4652 counter.EmitLoad (ig);
4653 ig.Emit (OpCodes.Ldc_I4_1);
4654 ig.Emit (OpCodes.Add);
4655 counter.EmitStore (ig);
4657 ig.MarkLabel (test);
4658 counter.EmitThis (ig);
4659 counter.EmitLoad (ig);
4662 ig.Emit (OpCodes.Ldlen);
4663 ig.Emit (OpCodes.Conv_I4);
4664 ig.Emit (OpCodes.Blt, loop);
4666 VariableStorage [] dim_len = new VariableStorage [rank];
4667 VariableStorage [] dim_count = new VariableStorage [rank];
4668 Label [] loop = new Label [rank];
4669 Label [] test = new Label [rank];
4672 for (dim = 0; dim < rank; dim++){
4673 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4674 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4675 test [dim] = ig.DefineLabel ();
4676 loop [dim] = ig.DefineLabel ();
4679 for (dim = 0; dim < rank; dim++){
4680 dim_len [dim].EmitThis (ig);
4683 IntLiteral.EmitInt (ig, dim);
4684 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4685 dim_len [dim].EmitStore (ig);
4689 for (dim = 0; dim < rank; dim++){
4690 dim_count [dim].EmitThis (ig);
4691 ig.Emit (OpCodes.Ldc_I4_0);
4692 dim_count [dim].EmitStore (ig);
4693 ig.Emit (OpCodes.Br, test [dim]);
4694 ig.MarkLabel (loop [dim]);
4698 ig.Emit (OpCodes.Ldarg_0);
4702 for (dim = 0; dim < rank; dim++){
4703 dim_count [dim].EmitThis (ig);
4704 dim_count [dim].EmitLoad (ig);
4708 // FIXME: Maybe we can cache the computation of `get'?
4710 Type [] args = new Type [rank];
4713 for (int i = 0; i < rank; i++)
4714 args [i] = TypeManager.int32_type;
4716 ModuleBuilder mb = CodeGen.Module.Builder;
4717 get = mb.GetArrayMethod (
4719 CallingConventions.HasThis| CallingConventions.Standard,
4721 ig.Emit (OpCodes.Call, get);
4724 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4726 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4727 statement.Emit (ec);
4728 ig.MarkLabel (ec.LoopBegin);
4729 for (dim = rank - 1; dim >= 0; dim--){
4730 dim_count [dim].EmitThis (ig);
4731 dim_count [dim].EmitThis (ig);
4732 dim_count [dim].EmitLoad (ig);
4733 ig.Emit (OpCodes.Ldc_I4_1);
4734 ig.Emit (OpCodes.Add);
4735 dim_count [dim].EmitStore (ig);
4737 ig.MarkLabel (test [dim]);
4738 dim_count [dim].EmitThis (ig);
4739 dim_count [dim].EmitLoad (ig);
4740 dim_len [dim].EmitThis (ig);
4741 dim_len [dim].EmitLoad (ig);
4742 ig.Emit (OpCodes.Blt, loop [dim]);
4745 ig.MarkLabel (ec.LoopEnd);
4750 protected override void DoEmit (EmitContext ec)
4752 ILGenerator ig = ec.ig;
4754 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4755 ec.LoopBegin = ig.DefineLabel ();
4756 ec.LoopEnd = ig.DefineLabel ();
4759 EmitCollectionForeach (ec);
4761 EmitArrayForeach (ec);
4763 ec.LoopBegin = old_begin;
4764 ec.LoopEnd = old_end;