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)
144 Report.Debug (1, "START IF BLOCK", loc);
146 expr = Expression.ResolveBoolean (ec, expr, loc);
152 Assign ass = expr as Assign;
153 if (ass != null && ass.Source is Constant) {
154 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
158 // Dead code elimination
160 if (expr is BoolConstant){
161 bool take = ((BoolConstant) expr).Value;
164 if (!TrueStatement.Resolve (ec))
167 if ((FalseStatement != null) &&
168 !FalseStatement.ResolveUnreachable (ec, true))
170 FalseStatement = null;
172 if (!TrueStatement.ResolveUnreachable (ec, true))
174 TrueStatement = null;
176 if ((FalseStatement != null) &&
177 !FalseStatement.Resolve (ec))
184 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
186 ok &= TrueStatement.Resolve (ec);
188 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
190 ec.CurrentBranching.CreateSibling ();
192 if (FalseStatement != null)
193 ok &= FalseStatement.Resolve (ec);
195 ec.EndFlowBranching ();
197 Report.Debug (1, "END IF BLOCK", loc);
202 protected override void DoEmit (EmitContext ec)
204 ILGenerator ig = ec.ig;
205 Label false_target = ig.DefineLabel ();
209 // If we're a boolean expression, Resolve() already
210 // eliminated dead code for us.
212 if (expr is BoolConstant){
213 bool take = ((BoolConstant) expr).Value;
216 TrueStatement.Emit (ec);
217 else if (FalseStatement != null)
218 FalseStatement.Emit (ec);
223 expr.EmitBranchable (ec, false_target, false);
225 TrueStatement.Emit (ec);
227 if (FalseStatement != null){
228 bool branch_emitted = false;
230 end = ig.DefineLabel ();
232 ig.Emit (OpCodes.Br, end);
233 branch_emitted = true;
236 ig.MarkLabel (false_target);
237 FalseStatement.Emit (ec);
242 ig.MarkLabel (false_target);
247 public class Do : Statement {
248 public Expression expr;
249 public readonly Statement EmbeddedStatement;
252 public Do (Statement statement, Expression boolExpr, Location l)
255 EmbeddedStatement = statement;
259 public override bool Resolve (EmitContext ec)
263 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
265 if (!EmbeddedStatement.Resolve (ec))
268 expr = Expression.ResolveBoolean (ec, expr, loc);
271 else if (expr is BoolConstant){
272 bool res = ((BoolConstant) expr).Value;
278 ec.CurrentBranching.Infinite = infinite;
279 ec.EndFlowBranching ();
284 protected override void DoEmit (EmitContext ec)
286 ILGenerator ig = ec.ig;
287 Label loop = ig.DefineLabel ();
288 Label old_begin = ec.LoopBegin;
289 Label old_end = ec.LoopEnd;
291 ec.LoopBegin = ig.DefineLabel ();
292 ec.LoopEnd = ig.DefineLabel ();
295 EmbeddedStatement.Emit (ec);
296 ig.MarkLabel (ec.LoopBegin);
299 // Dead code elimination
301 if (expr is BoolConstant){
302 bool res = ((BoolConstant) expr).Value;
305 ec.ig.Emit (OpCodes.Br, loop);
307 expr.EmitBranchable (ec, loop, true);
309 ig.MarkLabel (ec.LoopEnd);
311 ec.LoopBegin = old_begin;
312 ec.LoopEnd = old_end;
316 public class While : Statement {
317 public Expression expr;
318 public readonly Statement Statement;
319 bool infinite, empty;
321 public While (Expression boolExpr, Statement statement, Location l)
323 this.expr = boolExpr;
324 Statement = statement;
328 public override bool Resolve (EmitContext ec)
332 expr = Expression.ResolveBoolean (ec, expr, loc);
337 // Inform whether we are infinite or not
339 if (expr is BoolConstant){
340 BoolConstant bc = (BoolConstant) expr;
342 if (bc.Value == false){
343 if (!Statement.ResolveUnreachable (ec, true))
351 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
353 if (!Statement.Resolve (ec))
356 ec.CurrentBranching.Infinite = infinite;
357 ec.EndFlowBranching ();
362 protected override void DoEmit (EmitContext ec)
367 ILGenerator ig = ec.ig;
368 Label old_begin = ec.LoopBegin;
369 Label old_end = ec.LoopEnd;
371 ec.LoopBegin = ig.DefineLabel ();
372 ec.LoopEnd = ig.DefineLabel ();
375 // Inform whether we are infinite or not
377 if (expr is BoolConstant){
378 ig.MarkLabel (ec.LoopBegin);
380 ig.Emit (OpCodes.Br, ec.LoopBegin);
383 // Inform that we are infinite (ie, `we return'), only
384 // if we do not `break' inside the code.
386 ig.MarkLabel (ec.LoopEnd);
388 Label while_loop = ig.DefineLabel ();
390 ig.Emit (OpCodes.Br, ec.LoopBegin);
391 ig.MarkLabel (while_loop);
395 ig.MarkLabel (ec.LoopBegin);
397 expr.EmitBranchable (ec, while_loop, true);
399 ig.MarkLabel (ec.LoopEnd);
402 ec.LoopBegin = old_begin;
403 ec.LoopEnd = old_end;
407 public class For : Statement {
409 readonly Statement InitStatement;
410 readonly Statement Increment;
411 readonly Statement Statement;
412 bool infinite, empty;
414 public For (Statement initStatement,
420 InitStatement = initStatement;
422 Increment = increment;
423 Statement = statement;
427 public override bool Resolve (EmitContext ec)
431 if (InitStatement != null){
432 if (!InitStatement.Resolve (ec))
437 Test = Expression.ResolveBoolean (ec, Test, loc);
440 else if (Test is BoolConstant){
441 BoolConstant bc = (BoolConstant) Test;
443 if (bc.Value == false){
444 if (!Statement.ResolveUnreachable (ec, true))
446 if ((Increment != null) &&
447 !Increment.ResolveUnreachable (ec, false))
457 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
459 ec.CurrentBranching.CreateSibling ();
461 if (!Statement.Resolve (ec))
464 if (Increment != null){
465 if (!Increment.Resolve (ec))
469 ec.CurrentBranching.Infinite = infinite;
470 ec.EndFlowBranching ();
475 protected override void DoEmit (EmitContext ec)
480 ILGenerator ig = ec.ig;
481 Label old_begin = ec.LoopBegin;
482 Label old_end = ec.LoopEnd;
483 Label loop = ig.DefineLabel ();
484 Label test = ig.DefineLabel ();
486 if (InitStatement != null && InitStatement != EmptyStatement.Value)
487 InitStatement.Emit (ec);
489 ec.LoopBegin = ig.DefineLabel ();
490 ec.LoopEnd = ig.DefineLabel ();
492 ig.Emit (OpCodes.Br, test);
496 ig.MarkLabel (ec.LoopBegin);
497 if (Increment != EmptyStatement.Value)
502 // If test is null, there is no test, and we are just
507 // The Resolve code already catches the case for
508 // Test == BoolConstant (false) so we know that
511 if (Test is BoolConstant)
512 ig.Emit (OpCodes.Br, loop);
514 Test.EmitBranchable (ec, loop, true);
517 ig.Emit (OpCodes.Br, loop);
518 ig.MarkLabel (ec.LoopEnd);
520 ec.LoopBegin = old_begin;
521 ec.LoopEnd = old_end;
525 public class StatementExpression : Statement {
526 ExpressionStatement expr;
528 public StatementExpression (ExpressionStatement expr, Location l)
534 public override bool Resolve (EmitContext ec)
537 expr = expr.ResolveStatement (ec);
541 protected override void DoEmit (EmitContext ec)
543 expr.EmitStatement (ec);
546 public override string ToString ()
548 return "StatementExpression (" + expr + ")";
553 /// Implements the return statement
555 public class Return : Statement {
556 public Expression Expr;
558 public Return (Expression expr, Location l)
566 public override bool Resolve (EmitContext ec)
568 if (ec.ReturnType == null){
570 if (ec.CurrentAnonymousMethod != null){
571 Report.Error (1662, loc, String.Format (
572 "Anonymous method could not be converted to delegate " +
573 "since the return value does not match the delegate value"));
575 Error (127, "Return with a value not allowed here");
580 Error (126, "An object of type `{0}' is expected " +
581 "for the return statement",
582 TypeManager.CSharpName (ec.ReturnType));
587 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
588 "statement to return a value, or yield break to end the iteration");
592 Expr = Expr.Resolve (ec);
596 if (Expr.Type != ec.ReturnType) {
597 Expr = Convert.ImplicitConversionRequired (
598 ec, Expr, ec.ReturnType, loc);
605 Error (-206, "Return statement not allowed inside iterators");
609 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
611 if (ec.CurrentBranching.InTryOrCatch (true)) {
612 ec.CurrentBranching.AddFinallyVector (vector);
614 } else if (ec.CurrentBranching.InFinally (true)) {
615 Error (157, "Control can not leave the body of the finally block");
618 vector.CheckOutParameters (ec.CurrentBranching);
621 ec.NeedReturnLabel ();
623 ec.CurrentBranching.CurrentUsageVector.Return ();
627 protected override void DoEmit (EmitContext ec)
633 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
637 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
639 ec.ig.Emit (OpCodes.Ret);
643 public class Goto : Statement {
646 LabeledStatement label;
648 public override bool Resolve (EmitContext ec)
650 label = ec.CurrentBranching.LookupLabel (target, loc);
654 // If this is a forward goto.
655 if (!label.IsDefined)
656 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
658 ec.CurrentBranching.CurrentUsageVector.Goto ();
659 label.AddReference ();
664 public Goto (Block parent_block, string label, Location l)
666 block = parent_block;
671 public string Target {
677 protected override void DoEmit (EmitContext ec)
679 Label l = label.LabelTarget (ec);
680 ec.ig.Emit (OpCodes.Br, l);
684 public class LabeledStatement : Statement {
685 public readonly Location Location;
691 FlowBranching.UsageVector vectors;
693 public LabeledStatement (string label_name, Location l)
698 public Label LabelTarget (EmitContext ec)
703 label = ec.ig.DefineLabel ();
709 public bool IsDefined {
715 public bool HasBeenReferenced {
721 public void AddUsageVector (FlowBranching.UsageVector vector)
723 vector = vector.Clone ();
724 vector.Next = vectors;
728 public override bool Resolve (EmitContext ec)
730 ec.CurrentBranching.Label (vectors);
735 protected override void DoEmit (EmitContext ec)
737 if (ig != null && ig != ec.ig) {
738 Report.Error (1632, "Control cannot leave body of anonymous method");
742 ec.ig.MarkLabel (label);
745 public void AddReference ()
753 /// `goto default' statement
755 public class GotoDefault : Statement {
757 public GotoDefault (Location l)
762 public override bool Resolve (EmitContext ec)
764 ec.CurrentBranching.CurrentUsageVector.Goto ();
768 protected override void DoEmit (EmitContext ec)
770 if (ec.Switch == null){
771 Report.Error (153, loc, "goto default is only valid in a switch statement");
775 if (!ec.Switch.GotDefault){
776 Report.Error (159, loc, "No default target on switch statement");
779 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
784 /// `goto case' statement
786 public class GotoCase : Statement {
790 public GotoCase (Expression e, Location l)
796 public override bool Resolve (EmitContext ec)
798 if (ec.Switch == null){
799 Report.Error (153, loc, "goto case is only valid in a switch statement");
803 expr = expr.Resolve (ec);
807 if (!(expr is Constant)){
808 Report.Error (159, loc, "Target expression for goto case is not constant");
812 object val = Expression.ConvertIntLiteral (
813 (Constant) expr, ec.Switch.SwitchType, loc);
818 sl = (SwitchLabel) ec.Switch.Elements [val];
823 "No such label 'case " + val + "': for the goto case");
827 ec.CurrentBranching.CurrentUsageVector.Goto ();
831 protected override void DoEmit (EmitContext ec)
833 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
837 public class Throw : Statement {
840 public Throw (Expression expr, Location l)
846 public override bool Resolve (EmitContext ec)
848 ec.CurrentBranching.CurrentUsageVector.Throw ();
851 expr = expr.Resolve (ec);
855 ExprClass eclass = expr.eclass;
857 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
858 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
859 expr.Error_UnexpectedKind ("value, variable, property or indexer access ", loc);
865 if ((t != TypeManager.exception_type) &&
866 !t.IsSubclassOf (TypeManager.exception_type) &&
867 !(expr is NullLiteral)) {
869 "The type caught or thrown must be derived " +
870 "from System.Exception");
876 if (ec.CurrentBranching.InFinally (true)) {
877 Error (724, "A throw statement with no argument is only allowed in a catch clause nested inside of the innermost catch clause");
881 if (!ec.CurrentBranching.InCatch ()) {
882 Error (156, "A throw statement with no argument is only allowed in a catch clause");
888 protected override void DoEmit (EmitContext ec)
891 ec.ig.Emit (OpCodes.Rethrow);
895 ec.ig.Emit (OpCodes.Throw);
900 public class Break : Statement {
902 public Break (Location l)
909 public override bool Resolve (EmitContext ec)
911 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
912 Error (139, "No enclosing loop or switch to continue to");
914 } else if (ec.CurrentBranching.InFinally (false)) {
915 Error (157, "Control can not leave the body of the finally block");
917 } else if (ec.CurrentBranching.InTryOrCatch (false))
918 ec.CurrentBranching.AddFinallyVector (
919 ec.CurrentBranching.CurrentUsageVector);
920 else if (ec.CurrentBranching.InLoop ())
921 ec.CurrentBranching.AddBreakVector (
922 ec.CurrentBranching.CurrentUsageVector);
924 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
927 ec.NeedReturnLabel ();
929 ec.CurrentBranching.CurrentUsageVector.Break ();
933 protected override void DoEmit (EmitContext ec)
935 ILGenerator ig = ec.ig;
938 ig.Emit (OpCodes.Leave, ec.LoopEnd);
940 ig.Emit (OpCodes.Br, ec.LoopEnd);
945 public class Continue : Statement {
947 public Continue (Location l)
954 public override bool Resolve (EmitContext ec)
956 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
957 Error (139, "No enclosing loop to continue to");
959 } else if (ec.CurrentBranching.InFinally (false)) {
960 Error (157, "Control can not leave the body of the finally block");
962 } else if (ec.CurrentBranching.InTryOrCatch (false))
963 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
965 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
967 ec.CurrentBranching.CurrentUsageVector.Goto ();
971 protected override void DoEmit (EmitContext ec)
973 Label begin = ec.LoopBegin;
976 ec.ig.Emit (OpCodes.Leave, begin);
978 ec.ig.Emit (OpCodes.Br, begin);
983 // The information about a user-perceived local variable
985 public class LocalInfo {
986 public Expression Type;
989 // Most of the time a variable will be stored in a LocalBuilder
991 // But sometimes, it will be stored in a field (variables that have been
992 // hoisted by iterators or by anonymous methods). The context of the field will
993 // be stored in the EmitContext
996 public LocalBuilder LocalBuilder;
997 public FieldBuilder FieldBuilder;
999 public Type VariableType;
1000 public readonly string Name;
1001 public readonly Location Location;
1002 public readonly Block Block;
1004 public VariableInfo VariableInfo;
1017 public LocalInfo (Expression type, string name, Block block, Location l)
1025 public LocalInfo (TypeContainer tc, Block block, Location l)
1027 VariableType = tc.TypeBuilder;
1032 public bool IsThisAssigned (EmitContext ec, Location loc)
1034 if (VariableInfo == null)
1035 throw new Exception ();
1037 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1040 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1043 public bool IsAssigned (EmitContext ec)
1045 if (VariableInfo == null)
1046 throw new Exception ();
1048 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1051 public bool Resolve (EmitContext ec)
1053 if (VariableType == null) {
1054 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
1058 VariableType = texpr.Type;
1061 if (VariableType == TypeManager.void_type) {
1062 Report.Error (1547, Location,
1063 "Keyword 'void' cannot be used in this context");
1067 if (VariableType.IsAbstract && VariableType.IsSealed) {
1068 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1071 // TODO: breaks the build
1072 // if (VariableType.IsPointer && !ec.InUnsafe)
1073 // Expression.UnsafeError (Location);
1079 // Whether the variable is Fixed (because its Pinned or its a value type)
1081 public bool IsFixed {
1083 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1090 public bool IsCaptured {
1092 return (flags & Flags.Captured) != 0;
1096 flags |= Flags.Captured;
1100 public bool AddressTaken {
1102 return (flags & Flags.AddressTaken) != 0;
1106 flags |= Flags.AddressTaken;
1110 public override string ToString ()
1112 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1113 Name, Type, VariableInfo, Location);
1118 return (flags & Flags.Used) != 0;
1121 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1125 public bool ReadOnly {
1127 return (flags & Flags.ReadOnly) != 0;
1130 flags = value ? (flags | Flags.ReadOnly) : (unchecked (flags & ~Flags.ReadOnly));
1135 // Whether the variable is pinned, if Pinned the variable has been
1136 // allocated in a pinned slot with DeclareLocal.
1138 public bool Pinned {
1140 return (flags & Flags.Pinned) != 0;
1143 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1147 public bool IsThis {
1149 return (flags & Flags.IsThis) != 0;
1152 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1158 /// Block represents a C# block.
1162 /// This class is used in a number of places: either to represent
1163 /// explicit blocks that the programmer places or implicit blocks.
1165 /// Implicit blocks are used as labels or to introduce variable
1168 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1169 /// they contain extra information that is not necessary on normal blocks.
1171 public class Block : Statement {
1172 public Block Parent;
1173 public readonly Location StartLocation;
1174 public Location EndLocation = Location.Null;
1176 public readonly ToplevelBlock Toplevel;
1183 VariablesInitialized = 8,
1192 public bool Implicit {
1194 return (flags & Flags.Implicit) != 0;
1198 public bool Unchecked {
1200 return (flags & Flags.Unchecked) != 0;
1203 flags |= Flags.Unchecked;
1207 public bool Unsafe {
1209 return (flags & Flags.Unsafe) != 0;
1212 flags |= Flags.Unsafe;
1216 public bool HasVarargs {
1219 return Parent.HasVarargs;
1221 return (flags & Flags.HasVarargs) != 0;
1224 flags |= Flags.HasVarargs;
1229 // The statements in this block
1231 ArrayList statements;
1235 // An array of Blocks. We keep track of children just
1236 // to generate the local variable declarations.
1238 // Statements and child statements are handled through the
1244 // Labels. (label, block) pairs.
1249 // Keeps track of (name, type) pairs
1251 Hashtable variables;
1254 // Keeps track of constants
1255 Hashtable constants;
1258 // If this is a switch section, the enclosing switch block.
1262 protected static int id;
1266 public Block (Block parent)
1267 : this (parent, (Flags) 0, Location.Null, Location.Null)
1270 public Block (Block parent, Flags flags)
1271 : this (parent, flags, Location.Null, Location.Null)
1274 public Block (Block parent, Location start, Location end)
1275 : this (parent, (Flags) 0, start, end)
1278 public Block (Block parent, Flags flags, Location start, Location end)
1281 parent.AddChild (this);
1283 this.Parent = parent;
1285 this.StartLocation = start;
1286 this.EndLocation = end;
1289 statements = new ArrayList ();
1291 if ((flags & Flags.IsToplevel) != 0)
1292 Toplevel = (ToplevelBlock) this;
1294 Toplevel = parent.Toplevel;
1296 if (parent != null && Implicit) {
1297 if (parent.known_variables == null)
1298 parent.known_variables = new Hashtable ();
1299 // share with parent
1300 known_variables = parent.known_variables;
1305 public Block CreateSwitchBlock (Location start)
1307 Block new_block = new Block (this, start, start);
1308 new_block.switch_block = this;
1318 void AddChild (Block b)
1320 if (children == null)
1321 children = new ArrayList ();
1326 public void SetEndLocation (Location loc)
1332 /// Adds a label to the current block.
1336 /// false if the name already exists in this block. true
1340 public bool AddLabel (string name, LabeledStatement target, Location loc)
1342 if (switch_block != null)
1343 return switch_block.AddLabel (name, target, loc);
1346 while (cur != null) {
1347 if (cur.DoLookupLabel (name) != null) {
1349 140, loc, "The label '{0}' is a duplicate",
1360 while (cur != null) {
1361 if (cur.DoLookupLabel (name) != null) {
1364 "The label '{0}' shadows another label " +
1365 "by the same name in a containing scope.",
1370 if (children != null) {
1371 foreach (Block b in children) {
1372 LabeledStatement s = b.DoLookupLabel (name);
1378 "The label '{0}' shadows another " +
1379 "label by the same name in a " +
1380 "containing scope.",
1391 labels = new Hashtable ();
1393 labels.Add (name, target);
1397 public LabeledStatement LookupLabel (string name)
1399 LabeledStatement s = DoLookupLabel (name);
1403 if (children == null)
1406 foreach (Block child in children) {
1407 if (!child.Implicit)
1410 s = child.LookupLabel (name);
1418 LabeledStatement DoLookupLabel (string name)
1420 if (switch_block != null)
1421 return switch_block.LookupLabel (name);
1424 if (labels.Contains (name))
1425 return ((LabeledStatement) labels [name]);
1430 LocalInfo this_variable = null;
1433 // Returns the "this" instance variable of this block.
1434 // See AddThisVariable() for more information.
1436 public LocalInfo ThisVariable {
1438 for (Block b = this; b != null; b = b.Parent) {
1439 if (b.this_variable != null)
1440 return b.this_variable;
1447 Hashtable known_variables;
1450 // Marks a variable with name @name as being used in this or a child block.
1451 // If a variable name has been used in a child block, it's illegal to
1452 // declare a variable with the same name in the current block.
1454 void AddKnownVariable (string name, LocalInfo info)
1456 if (known_variables == null)
1457 known_variables = new Hashtable ();
1459 known_variables [name] = info;
1462 public LocalInfo GetKnownVariableInfo (string name)
1464 if (known_variables == null || !known_variables.Contains (name))
1466 return (LocalInfo) known_variables [name];
1470 // Checks whether a variable name has already been used in a child block.
1472 public bool IsVariableNameUsedInChildBlock (string name)
1474 LocalInfo vi = GetKnownVariableInfo (name);
1475 // Cheeky little test that knows that 'known_variables' is shared between
1476 // an implicit block and its enclosing real block.
1477 return vi != null && known_variables != vi.Block.known_variables;
1481 // Checks whether a variable name has already been used in this block, possibly by
1482 // an implicit block.
1484 public bool IsVariableNameUsedInBlock (string name)
1486 LocalInfo vi = GetKnownVariableInfo (name);
1487 return vi != null && known_variables == vi.Block.known_variables;
1491 // This is used by non-static `struct' constructors which do not have an
1492 // initializer - in this case, the constructor must initialize all of the
1493 // struct's fields. To do this, we add a "this" variable and use the flow
1494 // analysis code to ensure that it's been fully initialized before control
1495 // leaves the constructor.
1497 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1499 if (this_variable != null)
1500 return this_variable;
1502 if (variables == null)
1503 variables = new Hashtable ();
1505 this_variable = new LocalInfo (tc, this, l);
1506 this_variable.Used = true;
1507 this_variable.IsThis = true;
1509 variables.Add ("this", this_variable);
1511 return this_variable;
1514 public LocalInfo AddVariable (Expression type, string name, Location l)
1516 if (variables == null)
1517 variables = new Hashtable ();
1520 while (cur != null && cur.Implicit)
1523 LocalInfo vi = GetLocalInfo (name);
1525 Block var = vi.Block;
1526 while (var != null && var.Implicit)
1529 Report.Error (136, l, "A local variable named `" + name + "' " +
1530 "cannot be declared in this scope since it would " +
1531 "give a different meaning to `" + name + "', which " +
1532 "is already used in a `parent or current' scope to " +
1533 "denote something else");
1535 Report.Error (128, l, "A local variable `" + name + "' is already " +
1536 "defined in this scope");
1540 if (IsVariableNameUsedInChildBlock (name)) {
1541 Report.Error (136, l, "A local variable named `" + name + "' " +
1542 "cannot be declared in this scope since it would " +
1543 "give a different meaning to `" + name + "', which " +
1544 "is already used in a `child' scope to denote something " +
1550 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1552 Report.Error (136, l, "A local variable named `" + name + "' " +
1553 "cannot be declared in this scope since it would " +
1554 "give a different meaning to `" + name + "', which " +
1555 "is already used in a `parent or current' scope to " +
1556 "denote something else");
1560 vi = new LocalInfo (type, name, this, l);
1562 variables.Add (name, vi);
1564 for (Block b = cur; b != null; b = b.Parent)
1565 b.AddKnownVariable (name, vi);
1567 if ((flags & Flags.VariablesInitialized) != 0)
1568 throw new Exception ();
1570 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1574 public bool AddConstant (Expression type, string name, Expression value, Location l)
1576 if (AddVariable (type, name, l) == null)
1579 if (constants == null)
1580 constants = new Hashtable ();
1582 constants.Add (name, value);
1586 public Hashtable Variables {
1592 public LocalInfo GetLocalInfo (string name)
1594 for (Block b = this; b != null; b = b.Parent) {
1595 if (b.variables != null) {
1596 LocalInfo ret = b.variables [name] as LocalInfo;
1604 public Expression GetVariableType (string name)
1606 LocalInfo vi = GetLocalInfo (name);
1614 public Expression GetConstantExpression (string name)
1616 for (Block b = this; b != null; b = b.Parent) {
1617 if (b.constants != null) {
1618 Expression ret = b.constants [name] as Expression;
1627 /// True if the variable named @name is a constant
1629 public bool IsConstant (string name)
1631 Expression e = null;
1633 e = GetConstantExpression (name);
1639 // Returns a `ParameterReference' for the given name, or null if there
1640 // is no such parameter
1642 public ParameterReference GetParameterReference (string name, Location loc)
1647 for (Block b = this; b != null; b = b.Toplevel.Parent) {
1648 Parameters pars = b.Toplevel.Parameters;
1649 par = pars.GetParameterByName (name, out idx);
1651 return new ParameterReference (pars, this, idx, name, loc);
1657 // Whether the parameter named `name' is local to this block,
1658 // or false, if the parameter belongs to an encompassing block.
1660 public bool IsLocalParameter (string name)
1662 return Toplevel.Parameters.GetParameterByName (name) != null;
1666 // Whether the `name' is a parameter reference
1668 public bool IsParameterReference (string name)
1673 for (Block b = this; b != null; b = b.Toplevel.Parent) {
1674 par = b.Toplevel.Parameters.GetParameterByName (name, out idx);
1682 /// A list of labels that were not used within this block
1684 public string [] GetUnreferenced ()
1686 // FIXME: Implement me
1690 public void AddStatement (Statement s)
1693 flags |= Flags.BlockUsed;
1698 return (flags & Flags.BlockUsed) != 0;
1704 flags |= Flags.BlockUsed;
1707 public bool HasRet {
1709 return (flags & Flags.HasRet) != 0;
1713 public bool IsDestructor {
1715 return (flags & Flags.IsDestructor) != 0;
1719 public void SetDestructor ()
1721 flags |= Flags.IsDestructor;
1724 VariableMap param_map, local_map;
1726 public VariableMap ParameterMap {
1728 if ((flags & Flags.VariablesInitialized) == 0)
1729 throw new Exception ("Variables have not been initialized yet");
1735 public VariableMap LocalMap {
1737 if ((flags & Flags.VariablesInitialized) == 0)
1738 throw new Exception ("Variables have not been initialized yet");
1745 /// Emits the variable declarations and labels.
1748 /// tc: is our typecontainer (to resolve type references)
1749 /// ig: is the code generator:
1751 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1753 bool old_unsafe = ec.InUnsafe;
1755 // If some parent block was unsafe, we remain unsafe even if this block
1756 // isn't explicitly marked as such.
1757 ec.InUnsafe |= Unsafe;
1760 // Compute the VariableMap's.
1762 // Unfortunately, we don't know the type when adding variables with
1763 // AddVariable(), so we need to compute this info here.
1767 if (variables != null) {
1768 foreach (LocalInfo li in variables.Values)
1771 locals = new LocalInfo [variables.Count];
1772 variables.Values.CopyTo (locals, 0);
1774 locals = new LocalInfo [0];
1777 local_map = new VariableMap (Parent.LocalMap, locals);
1779 local_map = new VariableMap (locals);
1781 param_map = new VariableMap (ip);
1782 flags |= Flags.VariablesInitialized;
1784 bool old_check_state = ec.ConstantCheckState;
1785 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1788 // Process this block variables
1790 if (variables != null){
1791 foreach (DictionaryEntry de in variables){
1792 string name = (string) de.Key;
1793 LocalInfo vi = (LocalInfo) de.Value;
1795 if (vi.VariableType == null)
1798 Type variable_type = vi.VariableType;
1800 if (variable_type.IsPointer){
1802 // Am not really convinced that this test is required (Microsoft does it)
1803 // but the fact is that you would not be able to use the pointer variable
1806 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1813 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1816 // This is needed to compile on both .NET 1.x and .NET 2.x
1817 // the later introduced `DeclareLocal (Type t, bool pinned)'
1819 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1820 else if (!vi.IsThis)
1821 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1824 if (constants == null)
1827 Expression cv = (Expression) constants [name];
1831 ec.CurrentBlock = this;
1832 Expression e = cv.Resolve (ec);
1836 Constant ce = e as Constant;
1838 Report.Error (133, vi.Location,
1839 "The expression being assigned to `" +
1840 name + "' must be constant (" + e + ")");
1844 if (e.Type != variable_type){
1845 e = Const.ChangeType (vi.Location, ce, variable_type);
1850 constants.Remove (name);
1851 constants.Add (name, e);
1854 ec.ConstantCheckState = old_check_state;
1857 // Now, handle the children
1859 if (children != null){
1860 foreach (Block b in children)
1861 b.ResolveMeta (toplevel, ec, ip);
1863 ec.InUnsafe = old_unsafe;
1867 // Emits the local variable declarations for a block
1869 public void EmitMeta (EmitContext ec)
1871 ILGenerator ig = ec.ig;
1873 if (variables != null){
1874 bool have_captured_vars = ec.HaveCapturedVariables ();
1875 bool remap_locals = ec.RemapToProxy;
1877 foreach (DictionaryEntry de in variables){
1878 LocalInfo vi = (LocalInfo) de.Value;
1880 if (have_captured_vars && ec.IsCaptured (vi))
1884 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1888 // This is needed to compile on both .NET 1.x and .NET 2.x
1889 // the later introduced `DeclareLocal (Type t, bool pinned)'
1891 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1892 else if (!vi.IsThis)
1893 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1898 if (children != null){
1899 foreach (Block b in children)
1904 void UsageWarning (FlowBranching.UsageVector vector)
1908 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1909 foreach (DictionaryEntry de in variables){
1910 LocalInfo vi = (LocalInfo) de.Value;
1915 name = (string) de.Key;
1917 if (vector.IsAssigned (vi.VariableInfo)){
1918 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1920 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1926 bool unreachable_shown;
1928 public override bool Resolve (EmitContext ec)
1930 Block prev_block = ec.CurrentBlock;
1933 int errors = Report.Errors;
1935 ec.CurrentBlock = this;
1936 ec.StartFlowBranching (this);
1938 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1940 bool unreachable = unreachable_shown;
1942 int statement_count = statements.Count;
1943 for (int ix = 0; ix < statement_count; ix++){
1944 Statement s = (Statement) statements [ix];
1946 if (unreachable && !(s is LabeledStatement)) {
1947 if (s == EmptyStatement.Value)
1948 s.loc = EndLocation;
1950 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1953 if (s != EmptyStatement.Value)
1954 unreachable_shown = true;
1956 s.loc = Location.Null;
1958 if (ok && !(s is Block)) {
1959 statements [ix] = EmptyStatement.Value;
1964 if (s.Resolve (ec) == false) {
1966 statements [ix] = EmptyStatement.Value;
1970 num_statements = ix + 1;
1972 if (s is LabeledStatement)
1973 unreachable = false;
1975 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1978 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1979 ec.CurrentBranching, statement_count, num_statements);
1982 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1984 ec.CurrentBlock = prev_block;
1986 // If we're a non-static `struct' constructor which doesn't have an
1987 // initializer, then we must initialize all of the struct's fields.
1988 if ((this_variable != null) &&
1989 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1990 !this_variable.IsThisAssigned (ec, loc))
1993 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1994 foreach (LabeledStatement label in labels.Values)
1995 if (!label.HasBeenReferenced)
1996 Report.Warning (164, label.Location,
1997 "This label has not been referenced");
2000 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2002 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2003 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2004 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2005 flags |= Flags.HasRet;
2007 if (ok && (errors == Report.Errors)) {
2008 if (RootContext.WarningLevel >= 3)
2009 UsageWarning (vector);
2015 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2017 unreachable_shown = true;
2019 if (warn && (RootContext.WarningLevel >= 2))
2020 Report.Warning (162, loc, "Unreachable code detected");
2023 return Resolve (ec);
2025 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2026 bool ok = Resolve (ec);
2027 ec.KillFlowBranching ();
2032 protected override void DoEmit (EmitContext ec)
2034 for (int ix = 0; ix < num_statements; ix++){
2035 Statement s = (Statement) statements [ix];
2037 // Check whether we are the last statement in a
2040 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2041 ec.IsLastStatement = true;
2043 ec.IsLastStatement = false;
2049 public override void Emit (EmitContext ec)
2051 Block prev_block = ec.CurrentBlock;
2053 ec.CurrentBlock = this;
2055 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2056 bool is_lexical_block = !Implicit && (Parent != null);
2058 if (emit_debug_info) {
2059 if (is_lexical_block)
2062 if (variables != null) {
2063 foreach (DictionaryEntry de in variables) {
2064 string name = (string) de.Key;
2065 LocalInfo vi = (LocalInfo) de.Value;
2067 if (vi.LocalBuilder == null)
2070 ec.DefineLocalVariable (name, vi.LocalBuilder);
2075 ec.Mark (StartLocation, true);
2077 ec.Mark (EndLocation, true);
2079 if (emit_debug_info && is_lexical_block)
2082 ec.CurrentBlock = prev_block;
2086 // Returns true if we ar ea child of `b'.
2088 public bool IsChildOf (Block b)
2090 Block current = this;
2093 if (current.Parent == b)
2095 current = current.Parent;
2096 } while (current != null);
2102 // A toplevel block contains extra information, the split is done
2103 // only to separate information that would otherwise bloat the more
2104 // lightweight Block.
2106 // In particular, this was introduced when the support for Anonymous
2107 // Methods was implemented.
2109 public class ToplevelBlock : Block {
2111 // Pointer to the host of this anonymous method, or null
2112 // if we are the topmost block
2114 public ToplevelBlock Container;
2115 CaptureContext capture_context;
2117 Hashtable capture_contexts;
2122 // The parameters for the block.
2124 public readonly Parameters Parameters;
2126 public void RegisterCaptureContext (CaptureContext cc)
2128 if (capture_contexts == null)
2129 capture_contexts = new Hashtable ();
2130 capture_contexts [cc] = cc;
2133 public void CompleteContexts ()
2135 if (capture_contexts == null)
2138 foreach (CaptureContext cc in capture_contexts.Keys){
2143 public CaptureContext ToplevelBlockCaptureContext {
2145 return capture_context;
2150 // Parent is only used by anonymous blocks to link back to their
2153 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2154 this (container, (Flags) 0, parameters, start)
2158 public ToplevelBlock (Parameters parameters, Location start) :
2159 this (null, (Flags) 0, parameters, start)
2163 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2164 this (null, flags, parameters, start)
2168 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2169 base (null, flags | Flags.IsToplevel, start, Location.Null)
2171 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2172 Container = container;
2175 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2179 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2181 if (capture_context == null)
2182 capture_context = new CaptureContext (this, loc, host);
2185 public CaptureContext CaptureContext {
2187 return capture_context;
2192 public class SwitchLabel {
2195 public Location loc;
2199 Label il_label_code;
2200 bool il_label_code_set;
2203 // if expr == null, then it is the default case.
2205 public SwitchLabel (Expression expr, Location l)
2211 public Expression Label {
2217 public object Converted {
2223 public Label GetILLabel (EmitContext ec)
2226 il_label = ec.ig.DefineLabel ();
2227 il_label_set = true;
2232 public Label GetILLabelCode (EmitContext ec)
2234 if (!il_label_code_set){
2235 il_label_code = ec.ig.DefineLabel ();
2236 il_label_code_set = true;
2238 return il_label_code;
2242 // Resolves the expression, reduces it to a literal if possible
2243 // and then converts it to the requested type.
2245 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2250 Expression e = label.Resolve (ec);
2255 if (!(e is Constant)){
2256 Report.Error (150, loc, "A constant value is expected, got: " + e);
2260 if (e is StringConstant || e is NullLiteral){
2261 if (required_type == TypeManager.string_type){
2267 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2268 if (converted == null)
2275 public class SwitchSection {
2276 // An array of SwitchLabels.
2277 public readonly ArrayList Labels;
2278 public readonly Block Block;
2280 public SwitchSection (ArrayList labels, Block block)
2287 public class Switch : Statement {
2288 public readonly ArrayList Sections;
2289 public Expression Expr;
2292 /// Maps constants whose type type SwitchType to their SwitchLabels.
2294 public Hashtable Elements;
2297 /// The governing switch type
2299 public Type SwitchType;
2305 Label default_target;
2306 Expression new_expr;
2308 SwitchSection constant_section;
2311 // The types allowed to be implicitly cast from
2312 // on the governing type
2314 static Type [] allowed_types;
2316 public Switch (Expression e, ArrayList sects, Location l)
2323 public bool GotDefault {
2329 public Label DefaultTarget {
2331 return default_target;
2336 // Determines the governing type for a switch. The returned
2337 // expression might be the expression from the switch, or an
2338 // expression that includes any potential conversions to the
2339 // integral types or to string.
2341 Expression SwitchGoverningType (EmitContext ec, Type t)
2343 if (t == TypeManager.int32_type ||
2344 t == TypeManager.uint32_type ||
2345 t == TypeManager.char_type ||
2346 t == TypeManager.byte_type ||
2347 t == TypeManager.sbyte_type ||
2348 t == TypeManager.ushort_type ||
2349 t == TypeManager.short_type ||
2350 t == TypeManager.uint64_type ||
2351 t == TypeManager.int64_type ||
2352 t == TypeManager.string_type ||
2353 t == TypeManager.bool_type ||
2354 t.IsSubclassOf (TypeManager.enum_type))
2357 if (allowed_types == null){
2358 allowed_types = new Type [] {
2359 TypeManager.int32_type,
2360 TypeManager.uint32_type,
2361 TypeManager.sbyte_type,
2362 TypeManager.byte_type,
2363 TypeManager.short_type,
2364 TypeManager.ushort_type,
2365 TypeManager.int64_type,
2366 TypeManager.uint64_type,
2367 TypeManager.char_type,
2368 TypeManager.bool_type,
2369 TypeManager.string_type
2374 // Try to find a *user* defined implicit conversion.
2376 // If there is no implicit conversion, or if there are multiple
2377 // conversions, we have to report an error
2379 Expression converted = null;
2380 foreach (Type tt in allowed_types){
2383 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2388 // Ignore over-worked ImplicitUserConversions that do
2389 // an implicit conversion in addition to the user conversion.
2392 UserCast ue = e as UserCast;
2394 if (ue.Source != Expr)
2398 if (converted != null){
2399 Report.ExtraInformation (
2401 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2402 TypeManager.CSharpName (Expr.Type)));
2411 static string Error152 {
2413 return "The label '{0}:' already occurs in this switch statement";
2418 // Performs the basic sanity checks on the switch statement
2419 // (looks for duplicate keys and non-constant expressions).
2421 // It also returns a hashtable with the keys that we will later
2422 // use to compute the switch tables
2424 bool CheckSwitch (EmitContext ec)
2428 Elements = new Hashtable ();
2430 got_default = false;
2432 if (TypeManager.IsEnumType (SwitchType)){
2433 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2435 compare_type = SwitchType;
2437 foreach (SwitchSection ss in Sections){
2438 foreach (SwitchLabel sl in ss.Labels){
2439 if (!sl.ResolveAndReduce (ec, SwitchType)){
2444 if (sl.Label == null){
2446 Report.Error (152, sl.loc, Error152, "default");
2453 object key = sl.Converted;
2455 if (key is Constant)
2456 key = ((Constant) key).GetValue ();
2459 key = NullLiteral.Null;
2461 string lname = null;
2462 if (compare_type == TypeManager.uint64_type){
2463 ulong v = (ulong) key;
2465 if (Elements.Contains (v))
2466 lname = v.ToString ();
2468 Elements.Add (v, sl);
2469 } else if (compare_type == TypeManager.int64_type){
2470 long v = (long) key;
2472 if (Elements.Contains (v))
2473 lname = v.ToString ();
2475 Elements.Add (v, sl);
2476 } else if (compare_type == TypeManager.uint32_type){
2477 uint v = (uint) key;
2479 if (Elements.Contains (v))
2480 lname = v.ToString ();
2482 Elements.Add (v, sl);
2483 } else if (compare_type == TypeManager.char_type){
2484 char v = (char) key;
2486 if (Elements.Contains (v))
2487 lname = v.ToString ();
2489 Elements.Add (v, sl);
2490 } else if (compare_type == TypeManager.byte_type){
2491 byte v = (byte) key;
2493 if (Elements.Contains (v))
2494 lname = v.ToString ();
2496 Elements.Add (v, sl);
2497 } else if (compare_type == TypeManager.sbyte_type){
2498 sbyte v = (sbyte) key;
2500 if (Elements.Contains (v))
2501 lname = v.ToString ();
2503 Elements.Add (v, sl);
2504 } else if (compare_type == TypeManager.short_type){
2505 short v = (short) key;
2507 if (Elements.Contains (v))
2508 lname = v.ToString ();
2510 Elements.Add (v, sl);
2511 } else if (compare_type == TypeManager.ushort_type){
2512 ushort v = (ushort) key;
2514 if (Elements.Contains (v))
2515 lname = v.ToString ();
2517 Elements.Add (v, sl);
2518 } else if (compare_type == TypeManager.string_type){
2519 if (key is NullLiteral){
2520 if (Elements.Contains (NullLiteral.Null))
2523 Elements.Add (NullLiteral.Null, null);
2525 string s = (string) key;
2527 if (Elements.Contains (s))
2530 Elements.Add (s, sl);
2532 } else if (compare_type == TypeManager.int32_type) {
2535 if (Elements.Contains (v))
2536 lname = v.ToString ();
2538 Elements.Add (v, sl);
2539 } else if (compare_type == TypeManager.bool_type) {
2540 bool v = (bool) key;
2542 if (Elements.Contains (v))
2543 lname = v.ToString ();
2545 Elements.Add (v, sl);
2549 throw new Exception ("Unknown switch type!" +
2550 SwitchType + " " + compare_type);
2554 Report.Error (152, sl.loc, Error152, "case " + lname);
2565 void EmitObjectInteger (ILGenerator ig, object k)
2568 IntConstant.EmitInt (ig, (int) k);
2569 else if (k is Constant) {
2570 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2573 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2576 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2578 IntConstant.EmitInt (ig, (int) (long) k);
2579 ig.Emit (OpCodes.Conv_I8);
2582 LongConstant.EmitLong (ig, (long) k);
2584 else if (k is ulong)
2586 if ((ulong) k < (1L<<32))
2588 IntConstant.EmitInt (ig, (int) (long) k);
2589 ig.Emit (OpCodes.Conv_U8);
2593 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2597 IntConstant.EmitInt (ig, (int) ((char) k));
2598 else if (k is sbyte)
2599 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2601 IntConstant.EmitInt (ig, (int) ((byte) k));
2602 else if (k is short)
2603 IntConstant.EmitInt (ig, (int) ((short) k));
2604 else if (k is ushort)
2605 IntConstant.EmitInt (ig, (int) ((ushort) k));
2607 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2609 throw new Exception ("Unhandled case");
2612 // structure used to hold blocks of keys while calculating table switch
2613 class KeyBlock : IComparable
2615 public KeyBlock (long _nFirst)
2617 nFirst = nLast = _nFirst;
2621 public ArrayList rgKeys = null;
2622 // how many items are in the bucket
2623 public int Size = 1;
2626 get { return (int) (nLast - nFirst + 1); }
2628 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2630 return kbLast.nLast - kbFirst.nFirst + 1;
2632 public int CompareTo (object obj)
2634 KeyBlock kb = (KeyBlock) obj;
2635 int nLength = Length;
2636 int nLengthOther = kb.Length;
2637 if (nLengthOther == nLength)
2638 return (int) (kb.nFirst - nFirst);
2639 return nLength - nLengthOther;
2644 /// This method emits code for a lookup-based switch statement (non-string)
2645 /// Basically it groups the cases into blocks that are at least half full,
2646 /// and then spits out individual lookup opcodes for each block.
2647 /// It emits the longest blocks first, and short blocks are just
2648 /// handled with direct compares.
2650 /// <param name="ec"></param>
2651 /// <param name="val"></param>
2652 /// <returns></returns>
2653 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2655 int cElements = Elements.Count;
2656 object [] rgKeys = new object [cElements];
2657 Elements.Keys.CopyTo (rgKeys, 0);
2658 Array.Sort (rgKeys);
2660 // initialize the block list with one element per key
2661 ArrayList rgKeyBlocks = new ArrayList ();
2662 foreach (object key in rgKeys)
2663 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2666 // iteratively merge the blocks while they are at least half full
2667 // there's probably a really cool way to do this with a tree...
2668 while (rgKeyBlocks.Count > 1)
2670 ArrayList rgKeyBlocksNew = new ArrayList ();
2671 kbCurr = (KeyBlock) rgKeyBlocks [0];
2672 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2674 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2675 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2678 kbCurr.nLast = kb.nLast;
2679 kbCurr.Size += kb.Size;
2683 // start a new block
2684 rgKeyBlocksNew.Add (kbCurr);
2688 rgKeyBlocksNew.Add (kbCurr);
2689 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2691 rgKeyBlocks = rgKeyBlocksNew;
2694 // initialize the key lists
2695 foreach (KeyBlock kb in rgKeyBlocks)
2696 kb.rgKeys = new ArrayList ();
2698 // fill the key lists
2700 if (rgKeyBlocks.Count > 0) {
2701 kbCurr = (KeyBlock) rgKeyBlocks [0];
2702 foreach (object key in rgKeys)
2704 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2705 System.Convert.ToInt64 (key) > kbCurr.nLast;
2707 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2708 kbCurr.rgKeys.Add (key);
2712 // sort the blocks so we can tackle the largest ones first
2713 rgKeyBlocks.Sort ();
2715 // okay now we can start...
2716 ILGenerator ig = ec.ig;
2717 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2718 Label lblDefault = ig.DefineLabel ();
2720 Type typeKeys = null;
2721 if (rgKeys.Length > 0)
2722 typeKeys = rgKeys [0].GetType (); // used for conversions
2726 if (TypeManager.IsEnumType (SwitchType))
2727 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2729 compare_type = SwitchType;
2731 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2733 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2734 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2737 foreach (object key in kb.rgKeys)
2739 ig.Emit (OpCodes.Ldloc, val);
2740 EmitObjectInteger (ig, key);
2741 SwitchLabel sl = (SwitchLabel) Elements [key];
2742 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2747 // TODO: if all the keys in the block are the same and there are
2748 // no gaps/defaults then just use a range-check.
2749 if (compare_type == TypeManager.int64_type ||
2750 compare_type == TypeManager.uint64_type)
2752 // TODO: optimize constant/I4 cases
2754 // check block range (could be > 2^31)
2755 ig.Emit (OpCodes.Ldloc, val);
2756 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2757 ig.Emit (OpCodes.Blt, lblDefault);
2758 ig.Emit (OpCodes.Ldloc, val);
2759 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2760 ig.Emit (OpCodes.Bgt, lblDefault);
2763 ig.Emit (OpCodes.Ldloc, val);
2766 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2767 ig.Emit (OpCodes.Sub);
2769 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2774 ig.Emit (OpCodes.Ldloc, val);
2775 int nFirst = (int) kb.nFirst;
2778 IntConstant.EmitInt (ig, nFirst);
2779 ig.Emit (OpCodes.Sub);
2781 else if (nFirst < 0)
2783 IntConstant.EmitInt (ig, -nFirst);
2784 ig.Emit (OpCodes.Add);
2788 // first, build the list of labels for the switch
2790 int cJumps = kb.Length;
2791 Label [] rgLabels = new Label [cJumps];
2792 for (int iJump = 0; iJump < cJumps; iJump++)
2794 object key = kb.rgKeys [iKey];
2795 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2797 SwitchLabel sl = (SwitchLabel) Elements [key];
2798 rgLabels [iJump] = sl.GetILLabel (ec);
2802 rgLabels [iJump] = lblDefault;
2804 // emit the switch opcode
2805 ig.Emit (OpCodes.Switch, rgLabels);
2808 // mark the default for this block
2810 ig.MarkLabel (lblDefault);
2813 // TODO: find the default case and emit it here,
2814 // to prevent having to do the following jump.
2815 // make sure to mark other labels in the default section
2817 // the last default just goes to the end
2818 ig.Emit (OpCodes.Br, lblDefault);
2820 // now emit the code for the sections
2821 bool fFoundDefault = false;
2822 foreach (SwitchSection ss in Sections)
2824 foreach (SwitchLabel sl in ss.Labels)
2826 ig.MarkLabel (sl.GetILLabel (ec));
2827 ig.MarkLabel (sl.GetILLabelCode (ec));
2828 if (sl.Label == null)
2830 ig.MarkLabel (lblDefault);
2831 fFoundDefault = true;
2835 //ig.Emit (OpCodes.Br, lblEnd);
2838 if (!fFoundDefault) {
2839 ig.MarkLabel (lblDefault);
2841 ig.MarkLabel (lblEnd);
2844 // This simple emit switch works, but does not take advantage of the
2846 // TODO: remove non-string logic from here
2847 // TODO: binary search strings?
2849 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2851 ILGenerator ig = ec.ig;
2852 Label end_of_switch = ig.DefineLabel ();
2853 Label next_test = ig.DefineLabel ();
2854 Label null_target = ig.DefineLabel ();
2855 bool default_found = false;
2856 bool first_test = true;
2857 bool pending_goto_end = false;
2859 bool default_at_end = false;
2861 ig.Emit (OpCodes.Ldloc, val);
2863 if (Elements.Contains (NullLiteral.Null)){
2864 ig.Emit (OpCodes.Brfalse, null_target);
2866 ig.Emit (OpCodes.Brfalse, default_target);
2868 ig.Emit (OpCodes.Ldloc, val);
2869 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2870 ig.Emit (OpCodes.Stloc, val);
2872 int section_count = Sections.Count;
2873 for (int section = 0; section < section_count; section++){
2874 SwitchSection ss = (SwitchSection) Sections [section];
2875 Label sec_begin = ig.DefineLabel ();
2877 if (pending_goto_end)
2878 ig.Emit (OpCodes.Br, end_of_switch);
2880 int label_count = ss.Labels.Count;
2881 bool mark_default = false;
2883 for (int label = 0; label < label_count; label++){
2884 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2885 ig.MarkLabel (sl.GetILLabel (ec));
2888 ig.MarkLabel (next_test);
2889 next_test = ig.DefineLabel ();
2892 // If we are the default target
2894 if (sl.Label == null){
2895 if (label+1 == label_count)
2896 default_at_end = true;
2897 mark_default = true;
2898 default_found = true;
2900 object lit = sl.Converted;
2902 if (lit is NullLiteral){
2904 if (label_count == 1)
2905 ig.Emit (OpCodes.Br, next_test);
2909 StringConstant str = (StringConstant) lit;
2911 ig.Emit (OpCodes.Ldloc, val);
2912 ig.Emit (OpCodes.Ldstr, str.Value);
2913 if (label_count == 1)
2914 ig.Emit (OpCodes.Bne_Un, next_test);
2916 if (label+1 == label_count)
2917 ig.Emit (OpCodes.Bne_Un, next_test);
2919 ig.Emit (OpCodes.Beq, sec_begin);
2924 ig.MarkLabel (null_target);
2925 ig.MarkLabel (sec_begin);
2926 foreach (SwitchLabel sl in ss.Labels)
2927 ig.MarkLabel (sl.GetILLabelCode (ec));
2930 ig.MarkLabel (default_target);
2932 pending_goto_end = !ss.Block.HasRet;
2935 ig.MarkLabel (next_test);
2937 if (!default_at_end)
2938 ig.Emit (OpCodes.Br, default_target);
2940 ig.MarkLabel (default_target);
2941 ig.MarkLabel (end_of_switch);
2944 SwitchSection FindSection (SwitchLabel label)
2946 foreach (SwitchSection ss in Sections){
2947 foreach (SwitchLabel sl in ss.Labels){
2956 bool ResolveConstantSwitch (EmitContext ec)
2958 object key = ((Constant) new_expr).GetValue ();
2959 SwitchLabel label = (SwitchLabel) Elements [key];
2964 constant_section = FindSection (label);
2965 if (constant_section == null)
2968 if (constant_section.Block.Resolve (ec) != true)
2974 public override bool Resolve (EmitContext ec)
2976 Expr = Expr.Resolve (ec);
2980 new_expr = SwitchGoverningType (ec, Expr.Type);
2981 if (new_expr == null){
2982 Report.Error (151, loc, "An integer type or string was expected for switch");
2987 SwitchType = new_expr.Type;
2989 if (!CheckSwitch (ec))
2992 Switch old_switch = ec.Switch;
2994 ec.Switch.SwitchType = SwitchType;
2996 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2997 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2999 is_constant = new_expr is Constant;
3001 object key = ((Constant) new_expr).GetValue ();
3002 SwitchLabel label = (SwitchLabel) Elements [key];
3004 constant_section = FindSection (label);
3008 foreach (SwitchSection ss in Sections){
3010 ec.CurrentBranching.CreateSibling (
3011 null, FlowBranching.SiblingType.SwitchSection);
3015 if (is_constant && (ss != constant_section)) {
3016 // If we're a constant switch, we're only emitting
3017 // one single section - mark all the others as
3019 ec.CurrentBranching.CurrentUsageVector.Goto ();
3020 if (!ss.Block.ResolveUnreachable (ec, true))
3023 if (!ss.Block.Resolve (ec))
3029 ec.CurrentBranching.CreateSibling (
3030 null, FlowBranching.SiblingType.SwitchSection);
3032 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3033 ec.Switch = old_switch;
3035 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3041 protected override void DoEmit (EmitContext ec)
3043 ILGenerator ig = ec.ig;
3045 // Store variable for comparission purposes
3048 value = ig.DeclareLocal (SwitchType);
3050 ig.Emit (OpCodes.Stloc, value);
3054 default_target = ig.DefineLabel ();
3057 // Setup the codegen context
3059 Label old_end = ec.LoopEnd;
3060 Switch old_switch = ec.Switch;
3062 ec.LoopEnd = ig.DefineLabel ();
3067 if (constant_section != null)
3068 constant_section.Block.Emit (ec);
3069 } else if (SwitchType == TypeManager.string_type)
3070 SimpleSwitchEmit (ec, value);
3072 TableSwitchEmit (ec, value);
3074 // Restore context state.
3075 ig.MarkLabel (ec.LoopEnd);
3078 // Restore the previous context
3080 ec.LoopEnd = old_end;
3081 ec.Switch = old_switch;
3085 public abstract class ExceptionStatement : Statement
3087 public abstract void EmitFinally (EmitContext ec);
3089 protected bool emit_finally = true;
3090 ArrayList parent_vectors;
3092 protected void DoEmitFinally (EmitContext ec)
3095 ec.ig.BeginFinallyBlock ();
3097 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3101 protected void ResolveFinally (FlowBranchingException branching)
3103 emit_finally = branching.EmitFinally;
3105 branching.Parent.StealFinallyClauses (ref parent_vectors);
3109 public class Lock : ExceptionStatement {
3111 Statement Statement;
3114 public Lock (Expression expr, Statement stmt, Location l)
3121 public override bool Resolve (EmitContext ec)
3123 expr = expr.Resolve (ec);
3127 if (expr.Type.IsValueType){
3128 Error (185, "lock statement requires the expression to be " +
3129 " a reference type (type is: `{0}'",
3130 TypeManager.CSharpName (expr.Type));
3134 FlowBranchingException branching = ec.StartFlowBranching (this);
3135 bool ok = Statement.Resolve (ec);
3137 ec.KillFlowBranching ();
3141 ResolveFinally (branching);
3143 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3144 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3145 // Unfortunately, System.Reflection.Emit automatically emits
3146 // a leave to the end of the finally block.
3147 // This is a problem if `returns' is true since we may jump
3148 // to a point after the end of the method.
3149 // As a workaround, emit an explicit ret here.
3150 ec.NeedReturnLabel ();
3156 protected override void DoEmit (EmitContext ec)
3158 Type type = expr.Type;
3160 ILGenerator ig = ec.ig;
3161 temp = ig.DeclareLocal (type);
3164 ig.Emit (OpCodes.Dup);
3165 ig.Emit (OpCodes.Stloc, temp);
3166 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3170 ig.BeginExceptionBlock ();
3171 Statement.Emit (ec);
3176 ig.EndExceptionBlock ();
3179 public override void EmitFinally (EmitContext ec)
3181 ILGenerator ig = ec.ig;
3182 ig.Emit (OpCodes.Ldloc, temp);
3183 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3187 public class Unchecked : Statement {
3188 public readonly Block Block;
3190 public Unchecked (Block b)
3196 public override bool Resolve (EmitContext ec)
3198 bool previous_state = ec.CheckState;
3199 bool previous_state_const = ec.ConstantCheckState;
3201 ec.CheckState = false;
3202 ec.ConstantCheckState = false;
3203 bool ret = Block.Resolve (ec);
3204 ec.CheckState = previous_state;
3205 ec.ConstantCheckState = previous_state_const;
3210 protected override void DoEmit (EmitContext ec)
3212 bool previous_state = ec.CheckState;
3213 bool previous_state_const = ec.ConstantCheckState;
3215 ec.CheckState = false;
3216 ec.ConstantCheckState = false;
3218 ec.CheckState = previous_state;
3219 ec.ConstantCheckState = previous_state_const;
3223 public class Checked : Statement {
3224 public readonly Block Block;
3226 public Checked (Block b)
3229 b.Unchecked = false;
3232 public override bool Resolve (EmitContext ec)
3234 bool previous_state = ec.CheckState;
3235 bool previous_state_const = ec.ConstantCheckState;
3237 ec.CheckState = true;
3238 ec.ConstantCheckState = true;
3239 bool ret = Block.Resolve (ec);
3240 ec.CheckState = previous_state;
3241 ec.ConstantCheckState = previous_state_const;
3246 protected override void DoEmit (EmitContext ec)
3248 bool previous_state = ec.CheckState;
3249 bool previous_state_const = ec.ConstantCheckState;
3251 ec.CheckState = true;
3252 ec.ConstantCheckState = true;
3254 ec.CheckState = previous_state;
3255 ec.ConstantCheckState = previous_state_const;
3259 public class Unsafe : Statement {
3260 public readonly Block Block;
3262 public Unsafe (Block b)
3265 Block.Unsafe = true;
3268 public override bool Resolve (EmitContext ec)
3270 bool previous_state = ec.InUnsafe;
3274 val = Block.Resolve (ec);
3275 ec.InUnsafe = previous_state;
3280 protected override void DoEmit (EmitContext ec)
3282 bool previous_state = ec.InUnsafe;
3286 ec.InUnsafe = previous_state;
3293 public class Fixed : Statement {
3295 ArrayList declarators;
3296 Statement statement;
3301 abstract class Emitter
3303 protected LocalInfo vi;
3304 protected Expression converted;
3306 protected Emitter (Expression expr, LocalInfo li)
3312 public abstract void Emit (EmitContext ec);
3313 public abstract void EmitExit (ILGenerator ig);
3316 class ExpressionEmitter: Emitter {
3317 public ExpressionEmitter (Expression converted, LocalInfo li) :
3318 base (converted, li)
3322 public override void Emit (EmitContext ec) {
3324 // Store pointer in pinned location
3326 converted.Emit (ec);
3327 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3330 public override void EmitExit (ILGenerator ig)
3332 ig.Emit (OpCodes.Ldc_I4_0);
3333 ig.Emit (OpCodes.Conv_U);
3334 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3338 class StringEmitter: Emitter {
3339 LocalBuilder pinned_string;
3342 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3348 public override void Emit (EmitContext ec)
3350 ILGenerator ig = ec.ig;
3351 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3353 converted.Emit (ec);
3354 ig.Emit (OpCodes.Stloc, pinned_string);
3356 Expression sptr = new StringPtr (pinned_string, loc);
3357 converted = Convert.ImplicitConversionRequired (
3358 ec, sptr, vi.VariableType, loc);
3360 if (converted == null)
3363 converted.Emit (ec);
3364 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3367 public override void EmitExit(ILGenerator ig)
3369 ig.Emit (OpCodes.Ldnull);
3370 ig.Emit (OpCodes.Stloc, pinned_string);
3374 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3377 declarators = decls;
3382 public override bool Resolve (EmitContext ec)
3385 Expression.UnsafeError (loc);
3389 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3393 expr_type = texpr.Type;
3395 CheckObsolete (expr_type);
3397 if (ec.RemapToProxy){
3398 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3402 data = new Emitter [declarators.Count];
3404 if (!expr_type.IsPointer){
3405 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3410 foreach (Pair p in declarators){
3411 LocalInfo vi = (LocalInfo) p.First;
3412 Expression e = (Expression) p.Second;
3414 vi.VariableInfo.SetAssigned (ec);
3418 // The rules for the possible declarators are pretty wise,
3419 // but the production on the grammar is more concise.
3421 // So we have to enforce these rules here.
3423 // We do not resolve before doing the case 1 test,
3424 // because the grammar is explicit in that the token &
3425 // is present, so we need to test for this particular case.
3429 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3434 // Case 1: & object.
3436 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3437 Expression child = ((Unary) e).Expr;
3439 if (child is ParameterReference || child is LocalVariableReference){
3442 "No need to use fixed statement for parameters or " +
3443 "local variable declarations (address is already " +
3448 ec.InFixedInitializer = true;
3450 ec.InFixedInitializer = false;
3454 child = ((Unary) e).Expr;
3456 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3459 data [i] = new ExpressionEmitter (e, vi);
3465 ec.InFixedInitializer = true;
3467 ec.InFixedInitializer = false;
3474 if (e.Type.IsArray){
3475 Type array_type = TypeManager.GetElementType (e.Type);
3478 // Provided that array_type is unmanaged,
3480 if (!TypeManager.VerifyUnManaged (array_type, loc))
3484 // and T* is implicitly convertible to the
3485 // pointer type given in the fixed statement.
3487 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3489 Expression converted = Convert.ImplicitConversionRequired (
3490 ec, array_ptr, vi.VariableType, loc);
3491 if (converted == null)
3494 data [i] = new ExpressionEmitter (converted, vi);
3503 if (e.Type == TypeManager.string_type){
3504 data [i] = new StringEmitter (e, vi, loc);
3509 // Case 4: fixed buffer
3510 FieldExpr fe = e as FieldExpr;
3512 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3514 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3516 Expression converted = Convert.ImplicitConversionRequired (
3517 ec, fixed_buffer_ptr, vi.VariableType, loc);
3518 if (converted == null)
3521 data [i] = new ExpressionEmitter (converted, vi);
3529 // For other cases, flag a `this is already fixed expression'
3531 if (e is LocalVariableReference || e is ParameterReference ||
3532 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3534 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3538 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3542 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3544 if (!statement.Resolve (ec)) {
3545 ec.KillFlowBranching ();
3549 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3550 has_ret = reachability.IsUnreachable;
3555 protected override void DoEmit (EmitContext ec)
3557 for (int i = 0; i < data.Length; i++) {
3561 statement.Emit (ec);
3566 ILGenerator ig = ec.ig;
3569 // Clear the pinned variable
3571 for (int i = 0; i < data.Length; i++) {
3572 data [i].EmitExit (ig);
3577 public class Catch: Statement {
3578 public readonly string Name;
3579 public readonly Block Block;
3581 Expression type_expr;
3584 public Catch (Expression type, string name, Block block, Location l)
3592 public Type CatchType {
3598 public bool IsGeneral {
3600 return type_expr == null;
3604 protected override void DoEmit(EmitContext ec)
3608 public override bool Resolve (EmitContext ec)
3610 if (type_expr != null) {
3611 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3617 CheckObsolete (type);
3619 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3620 Error (155, "The type caught or thrown must be derived from System.Exception");
3626 return Block.Resolve (ec);
3630 public class Try : ExceptionStatement {
3631 public readonly Block Fini, Block;
3632 public readonly ArrayList Specific;
3633 public readonly Catch General;
3635 bool need_exc_block;
3638 // specific, general and fini might all be null.
3640 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3642 if (specific == null && general == null){
3643 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3647 this.Specific = specific;
3648 this.General = general;
3653 public override bool Resolve (EmitContext ec)
3657 FlowBranchingException branching = ec.StartFlowBranching (this);
3659 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3661 if (!Block.Resolve (ec))
3664 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3666 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3668 Type[] prevCatches = new Type [Specific.Count];
3670 foreach (Catch c in Specific){
3671 ec.CurrentBranching.CreateSibling (
3672 c.Block, FlowBranching.SiblingType.Catch);
3674 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3676 if (c.Name != null) {
3677 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3679 throw new Exception ();
3681 vi.VariableInfo = null;
3684 if (!c.Resolve (ec))
3687 Type resolvedType = c.CatchType;
3688 for (int ii = 0; ii < last_index; ++ii) {
3689 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3690 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3695 prevCatches [last_index++] = resolvedType;
3696 need_exc_block = true;
3699 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3701 if (General != null){
3702 ec.CurrentBranching.CreateSibling (
3703 General.Block, FlowBranching.SiblingType.Catch);
3705 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3707 if (!General.Resolve (ec))
3710 need_exc_block = true;
3713 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3717 ec.CurrentBranching.CreateSibling (
3718 Fini, FlowBranching.SiblingType.Finally);
3720 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3722 if (!Fini.Resolve (ec))
3726 ResolveFinally (branching);
3727 need_exc_block |= emit_finally;
3729 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3731 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3733 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3735 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3736 // Unfortunately, System.Reflection.Emit automatically emits
3737 // a leave to the end of the finally block. This is a problem
3738 // if `returns' is true since we may jump to a point after the
3739 // end of the method.
3740 // As a workaround, emit an explicit ret here.
3741 ec.NeedReturnLabel ();
3747 protected override void DoEmit (EmitContext ec)
3749 ILGenerator ig = ec.ig;
3752 ig.BeginExceptionBlock ();
3755 foreach (Catch c in Specific){
3758 ig.BeginCatchBlock (c.CatchType);
3760 if (c.Name != null){
3761 vi = c.Block.GetLocalInfo (c.Name);
3763 throw new Exception ("Variable does not exist in this block");
3765 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3767 ig.Emit (OpCodes.Pop);
3772 if (General != null){
3773 ig.BeginCatchBlock (TypeManager.object_type);
3774 ig.Emit (OpCodes.Pop);
3775 General.Block.Emit (ec);
3780 ig.EndExceptionBlock ();
3783 public override void EmitFinally (EmitContext ec)
3791 public class Using : ExceptionStatement {
3792 object expression_or_block;
3793 Statement Statement;
3798 Expression [] resolved_vars;
3799 Expression [] converted_vars;
3800 ExpressionStatement [] assign;
3801 LocalBuilder local_copy;
3803 public Using (object expression_or_block, Statement stmt, Location l)
3805 this.expression_or_block = expression_or_block;
3811 // Resolves for the case of using using a local variable declaration.
3813 bool ResolveLocalVariableDecls (EmitContext ec)
3817 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3821 expr_type = texpr.Type;
3824 // The type must be an IDisposable or an implicit conversion
3827 converted_vars = new Expression [var_list.Count];
3828 resolved_vars = new Expression [var_list.Count];
3829 assign = new ExpressionStatement [var_list.Count];
3831 bool need_conv = !TypeManager.ImplementsInterface (
3832 expr_type, TypeManager.idisposable_type);
3834 foreach (DictionaryEntry e in var_list){
3835 Expression var = (Expression) e.Key;
3837 var = var.ResolveLValue (ec, new EmptyExpression ());
3841 resolved_vars [i] = var;
3848 converted_vars [i] = Convert.ImplicitConversionRequired (
3849 ec, var, TypeManager.idisposable_type, loc);
3851 if (converted_vars [i] == null)
3858 foreach (DictionaryEntry e in var_list){
3859 Expression var = resolved_vars [i];
3860 Expression new_expr = (Expression) e.Value;
3863 a = new Assign (var, new_expr, loc);
3869 converted_vars [i] = var;
3870 assign [i] = (ExpressionStatement) a;
3877 bool ResolveExpression (EmitContext ec)
3879 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3880 conv = Convert.ImplicitConversionRequired (
3881 ec, expr, TypeManager.idisposable_type, loc);
3891 // Emits the code for the case of using using a local variable declaration.
3893 void EmitLocalVariableDecls (EmitContext ec)
3895 ILGenerator ig = ec.ig;
3898 for (i = 0; i < assign.Length; i++) {
3899 assign [i].EmitStatement (ec);
3902 ig.BeginExceptionBlock ();
3904 Statement.Emit (ec);
3906 var_list.Reverse ();
3911 void EmitLocalVariableDeclFinally (EmitContext ec)
3913 ILGenerator ig = ec.ig;
3915 int i = assign.Length;
3916 for (int ii = 0; ii < var_list.Count; ++ii){
3917 Expression var = resolved_vars [--i];
3918 Label skip = ig.DefineLabel ();
3920 ig.BeginFinallyBlock ();
3922 if (!var.Type.IsValueType) {
3924 ig.Emit (OpCodes.Brfalse, skip);
3925 converted_vars [i].Emit (ec);
3926 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3928 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3930 if (!(ml is MethodGroupExpr)) {
3932 ig.Emit (OpCodes.Box, var.Type);
3933 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3935 MethodInfo mi = null;
3937 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3938 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3945 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3949 IMemoryLocation mloc = (IMemoryLocation) var;
3951 mloc.AddressOf (ec, AddressOp.Load);
3952 ig.Emit (OpCodes.Call, mi);
3956 ig.MarkLabel (skip);
3959 ig.EndExceptionBlock ();
3961 ig.BeginFinallyBlock ();
3966 void EmitExpression (EmitContext ec)
3969 // Make a copy of the expression and operate on that.
3971 ILGenerator ig = ec.ig;
3972 local_copy = ig.DeclareLocal (expr_type);
3977 ig.Emit (OpCodes.Stloc, local_copy);
3980 ig.BeginExceptionBlock ();
3982 Statement.Emit (ec);
3986 ig.EndExceptionBlock ();
3989 void EmitExpressionFinally (EmitContext ec)
3991 ILGenerator ig = ec.ig;
3992 if (!local_copy.LocalType.IsValueType) {
3993 Label skip = ig.DefineLabel ();
3994 ig.Emit (OpCodes.Ldloc, local_copy);
3995 ig.Emit (OpCodes.Brfalse, skip);
3996 ig.Emit (OpCodes.Ldloc, local_copy);
3997 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3998 ig.MarkLabel (skip);
4000 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4002 if (!(ml is MethodGroupExpr)) {
4003 ig.Emit (OpCodes.Ldloc, local_copy);
4004 ig.Emit (OpCodes.Box, local_copy.LocalType);
4005 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4007 MethodInfo mi = null;
4009 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4010 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4017 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4021 ig.Emit (OpCodes.Ldloca, local_copy);
4022 ig.Emit (OpCodes.Call, mi);
4027 public override bool Resolve (EmitContext ec)
4029 if (expression_or_block is DictionaryEntry){
4030 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4031 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4033 if (!ResolveLocalVariableDecls (ec))
4036 } else if (expression_or_block is Expression){
4037 expr = (Expression) expression_or_block;
4039 expr = expr.Resolve (ec);
4043 expr_type = expr.Type;
4045 if (!ResolveExpression (ec))
4049 FlowBranchingException branching = ec.StartFlowBranching (this);
4051 bool ok = Statement.Resolve (ec);
4054 ec.KillFlowBranching ();
4058 ResolveFinally (branching);
4059 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4061 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4062 // Unfortunately, System.Reflection.Emit automatically emits a leave
4063 // to the end of the finally block. This is a problem if `returns'
4064 // is true since we may jump to a point after the end of the method.
4065 // As a workaround, emit an explicit ret here.
4066 ec.NeedReturnLabel ();
4072 protected override void DoEmit (EmitContext ec)
4074 if (expression_or_block is DictionaryEntry)
4075 EmitLocalVariableDecls (ec);
4076 else if (expression_or_block is Expression)
4077 EmitExpression (ec);
4080 public override void EmitFinally (EmitContext ec)
4082 if (expression_or_block is DictionaryEntry)
4083 EmitLocalVariableDeclFinally (ec);
4084 else if (expression_or_block is Expression)
4085 EmitExpressionFinally (ec);
4090 /// Implementation of the foreach C# statement
4092 public class Foreach : ExceptionStatement {
4094 Expression variable;
4096 Statement statement;
4097 ForeachHelperMethods hm;
4098 Expression empty, conv;
4099 Type array_type, element_type;
4101 VariableStorage enumerator;
4103 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4104 Statement stmt, Location l)
4107 this.variable = var;
4113 public override bool Resolve (EmitContext ec)
4115 expr = expr.Resolve (ec);
4119 if (expr is NullLiteral) {
4120 Report.Error (186, expr.Location, "Use of null is not valid in this context");
4124 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4128 var_type = texpr.Type;
4131 // We need an instance variable. Not sure this is the best
4132 // way of doing this.
4134 // FIXME: When we implement propertyaccess, will those turn
4135 // out to return values in ExprClass? I think they should.
4137 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4138 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4139 error1579 (expr.Type);
4143 if (expr.Type.IsArray) {
4144 array_type = expr.Type;
4145 element_type = TypeManager.GetElementType (array_type);
4147 empty = new EmptyExpression (element_type);
4149 hm = ProbeCollectionType (ec, expr.Type);
4151 error1579 (expr.Type);
4155 array_type = expr.Type;
4156 element_type = hm.element_type;
4158 empty = new EmptyExpression (hm.element_type);
4163 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4164 ec.CurrentBranching.CreateSibling ();
4168 // FIXME: maybe we can apply the same trick we do in the
4169 // array handling to avoid creating empty and conv in some cases.
4171 // Although it is not as important in this case, as the type
4172 // will not likely be object (what the enumerator will return).
4174 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4178 variable = variable.ResolveLValue (ec, empty);
4179 if (variable == null)
4182 bool disposable = (hm != null) && hm.is_disposable;
4183 FlowBranchingException branching = null;
4185 branching = ec.StartFlowBranching (this);
4187 if (!statement.Resolve (ec))
4191 ResolveFinally (branching);
4192 ec.EndFlowBranching ();
4194 emit_finally = true;
4196 ec.EndFlowBranching ();
4202 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4204 static MethodInfo FetchMethodMoveNext (Type t)
4206 MemberList move_next_list;
4208 move_next_list = TypeContainer.FindMembers (
4209 t, MemberTypes.Method,
4210 BindingFlags.Public | BindingFlags.Instance,
4211 Type.FilterName, "MoveNext");
4212 if (move_next_list.Count == 0)
4215 foreach (MemberInfo m in move_next_list){
4216 MethodInfo mi = (MethodInfo) m;
4219 args = TypeManager.GetArgumentTypes (mi);
4220 if (args != null && args.Length == 0){
4221 if (TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type)
4229 // Retrieves a `public T get_Current ()' method from the Type `t'
4231 static MethodInfo FetchMethodGetCurrent (Type t)
4233 MemberList get_current_list;
4235 get_current_list = TypeContainer.FindMembers (
4236 t, MemberTypes.Method,
4237 BindingFlags.Public | BindingFlags.Instance,
4238 Type.FilterName, "get_Current");
4239 if (get_current_list.Count == 0)
4242 foreach (MemberInfo m in get_current_list){
4243 MethodInfo mi = (MethodInfo) m;
4246 args = TypeManager.GetArgumentTypes (mi);
4247 if (args != null && args.Length == 0)
4254 // Retrieves a `public void Dispose ()' method from the Type `t'
4256 static MethodInfo FetchMethodDispose (Type t)
4258 MemberList dispose_list;
4260 dispose_list = TypeContainer.FindMembers (
4261 t, MemberTypes.Method,
4262 BindingFlags.Public | BindingFlags.Instance,
4263 Type.FilterName, "Dispose");
4264 if (dispose_list.Count == 0)
4267 foreach (MemberInfo m in dispose_list){
4268 MethodInfo mi = (MethodInfo) m;
4271 args = TypeManager.GetArgumentTypes (mi);
4272 if (args != null && args.Length == 0){
4273 if (mi.ReturnType == TypeManager.void_type)
4281 // This struct records the helper methods used by the Foreach construct
4283 class ForeachHelperMethods {
4284 public EmitContext ec;
4285 public MethodInfo get_enumerator;
4286 public MethodInfo move_next;
4287 public MethodInfo get_current;
4288 public Type element_type;
4289 public Type enumerator_type;
4290 public bool is_disposable;
4292 public ForeachHelperMethods (EmitContext ec)
4295 this.element_type = TypeManager.object_type;
4296 this.enumerator_type = TypeManager.ienumerator_type;
4297 this.is_disposable = true;
4301 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4306 if (!(m is MethodInfo))
4309 if (m.Name != "GetEnumerator")
4312 MethodInfo mi = (MethodInfo) m;
4313 Type [] args = TypeManager.GetArgumentTypes (mi);
4315 if (args.Length != 0)
4318 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4320 // Check whether GetEnumerator is public
4321 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4324 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4326 // Apply the same optimization as MS: skip the GetEnumerator
4327 // returning an IEnumerator, and use the one returning a
4328 // CharEnumerator instead. This allows us to avoid the
4329 // try-finally block and the boxing.
4334 // Ok, we can access it, now make sure that we can do something
4335 // with this `GetEnumerator'
4338 Type return_type = mi.ReturnType;
4339 if (mi.ReturnType == TypeManager.ienumerator_type ||
4340 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4341 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4344 // If it is not an interface, lets try to find the methods ourselves.
4345 // For example, if we have:
4346 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4347 // We can avoid the iface call. This is a runtime perf boost.
4348 // even bigger if we have a ValueType, because we avoid the cost
4351 // We have to make sure that both methods exist for us to take
4352 // this path. If one of the methods does not exist, we will just
4353 // use the interface. Sadly, this complex if statement is the only
4354 // way I could do this without a goto
4357 if (return_type.IsInterface ||
4358 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4359 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4361 hm.move_next = TypeManager.bool_movenext_void;
4362 hm.get_current = TypeManager.object_getcurrent_void;
4369 // Ok, so they dont return an IEnumerable, we will have to
4370 // find if they support the GetEnumerator pattern.
4373 hm.move_next = FetchMethodMoveNext (return_type);
4374 if (hm.move_next == null)
4377 hm.get_current = FetchMethodGetCurrent (return_type);
4378 if (hm.get_current == null)
4382 hm.element_type = hm.get_current.ReturnType;
4383 hm.enumerator_type = return_type;
4384 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4385 TypeManager.ImplementsInterface (
4386 hm.enumerator_type, TypeManager.idisposable_type);
4392 /// This filter is used to find the GetEnumerator method
4393 /// on which IEnumerator operates
4395 static MemberFilter FilterEnumerator;
4399 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4402 void error1579 (Type t)
4404 Report.Error (1579, loc,
4405 "foreach statement cannot operate on variables of type `" +
4406 t.FullName + "' because that class does not provide a " +
4407 " GetEnumerator method or it is inaccessible");
4410 static bool TryType (Type t, ForeachHelperMethods hm)
4414 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4415 BindingFlags.Public | BindingFlags.NonPublic |
4416 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4417 FilterEnumerator, hm);
4422 hm.get_enumerator = (MethodInfo) mi [0];
4427 // Looks for a usable GetEnumerator in the Type, and if found returns
4428 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4430 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4432 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4434 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4435 if (TryType (tt, hm))
4441 // Now try to find the method in the interfaces
4444 Type [] ifaces = t.GetInterfaces ();
4446 foreach (Type i in ifaces){
4447 if (TryType (i, hm))
4452 // Since TypeBuilder.GetInterfaces only returns the interface
4453 // types for this type, we have to keep looping, but once
4454 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4455 // done, because it returns all the types
4457 if ((t is TypeBuilder))
4467 // FIXME: possible optimization.
4468 // We might be able to avoid creating `empty' if the type is the sam
4470 bool EmitCollectionForeach (EmitContext ec)
4472 ILGenerator ig = ec.ig;
4474 enumerator = new VariableStorage (ec, hm.enumerator_type);
4475 enumerator.EmitThis (ig);
4477 // Instantiate the enumerator
4479 if (expr.Type.IsValueType){
4480 IMemoryLocation ml = expr as IMemoryLocation;
4481 // Load the address of the value type.
4483 // This happens if, for example, you have a property
4484 // returning a struct which is IEnumerable
4485 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4487 ig.Emit (OpCodes.Stloc, t);
4488 ig.Emit (OpCodes.Ldloca, t);
4489 ec.FreeTemporaryLocal (t, expr.Type);
4491 ml.AddressOf (ec, AddressOp.Load);
4495 if (hm.get_enumerator.DeclaringType.IsValueType) {
4496 // the method is declared on the value type
4497 ig.Emit (OpCodes.Call, hm.get_enumerator);
4499 // it is an interface method, so we must box
4500 ig.Emit (OpCodes.Box, expr.Type);
4501 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4505 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4507 enumerator.EmitStore (ig);
4510 // Protect the code in a try/finalize block, so that
4511 // if the beast implement IDisposable, we get rid of it
4513 if (hm.is_disposable && emit_finally)
4514 ig.BeginExceptionBlock ();
4516 Label end_try = ig.DefineLabel ();
4518 ig.MarkLabel (ec.LoopBegin);
4520 enumerator.EmitCall (ig, hm.move_next);
4522 ig.Emit (OpCodes.Brfalse, end_try);
4525 ig.Emit (OpCodes.Ldarg_0);
4527 enumerator.EmitCall (ig, hm.get_current);
4531 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4533 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4535 statement.Emit (ec);
4536 ig.Emit (OpCodes.Br, ec.LoopBegin);
4537 ig.MarkLabel (end_try);
4539 // The runtime provides this for us.
4540 // ig.Emit (OpCodes.Leave, end);
4543 // Now the finally block
4545 if (hm.is_disposable) {
4548 ig.EndExceptionBlock ();
4551 ig.MarkLabel (ec.LoopEnd);
4555 public override void EmitFinally (EmitContext ec)
4557 ILGenerator ig = ec.ig;
4559 if (hm.enumerator_type.IsValueType) {
4560 enumerator.EmitThis (ig);
4562 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4564 enumerator.EmitLoadAddress (ig);
4565 ig.Emit (OpCodes.Call, mi);
4567 enumerator.EmitLoad (ig);
4568 ig.Emit (OpCodes.Box, hm.enumerator_type);
4569 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4572 Label call_dispose = ig.DefineLabel ();
4574 enumerator.EmitThis (ig);
4575 enumerator.EmitLoad (ig);
4576 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4577 ig.Emit (OpCodes.Dup);
4578 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4579 ig.Emit (OpCodes.Pop);
4581 Label end_finally = ig.DefineLabel ();
4582 ig.Emit (OpCodes.Br, end_finally);
4584 ig.MarkLabel (call_dispose);
4585 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4586 ig.MarkLabel (end_finally);
4589 ig.Emit (OpCodes.Endfinally);
4594 // FIXME: possible optimization.
4595 // We might be able to avoid creating `empty' if the type is the sam
4597 bool EmitArrayForeach (EmitContext ec)
4599 int rank = array_type.GetArrayRank ();
4600 ILGenerator ig = ec.ig;
4602 VariableStorage copy = new VariableStorage (ec, array_type);
4605 // Make our copy of the array
4609 copy.EmitStore (ig);
4612 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4616 counter.EmitThis (ig);
4617 ig.Emit (OpCodes.Ldc_I4_0);
4618 counter.EmitStore (ig);
4619 test = ig.DefineLabel ();
4620 ig.Emit (OpCodes.Br, test);
4622 loop = ig.DefineLabel ();
4623 ig.MarkLabel (loop);
4626 ig.Emit (OpCodes.Ldarg_0);
4630 counter.EmitThis (ig);
4631 counter.EmitLoad (ig);
4634 // Load the value, we load the value using the underlying type,
4635 // then we use the variable.EmitAssign to load using the proper cast.
4637 ArrayAccess.EmitLoadOpcode (ig, element_type);
4640 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4642 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4644 statement.Emit (ec);
4646 ig.MarkLabel (ec.LoopBegin);
4647 counter.EmitThis (ig);
4648 counter.EmitThis (ig);
4649 counter.EmitLoad (ig);
4650 ig.Emit (OpCodes.Ldc_I4_1);
4651 ig.Emit (OpCodes.Add);
4652 counter.EmitStore (ig);
4654 ig.MarkLabel (test);
4655 counter.EmitThis (ig);
4656 counter.EmitLoad (ig);
4659 ig.Emit (OpCodes.Ldlen);
4660 ig.Emit (OpCodes.Conv_I4);
4661 ig.Emit (OpCodes.Blt, loop);
4663 VariableStorage [] dim_len = new VariableStorage [rank];
4664 VariableStorage [] dim_count = new VariableStorage [rank];
4665 Label [] loop = new Label [rank];
4666 Label [] test = new Label [rank];
4669 for (dim = 0; dim < rank; dim++){
4670 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4671 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4672 test [dim] = ig.DefineLabel ();
4673 loop [dim] = ig.DefineLabel ();
4676 for (dim = 0; dim < rank; dim++){
4677 dim_len [dim].EmitThis (ig);
4680 IntLiteral.EmitInt (ig, dim);
4681 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4682 dim_len [dim].EmitStore (ig);
4686 for (dim = 0; dim < rank; dim++){
4687 dim_count [dim].EmitThis (ig);
4688 ig.Emit (OpCodes.Ldc_I4_0);
4689 dim_count [dim].EmitStore (ig);
4690 ig.Emit (OpCodes.Br, test [dim]);
4691 ig.MarkLabel (loop [dim]);
4695 ig.Emit (OpCodes.Ldarg_0);
4699 for (dim = 0; dim < rank; dim++){
4700 dim_count [dim].EmitThis (ig);
4701 dim_count [dim].EmitLoad (ig);
4705 // FIXME: Maybe we can cache the computation of `get'?
4707 Type [] args = new Type [rank];
4710 for (int i = 0; i < rank; i++)
4711 args [i] = TypeManager.int32_type;
4713 ModuleBuilder mb = CodeGen.Module.Builder;
4714 get = mb.GetArrayMethod (
4716 CallingConventions.HasThis| CallingConventions.Standard,
4718 ig.Emit (OpCodes.Call, get);
4721 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4723 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4724 statement.Emit (ec);
4725 ig.MarkLabel (ec.LoopBegin);
4726 for (dim = rank - 1; dim >= 0; dim--){
4727 dim_count [dim].EmitThis (ig);
4728 dim_count [dim].EmitThis (ig);
4729 dim_count [dim].EmitLoad (ig);
4730 ig.Emit (OpCodes.Ldc_I4_1);
4731 ig.Emit (OpCodes.Add);
4732 dim_count [dim].EmitStore (ig);
4734 ig.MarkLabel (test [dim]);
4735 dim_count [dim].EmitThis (ig);
4736 dim_count [dim].EmitLoad (ig);
4737 dim_len [dim].EmitThis (ig);
4738 dim_len [dim].EmitLoad (ig);
4739 ig.Emit (OpCodes.Blt, loop [dim]);
4742 ig.MarkLabel (ec.LoopEnd);
4747 protected override void DoEmit (EmitContext ec)
4749 ILGenerator ig = ec.ig;
4751 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4752 ec.LoopBegin = ig.DefineLabel ();
4753 ec.LoopEnd = ig.DefineLabel ();
4756 EmitCollectionForeach (ec);
4758 EmitArrayForeach (ec);
4760 ec.LoopBegin = old_begin;
4761 ec.LoopEnd = old_end;