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;
17 using System.Collections;
18 using System.Collections.Specialized;
20 namespace Mono.CSharp {
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.
50 Report.Warning (162, 2, loc, "Unreachable code detected");
52 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
53 bool ok = Resolve (ec);
54 ec.KillFlowBranching ();
60 /// Return value indicates whether all code paths emitted return.
62 protected abstract void DoEmit (EmitContext ec);
65 /// Utility wrapper routine for Error, just to beautify the code
67 public void Error (int error, string format, params object[] args)
69 Error (error, String.Format (format, args));
72 public void Error (int error, string s)
75 Report.Error (error, loc, s);
77 Report.Error (error, s);
81 /// Return value indicates whether all code paths emitted return.
83 public virtual void Emit (EmitContext ec)
90 public sealed class EmptyStatement : Statement {
92 private EmptyStatement () {}
94 public static readonly EmptyStatement Value = new EmptyStatement ();
96 public override bool Resolve (EmitContext ec)
101 public override bool ResolveUnreachable (EmitContext ec, bool warn)
106 protected override void DoEmit (EmitContext ec)
111 public class If : Statement {
113 public Statement TrueStatement;
114 public Statement FalseStatement;
118 public If (Expression expr, Statement trueStatement, Location l)
121 TrueStatement = trueStatement;
125 public If (Expression expr,
126 Statement trueStatement,
127 Statement falseStatement,
131 TrueStatement = trueStatement;
132 FalseStatement = falseStatement;
136 public override bool Resolve (EmitContext ec)
140 Report.Debug (1, "START IF BLOCK", loc);
142 expr = Expression.ResolveBoolean (ec, expr, loc);
148 Assign ass = expr as Assign;
149 if (ass != null && ass.Source is Constant) {
150 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
154 // Dead code elimination
156 if (expr is BoolConstant){
157 bool take = ((BoolConstant) expr).Value;
160 if (!TrueStatement.Resolve (ec))
163 if ((FalseStatement != null) &&
164 !FalseStatement.ResolveUnreachable (ec, true))
166 FalseStatement = null;
168 if (!TrueStatement.ResolveUnreachable (ec, true))
170 TrueStatement = null;
172 if ((FalseStatement != null) &&
173 !FalseStatement.Resolve (ec))
180 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
182 ok &= TrueStatement.Resolve (ec);
184 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
186 ec.CurrentBranching.CreateSibling ();
188 if (FalseStatement != null)
189 ok &= FalseStatement.Resolve (ec);
191 ec.EndFlowBranching ();
193 Report.Debug (1, "END IF BLOCK", loc);
198 protected override void DoEmit (EmitContext ec)
200 ILGenerator ig = ec.ig;
201 Label false_target = ig.DefineLabel ();
205 // If we're a boolean expression, Resolve() already
206 // eliminated dead code for us.
208 if (expr is BoolConstant){
209 bool take = ((BoolConstant) expr).Value;
212 TrueStatement.Emit (ec);
213 else if (FalseStatement != null)
214 FalseStatement.Emit (ec);
219 expr.EmitBranchable (ec, false_target, false);
221 TrueStatement.Emit (ec);
223 if (FalseStatement != null){
224 bool branch_emitted = false;
226 end = ig.DefineLabel ();
228 ig.Emit (OpCodes.Br, end);
229 branch_emitted = true;
232 ig.MarkLabel (false_target);
233 FalseStatement.Emit (ec);
238 ig.MarkLabel (false_target);
243 public class Do : Statement {
244 public Expression expr;
245 public readonly Statement EmbeddedStatement;
248 public Do (Statement statement, Expression boolExpr, Location l)
251 EmbeddedStatement = statement;
255 public override bool Resolve (EmitContext ec)
259 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
261 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
263 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
264 if (!EmbeddedStatement.Resolve (ec))
266 ec.EndFlowBranching ();
268 if (ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable && !was_unreachable)
269 Report.Warning (162, 2, expr.Location, "Unreachable code detected");
271 expr = Expression.ResolveBoolean (ec, expr, loc);
274 else if (expr is BoolConstant){
275 bool res = ((BoolConstant) expr).Value;
281 ec.CurrentBranching.CurrentUsageVector.Goto ();
283 ec.EndFlowBranching ();
288 protected override void DoEmit (EmitContext ec)
290 ILGenerator ig = ec.ig;
291 Label loop = ig.DefineLabel ();
292 Label old_begin = ec.LoopBegin;
293 Label old_end = ec.LoopEnd;
295 ec.LoopBegin = ig.DefineLabel ();
296 ec.LoopEnd = ig.DefineLabel ();
299 EmbeddedStatement.Emit (ec);
300 ig.MarkLabel (ec.LoopBegin);
303 // Dead code elimination
305 if (expr is BoolConstant){
306 bool res = ((BoolConstant) expr).Value;
309 ec.ig.Emit (OpCodes.Br, loop);
311 expr.EmitBranchable (ec, loop, true);
313 ig.MarkLabel (ec.LoopEnd);
315 ec.LoopBegin = old_begin;
316 ec.LoopEnd = old_end;
320 public class While : Statement {
321 public Expression expr;
322 public readonly Statement Statement;
323 bool infinite, empty;
325 public While (Expression boolExpr, Statement statement, Location l)
327 this.expr = boolExpr;
328 Statement = statement;
332 public override bool Resolve (EmitContext ec)
336 expr = Expression.ResolveBoolean (ec, expr, loc);
341 // Inform whether we are infinite or not
343 if (expr is BoolConstant){
344 BoolConstant bc = (BoolConstant) expr;
346 if (bc.Value == false){
347 if (!Statement.ResolveUnreachable (ec, true))
355 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
357 ec.CurrentBranching.CreateSibling ();
359 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
360 if (!Statement.Resolve (ec))
362 ec.EndFlowBranching ();
364 // There's no direct control flow from the end of the embedded statement to the end of the loop
365 ec.CurrentBranching.CurrentUsageVector.Goto ();
367 ec.EndFlowBranching ();
372 protected override void DoEmit (EmitContext ec)
377 ILGenerator ig = ec.ig;
378 Label old_begin = ec.LoopBegin;
379 Label old_end = ec.LoopEnd;
381 ec.LoopBegin = ig.DefineLabel ();
382 ec.LoopEnd = ig.DefineLabel ();
385 // Inform whether we are infinite or not
387 if (expr is BoolConstant){
388 ig.MarkLabel (ec.LoopBegin);
390 ig.Emit (OpCodes.Br, ec.LoopBegin);
393 // Inform that we are infinite (ie, `we return'), only
394 // if we do not `break' inside the code.
396 ig.MarkLabel (ec.LoopEnd);
398 Label while_loop = ig.DefineLabel ();
400 ig.Emit (OpCodes.Br, ec.LoopBegin);
401 ig.MarkLabel (while_loop);
405 ig.MarkLabel (ec.LoopBegin);
407 expr.EmitBranchable (ec, while_loop, true);
409 ig.MarkLabel (ec.LoopEnd);
412 ec.LoopBegin = old_begin;
413 ec.LoopEnd = old_end;
417 public class For : Statement {
419 readonly Statement InitStatement;
420 readonly Statement Increment;
421 public readonly Statement Statement;
422 bool infinite, empty;
424 public For (Statement initStatement,
430 InitStatement = initStatement;
432 Increment = increment;
433 Statement = statement;
437 public override bool Resolve (EmitContext ec)
441 if (InitStatement != null){
442 if (!InitStatement.Resolve (ec))
447 Test = Expression.ResolveBoolean (ec, Test, loc);
450 else if (Test is BoolConstant){
451 BoolConstant bc = (BoolConstant) Test;
453 if (bc.Value == false){
454 if (!Statement.ResolveUnreachable (ec, true))
456 if ((Increment != null) &&
457 !Increment.ResolveUnreachable (ec, false))
467 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
469 ec.CurrentBranching.CreateSibling ();
471 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
473 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
474 if (!Statement.Resolve (ec))
476 ec.EndFlowBranching ();
478 if (Increment != null){
479 if (ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable) {
480 if (!Increment.ResolveUnreachable (ec, !was_unreachable))
483 if (!Increment.Resolve (ec))
488 // There's no direct control flow from the end of the embedded statement to the end of the loop
489 ec.CurrentBranching.CurrentUsageVector.Goto ();
491 ec.EndFlowBranching ();
496 protected override void DoEmit (EmitContext ec)
501 ILGenerator ig = ec.ig;
502 Label old_begin = ec.LoopBegin;
503 Label old_end = ec.LoopEnd;
504 Label loop = ig.DefineLabel ();
505 Label test = ig.DefineLabel ();
507 if (InitStatement != null && InitStatement != EmptyStatement.Value)
508 InitStatement.Emit (ec);
510 ec.LoopBegin = ig.DefineLabel ();
511 ec.LoopEnd = ig.DefineLabel ();
513 ig.Emit (OpCodes.Br, test);
517 ig.MarkLabel (ec.LoopBegin);
518 if (Increment != EmptyStatement.Value)
523 // If test is null, there is no test, and we are just
528 // The Resolve code already catches the case for
529 // Test == BoolConstant (false) so we know that
532 if (Test is BoolConstant)
533 ig.Emit (OpCodes.Br, loop);
535 Test.EmitBranchable (ec, loop, true);
538 ig.Emit (OpCodes.Br, loop);
539 ig.MarkLabel (ec.LoopEnd);
541 ec.LoopBegin = old_begin;
542 ec.LoopEnd = old_end;
546 public class StatementExpression : Statement {
547 ExpressionStatement expr;
549 public StatementExpression (ExpressionStatement expr)
555 public override bool Resolve (EmitContext ec)
558 expr = expr.ResolveStatement (ec);
562 protected override void DoEmit (EmitContext ec)
564 expr.EmitStatement (ec);
567 public override string ToString ()
569 return "StatementExpression (" + expr + ")";
574 /// Implements the return statement
576 public class Return : Statement {
577 public Expression Expr;
579 public Return (Expression expr, Location l)
587 public override bool Resolve (EmitContext ec)
589 AnonymousContainer am = ec.CurrentAnonymousMethod;
590 if ((am != null) && am.IsIterator && ec.InIterator) {
591 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
592 "statement to return a value, or yield break to end the iteration");
596 if (ec.ReturnType == null){
598 if (ec.CurrentAnonymousMethod != null){
599 Report.Error (1662, loc,
600 "Cannot convert anonymous method block to delegate type `{0}' because some of the return types in the block are not implicitly convertible to the delegate return type",
601 ec.CurrentAnonymousMethod.GetSignatureForError ());
603 Error (127, "A return keyword must not be followed by any expression when method returns void");
608 Error (126, "An object of a type convertible to `{0}' is required " +
609 "for the return statement",
610 TypeManager.CSharpName (ec.ReturnType));
614 Expr = Expr.Resolve (ec);
618 if (Expr.Type != ec.ReturnType) {
619 Expr = Convert.ImplicitConversionRequired (
620 ec, Expr, ec.ReturnType, loc);
626 int errors = Report.Errors;
627 unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
629 ec.NeedReturnLabel ();
630 ec.CurrentBranching.CurrentUsageVector.Return ();
631 return errors == Report.Errors;
634 protected override void DoEmit (EmitContext ec)
640 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
644 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
646 ec.ig.Emit (OpCodes.Ret);
650 public class Goto : Statement {
652 LabeledStatement label;
655 public override bool Resolve (EmitContext ec)
657 int errors = Report.Errors;
658 unwind_protect = ec.CurrentBranching.AddGotoOrigin (ec.CurrentBranching.CurrentUsageVector, this);
659 ec.CurrentBranching.CurrentUsageVector.Goto ();
660 return errors == Report.Errors;
663 public Goto (string label, Location l)
669 public string Target {
670 get { return target; }
673 public void SetResolvedTarget (LabeledStatement label)
676 label.AddReference ();
679 protected override void DoEmit (EmitContext ec)
682 throw new InternalErrorException ("goto emitted before target resolved");
683 Label l = label.LabelTarget (ec);
684 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
688 public class LabeledStatement : Statement {
695 FlowBranching.UsageVector vectors;
697 public LabeledStatement (string name, Location l)
703 public Label LabelTarget (EmitContext ec)
708 label = ec.ig.DefineLabel ();
718 public bool IsDefined {
719 get { return defined; }
722 public bool HasBeenReferenced {
723 get { return referenced; }
726 public FlowBranching.UsageVector JumpOrigins {
727 get { return vectors; }
730 public void AddUsageVector (FlowBranching.UsageVector vector)
732 vector = vector.Clone ();
733 vector.Next = vectors;
737 public override bool Resolve (EmitContext ec)
739 // this flow-branching will be terminated when the surrounding block ends
740 ec.StartFlowBranching (this);
744 protected override void DoEmit (EmitContext ec)
746 if (ig != null && ig != ec.ig)
747 throw new InternalErrorException ("cannot happen");
749 ec.ig.MarkLabel (label);
752 public void AddReference ()
760 /// `goto default' statement
762 public class GotoDefault : Statement {
764 public GotoDefault (Location l)
769 public override bool Resolve (EmitContext ec)
771 ec.CurrentBranching.CurrentUsageVector.Goto ();
775 protected override void DoEmit (EmitContext ec)
777 if (ec.Switch == null){
778 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
782 if (!ec.Switch.GotDefault){
783 Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
786 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
791 /// `goto case' statement
793 public class GotoCase : Statement {
797 public GotoCase (Expression e, Location l)
803 public override bool Resolve (EmitContext ec)
805 if (ec.Switch == null){
806 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
810 expr = expr.Resolve (ec);
814 Constant c = expr as Constant;
816 Error (150, "A constant value is expected");
820 Type type = ec.Switch.SwitchType;
821 if (!Convert.ImplicitStandardConversionExists (c, type))
822 Report.Warning (469, 2, loc, "The `goto case' value is not implicitly " +
823 "convertible to type `{0}'", TypeManager.CSharpName (type));
826 object val = c.GetValue ();
827 if ((val != null) && (c.Type != type) && (c.Type != TypeManager.object_type))
828 val = TypeManager.ChangeType (val, type, out fail);
831 Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
832 c.GetSignatureForError (), TypeManager.CSharpName (type));
837 val = SwitchLabel.NullStringCase;
839 sl = (SwitchLabel) ec.Switch.Elements [val];
842 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", c.GetValue () == null ? "null" : val.ToString ());
846 ec.CurrentBranching.CurrentUsageVector.Goto ();
850 protected override void DoEmit (EmitContext ec)
852 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
856 public class Throw : Statement {
859 public Throw (Expression expr, Location l)
865 public override bool Resolve (EmitContext ec)
867 ec.CurrentBranching.CurrentUsageVector.Throw ();
870 expr = expr.Resolve (ec);
874 ExprClass eclass = expr.eclass;
876 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
877 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
878 expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
884 if ((t != TypeManager.exception_type) &&
885 !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
886 !(expr is NullLiteral)) {
888 "The type caught or thrown must be derived " +
889 "from System.Exception");
896 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
901 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
907 protected override void DoEmit (EmitContext ec)
910 ec.ig.Emit (OpCodes.Rethrow);
914 ec.ig.Emit (OpCodes.Throw);
919 public class Break : Statement {
921 public Break (Location l)
928 public override bool Resolve (EmitContext ec)
930 int errors = Report.Errors;
931 unwind_protect = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
932 ec.CurrentBranching.CurrentUsageVector.Goto ();
933 return errors == Report.Errors;
936 protected override void DoEmit (EmitContext ec)
938 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
942 public class Continue : Statement {
944 public Continue (Location l)
951 public override bool Resolve (EmitContext ec)
953 int errors = Report.Errors;
954 unwind_protect = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
955 ec.CurrentBranching.CurrentUsageVector.Goto ();
956 return errors == Report.Errors;
959 protected override void DoEmit (EmitContext ec)
961 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
966 // The information about a user-perceived local variable
968 public class LocalInfo {
969 public Expression Type;
972 // Most of the time a variable will be stored in a LocalBuilder
974 // But sometimes, it will be stored in a field (variables that have been
975 // hoisted by iterators or by anonymous methods). The context of the field will
976 // be stored in the EmitContext
979 public LocalBuilder LocalBuilder;
980 public FieldBuilder FieldBuilder;
982 public Type VariableType;
983 public readonly string Name;
984 public readonly Location Location;
985 public readonly Block Block;
987 public VariableInfo VariableInfo;
997 CompilerGenerated = 64,
1001 public enum ReadOnlyContext: byte {
1008 ReadOnlyContext ro_context;
1010 public LocalInfo (Expression type, string name, Block block, Location l)
1018 public LocalInfo (DeclSpace ds, Block block, Location l)
1020 VariableType = ds.TypeBuilder;
1025 public void DeclareLocal (ILGenerator ig)
1029 // This is needed to compile on both .NET 1.x and .NET 2.x
1030 // the later introduced `DeclareLocal (Type t, bool pinned)'
1032 LocalBuilder = TypeManager.DeclareLocalPinned (ig, VariableType);
1035 if (!IsThis && !IsConstant)
1036 LocalBuilder = ig.DeclareLocal (VariableType);
1039 public bool IsThisAssigned (EmitContext ec, Location loc)
1041 if (VariableInfo == null)
1042 throw new Exception ();
1044 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1047 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1050 public bool IsAssigned (EmitContext ec)
1052 if (VariableInfo == null)
1053 throw new Exception ();
1055 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1058 public bool Resolve (EmitContext ec)
1060 if (VariableType == null) {
1061 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1065 VariableType = texpr.Type;
1068 if (VariableType == TypeManager.void_type) {
1069 Expression.Error_VoidInvalidInTheContext (Location);
1073 if (VariableType.IsAbstract && VariableType.IsSealed) {
1074 Report.Error (723, Location, "Cannot declare variable of static type `{0}'", TypeManager.CSharpName (VariableType));
1078 if (VariableType.IsPointer && !ec.InUnsafe)
1079 Expression.UnsafeError (Location);
1084 public bool IsCaptured {
1086 return (flags & Flags.Captured) != 0;
1090 flags |= Flags.Captured;
1094 public bool IsConstant {
1096 return (flags & Flags.IsConstant) != 0;
1099 flags |= Flags.IsConstant;
1103 public bool AddressTaken {
1105 return (flags & Flags.AddressTaken) != 0;
1109 flags |= Flags.AddressTaken;
1113 public bool CompilerGenerated {
1115 return (flags & Flags.CompilerGenerated) != 0;
1119 flags |= Flags.CompilerGenerated;
1123 public override string ToString ()
1125 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1126 Name, Type, VariableInfo, Location);
1131 return (flags & Flags.Used) != 0;
1134 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1138 public bool ReadOnly {
1140 return (flags & Flags.ReadOnly) != 0;
1144 public void SetReadOnlyContext (ReadOnlyContext context)
1146 flags |= Flags.ReadOnly;
1147 ro_context = context;
1150 public string GetReadOnlyContext ()
1153 throw new InternalErrorException ("Variable is not readonly");
1155 switch (ro_context) {
1156 case ReadOnlyContext.Fixed:
1157 return "fixed variable";
1158 case ReadOnlyContext.Foreach:
1159 return "foreach iteration variable";
1160 case ReadOnlyContext.Using:
1161 return "using variable";
1163 throw new NotImplementedException ();
1167 // Whether the variable is pinned, if Pinned the variable has been
1168 // allocated in a pinned slot with DeclareLocal.
1170 public bool Pinned {
1172 return (flags & Flags.Pinned) != 0;
1175 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1179 public bool IsThis {
1181 return (flags & Flags.IsThis) != 0;
1184 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1190 /// Block represents a C# block.
1194 /// This class is used in a number of places: either to represent
1195 /// explicit blocks that the programmer places or implicit blocks.
1197 /// Implicit blocks are used as labels or to introduce variable
1200 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1201 /// they contain extra information that is not necessary on normal blocks.
1203 public class Block : Statement {
1204 public Block Parent;
1205 public readonly Location StartLocation;
1206 public Location EndLocation = Location.Null;
1208 public readonly ToplevelBlock Toplevel;
1211 public enum Flags : ushort {
1215 VariablesInitialized = 8,
1220 HasVarargs = 256 // Used in ToplevelBlock
1222 protected Flags flags;
1224 public bool Implicit {
1225 get { return (flags & Flags.Implicit) != 0; }
1228 public bool Unchecked {
1229 get { return (flags & Flags.Unchecked) != 0; }
1230 set { flags |= Flags.Unchecked; }
1233 public bool Unsafe {
1234 get { return (flags & Flags.Unsafe) != 0; }
1235 set { flags |= Flags.Unsafe; }
1239 // The statements in this block
1241 ArrayList statements;
1245 // An array of Blocks. We keep track of children just
1246 // to generate the local variable declarations.
1248 // Statements and child statements are handled through the
1254 // Labels. (label, block) pairs.
1259 // Keeps track of (name, type) pairs
1261 IDictionary variables;
1264 // Keeps track of constants
1265 Hashtable constants;
1268 // Temporary variables.
1270 ArrayList temporary_variables;
1273 // If this is a switch section, the enclosing switch block.
1277 protected static int id;
1281 public Block (Block parent)
1282 : this (parent, (Flags) 0, Location.Null, Location.Null)
1285 public Block (Block parent, Flags flags)
1286 : this (parent, flags, Location.Null, Location.Null)
1289 public Block (Block parent, Location start, Location end)
1290 : this (parent, (Flags) 0, start, end)
1293 public Block (Block parent, Flags flags, Location start, Location end)
1296 parent.AddChild (this);
1298 this.Parent = parent;
1300 this.StartLocation = start;
1301 this.EndLocation = end;
1304 statements = new ArrayList ();
1306 if ((flags & Flags.IsToplevel) != 0)
1307 Toplevel = (ToplevelBlock) this;
1309 Toplevel = parent.Toplevel;
1311 if (parent != null && Implicit) {
1312 if (parent.known_variables == null)
1313 parent.known_variables = new Hashtable ();
1314 // share with parent
1315 known_variables = parent.known_variables;
1319 public Block CreateSwitchBlock (Location start)
1321 Block new_block = new Block (this, start, start);
1322 new_block.switch_block = this;
1327 get { return this_id; }
1330 protected IDictionary Variables {
1332 if (variables == null)
1333 variables = new ListDictionary ();
1338 void AddChild (Block b)
1340 if (children == null)
1341 children = new ArrayList ();
1346 public void SetEndLocation (Location loc)
1352 /// Adds a label to the current block.
1356 /// false if the name already exists in this block. true
1360 public bool AddLabel (LabeledStatement target)
1362 if (switch_block != null)
1363 return switch_block.AddLabel (target);
1365 string name = target.Name;
1368 while (cur != null) {
1369 if (cur.DoLookupLabel (name) != null) {
1370 Report.Error (140, target.loc, "The label `{0}' is a duplicate", name);
1380 while (cur != null) {
1381 if (cur.DoLookupLabel (name) != null) {
1384 "The label `{0}' shadows another label by the same name in a contained scope.",
1389 if (children != null) {
1390 foreach (Block b in children) {
1391 LabeledStatement s = b.DoLookupLabel (name);
1397 "The label `{0}' shadows another label by the same name in a contained scope.",
1408 labels = new Hashtable ();
1410 labels.Add (name, target);
1414 public LabeledStatement LookupLabel (string name)
1416 LabeledStatement s = DoLookupLabel (name);
1420 if (children == null)
1423 foreach (Block child in children) {
1424 if (!child.Implicit)
1427 s = child.LookupLabel (name);
1435 LabeledStatement DoLookupLabel (string name)
1437 if (switch_block != null)
1438 return switch_block.LookupLabel (name);
1441 if (labels.Contains (name))
1442 return ((LabeledStatement) labels [name]);
1447 Hashtable known_variables;
1450 // Marks a variable with name @name as being used in this or a child block.
1451 // If a variable name has been used in a child block, it's illegal to
1452 // declare a variable with the same name in the current block.
1454 void AddKnownVariable (string name, LocalInfo info)
1456 if (known_variables == null)
1457 known_variables = new Hashtable ();
1459 known_variables [name] = info;
1462 LocalInfo GetKnownVariableInfo (string name)
1464 if (known_variables == null)
1466 return (LocalInfo) known_variables [name];
1469 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1472 LocalInfo kvi = b.GetKnownVariableInfo (name);
1473 while (kvi == null) {
1479 kvi = b.GetKnownVariableInfo (name);
1485 // Is kvi.Block nested inside 'b'
1486 if (b.known_variables != kvi.Block.known_variables) {
1488 // If a variable by the same name it defined in a nested block of this
1489 // block, we violate the invariant meaning in a block.
1492 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1493 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1498 // It's ok if the definition is in a nested subblock of b, but not
1499 // nested inside this block -- a definition in a sibling block
1500 // should not affect us.
1506 // Block 'b' and kvi.Block are the same textual block.
1507 // However, different variables are extant.
1509 // Check if the variable is in scope in both blocks. We use
1510 // an indirect check that depends on AddVariable doing its
1511 // part in maintaining the invariant-meaning-in-block property.
1513 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1517 // Even though we detected the error when the name is used, we
1518 // treat it as if the variable declaration was in error.
1520 Report.SymbolRelatedToPreviousError (loc, name);
1521 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1525 public LocalInfo AddVariable (Expression type, string name, Location l)
1527 LocalInfo vi = GetLocalInfo (name);
1529 Report.SymbolRelatedToPreviousError (vi.Location, name);
1530 if (known_variables == vi.Block.known_variables)
1531 Report.Error (128, l,
1532 "A local variable named `{0}' is already defined in this scope", name);
1534 Error_AlreadyDeclared (l, name, "parent");
1538 vi = GetKnownVariableInfo (name);
1540 Report.SymbolRelatedToPreviousError (vi.Location, name);
1541 Error_AlreadyDeclared (l, name, "child");
1546 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1548 Report.SymbolRelatedToPreviousError (p.Location, name);
1549 Error_AlreadyDeclared (l, name, "method argument");
1553 vi = new LocalInfo (type, name, this, l);
1555 Variables.Add (name, vi);
1557 for (Block b = this; b != null; b = b.Parent)
1558 b.AddKnownVariable (name, vi);
1560 if ((flags & Flags.VariablesInitialized) != 0)
1561 throw new Exception ();
1566 void Error_AlreadyDeclared (Location loc, string var, string reason)
1568 Report.Error (136, loc, "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning to `{0}', " +
1569 "which is already used in a `{1}' scope", var, reason);
1572 public bool AddConstant (Expression type, string name, Expression value, Location l)
1574 if (AddVariable (type, name, l) == null)
1577 if (constants == null)
1578 constants = new Hashtable ();
1580 constants.Add (name, value);
1582 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1587 static int next_temp_id = 0;
1589 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1591 if (temporary_variables == null)
1592 temporary_variables = new ArrayList ();
1594 int id = ++next_temp_id;
1595 string name = "$s_" + id.ToString ();
1597 LocalInfo li = new LocalInfo (te, name, this, loc);
1598 li.CompilerGenerated = true;
1599 temporary_variables.Add (li);
1603 public LocalInfo GetLocalInfo (string name)
1605 for (Block b = this; b != null; b = b.Parent) {
1606 if (b.variables != null) {
1607 LocalInfo ret = b.variables [name] as LocalInfo;
1615 public Expression GetVariableType (string name)
1617 LocalInfo vi = GetLocalInfo (name);
1618 return vi == null ? null : vi.Type;
1621 public Expression GetConstantExpression (string name)
1623 for (Block b = this; b != null; b = b.Parent) {
1624 if (b.constants != null) {
1625 Expression ret = b.constants [name] as Expression;
1633 public void AddStatement (Statement s)
1636 flags |= Flags.BlockUsed;
1640 get { return (flags & Flags.BlockUsed) != 0; }
1645 flags |= Flags.BlockUsed;
1648 public bool HasRet {
1649 get { return (flags & Flags.HasRet) != 0; }
1652 public bool IsDestructor {
1653 get { return (flags & Flags.IsDestructor) != 0; }
1656 public void SetDestructor ()
1658 flags |= Flags.IsDestructor;
1661 VariableMap param_map, local_map;
1663 public VariableMap ParameterMap {
1665 if ((flags & Flags.VariablesInitialized) == 0)
1666 throw new Exception ("Variables have not been initialized yet");
1672 public VariableMap LocalMap {
1674 if ((flags & Flags.VariablesInitialized) == 0)
1675 throw new Exception ("Variables have not been initialized yet");
1682 /// Emits the variable declarations and labels.
1685 /// tc: is our typecontainer (to resolve type references)
1686 /// ig: is the code generator:
1688 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
1690 // If some parent block was unsafe, we remain unsafe even if this block
1691 // isn't explicitly marked as such.
1692 using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
1694 // Compute the VariableMap's.
1696 // Unfortunately, we don't know the type when adding variables with
1697 // AddVariable(), so we need to compute this info here.
1701 if (variables != null) {
1702 foreach (LocalInfo li in variables.Values)
1705 locals = new LocalInfo [variables.Count];
1706 variables.Values.CopyTo (locals, 0);
1708 locals = new LocalInfo [0];
1711 local_map = new VariableMap (Parent.LocalMap, locals);
1713 local_map = new VariableMap (locals);
1715 param_map = new VariableMap (ip);
1716 flags |= Flags.VariablesInitialized;
1719 // Process this block variables
1721 if (variables != null) {
1722 foreach (DictionaryEntry de in variables) {
1723 string name = (string) de.Key;
1724 LocalInfo vi = (LocalInfo) de.Value;
1725 Type variable_type = vi.VariableType;
1727 if (variable_type == null)
1730 if (variable_type.IsPointer) {
1732 // Am not really convinced that this test is required (Microsoft does it)
1733 // but the fact is that you would not be able to use the pointer variable
1736 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1741 if (constants == null)
1744 Expression cv = (Expression) constants [name];
1748 // Don't let 'const int Foo = Foo;' succeed.
1749 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
1750 // which in turn causes the 'must be constant' error to be triggered.
1751 constants.Remove (name);
1753 using (ec.With (EmitContext.Flags.ConstantCheckState, (flags & Flags.Unchecked) == 0)) {
1754 ec.CurrentBlock = this;
1755 Expression e = cv.Resolve (ec);
1759 Constant ce = e as Constant;
1761 Const.Error_ExpressionMustBeConstant (variable_type, vi.Location, name);
1765 e = ce.ToType (variable_type, vi.Location);
1769 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue) {
1770 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
1774 constants.Add (name, e);
1775 vi.IsConstant = true;
1781 // Now, handle the children
1783 if (children != null) {
1784 foreach (Block b in children)
1785 b.ResolveMeta (toplevel, ec, ip);
1791 // Emits the local variable declarations for a block
1793 public void EmitMeta (EmitContext ec)
1795 ILGenerator ig = ec.ig;
1797 if (variables != null){
1798 bool have_captured_vars = ec.HaveCapturedVariables ();
1800 foreach (DictionaryEntry de in variables){
1801 LocalInfo vi = (LocalInfo) de.Value;
1803 if (have_captured_vars && ec.IsCaptured (vi))
1806 vi.DeclareLocal (ig);
1810 if (temporary_variables != null) {
1811 AnonymousContainer am = ec.CurrentAnonymousMethod;
1812 TypeBuilder scope = null;
1813 if ((am != null) && am.IsIterator) {
1814 scope = am.Scope.ScopeTypeBuilder;
1816 throw new InternalErrorException ();
1818 foreach (LocalInfo vi in temporary_variables) {
1819 if (scope != null) {
1820 if (vi.FieldBuilder == null)
1821 vi.FieldBuilder = scope.DefineField (
1822 vi.Name, vi.VariableType, FieldAttributes.Assembly);
1824 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1828 if (children != null){
1829 foreach (Block b in children)
1834 void UsageWarning (FlowBranching.UsageVector vector)
1838 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1839 foreach (DictionaryEntry de in variables){
1840 LocalInfo vi = (LocalInfo) de.Value;
1845 name = (string) de.Key;
1847 // vi.VariableInfo can be null for 'catch' variables
1848 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
1849 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
1851 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
1857 bool unreachable_shown;
1860 private void CheckPossibleMistakenEmptyStatement (Statement s)
1864 // Some statements are wrapped by a Block. Since
1865 // others' internal could be changed, here I treat
1866 // them as possibly wrapped by Block equally.
1867 Block b = s as Block;
1868 if (b != null && b.statements.Count == 1)
1869 s = (Statement) b.statements [0];
1872 body = ((Lock) s).Statement;
1874 body = ((For) s).Statement;
1875 else if (s is Foreach)
1876 body = ((Foreach) s).Statement;
1877 else if (s is While)
1878 body = ((While) s).Statement;
1879 else if (s is Using)
1880 body = ((Using) s).Statement;
1881 else if (s is Fixed)
1882 body = ((Fixed) s).Statement;
1886 if (body == null || body is EmptyStatement)
1887 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
1890 public override bool Resolve (EmitContext ec)
1892 Block prev_block = ec.CurrentBlock;
1895 int errors = Report.Errors;
1897 ec.CurrentBlock = this;
1898 ec.StartFlowBranching (this);
1900 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1903 // This flag is used to notate nested statements as unreachable from the beginning of this block.
1904 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
1905 // from the beginning of the function. The outer Resolve() that detected the unreachability is
1906 // responsible for handling the situation.
1908 int statement_count = statements.Count;
1909 for (int ix = 0; ix < statement_count; ix++){
1910 Statement s = (Statement) statements [ix];
1911 // Check possible empty statement (CS0642)
1912 if (RootContext.WarningLevel >= 3 &&
1913 ix + 1 < statement_count &&
1914 statements [ix + 1] is Block)
1915 CheckPossibleMistakenEmptyStatement (s);
1918 if (s is EmptyStatement)
1922 ((Block) s).unreachable = true;
1924 if (!unreachable_shown && !(s is LabeledStatement)) {
1925 Report.Warning (162, 2, s.loc, "Unreachable code detected");
1926 unreachable_shown = true;
1930 if (!s.Resolve (ec)) {
1932 statements [ix] = EmptyStatement.Value;
1936 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1937 statements [ix] = EmptyStatement.Value;
1939 num_statements = ix + 1;
1941 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1942 if (unreachable && s is LabeledStatement)
1943 throw new InternalErrorException ("should not happen");
1946 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1947 ec.CurrentBranching, statement_count, num_statements);
1949 while (ec.CurrentBranching is FlowBranchingLabeled)
1950 ec.EndFlowBranching ();
1952 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1954 ec.CurrentBlock = prev_block;
1956 // If we're a non-static `struct' constructor which doesn't have an
1957 // initializer, then we must initialize all of the struct's fields.
1958 if ((flags & Flags.IsToplevel) != 0 &&
1959 !Toplevel.IsThisAssigned (ec) &&
1960 !vector.Reachability.AlwaysThrows)
1963 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1964 foreach (LabeledStatement label in labels.Values)
1965 if (!label.HasBeenReferenced)
1966 Report.Warning (164, 2, label.loc,
1967 "This label has not been referenced");
1970 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1972 if (vector.Reachability.IsUnreachable)
1973 flags |= Flags.HasRet;
1975 if (ok && (errors == Report.Errors)) {
1976 if (RootContext.WarningLevel >= 3)
1977 UsageWarning (vector);
1983 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1985 unreachable_shown = true;
1989 Report.Warning (162, 2, loc, "Unreachable code detected");
1991 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1992 bool ok = Resolve (ec);
1993 ec.KillFlowBranching ();
1998 protected override void DoEmit (EmitContext ec)
2000 for (int ix = 0; ix < num_statements; ix++){
2001 Statement s = (Statement) statements [ix];
2003 // Check whether we are the last statement in a
2006 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2007 ec.IsLastStatement = true;
2009 ec.IsLastStatement = false;
2015 public override void Emit (EmitContext ec)
2017 Block prev_block = ec.CurrentBlock;
2019 ec.CurrentBlock = this;
2021 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2022 bool is_lexical_block = !Implicit && (Parent != null);
2024 if (emit_debug_info) {
2025 if (is_lexical_block)
2028 if (variables != null) {
2029 foreach (DictionaryEntry de in variables) {
2030 string name = (string) de.Key;
2031 LocalInfo vi = (LocalInfo) de.Value;
2033 if (vi.LocalBuilder == null)
2036 ec.DefineLocalVariable (name, vi.LocalBuilder);
2040 ec.Mark (StartLocation, true);
2041 ec.EmitScopeInitFromBlock (this);
2043 ec.Mark (EndLocation, true);
2045 if (emit_debug_info && is_lexical_block)
2048 ec.CurrentBlock = prev_block;
2052 // Returns true if we ar ea child of `b'.
2054 public bool IsChildOf (Block b)
2056 Block current = this;
2059 if (current.Parent == b)
2061 current = current.Parent;
2062 } while (current != null);
2066 public override string ToString ()
2068 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2073 // A toplevel block contains extra information, the split is done
2074 // only to separate information that would otherwise bloat the more
2075 // lightweight Block.
2077 // In particular, this was introduced when the support for Anonymous
2078 // Methods was implemented.
2080 public class ToplevelBlock : Block {
2082 // Pointer to the host of this anonymous method, or null
2083 // if we are the topmost block
2085 ToplevelBlock container;
2086 CaptureContext capture_context;
2087 FlowBranchingToplevel top_level_branching;
2089 Hashtable capture_contexts;
2092 public bool HasVarargs {
2093 get { return (flags & Flags.HasVarargs) != 0; }
2094 set { flags |= Flags.HasVarargs; }
2098 // The parameters for the block.
2100 Parameters parameters;
2101 public Parameters Parameters {
2102 get { return parameters; }
2105 public void RegisterCaptureContext (CaptureContext cc)
2107 if (capture_contexts == null)
2108 capture_contexts = new Hashtable ();
2109 capture_contexts [cc] = cc;
2112 public void CompleteContexts ()
2114 if (capture_contexts == null)
2117 foreach (CaptureContext cc in capture_contexts.Keys){
2122 public CaptureContext ToplevelBlockCaptureContext {
2123 get { return capture_context; }
2126 public ToplevelBlock Container {
2127 get { return container; }
2130 protected void AddChild (ToplevelBlock block)
2132 if (children == null)
2133 children = new ArrayList ();
2135 children.Add (block);
2139 // Parent is only used by anonymous blocks to link back to their
2142 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2143 this (container, (Flags) 0, parameters, start)
2147 public ToplevelBlock (Parameters parameters, Location start) :
2148 this (null, (Flags) 0, parameters, start)
2152 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2153 this (null, flags, parameters, start)
2157 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2158 base (null, flags | Flags.IsToplevel, start, Location.Null)
2160 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2161 this.container = container;
2163 if (container != null)
2164 container.AddChild (this);
2167 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2171 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2173 if (capture_context == null)
2174 capture_context = new CaptureContext (this, loc, host);
2177 public CaptureContext CaptureContext {
2178 get { return capture_context; }
2181 public FlowBranchingToplevel TopLevelBranching {
2182 get { return top_level_branching; }
2186 // This is used if anonymous methods are used inside an iterator
2187 // (see 2test-22.cs for an example).
2189 // The AnonymousMethod is created while parsing - at a time when we don't
2190 // know yet that we're inside an iterator, so it's `Container' is initially
2191 // null. Later on, when resolving the iterator, we need to move the
2192 // anonymous method into that iterator.
2194 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2196 foreach (ToplevelBlock block in children) {
2197 if (block.CaptureContext == null)
2200 block.container = new_parent;
2201 block.CaptureContext.ReParent (new_parent, new_host);
2206 // Returns a `ParameterReference' for the given name, or null if there
2207 // is no such parameter
2209 public ParameterReference GetParameterReference (string name, Location loc)
2214 for (ToplevelBlock t = this; t != null; t = t.Container) {
2215 Parameters pars = t.Parameters;
2216 par = pars.GetParameterByName (name, out idx);
2218 return new ParameterReference (par, this, idx, loc);
2224 // Whether the parameter named `name' is local to this block,
2225 // or false, if the parameter belongs to an encompassing block.
2227 public bool IsLocalParameter (string name)
2229 return Parameters.GetParameterByName (name) != null;
2233 // Whether the `name' is a parameter reference
2235 public bool IsParameterReference (string name)
2237 for (ToplevelBlock t = this; t != null; t = t.Container) {
2238 if (t.IsLocalParameter (name))
2244 LocalInfo this_variable = null;
2247 // Returns the "this" instance variable of this block.
2248 // See AddThisVariable() for more information.
2250 public LocalInfo ThisVariable {
2251 get { return this_variable; }
2256 // This is used by non-static `struct' constructors which do not have an
2257 // initializer - in this case, the constructor must initialize all of the
2258 // struct's fields. To do this, we add a "this" variable and use the flow
2259 // analysis code to ensure that it's been fully initialized before control
2260 // leaves the constructor.
2262 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2264 if (this_variable == null) {
2265 this_variable = new LocalInfo (ds, this, l);
2266 this_variable.Used = true;
2267 this_variable.IsThis = true;
2269 Variables.Add ("this", this_variable);
2272 return this_variable;
2275 public bool IsThisAssigned (EmitContext ec)
2277 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2280 public bool ResolveMeta (EmitContext ec, Parameters ip)
2282 int errors = Report.Errors;
2284 if (top_level_branching != null)
2290 ResolveMeta (this, ec, ip);
2292 top_level_branching = ec.StartFlowBranching (this);
2294 return Report.Errors == errors;
2298 public class SwitchLabel {
2305 Label il_label_code;
2306 bool il_label_code_set;
2308 public static readonly object NullStringCase = new object ();
2311 // if expr == null, then it is the default case.
2313 public SwitchLabel (Expression expr, Location l)
2319 public Expression Label {
2325 public object Converted {
2331 public Label GetILLabel (EmitContext ec)
2334 il_label = ec.ig.DefineLabel ();
2335 il_label_set = true;
2340 public Label GetILLabelCode (EmitContext ec)
2342 if (!il_label_code_set){
2343 il_label_code = ec.ig.DefineLabel ();
2344 il_label_code_set = true;
2346 return il_label_code;
2350 // Resolves the expression, reduces it to a literal if possible
2351 // and then converts it to the requested type.
2353 public bool ResolveAndReduce (EmitContext ec, Type required_type, bool allow_nullable)
2355 Expression e = label.Resolve (ec);
2360 Constant c = e as Constant;
2362 Report.Error (150, loc, "A constant value is expected");
2366 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2367 converted = NullStringCase;
2371 if (allow_nullable && c.GetValue () == null) {
2372 converted = NullStringCase;
2376 c = c.ToType (required_type, loc);
2380 converted = c.GetValue ();
2384 public void Erorr_AlreadyOccurs ()
2387 if (converted == null)
2389 else if (converted == NullStringCase)
2392 label = converted.ToString ();
2394 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2398 public class SwitchSection {
2399 // An array of SwitchLabels.
2400 public readonly ArrayList Labels;
2401 public readonly Block Block;
2403 public SwitchSection (ArrayList labels, Block block)
2410 public class Switch : Statement {
2411 public readonly ArrayList Sections;
2412 public Expression Expr;
2415 /// Maps constants whose type type SwitchType to their SwitchLabels.
2417 public IDictionary Elements;
2420 /// The governing switch type
2422 public Type SwitchType;
2427 Label default_target;
2429 Expression new_expr;
2430 Nullable.Unwrap unwrap;
2432 SwitchSection constant_section;
2433 SwitchSection default_section;
2436 // The types allowed to be implicitly cast from
2437 // on the governing type
2439 static Type [] allowed_types;
2441 public Switch (Expression e, ArrayList sects, Location l)
2448 public bool GotDefault {
2450 return default_section != null;
2454 public Label DefaultTarget {
2456 return default_target;
2461 // Determines the governing type for a switch. The returned
2462 // expression might be the expression from the switch, or an
2463 // expression that includes any potential conversions to the
2464 // integral types or to string.
2466 Expression SwitchGoverningType (EmitContext ec, Expression expr)
2470 if (t == TypeManager.byte_type ||
2471 t == TypeManager.sbyte_type ||
2472 t == TypeManager.ushort_type ||
2473 t == TypeManager.short_type ||
2474 t == TypeManager.uint32_type ||
2475 t == TypeManager.int32_type ||
2476 t == TypeManager.uint64_type ||
2477 t == TypeManager.int64_type ||
2478 t == TypeManager.char_type ||
2479 t == TypeManager.string_type ||
2480 t == TypeManager.bool_type ||
2481 t.IsSubclassOf (TypeManager.enum_type))
2484 if (allowed_types == null){
2485 allowed_types = new Type [] {
2486 TypeManager.sbyte_type,
2487 TypeManager.byte_type,
2488 TypeManager.short_type,
2489 TypeManager.ushort_type,
2490 TypeManager.int32_type,
2491 TypeManager.uint32_type,
2492 TypeManager.int64_type,
2493 TypeManager.uint64_type,
2494 TypeManager.char_type,
2495 TypeManager.string_type,
2496 TypeManager.bool_type
2501 // Try to find a *user* defined implicit conversion.
2503 // If there is no implicit conversion, or if there are multiple
2504 // conversions, we have to report an error
2506 Expression converted = null;
2507 foreach (Type tt in allowed_types){
2510 e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
2515 // Ignore over-worked ImplicitUserConversions that do
2516 // an implicit conversion in addition to the user conversion.
2518 if (!(e is UserCast))
2521 if (converted != null){
2522 Report.ExtraInformation (
2524 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2525 TypeManager.CSharpName (expr.Type)));
2535 // Performs the basic sanity checks on the switch statement
2536 // (looks for duplicate keys and non-constant expressions).
2538 // It also returns a hashtable with the keys that we will later
2539 // use to compute the switch tables
2541 bool CheckSwitch (EmitContext ec)
2544 Elements = Sections.Count > 10 ?
2545 (IDictionary)new Hashtable () :
2546 (IDictionary)new ListDictionary ();
2548 foreach (SwitchSection ss in Sections){
2549 foreach (SwitchLabel sl in ss.Labels){
2550 if (sl.Label == null){
2551 if (default_section != null){
2552 sl.Erorr_AlreadyOccurs ();
2555 default_section = ss;
2559 if (!sl.ResolveAndReduce (ec, SwitchType, unwrap != null)){
2564 object key = sl.Converted;
2566 Elements.Add (key, sl);
2567 } catch (ArgumentException) {
2568 sl.Erorr_AlreadyOccurs ();
2576 void EmitObjectInteger (ILGenerator ig, object k)
2579 IntConstant.EmitInt (ig, (int) k);
2580 else if (k is Constant) {
2581 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2584 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2587 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2589 IntConstant.EmitInt (ig, (int) (long) k);
2590 ig.Emit (OpCodes.Conv_I8);
2593 LongConstant.EmitLong (ig, (long) k);
2595 else if (k is ulong)
2597 ulong ul = (ulong) k;
2600 IntConstant.EmitInt (ig, unchecked ((int) ul));
2601 ig.Emit (OpCodes.Conv_U8);
2605 LongConstant.EmitLong (ig, unchecked ((long) ul));
2609 IntConstant.EmitInt (ig, (int) ((char) k));
2610 else if (k is sbyte)
2611 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2613 IntConstant.EmitInt (ig, (int) ((byte) k));
2614 else if (k is short)
2615 IntConstant.EmitInt (ig, (int) ((short) k));
2616 else if (k is ushort)
2617 IntConstant.EmitInt (ig, (int) ((ushort) k));
2619 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2621 throw new Exception ("Unhandled case");
2624 // structure used to hold blocks of keys while calculating table switch
2625 class KeyBlock : IComparable
2627 public KeyBlock (long _nFirst)
2629 nFirst = nLast = _nFirst;
2633 public ArrayList rgKeys = null;
2634 // how many items are in the bucket
2635 public int Size = 1;
2638 get { return (int) (nLast - nFirst + 1); }
2640 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2642 return kbLast.nLast - kbFirst.nFirst + 1;
2644 public int CompareTo (object obj)
2646 KeyBlock kb = (KeyBlock) obj;
2647 int nLength = Length;
2648 int nLengthOther = kb.Length;
2649 if (nLengthOther == nLength)
2650 return (int) (kb.nFirst - nFirst);
2651 return nLength - nLengthOther;
2656 /// This method emits code for a lookup-based switch statement (non-string)
2657 /// Basically it groups the cases into blocks that are at least half full,
2658 /// and then spits out individual lookup opcodes for each block.
2659 /// It emits the longest blocks first, and short blocks are just
2660 /// handled with direct compares.
2662 /// <param name="ec"></param>
2663 /// <param name="val"></param>
2664 /// <returns></returns>
2665 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2667 int cElements = Elements.Count;
2668 object [] rgKeys = new object [cElements];
2669 Elements.Keys.CopyTo (rgKeys, 0);
2670 Array.Sort (rgKeys);
2672 // initialize the block list with one element per key
2673 ArrayList rgKeyBlocks = new ArrayList ();
2674 foreach (object key in rgKeys)
2675 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2678 // iteratively merge the blocks while they are at least half full
2679 // there's probably a really cool way to do this with a tree...
2680 while (rgKeyBlocks.Count > 1)
2682 ArrayList rgKeyBlocksNew = new ArrayList ();
2683 kbCurr = (KeyBlock) rgKeyBlocks [0];
2684 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2686 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2687 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2690 kbCurr.nLast = kb.nLast;
2691 kbCurr.Size += kb.Size;
2695 // start a new block
2696 rgKeyBlocksNew.Add (kbCurr);
2700 rgKeyBlocksNew.Add (kbCurr);
2701 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2703 rgKeyBlocks = rgKeyBlocksNew;
2706 // initialize the key lists
2707 foreach (KeyBlock kb in rgKeyBlocks)
2708 kb.rgKeys = new ArrayList ();
2710 // fill the key lists
2712 if (rgKeyBlocks.Count > 0) {
2713 kbCurr = (KeyBlock) rgKeyBlocks [0];
2714 foreach (object key in rgKeys)
2716 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2717 System.Convert.ToInt64 (key) > kbCurr.nLast;
2719 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2720 kbCurr.rgKeys.Add (key);
2724 // sort the blocks so we can tackle the largest ones first
2725 rgKeyBlocks.Sort ();
2727 // okay now we can start...
2728 ILGenerator ig = ec.ig;
2729 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2730 Label lblDefault = ig.DefineLabel ();
2732 Type typeKeys = null;
2733 if (rgKeys.Length > 0)
2734 typeKeys = rgKeys [0].GetType (); // used for conversions
2738 if (TypeManager.IsEnumType (SwitchType))
2739 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2741 compare_type = SwitchType;
2743 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2745 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2746 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2749 foreach (object key in kb.rgKeys)
2751 ig.Emit (OpCodes.Ldloc, val);
2752 EmitObjectInteger (ig, key);
2753 SwitchLabel sl = (SwitchLabel) Elements [key];
2754 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2759 // TODO: if all the keys in the block are the same and there are
2760 // no gaps/defaults then just use a range-check.
2761 if (compare_type == TypeManager.int64_type ||
2762 compare_type == TypeManager.uint64_type)
2764 // TODO: optimize constant/I4 cases
2766 // check block range (could be > 2^31)
2767 ig.Emit (OpCodes.Ldloc, val);
2768 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2769 ig.Emit (OpCodes.Blt, lblDefault);
2770 ig.Emit (OpCodes.Ldloc, val);
2771 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2772 ig.Emit (OpCodes.Bgt, lblDefault);
2775 ig.Emit (OpCodes.Ldloc, val);
2778 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2779 ig.Emit (OpCodes.Sub);
2781 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2786 ig.Emit (OpCodes.Ldloc, val);
2787 int nFirst = (int) kb.nFirst;
2790 IntConstant.EmitInt (ig, nFirst);
2791 ig.Emit (OpCodes.Sub);
2793 else if (nFirst < 0)
2795 IntConstant.EmitInt (ig, -nFirst);
2796 ig.Emit (OpCodes.Add);
2800 // first, build the list of labels for the switch
2802 int cJumps = kb.Length;
2803 Label [] rgLabels = new Label [cJumps];
2804 for (int iJump = 0; iJump < cJumps; iJump++)
2806 object key = kb.rgKeys [iKey];
2807 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2809 SwitchLabel sl = (SwitchLabel) Elements [key];
2810 rgLabels [iJump] = sl.GetILLabel (ec);
2814 rgLabels [iJump] = lblDefault;
2816 // emit the switch opcode
2817 ig.Emit (OpCodes.Switch, rgLabels);
2820 // mark the default for this block
2822 ig.MarkLabel (lblDefault);
2825 // TODO: find the default case and emit it here,
2826 // to prevent having to do the following jump.
2827 // make sure to mark other labels in the default section
2829 // the last default just goes to the end
2830 ig.Emit (OpCodes.Br, lblDefault);
2832 // now emit the code for the sections
2833 bool fFoundDefault = false;
2834 bool fFoundNull = false;
2835 foreach (SwitchSection ss in Sections)
2837 foreach (SwitchLabel sl in ss.Labels)
2838 if (sl.Converted == SwitchLabel.NullStringCase)
2842 foreach (SwitchSection ss in Sections)
2844 foreach (SwitchLabel sl in ss.Labels)
2846 ig.MarkLabel (sl.GetILLabel (ec));
2847 ig.MarkLabel (sl.GetILLabelCode (ec));
2848 if (sl.Converted == SwitchLabel.NullStringCase)
2849 ig.MarkLabel (null_target);
2850 else if (sl.Label == null) {
2851 ig.MarkLabel (lblDefault);
2852 fFoundDefault = true;
2854 ig.MarkLabel (null_target);
2858 //ig.Emit (OpCodes.Br, lblEnd);
2861 if (!fFoundDefault) {
2862 ig.MarkLabel (lblDefault);
2864 ig.MarkLabel (lblEnd);
2867 // This simple emit switch works, but does not take advantage of the
2869 // TODO: remove non-string logic from here
2870 // TODO: binary search strings?
2872 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2874 ILGenerator ig = ec.ig;
2875 Label end_of_switch = ig.DefineLabel ();
2876 Label next_test = ig.DefineLabel ();
2877 bool first_test = true;
2878 bool pending_goto_end = false;
2879 bool null_marked = false;
2882 ig.Emit (OpCodes.Ldloc, val);
2884 if (Elements.Contains (SwitchLabel.NullStringCase)){
2885 ig.Emit (OpCodes.Brfalse, null_target);
2887 ig.Emit (OpCodes.Brfalse, default_target);
2889 ig.Emit (OpCodes.Ldloc, val);
2890 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2891 ig.Emit (OpCodes.Stloc, val);
2893 int section_count = Sections.Count;
2894 for (int section = 0; section < section_count; section++){
2895 SwitchSection ss = (SwitchSection) Sections [section];
2897 if (ss == default_section)
2900 Label sec_begin = ig.DefineLabel ();
2902 ig.Emit (OpCodes.Nop);
2904 if (pending_goto_end)
2905 ig.Emit (OpCodes.Br, end_of_switch);
2907 int label_count = ss.Labels.Count;
2909 for (int label = 0; label < label_count; label++){
2910 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2911 ig.MarkLabel (sl.GetILLabel (ec));
2914 ig.MarkLabel (next_test);
2915 next_test = ig.DefineLabel ();
2918 // If we are the default target
2920 if (sl.Label != null){
2921 object lit = sl.Converted;
2923 if (lit == SwitchLabel.NullStringCase){
2925 if (label + 1 == label_count)
2926 ig.Emit (OpCodes.Br, next_test);
2930 ig.Emit (OpCodes.Ldloc, val);
2931 ig.Emit (OpCodes.Ldstr, (string)lit);
2932 if (label_count == 1)
2933 ig.Emit (OpCodes.Bne_Un, next_test);
2935 if (label+1 == label_count)
2936 ig.Emit (OpCodes.Bne_Un, next_test);
2938 ig.Emit (OpCodes.Beq, sec_begin);
2943 ig.MarkLabel (null_target);
2946 ig.MarkLabel (sec_begin);
2947 foreach (SwitchLabel sl in ss.Labels)
2948 ig.MarkLabel (sl.GetILLabelCode (ec));
2951 pending_goto_end = !ss.Block.HasRet;
2954 ig.MarkLabel (next_test);
2955 ig.MarkLabel (default_target);
2957 ig.MarkLabel (null_target);
2958 if (default_section != null)
2959 default_section.Block.Emit (ec);
2960 ig.MarkLabel (end_of_switch);
2963 SwitchSection FindSection (SwitchLabel label)
2965 foreach (SwitchSection ss in Sections){
2966 foreach (SwitchLabel sl in ss.Labels){
2975 public override bool Resolve (EmitContext ec)
2977 Expr = Expr.Resolve (ec);
2981 new_expr = SwitchGoverningType (ec, Expr);
2983 if ((new_expr == null) && TypeManager.IsNullableType (Expr.Type)) {
2984 unwrap = Nullable.Unwrap.Create (Expr, ec);
2988 new_expr = SwitchGoverningType (ec, unwrap);
2991 if (new_expr == null){
2992 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2997 SwitchType = new_expr.Type;
2999 if (!CheckSwitch (ec))
3002 if (unwrap != null) {
3003 Elements.Remove (SwitchLabel.NullStringCase);
3006 Switch old_switch = ec.Switch;
3008 ec.Switch.SwitchType = SwitchType;
3010 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3011 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3013 is_constant = new_expr is Constant;
3015 object key = ((Constant) new_expr).GetValue ();
3016 SwitchLabel label = (SwitchLabel) Elements [key];
3018 constant_section = FindSection (label);
3019 if (constant_section == null)
3020 constant_section = default_section;
3024 foreach (SwitchSection ss in Sections){
3026 ec.CurrentBranching.CreateSibling (
3027 null, FlowBranching.SiblingType.SwitchSection);
3031 if (is_constant && (ss != constant_section)) {
3032 // If we're a constant switch, we're only emitting
3033 // one single section - mark all the others as
3035 ec.CurrentBranching.CurrentUsageVector.Goto ();
3036 if (!ss.Block.ResolveUnreachable (ec, true))
3039 if (!ss.Block.Resolve (ec))
3044 if (default_section == null)
3045 ec.CurrentBranching.CreateSibling (
3046 null, FlowBranching.SiblingType.SwitchSection);
3048 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3049 ec.Switch = old_switch;
3051 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3057 protected override void DoEmit (EmitContext ec)
3059 ILGenerator ig = ec.ig;
3061 default_target = ig.DefineLabel ();
3062 null_target = ig.DefineLabel ();
3064 // Store variable for comparission purposes
3066 if (unwrap != null) {
3067 value = ig.DeclareLocal (SwitchType);
3068 unwrap.EmitCheck (ec);
3069 ig.Emit (OpCodes.Brfalse, null_target);
3071 ig.Emit (OpCodes.Stloc, value);
3072 } else if (!is_constant) {
3073 value = ig.DeclareLocal (SwitchType);
3075 ig.Emit (OpCodes.Stloc, value);
3080 // Setup the codegen context
3082 Label old_end = ec.LoopEnd;
3083 Switch old_switch = ec.Switch;
3085 ec.LoopEnd = ig.DefineLabel ();
3090 if (constant_section != null)
3091 constant_section.Block.Emit (ec);
3092 } else if (SwitchType == TypeManager.string_type)
3093 SimpleSwitchEmit (ec, value);
3095 TableSwitchEmit (ec, value);
3097 // Restore context state.
3098 ig.MarkLabel (ec.LoopEnd);
3101 // Restore the previous context
3103 ec.LoopEnd = old_end;
3104 ec.Switch = old_switch;
3108 public abstract class ExceptionStatement : Statement
3110 public abstract void EmitFinally (EmitContext ec);
3112 protected bool emit_finally = true;
3113 ArrayList parent_vectors;
3115 protected void DoEmitFinally (EmitContext ec)
3118 ec.ig.BeginFinallyBlock ();
3119 else if (ec.InIterator)
3120 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3124 protected void ResolveFinally (FlowBranchingException branching)
3126 emit_finally = branching.EmitFinally;
3128 branching.Parent.StealFinallyClauses (ref parent_vectors);
3132 public class Lock : ExceptionStatement {
3134 public Statement Statement;
3135 TemporaryVariable temp;
3137 public Lock (Expression expr, Statement stmt, Location l)
3144 public override bool Resolve (EmitContext ec)
3146 expr = expr.Resolve (ec);
3150 if (expr.Type.IsValueType){
3151 Report.Error (185, loc,
3152 "`{0}' is not a reference type as required by the lock statement",
3153 TypeManager.CSharpName (expr.Type));
3157 FlowBranchingException branching = ec.StartFlowBranching (this);
3158 bool ok = Statement.Resolve (ec);
3160 ec.KillFlowBranching ();
3164 ResolveFinally (branching);
3166 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3167 if (!reachability.AlwaysReturns) {
3168 // Unfortunately, System.Reflection.Emit automatically emits
3169 // a leave to the end of the finally block.
3170 // This is a problem if `returns' is true since we may jump
3171 // to a point after the end of the method.
3172 // As a workaround, emit an explicit ret here.
3173 ec.NeedReturnLabel ();
3177 if (t == TypeManager.null_type)
3178 t = TypeManager.object_type;
3180 temp = new TemporaryVariable (t, loc);
3186 protected override void DoEmit (EmitContext ec)
3188 ILGenerator ig = ec.ig;
3190 temp.Store (ec, expr);
3192 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3196 ig.BeginExceptionBlock ();
3197 Statement.Emit (ec);
3202 ig.EndExceptionBlock ();
3205 public override void EmitFinally (EmitContext ec)
3208 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3212 public class Unchecked : Statement {
3213 public readonly Block Block;
3215 public Unchecked (Block b)
3221 public override bool Resolve (EmitContext ec)
3223 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3224 return Block.Resolve (ec);
3227 protected override void DoEmit (EmitContext ec)
3229 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3234 public class Checked : Statement {
3235 public readonly Block Block;
3237 public Checked (Block b)
3240 b.Unchecked = false;
3243 public override bool Resolve (EmitContext ec)
3245 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3246 return Block.Resolve (ec);
3249 protected override void DoEmit (EmitContext ec)
3251 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3256 public class Unsafe : Statement {
3257 public readonly Block Block;
3259 public Unsafe (Block b)
3262 Block.Unsafe = true;
3265 public override bool Resolve (EmitContext ec)
3267 using (ec.With (EmitContext.Flags.InUnsafe, true))
3268 return Block.Resolve (ec);
3271 protected override void DoEmit (EmitContext ec)
3273 using (ec.With (EmitContext.Flags.InUnsafe, true))
3281 public class Fixed : Statement {
3283 ArrayList declarators;
3284 Statement statement;
3289 abstract class Emitter
3291 protected LocalInfo vi;
3292 protected Expression converted;
3294 protected Emitter (Expression expr, LocalInfo li)
3300 public abstract void Emit (EmitContext ec);
3301 public abstract void EmitExit (ILGenerator ig);
3304 class ExpressionEmitter : Emitter {
3305 public ExpressionEmitter (Expression converted, LocalInfo li) :
3306 base (converted, li)
3310 public override void Emit (EmitContext ec) {
3312 // Store pointer in pinned location
3314 converted.Emit (ec);
3315 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3318 public override void EmitExit (ILGenerator ig)
3320 ig.Emit (OpCodes.Ldc_I4_0);
3321 ig.Emit (OpCodes.Conv_U);
3322 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3326 class StringEmitter : Emitter {
3327 LocalBuilder pinned_string;
3330 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3336 public override void Emit (EmitContext ec)
3338 ILGenerator ig = ec.ig;
3339 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3341 converted.Emit (ec);
3342 ig.Emit (OpCodes.Stloc, pinned_string);
3344 Expression sptr = new StringPtr (pinned_string, loc);
3345 converted = Convert.ImplicitConversionRequired (
3346 ec, sptr, vi.VariableType, loc);
3348 if (converted == null)
3351 converted.Emit (ec);
3352 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3355 public override void EmitExit(ILGenerator ig)
3357 ig.Emit (OpCodes.Ldnull);
3358 ig.Emit (OpCodes.Stloc, pinned_string);
3362 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3365 declarators = decls;
3370 public Statement Statement {
3371 get { return statement; }
3374 public override bool Resolve (EmitContext ec)
3377 Expression.UnsafeError (loc);
3381 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3385 expr_type = texpr.Type;
3387 data = new Emitter [declarators.Count];
3389 if (!expr_type.IsPointer){
3390 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3395 foreach (Pair p in declarators){
3396 LocalInfo vi = (LocalInfo) p.First;
3397 Expression e = (Expression) p.Second;
3399 vi.VariableInfo.SetAssigned (ec);
3400 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3403 // The rules for the possible declarators are pretty wise,
3404 // but the production on the grammar is more concise.
3406 // So we have to enforce these rules here.
3408 // We do not resolve before doing the case 1 test,
3409 // because the grammar is explicit in that the token &
3410 // is present, so we need to test for this particular case.
3414 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3419 // Case 1: & object.
3421 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3422 Expression child = ((Unary) e).Expr;
3424 if (child is ParameterReference || child is LocalVariableReference){
3427 "No need to use fixed statement for parameters or " +
3428 "local variable declarations (address is already " +
3433 ec.InFixedInitializer = true;
3435 ec.InFixedInitializer = false;
3439 child = ((Unary) e).Expr;
3441 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3444 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
3445 e.Error_ValueCannotBeConverted (e.Location, expr_type, false);
3449 data [i] = new ExpressionEmitter (e, vi);
3455 ec.InFixedInitializer = true;
3457 ec.InFixedInitializer = false;
3464 if (e.Type.IsArray){
3465 Type array_type = TypeManager.GetElementType (e.Type);
3468 // Provided that array_type is unmanaged,
3470 if (!TypeManager.VerifyUnManaged (array_type, loc))
3474 // and T* is implicitly convertible to the
3475 // pointer type given in the fixed statement.
3477 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3479 Expression converted = Convert.ImplicitConversionRequired (
3480 ec, array_ptr, vi.VariableType, loc);
3481 if (converted == null)
3484 data [i] = new ExpressionEmitter (converted, vi);
3493 if (e.Type == TypeManager.string_type){
3494 data [i] = new StringEmitter (e, vi, loc);
3499 // Case 4: fixed buffer
3500 FieldExpr fe = e as FieldExpr;
3502 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3504 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3506 Expression converted = Convert.ImplicitConversionRequired (
3507 ec, fixed_buffer_ptr, vi.VariableType, loc);
3508 if (converted == null)
3511 data [i] = new ExpressionEmitter (converted, vi);
3519 // For other cases, flag a `this is already fixed expression'
3521 if (e is LocalVariableReference || e is ParameterReference ||
3522 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3524 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3528 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3532 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3534 if (!statement.Resolve (ec)) {
3535 ec.KillFlowBranching ();
3539 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3540 has_ret = reachability.IsUnreachable;
3545 protected override void DoEmit (EmitContext ec)
3547 for (int i = 0; i < data.Length; i++) {
3551 statement.Emit (ec);
3556 ILGenerator ig = ec.ig;
3559 // Clear the pinned variable
3561 for (int i = 0; i < data.Length; i++) {
3562 data [i].EmitExit (ig);
3567 public class Catch : Statement {
3568 public readonly string Name;
3569 public readonly Block Block;
3570 public readonly Block VarBlock;
3572 Expression type_expr;
3575 public Catch (Expression type, string name, Block block, Block var_block, Location l)
3580 VarBlock = var_block;
3584 public Type CatchType {
3590 public bool IsGeneral {
3592 return type_expr == null;
3596 protected override void DoEmit(EmitContext ec)
3600 public override bool Resolve (EmitContext ec)
3602 using (ec.With (EmitContext.Flags.InCatch, true)) {
3603 if (type_expr != null) {
3604 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3610 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3611 Error (155, "The type caught or thrown must be derived from System.Exception");
3617 if (!Block.Resolve (ec))
3620 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
3621 // emit the "unused variable" warnings.
3622 if (VarBlock != null)
3623 return VarBlock.Resolve (ec);
3630 public class Try : ExceptionStatement {
3631 public readonly Block Fini, Block;
3632 public readonly ArrayList Specific;
3633 public readonly Catch General;
3635 bool need_exc_block;
3638 // specific, general and fini might all be null.
3640 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3642 if (specific == null && general == null){
3643 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3647 this.Specific = specific;
3648 this.General = general;
3653 public override bool Resolve (EmitContext ec)
3657 FlowBranchingException branching = ec.StartFlowBranching (this);
3659 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3661 if (!Block.Resolve (ec))
3664 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3666 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3668 Type[] prevCatches = new Type [Specific.Count];
3670 foreach (Catch c in Specific){
3671 ec.CurrentBranching.CreateSibling (
3672 c.Block, FlowBranching.SiblingType.Catch);
3674 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3676 if (c.Name != null) {
3677 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3679 throw new Exception ();
3681 vi.VariableInfo = null;
3684 if (!c.Resolve (ec))
3687 Type resolvedType = c.CatchType;
3688 for (int ii = 0; ii < last_index; ++ii) {
3689 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3690 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3695 prevCatches [last_index++] = resolvedType;
3696 need_exc_block = true;
3699 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3701 if (General != null){
3702 if (CodeGen.Assembly.WrapNonExceptionThrows) {
3703 foreach (Catch c in Specific){
3704 if (c.CatchType == TypeManager.exception_type) {
3705 Report.Warning (1058, 1, c.loc, "A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a `System.Runtime.CompilerServices.RuntimeWrappedException'");
3710 ec.CurrentBranching.CreateSibling (
3711 General.Block, FlowBranching.SiblingType.Catch);
3713 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3715 if (!General.Resolve (ec))
3718 need_exc_block = true;
3721 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3725 ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
3727 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3728 using (ec.With (EmitContext.Flags.InFinally, true)) {
3729 if (!Fini.Resolve (ec))
3734 need_exc_block = true;
3737 if (ec.InIterator) {
3738 ResolveFinally (branching);
3739 need_exc_block |= emit_finally;
3741 emit_finally = Fini != null;
3743 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3745 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3747 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3749 if (!reachability.AlwaysReturns) {
3750 // Unfortunately, System.Reflection.Emit automatically emits
3751 // a leave to the end of the finally block. This is a problem
3752 // if `returns' is true since we may jump to a point after the
3753 // end of the method.
3754 // As a workaround, emit an explicit ret here.
3755 ec.NeedReturnLabel ();
3761 protected override void DoEmit (EmitContext ec)
3763 ILGenerator ig = ec.ig;
3766 ig.BeginExceptionBlock ();
3769 foreach (Catch c in Specific){
3772 ig.BeginCatchBlock (c.CatchType);
3774 if (c.VarBlock != null)
3775 ec.EmitScopeInitFromBlock (c.VarBlock);
3776 if (c.Name != null){
3777 vi = c.Block.GetLocalInfo (c.Name);
3779 throw new Exception ("Variable does not exist in this block");
3782 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
3783 ig.Emit (OpCodes.Stloc, e);
3785 ec.EmitCapturedVariableInstance (vi);
3786 ig.Emit (OpCodes.Ldloc, e);
3787 ig.Emit (OpCodes.Stfld, vi.FieldBuilder);
3789 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3791 ig.Emit (OpCodes.Pop);
3796 if (General != null){
3797 ig.BeginCatchBlock (TypeManager.object_type);
3798 ig.Emit (OpCodes.Pop);
3799 General.Block.Emit (ec);
3804 ig.EndExceptionBlock ();
3807 public override void EmitFinally (EmitContext ec)
3813 public bool HasCatch
3816 return General != null || Specific.Count > 0;
3821 public class Using : ExceptionStatement {
3822 object expression_or_block;
3823 public Statement Statement;
3827 Expression [] resolved_vars;
3828 Expression [] converted_vars;
3829 ExpressionStatement [] assign;
3830 LocalBuilder local_copy;
3832 public Using (object expression_or_block, Statement stmt, Location l)
3834 this.expression_or_block = expression_or_block;
3840 // Resolves for the case of using using a local variable declaration.
3842 bool ResolveLocalVariableDecls (EmitContext ec)
3846 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3850 expr_type = texpr.Type;
3853 // The type must be an IDisposable or an implicit conversion
3856 converted_vars = new Expression [var_list.Count];
3857 resolved_vars = new Expression [var_list.Count];
3858 assign = new ExpressionStatement [var_list.Count];
3860 bool need_conv = !TypeManager.ImplementsInterface (
3861 expr_type, TypeManager.idisposable_type);
3863 foreach (DictionaryEntry e in var_list){
3864 Expression var = (Expression) e.Key;
3866 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3870 resolved_vars [i] = var;
3877 converted_vars [i] = Convert.ImplicitConversion (
3878 ec, var, TypeManager.idisposable_type, loc);
3880 if (converted_vars [i] == null) {
3881 Error_IsNotConvertibleToIDisposable ();
3889 foreach (DictionaryEntry e in var_list){
3890 Expression var = resolved_vars [i];
3891 Expression new_expr = (Expression) e.Value;
3894 a = new Assign (var, new_expr, loc);
3900 converted_vars [i] = var;
3901 assign [i] = (ExpressionStatement) a;
3908 void Error_IsNotConvertibleToIDisposable ()
3910 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
3911 TypeManager.CSharpName (expr_type));
3914 bool ResolveExpression (EmitContext ec)
3916 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3917 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3918 Error_IsNotConvertibleToIDisposable ();
3927 // Emits the code for the case of using using a local variable declaration.
3929 void EmitLocalVariableDecls (EmitContext ec)
3931 ILGenerator ig = ec.ig;
3934 for (i = 0; i < assign.Length; i++) {
3935 assign [i].EmitStatement (ec);
3938 ig.BeginExceptionBlock ();
3940 Statement.Emit (ec);
3942 var_list.Reverse ();
3947 void EmitLocalVariableDeclFinally (EmitContext ec)
3949 ILGenerator ig = ec.ig;
3951 int i = assign.Length;
3952 for (int ii = 0; ii < var_list.Count; ++ii){
3953 Expression var = resolved_vars [--i];
3954 Label skip = ig.DefineLabel ();
3956 ig.BeginFinallyBlock ();
3958 if (!var.Type.IsValueType) {
3960 ig.Emit (OpCodes.Brfalse, skip);
3961 converted_vars [i].Emit (ec);
3962 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3964 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3966 if (!(ml is MethodGroupExpr)) {
3968 ig.Emit (OpCodes.Box, var.Type);
3969 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3971 MethodInfo mi = null;
3973 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3974 if (TypeManager.GetParameterData (mk).Count == 0) {
3981 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3985 IMemoryLocation mloc = (IMemoryLocation) var;
3987 mloc.AddressOf (ec, AddressOp.Load);
3988 ig.Emit (OpCodes.Call, mi);
3992 ig.MarkLabel (skip);
3995 ig.EndExceptionBlock ();
3997 ig.BeginFinallyBlock ();
4002 void EmitExpression (EmitContext ec)
4005 // Make a copy of the expression and operate on that.
4007 ILGenerator ig = ec.ig;
4008 local_copy = ig.DeclareLocal (expr_type);
4011 ig.Emit (OpCodes.Stloc, local_copy);
4014 ig.BeginExceptionBlock ();
4016 Statement.Emit (ec);
4020 ig.EndExceptionBlock ();
4023 void EmitExpressionFinally (EmitContext ec)
4025 ILGenerator ig = ec.ig;
4026 if (!local_copy.LocalType.IsValueType) {
4027 Label skip = ig.DefineLabel ();
4028 ig.Emit (OpCodes.Ldloc, local_copy);
4029 ig.Emit (OpCodes.Brfalse, skip);
4030 ig.Emit (OpCodes.Ldloc, local_copy);
4031 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4032 ig.MarkLabel (skip);
4034 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4036 if (!(ml is MethodGroupExpr)) {
4037 ig.Emit (OpCodes.Ldloc, local_copy);
4038 ig.Emit (OpCodes.Box, local_copy.LocalType);
4039 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4041 MethodInfo mi = null;
4043 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4044 if (TypeManager.GetParameterData (mk).Count == 0) {
4051 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4055 ig.Emit (OpCodes.Ldloca, local_copy);
4056 ig.Emit (OpCodes.Call, mi);
4061 public override bool Resolve (EmitContext ec)
4063 if (expression_or_block is DictionaryEntry){
4064 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4065 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4067 if (!ResolveLocalVariableDecls (ec))
4070 } else if (expression_or_block is Expression){
4071 expr = (Expression) expression_or_block;
4073 expr = expr.Resolve (ec);
4077 expr_type = expr.Type;
4079 if (!ResolveExpression (ec))
4083 FlowBranchingException branching = ec.StartFlowBranching (this);
4085 bool ok = Statement.Resolve (ec);
4088 ec.KillFlowBranching ();
4092 ResolveFinally (branching);
4093 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4095 if (!reachability.AlwaysReturns) {
4096 // Unfortunately, System.Reflection.Emit automatically emits a leave
4097 // to the end of the finally block. This is a problem if `returns'
4098 // is true since we may jump to a point after the end of the method.
4099 // As a workaround, emit an explicit ret here.
4100 ec.NeedReturnLabel ();
4106 protected override void DoEmit (EmitContext ec)
4108 if (expression_or_block is DictionaryEntry)
4109 EmitLocalVariableDecls (ec);
4110 else if (expression_or_block is Expression)
4111 EmitExpression (ec);
4114 public override void EmitFinally (EmitContext ec)
4116 if (expression_or_block is DictionaryEntry)
4117 EmitLocalVariableDeclFinally (ec);
4118 else if (expression_or_block is Expression)
4119 EmitExpressionFinally (ec);
4124 /// Implementation of the foreach C# statement
4126 public class Foreach : Statement {
4128 Expression variable;
4130 Statement statement;
4132 CollectionForeach collection;
4134 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4135 Statement stmt, Location l)
4138 this.variable = var;
4144 public Statement Statement {
4145 get { return statement; }
4148 public override bool Resolve (EmitContext ec)
4150 expr = expr.Resolve (ec);
4154 Constant c = expr as Constant;
4155 if (c != null && c.GetValue () == null) {
4156 Report.Error (186, loc, "Use of null is not valid in this context");
4160 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4164 Type var_type = texpr.Type;
4166 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethod) {
4167 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4168 expr.ExprClassName);
4173 // We need an instance variable. Not sure this is the best
4174 // way of doing this.
4176 // FIXME: When we implement propertyaccess, will those turn
4177 // out to return values in ExprClass? I think they should.
4179 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4180 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4181 collection.Error_Enumerator ();
4185 if (expr.Type.IsArray) {
4186 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4187 return array.Resolve (ec);
4189 collection = new CollectionForeach (
4190 var_type, variable, expr, statement, loc);
4191 return collection.Resolve (ec);
4195 protected override void DoEmit (EmitContext ec)
4197 ILGenerator ig = ec.ig;
4199 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4200 ec.LoopBegin = ig.DefineLabel ();
4201 ec.LoopEnd = ig.DefineLabel ();
4203 if (collection != null)
4204 collection.Emit (ec);
4208 ec.LoopBegin = old_begin;
4209 ec.LoopEnd = old_end;
4212 protected class ArrayCounter : TemporaryVariable
4214 public ArrayCounter (Location loc)
4215 : base (TypeManager.int32_type, loc)
4218 public void Initialize (EmitContext ec)
4221 ec.ig.Emit (OpCodes.Ldc_I4_0);
4225 public void Increment (EmitContext ec)
4229 ec.ig.Emit (OpCodes.Ldc_I4_1);
4230 ec.ig.Emit (OpCodes.Add);
4235 protected class ArrayForeach : Statement
4237 Expression variable, expr, conv;
4238 Statement statement;
4241 TemporaryVariable[] lengths;
4242 ArrayCounter[] counter;
4245 TemporaryVariable copy;
4248 public ArrayForeach (Type var_type, Expression var,
4249 Expression expr, Statement stmt, Location l)
4251 this.var_type = var_type;
4252 this.variable = var;
4258 public override bool Resolve (EmitContext ec)
4260 array_type = expr.Type;
4261 rank = array_type.GetArrayRank ();
4263 copy = new TemporaryVariable (array_type, loc);
4266 counter = new ArrayCounter [rank];
4267 lengths = new TemporaryVariable [rank];
4269 ArrayList list = new ArrayList ();
4270 for (int i = 0; i < rank; i++) {
4271 counter [i] = new ArrayCounter (loc);
4272 counter [i].Resolve (ec);
4274 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4275 lengths [i].Resolve (ec);
4277 list.Add (counter [i]);
4280 access = new ElementAccess (copy, list).Resolve (ec);
4284 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4290 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4291 ec.CurrentBranching.CreateSibling ();
4293 variable = variable.ResolveLValue (ec, conv, loc);
4294 if (variable == null)
4297 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4298 if (!statement.Resolve (ec))
4300 ec.EndFlowBranching ();
4302 // There's no direct control flow from the end of the embedded statement to the end of the loop
4303 ec.CurrentBranching.CurrentUsageVector.Goto ();
4305 ec.EndFlowBranching ();
4310 protected override void DoEmit (EmitContext ec)
4312 ILGenerator ig = ec.ig;
4314 copy.Store (ec, expr);
4316 Label[] test = new Label [rank];
4317 Label[] loop = new Label [rank];
4319 for (int i = 0; i < rank; i++) {
4320 test [i] = ig.DefineLabel ();
4321 loop [i] = ig.DefineLabel ();
4323 lengths [i].EmitThis (ec);
4324 ((ArrayAccess) access).EmitGetLength (ec, i);
4325 lengths [i].EmitStore (ig);
4328 for (int i = 0; i < rank; i++) {
4329 counter [i].Initialize (ec);
4331 ig.Emit (OpCodes.Br, test [i]);
4332 ig.MarkLabel (loop [i]);
4335 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4337 statement.Emit (ec);
4339 ig.MarkLabel (ec.LoopBegin);
4341 for (int i = rank - 1; i >= 0; i--){
4342 counter [i].Increment (ec);
4344 ig.MarkLabel (test [i]);
4345 counter [i].Emit (ec);
4346 lengths [i].Emit (ec);
4347 ig.Emit (OpCodes.Blt, loop [i]);
4350 ig.MarkLabel (ec.LoopEnd);
4354 protected class CollectionForeach : ExceptionStatement
4356 Expression variable, expr;
4357 Statement statement;
4359 TemporaryVariable enumerator;
4363 MethodGroupExpr get_enumerator;
4364 PropertyExpr get_current;
4365 MethodInfo move_next;
4366 Type var_type, enumerator_type;
4368 bool enumerator_found;
4370 public CollectionForeach (Type var_type, Expression var,
4371 Expression expr, Statement stmt, Location l)
4373 this.var_type = var_type;
4374 this.variable = var;
4380 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4382 Type return_type = mi.ReturnType;
4384 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4386 // Apply the same optimization as MS: skip the GetEnumerator
4387 // returning an IEnumerator, and use the one returning a
4388 // CharEnumerator instead. This allows us to avoid the
4389 // try-finally block and the boxing.
4394 // Ok, we can access it, now make sure that we can do something
4395 // with this `GetEnumerator'
4398 if (return_type == TypeManager.ienumerator_type ||
4399 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4400 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4402 // If it is not an interface, lets try to find the methods ourselves.
4403 // For example, if we have:
4404 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4405 // We can avoid the iface call. This is a runtime perf boost.
4406 // even bigger if we have a ValueType, because we avoid the cost
4409 // We have to make sure that both methods exist for us to take
4410 // this path. If one of the methods does not exist, we will just
4411 // use the interface. Sadly, this complex if statement is the only
4412 // way I could do this without a goto
4415 if (return_type.IsInterface && return_type.IsGenericType) {
4416 enumerator_type = return_type;
4417 if (!FetchGetCurrent (ec, return_type))
4418 get_current = new PropertyExpr (
4419 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4420 if (!FetchMoveNext (return_type))
4421 move_next = TypeManager.bool_movenext_void;
4425 if (return_type.IsInterface ||
4426 !FetchMoveNext (return_type) ||
4427 !FetchGetCurrent (ec, return_type)) {
4428 enumerator_type = return_type;
4429 move_next = TypeManager.bool_movenext_void;
4430 get_current = new PropertyExpr (
4431 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4436 // Ok, so they dont return an IEnumerable, we will have to
4437 // find if they support the GetEnumerator pattern.
4440 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
4441 Report.Error (202, loc, "foreach statement requires that the return type `{0}' of `{1}' must have a suitable public MoveNext method and public Current property",
4442 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
4447 enumerator_type = return_type;
4448 is_disposable = !enumerator_type.IsSealed ||
4449 TypeManager.ImplementsInterface (
4450 enumerator_type, TypeManager.idisposable_type);
4456 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4458 bool FetchMoveNext (Type t)
4460 MemberList move_next_list;
4462 move_next_list = TypeContainer.FindMembers (
4463 t, MemberTypes.Method,
4464 Expression.AllBindingFlags,
4465 Type.FilterName, "MoveNext");
4466 if (move_next_list.Count == 0)
4470 foreach (MemberInfo m in move_next_list){
4471 MethodInfo mi = (MethodInfo) m;
4473 if ((TypeManager.GetParameterData (mi).Count == 0) &&
4474 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4486 // Retrieves a `public T get_Current ()' method from the Type `t'
4488 bool FetchGetCurrent (EmitContext ec, Type t)
4490 PropertyExpr pe = Expression.MemberLookup (
4491 ec.ContainerType, t, "Current", MemberTypes.Property,
4492 Expression.AllBindingFlags, loc) as PropertyExpr;
4501 // Retrieves a `public void Dispose ()' method from the Type `t'
4503 static MethodInfo FetchMethodDispose (Type t)
4505 MemberList dispose_list;
4507 dispose_list = TypeContainer.FindMembers (
4508 t, MemberTypes.Method,
4509 BindingFlags.Public | BindingFlags.Instance,
4510 Type.FilterName, "Dispose");
4511 if (dispose_list.Count == 0)
4514 foreach (MemberInfo m in dispose_list){
4515 MethodInfo mi = (MethodInfo) m;
4517 if (TypeManager.GetParameterData (mi).Count == 0){
4518 if (mi.ReturnType == TypeManager.void_type)
4525 public void Error_Enumerator ()
4527 if (enumerator_found) {
4531 Report.Error (1579, loc,
4532 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4533 TypeManager.CSharpName (expr.Type));
4536 bool TryType (EmitContext ec, Type t)
4538 MethodGroupExpr mg = Expression.MemberLookup (
4539 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
4540 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4544 MethodBase result = null;
4545 MethodInfo tmp_move_next = null;
4546 PropertyExpr tmp_get_cur = null;
4547 Type tmp_enumerator_type = enumerator_type;
4548 foreach (MethodInfo mi in mg.Methods) {
4549 if (TypeManager.GetParameterData (mi).Count != 0)
4552 // Check whether GetEnumerator is public
4553 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4556 if (TypeManager.IsOverride (mi))
4559 enumerator_found = true;
4561 if (!GetEnumeratorFilter (ec, mi)) {
4566 tmp_move_next = move_next;
4567 tmp_get_cur = get_current;
4568 tmp_enumerator_type = enumerator_type;
4569 if (mi.DeclaringType == t)
4573 if (result != null) {
4574 move_next = tmp_move_next;
4575 get_current = tmp_get_cur;
4576 enumerator_type = tmp_enumerator_type;
4577 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
4578 get_enumerator = new MethodGroupExpr (mi, loc);
4580 if (t != expr.Type) {
4581 expr = Convert.ExplicitConversion (
4584 throw new InternalErrorException ();
4587 get_enumerator.InstanceExpression = expr;
4588 get_enumerator.IsBase = t != expr.Type;
4596 bool ProbeCollectionType (EmitContext ec, Type t)
4598 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4599 if (TryType (ec, tt))
4605 // Now try to find the method in the interfaces
4608 Type [] ifaces = t.GetInterfaces ();
4610 foreach (Type i in ifaces){
4611 if (TryType (ec, i))
4616 // Since TypeBuilder.GetInterfaces only returns the interface
4617 // types for this type, we have to keep looping, but once
4618 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4619 // done, because it returns all the types
4621 if ((t is TypeBuilder))
4630 public override bool Resolve (EmitContext ec)
4632 enumerator_type = TypeManager.ienumerator_type;
4633 is_disposable = true;
4635 if (!ProbeCollectionType (ec, expr.Type)) {
4636 Error_Enumerator ();
4640 enumerator = new TemporaryVariable (enumerator_type, loc);
4641 enumerator.Resolve (ec);
4643 init = new Invocation (get_enumerator, new ArrayList ());
4644 init = init.Resolve (ec);
4648 Expression move_next_expr;
4650 MemberInfo[] mi = new MemberInfo[] { move_next };
4651 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4652 mg.InstanceExpression = enumerator;
4654 move_next_expr = new Invocation (mg, new ArrayList ());
4657 get_current.InstanceExpression = enumerator;
4659 Statement block = new CollectionForeachStatement (
4660 var_type, variable, get_current, statement, loc);
4662 loop = new While (move_next_expr, block, loc);
4666 FlowBranchingException branching = null;
4668 branching = ec.StartFlowBranching (this);
4670 if (!loop.Resolve (ec))
4673 if (is_disposable) {
4674 ResolveFinally (branching);
4675 ec.EndFlowBranching ();
4677 emit_finally = true;
4682 protected override void DoEmit (EmitContext ec)
4684 ILGenerator ig = ec.ig;
4686 enumerator.Store (ec, init);
4689 // Protect the code in a try/finalize block, so that
4690 // if the beast implement IDisposable, we get rid of it
4692 if (is_disposable && emit_finally)
4693 ig.BeginExceptionBlock ();
4698 // Now the finally block
4700 if (is_disposable) {
4703 ig.EndExceptionBlock ();
4708 public override void EmitFinally (EmitContext ec)
4710 ILGenerator ig = ec.ig;
4712 if (enumerator_type.IsValueType) {
4713 MethodInfo mi = FetchMethodDispose (enumerator_type);
4715 enumerator.EmitLoadAddress (ec);
4716 ig.Emit (OpCodes.Call, mi);
4718 enumerator.Emit (ec);
4719 ig.Emit (OpCodes.Box, enumerator_type);
4720 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4723 Label call_dispose = ig.DefineLabel ();
4725 enumerator.Emit (ec);
4726 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4727 ig.Emit (OpCodes.Dup);
4728 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4729 ig.Emit (OpCodes.Pop);
4731 Label end_finally = ig.DefineLabel ();
4732 ig.Emit (OpCodes.Br, end_finally);
4734 ig.MarkLabel (call_dispose);
4735 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4736 ig.MarkLabel (end_finally);
4741 protected class CollectionForeachStatement : Statement
4744 Expression variable, current, conv;
4745 Statement statement;
4748 public CollectionForeachStatement (Type type, Expression variable,
4749 Expression current, Statement statement,
4753 this.variable = variable;
4754 this.current = current;
4755 this.statement = statement;
4759 public override bool Resolve (EmitContext ec)
4761 current = current.Resolve (ec);
4762 if (current == null)
4765 conv = Convert.ExplicitConversion (ec, current, type, loc);
4769 assign = new Assign (variable, conv, loc);
4770 if (assign.Resolve (ec) == null)
4773 if (!statement.Resolve (ec))
4779 protected override void DoEmit (EmitContext ec)
4781 assign.EmitStatement (ec);
4782 statement.Emit (ec);