2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@ximian.com)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 // (C) 2003, 2004 Novell, Inc.
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Diagnostics;
18 namespace Mono.CSharp {
20 using System.Collections;
22 public abstract class Statement {
26 /// Resolves the statement, true means that all sub-statements
29 public virtual bool Resolve (EmitContext ec)
35 /// We already know that the statement is unreachable, but we still
36 /// need to resolve it to catch errors.
38 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
41 // This conflicts with csc's way of doing this, but IMHO it's
42 // the right thing to do.
44 // If something is unreachable, we still check whether it's
45 // correct. This means that you cannot use unassigned variables
46 // in unreachable code, for instance.
49 if (warn && (RootContext.WarningLevel >= 2))
50 Report.Warning (162, loc, "Unreachable code detected");
52 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
53 bool ok = Resolve (ec);
54 ec.KillFlowBranching ();
59 protected void CheckObsolete (Type type)
61 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
62 if (obsolete_attr == null)
65 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
69 /// Return value indicates whether all code paths emitted return.
71 protected abstract void DoEmit (EmitContext ec);
74 /// Utility wrapper routine for Error, just to beautify the code
76 public void Error (int error, string format, params object[] args)
78 Error (error, String.Format (format, args));
81 public void Error (int error, string s)
83 if (!Location.IsNull (loc))
84 Report.Error (error, loc, s);
86 Report.Error (error, s);
90 /// Return value indicates whether all code paths emitted return.
92 public virtual void Emit (EmitContext ec)
99 public sealed class EmptyStatement : Statement {
101 private EmptyStatement () {}
103 public static readonly EmptyStatement Value = new EmptyStatement ();
105 public override bool Resolve (EmitContext ec)
110 protected override void DoEmit (EmitContext ec)
115 public class If : Statement {
117 public Statement TrueStatement;
118 public Statement FalseStatement;
122 public If (Expression expr, Statement trueStatement, Location l)
125 TrueStatement = trueStatement;
129 public If (Expression expr,
130 Statement trueStatement,
131 Statement falseStatement,
135 TrueStatement = trueStatement;
136 FalseStatement = falseStatement;
140 public override bool Resolve (EmitContext ec)
144 Report.Debug (1, "START IF BLOCK", loc);
146 expr = Expression.ResolveBoolean (ec, expr, loc);
152 Assign ass = expr as Assign;
153 if (ass != null && ass.Source is Constant) {
154 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
158 // Dead code elimination
160 if (expr is BoolConstant){
161 bool take = ((BoolConstant) expr).Value;
164 if (!TrueStatement.Resolve (ec))
167 if ((FalseStatement != null) &&
168 !FalseStatement.ResolveUnreachable (ec, true))
170 FalseStatement = null;
172 if (!TrueStatement.ResolveUnreachable (ec, true))
174 TrueStatement = null;
176 if ((FalseStatement != null) &&
177 !FalseStatement.Resolve (ec))
184 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
186 ok &= TrueStatement.Resolve (ec);
188 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
190 ec.CurrentBranching.CreateSibling ();
192 if (FalseStatement != null)
193 ok &= FalseStatement.Resolve (ec);
195 ec.EndFlowBranching ();
197 Report.Debug (1, "END IF BLOCK", loc);
202 protected override void DoEmit (EmitContext ec)
204 ILGenerator ig = ec.ig;
205 Label false_target = ig.DefineLabel ();
209 // If we're a boolean expression, Resolve() already
210 // eliminated dead code for us.
212 if (expr is BoolConstant){
213 bool take = ((BoolConstant) expr).Value;
216 TrueStatement.Emit (ec);
217 else if (FalseStatement != null)
218 FalseStatement.Emit (ec);
223 expr.EmitBranchable (ec, false_target, false);
225 TrueStatement.Emit (ec);
227 if (FalseStatement != null){
228 bool branch_emitted = false;
230 end = ig.DefineLabel ();
232 ig.Emit (OpCodes.Br, end);
233 branch_emitted = true;
236 ig.MarkLabel (false_target);
237 FalseStatement.Emit (ec);
242 ig.MarkLabel (false_target);
247 public class Do : Statement {
248 public Expression expr;
249 public readonly Statement EmbeddedStatement;
252 public Do (Statement statement, Expression boolExpr, Location l)
255 EmbeddedStatement = statement;
259 public override bool Resolve (EmitContext ec)
263 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
265 if (!EmbeddedStatement.Resolve (ec))
268 expr = Expression.ResolveBoolean (ec, expr, loc);
271 else if (expr is BoolConstant){
272 bool res = ((BoolConstant) expr).Value;
278 ec.CurrentBranching.Infinite = infinite;
279 ec.EndFlowBranching ();
284 protected override void DoEmit (EmitContext ec)
286 ILGenerator ig = ec.ig;
287 Label loop = ig.DefineLabel ();
288 Label old_begin = ec.LoopBegin;
289 Label old_end = ec.LoopEnd;
291 ec.LoopBegin = ig.DefineLabel ();
292 ec.LoopEnd = ig.DefineLabel ();
295 EmbeddedStatement.Emit (ec);
296 ig.MarkLabel (ec.LoopBegin);
299 // Dead code elimination
301 if (expr is BoolConstant){
302 bool res = ((BoolConstant) expr).Value;
305 ec.ig.Emit (OpCodes.Br, loop);
307 expr.EmitBranchable (ec, loop, true);
309 ig.MarkLabel (ec.LoopEnd);
311 ec.LoopBegin = old_begin;
312 ec.LoopEnd = old_end;
316 public class While : Statement {
317 public Expression expr;
318 public readonly Statement Statement;
319 bool infinite, empty;
321 public While (Expression boolExpr, Statement statement, Location l)
323 this.expr = boolExpr;
324 Statement = statement;
328 public override bool Resolve (EmitContext ec)
332 expr = Expression.ResolveBoolean (ec, expr, loc);
337 // Inform whether we are infinite or not
339 if (expr is BoolConstant){
340 BoolConstant bc = (BoolConstant) expr;
342 if (bc.Value == false){
343 if (!Statement.ResolveUnreachable (ec, true))
351 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
353 ec.CurrentBranching.CreateSibling ();
355 if (!Statement.Resolve (ec))
358 ec.CurrentBranching.Infinite = infinite;
359 ec.EndFlowBranching ();
364 protected override void DoEmit (EmitContext ec)
369 ILGenerator ig = ec.ig;
370 Label old_begin = ec.LoopBegin;
371 Label old_end = ec.LoopEnd;
373 ec.LoopBegin = ig.DefineLabel ();
374 ec.LoopEnd = ig.DefineLabel ();
377 // Inform whether we are infinite or not
379 if (expr is BoolConstant){
380 ig.MarkLabel (ec.LoopBegin);
382 ig.Emit (OpCodes.Br, ec.LoopBegin);
385 // Inform that we are infinite (ie, `we return'), only
386 // if we do not `break' inside the code.
388 ig.MarkLabel (ec.LoopEnd);
390 Label while_loop = ig.DefineLabel ();
392 ig.Emit (OpCodes.Br, ec.LoopBegin);
393 ig.MarkLabel (while_loop);
397 ig.MarkLabel (ec.LoopBegin);
399 expr.EmitBranchable (ec, while_loop, true);
401 ig.MarkLabel (ec.LoopEnd);
404 ec.LoopBegin = old_begin;
405 ec.LoopEnd = old_end;
409 public class For : Statement {
411 readonly Statement InitStatement;
412 readonly Statement Increment;
413 readonly Statement Statement;
414 bool infinite, empty;
416 public For (Statement initStatement,
422 InitStatement = initStatement;
424 Increment = increment;
425 Statement = statement;
429 public override bool Resolve (EmitContext ec)
433 if (InitStatement != null){
434 if (!InitStatement.Resolve (ec))
439 Test = Expression.ResolveBoolean (ec, Test, loc);
442 else if (Test is BoolConstant){
443 BoolConstant bc = (BoolConstant) Test;
445 if (bc.Value == false){
446 if (!Statement.ResolveUnreachable (ec, true))
448 if ((Increment != null) &&
449 !Increment.ResolveUnreachable (ec, false))
459 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
461 ec.CurrentBranching.CreateSibling ();
463 if (!Statement.Resolve (ec))
466 if (Increment != null){
467 if (!Increment.Resolve (ec))
471 ec.CurrentBranching.Infinite = infinite;
472 ec.EndFlowBranching ();
477 protected override void DoEmit (EmitContext ec)
482 ILGenerator ig = ec.ig;
483 Label old_begin = ec.LoopBegin;
484 Label old_end = ec.LoopEnd;
485 Label loop = ig.DefineLabel ();
486 Label test = ig.DefineLabel ();
488 if (InitStatement != null && InitStatement != EmptyStatement.Value)
489 InitStatement.Emit (ec);
491 ec.LoopBegin = ig.DefineLabel ();
492 ec.LoopEnd = ig.DefineLabel ();
494 ig.Emit (OpCodes.Br, test);
498 ig.MarkLabel (ec.LoopBegin);
499 if (Increment != EmptyStatement.Value)
504 // If test is null, there is no test, and we are just
509 // The Resolve code already catches the case for
510 // Test == BoolConstant (false) so we know that
513 if (Test is BoolConstant)
514 ig.Emit (OpCodes.Br, loop);
516 Test.EmitBranchable (ec, loop, true);
519 ig.Emit (OpCodes.Br, loop);
520 ig.MarkLabel (ec.LoopEnd);
522 ec.LoopBegin = old_begin;
523 ec.LoopEnd = old_end;
527 public class StatementExpression : Statement {
528 ExpressionStatement expr;
530 public StatementExpression (ExpressionStatement expr, Location l)
536 public override bool Resolve (EmitContext ec)
539 expr = expr.ResolveStatement (ec);
543 protected override void DoEmit (EmitContext ec)
545 expr.EmitStatement (ec);
548 public override string ToString ()
550 return "StatementExpression (" + expr + ")";
555 /// Implements the return statement
557 public class Return : Statement {
558 public Expression Expr;
560 public Return (Expression expr, Location l)
568 public override bool Resolve (EmitContext ec)
570 AnonymousContainer am = ec.CurrentAnonymousMethod;
571 if ((am != null) && am.IsIterator && ec.InIterator) {
572 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
573 "statement to return a value, or yield break to end the iteration");
577 if (ec.ReturnType == null){
579 if (ec.CurrentAnonymousMethod != null){
580 Report.Error (1662, loc,
581 "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",
582 ec.CurrentAnonymousMethod.GetSignatureForError ());
584 Error (127, "A return keyword must not be followed by any expression when method returns void");
589 Error (126, "An object of a type convertible to `{0}' is required " +
590 "for the return statement",
591 TypeManager.CSharpName (ec.ReturnType));
595 Expr = Expr.Resolve (ec);
599 if (Expr.Type != ec.ReturnType) {
600 Expr = Convert.ImplicitConversionRequired (
601 ec, Expr, ec.ReturnType, loc);
607 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
609 if (ec.CurrentBranching.InTryOrCatch (true)) {
610 ec.CurrentBranching.AddFinallyVector (vector);
612 } else if (ec.InFinally) {
613 Error (157, "Control cannot leave the body of a finally clause");
616 vector.CheckOutParameters (ec.CurrentBranching);
619 ec.NeedReturnLabel ();
621 ec.CurrentBranching.CurrentUsageVector.Return ();
625 protected override void DoEmit (EmitContext ec)
631 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
635 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
637 ec.ig.Emit (OpCodes.Ret);
641 public class Goto : Statement {
643 LabeledStatement label;
645 public override bool Resolve (EmitContext ec)
647 label = ec.CurrentBranching.LookupLabel (target, loc);
651 // If this is a forward goto.
652 if (!label.IsDefined)
653 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
655 ec.CurrentBranching.CurrentUsageVector.Goto ();
656 label.AddReference ();
661 public Goto (string label, Location l)
667 public string Target {
673 protected override void DoEmit (EmitContext ec)
675 Label l = label.LabelTarget (ec);
676 ec.ig.Emit (OpCodes.Br, l);
680 public class LabeledStatement : Statement {
686 FlowBranching.UsageVector vectors;
688 public LabeledStatement (string label_name, Location l)
693 public Label LabelTarget (EmitContext ec)
698 label = ec.ig.DefineLabel ();
704 public bool IsDefined {
710 public bool HasBeenReferenced {
716 public void AddUsageVector (FlowBranching.UsageVector vector)
718 vector = vector.Clone ();
719 vector.Next = vectors;
723 public override bool Resolve (EmitContext ec)
725 ec.CurrentBranching.Label (vectors);
730 protected override void DoEmit (EmitContext ec)
732 if (ig != null && ig != ec.ig) {
733 // TODO: location is wrong
734 Report.Error (1632, loc, "Control cannot leave the body of an anonymous method");
738 ec.ig.MarkLabel (label);
741 public void AddReference ()
749 /// `goto default' statement
751 public class GotoDefault : Statement {
753 public GotoDefault (Location l)
758 public override bool Resolve (EmitContext ec)
760 ec.CurrentBranching.CurrentUsageVector.Goto ();
764 protected override void DoEmit (EmitContext ec)
766 if (ec.Switch == null){
767 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
771 if (!ec.Switch.GotDefault){
772 Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
775 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
780 /// `goto case' statement
782 public class GotoCase : Statement {
786 public GotoCase (Expression e, Location l)
792 public override bool Resolve (EmitContext ec)
794 if (ec.Switch == null){
795 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
799 expr = expr.Resolve (ec);
803 if (!(expr is Constant)){
804 Error (150, "A constant value is expected");
808 object val = Expression.ConvertIntLiteral (
809 (Constant) expr, ec.Switch.SwitchType, loc);
814 sl = (SwitchLabel) ec.Switch.Elements [val];
817 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", val);
821 ec.CurrentBranching.CurrentUsageVector.Goto ();
825 protected override void DoEmit (EmitContext ec)
827 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
831 public class Throw : Statement {
834 public Throw (Expression expr, Location l)
840 public override bool Resolve (EmitContext ec)
842 ec.CurrentBranching.CurrentUsageVector.Throw ();
845 expr = expr.Resolve (ec);
849 ExprClass eclass = expr.eclass;
851 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
852 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
853 expr.Error_UnexpectedKind (ec, "value, variable, property or indexer access ", loc);
859 if ((t != TypeManager.exception_type) &&
860 !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
861 !(expr is NullLiteral)) {
863 "The type caught or thrown must be derived " +
864 "from System.Exception");
871 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
876 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
882 protected override void DoEmit (EmitContext ec)
885 ec.ig.Emit (OpCodes.Rethrow);
889 ec.ig.Emit (OpCodes.Throw);
894 public class Break : Statement {
896 public Break (Location l)
903 public override bool Resolve (EmitContext ec)
905 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
906 Error (139, "No enclosing loop out of which to break or continue");
908 } else if (ec.InFinally && ec.CurrentBranching.BreakCrossesTryCatchBoundary()) {
909 Error (157, "Control cannot leave the body of a finally clause");
911 } else if (ec.CurrentBranching.InTryOrCatch (false))
912 ec.CurrentBranching.AddFinallyVector (
913 ec.CurrentBranching.CurrentUsageVector);
914 else if (ec.CurrentBranching.InLoop () || ec.CurrentBranching.InSwitch ())
915 ec.CurrentBranching.AddBreakVector (
916 ec.CurrentBranching.CurrentUsageVector);
918 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
921 ec.NeedReturnLabel ();
923 ec.CurrentBranching.CurrentUsageVector.Break ();
927 protected override void DoEmit (EmitContext ec)
929 ILGenerator ig = ec.ig;
932 ig.Emit (OpCodes.Leave, ec.LoopEnd);
934 ig.Emit (OpCodes.Br, ec.LoopEnd);
939 public class Continue : Statement {
941 public Continue (Location l)
948 public override bool Resolve (EmitContext ec)
950 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
951 Error (139, "No enclosing loop out of which to break or continue");
953 } else if (ec.InFinally) {
954 Error (157, "Control cannot leave the body of a finally clause");
956 } else if (ec.CurrentBranching.InTryOrCatch (false))
957 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
959 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
961 ec.CurrentBranching.CurrentUsageVector.Goto ();
965 protected override void DoEmit (EmitContext ec)
967 Label begin = ec.LoopBegin;
970 ec.ig.Emit (OpCodes.Leave, begin);
972 ec.ig.Emit (OpCodes.Br, begin);
977 // The information about a user-perceived local variable
979 public class LocalInfo {
980 public Expression Type;
983 // Most of the time a variable will be stored in a LocalBuilder
985 // But sometimes, it will be stored in a field (variables that have been
986 // hoisted by iterators or by anonymous methods). The context of the field will
987 // be stored in the EmitContext
990 public LocalBuilder LocalBuilder;
991 public FieldBuilder FieldBuilder;
993 public Type VariableType;
994 public readonly string Name;
995 public readonly Location Location;
996 public readonly Block Block;
998 public VariableInfo VariableInfo;
1007 CompilerGenerated = 64
1010 public enum ReadOnlyContext: byte {
1017 ReadOnlyContext ro_context;
1019 public LocalInfo (Expression type, string name, Block block, Location l)
1027 public LocalInfo (TypeContainer tc, Block block, Location l)
1029 VariableType = tc.TypeBuilder;
1034 public bool IsThisAssigned (EmitContext ec, Location loc)
1036 if (VariableInfo == null)
1037 throw new Exception ();
1039 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1042 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1045 public bool IsAssigned (EmitContext ec)
1047 if (VariableInfo == null)
1048 throw new Exception ();
1050 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1053 public bool Resolve (EmitContext ec)
1055 if (VariableType == null) {
1056 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
1060 VariableType = texpr.Type;
1063 if (VariableType == TypeManager.void_type) {
1064 Report.Error (1547, Location,
1065 "Keyword 'void' cannot be used in this context");
1069 if (VariableType.IsAbstract && VariableType.IsSealed) {
1070 Report.Error (723, Location, "Cannot declare variable of static type `{0}'", TypeManager.CSharpName (VariableType));
1074 if (VariableType.IsPointer && !ec.InUnsafe)
1075 Expression.UnsafeError (Location);
1080 public bool IsCaptured {
1082 return (flags & Flags.Captured) != 0;
1086 flags |= Flags.Captured;
1090 public bool AddressTaken {
1092 return (flags & Flags.AddressTaken) != 0;
1096 flags |= Flags.AddressTaken;
1100 public bool CompilerGenerated {
1102 return (flags & Flags.CompilerGenerated) != 0;
1106 flags |= Flags.CompilerGenerated;
1110 public override string ToString ()
1112 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1113 Name, Type, VariableInfo, Location);
1118 return (flags & Flags.Used) != 0;
1121 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1125 public bool ReadOnly {
1127 return (flags & Flags.ReadOnly) != 0;
1131 public void SetReadOnlyContext (ReadOnlyContext context)
1133 flags |= Flags.ReadOnly;
1134 ro_context = context;
1137 public string GetReadOnlyContext ()
1140 throw new InternalErrorException ("Variable is not readonly");
1142 switch (ro_context) {
1143 case ReadOnlyContext.Fixed:
1144 return "fixed variable";
1145 case ReadOnlyContext.Foreach:
1146 return "foreach iteration variable";
1147 case ReadOnlyContext.Using:
1148 return "using variable";
1150 throw new NotImplementedException ();
1154 // Whether the variable is pinned, if Pinned the variable has been
1155 // allocated in a pinned slot with DeclareLocal.
1157 public bool Pinned {
1159 return (flags & Flags.Pinned) != 0;
1162 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1166 public bool IsThis {
1168 return (flags & Flags.IsThis) != 0;
1171 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1177 /// Block represents a C# block.
1181 /// This class is used in a number of places: either to represent
1182 /// explicit blocks that the programmer places or implicit blocks.
1184 /// Implicit blocks are used as labels or to introduce variable
1187 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1188 /// they contain extra information that is not necessary on normal blocks.
1190 public class Block : Statement {
1191 public Block Parent;
1192 public readonly Location StartLocation;
1193 public Location EndLocation = Location.Null;
1195 public readonly ToplevelBlock Toplevel;
1202 VariablesInitialized = 8,
1210 public bool Implicit {
1211 get { return (flags & Flags.Implicit) != 0; }
1214 public bool Unchecked {
1215 get { return (flags & Flags.Unchecked) != 0; }
1216 set { flags |= Flags.Unchecked; }
1219 public bool Unsafe {
1220 get { return (flags & Flags.Unsafe) != 0; }
1221 set { flags |= Flags.Unsafe; }
1225 // The statements in this block
1227 ArrayList statements;
1231 // An array of Blocks. We keep track of children just
1232 // to generate the local variable declarations.
1234 // Statements and child statements are handled through the
1240 // Labels. (label, block) pairs.
1245 // Keeps track of (name, type) pairs
1247 Hashtable variables;
1250 // Keeps track of constants
1251 Hashtable constants;
1254 // Temporary variables.
1256 ArrayList temporary_variables;
1259 // If this is a switch section, the enclosing switch block.
1263 protected static int id;
1267 public Block (Block parent)
1268 : this (parent, (Flags) 0, Location.Null, Location.Null)
1271 public Block (Block parent, Flags flags)
1272 : this (parent, flags, Location.Null, Location.Null)
1275 public Block (Block parent, Location start, Location end)
1276 : this (parent, (Flags) 0, start, end)
1279 public Block (Block parent, Flags flags, Location start, Location end)
1282 parent.AddChild (this);
1284 this.Parent = parent;
1286 this.StartLocation = start;
1287 this.EndLocation = end;
1290 statements = new ArrayList ();
1292 if ((flags & Flags.IsToplevel) != 0)
1293 Toplevel = (ToplevelBlock) this;
1295 Toplevel = parent.Toplevel;
1297 if (parent != null && Implicit) {
1298 if (parent.known_variables == null)
1299 parent.known_variables = new Hashtable ();
1300 // share with parent
1301 known_variables = parent.known_variables;
1306 public Block CreateSwitchBlock (Location start)
1308 Block new_block = new Block (this, start, start);
1309 new_block.switch_block = this;
1314 get { return this_id; }
1317 protected Hashtable Variables {
1319 if (variables == null)
1320 variables = new Hashtable ();
1325 void AddChild (Block b)
1327 if (children == null)
1328 children = new ArrayList ();
1333 public void SetEndLocation (Location loc)
1339 /// Adds a label to the current block.
1343 /// false if the name already exists in this block. true
1347 public bool AddLabel (string name, LabeledStatement target, Location loc)
1349 if (switch_block != null)
1350 return switch_block.AddLabel (name, target, loc);
1353 while (cur != null) {
1354 if (cur.DoLookupLabel (name) != null) {
1356 140, loc, "The label `{0}' is a duplicate",
1367 while (cur != null) {
1368 if (cur.DoLookupLabel (name) != null) {
1371 "The label `{0}' shadows another label " +
1372 "by the same name in a contained scope.",
1377 if (children != null) {
1378 foreach (Block b in children) {
1379 LabeledStatement s = b.DoLookupLabel (name);
1385 "The label `{0}' shadows another " +
1386 "label by the same name in a " +
1398 labels = new Hashtable ();
1400 labels.Add (name, target);
1404 public LabeledStatement LookupLabel (string name)
1406 LabeledStatement s = DoLookupLabel (name);
1410 if (children == null)
1413 foreach (Block child in children) {
1414 if (!child.Implicit)
1417 s = child.LookupLabel (name);
1425 LabeledStatement DoLookupLabel (string name)
1427 if (switch_block != null)
1428 return switch_block.LookupLabel (name);
1431 if (labels.Contains (name))
1432 return ((LabeledStatement) labels [name]);
1437 Hashtable known_variables;
1440 // Marks a variable with name @name as being used in this or a child block.
1441 // If a variable name has been used in a child block, it's illegal to
1442 // declare a variable with the same name in the current block.
1444 void AddKnownVariable (string name, LocalInfo info)
1446 if (known_variables == null)
1447 known_variables = new Hashtable ();
1449 known_variables [name] = info;
1452 LocalInfo GetKnownVariableInfo (string name)
1454 if (known_variables == null)
1456 return (LocalInfo) known_variables [name];
1459 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1461 LocalInfo kvi = GetKnownVariableInfo (name);
1462 if (kvi == null || kvi.Block == this)
1465 if (known_variables != kvi.Block.known_variables) {
1466 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1467 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1472 // this block and kvi.Block are the same textual block.
1473 // However, different variables are extant.
1475 // Check if the variable is in scope in both blocks. We use
1476 // an indirect check that depends on AddVariable doing its
1477 // part in maintaining the invariant-meaning-in-block property.
1479 if (e is LocalVariableReference || (e is Constant && GetLocalInfo (name) != null))
1482 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1483 Error_AlreadyDeclared (loc, name, "parent or current");
1487 public LocalInfo AddVariable (Expression type, string name, Location l)
1489 LocalInfo vi = GetLocalInfo (name);
1491 Report.SymbolRelatedToPreviousError (vi.Location, name);
1492 if (known_variables == vi.Block.known_variables)
1493 Report.Error (128, l,
1494 "A local variable named `{0}' is already defined in this scope", name);
1496 Error_AlreadyDeclared (l, name, "parent");
1500 vi = GetKnownVariableInfo (name);
1502 Report.SymbolRelatedToPreviousError (vi.Location, name);
1503 Error_AlreadyDeclared (l, name, "child");
1508 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1510 Report.SymbolRelatedToPreviousError (p.Location, name);
1511 Error_AlreadyDeclared (l, name, "method argument");
1515 vi = new LocalInfo (type, name, this, l);
1517 Variables.Add (name, vi);
1519 for (Block b = this; b != null; b = b.Parent)
1520 b.AddKnownVariable (name, vi);
1522 if ((flags & Flags.VariablesInitialized) != 0)
1523 throw new Exception ();
1528 void Error_AlreadyDeclared (Location loc, string var, string reason)
1530 Report.Error (136, loc, "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning to `{0}', " +
1531 "which is already used in a `{1}' scope", var, reason);
1534 public bool AddConstant (Expression type, string name, Expression value, Location l)
1536 if (AddVariable (type, name, l) == null)
1539 if (constants == null)
1540 constants = new Hashtable ();
1542 constants.Add (name, value);
1546 static int next_temp_id = 0;
1548 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1550 if (temporary_variables == null)
1551 temporary_variables = new ArrayList ();
1553 int id = ++next_temp_id;
1554 string name = "$s_" + id.ToString ();
1556 LocalInfo li = new LocalInfo (te, name, this, loc);
1557 li.CompilerGenerated = true;
1558 temporary_variables.Add (li);
1562 public LocalInfo GetLocalInfo (string name)
1564 for (Block b = this; b != null; b = b.Parent) {
1565 if (b.variables != null) {
1566 LocalInfo ret = b.variables [name] as LocalInfo;
1574 public Expression GetVariableType (string name)
1576 LocalInfo vi = GetLocalInfo (name);
1577 return vi == null ? null : vi.Type;
1580 public Expression GetConstantExpression (string name)
1582 for (Block b = this; b != null; b = b.Parent) {
1583 if (b.constants != null) {
1584 Expression ret = b.constants [name] as Expression;
1593 /// True if the variable named @name is a constant
1595 public bool IsConstant (string name)
1597 Expression e = GetConstantExpression (name);
1601 public void AddStatement (Statement s)
1604 flags |= Flags.BlockUsed;
1608 get { return (flags & Flags.BlockUsed) != 0; }
1613 flags |= Flags.BlockUsed;
1616 public bool HasRet {
1617 get { return (flags & Flags.HasRet) != 0; }
1620 public bool IsDestructor {
1621 get { return (flags & Flags.IsDestructor) != 0; }
1624 public void SetDestructor ()
1626 flags |= Flags.IsDestructor;
1629 VariableMap param_map, local_map;
1631 public VariableMap ParameterMap {
1633 if ((flags & Flags.VariablesInitialized) == 0)
1634 throw new Exception ("Variables have not been initialized yet");
1640 public VariableMap LocalMap {
1642 if ((flags & Flags.VariablesInitialized) == 0)
1643 throw new Exception ("Variables have not been initialized yet");
1650 /// Emits the variable declarations and labels.
1653 /// tc: is our typecontainer (to resolve type references)
1654 /// ig: is the code generator:
1656 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1658 bool old_unsafe = ec.InUnsafe;
1660 // If some parent block was unsafe, we remain unsafe even if this block
1661 // isn't explicitly marked as such.
1662 ec.InUnsafe |= Unsafe;
1665 // Compute the VariableMap's.
1667 // Unfortunately, we don't know the type when adding variables with
1668 // AddVariable(), so we need to compute this info here.
1672 if (variables != null) {
1673 foreach (LocalInfo li in variables.Values)
1676 locals = new LocalInfo [variables.Count];
1677 variables.Values.CopyTo (locals, 0);
1679 locals = new LocalInfo [0];
1682 local_map = new VariableMap (Parent.LocalMap, locals);
1684 local_map = new VariableMap (locals);
1686 param_map = new VariableMap (ip);
1687 flags |= Flags.VariablesInitialized;
1689 bool old_check_state = ec.ConstantCheckState;
1690 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1693 // Process this block variables
1695 if (variables != null){
1696 foreach (DictionaryEntry de in variables){
1697 string name = (string) de.Key;
1698 LocalInfo vi = (LocalInfo) de.Value;
1700 if (vi.VariableType == null)
1703 Type variable_type = vi.VariableType;
1705 if (variable_type.IsPointer){
1707 // Am not really convinced that this test is required (Microsoft does it)
1708 // but the fact is that you would not be able to use the pointer variable
1711 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1716 if (constants == null)
1719 Expression cv = (Expression) constants [name];
1723 ec.CurrentBlock = this;
1724 Expression e = cv.Resolve (ec);
1726 Constant ce = e as Constant;
1728 Report.Error (133, vi.Location,
1729 "The expression being assigned to `{0}' must be constant", name);
1733 if (e.Type != variable_type){
1734 e = Const.ChangeType (vi.Location, ce, variable_type);
1739 constants.Remove (name);
1740 constants.Add (name, e);
1743 ec.ConstantCheckState = old_check_state;
1746 // Now, handle the children
1748 if (children != null){
1749 foreach (Block b in children)
1750 b.ResolveMeta (toplevel, ec, ip);
1752 ec.InUnsafe = old_unsafe;
1756 // Emits the local variable declarations for a block
1758 public void EmitMeta (EmitContext ec)
1760 ILGenerator ig = ec.ig;
1762 if (variables != null){
1763 bool have_captured_vars = ec.HaveCapturedVariables ();
1765 foreach (DictionaryEntry de in variables){
1766 LocalInfo vi = (LocalInfo) de.Value;
1768 if (have_captured_vars && ec.IsCaptured (vi))
1773 // This is needed to compile on both .NET 1.x and .NET 2.x
1774 // the later introduced `DeclareLocal (Type t, bool pinned)'
1776 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1777 else if (!vi.IsThis)
1778 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1782 if (temporary_variables != null) {
1783 AnonymousContainer am = ec.CurrentAnonymousMethod;
1784 TypeBuilder scope = null;
1785 if ((am != null) && am.IsIterator) {
1786 scope = am.Scope.ScopeTypeBuilder;
1788 throw new InternalErrorException ();
1790 foreach (LocalInfo vi in temporary_variables) {
1791 if (scope != null) {
1792 if (vi.FieldBuilder == null)
1793 vi.FieldBuilder = scope.DefineField (
1794 vi.Name, vi.VariableType, FieldAttributes.Assembly);
1796 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1800 if (children != null){
1801 foreach (Block b in children)
1806 void UsageWarning (FlowBranching.UsageVector vector)
1810 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1811 foreach (DictionaryEntry de in variables){
1812 LocalInfo vi = (LocalInfo) de.Value;
1817 name = (string) de.Key;
1819 if (vector.IsAssigned (vi.VariableInfo)){
1820 Report.Warning (219, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
1822 Report.Warning (168, vi.Location, "The variable `{0}' is declared but never used", name);
1828 bool unreachable_shown;
1831 public override bool Resolve (EmitContext ec)
1833 Block prev_block = ec.CurrentBlock;
1836 int errors = Report.Errors;
1838 ec.CurrentBlock = this;
1839 ec.StartFlowBranching (this);
1841 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1844 // This flag is used to notate nested statements as unreachable from the beginning of this block.
1845 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
1846 // from the beginning of the function. The outer Resolve() that detected the unreachability is
1847 // responsible for handling the situation.
1849 int statement_count = statements.Count;
1850 for (int ix = 0; ix < statement_count; ix++){
1851 Statement s = (Statement) statements [ix];
1855 ((Block) s).unreachable = true;
1857 if (!unreachable_shown && (RootContext.WarningLevel >= 2)) {
1859 162, loc, "Unreachable code detected");
1860 unreachable_shown = true;
1864 if (!s.Resolve (ec)) {
1866 statements [ix] = EmptyStatement.Value;
1870 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1871 statements [ix] = EmptyStatement.Value;
1873 num_statements = ix + 1;
1874 if (s is LabeledStatement)
1875 unreachable = false;
1877 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1880 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1881 ec.CurrentBranching, statement_count, num_statements);
1883 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1885 ec.CurrentBlock = prev_block;
1887 // If we're a non-static `struct' constructor which doesn't have an
1888 // initializer, then we must initialize all of the struct's fields.
1889 if ((flags & Flags.IsToplevel) != 0 &&
1890 !Toplevel.IsThisAssigned (ec) &&
1891 vector.Reachability.Throws != FlowBranching.FlowReturns.Always)
1894 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1895 foreach (LabeledStatement label in labels.Values)
1896 if (!label.HasBeenReferenced)
1897 Report.Warning (164, label.loc,
1898 "This label has not been referenced");
1901 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1903 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1904 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1905 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1906 flags |= Flags.HasRet;
1908 if (ok && (errors == Report.Errors)) {
1909 if (RootContext.WarningLevel >= 3)
1910 UsageWarning (vector);
1916 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1918 unreachable_shown = true;
1921 if (warn && (RootContext.WarningLevel >= 2))
1922 Report.Warning (162, loc, "Unreachable code detected");
1924 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1925 bool ok = Resolve (ec);
1926 ec.KillFlowBranching ();
1931 protected override void DoEmit (EmitContext ec)
1933 for (int ix = 0; ix < num_statements; ix++){
1934 Statement s = (Statement) statements [ix];
1936 // Check whether we are the last statement in a
1939 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
1940 ec.IsLastStatement = true;
1942 ec.IsLastStatement = false;
1948 public override void Emit (EmitContext ec)
1950 Block prev_block = ec.CurrentBlock;
1952 ec.CurrentBlock = this;
1954 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1955 bool is_lexical_block = !Implicit && (Parent != null);
1957 if (emit_debug_info) {
1958 if (is_lexical_block)
1961 if (variables != null) {
1962 foreach (DictionaryEntry de in variables) {
1963 string name = (string) de.Key;
1964 LocalInfo vi = (LocalInfo) de.Value;
1966 if (vi.LocalBuilder == null)
1969 ec.DefineLocalVariable (name, vi.LocalBuilder);
1974 ec.Mark (StartLocation, true);
1976 ec.Mark (EndLocation, true);
1978 if (emit_debug_info && is_lexical_block)
1981 ec.CurrentBlock = prev_block;
1985 // Returns true if we ar ea child of `b'.
1987 public bool IsChildOf (Block b)
1989 Block current = this;
1992 if (current.Parent == b)
1994 current = current.Parent;
1995 } while (current != null);
1999 public override string ToString ()
2001 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2006 // A toplevel block contains extra information, the split is done
2007 // only to separate information that would otherwise bloat the more
2008 // lightweight Block.
2010 // In particular, this was introduced when the support for Anonymous
2011 // Methods was implemented.
2013 public class ToplevelBlock : Block {
2015 // Pointer to the host of this anonymous method, or null
2016 // if we are the topmost block
2018 ToplevelBlock container;
2019 CaptureContext capture_context;
2020 FlowBranching top_level_branching;
2022 Hashtable capture_contexts;
2025 public bool HasVarargs = false;
2028 // The parameters for the block.
2030 Parameters parameters;
2031 public Parameters Parameters {
2032 get { return parameters; }
2035 public void RegisterCaptureContext (CaptureContext cc)
2037 if (capture_contexts == null)
2038 capture_contexts = new Hashtable ();
2039 capture_contexts [cc] = cc;
2042 public void CompleteContexts ()
2044 if (capture_contexts == null)
2047 foreach (CaptureContext cc in capture_contexts.Keys){
2052 public CaptureContext ToplevelBlockCaptureContext {
2053 get { return capture_context; }
2056 public ToplevelBlock Container {
2057 get { return container; }
2060 protected void AddChild (ToplevelBlock block)
2062 if (children == null)
2063 children = new ArrayList ();
2065 children.Add (block);
2069 // Parent is only used by anonymous blocks to link back to their
2072 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2073 this (container, (Flags) 0, parameters, start)
2077 public ToplevelBlock (Parameters parameters, Location start) :
2078 this (null, (Flags) 0, parameters, start)
2082 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2083 this (null, flags, parameters, start)
2087 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2088 base (null, flags | Flags.IsToplevel, start, Location.Null)
2090 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2091 this.container = container;
2093 if (container != null)
2094 container.AddChild (this);
2097 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2101 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2103 if (capture_context == null)
2104 capture_context = new CaptureContext (this, loc, host);
2107 public CaptureContext CaptureContext {
2108 get { return capture_context; }
2111 public FlowBranching TopLevelBranching {
2112 get { return top_level_branching; }
2116 // This is used if anonymous methods are used inside an iterator
2117 // (see 2test-22.cs for an example).
2119 // The AnonymousMethod is created while parsing - at a time when we don't
2120 // know yet that we're inside an iterator, so it's `Container' is initially
2121 // null. Later on, when resolving the iterator, we need to move the
2122 // anonymous method into that iterator.
2124 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2126 foreach (ToplevelBlock block in children) {
2127 if (block.CaptureContext == null)
2130 block.container = new_parent;
2131 block.CaptureContext.ReParent (new_parent, new_host);
2136 // Returns a `ParameterReference' for the given name, or null if there
2137 // is no such parameter
2139 public ParameterReference GetParameterReference (string name, Location loc)
2144 for (ToplevelBlock t = this; t != null; t = t.Container) {
2145 Parameters pars = t.Parameters;
2146 par = pars.GetParameterByName (name, out idx);
2148 return new ParameterReference (pars, this, idx, name, loc);
2154 // Whether the parameter named `name' is local to this block,
2155 // or false, if the parameter belongs to an encompassing block.
2157 public bool IsLocalParameter (string name)
2159 return Parameters.GetParameterByName (name) != null;
2163 // Whether the `name' is a parameter reference
2165 public bool IsParameterReference (string name)
2167 for (ToplevelBlock t = this; t != null; t = t.Container) {
2168 if (t.IsLocalParameter (name))
2174 LocalInfo this_variable = null;
2177 // Returns the "this" instance variable of this block.
2178 // See AddThisVariable() for more information.
2180 public LocalInfo ThisVariable {
2181 get { return this_variable; }
2186 // This is used by non-static `struct' constructors which do not have an
2187 // initializer - in this case, the constructor must initialize all of the
2188 // struct's fields. To do this, we add a "this" variable and use the flow
2189 // analysis code to ensure that it's been fully initialized before control
2190 // leaves the constructor.
2192 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
2194 if (this_variable == null) {
2195 this_variable = new LocalInfo (tc, this, l);
2196 this_variable.Used = true;
2197 this_variable.IsThis = true;
2199 Variables.Add ("this", this_variable);
2202 return this_variable;
2205 public bool IsThisAssigned (EmitContext ec)
2207 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2210 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2212 int errors = Report.Errors;
2214 if (top_level_branching != null)
2218 parameters = ip.Parameters;
2220 ResolveMeta (this, ec, ip);
2222 top_level_branching = ec.StartFlowBranching (this);
2224 return Report.Errors == errors;
2228 public class SwitchLabel {
2231 public Location loc;
2235 Label il_label_code;
2236 bool il_label_code_set;
2239 // if expr == null, then it is the default case.
2241 public SwitchLabel (Expression expr, Location l)
2247 public Expression Label {
2253 public object Converted {
2259 public Label GetILLabel (EmitContext ec)
2262 il_label = ec.ig.DefineLabel ();
2263 il_label_set = true;
2268 public Label GetILLabelCode (EmitContext ec)
2270 if (!il_label_code_set){
2271 il_label_code = ec.ig.DefineLabel ();
2272 il_label_code_set = true;
2274 return il_label_code;
2278 // Resolves the expression, reduces it to a literal if possible
2279 // and then converts it to the requested type.
2281 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2286 Expression e = label.Resolve (ec);
2291 if (!(e is Constant)){
2292 Report.Error (150, loc, "A constant value is expected, got: " + e);
2296 if (e is StringConstant || e is NullLiteral){
2297 if (required_type == TypeManager.string_type){
2303 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2304 if (converted == null)
2311 public class SwitchSection {
2312 // An array of SwitchLabels.
2313 public readonly ArrayList Labels;
2314 public readonly Block Block;
2316 public SwitchSection (ArrayList labels, Block block)
2323 public class Switch : Statement {
2324 public readonly ArrayList Sections;
2325 public Expression Expr;
2328 /// Maps constants whose type type SwitchType to their SwitchLabels.
2330 public Hashtable Elements;
2333 /// The governing switch type
2335 public Type SwitchType;
2340 Label default_target;
2341 Expression new_expr;
2343 SwitchSection constant_section;
2344 SwitchSection default_section;
2347 // The types allowed to be implicitly cast from
2348 // on the governing type
2350 static Type [] allowed_types;
2352 public Switch (Expression e, ArrayList sects, Location l)
2359 public bool GotDefault {
2361 return default_section != null;
2365 public Label DefaultTarget {
2367 return default_target;
2372 // Determines the governing type for a switch. The returned
2373 // expression might be the expression from the switch, or an
2374 // expression that includes any potential conversions to the
2375 // integral types or to string.
2377 Expression SwitchGoverningType (EmitContext ec, Type t)
2379 if (t == TypeManager.byte_type ||
2380 t == TypeManager.sbyte_type ||
2381 t == TypeManager.ushort_type ||
2382 t == TypeManager.short_type ||
2383 t == TypeManager.uint32_type ||
2384 t == TypeManager.int32_type ||
2385 t == TypeManager.uint64_type ||
2386 t == TypeManager.int64_type ||
2387 t == TypeManager.char_type ||
2388 t == TypeManager.string_type ||
2389 t == TypeManager.bool_type ||
2390 t.IsSubclassOf (TypeManager.enum_type))
2393 if (allowed_types == null){
2394 allowed_types = new Type [] {
2395 TypeManager.sbyte_type,
2396 TypeManager.byte_type,
2397 TypeManager.short_type,
2398 TypeManager.ushort_type,
2399 TypeManager.int32_type,
2400 TypeManager.uint32_type,
2401 TypeManager.int64_type,
2402 TypeManager.uint64_type,
2403 TypeManager.char_type,
2404 TypeManager.string_type,
2405 TypeManager.bool_type
2410 // Try to find a *user* defined implicit conversion.
2412 // If there is no implicit conversion, or if there are multiple
2413 // conversions, we have to report an error
2415 Expression converted = null;
2416 foreach (Type tt in allowed_types){
2419 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2424 // Ignore over-worked ImplicitUserConversions that do
2425 // an implicit conversion in addition to the user conversion.
2427 if (!(e is UserCast))
2430 if (converted != null){
2431 Report.ExtraInformation (
2433 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2434 TypeManager.CSharpName (Expr.Type)));
2443 static string Error152 {
2445 return "The label `{0}:' already occurs in this switch statement";
2450 // Performs the basic sanity checks on the switch statement
2451 // (looks for duplicate keys and non-constant expressions).
2453 // It also returns a hashtable with the keys that we will later
2454 // use to compute the switch tables
2456 bool CheckSwitch (EmitContext ec)
2460 Elements = new Hashtable ();
2462 if (TypeManager.IsEnumType (SwitchType)){
2463 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2465 compare_type = SwitchType;
2467 foreach (SwitchSection ss in Sections){
2468 foreach (SwitchLabel sl in ss.Labels){
2469 if (!sl.ResolveAndReduce (ec, SwitchType)){
2474 if (sl.Label == null){
2475 if (default_section != null){
2476 Report.Error (152, sl.loc, Error152, "default");
2479 default_section = ss;
2483 object key = sl.Converted;
2485 if (key is Constant)
2486 key = ((Constant) key).GetValue ();
2489 key = NullLiteral.Null;
2491 string lname = null;
2492 if (compare_type == TypeManager.uint64_type){
2493 ulong v = (ulong) key;
2495 if (Elements.Contains (v))
2496 lname = v.ToString ();
2498 Elements.Add (v, sl);
2499 } else if (compare_type == TypeManager.int64_type){
2500 long v = (long) key;
2502 if (Elements.Contains (v))
2503 lname = v.ToString ();
2505 Elements.Add (v, sl);
2506 } else if (compare_type == TypeManager.uint32_type){
2507 uint v = (uint) key;
2509 if (Elements.Contains (v))
2510 lname = v.ToString ();
2512 Elements.Add (v, sl);
2513 } else if (compare_type == TypeManager.char_type){
2514 char v = (char) key;
2516 if (Elements.Contains (v))
2517 lname = v.ToString ();
2519 Elements.Add (v, sl);
2520 } else if (compare_type == TypeManager.byte_type){
2521 byte v = (byte) key;
2523 if (Elements.Contains (v))
2524 lname = v.ToString ();
2526 Elements.Add (v, sl);
2527 } else if (compare_type == TypeManager.sbyte_type){
2528 sbyte v = (sbyte) key;
2530 if (Elements.Contains (v))
2531 lname = v.ToString ();
2533 Elements.Add (v, sl);
2534 } else if (compare_type == TypeManager.short_type){
2535 short v = (short) key;
2537 if (Elements.Contains (v))
2538 lname = v.ToString ();
2540 Elements.Add (v, sl);
2541 } else if (compare_type == TypeManager.ushort_type){
2542 ushort v = (ushort) key;
2544 if (Elements.Contains (v))
2545 lname = v.ToString ();
2547 Elements.Add (v, sl);
2548 } else if (compare_type == TypeManager.string_type){
2549 if (key is NullLiteral){
2550 if (Elements.Contains (NullLiteral.Null))
2553 Elements.Add (NullLiteral.Null, null);
2555 string s = (string) key;
2557 if (Elements.Contains (s))
2560 Elements.Add (s, sl);
2562 } else if (compare_type == TypeManager.int32_type) {
2565 if (Elements.Contains (v))
2566 lname = v.ToString ();
2568 Elements.Add (v, sl);
2569 } else if (compare_type == TypeManager.bool_type) {
2570 bool v = (bool) key;
2572 if (Elements.Contains (v))
2573 lname = v.ToString ();
2575 Elements.Add (v, sl);
2579 throw new Exception ("Unknown switch type!" +
2580 SwitchType + " " + compare_type);
2584 Report.Error (152, sl.loc, Error152, "case " + lname);
2595 void EmitObjectInteger (ILGenerator ig, object k)
2598 IntConstant.EmitInt (ig, (int) k);
2599 else if (k is Constant) {
2600 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2603 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2606 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2608 IntConstant.EmitInt (ig, (int) (long) k);
2609 ig.Emit (OpCodes.Conv_I8);
2612 LongConstant.EmitLong (ig, (long) k);
2614 else if (k is ulong)
2616 if ((ulong) k < (1L<<32))
2618 IntConstant.EmitInt (ig, (int) (long) k);
2619 ig.Emit (OpCodes.Conv_U8);
2623 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2627 IntConstant.EmitInt (ig, (int) ((char) k));
2628 else if (k is sbyte)
2629 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2631 IntConstant.EmitInt (ig, (int) ((byte) k));
2632 else if (k is short)
2633 IntConstant.EmitInt (ig, (int) ((short) k));
2634 else if (k is ushort)
2635 IntConstant.EmitInt (ig, (int) ((ushort) k));
2637 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2639 throw new Exception ("Unhandled case");
2642 // structure used to hold blocks of keys while calculating table switch
2643 class KeyBlock : IComparable
2645 public KeyBlock (long _nFirst)
2647 nFirst = nLast = _nFirst;
2651 public ArrayList rgKeys = null;
2652 // how many items are in the bucket
2653 public int Size = 1;
2656 get { return (int) (nLast - nFirst + 1); }
2658 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2660 return kbLast.nLast - kbFirst.nFirst + 1;
2662 public int CompareTo (object obj)
2664 KeyBlock kb = (KeyBlock) obj;
2665 int nLength = Length;
2666 int nLengthOther = kb.Length;
2667 if (nLengthOther == nLength)
2668 return (int) (kb.nFirst - nFirst);
2669 return nLength - nLengthOther;
2674 /// This method emits code for a lookup-based switch statement (non-string)
2675 /// Basically it groups the cases into blocks that are at least half full,
2676 /// and then spits out individual lookup opcodes for each block.
2677 /// It emits the longest blocks first, and short blocks are just
2678 /// handled with direct compares.
2680 /// <param name="ec"></param>
2681 /// <param name="val"></param>
2682 /// <returns></returns>
2683 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2685 int cElements = Elements.Count;
2686 object [] rgKeys = new object [cElements];
2687 Elements.Keys.CopyTo (rgKeys, 0);
2688 Array.Sort (rgKeys);
2690 // initialize the block list with one element per key
2691 ArrayList rgKeyBlocks = new ArrayList ();
2692 foreach (object key in rgKeys)
2693 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2696 // iteratively merge the blocks while they are at least half full
2697 // there's probably a really cool way to do this with a tree...
2698 while (rgKeyBlocks.Count > 1)
2700 ArrayList rgKeyBlocksNew = new ArrayList ();
2701 kbCurr = (KeyBlock) rgKeyBlocks [0];
2702 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2704 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2705 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2708 kbCurr.nLast = kb.nLast;
2709 kbCurr.Size += kb.Size;
2713 // start a new block
2714 rgKeyBlocksNew.Add (kbCurr);
2718 rgKeyBlocksNew.Add (kbCurr);
2719 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2721 rgKeyBlocks = rgKeyBlocksNew;
2724 // initialize the key lists
2725 foreach (KeyBlock kb in rgKeyBlocks)
2726 kb.rgKeys = new ArrayList ();
2728 // fill the key lists
2730 if (rgKeyBlocks.Count > 0) {
2731 kbCurr = (KeyBlock) rgKeyBlocks [0];
2732 foreach (object key in rgKeys)
2734 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2735 System.Convert.ToInt64 (key) > kbCurr.nLast;
2737 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2738 kbCurr.rgKeys.Add (key);
2742 // sort the blocks so we can tackle the largest ones first
2743 rgKeyBlocks.Sort ();
2745 // okay now we can start...
2746 ILGenerator ig = ec.ig;
2747 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2748 Label lblDefault = ig.DefineLabel ();
2750 Type typeKeys = null;
2751 if (rgKeys.Length > 0)
2752 typeKeys = rgKeys [0].GetType (); // used for conversions
2756 if (TypeManager.IsEnumType (SwitchType))
2757 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2759 compare_type = SwitchType;
2761 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2763 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2764 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2767 foreach (object key in kb.rgKeys)
2769 ig.Emit (OpCodes.Ldloc, val);
2770 EmitObjectInteger (ig, key);
2771 SwitchLabel sl = (SwitchLabel) Elements [key];
2772 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2777 // TODO: if all the keys in the block are the same and there are
2778 // no gaps/defaults then just use a range-check.
2779 if (compare_type == TypeManager.int64_type ||
2780 compare_type == TypeManager.uint64_type)
2782 // TODO: optimize constant/I4 cases
2784 // check block range (could be > 2^31)
2785 ig.Emit (OpCodes.Ldloc, val);
2786 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2787 ig.Emit (OpCodes.Blt, lblDefault);
2788 ig.Emit (OpCodes.Ldloc, val);
2789 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2790 ig.Emit (OpCodes.Bgt, lblDefault);
2793 ig.Emit (OpCodes.Ldloc, val);
2796 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2797 ig.Emit (OpCodes.Sub);
2799 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2804 ig.Emit (OpCodes.Ldloc, val);
2805 int nFirst = (int) kb.nFirst;
2808 IntConstant.EmitInt (ig, nFirst);
2809 ig.Emit (OpCodes.Sub);
2811 else if (nFirst < 0)
2813 IntConstant.EmitInt (ig, -nFirst);
2814 ig.Emit (OpCodes.Add);
2818 // first, build the list of labels for the switch
2820 int cJumps = kb.Length;
2821 Label [] rgLabels = new Label [cJumps];
2822 for (int iJump = 0; iJump < cJumps; iJump++)
2824 object key = kb.rgKeys [iKey];
2825 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2827 SwitchLabel sl = (SwitchLabel) Elements [key];
2828 rgLabels [iJump] = sl.GetILLabel (ec);
2832 rgLabels [iJump] = lblDefault;
2834 // emit the switch opcode
2835 ig.Emit (OpCodes.Switch, rgLabels);
2838 // mark the default for this block
2840 ig.MarkLabel (lblDefault);
2843 // TODO: find the default case and emit it here,
2844 // to prevent having to do the following jump.
2845 // make sure to mark other labels in the default section
2847 // the last default just goes to the end
2848 ig.Emit (OpCodes.Br, lblDefault);
2850 // now emit the code for the sections
2851 bool fFoundDefault = false;
2852 foreach (SwitchSection ss in Sections)
2854 foreach (SwitchLabel sl in ss.Labels)
2856 ig.MarkLabel (sl.GetILLabel (ec));
2857 ig.MarkLabel (sl.GetILLabelCode (ec));
2858 if (sl.Label == null)
2860 ig.MarkLabel (lblDefault);
2861 fFoundDefault = true;
2865 //ig.Emit (OpCodes.Br, lblEnd);
2868 if (!fFoundDefault) {
2869 ig.MarkLabel (lblDefault);
2871 ig.MarkLabel (lblEnd);
2874 // This simple emit switch works, but does not take advantage of the
2876 // TODO: remove non-string logic from here
2877 // TODO: binary search strings?
2879 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2881 ILGenerator ig = ec.ig;
2882 Label end_of_switch = ig.DefineLabel ();
2883 Label next_test = ig.DefineLabel ();
2884 Label null_target = ig.DefineLabel ();
2885 bool first_test = true;
2886 bool pending_goto_end = false;
2887 bool null_marked = false;
2890 ig.Emit (OpCodes.Ldloc, val);
2892 if (Elements.Contains (NullLiteral.Null)){
2893 ig.Emit (OpCodes.Brfalse, null_target);
2895 ig.Emit (OpCodes.Brfalse, default_target);
2897 ig.Emit (OpCodes.Ldloc, val);
2898 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2899 ig.Emit (OpCodes.Stloc, val);
2901 int section_count = Sections.Count;
2902 for (int section = 0; section < section_count; section++){
2903 SwitchSection ss = (SwitchSection) Sections [section];
2905 if (ss == default_section)
2908 Label sec_begin = ig.DefineLabel ();
2910 ig.Emit (OpCodes.Nop);
2912 if (pending_goto_end)
2913 ig.Emit (OpCodes.Br, end_of_switch);
2915 int label_count = ss.Labels.Count;
2917 for (int label = 0; label < label_count; label++){
2918 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2919 ig.MarkLabel (sl.GetILLabel (ec));
2922 ig.MarkLabel (next_test);
2923 next_test = ig.DefineLabel ();
2926 // If we are the default target
2928 if (sl.Label != null){
2929 object lit = sl.Converted;
2931 if (lit is NullLiteral){
2933 if (label_count == 1)
2934 ig.Emit (OpCodes.Br, next_test);
2938 StringConstant str = (StringConstant) lit;
2940 ig.Emit (OpCodes.Ldloc, val);
2941 ig.Emit (OpCodes.Ldstr, str.Value);
2942 if (label_count == 1)
2943 ig.Emit (OpCodes.Bne_Un, next_test);
2945 if (label+1 == label_count)
2946 ig.Emit (OpCodes.Bne_Un, next_test);
2948 ig.Emit (OpCodes.Beq, sec_begin);
2953 ig.MarkLabel (null_target);
2956 ig.MarkLabel (sec_begin);
2957 foreach (SwitchLabel sl in ss.Labels)
2958 ig.MarkLabel (sl.GetILLabelCode (ec));
2961 pending_goto_end = !ss.Block.HasRet;
2964 ig.MarkLabel (next_test);
2965 ig.MarkLabel (default_target);
2967 ig.MarkLabel (null_target);
2968 if (default_section != null)
2969 default_section.Block.Emit (ec);
2970 ig.MarkLabel (end_of_switch);
2973 SwitchSection FindSection (SwitchLabel label)
2975 foreach (SwitchSection ss in Sections){
2976 foreach (SwitchLabel sl in ss.Labels){
2985 public override bool Resolve (EmitContext ec)
2987 Expr = Expr.Resolve (ec);
2991 new_expr = SwitchGoverningType (ec, Expr.Type);
2992 if (new_expr == null){
2993 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2998 SwitchType = new_expr.Type;
3000 if (!CheckSwitch (ec))
3003 Switch old_switch = ec.Switch;
3005 ec.Switch.SwitchType = SwitchType;
3007 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3008 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3010 is_constant = new_expr is Constant;
3012 object key = ((Constant) new_expr).GetValue ();
3013 SwitchLabel label = (SwitchLabel) Elements [key];
3015 constant_section = FindSection (label);
3016 if (constant_section == null)
3017 constant_section = default_section;
3021 foreach (SwitchSection ss in Sections){
3023 ec.CurrentBranching.CreateSibling (
3024 null, FlowBranching.SiblingType.SwitchSection);
3028 if (is_constant && (ss != constant_section)) {
3029 // If we're a constant switch, we're only emitting
3030 // one single section - mark all the others as
3032 ec.CurrentBranching.CurrentUsageVector.Goto ();
3033 if (!ss.Block.ResolveUnreachable (ec, true))
3036 if (!ss.Block.Resolve (ec))
3041 if (default_section == null)
3042 ec.CurrentBranching.CreateSibling (
3043 null, FlowBranching.SiblingType.SwitchSection);
3045 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3046 ec.Switch = old_switch;
3048 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3054 protected override void DoEmit (EmitContext ec)
3056 ILGenerator ig = ec.ig;
3058 // Store variable for comparission purposes
3061 value = ig.DeclareLocal (SwitchType);
3063 ig.Emit (OpCodes.Stloc, value);
3067 default_target = ig.DefineLabel ();
3070 // Setup the codegen context
3072 Label old_end = ec.LoopEnd;
3073 Switch old_switch = ec.Switch;
3075 ec.LoopEnd = ig.DefineLabel ();
3080 if (constant_section != null)
3081 constant_section.Block.Emit (ec);
3082 } else if (SwitchType == TypeManager.string_type)
3083 SimpleSwitchEmit (ec, value);
3085 TableSwitchEmit (ec, value);
3087 // Restore context state.
3088 ig.MarkLabel (ec.LoopEnd);
3091 // Restore the previous context
3093 ec.LoopEnd = old_end;
3094 ec.Switch = old_switch;
3098 public abstract class ExceptionStatement : Statement
3100 public abstract void EmitFinally (EmitContext ec);
3102 protected bool emit_finally = true;
3103 ArrayList parent_vectors;
3105 protected void DoEmitFinally (EmitContext ec)
3108 ec.ig.BeginFinallyBlock ();
3109 else if (ec.InIterator)
3110 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3114 protected void ResolveFinally (FlowBranchingException branching)
3116 emit_finally = branching.EmitFinally;
3118 branching.Parent.StealFinallyClauses (ref parent_vectors);
3122 public class Lock : ExceptionStatement {
3124 Statement Statement;
3127 public Lock (Expression expr, Statement stmt, Location l)
3134 public override bool Resolve (EmitContext ec)
3136 expr = expr.Resolve (ec);
3140 if (expr.Type.IsValueType){
3141 Report.Error (185, loc,
3142 "`{0}' is not a reference type as required by the lock statement",
3143 TypeManager.CSharpName (expr.Type));
3147 FlowBranchingException branching = ec.StartFlowBranching (this);
3148 bool ok = Statement.Resolve (ec);
3150 ec.KillFlowBranching ();
3154 ResolveFinally (branching);
3156 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3157 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3158 // Unfortunately, System.Reflection.Emit automatically emits
3159 // a leave to the end of the finally block.
3160 // This is a problem if `returns' is true since we may jump
3161 // to a point after the end of the method.
3162 // As a workaround, emit an explicit ret here.
3163 ec.NeedReturnLabel ();
3169 protected override void DoEmit (EmitContext ec)
3171 Type type = expr.Type;
3173 ILGenerator ig = ec.ig;
3174 temp = ig.DeclareLocal (type);
3177 ig.Emit (OpCodes.Dup);
3178 ig.Emit (OpCodes.Stloc, temp);
3179 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3183 ig.BeginExceptionBlock ();
3184 Statement.Emit (ec);
3189 ig.EndExceptionBlock ();
3192 public override void EmitFinally (EmitContext ec)
3194 ILGenerator ig = ec.ig;
3195 ig.Emit (OpCodes.Ldloc, temp);
3196 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3200 public class Unchecked : Statement {
3201 public readonly Block Block;
3203 public Unchecked (Block b)
3209 public override bool Resolve (EmitContext ec)
3211 bool previous_state = ec.CheckState;
3212 bool previous_state_const = ec.ConstantCheckState;
3214 ec.CheckState = false;
3215 ec.ConstantCheckState = false;
3216 bool ret = Block.Resolve (ec);
3217 ec.CheckState = previous_state;
3218 ec.ConstantCheckState = previous_state_const;
3223 protected override void DoEmit (EmitContext ec)
3225 bool previous_state = ec.CheckState;
3226 bool previous_state_const = ec.ConstantCheckState;
3228 ec.CheckState = false;
3229 ec.ConstantCheckState = false;
3231 ec.CheckState = previous_state;
3232 ec.ConstantCheckState = previous_state_const;
3236 public class Checked : Statement {
3237 public readonly Block Block;
3239 public Checked (Block b)
3242 b.Unchecked = false;
3245 public override bool Resolve (EmitContext ec)
3247 bool previous_state = ec.CheckState;
3248 bool previous_state_const = ec.ConstantCheckState;
3250 ec.CheckState = true;
3251 ec.ConstantCheckState = true;
3252 bool ret = Block.Resolve (ec);
3253 ec.CheckState = previous_state;
3254 ec.ConstantCheckState = previous_state_const;
3259 protected override void DoEmit (EmitContext ec)
3261 bool previous_state = ec.CheckState;
3262 bool previous_state_const = ec.ConstantCheckState;
3264 ec.CheckState = true;
3265 ec.ConstantCheckState = true;
3267 ec.CheckState = previous_state;
3268 ec.ConstantCheckState = previous_state_const;
3272 public class Unsafe : Statement {
3273 public readonly Block Block;
3275 public Unsafe (Block b)
3278 Block.Unsafe = true;
3281 public override bool Resolve (EmitContext ec)
3283 bool previous_state = ec.InUnsafe;
3287 val = Block.Resolve (ec);
3288 ec.InUnsafe = previous_state;
3293 protected override void DoEmit (EmitContext ec)
3295 bool previous_state = ec.InUnsafe;
3299 ec.InUnsafe = previous_state;
3306 public class Fixed : Statement {
3308 ArrayList declarators;
3309 Statement statement;
3314 abstract class Emitter
3316 protected LocalInfo vi;
3317 protected Expression converted;
3319 protected Emitter (Expression expr, LocalInfo li)
3325 public abstract void Emit (EmitContext ec);
3326 public abstract void EmitExit (ILGenerator ig);
3329 class ExpressionEmitter: Emitter {
3330 public ExpressionEmitter (Expression converted, LocalInfo li) :
3331 base (converted, li)
3335 public override void Emit (EmitContext ec) {
3337 // Store pointer in pinned location
3339 converted.Emit (ec);
3340 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3343 public override void EmitExit (ILGenerator ig)
3345 ig.Emit (OpCodes.Ldc_I4_0);
3346 ig.Emit (OpCodes.Conv_U);
3347 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3351 class StringEmitter: Emitter {
3352 LocalBuilder pinned_string;
3355 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3361 public override void Emit (EmitContext ec)
3363 ILGenerator ig = ec.ig;
3364 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3366 converted.Emit (ec);
3367 ig.Emit (OpCodes.Stloc, pinned_string);
3369 Expression sptr = new StringPtr (pinned_string, loc);
3370 converted = Convert.ImplicitConversionRequired (
3371 ec, sptr, vi.VariableType, loc);
3373 if (converted == null)
3376 converted.Emit (ec);
3377 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3380 public override void EmitExit(ILGenerator ig)
3382 ig.Emit (OpCodes.Ldnull);
3383 ig.Emit (OpCodes.Stloc, pinned_string);
3387 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3390 declarators = decls;
3395 public override bool Resolve (EmitContext ec)
3398 Expression.UnsafeError (loc);
3402 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
3406 expr_type = texpr.Type;
3408 CheckObsolete (expr_type);
3410 data = new Emitter [declarators.Count];
3412 if (!expr_type.IsPointer){
3413 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3418 foreach (Pair p in declarators){
3419 LocalInfo vi = (LocalInfo) p.First;
3420 Expression e = (Expression) p.Second;
3422 vi.VariableInfo.SetAssigned (ec);
3423 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3426 // The rules for the possible declarators are pretty wise,
3427 // but the production on the grammar is more concise.
3429 // So we have to enforce these rules here.
3431 // We do not resolve before doing the case 1 test,
3432 // because the grammar is explicit in that the token &
3433 // is present, so we need to test for this particular case.
3437 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3442 // Case 1: & object.
3444 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3445 Expression child = ((Unary) e).Expr;
3447 if (child is ParameterReference || child is LocalVariableReference){
3450 "No need to use fixed statement for parameters or " +
3451 "local variable declarations (address is already " +
3456 ec.InFixedInitializer = true;
3458 ec.InFixedInitializer = false;
3462 child = ((Unary) e).Expr;
3464 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3467 data [i] = new ExpressionEmitter (e, vi);
3473 ec.InFixedInitializer = true;
3475 ec.InFixedInitializer = false;
3482 if (e.Type.IsArray){
3483 Type array_type = TypeManager.GetElementType (e.Type);
3486 // Provided that array_type is unmanaged,
3488 if (!TypeManager.VerifyUnManaged (array_type, loc))
3492 // and T* is implicitly convertible to the
3493 // pointer type given in the fixed statement.
3495 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3497 Expression converted = Convert.ImplicitConversionRequired (
3498 ec, array_ptr, vi.VariableType, loc);
3499 if (converted == null)
3502 data [i] = new ExpressionEmitter (converted, vi);
3511 if (e.Type == TypeManager.string_type){
3512 data [i] = new StringEmitter (e, vi, loc);
3517 // Case 4: fixed buffer
3518 FieldExpr fe = e as FieldExpr;
3520 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3522 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3524 Expression converted = Convert.ImplicitConversionRequired (
3525 ec, fixed_buffer_ptr, vi.VariableType, loc);
3526 if (converted == null)
3529 data [i] = new ExpressionEmitter (converted, vi);
3537 // For other cases, flag a `this is already fixed expression'
3539 if (e is LocalVariableReference || e is ParameterReference ||
3540 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3542 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3546 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3550 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3552 if (!statement.Resolve (ec)) {
3553 ec.KillFlowBranching ();
3557 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3558 has_ret = reachability.IsUnreachable;
3563 protected override void DoEmit (EmitContext ec)
3565 for (int i = 0; i < data.Length; i++) {
3569 statement.Emit (ec);
3574 ILGenerator ig = ec.ig;
3577 // Clear the pinned variable
3579 for (int i = 0; i < data.Length; i++) {
3580 data [i].EmitExit (ig);
3585 public class Catch: Statement {
3586 public readonly string Name;
3587 public readonly Block Block;
3589 Expression type_expr;
3592 public Catch (Expression type, string name, Block block, Location l)
3600 public Type CatchType {
3606 public bool IsGeneral {
3608 return type_expr == null;
3612 protected override void DoEmit(EmitContext ec)
3616 public override bool Resolve (EmitContext ec)
3618 bool was_catch = ec.InCatch;
3621 if (type_expr != null) {
3622 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
3626 type = te.ResolveType (ec);
3628 CheckObsolete (type);
3630 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3631 Error (155, "The type caught or thrown must be derived from System.Exception");
3637 return Block.Resolve (ec);
3640 ec.InCatch = was_catch;
3645 public class Try : ExceptionStatement {
3646 public readonly Block Fini, Block;
3647 public readonly ArrayList Specific;
3648 public readonly Catch General;
3650 bool need_exc_block;
3653 // specific, general and fini might all be null.
3655 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3657 if (specific == null && general == null){
3658 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3662 this.Specific = specific;
3663 this.General = general;
3668 public override bool Resolve (EmitContext ec)
3672 FlowBranchingException branching = ec.StartFlowBranching (this);
3674 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3676 if (!Block.Resolve (ec))
3679 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3681 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3683 Type[] prevCatches = new Type [Specific.Count];
3685 foreach (Catch c in Specific){
3686 ec.CurrentBranching.CreateSibling (
3687 c.Block, FlowBranching.SiblingType.Catch);
3689 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3691 if (c.Name != null) {
3692 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3694 throw new Exception ();
3696 vi.VariableInfo = null;
3699 if (!c.Resolve (ec))
3702 Type resolvedType = c.CatchType;
3703 for (int ii = 0; ii < last_index; ++ii) {
3704 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3705 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3710 prevCatches [last_index++] = resolvedType;
3711 need_exc_block = true;
3714 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3716 if (General != null){
3717 ec.CurrentBranching.CreateSibling (
3718 General.Block, FlowBranching.SiblingType.Catch);
3720 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3722 if (!General.Resolve (ec))
3725 need_exc_block = true;
3728 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3732 ec.CurrentBranching.CreateSibling (
3733 Fini, FlowBranching.SiblingType.Finally);
3735 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3736 bool was_finally = ec.InFinally;
3737 ec.InFinally = true;
3738 if (!Fini.Resolve (ec))
3740 ec.InFinally = was_finally;
3743 need_exc_block = true;
3746 if (ec.InIterator) {
3747 ResolveFinally (branching);
3748 need_exc_block |= emit_finally;
3750 emit_finally = Fini != null;
3752 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3754 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3756 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3758 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3759 // Unfortunately, System.Reflection.Emit automatically emits
3760 // a leave to the end of the finally block. This is a problem
3761 // if `returns' is true since we may jump to a point after the
3762 // end of the method.
3763 // As a workaround, emit an explicit ret here.
3764 ec.NeedReturnLabel ();
3770 protected override void DoEmit (EmitContext ec)
3772 ILGenerator ig = ec.ig;
3775 ig.BeginExceptionBlock ();
3778 foreach (Catch c in Specific){
3781 ig.BeginCatchBlock (c.CatchType);
3783 if (c.Name != null){
3784 vi = c.Block.GetLocalInfo (c.Name);
3786 throw new Exception ("Variable does not exist in this block");
3788 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3790 ec.EmitCapturedVariableInstance (vi);
3791 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
3792 ig.Emit (OpCodes.Stfld, vi.FieldBuilder);
3795 ig.Emit (OpCodes.Pop);
3800 if (General != null){
3801 ig.BeginCatchBlock (TypeManager.object_type);
3802 ig.Emit (OpCodes.Pop);
3803 General.Block.Emit (ec);
3808 ig.EndExceptionBlock ();
3811 public override void EmitFinally (EmitContext ec)
3817 public bool HasCatch
3820 return General != null || Specific.Count > 0;
3825 public class Using : ExceptionStatement {
3826 object expression_or_block;
3827 Statement Statement;
3832 Expression [] resolved_vars;
3833 Expression [] converted_vars;
3834 ExpressionStatement [] assign;
3835 LocalBuilder local_copy;
3837 public Using (object expression_or_block, Statement stmt, Location l)
3839 this.expression_or_block = expression_or_block;
3845 // Resolves for the case of using using a local variable declaration.
3847 bool ResolveLocalVariableDecls (EmitContext ec)
3851 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
3855 expr_type = texpr.Type;
3858 // The type must be an IDisposable or an implicit conversion
3861 converted_vars = new Expression [var_list.Count];
3862 resolved_vars = new Expression [var_list.Count];
3863 assign = new ExpressionStatement [var_list.Count];
3865 bool need_conv = !TypeManager.ImplementsInterface (
3866 expr_type, TypeManager.idisposable_type);
3868 foreach (DictionaryEntry e in var_list){
3869 Expression var = (Expression) e.Key;
3871 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3875 resolved_vars [i] = var;
3882 converted_vars [i] = Convert.ImplicitConversionRequired (
3883 ec, var, TypeManager.idisposable_type, loc);
3885 if (converted_vars [i] == null)
3892 foreach (DictionaryEntry e in var_list){
3893 Expression var = resolved_vars [i];
3894 Expression new_expr = (Expression) e.Value;
3897 a = new Assign (var, new_expr, loc);
3903 converted_vars [i] = var;
3904 assign [i] = (ExpressionStatement) a;
3911 bool ResolveExpression (EmitContext ec)
3913 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3914 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3915 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3916 TypeManager.CSharpName (expr_type));
3925 // Emits the code for the case of using using a local variable declaration.
3927 void EmitLocalVariableDecls (EmitContext ec)
3929 ILGenerator ig = ec.ig;
3932 for (i = 0; i < assign.Length; i++) {
3933 assign [i].EmitStatement (ec);
3936 ig.BeginExceptionBlock ();
3938 Statement.Emit (ec);
3940 var_list.Reverse ();
3945 void EmitLocalVariableDeclFinally (EmitContext ec)
3947 ILGenerator ig = ec.ig;
3949 int i = assign.Length;
3950 for (int ii = 0; ii < var_list.Count; ++ii){
3951 Expression var = resolved_vars [--i];
3952 Label skip = ig.DefineLabel ();
3954 ig.BeginFinallyBlock ();
3956 if (!var.Type.IsValueType) {
3958 ig.Emit (OpCodes.Brfalse, skip);
3959 converted_vars [i].Emit (ec);
3960 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3962 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3964 if (!(ml is MethodGroupExpr)) {
3966 ig.Emit (OpCodes.Box, var.Type);
3967 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3969 MethodInfo mi = null;
3971 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3972 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3979 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3983 IMemoryLocation mloc = (IMemoryLocation) var;
3985 mloc.AddressOf (ec, AddressOp.Load);
3986 ig.Emit (OpCodes.Call, mi);
3990 ig.MarkLabel (skip);
3993 ig.EndExceptionBlock ();
3995 ig.BeginFinallyBlock ();
4000 void EmitExpression (EmitContext ec)
4003 // Make a copy of the expression and operate on that.
4005 ILGenerator ig = ec.ig;
4006 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, 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.GetArgumentTypes (mk).Length == 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.Returns != FlowBranching.FlowReturns.Always) {
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 override bool Resolve (EmitContext ec)
4146 expr = expr.Resolve (ec);
4150 if (expr is NullLiteral) {
4151 Report.Error (186, loc, "Use of null is not valid in this context");
4155 TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
4159 Type var_type = texpr.Type;
4162 // We need an instance variable. Not sure this is the best
4163 // way of doing this.
4165 // FIXME: When we implement propertyaccess, will those turn
4166 // out to return values in ExprClass? I think they should.
4168 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4169 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4170 collection.error1579 ();
4174 if (expr.Type.IsArray) {
4175 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4176 return array.Resolve (ec);
4178 collection = new CollectionForeach (
4179 var_type, variable, expr, statement, loc);
4180 return collection.Resolve (ec);
4184 protected override void DoEmit (EmitContext ec)
4186 ILGenerator ig = ec.ig;
4188 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4189 ec.LoopBegin = ig.DefineLabel ();
4190 ec.LoopEnd = ig.DefineLabel ();
4192 if (collection != null)
4193 collection.Emit (ec);
4197 ec.LoopBegin = old_begin;
4198 ec.LoopEnd = old_end;
4201 protected class TemporaryVariable : Expression, IMemoryLocation
4205 public TemporaryVariable (Type type, Location loc)
4209 eclass = ExprClass.Value;
4212 public override Expression DoResolve (EmitContext ec)
4217 TypeExpr te = new TypeExpression (type, loc);
4218 li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
4219 if (!li.Resolve (ec))
4222 AnonymousContainer am = ec.CurrentAnonymousMethod;
4223 if ((am != null) && am.IsIterator)
4224 ec.CaptureVariable (li);
4229 public override void Emit (EmitContext ec)
4231 ILGenerator ig = ec.ig;
4233 if (li.FieldBuilder != null) {
4234 ig.Emit (OpCodes.Ldarg_0);
4235 ig.Emit (OpCodes.Ldfld, li.FieldBuilder);
4237 ig.Emit (OpCodes.Ldloc, li.LocalBuilder);
4241 public void EmitLoadAddress (EmitContext ec)
4243 ILGenerator ig = ec.ig;
4245 if (li.FieldBuilder != null) {
4246 ig.Emit (OpCodes.Ldarg_0);
4247 ig.Emit (OpCodes.Ldflda, li.FieldBuilder);
4249 ig.Emit (OpCodes.Ldloca, li.LocalBuilder);
4253 public void Store (EmitContext ec, Expression right_side)
4255 if (li.FieldBuilder != null)
4256 ec.ig.Emit (OpCodes.Ldarg_0);
4258 right_side.Emit (ec);
4259 if (li.FieldBuilder != null) {
4260 ec.ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4262 ec.ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4266 public void EmitThis (EmitContext ec)
4268 if (li.FieldBuilder != null) {
4269 ec.ig.Emit (OpCodes.Ldarg_0);
4273 public void EmitStore (ILGenerator ig)
4275 if (li.FieldBuilder != null)
4276 ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4278 ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4281 public void AddressOf (EmitContext ec, AddressOp mode)
4283 EmitLoadAddress (ec);
4287 protected class ArrayCounter : TemporaryVariable
4289 public ArrayCounter (Location loc)
4290 : base (TypeManager.int32_type, loc)
4293 public void Initialize (EmitContext ec)
4296 ec.ig.Emit (OpCodes.Ldc_I4_0);
4300 public void Increment (EmitContext ec)
4304 ec.ig.Emit (OpCodes.Ldc_I4_1);
4305 ec.ig.Emit (OpCodes.Add);
4310 protected class ArrayForeach : Statement
4312 Expression variable, expr, conv;
4313 Statement statement;
4316 TemporaryVariable[] lengths;
4317 ArrayCounter[] counter;
4320 TemporaryVariable copy;
4323 public ArrayForeach (Type var_type, Expression var,
4324 Expression expr, Statement stmt, Location l)
4326 this.var_type = var_type;
4327 this.variable = var;
4333 public override bool Resolve (EmitContext ec)
4335 array_type = expr.Type;
4336 rank = array_type.GetArrayRank ();
4338 copy = new TemporaryVariable (array_type, loc);
4341 counter = new ArrayCounter [rank];
4342 lengths = new TemporaryVariable [rank];
4344 ArrayList list = new ArrayList ();
4345 for (int i = 0; i < rank; i++) {
4346 counter [i] = new ArrayCounter (loc);
4347 counter [i].Resolve (ec);
4349 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4350 lengths [i].Resolve (ec);
4352 list.Add (counter [i]);
4355 access = new ElementAccess (copy, list, loc).Resolve (ec);
4359 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4365 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4366 ec.CurrentBranching.CreateSibling ();
4368 variable = variable.ResolveLValue (ec, conv, loc);
4369 if (variable == null)
4372 if (!statement.Resolve (ec))
4375 ec.EndFlowBranching ();
4380 protected override void DoEmit (EmitContext ec)
4382 ILGenerator ig = ec.ig;
4384 copy.Store (ec, expr);
4386 Label[] test = new Label [rank];
4387 Label[] loop = new Label [rank];
4389 for (int i = 0; i < rank; i++) {
4390 test [i] = ig.DefineLabel ();
4391 loop [i] = ig.DefineLabel ();
4393 lengths [i].EmitThis (ec);
4394 ((ArrayAccess) access).EmitGetLength (ec, i);
4395 lengths [i].EmitStore (ig);
4398 for (int i = 0; i < rank; i++) {
4399 counter [i].Initialize (ec);
4401 ig.Emit (OpCodes.Br, test [i]);
4402 ig.MarkLabel (loop [i]);
4405 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4407 statement.Emit (ec);
4409 ig.MarkLabel (ec.LoopBegin);
4411 for (int i = rank - 1; i >= 0; i--){
4412 counter [i].Increment (ec);
4414 ig.MarkLabel (test [i]);
4415 counter [i].Emit (ec);
4416 lengths [i].Emit (ec);
4417 ig.Emit (OpCodes.Blt, loop [i]);
4420 ig.MarkLabel (ec.LoopEnd);
4424 protected class CollectionForeach : ExceptionStatement
4426 Expression variable, expr;
4427 Statement statement;
4429 TemporaryVariable enumerator;
4433 MethodGroupExpr get_enumerator;
4434 PropertyExpr get_current;
4435 MethodInfo move_next;
4436 Type var_type, enumerator_type;
4439 public CollectionForeach (Type var_type, Expression var,
4440 Expression expr, Statement stmt, Location l)
4442 this.var_type = var_type;
4443 this.variable = var;
4449 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4451 Type [] args = TypeManager.GetArgumentTypes (mi);
4453 if (args.Length != 0)
4457 if (TypeManager.IsOverride (mi))
4460 // Check whether GetEnumerator is public
4461 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4464 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4466 // Apply the same optimization as MS: skip the GetEnumerator
4467 // returning an IEnumerator, and use the one returning a
4468 // CharEnumerator instead. This allows us to avoid the
4469 // try-finally block and the boxing.
4474 // Ok, we can access it, now make sure that we can do something
4475 // with this `GetEnumerator'
4478 Type return_type = mi.ReturnType;
4479 if (mi.ReturnType == TypeManager.ienumerator_type ||
4480 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4481 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4483 // If it is not an interface, lets try to find the methods ourselves.
4484 // For example, if we have:
4485 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4486 // We can avoid the iface call. This is a runtime perf boost.
4487 // even bigger if we have a ValueType, because we avoid the cost
4490 // We have to make sure that both methods exist for us to take
4491 // this path. If one of the methods does not exist, we will just
4492 // use the interface. Sadly, this complex if statement is the only
4493 // way I could do this without a goto
4496 if (return_type.IsInterface && return_type.IsGenericType) {
4497 enumerator_type = return_type;
4498 if (!FetchGetCurrent (ec, return_type))
4499 get_current = new PropertyExpr (
4500 ec, TypeManager.ienumerator_getcurrent, loc);
4501 if (!FetchMoveNext (ec, return_type))
4502 move_next = TypeManager.bool_movenext_void;
4506 if (return_type.IsInterface ||
4507 !FetchMoveNext (ec, return_type) ||
4508 !FetchGetCurrent (ec, return_type)) {
4509 enumerator_type = return_type;
4510 move_next = TypeManager.bool_movenext_void;
4511 get_current = new PropertyExpr (
4512 ec, TypeManager.ienumerator_getcurrent, loc);
4517 // Ok, so they dont return an IEnumerable, we will have to
4518 // find if they support the GetEnumerator pattern.
4521 if (!FetchMoveNext (ec, return_type))
4524 if (!FetchGetCurrent (ec, return_type))
4528 enumerator_type = return_type;
4529 is_disposable = !enumerator_type.IsSealed ||
4530 TypeManager.ImplementsInterface (
4531 enumerator_type, TypeManager.idisposable_type);
4537 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4539 bool FetchMoveNext (EmitContext ec, Type t)
4541 MemberList move_next_list;
4543 move_next_list = TypeContainer.FindMembers (
4544 t, MemberTypes.Method,
4545 Expression.AllBindingFlags,
4546 Type.FilterName, "MoveNext");
4547 if (move_next_list.Count == 0)
4551 foreach (MemberInfo m in move_next_list){
4552 MethodInfo mi = (MethodInfo) m;
4555 args = TypeManager.GetArgumentTypes (mi);
4556 if ((args != null) && (args.Length == 0) &&
4557 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4569 // Retrieves a `public T get_Current ()' method from the Type `t'
4571 bool FetchGetCurrent (EmitContext ec, Type t)
4573 PropertyExpr pe = Expression.MemberLookup (
4574 ec, t, "Current", MemberTypes.Property,
4575 Expression.AllBindingFlags, loc) as PropertyExpr;
4584 // Retrieves a `public void Dispose ()' method from the Type `t'
4586 static MethodInfo FetchMethodDispose (Type t)
4588 MemberList dispose_list;
4590 dispose_list = TypeContainer.FindMembers (
4591 t, MemberTypes.Method,
4592 BindingFlags.Public | BindingFlags.Instance,
4593 Type.FilterName, "Dispose");
4594 if (dispose_list.Count == 0)
4597 foreach (MemberInfo m in dispose_list){
4598 MethodInfo mi = (MethodInfo) m;
4601 args = TypeManager.GetArgumentTypes (mi);
4602 if (args != null && args.Length == 0){
4603 if (mi.ReturnType == TypeManager.void_type)
4610 public void error1579 ()
4612 Report.Error (1579, loc,
4613 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4614 TypeManager.CSharpName (expr.Type));
4617 bool TryType (EmitContext ec, Type t)
4619 MethodGroupExpr mg = Expression.MemberLookup (
4620 ec, t, "GetEnumerator", MemberTypes.Method,
4621 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4625 MethodBase result = null;
4626 MethodInfo tmp_move_next = null;
4627 PropertyExpr tmp_get_cur = null;
4628 Type tmp_enumerator_type = enumerator_type;
4629 foreach (MethodInfo mi in mg.Methods) {
4630 if (!GetEnumeratorFilter (ec, mi)) {
4635 tmp_move_next = move_next;
4636 tmp_get_cur = get_current;
4637 tmp_enumerator_type = enumerator_type;
4638 if (mi.DeclaringType == t)
4642 if (result != null) {
4643 move_next = tmp_move_next;
4644 get_current = tmp_get_cur;
4645 enumerator_type = tmp_enumerator_type;
4646 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
4647 get_enumerator = new MethodGroupExpr (mi, loc);
4649 if (t != expr.Type) {
4650 expr = Convert.ExplicitConversion (
4653 throw new InternalErrorException ();
4656 get_enumerator.InstanceExpression = expr;
4657 get_enumerator.IsBase = t != expr.Type;
4665 bool ProbeCollectionType (EmitContext ec, Type t)
4667 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4668 if (TryType (ec, tt))
4674 // Now try to find the method in the interfaces
4677 Type [] ifaces = t.GetInterfaces ();
4679 foreach (Type i in ifaces){
4680 if (TryType (ec, i))
4685 // Since TypeBuilder.GetInterfaces only returns the interface
4686 // types for this type, we have to keep looping, but once
4687 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4688 // done, because it returns all the types
4690 if ((t is TypeBuilder))
4699 public override bool Resolve (EmitContext ec)
4701 enumerator_type = TypeManager.ienumerator_type;
4702 is_disposable = true;
4704 if (!ProbeCollectionType (ec, expr.Type)) {
4709 enumerator = new TemporaryVariable (enumerator_type, loc);
4710 enumerator.Resolve (ec);
4712 init = new Invocation (get_enumerator, new ArrayList (), loc);
4713 init = init.Resolve (ec);
4717 Expression move_next_expr;
4719 MemberInfo[] mi = new MemberInfo[] { move_next };
4720 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4721 mg.InstanceExpression = enumerator;
4723 move_next_expr = new Invocation (mg, new ArrayList (), loc);
4726 get_current.InstanceExpression = enumerator;
4728 Statement block = new CollectionForeachStatement (
4729 var_type, variable, get_current, statement, loc);
4731 loop = new While (move_next_expr, block, loc);
4735 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4736 ec.CurrentBranching.CreateSibling ();
4738 FlowBranchingException branching = null;
4740 branching = ec.StartFlowBranching (this);
4742 if (!loop.Resolve (ec))
4745 if (is_disposable) {
4746 ResolveFinally (branching);
4747 ec.EndFlowBranching ();
4749 emit_finally = true;
4751 ec.EndFlowBranching ();
4756 protected override void DoEmit (EmitContext ec)
4758 ILGenerator ig = ec.ig;
4760 enumerator.Store (ec, init);
4763 // Protect the code in a try/finalize block, so that
4764 // if the beast implement IDisposable, we get rid of it
4766 if (is_disposable && emit_finally)
4767 ig.BeginExceptionBlock ();
4772 // Now the finally block
4774 if (is_disposable) {
4777 ig.EndExceptionBlock ();
4782 public override void EmitFinally (EmitContext ec)
4784 ILGenerator ig = ec.ig;
4786 if (enumerator_type.IsValueType) {
4787 enumerator.Emit (ec);
4789 MethodInfo mi = FetchMethodDispose (enumerator_type);
4791 enumerator.EmitLoadAddress (ec);
4792 ig.Emit (OpCodes.Call, mi);
4794 enumerator.Emit (ec);
4795 ig.Emit (OpCodes.Box, enumerator_type);
4796 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4799 Label call_dispose = ig.DefineLabel ();
4801 enumerator.Emit (ec);
4802 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4803 ig.Emit (OpCodes.Dup);
4804 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4805 ig.Emit (OpCodes.Pop);
4807 Label end_finally = ig.DefineLabel ();
4808 ig.Emit (OpCodes.Br, end_finally);
4810 ig.MarkLabel (call_dispose);
4811 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4812 ig.MarkLabel (end_finally);
4817 protected class CollectionForeachStatement : Statement
4820 Expression variable, current, conv;
4821 Statement statement;
4824 public CollectionForeachStatement (Type type, Expression variable,
4825 Expression current, Statement statement,
4829 this.variable = variable;
4830 this.current = current;
4831 this.statement = statement;
4835 public override bool Resolve (EmitContext ec)
4837 current = current.Resolve (ec);
4838 if (current == null)
4841 conv = Convert.ExplicitConversion (ec, current, type, loc);
4845 assign = new Assign (variable, conv, loc);
4846 if (assign.Resolve (ec) == null)
4849 if (!statement.Resolve (ec))
4855 protected override void DoEmit (EmitContext ec)
4857 assign.EmitStatement (ec);
4858 statement.Emit (ec);