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.InFinally) {
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 {
645 LabeledStatement label;
647 public override bool Resolve (EmitContext ec)
649 label = ec.CurrentBranching.LookupLabel (target, loc);
653 // If this is a forward goto.
654 if (!label.IsDefined)
655 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
657 ec.CurrentBranching.CurrentUsageVector.Goto ();
658 label.AddReference ();
663 public Goto (string label, Location l)
669 public string Target {
675 protected override void DoEmit (EmitContext ec)
677 Label l = label.LabelTarget (ec);
678 ec.ig.Emit (OpCodes.Br, l);
682 public class LabeledStatement : Statement {
683 public readonly Location Location;
689 FlowBranching.UsageVector vectors;
691 public LabeledStatement (string label_name, Location l)
696 public Label LabelTarget (EmitContext ec)
701 label = ec.ig.DefineLabel ();
707 public bool IsDefined {
713 public bool HasBeenReferenced {
719 public void AddUsageVector (FlowBranching.UsageVector vector)
721 vector = vector.Clone ();
722 vector.Next = vectors;
726 public override bool Resolve (EmitContext ec)
728 ec.CurrentBranching.Label (vectors);
733 protected override void DoEmit (EmitContext ec)
735 if (ig != null && ig != ec.ig) {
736 Report.Error (1632, "Control cannot leave body of anonymous method");
740 ec.ig.MarkLabel (label);
743 public void AddReference ()
751 /// `goto default' statement
753 public class GotoDefault : Statement {
755 public GotoDefault (Location l)
760 public override bool Resolve (EmitContext ec)
762 ec.CurrentBranching.CurrentUsageVector.Goto ();
766 protected override void DoEmit (EmitContext ec)
768 if (ec.Switch == null){
769 Report.Error (153, loc, "goto default is only valid in a switch statement");
773 if (!ec.Switch.GotDefault){
774 Report.Error (159, loc, "No default target on switch statement");
777 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
782 /// `goto case' statement
784 public class GotoCase : Statement {
788 public GotoCase (Expression e, Location l)
794 public override bool Resolve (EmitContext ec)
796 if (ec.Switch == null){
797 Report.Error (153, loc, "goto case is only valid in a switch statement");
801 expr = expr.Resolve (ec);
805 if (!(expr is Constant)){
806 Report.Error (159, loc, "Target expression for goto case is not constant");
810 object val = Expression.ConvertIntLiteral (
811 (Constant) expr, ec.Switch.SwitchType, loc);
816 sl = (SwitchLabel) ec.Switch.Elements [val];
821 "No such label 'case " + val + "': for the goto case");
825 ec.CurrentBranching.CurrentUsageVector.Goto ();
829 protected override void DoEmit (EmitContext ec)
831 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
835 public class Throw : Statement {
838 public Throw (Expression expr, Location l)
844 public override bool Resolve (EmitContext ec)
846 ec.CurrentBranching.CurrentUsageVector.Throw ();
849 expr = expr.Resolve (ec);
853 ExprClass eclass = expr.eclass;
855 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
856 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
857 expr.Error_UnexpectedKind ("value, variable, property or indexer access ", loc);
863 if ((t != TypeManager.exception_type) &&
864 !t.IsSubclassOf (TypeManager.exception_type) &&
865 !(expr is NullLiteral)) {
867 "The type caught or thrown must be derived " +
868 "from System.Exception");
875 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
880 Error (724, "A throw statement with no argument is only allowed in a catch clause nested inside of the innermost catch clause");
886 protected override void DoEmit (EmitContext ec)
889 ec.ig.Emit (OpCodes.Rethrow);
893 ec.ig.Emit (OpCodes.Throw);
898 public class Break : Statement {
900 public Break (Location l)
907 public override bool Resolve (EmitContext ec)
909 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
910 Error (139, "No enclosing loop or switch to continue to");
912 } else if (ec.InFinally && ec.CurrentBranching.BreakCrossesTryCatchBoundary()) {
913 Error (157, "Control can not leave the body of the finally block");
915 } else if (ec.CurrentBranching.InTryOrCatch (false))
916 ec.CurrentBranching.AddFinallyVector (
917 ec.CurrentBranching.CurrentUsageVector);
918 else if (ec.CurrentBranching.InLoop ())
919 ec.CurrentBranching.AddBreakVector (
920 ec.CurrentBranching.CurrentUsageVector);
922 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
925 ec.NeedReturnLabel ();
927 ec.CurrentBranching.CurrentUsageVector.Break ();
931 protected override void DoEmit (EmitContext ec)
933 ILGenerator ig = ec.ig;
936 ig.Emit (OpCodes.Leave, ec.LoopEnd);
938 ig.Emit (OpCodes.Br, ec.LoopEnd);
943 public class Continue : Statement {
945 public Continue (Location l)
952 public override bool Resolve (EmitContext ec)
954 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
955 Error (139, "No enclosing loop to continue to");
957 } else if (ec.InFinally) {
958 Error (157, "Control can not leave the body of the finally block");
960 } else if (ec.CurrentBranching.InTryOrCatch (false))
961 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
963 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
965 ec.CurrentBranching.CurrentUsageVector.Goto ();
969 protected override void DoEmit (EmitContext ec)
971 Label begin = ec.LoopBegin;
974 ec.ig.Emit (OpCodes.Leave, begin);
976 ec.ig.Emit (OpCodes.Br, begin);
981 // The information about a user-perceived local variable
983 public class LocalInfo {
984 public Expression Type;
987 // Most of the time a variable will be stored in a LocalBuilder
989 // But sometimes, it will be stored in a field (variables that have been
990 // hoisted by iterators or by anonymous methods). The context of the field will
991 // be stored in the EmitContext
994 public LocalBuilder LocalBuilder;
995 public FieldBuilder FieldBuilder;
997 public Type VariableType;
998 public readonly string Name;
999 public readonly Location Location;
1000 public readonly Block Block;
1002 public VariableInfo VariableInfo;
1015 public LocalInfo (Expression type, string name, Block block, Location l)
1023 public LocalInfo (TypeContainer tc, Block block, Location l)
1025 VariableType = tc.TypeBuilder;
1030 public bool IsThisAssigned (EmitContext ec, Location loc)
1032 if (VariableInfo == null)
1033 throw new Exception ();
1035 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1038 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1041 public bool IsAssigned (EmitContext ec)
1043 if (VariableInfo == null)
1044 throw new Exception ();
1046 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1049 public bool Resolve (EmitContext ec)
1051 if (VariableType == null) {
1052 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
1056 VariableType = texpr.Type;
1059 if (VariableType == TypeManager.void_type) {
1060 Report.Error (1547, Location,
1061 "Keyword 'void' cannot be used in this context");
1065 if (VariableType.IsAbstract && VariableType.IsSealed) {
1066 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1069 // TODO: breaks the build
1070 // if (VariableType.IsPointer && !ec.InUnsafe)
1071 // Expression.UnsafeError (Location);
1077 // Whether the variable is Fixed (because its Pinned or its a value type)
1079 public bool IsFixed {
1081 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1088 public bool IsCaptured {
1090 return (flags & Flags.Captured) != 0;
1094 flags |= Flags.Captured;
1098 public bool AddressTaken {
1100 return (flags & Flags.AddressTaken) != 0;
1104 flags |= Flags.AddressTaken;
1108 public override string ToString ()
1110 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1111 Name, Type, VariableInfo, Location);
1116 return (flags & Flags.Used) != 0;
1119 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1123 public bool ReadOnly {
1125 return (flags & Flags.ReadOnly) != 0;
1128 flags = value ? (flags | Flags.ReadOnly) : (unchecked (flags & ~Flags.ReadOnly));
1133 // Whether the variable is pinned, if Pinned the variable has been
1134 // allocated in a pinned slot with DeclareLocal.
1136 public bool Pinned {
1138 return (flags & Flags.Pinned) != 0;
1141 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1145 public bool IsThis {
1147 return (flags & Flags.IsThis) != 0;
1150 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1156 /// Block represents a C# block.
1160 /// This class is used in a number of places: either to represent
1161 /// explicit blocks that the programmer places or implicit blocks.
1163 /// Implicit blocks are used as labels or to introduce variable
1166 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1167 /// they contain extra information that is not necessary on normal blocks.
1169 public class Block : Statement {
1170 public Block Parent;
1171 public readonly Location StartLocation;
1172 public Location EndLocation = Location.Null;
1174 public readonly ToplevelBlock Toplevel;
1181 VariablesInitialized = 8,
1190 public bool Implicit {
1192 return (flags & Flags.Implicit) != 0;
1196 public bool Unchecked {
1198 return (flags & Flags.Unchecked) != 0;
1201 flags |= Flags.Unchecked;
1205 public bool Unsafe {
1207 return (flags & Flags.Unsafe) != 0;
1210 flags |= Flags.Unsafe;
1214 public bool HasVarargs {
1217 return Parent.HasVarargs;
1219 return (flags & Flags.HasVarargs) != 0;
1222 flags |= Flags.HasVarargs;
1227 // The statements in this block
1229 ArrayList statements;
1233 // An array of Blocks. We keep track of children just
1234 // to generate the local variable declarations.
1236 // Statements and child statements are handled through the
1242 // Labels. (label, block) pairs.
1247 // Keeps track of (name, type) pairs
1249 Hashtable variables;
1252 // Keeps track of constants
1253 Hashtable constants;
1256 // If this is a switch section, the enclosing switch block.
1260 protected static int id;
1264 public Block (Block parent)
1265 : this (parent, (Flags) 0, Location.Null, Location.Null)
1268 public Block (Block parent, Flags flags)
1269 : this (parent, flags, Location.Null, Location.Null)
1272 public Block (Block parent, Location start, Location end)
1273 : this (parent, (Flags) 0, start, end)
1276 public Block (Block parent, Flags flags, Location start, Location end)
1279 parent.AddChild (this);
1281 this.Parent = parent;
1283 this.StartLocation = start;
1284 this.EndLocation = end;
1287 statements = new ArrayList ();
1289 if ((flags & Flags.IsToplevel) != 0)
1290 Toplevel = (ToplevelBlock) this;
1292 Toplevel = parent.Toplevel;
1294 if (parent != null && Implicit) {
1295 if (parent.known_variables == null)
1296 parent.known_variables = new Hashtable ();
1297 // share with parent
1298 known_variables = parent.known_variables;
1303 public Block CreateSwitchBlock (Location start)
1305 Block new_block = new Block (this, start, start);
1306 new_block.switch_block = this;
1316 void AddChild (Block b)
1318 if (children == null)
1319 children = new ArrayList ();
1324 public void SetEndLocation (Location loc)
1330 /// Adds a label to the current block.
1334 /// false if the name already exists in this block. true
1338 public bool AddLabel (string name, LabeledStatement target, Location loc)
1340 if (switch_block != null)
1341 return switch_block.AddLabel (name, target, loc);
1344 while (cur != null) {
1345 if (cur.DoLookupLabel (name) != null) {
1347 140, loc, "The label '{0}' is a duplicate",
1358 while (cur != null) {
1359 if (cur.DoLookupLabel (name) != null) {
1362 "The label '{0}' shadows another label " +
1363 "by the same name in a containing scope.",
1368 if (children != null) {
1369 foreach (Block b in children) {
1370 LabeledStatement s = b.DoLookupLabel (name);
1376 "The label '{0}' shadows another " +
1377 "label by the same name in a " +
1378 "containing scope.",
1389 labels = new Hashtable ();
1391 labels.Add (name, target);
1395 public LabeledStatement LookupLabel (string name)
1397 LabeledStatement s = DoLookupLabel (name);
1401 if (children == null)
1404 foreach (Block child in children) {
1405 if (!child.Implicit)
1408 s = child.LookupLabel (name);
1416 LabeledStatement DoLookupLabel (string name)
1418 if (switch_block != null)
1419 return switch_block.LookupLabel (name);
1422 if (labels.Contains (name))
1423 return ((LabeledStatement) labels [name]);
1428 LocalInfo this_variable = null;
1431 // Returns the "this" instance variable of this block.
1432 // See AddThisVariable() for more information.
1434 public LocalInfo ThisVariable {
1436 for (Block b = this; b != null; b = b.Parent) {
1437 if (b.this_variable != null)
1438 return b.this_variable;
1445 Hashtable known_variables;
1448 // Marks a variable with name @name as being used in this or a child block.
1449 // If a variable name has been used in a child block, it's illegal to
1450 // declare a variable with the same name in the current block.
1452 void AddKnownVariable (string name, LocalInfo info)
1454 if (known_variables == null)
1455 known_variables = new Hashtable ();
1457 known_variables [name] = info;
1460 LocalInfo GetKnownVariableInfo (string name)
1462 if (known_variables == null)
1464 return (LocalInfo) known_variables [name];
1467 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1469 LocalInfo kvi = GetKnownVariableInfo (name);
1470 if (kvi == null || kvi.Block == this)
1473 if (known_variables != kvi.Block.known_variables) {
1474 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1475 Report.Error (135, loc, "'{0}' has a different meaning in a child block", name);
1480 // this block and kvi.Block are the same textual block.
1481 // However, different variables are extant.
1483 // Check if the variable is in scope in both blocks. We use
1484 // an indirect check that depends on AddVariable doing its
1485 // part in maintaining the invariant-meaning-in-block property.
1487 if (e is LocalVariableReference || (e is Constant && GetLocalInfo (name) != null))
1490 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1491 Report.Error (136, loc, "'{0}' has a different meaning later in the block", name);
1496 // This is used by non-static `struct' constructors which do not have an
1497 // initializer - in this case, the constructor must initialize all of the
1498 // struct's fields. To do this, we add a "this" variable and use the flow
1499 // analysis code to ensure that it's been fully initialized before control
1500 // leaves the constructor.
1502 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1504 if (this_variable != null)
1505 return this_variable;
1507 if (variables == null)
1508 variables = new Hashtable ();
1510 this_variable = new LocalInfo (tc, this, l);
1511 this_variable.Used = true;
1512 this_variable.IsThis = true;
1514 variables.Add ("this", this_variable);
1516 return this_variable;
1519 public LocalInfo AddVariable (Expression type, string name, Location l)
1521 if (variables == null)
1522 variables = new Hashtable ();
1524 LocalInfo vi = GetLocalInfo (name);
1526 Report.SymbolRelatedToPreviousError (vi.Location, name);
1527 if (known_variables == vi.Block.known_variables)
1528 Report.Error (128, l,
1529 "A local variable '{0}' is already declared in this scope", name);
1531 Report.Error (136, l,
1532 "'{0}' hides the declaration of local variable '{0}' in a parent scope", name);
1536 vi = GetKnownVariableInfo (name);
1538 Report.SymbolRelatedToPreviousError (vi.Location, name);
1539 Report.Error (136, l,
1540 "A child block already has a declaration of local variable '{0}':" +
1541 " allowing this declaration would violate 'invariant meaning in a block'",
1547 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1549 Report.SymbolRelatedToPreviousError (Toplevel.Parameters.Location, name);
1550 Report.Error (136, l, "'{0}' hides a method parameter", name);
1554 vi = new LocalInfo (type, name, this, l);
1556 variables.Add (name, vi);
1558 for (Block b = this; b != null; b = b.Parent)
1559 b.AddKnownVariable (name, vi);
1561 if ((flags & Flags.VariablesInitialized) != 0)
1562 throw new Exception ();
1564 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1568 public bool AddConstant (Expression type, string name, Expression value, Location l)
1570 if (AddVariable (type, name, l) == null)
1573 if (constants == null)
1574 constants = new Hashtable ();
1576 constants.Add (name, value);
1580 public Hashtable Variables {
1586 public LocalInfo GetLocalInfo (string name)
1588 for (Block b = this; b != null; b = b.Parent) {
1589 if (b.variables != null) {
1590 LocalInfo ret = b.variables [name] as LocalInfo;
1598 public Expression GetVariableType (string name)
1600 LocalInfo vi = GetLocalInfo (name);
1608 public Expression GetConstantExpression (string name)
1610 for (Block b = this; b != null; b = b.Parent) {
1611 if (b.constants != null) {
1612 Expression ret = b.constants [name] as Expression;
1621 /// True if the variable named @name is a constant
1623 public bool IsConstant (string name)
1625 Expression e = null;
1627 e = GetConstantExpression (name);
1633 // Returns a `ParameterReference' for the given name, or null if there
1634 // is no such parameter
1636 public ParameterReference GetParameterReference (string name, Location loc)
1641 for (Block b = this; b != null; b = b.Toplevel.Parent) {
1642 Parameters pars = b.Toplevel.Parameters;
1643 par = pars.GetParameterByName (name, out idx);
1645 return new ParameterReference (pars, this, idx, name, loc);
1651 // Whether the parameter named `name' is local to this block,
1652 // or false, if the parameter belongs to an encompassing block.
1654 public bool IsLocalParameter (string name)
1656 return Toplevel.Parameters.GetParameterByName (name) != null;
1660 // Whether the `name' is a parameter reference
1662 public bool IsParameterReference (string name)
1667 for (Block b = this; b != null; b = b.Toplevel.Parent) {
1668 par = b.Toplevel.Parameters.GetParameterByName (name, out idx);
1676 /// A list of labels that were not used within this block
1678 public string [] GetUnreferenced ()
1680 // FIXME: Implement me
1684 public void AddStatement (Statement s)
1687 flags |= Flags.BlockUsed;
1692 return (flags & Flags.BlockUsed) != 0;
1698 flags |= Flags.BlockUsed;
1701 public bool HasRet {
1703 return (flags & Flags.HasRet) != 0;
1707 public bool IsDestructor {
1709 return (flags & Flags.IsDestructor) != 0;
1713 public void SetDestructor ()
1715 flags |= Flags.IsDestructor;
1718 VariableMap param_map, local_map;
1720 public VariableMap ParameterMap {
1722 if ((flags & Flags.VariablesInitialized) == 0)
1723 throw new Exception ("Variables have not been initialized yet");
1729 public VariableMap LocalMap {
1731 if ((flags & Flags.VariablesInitialized) == 0)
1732 throw new Exception ("Variables have not been initialized yet");
1739 /// Emits the variable declarations and labels.
1742 /// tc: is our typecontainer (to resolve type references)
1743 /// ig: is the code generator:
1745 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1747 bool old_unsafe = ec.InUnsafe;
1749 // If some parent block was unsafe, we remain unsafe even if this block
1750 // isn't explicitly marked as such.
1751 ec.InUnsafe |= Unsafe;
1754 // Compute the VariableMap's.
1756 // Unfortunately, we don't know the type when adding variables with
1757 // AddVariable(), so we need to compute this info here.
1761 if (variables != null) {
1762 foreach (LocalInfo li in variables.Values)
1765 locals = new LocalInfo [variables.Count];
1766 variables.Values.CopyTo (locals, 0);
1768 locals = new LocalInfo [0];
1771 local_map = new VariableMap (Parent.LocalMap, locals);
1773 local_map = new VariableMap (locals);
1775 param_map = new VariableMap (ip);
1776 flags |= Flags.VariablesInitialized;
1778 bool old_check_state = ec.ConstantCheckState;
1779 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1782 // Process this block variables
1784 if (variables != null){
1785 foreach (DictionaryEntry de in variables){
1786 string name = (string) de.Key;
1787 LocalInfo vi = (LocalInfo) de.Value;
1789 if (vi.VariableType == null)
1792 Type variable_type = vi.VariableType;
1794 if (variable_type.IsPointer){
1796 // Am not really convinced that this test is required (Microsoft does it)
1797 // but the fact is that you would not be able to use the pointer variable
1800 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1807 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1810 // This is needed to compile on both .NET 1.x and .NET 2.x
1811 // the later introduced `DeclareLocal (Type t, bool pinned)'
1813 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1814 else if (!vi.IsThis)
1815 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1818 if (constants == null)
1821 Expression cv = (Expression) constants [name];
1825 ec.CurrentBlock = this;
1826 Expression e = cv.Resolve (ec);
1830 Constant ce = e as Constant;
1832 Report.Error (133, vi.Location,
1833 "The expression being assigned to `" +
1834 name + "' must be constant (" + e + ")");
1838 if (e.Type != variable_type){
1839 e = Const.ChangeType (vi.Location, ce, variable_type);
1844 constants.Remove (name);
1845 constants.Add (name, e);
1848 ec.ConstantCheckState = old_check_state;
1851 // Now, handle the children
1853 if (children != null){
1854 foreach (Block b in children)
1855 b.ResolveMeta (toplevel, ec, ip);
1857 ec.InUnsafe = old_unsafe;
1861 // Emits the local variable declarations for a block
1863 public void EmitMeta (EmitContext ec)
1865 ILGenerator ig = ec.ig;
1867 if (variables != null){
1868 bool have_captured_vars = ec.HaveCapturedVariables ();
1869 bool remap_locals = ec.RemapToProxy;
1871 foreach (DictionaryEntry de in variables){
1872 LocalInfo vi = (LocalInfo) de.Value;
1874 if (have_captured_vars && ec.IsCaptured (vi))
1878 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1882 // This is needed to compile on both .NET 1.x and .NET 2.x
1883 // the later introduced `DeclareLocal (Type t, bool pinned)'
1885 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1886 else if (!vi.IsThis)
1887 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1892 if (children != null){
1893 foreach (Block b in children)
1898 void UsageWarning (FlowBranching.UsageVector vector)
1902 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1903 foreach (DictionaryEntry de in variables){
1904 LocalInfo vi = (LocalInfo) de.Value;
1909 name = (string) de.Key;
1911 if (vector.IsAssigned (vi.VariableInfo)){
1912 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1914 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1920 bool unreachable_shown;
1922 public override bool Resolve (EmitContext ec)
1924 Block prev_block = ec.CurrentBlock;
1927 int errors = Report.Errors;
1929 ec.CurrentBlock = this;
1930 ec.StartFlowBranching (this);
1932 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1935 // This flag is used to notate nested statements as unreachable from the beginning of this block.
1936 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
1937 // from the beginning of the function. The outer Resolve() that detected the unreachability is
1938 // responsible for handling the situation.
1940 bool unreachable = false;
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;
2116 FlowBranching top_level_branching;
2118 Hashtable capture_contexts;
2121 // The parameters for the block.
2123 public readonly Parameters Parameters;
2125 public void RegisterCaptureContext (CaptureContext cc)
2127 if (capture_contexts == null)
2128 capture_contexts = new Hashtable ();
2129 capture_contexts [cc] = cc;
2132 public void CompleteContexts ()
2134 if (capture_contexts == null)
2137 foreach (CaptureContext cc in capture_contexts.Keys){
2142 public CaptureContext ToplevelBlockCaptureContext {
2144 return capture_context;
2149 // Parent is only used by anonymous blocks to link back to their
2152 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2153 this (container, (Flags) 0, parameters, start)
2157 public ToplevelBlock (Parameters parameters, Location start) :
2158 this (null, (Flags) 0, parameters, start)
2162 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2163 this (null, flags, parameters, start)
2167 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2168 base (null, flags | Flags.IsToplevel, start, Location.Null)
2170 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2171 Container = container;
2174 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2178 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2180 if (capture_context == null)
2181 capture_context = new CaptureContext (this, loc, host);
2184 public CaptureContext CaptureContext {
2186 return capture_context;
2190 public FlowBranching TopLevelBranching {
2192 return top_level_branching;
2196 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2198 int errors = Report.Errors;
2200 if (top_level_branching != null)
2203 ResolveMeta (this, ec, ip);
2205 top_level_branching = ec.StartFlowBranching (this);
2207 return Report.Errors == errors;
2211 public class SwitchLabel {
2214 public Location loc;
2218 Label il_label_code;
2219 bool il_label_code_set;
2222 // if expr == null, then it is the default case.
2224 public SwitchLabel (Expression expr, Location l)
2230 public Expression Label {
2236 public object Converted {
2242 public Label GetILLabel (EmitContext ec)
2245 il_label = ec.ig.DefineLabel ();
2246 il_label_set = true;
2251 public Label GetILLabelCode (EmitContext ec)
2253 if (!il_label_code_set){
2254 il_label_code = ec.ig.DefineLabel ();
2255 il_label_code_set = true;
2257 return il_label_code;
2261 // Resolves the expression, reduces it to a literal if possible
2262 // and then converts it to the requested type.
2264 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2269 Expression e = label.Resolve (ec);
2274 if (!(e is Constant)){
2275 Report.Error (150, loc, "A constant value is expected, got: " + e);
2279 if (e is StringConstant || e is NullLiteral){
2280 if (required_type == TypeManager.string_type){
2286 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2287 if (converted == null)
2294 public class SwitchSection {
2295 // An array of SwitchLabels.
2296 public readonly ArrayList Labels;
2297 public readonly Block Block;
2299 public SwitchSection (ArrayList labels, Block block)
2306 public class Switch : Statement {
2307 public readonly ArrayList Sections;
2308 public Expression Expr;
2311 /// Maps constants whose type type SwitchType to their SwitchLabels.
2313 public Hashtable Elements;
2316 /// The governing switch type
2318 public Type SwitchType;
2324 Label default_target;
2325 Expression new_expr;
2327 SwitchSection constant_section;
2330 // The types allowed to be implicitly cast from
2331 // on the governing type
2333 static Type [] allowed_types;
2335 public Switch (Expression e, ArrayList sects, Location l)
2342 public bool GotDefault {
2348 public Label DefaultTarget {
2350 return default_target;
2355 // Determines the governing type for a switch. The returned
2356 // expression might be the expression from the switch, or an
2357 // expression that includes any potential conversions to the
2358 // integral types or to string.
2360 Expression SwitchGoverningType (EmitContext ec, Type t)
2362 if (t == TypeManager.int32_type ||
2363 t == TypeManager.uint32_type ||
2364 t == TypeManager.char_type ||
2365 t == TypeManager.byte_type ||
2366 t == TypeManager.sbyte_type ||
2367 t == TypeManager.ushort_type ||
2368 t == TypeManager.short_type ||
2369 t == TypeManager.uint64_type ||
2370 t == TypeManager.int64_type ||
2371 t == TypeManager.string_type ||
2372 t == TypeManager.bool_type ||
2373 t.IsSubclassOf (TypeManager.enum_type))
2376 if (allowed_types == null){
2377 allowed_types = new Type [] {
2378 TypeManager.int32_type,
2379 TypeManager.uint32_type,
2380 TypeManager.sbyte_type,
2381 TypeManager.byte_type,
2382 TypeManager.short_type,
2383 TypeManager.ushort_type,
2384 TypeManager.int64_type,
2385 TypeManager.uint64_type,
2386 TypeManager.char_type,
2387 TypeManager.bool_type,
2388 TypeManager.string_type
2393 // Try to find a *user* defined implicit conversion.
2395 // If there is no implicit conversion, or if there are multiple
2396 // conversions, we have to report an error
2398 Expression converted = null;
2399 foreach (Type tt in allowed_types){
2402 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2407 // Ignore over-worked ImplicitUserConversions that do
2408 // an implicit conversion in addition to the user conversion.
2411 UserCast ue = e as UserCast;
2413 if (ue.Source != Expr)
2417 if (converted != null){
2418 Report.ExtraInformation (
2420 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2421 TypeManager.CSharpName (Expr.Type)));
2430 static string Error152 {
2432 return "The label '{0}:' already occurs in this switch statement";
2437 // Performs the basic sanity checks on the switch statement
2438 // (looks for duplicate keys and non-constant expressions).
2440 // It also returns a hashtable with the keys that we will later
2441 // use to compute the switch tables
2443 bool CheckSwitch (EmitContext ec)
2447 Elements = new Hashtable ();
2449 got_default = false;
2451 if (TypeManager.IsEnumType (SwitchType)){
2452 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2454 compare_type = SwitchType;
2456 foreach (SwitchSection ss in Sections){
2457 foreach (SwitchLabel sl in ss.Labels){
2458 if (!sl.ResolveAndReduce (ec, SwitchType)){
2463 if (sl.Label == null){
2465 Report.Error (152, sl.loc, Error152, "default");
2472 object key = sl.Converted;
2474 if (key is Constant)
2475 key = ((Constant) key).GetValue ();
2478 key = NullLiteral.Null;
2480 string lname = null;
2481 if (compare_type == TypeManager.uint64_type){
2482 ulong v = (ulong) key;
2484 if (Elements.Contains (v))
2485 lname = v.ToString ();
2487 Elements.Add (v, sl);
2488 } else if (compare_type == TypeManager.int64_type){
2489 long v = (long) key;
2491 if (Elements.Contains (v))
2492 lname = v.ToString ();
2494 Elements.Add (v, sl);
2495 } else if (compare_type == TypeManager.uint32_type){
2496 uint v = (uint) key;
2498 if (Elements.Contains (v))
2499 lname = v.ToString ();
2501 Elements.Add (v, sl);
2502 } else if (compare_type == TypeManager.char_type){
2503 char v = (char) key;
2505 if (Elements.Contains (v))
2506 lname = v.ToString ();
2508 Elements.Add (v, sl);
2509 } else if (compare_type == TypeManager.byte_type){
2510 byte v = (byte) key;
2512 if (Elements.Contains (v))
2513 lname = v.ToString ();
2515 Elements.Add (v, sl);
2516 } else if (compare_type == TypeManager.sbyte_type){
2517 sbyte v = (sbyte) key;
2519 if (Elements.Contains (v))
2520 lname = v.ToString ();
2522 Elements.Add (v, sl);
2523 } else if (compare_type == TypeManager.short_type){
2524 short v = (short) key;
2526 if (Elements.Contains (v))
2527 lname = v.ToString ();
2529 Elements.Add (v, sl);
2530 } else if (compare_type == TypeManager.ushort_type){
2531 ushort v = (ushort) key;
2533 if (Elements.Contains (v))
2534 lname = v.ToString ();
2536 Elements.Add (v, sl);
2537 } else if (compare_type == TypeManager.string_type){
2538 if (key is NullLiteral){
2539 if (Elements.Contains (NullLiteral.Null))
2542 Elements.Add (NullLiteral.Null, null);
2544 string s = (string) key;
2546 if (Elements.Contains (s))
2549 Elements.Add (s, sl);
2551 } else if (compare_type == TypeManager.int32_type) {
2554 if (Elements.Contains (v))
2555 lname = v.ToString ();
2557 Elements.Add (v, sl);
2558 } else if (compare_type == TypeManager.bool_type) {
2559 bool v = (bool) key;
2561 if (Elements.Contains (v))
2562 lname = v.ToString ();
2564 Elements.Add (v, sl);
2568 throw new Exception ("Unknown switch type!" +
2569 SwitchType + " " + compare_type);
2573 Report.Error (152, sl.loc, Error152, "case " + lname);
2584 void EmitObjectInteger (ILGenerator ig, object k)
2587 IntConstant.EmitInt (ig, (int) k);
2588 else if (k is Constant) {
2589 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2592 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2595 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2597 IntConstant.EmitInt (ig, (int) (long) k);
2598 ig.Emit (OpCodes.Conv_I8);
2601 LongConstant.EmitLong (ig, (long) k);
2603 else if (k is ulong)
2605 if ((ulong) k < (1L<<32))
2607 IntConstant.EmitInt (ig, (int) (long) k);
2608 ig.Emit (OpCodes.Conv_U8);
2612 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2616 IntConstant.EmitInt (ig, (int) ((char) k));
2617 else if (k is sbyte)
2618 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2620 IntConstant.EmitInt (ig, (int) ((byte) k));
2621 else if (k is short)
2622 IntConstant.EmitInt (ig, (int) ((short) k));
2623 else if (k is ushort)
2624 IntConstant.EmitInt (ig, (int) ((ushort) k));
2626 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2628 throw new Exception ("Unhandled case");
2631 // structure used to hold blocks of keys while calculating table switch
2632 class KeyBlock : IComparable
2634 public KeyBlock (long _nFirst)
2636 nFirst = nLast = _nFirst;
2640 public ArrayList rgKeys = null;
2641 // how many items are in the bucket
2642 public int Size = 1;
2645 get { return (int) (nLast - nFirst + 1); }
2647 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2649 return kbLast.nLast - kbFirst.nFirst + 1;
2651 public int CompareTo (object obj)
2653 KeyBlock kb = (KeyBlock) obj;
2654 int nLength = Length;
2655 int nLengthOther = kb.Length;
2656 if (nLengthOther == nLength)
2657 return (int) (kb.nFirst - nFirst);
2658 return nLength - nLengthOther;
2663 /// This method emits code for a lookup-based switch statement (non-string)
2664 /// Basically it groups the cases into blocks that are at least half full,
2665 /// and then spits out individual lookup opcodes for each block.
2666 /// It emits the longest blocks first, and short blocks are just
2667 /// handled with direct compares.
2669 /// <param name="ec"></param>
2670 /// <param name="val"></param>
2671 /// <returns></returns>
2672 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2674 int cElements = Elements.Count;
2675 object [] rgKeys = new object [cElements];
2676 Elements.Keys.CopyTo (rgKeys, 0);
2677 Array.Sort (rgKeys);
2679 // initialize the block list with one element per key
2680 ArrayList rgKeyBlocks = new ArrayList ();
2681 foreach (object key in rgKeys)
2682 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2685 // iteratively merge the blocks while they are at least half full
2686 // there's probably a really cool way to do this with a tree...
2687 while (rgKeyBlocks.Count > 1)
2689 ArrayList rgKeyBlocksNew = new ArrayList ();
2690 kbCurr = (KeyBlock) rgKeyBlocks [0];
2691 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2693 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2694 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2697 kbCurr.nLast = kb.nLast;
2698 kbCurr.Size += kb.Size;
2702 // start a new block
2703 rgKeyBlocksNew.Add (kbCurr);
2707 rgKeyBlocksNew.Add (kbCurr);
2708 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2710 rgKeyBlocks = rgKeyBlocksNew;
2713 // initialize the key lists
2714 foreach (KeyBlock kb in rgKeyBlocks)
2715 kb.rgKeys = new ArrayList ();
2717 // fill the key lists
2719 if (rgKeyBlocks.Count > 0) {
2720 kbCurr = (KeyBlock) rgKeyBlocks [0];
2721 foreach (object key in rgKeys)
2723 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2724 System.Convert.ToInt64 (key) > kbCurr.nLast;
2726 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2727 kbCurr.rgKeys.Add (key);
2731 // sort the blocks so we can tackle the largest ones first
2732 rgKeyBlocks.Sort ();
2734 // okay now we can start...
2735 ILGenerator ig = ec.ig;
2736 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2737 Label lblDefault = ig.DefineLabel ();
2739 Type typeKeys = null;
2740 if (rgKeys.Length > 0)
2741 typeKeys = rgKeys [0].GetType (); // used for conversions
2745 if (TypeManager.IsEnumType (SwitchType))
2746 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2748 compare_type = SwitchType;
2750 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2752 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2753 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2756 foreach (object key in kb.rgKeys)
2758 ig.Emit (OpCodes.Ldloc, val);
2759 EmitObjectInteger (ig, key);
2760 SwitchLabel sl = (SwitchLabel) Elements [key];
2761 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2766 // TODO: if all the keys in the block are the same and there are
2767 // no gaps/defaults then just use a range-check.
2768 if (compare_type == TypeManager.int64_type ||
2769 compare_type == TypeManager.uint64_type)
2771 // TODO: optimize constant/I4 cases
2773 // check block range (could be > 2^31)
2774 ig.Emit (OpCodes.Ldloc, val);
2775 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2776 ig.Emit (OpCodes.Blt, lblDefault);
2777 ig.Emit (OpCodes.Ldloc, val);
2778 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2779 ig.Emit (OpCodes.Bgt, lblDefault);
2782 ig.Emit (OpCodes.Ldloc, val);
2785 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2786 ig.Emit (OpCodes.Sub);
2788 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2793 ig.Emit (OpCodes.Ldloc, val);
2794 int nFirst = (int) kb.nFirst;
2797 IntConstant.EmitInt (ig, nFirst);
2798 ig.Emit (OpCodes.Sub);
2800 else if (nFirst < 0)
2802 IntConstant.EmitInt (ig, -nFirst);
2803 ig.Emit (OpCodes.Add);
2807 // first, build the list of labels for the switch
2809 int cJumps = kb.Length;
2810 Label [] rgLabels = new Label [cJumps];
2811 for (int iJump = 0; iJump < cJumps; iJump++)
2813 object key = kb.rgKeys [iKey];
2814 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2816 SwitchLabel sl = (SwitchLabel) Elements [key];
2817 rgLabels [iJump] = sl.GetILLabel (ec);
2821 rgLabels [iJump] = lblDefault;
2823 // emit the switch opcode
2824 ig.Emit (OpCodes.Switch, rgLabels);
2827 // mark the default for this block
2829 ig.MarkLabel (lblDefault);
2832 // TODO: find the default case and emit it here,
2833 // to prevent having to do the following jump.
2834 // make sure to mark other labels in the default section
2836 // the last default just goes to the end
2837 ig.Emit (OpCodes.Br, lblDefault);
2839 // now emit the code for the sections
2840 bool fFoundDefault = false;
2841 foreach (SwitchSection ss in Sections)
2843 foreach (SwitchLabel sl in ss.Labels)
2845 ig.MarkLabel (sl.GetILLabel (ec));
2846 ig.MarkLabel (sl.GetILLabelCode (ec));
2847 if (sl.Label == null)
2849 ig.MarkLabel (lblDefault);
2850 fFoundDefault = true;
2854 //ig.Emit (OpCodes.Br, lblEnd);
2857 if (!fFoundDefault) {
2858 ig.MarkLabel (lblDefault);
2860 ig.MarkLabel (lblEnd);
2863 // This simple emit switch works, but does not take advantage of the
2865 // TODO: remove non-string logic from here
2866 // TODO: binary search strings?
2868 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2870 ILGenerator ig = ec.ig;
2871 Label end_of_switch = ig.DefineLabel ();
2872 Label next_test = ig.DefineLabel ();
2873 Label null_target = ig.DefineLabel ();
2874 bool default_found = false;
2875 bool first_test = true;
2876 bool pending_goto_end = false;
2878 bool default_at_end = false;
2880 ig.Emit (OpCodes.Ldloc, val);
2882 if (Elements.Contains (NullLiteral.Null)){
2883 ig.Emit (OpCodes.Brfalse, null_target);
2885 ig.Emit (OpCodes.Brfalse, default_target);
2887 ig.Emit (OpCodes.Ldloc, val);
2888 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2889 ig.Emit (OpCodes.Stloc, val);
2891 int section_count = Sections.Count;
2892 for (int section = 0; section < section_count; section++){
2893 SwitchSection ss = (SwitchSection) Sections [section];
2894 Label sec_begin = ig.DefineLabel ();
2896 default_at_end = false;
2898 if (pending_goto_end)
2899 ig.Emit (OpCodes.Br, end_of_switch);
2901 int label_count = ss.Labels.Count;
2902 bool mark_default = false;
2904 for (int label = 0; label < label_count; label++){
2905 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2906 ig.MarkLabel (sl.GetILLabel (ec));
2909 ig.MarkLabel (next_test);
2910 next_test = ig.DefineLabel ();
2913 // If we are the default target
2915 if (sl.Label == null){
2916 if (label+1 == label_count)
2917 default_at_end = true;
2918 mark_default = true;
2919 default_found = true;
2921 object lit = sl.Converted;
2923 if (lit is NullLiteral){
2925 if (label_count == 1)
2926 ig.Emit (OpCodes.Br, next_test);
2930 StringConstant str = (StringConstant) lit;
2932 ig.Emit (OpCodes.Ldloc, val);
2933 ig.Emit (OpCodes.Ldstr, str.Value);
2934 if (label_count == 1)
2935 ig.Emit (OpCodes.Bne_Un, next_test);
2937 if (label+1 == label_count)
2938 ig.Emit (OpCodes.Bne_Un, next_test);
2940 ig.Emit (OpCodes.Beq, sec_begin);
2945 ig.MarkLabel (null_target);
2946 ig.MarkLabel (sec_begin);
2947 foreach (SwitchLabel sl in ss.Labels)
2948 ig.MarkLabel (sl.GetILLabelCode (ec));
2951 ig.MarkLabel (default_target);
2953 pending_goto_end = !ss.Block.HasRet;
2956 ig.MarkLabel (next_test);
2958 if (!default_at_end)
2959 ig.Emit (OpCodes.Br, default_target);
2961 ig.MarkLabel (default_target);
2962 ig.MarkLabel (end_of_switch);
2965 SwitchSection FindSection (SwitchLabel label)
2967 foreach (SwitchSection ss in Sections){
2968 foreach (SwitchLabel sl in ss.Labels){
2977 public override bool Resolve (EmitContext ec)
2979 Expr = Expr.Resolve (ec);
2983 new_expr = SwitchGoverningType (ec, Expr.Type);
2984 if (new_expr == null){
2985 Report.Error (151, loc, "An integer type or string was expected for switch");
2990 SwitchType = new_expr.Type;
2992 if (!CheckSwitch (ec))
2995 Switch old_switch = ec.Switch;
2997 ec.Switch.SwitchType = SwitchType;
2999 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3000 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3002 is_constant = new_expr is Constant;
3004 object key = ((Constant) new_expr).GetValue ();
3005 SwitchLabel label = (SwitchLabel) Elements [key];
3007 constant_section = FindSection (label);
3011 foreach (SwitchSection ss in Sections){
3013 ec.CurrentBranching.CreateSibling (
3014 null, FlowBranching.SiblingType.SwitchSection);
3018 if (is_constant && (ss != constant_section)) {
3019 // If we're a constant switch, we're only emitting
3020 // one single section - mark all the others as
3022 ec.CurrentBranching.CurrentUsageVector.Goto ();
3023 if (!ss.Block.ResolveUnreachable (ec, true))
3026 if (!ss.Block.Resolve (ec))
3032 ec.CurrentBranching.CreateSibling (
3033 null, FlowBranching.SiblingType.SwitchSection);
3035 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3036 ec.Switch = old_switch;
3038 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3044 protected override void DoEmit (EmitContext ec)
3046 ILGenerator ig = ec.ig;
3048 // Store variable for comparission purposes
3051 value = ig.DeclareLocal (SwitchType);
3053 ig.Emit (OpCodes.Stloc, value);
3057 default_target = ig.DefineLabel ();
3060 // Setup the codegen context
3062 Label old_end = ec.LoopEnd;
3063 Switch old_switch = ec.Switch;
3065 ec.LoopEnd = ig.DefineLabel ();
3070 if (constant_section != null)
3071 constant_section.Block.Emit (ec);
3072 } else if (SwitchType == TypeManager.string_type)
3073 SimpleSwitchEmit (ec, value);
3075 TableSwitchEmit (ec, value);
3077 // Restore context state.
3078 ig.MarkLabel (ec.LoopEnd);
3081 // Restore the previous context
3083 ec.LoopEnd = old_end;
3084 ec.Switch = old_switch;
3088 public abstract class ExceptionStatement : Statement
3090 public abstract void EmitFinally (EmitContext ec);
3092 protected bool emit_finally = true;
3093 ArrayList parent_vectors;
3095 protected void DoEmitFinally (EmitContext ec)
3098 ec.ig.BeginFinallyBlock ();
3100 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3104 protected void ResolveFinally (FlowBranchingException branching)
3106 emit_finally = branching.EmitFinally;
3108 branching.Parent.StealFinallyClauses (ref parent_vectors);
3112 public class Lock : ExceptionStatement {
3114 Statement Statement;
3117 public Lock (Expression expr, Statement stmt, Location l)
3124 public override bool Resolve (EmitContext ec)
3126 expr = expr.Resolve (ec);
3130 if (expr.Type.IsValueType){
3131 Error (185, "lock statement requires the expression to be " +
3132 " a reference type (type is: `{0}'",
3133 TypeManager.CSharpName (expr.Type));
3137 FlowBranchingException branching = ec.StartFlowBranching (this);
3138 bool ok = Statement.Resolve (ec);
3140 ec.KillFlowBranching ();
3144 ResolveFinally (branching);
3146 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3147 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3148 // Unfortunately, System.Reflection.Emit automatically emits
3149 // a leave to the end of the finally block.
3150 // This is a problem if `returns' is true since we may jump
3151 // to a point after the end of the method.
3152 // As a workaround, emit an explicit ret here.
3153 ec.NeedReturnLabel ();
3159 protected override void DoEmit (EmitContext ec)
3161 Type type = expr.Type;
3163 ILGenerator ig = ec.ig;
3164 temp = ig.DeclareLocal (type);
3167 ig.Emit (OpCodes.Dup);
3168 ig.Emit (OpCodes.Stloc, temp);
3169 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3173 ig.BeginExceptionBlock ();
3174 Statement.Emit (ec);
3179 ig.EndExceptionBlock ();
3182 public override void EmitFinally (EmitContext ec)
3184 ILGenerator ig = ec.ig;
3185 ig.Emit (OpCodes.Ldloc, temp);
3186 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3190 public class Unchecked : Statement {
3191 public readonly Block Block;
3193 public Unchecked (Block b)
3199 public override bool Resolve (EmitContext ec)
3201 bool previous_state = ec.CheckState;
3202 bool previous_state_const = ec.ConstantCheckState;
3204 ec.CheckState = false;
3205 ec.ConstantCheckState = false;
3206 bool ret = Block.Resolve (ec);
3207 ec.CheckState = previous_state;
3208 ec.ConstantCheckState = previous_state_const;
3213 protected override void DoEmit (EmitContext ec)
3215 bool previous_state = ec.CheckState;
3216 bool previous_state_const = ec.ConstantCheckState;
3218 ec.CheckState = false;
3219 ec.ConstantCheckState = false;
3221 ec.CheckState = previous_state;
3222 ec.ConstantCheckState = previous_state_const;
3226 public class Checked : Statement {
3227 public readonly Block Block;
3229 public Checked (Block b)
3232 b.Unchecked = false;
3235 public override bool Resolve (EmitContext ec)
3237 bool previous_state = ec.CheckState;
3238 bool previous_state_const = ec.ConstantCheckState;
3240 ec.CheckState = true;
3241 ec.ConstantCheckState = true;
3242 bool ret = Block.Resolve (ec);
3243 ec.CheckState = previous_state;
3244 ec.ConstantCheckState = previous_state_const;
3249 protected override void DoEmit (EmitContext ec)
3251 bool previous_state = ec.CheckState;
3252 bool previous_state_const = ec.ConstantCheckState;
3254 ec.CheckState = true;
3255 ec.ConstantCheckState = true;
3257 ec.CheckState = previous_state;
3258 ec.ConstantCheckState = previous_state_const;
3262 public class Unsafe : Statement {
3263 public readonly Block Block;
3265 public Unsafe (Block b)
3268 Block.Unsafe = true;
3271 public override bool Resolve (EmitContext ec)
3273 bool previous_state = ec.InUnsafe;
3277 val = Block.Resolve (ec);
3278 ec.InUnsafe = previous_state;
3283 protected override void DoEmit (EmitContext ec)
3285 bool previous_state = ec.InUnsafe;
3289 ec.InUnsafe = previous_state;
3296 public class Fixed : Statement {
3298 ArrayList declarators;
3299 Statement statement;
3304 abstract class Emitter
3306 protected LocalInfo vi;
3307 protected Expression converted;
3309 protected Emitter (Expression expr, LocalInfo li)
3315 public abstract void Emit (EmitContext ec);
3316 public abstract void EmitExit (ILGenerator ig);
3319 class ExpressionEmitter: Emitter {
3320 public ExpressionEmitter (Expression converted, LocalInfo li) :
3321 base (converted, li)
3325 public override void Emit (EmitContext ec) {
3327 // Store pointer in pinned location
3329 converted.Emit (ec);
3330 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3333 public override void EmitExit (ILGenerator ig)
3335 ig.Emit (OpCodes.Ldc_I4_0);
3336 ig.Emit (OpCodes.Conv_U);
3337 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3341 class StringEmitter: Emitter {
3342 LocalBuilder pinned_string;
3345 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3351 public override void Emit (EmitContext ec)
3353 ILGenerator ig = ec.ig;
3354 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3356 converted.Emit (ec);
3357 ig.Emit (OpCodes.Stloc, pinned_string);
3359 Expression sptr = new StringPtr (pinned_string, loc);
3360 converted = Convert.ImplicitConversionRequired (
3361 ec, sptr, vi.VariableType, loc);
3363 if (converted == null)
3366 converted.Emit (ec);
3367 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3370 public override void EmitExit(ILGenerator ig)
3372 ig.Emit (OpCodes.Ldnull);
3373 ig.Emit (OpCodes.Stloc, pinned_string);
3377 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3380 declarators = decls;
3385 public override bool Resolve (EmitContext ec)
3388 Expression.UnsafeError (loc);
3392 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3396 expr_type = texpr.Type;
3398 CheckObsolete (expr_type);
3400 if (ec.RemapToProxy){
3401 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3405 data = new Emitter [declarators.Count];
3407 if (!expr_type.IsPointer){
3408 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3413 foreach (Pair p in declarators){
3414 LocalInfo vi = (LocalInfo) p.First;
3415 Expression e = (Expression) p.Second;
3417 vi.VariableInfo.SetAssigned (ec);
3421 // The rules for the possible declarators are pretty wise,
3422 // but the production on the grammar is more concise.
3424 // So we have to enforce these rules here.
3426 // We do not resolve before doing the case 1 test,
3427 // because the grammar is explicit in that the token &
3428 // is present, so we need to test for this particular case.
3432 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3437 // Case 1: & object.
3439 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3440 Expression child = ((Unary) e).Expr;
3442 if (child is ParameterReference || child is LocalVariableReference){
3445 "No need to use fixed statement for parameters or " +
3446 "local variable declarations (address is already " +
3451 ec.InFixedInitializer = true;
3453 ec.InFixedInitializer = false;
3457 child = ((Unary) e).Expr;
3459 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3462 data [i] = new ExpressionEmitter (e, vi);
3468 ec.InFixedInitializer = true;
3470 ec.InFixedInitializer = false;
3477 if (e.Type.IsArray){
3478 Type array_type = TypeManager.GetElementType (e.Type);
3481 // Provided that array_type is unmanaged,
3483 if (!TypeManager.VerifyUnManaged (array_type, loc))
3487 // and T* is implicitly convertible to the
3488 // pointer type given in the fixed statement.
3490 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3492 Expression converted = Convert.ImplicitConversionRequired (
3493 ec, array_ptr, vi.VariableType, loc);
3494 if (converted == null)
3497 data [i] = new ExpressionEmitter (converted, vi);
3506 if (e.Type == TypeManager.string_type){
3507 data [i] = new StringEmitter (e, vi, loc);
3512 // Case 4: fixed buffer
3513 FieldExpr fe = e as FieldExpr;
3515 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3517 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3519 Expression converted = Convert.ImplicitConversionRequired (
3520 ec, fixed_buffer_ptr, vi.VariableType, loc);
3521 if (converted == null)
3524 data [i] = new ExpressionEmitter (converted, vi);
3532 // For other cases, flag a `this is already fixed expression'
3534 if (e is LocalVariableReference || e is ParameterReference ||
3535 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3537 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3541 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3545 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3547 if (!statement.Resolve (ec)) {
3548 ec.KillFlowBranching ();
3552 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3553 has_ret = reachability.IsUnreachable;
3558 protected override void DoEmit (EmitContext ec)
3560 for (int i = 0; i < data.Length; i++) {
3564 statement.Emit (ec);
3569 ILGenerator ig = ec.ig;
3572 // Clear the pinned variable
3574 for (int i = 0; i < data.Length; i++) {
3575 data [i].EmitExit (ig);
3580 public class Catch: Statement {
3581 public readonly string Name;
3582 public readonly Block Block;
3584 Expression type_expr;
3587 public Catch (Expression type, string name, Block block, Location l)
3595 public Type CatchType {
3601 public bool IsGeneral {
3603 return type_expr == null;
3607 protected override void DoEmit(EmitContext ec)
3611 public override bool Resolve (EmitContext ec)
3613 bool was_catch = ec.InCatch;
3616 if (type_expr != null) {
3617 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3621 type = te.ResolveType (ec);
3623 CheckObsolete (type);
3625 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3626 Error (155, "The type caught or thrown must be derived from System.Exception");
3632 return Block.Resolve (ec);
3635 ec.InCatch = was_catch;
3640 public class Try : ExceptionStatement {
3641 public readonly Block Fini, Block;
3642 public readonly ArrayList Specific;
3643 public readonly Catch General;
3645 bool need_exc_block;
3648 // specific, general and fini might all be null.
3650 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3652 if (specific == null && general == null){
3653 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3657 this.Specific = specific;
3658 this.General = general;
3663 public override bool Resolve (EmitContext ec)
3667 FlowBranchingException branching = ec.StartFlowBranching (this);
3669 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3671 if (!Block.Resolve (ec))
3674 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3676 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3678 Type[] prevCatches = new Type [Specific.Count];
3680 foreach (Catch c in Specific){
3681 ec.CurrentBranching.CreateSibling (
3682 c.Block, FlowBranching.SiblingType.Catch);
3684 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3686 if (c.Name != null) {
3687 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3689 throw new Exception ();
3691 vi.VariableInfo = null;
3694 if (!c.Resolve (ec))
3697 Type resolvedType = c.CatchType;
3698 for (int ii = 0; ii < last_index; ++ii) {
3699 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3700 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3705 prevCatches [last_index++] = resolvedType;
3706 need_exc_block = true;
3709 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3711 if (General != null){
3712 ec.CurrentBranching.CreateSibling (
3713 General.Block, FlowBranching.SiblingType.Catch);
3715 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3717 if (!General.Resolve (ec))
3720 need_exc_block = true;
3723 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3727 ec.CurrentBranching.CreateSibling (
3728 Fini, FlowBranching.SiblingType.Finally);
3730 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3731 bool was_finally = ec.InFinally;
3732 ec.InFinally = true;
3733 if (!Fini.Resolve (ec))
3735 ec.InFinally = was_finally;
3738 ResolveFinally (branching);
3739 need_exc_block |= emit_finally;
3741 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3743 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3745 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3747 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3748 // Unfortunately, System.Reflection.Emit automatically emits
3749 // a leave to the end of the finally block. This is a problem
3750 // if `returns' is true since we may jump to a point after the
3751 // end of the method.
3752 // As a workaround, emit an explicit ret here.
3753 ec.NeedReturnLabel ();
3759 protected override void DoEmit (EmitContext ec)
3761 ILGenerator ig = ec.ig;
3764 ig.BeginExceptionBlock ();
3767 foreach (Catch c in Specific){
3770 ig.BeginCatchBlock (c.CatchType);
3772 if (c.Name != null){
3773 vi = c.Block.GetLocalInfo (c.Name);
3775 throw new Exception ("Variable does not exist in this block");
3777 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3779 ig.Emit (OpCodes.Pop);
3784 if (General != null){
3785 ig.BeginCatchBlock (TypeManager.object_type);
3786 ig.Emit (OpCodes.Pop);
3787 General.Block.Emit (ec);
3792 ig.EndExceptionBlock ();
3795 public override void EmitFinally (EmitContext ec)
3802 public bool HasCatch
3805 return General != null || Specific.Count > 0;
3810 public class Using : ExceptionStatement {
3811 object expression_or_block;
3812 Statement Statement;
3817 Expression [] resolved_vars;
3818 Expression [] converted_vars;
3819 ExpressionStatement [] assign;
3820 LocalBuilder local_copy;
3822 public Using (object expression_or_block, Statement stmt, Location l)
3824 this.expression_or_block = expression_or_block;
3830 // Resolves for the case of using using a local variable declaration.
3832 bool ResolveLocalVariableDecls (EmitContext ec)
3836 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3840 expr_type = texpr.Type;
3843 // The type must be an IDisposable or an implicit conversion
3846 converted_vars = new Expression [var_list.Count];
3847 resolved_vars = new Expression [var_list.Count];
3848 assign = new ExpressionStatement [var_list.Count];
3850 bool need_conv = !TypeManager.ImplementsInterface (
3851 expr_type, TypeManager.idisposable_type);
3853 foreach (DictionaryEntry e in var_list){
3854 Expression var = (Expression) e.Key;
3856 var = var.ResolveLValue (ec, new EmptyExpression ());
3860 resolved_vars [i] = var;
3867 converted_vars [i] = Convert.ImplicitConversionRequired (
3868 ec, var, TypeManager.idisposable_type, loc);
3870 if (converted_vars [i] == null)
3877 foreach (DictionaryEntry e in var_list){
3878 Expression var = resolved_vars [i];
3879 Expression new_expr = (Expression) e.Value;
3882 a = new Assign (var, new_expr, loc);
3888 converted_vars [i] = var;
3889 assign [i] = (ExpressionStatement) a;
3896 bool ResolveExpression (EmitContext ec)
3898 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3899 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3900 Report.Error (1674, loc, "'{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3901 TypeManager.CSharpName (expr_type));
3910 // Emits the code for the case of using using a local variable declaration.
3912 void EmitLocalVariableDecls (EmitContext ec)
3914 ILGenerator ig = ec.ig;
3917 for (i = 0; i < assign.Length; i++) {
3918 assign [i].EmitStatement (ec);
3921 ig.BeginExceptionBlock ();
3923 Statement.Emit (ec);
3925 var_list.Reverse ();
3930 void EmitLocalVariableDeclFinally (EmitContext ec)
3932 ILGenerator ig = ec.ig;
3934 int i = assign.Length;
3935 for (int ii = 0; ii < var_list.Count; ++ii){
3936 Expression var = resolved_vars [--i];
3937 Label skip = ig.DefineLabel ();
3939 ig.BeginFinallyBlock ();
3941 if (!var.Type.IsValueType) {
3943 ig.Emit (OpCodes.Brfalse, skip);
3944 converted_vars [i].Emit (ec);
3945 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3947 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3949 if (!(ml is MethodGroupExpr)) {
3951 ig.Emit (OpCodes.Box, var.Type);
3952 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3954 MethodInfo mi = null;
3956 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3957 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3964 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3968 IMemoryLocation mloc = (IMemoryLocation) var;
3970 mloc.AddressOf (ec, AddressOp.Load);
3971 ig.Emit (OpCodes.Call, mi);
3975 ig.MarkLabel (skip);
3978 ig.EndExceptionBlock ();
3980 ig.BeginFinallyBlock ();
3985 void EmitExpression (EmitContext ec)
3988 // Make a copy of the expression and operate on that.
3990 ILGenerator ig = ec.ig;
3991 local_copy = ig.DeclareLocal (expr_type);
3996 ig.Emit (OpCodes.Stloc, local_copy);
3999 ig.BeginExceptionBlock ();
4001 Statement.Emit (ec);
4005 ig.EndExceptionBlock ();
4008 void EmitExpressionFinally (EmitContext ec)
4010 ILGenerator ig = ec.ig;
4011 if (!local_copy.LocalType.IsValueType) {
4012 Label skip = ig.DefineLabel ();
4013 ig.Emit (OpCodes.Ldloc, local_copy);
4014 ig.Emit (OpCodes.Brfalse, skip);
4015 ig.Emit (OpCodes.Ldloc, local_copy);
4016 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4017 ig.MarkLabel (skip);
4019 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4021 if (!(ml is MethodGroupExpr)) {
4022 ig.Emit (OpCodes.Ldloc, local_copy);
4023 ig.Emit (OpCodes.Box, local_copy.LocalType);
4024 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4026 MethodInfo mi = null;
4028 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4029 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4036 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4040 ig.Emit (OpCodes.Ldloca, local_copy);
4041 ig.Emit (OpCodes.Call, mi);
4046 public override bool Resolve (EmitContext ec)
4048 if (expression_or_block is DictionaryEntry){
4049 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4050 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4052 if (!ResolveLocalVariableDecls (ec))
4055 } else if (expression_or_block is Expression){
4056 expr = (Expression) expression_or_block;
4058 expr = expr.Resolve (ec);
4062 expr_type = expr.Type;
4064 if (!ResolveExpression (ec))
4068 FlowBranchingException branching = ec.StartFlowBranching (this);
4070 bool ok = Statement.Resolve (ec);
4073 ec.KillFlowBranching ();
4077 ResolveFinally (branching);
4078 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4080 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4081 // Unfortunately, System.Reflection.Emit automatically emits a leave
4082 // to the end of the finally block. This is a problem if `returns'
4083 // is true since we may jump to a point after the end of the method.
4084 // As a workaround, emit an explicit ret here.
4085 ec.NeedReturnLabel ();
4091 protected override void DoEmit (EmitContext ec)
4093 if (expression_or_block is DictionaryEntry)
4094 EmitLocalVariableDecls (ec);
4095 else if (expression_or_block is Expression)
4096 EmitExpression (ec);
4099 public override void EmitFinally (EmitContext ec)
4101 if (expression_or_block is DictionaryEntry)
4102 EmitLocalVariableDeclFinally (ec);
4103 else if (expression_or_block is Expression)
4104 EmitExpressionFinally (ec);
4109 /// Implementation of the foreach C# statement
4111 public class Foreach : ExceptionStatement {
4113 Expression variable;
4115 Statement statement;
4116 ForeachHelperMethods hm;
4117 Expression empty, conv;
4118 Type array_type, element_type;
4120 VariableStorage enumerator;
4122 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4123 Statement stmt, Location l)
4126 this.variable = var;
4132 public override bool Resolve (EmitContext ec)
4134 expr = expr.Resolve (ec);
4138 if (expr is NullLiteral) {
4139 Report.Error (186, expr.Location, "Use of null is not valid in this context");
4143 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4147 var_type = texpr.Type;
4150 // We need an instance variable. Not sure this is the best
4151 // way of doing this.
4153 // FIXME: When we implement propertyaccess, will those turn
4154 // out to return values in ExprClass? I think they should.
4156 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4157 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4158 error1579 (expr.Type);
4162 if (expr.Type.IsArray) {
4163 array_type = expr.Type;
4164 element_type = TypeManager.GetElementType (array_type);
4166 empty = new EmptyExpression (element_type);
4168 hm = ProbeCollectionType (ec, expr.Type);
4170 error1579 (expr.Type);
4174 array_type = expr.Type;
4175 element_type = hm.element_type;
4177 empty = new EmptyExpression (hm.element_type);
4182 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4183 ec.CurrentBranching.CreateSibling ();
4187 // FIXME: maybe we can apply the same trick we do in the
4188 // array handling to avoid creating empty and conv in some cases.
4190 // Although it is not as important in this case, as the type
4191 // will not likely be object (what the enumerator will return).
4193 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4197 variable = variable.ResolveLValue (ec, empty);
4198 if (variable == null)
4201 bool disposable = (hm != null) && hm.is_disposable;
4202 FlowBranchingException branching = null;
4204 branching = ec.StartFlowBranching (this);
4206 if (!statement.Resolve (ec))
4210 ResolveFinally (branching);
4211 ec.EndFlowBranching ();
4213 emit_finally = true;
4215 ec.EndFlowBranching ();
4221 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4223 static MethodInfo FetchMethodMoveNext (Type t)
4225 MemberList move_next_list;
4227 move_next_list = TypeContainer.FindMembers (
4228 t, MemberTypes.Method,
4229 BindingFlags.Public | BindingFlags.Instance,
4230 Type.FilterName, "MoveNext");
4231 if (move_next_list.Count == 0)
4234 foreach (MemberInfo m in move_next_list){
4235 MethodInfo mi = (MethodInfo) m;
4238 args = TypeManager.GetArgumentTypes (mi);
4239 if (args != null && args.Length == 0){
4240 if (TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type)
4248 // Retrieves a `public T get_Current ()' method from the Type `t'
4250 static MethodInfo FetchMethodGetCurrent (Type t)
4252 MemberList get_current_list;
4254 get_current_list = TypeContainer.FindMembers (
4255 t, MemberTypes.Method,
4256 BindingFlags.Public | BindingFlags.Instance,
4257 Type.FilterName, "get_Current");
4258 if (get_current_list.Count == 0)
4261 foreach (MemberInfo m in get_current_list){
4262 MethodInfo mi = (MethodInfo) m;
4265 args = TypeManager.GetArgumentTypes (mi);
4266 if (args != null && args.Length == 0)
4273 // Retrieves a `public void Dispose ()' method from the Type `t'
4275 static MethodInfo FetchMethodDispose (Type t)
4277 MemberList dispose_list;
4279 dispose_list = TypeContainer.FindMembers (
4280 t, MemberTypes.Method,
4281 BindingFlags.Public | BindingFlags.Instance,
4282 Type.FilterName, "Dispose");
4283 if (dispose_list.Count == 0)
4286 foreach (MemberInfo m in dispose_list){
4287 MethodInfo mi = (MethodInfo) m;
4290 args = TypeManager.GetArgumentTypes (mi);
4291 if (args != null && args.Length == 0){
4292 if (mi.ReturnType == TypeManager.void_type)
4300 // This struct records the helper methods used by the Foreach construct
4302 class ForeachHelperMethods {
4303 public EmitContext ec;
4304 public MethodInfo get_enumerator;
4305 public MethodInfo move_next;
4306 public MethodInfo get_current;
4307 public Type element_type;
4308 public Type enumerator_type;
4309 public bool is_disposable;
4311 public ForeachHelperMethods (EmitContext ec)
4314 this.element_type = TypeManager.object_type;
4315 this.enumerator_type = TypeManager.ienumerator_type;
4316 this.is_disposable = true;
4320 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4325 if (!(m is MethodInfo))
4328 if (m.Name != "GetEnumerator")
4331 MethodInfo mi = (MethodInfo) m;
4332 Type [] args = TypeManager.GetArgumentTypes (mi);
4334 if (args.Length != 0)
4337 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4339 // Check whether GetEnumerator is public
4340 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4343 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4345 // Apply the same optimization as MS: skip the GetEnumerator
4346 // returning an IEnumerator, and use the one returning a
4347 // CharEnumerator instead. This allows us to avoid the
4348 // try-finally block and the boxing.
4353 // Ok, we can access it, now make sure that we can do something
4354 // with this `GetEnumerator'
4357 Type return_type = mi.ReturnType;
4358 if (mi.ReturnType == TypeManager.ienumerator_type ||
4359 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4360 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4363 // If it is not an interface, lets try to find the methods ourselves.
4364 // For example, if we have:
4365 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4366 // We can avoid the iface call. This is a runtime perf boost.
4367 // even bigger if we have a ValueType, because we avoid the cost
4370 // We have to make sure that both methods exist for us to take
4371 // this path. If one of the methods does not exist, we will just
4372 // use the interface. Sadly, this complex if statement is the only
4373 // way I could do this without a goto
4376 if (return_type.IsInterface ||
4377 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4378 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4380 hm.move_next = TypeManager.bool_movenext_void;
4381 hm.get_current = TypeManager.object_getcurrent_void;
4388 // Ok, so they dont return an IEnumerable, we will have to
4389 // find if they support the GetEnumerator pattern.
4392 hm.move_next = FetchMethodMoveNext (return_type);
4393 if (hm.move_next == null)
4396 hm.get_current = FetchMethodGetCurrent (return_type);
4397 if (hm.get_current == null)
4401 hm.element_type = hm.get_current.ReturnType;
4402 hm.enumerator_type = return_type;
4403 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4404 TypeManager.ImplementsInterface (
4405 hm.enumerator_type, TypeManager.idisposable_type);
4411 /// This filter is used to find the GetEnumerator method
4412 /// on which IEnumerator operates
4414 static MemberFilter FilterEnumerator;
4418 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4421 void error1579 (Type t)
4423 Report.Error (1579, loc,
4424 "foreach statement cannot operate on variables of type `" +
4425 t.FullName + "' because that class does not provide a " +
4426 " GetEnumerator method or it is inaccessible");
4429 static bool TryType (Type t, ForeachHelperMethods hm)
4433 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4434 BindingFlags.Public | BindingFlags.NonPublic |
4435 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4436 FilterEnumerator, hm);
4441 hm.get_enumerator = (MethodInfo) mi [0];
4446 // Looks for a usable GetEnumerator in the Type, and if found returns
4447 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4449 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4451 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4453 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4454 if (TryType (tt, hm))
4460 // Now try to find the method in the interfaces
4463 Type [] ifaces = t.GetInterfaces ();
4465 foreach (Type i in ifaces){
4466 if (TryType (i, hm))
4471 // Since TypeBuilder.GetInterfaces only returns the interface
4472 // types for this type, we have to keep looping, but once
4473 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4474 // done, because it returns all the types
4476 if ((t is TypeBuilder))
4486 // FIXME: possible optimization.
4487 // We might be able to avoid creating `empty' if the type is the sam
4489 bool EmitCollectionForeach (EmitContext ec)
4491 ILGenerator ig = ec.ig;
4493 enumerator = new VariableStorage (ec, hm.enumerator_type);
4494 enumerator.EmitThis (ig);
4496 // Instantiate the enumerator
4498 if (expr.Type.IsValueType){
4499 IMemoryLocation ml = expr as IMemoryLocation;
4500 // Load the address of the value type.
4502 // This happens if, for example, you have a property
4503 // returning a struct which is IEnumerable
4504 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4506 ig.Emit (OpCodes.Stloc, t);
4507 ig.Emit (OpCodes.Ldloca, t);
4508 ec.FreeTemporaryLocal (t, expr.Type);
4510 ml.AddressOf (ec, AddressOp.Load);
4514 if (hm.get_enumerator.DeclaringType.IsValueType) {
4515 // the method is declared on the value type
4516 ig.Emit (OpCodes.Call, hm.get_enumerator);
4518 // it is an interface method, so we must box
4519 ig.Emit (OpCodes.Box, expr.Type);
4520 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4524 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4526 enumerator.EmitStore (ig);
4529 // Protect the code in a try/finalize block, so that
4530 // if the beast implement IDisposable, we get rid of it
4532 if (hm.is_disposable && emit_finally)
4533 ig.BeginExceptionBlock ();
4535 Label end_try = ig.DefineLabel ();
4537 ig.MarkLabel (ec.LoopBegin);
4539 enumerator.EmitCall (ig, hm.move_next);
4541 ig.Emit (OpCodes.Brfalse, end_try);
4544 ig.Emit (OpCodes.Ldarg_0);
4546 enumerator.EmitCall (ig, hm.get_current);
4550 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4552 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4554 statement.Emit (ec);
4555 ig.Emit (OpCodes.Br, ec.LoopBegin);
4556 ig.MarkLabel (end_try);
4558 // The runtime provides this for us.
4559 // ig.Emit (OpCodes.Leave, end);
4562 // Now the finally block
4564 if (hm.is_disposable) {
4567 ig.EndExceptionBlock ();
4570 ig.MarkLabel (ec.LoopEnd);
4574 public override void EmitFinally (EmitContext ec)
4576 ILGenerator ig = ec.ig;
4578 if (hm.enumerator_type.IsValueType) {
4579 enumerator.EmitThis (ig);
4581 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4583 enumerator.EmitLoadAddress (ig);
4584 ig.Emit (OpCodes.Call, mi);
4586 enumerator.EmitLoad (ig);
4587 ig.Emit (OpCodes.Box, hm.enumerator_type);
4588 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4591 Label call_dispose = ig.DefineLabel ();
4593 enumerator.EmitThis (ig);
4594 enumerator.EmitLoad (ig);
4595 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4596 ig.Emit (OpCodes.Dup);
4597 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4598 ig.Emit (OpCodes.Pop);
4600 Label end_finally = ig.DefineLabel ();
4601 ig.Emit (OpCodes.Br, end_finally);
4603 ig.MarkLabel (call_dispose);
4604 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4605 ig.MarkLabel (end_finally);
4608 ig.Emit (OpCodes.Endfinally);
4613 // FIXME: possible optimization.
4614 // We might be able to avoid creating `empty' if the type is the sam
4616 bool EmitArrayForeach (EmitContext ec)
4618 int rank = array_type.GetArrayRank ();
4619 ILGenerator ig = ec.ig;
4621 VariableStorage copy = new VariableStorage (ec, array_type);
4624 // Make our copy of the array
4628 copy.EmitStore (ig);
4631 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4635 counter.EmitThis (ig);
4636 ig.Emit (OpCodes.Ldc_I4_0);
4637 counter.EmitStore (ig);
4638 test = ig.DefineLabel ();
4639 ig.Emit (OpCodes.Br, test);
4641 loop = ig.DefineLabel ();
4642 ig.MarkLabel (loop);
4645 ig.Emit (OpCodes.Ldarg_0);
4649 counter.EmitThis (ig);
4650 counter.EmitLoad (ig);
4653 // Load the value, we load the value using the underlying type,
4654 // then we use the variable.EmitAssign to load using the proper cast.
4656 ArrayAccess.EmitLoadOpcode (ig, element_type);
4659 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4661 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4663 statement.Emit (ec);
4665 ig.MarkLabel (ec.LoopBegin);
4666 counter.EmitThis (ig);
4667 counter.EmitThis (ig);
4668 counter.EmitLoad (ig);
4669 ig.Emit (OpCodes.Ldc_I4_1);
4670 ig.Emit (OpCodes.Add);
4671 counter.EmitStore (ig);
4673 ig.MarkLabel (test);
4674 counter.EmitThis (ig);
4675 counter.EmitLoad (ig);
4678 ig.Emit (OpCodes.Ldlen);
4679 ig.Emit (OpCodes.Conv_I4);
4680 ig.Emit (OpCodes.Blt, loop);
4682 VariableStorage [] dim_len = new VariableStorage [rank];
4683 VariableStorage [] dim_count = new VariableStorage [rank];
4684 Label [] loop = new Label [rank];
4685 Label [] test = new Label [rank];
4688 for (dim = 0; dim < rank; dim++){
4689 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4690 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4691 test [dim] = ig.DefineLabel ();
4692 loop [dim] = ig.DefineLabel ();
4695 for (dim = 0; dim < rank; dim++){
4696 dim_len [dim].EmitThis (ig);
4699 IntLiteral.EmitInt (ig, dim);
4700 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4701 dim_len [dim].EmitStore (ig);
4705 for (dim = 0; dim < rank; dim++){
4706 dim_count [dim].EmitThis (ig);
4707 ig.Emit (OpCodes.Ldc_I4_0);
4708 dim_count [dim].EmitStore (ig);
4709 ig.Emit (OpCodes.Br, test [dim]);
4710 ig.MarkLabel (loop [dim]);
4714 ig.Emit (OpCodes.Ldarg_0);
4718 for (dim = 0; dim < rank; dim++){
4719 dim_count [dim].EmitThis (ig);
4720 dim_count [dim].EmitLoad (ig);
4724 // FIXME: Maybe we can cache the computation of `get'?
4726 Type [] args = new Type [rank];
4729 for (int i = 0; i < rank; i++)
4730 args [i] = TypeManager.int32_type;
4732 ModuleBuilder mb = CodeGen.Module.Builder;
4733 get = mb.GetArrayMethod (
4735 CallingConventions.HasThis| CallingConventions.Standard,
4737 ig.Emit (OpCodes.Call, get);
4740 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4742 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4743 statement.Emit (ec);
4744 ig.MarkLabel (ec.LoopBegin);
4745 for (dim = rank - 1; dim >= 0; dim--){
4746 dim_count [dim].EmitThis (ig);
4747 dim_count [dim].EmitThis (ig);
4748 dim_count [dim].EmitLoad (ig);
4749 ig.Emit (OpCodes.Ldc_I4_1);
4750 ig.Emit (OpCodes.Add);
4751 dim_count [dim].EmitStore (ig);
4753 ig.MarkLabel (test [dim]);
4754 dim_count [dim].EmitThis (ig);
4755 dim_count [dim].EmitLoad (ig);
4756 dim_len [dim].EmitThis (ig);
4757 dim_len [dim].EmitLoad (ig);
4758 ig.Emit (OpCodes.Blt, loop [dim]);
4761 ig.MarkLabel (ec.LoopEnd);
4766 protected override void DoEmit (EmitContext ec)
4768 ILGenerator ig = ec.ig;
4770 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4771 ec.LoopBegin = ig.DefineLabel ();
4772 ec.LoopEnd = ig.DefineLabel ();
4775 EmitCollectionForeach (ec);
4777 EmitArrayForeach (ec);
4779 ec.LoopBegin = old_begin;
4780 ec.LoopEnd = old_end;