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 !t.IsSubclassOf (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, false);
1060 VariableType = texpr.ResolveType (ec);
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);
1843 int statement_count = statements.Count;
1844 for (int ix = 0; ix < statement_count; ix++){
1845 Statement s = (Statement) statements [ix];
1848 // Warn if we detect unreachable code.
1852 ((Block) s).unreachable = true;
1854 if (!unreachable_shown && (RootContext.WarningLevel >= 2)) {
1856 162, loc, "Unreachable code detected");
1857 unreachable_shown = true;
1862 // Note that we're not using ResolveUnreachable() for unreachable
1863 // statements here. ResolveUnreachable() creates a temporary
1864 // flow branching and kills it afterwards. This leads to problems
1865 // if you have two unreachable statements where the first one
1866 // assigns a variable and the second one tries to access it.
1869 if (!s.Resolve (ec)) {
1871 statements [ix] = EmptyStatement.Value;
1875 if (unreachable && !(s is LabeledStatement) && !(s is Block))
1876 statements [ix] = EmptyStatement.Value;
1878 num_statements = ix + 1;
1879 if (s is LabeledStatement)
1880 unreachable = false;
1882 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1885 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1886 ec.CurrentBranching, statement_count, num_statements);
1888 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1890 ec.CurrentBlock = prev_block;
1892 // If we're a non-static `struct' constructor which doesn't have an
1893 // initializer, then we must initialize all of the struct's fields.
1894 if ((flags & Flags.IsToplevel) != 0 &&
1895 !Toplevel.IsThisAssigned (ec) &&
1896 vector.Reachability.Throws != FlowBranching.FlowReturns.Always)
1899 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1900 foreach (LabeledStatement label in labels.Values)
1901 if (!label.HasBeenReferenced)
1902 Report.Warning (164, label.loc,
1903 "This label has not been referenced");
1906 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1908 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1909 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1910 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1911 flags |= Flags.HasRet;
1913 if (ok && (errors == Report.Errors)) {
1914 if (RootContext.WarningLevel >= 3)
1915 UsageWarning (vector);
1921 public override bool ResolveUnreachable (EmitContext ec, bool warn)
1923 unreachable_shown = true;
1926 if (warn && (RootContext.WarningLevel >= 2))
1927 Report.Warning (162, loc, "Unreachable code detected");
1929 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
1930 bool ok = Resolve (ec);
1931 ec.KillFlowBranching ();
1936 protected override void DoEmit (EmitContext ec)
1938 for (int ix = 0; ix < num_statements; ix++){
1939 Statement s = (Statement) statements [ix];
1941 // Check whether we are the last statement in a
1944 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
1945 ec.IsLastStatement = true;
1947 ec.IsLastStatement = false;
1953 public override void Emit (EmitContext ec)
1955 Block prev_block = ec.CurrentBlock;
1957 ec.CurrentBlock = this;
1959 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1960 bool is_lexical_block = !Implicit && (Parent != null);
1962 if (emit_debug_info) {
1963 if (is_lexical_block)
1966 if (variables != null) {
1967 foreach (DictionaryEntry de in variables) {
1968 string name = (string) de.Key;
1969 LocalInfo vi = (LocalInfo) de.Value;
1971 if (vi.LocalBuilder == null)
1974 ec.DefineLocalVariable (name, vi.LocalBuilder);
1979 ec.Mark (StartLocation, true);
1981 ec.Mark (EndLocation, true);
1983 if (emit_debug_info && is_lexical_block)
1986 ec.CurrentBlock = prev_block;
1990 // Returns true if we ar ea child of `b'.
1992 public bool IsChildOf (Block b)
1994 Block current = this;
1997 if (current.Parent == b)
1999 current = current.Parent;
2000 } while (current != null);
2004 public override string ToString ()
2006 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2011 // A toplevel block contains extra information, the split is done
2012 // only to separate information that would otherwise bloat the more
2013 // lightweight Block.
2015 // In particular, this was introduced when the support for Anonymous
2016 // Methods was implemented.
2018 public class ToplevelBlock : Block {
2020 // Pointer to the host of this anonymous method, or null
2021 // if we are the topmost block
2023 ToplevelBlock container;
2024 CaptureContext capture_context;
2025 FlowBranching top_level_branching;
2027 Hashtable capture_contexts;
2030 public bool HasVarargs = false;
2033 // The parameters for the block.
2035 public readonly Parameters Parameters;
2037 public void RegisterCaptureContext (CaptureContext cc)
2039 if (capture_contexts == null)
2040 capture_contexts = new Hashtable ();
2041 capture_contexts [cc] = cc;
2044 public void CompleteContexts ()
2046 if (capture_contexts == null)
2049 foreach (CaptureContext cc in capture_contexts.Keys){
2054 public CaptureContext ToplevelBlockCaptureContext {
2055 get { return capture_context; }
2058 public ToplevelBlock Container {
2059 get { return container; }
2062 protected void AddChild (ToplevelBlock block)
2064 if (children == null)
2065 children = new ArrayList ();
2067 children.Add (block);
2071 // Parent is only used by anonymous blocks to link back to their
2074 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2075 this (container, (Flags) 0, parameters, start)
2079 public ToplevelBlock (Parameters parameters, Location start) :
2080 this (null, (Flags) 0, parameters, start)
2084 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2085 this (null, flags, parameters, start)
2089 public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
2090 base (null, flags | Flags.IsToplevel, start, Location.Null)
2092 Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2093 this.container = container;
2095 if (container != null)
2096 container.AddChild (this);
2099 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2103 public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
2105 if (capture_context == null)
2106 capture_context = new CaptureContext (this, loc, host);
2109 public CaptureContext CaptureContext {
2110 get { return capture_context; }
2113 public FlowBranching TopLevelBranching {
2114 get { return top_level_branching; }
2118 // This is used if anonymous methods are used inside an iterator
2119 // (see 2test-22.cs for an example).
2121 // The AnonymousMethod is created while parsing - at a time when we don't
2122 // know yet that we're inside an iterator, so it's `Container' is initially
2123 // null. Later on, when resolving the iterator, we need to move the
2124 // anonymous method into that iterator.
2126 public void ReParent (ToplevelBlock new_parent, AnonymousContainer new_host)
2128 foreach (ToplevelBlock block in children) {
2129 if (block.CaptureContext == null)
2132 block.container = new_parent;
2133 block.CaptureContext.ReParent (new_parent, new_host);
2138 // Returns a `ParameterReference' for the given name, or null if there
2139 // is no such parameter
2141 public ParameterReference GetParameterReference (string name, Location loc)
2146 for (ToplevelBlock t = this; t != null; t = t.Container) {
2147 Parameters pars = t.Parameters;
2148 par = pars.GetParameterByName (name, out idx);
2150 return new ParameterReference (pars, this, idx, name, loc);
2156 // Whether the parameter named `name' is local to this block,
2157 // or false, if the parameter belongs to an encompassing block.
2159 public bool IsLocalParameter (string name)
2161 return Parameters.GetParameterByName (name) != null;
2165 // Whether the `name' is a parameter reference
2167 public bool IsParameterReference (string name)
2169 for (ToplevelBlock t = this; t != null; t = t.Container) {
2170 if (t.IsLocalParameter (name))
2176 LocalInfo this_variable = null;
2179 // Returns the "this" instance variable of this block.
2180 // See AddThisVariable() for more information.
2182 public LocalInfo ThisVariable {
2183 get { return this_variable; }
2188 // This is used by non-static `struct' constructors which do not have an
2189 // initializer - in this case, the constructor must initialize all of the
2190 // struct's fields. To do this, we add a "this" variable and use the flow
2191 // analysis code to ensure that it's been fully initialized before control
2192 // leaves the constructor.
2194 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
2196 if (this_variable == null) {
2197 this_variable = new LocalInfo (tc, this, l);
2198 this_variable.Used = true;
2199 this_variable.IsThis = true;
2201 Variables.Add ("this", this_variable);
2204 return this_variable;
2207 public bool IsThisAssigned (EmitContext ec)
2209 return this_variable == null || this_variable.IsThisAssigned (ec, loc);
2212 public bool ResolveMeta (EmitContext ec, InternalParameters ip)
2214 int errors = Report.Errors;
2216 if (top_level_branching != null)
2219 ResolveMeta (this, ec, ip);
2221 top_level_branching = ec.StartFlowBranching (this);
2223 return Report.Errors == errors;
2227 public class SwitchLabel {
2230 public Location loc;
2234 Label il_label_code;
2235 bool il_label_code_set;
2238 // if expr == null, then it is the default case.
2240 public SwitchLabel (Expression expr, Location l)
2246 public Expression Label {
2252 public object Converted {
2258 public Label GetILLabel (EmitContext ec)
2261 il_label = ec.ig.DefineLabel ();
2262 il_label_set = true;
2267 public Label GetILLabelCode (EmitContext ec)
2269 if (!il_label_code_set){
2270 il_label_code = ec.ig.DefineLabel ();
2271 il_label_code_set = true;
2273 return il_label_code;
2277 // Resolves the expression, reduces it to a literal if possible
2278 // and then converts it to the requested type.
2280 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2285 Expression e = label.Resolve (ec);
2290 if (!(e is Constant)){
2291 Report.Error (150, loc, "A constant value is expected, got: " + e);
2295 if (e is StringConstant || e is NullLiteral){
2296 if (required_type == TypeManager.string_type){
2302 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2303 if (converted == null)
2310 public class SwitchSection {
2311 // An array of SwitchLabels.
2312 public readonly ArrayList Labels;
2313 public readonly Block Block;
2315 public SwitchSection (ArrayList labels, Block block)
2322 public class Switch : Statement {
2323 public readonly ArrayList Sections;
2324 public Expression Expr;
2327 /// Maps constants whose type type SwitchType to their SwitchLabels.
2329 public Hashtable Elements;
2332 /// The governing switch type
2334 public Type SwitchType;
2339 Label default_target;
2340 Expression new_expr;
2342 SwitchSection constant_section;
2343 SwitchSection default_section;
2346 // The types allowed to be implicitly cast from
2347 // on the governing type
2349 static Type [] allowed_types;
2351 public Switch (Expression e, ArrayList sects, Location l)
2358 public bool GotDefault {
2360 return default_section != null;
2364 public Label DefaultTarget {
2366 return default_target;
2371 // Determines the governing type for a switch. The returned
2372 // expression might be the expression from the switch, or an
2373 // expression that includes any potential conversions to the
2374 // integral types or to string.
2376 Expression SwitchGoverningType (EmitContext ec, Type t)
2378 if (t == TypeManager.byte_type ||
2379 t == TypeManager.sbyte_type ||
2380 t == TypeManager.ushort_type ||
2381 t == TypeManager.short_type ||
2382 t == TypeManager.uint32_type ||
2383 t == TypeManager.int32_type ||
2384 t == TypeManager.uint64_type ||
2385 t == TypeManager.int64_type ||
2386 t == TypeManager.char_type ||
2387 t == TypeManager.string_type ||
2388 t == TypeManager.bool_type ||
2389 t.IsSubclassOf (TypeManager.enum_type))
2392 if (allowed_types == null){
2393 allowed_types = new Type [] {
2394 TypeManager.sbyte_type,
2395 TypeManager.byte_type,
2396 TypeManager.short_type,
2397 TypeManager.ushort_type,
2398 TypeManager.int32_type,
2399 TypeManager.uint32_type,
2400 TypeManager.int64_type,
2401 TypeManager.uint64_type,
2402 TypeManager.char_type,
2403 TypeManager.string_type,
2404 TypeManager.bool_type
2409 // Try to find a *user* defined implicit conversion.
2411 // If there is no implicit conversion, or if there are multiple
2412 // conversions, we have to report an error
2414 Expression converted = null;
2415 foreach (Type tt in allowed_types){
2418 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2423 // Ignore over-worked ImplicitUserConversions that do
2424 // an implicit conversion in addition to the user conversion.
2426 if (!(e is UserCast))
2429 if (converted != null){
2430 Report.ExtraInformation (
2432 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2433 TypeManager.CSharpName (Expr.Type)));
2442 static string Error152 {
2444 return "The label `{0}:' already occurs in this switch statement";
2449 // Performs the basic sanity checks on the switch statement
2450 // (looks for duplicate keys and non-constant expressions).
2452 // It also returns a hashtable with the keys that we will later
2453 // use to compute the switch tables
2455 bool CheckSwitch (EmitContext ec)
2459 Elements = new Hashtable ();
2461 if (TypeManager.IsEnumType (SwitchType)){
2462 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2464 compare_type = SwitchType;
2466 foreach (SwitchSection ss in Sections){
2467 foreach (SwitchLabel sl in ss.Labels){
2468 if (!sl.ResolveAndReduce (ec, SwitchType)){
2473 if (sl.Label == null){
2474 if (default_section != null){
2475 Report.Error (152, sl.loc, Error152, "default");
2478 default_section = ss;
2482 object key = sl.Converted;
2484 if (key is Constant)
2485 key = ((Constant) key).GetValue ();
2488 key = NullLiteral.Null;
2490 string lname = null;
2491 if (compare_type == TypeManager.uint64_type){
2492 ulong v = (ulong) key;
2494 if (Elements.Contains (v))
2495 lname = v.ToString ();
2497 Elements.Add (v, sl);
2498 } else if (compare_type == TypeManager.int64_type){
2499 long v = (long) key;
2501 if (Elements.Contains (v))
2502 lname = v.ToString ();
2504 Elements.Add (v, sl);
2505 } else if (compare_type == TypeManager.uint32_type){
2506 uint v = (uint) key;
2508 if (Elements.Contains (v))
2509 lname = v.ToString ();
2511 Elements.Add (v, sl);
2512 } else if (compare_type == TypeManager.char_type){
2513 char v = (char) key;
2515 if (Elements.Contains (v))
2516 lname = v.ToString ();
2518 Elements.Add (v, sl);
2519 } else if (compare_type == TypeManager.byte_type){
2520 byte v = (byte) key;
2522 if (Elements.Contains (v))
2523 lname = v.ToString ();
2525 Elements.Add (v, sl);
2526 } else if (compare_type == TypeManager.sbyte_type){
2527 sbyte v = (sbyte) key;
2529 if (Elements.Contains (v))
2530 lname = v.ToString ();
2532 Elements.Add (v, sl);
2533 } else if (compare_type == TypeManager.short_type){
2534 short v = (short) key;
2536 if (Elements.Contains (v))
2537 lname = v.ToString ();
2539 Elements.Add (v, sl);
2540 } else if (compare_type == TypeManager.ushort_type){
2541 ushort v = (ushort) key;
2543 if (Elements.Contains (v))
2544 lname = v.ToString ();
2546 Elements.Add (v, sl);
2547 } else if (compare_type == TypeManager.string_type){
2548 if (key is NullLiteral){
2549 if (Elements.Contains (NullLiteral.Null))
2552 Elements.Add (NullLiteral.Null, null);
2554 string s = (string) key;
2556 if (Elements.Contains (s))
2559 Elements.Add (s, sl);
2561 } else if (compare_type == TypeManager.int32_type) {
2564 if (Elements.Contains (v))
2565 lname = v.ToString ();
2567 Elements.Add (v, sl);
2568 } else if (compare_type == TypeManager.bool_type) {
2569 bool v = (bool) key;
2571 if (Elements.Contains (v))
2572 lname = v.ToString ();
2574 Elements.Add (v, sl);
2578 throw new Exception ("Unknown switch type!" +
2579 SwitchType + " " + compare_type);
2582 if (lname != null) {
2583 Report.Error (152, sl.loc, Error152, "case " + lname);
2594 void EmitObjectInteger (ILGenerator ig, object k)
2597 IntConstant.EmitInt (ig, (int) k);
2598 else if (k is Constant) {
2599 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2602 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2605 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2607 IntConstant.EmitInt (ig, (int) (long) k);
2608 ig.Emit (OpCodes.Conv_I8);
2611 LongConstant.EmitLong (ig, (long) k);
2613 else if (k is ulong)
2615 if ((ulong) k < (1L<<32))
2617 IntConstant.EmitInt (ig, (int) (long) k);
2618 ig.Emit (OpCodes.Conv_U8);
2622 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2626 IntConstant.EmitInt (ig, (int) ((char) k));
2627 else if (k is sbyte)
2628 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2630 IntConstant.EmitInt (ig, (int) ((byte) k));
2631 else if (k is short)
2632 IntConstant.EmitInt (ig, (int) ((short) k));
2633 else if (k is ushort)
2634 IntConstant.EmitInt (ig, (int) ((ushort) k));
2636 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2638 throw new Exception ("Unhandled case");
2641 // structure used to hold blocks of keys while calculating table switch
2642 class KeyBlock : IComparable
2644 public KeyBlock (long _nFirst)
2646 nFirst = nLast = _nFirst;
2650 public ArrayList rgKeys = null;
2651 // how many items are in the bucket
2652 public int Size = 1;
2655 get { return (int) (nLast - nFirst + 1); }
2657 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2659 return kbLast.nLast - kbFirst.nFirst + 1;
2661 public int CompareTo (object obj)
2663 KeyBlock kb = (KeyBlock) obj;
2664 int nLength = Length;
2665 int nLengthOther = kb.Length;
2666 if (nLengthOther == nLength)
2667 return (int) (kb.nFirst - nFirst);
2668 return nLength - nLengthOther;
2673 /// This method emits code for a lookup-based switch statement (non-string)
2674 /// Basically it groups the cases into blocks that are at least half full,
2675 /// and then spits out individual lookup opcodes for each block.
2676 /// It emits the longest blocks first, and short blocks are just
2677 /// handled with direct compares.
2679 /// <param name="ec"></param>
2680 /// <param name="val"></param>
2681 /// <returns></returns>
2682 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2684 int cElements = Elements.Count;
2685 object [] rgKeys = new object [cElements];
2686 Elements.Keys.CopyTo (rgKeys, 0);
2687 Array.Sort (rgKeys);
2689 // initialize the block list with one element per key
2690 ArrayList rgKeyBlocks = new ArrayList ();
2691 foreach (object key in rgKeys)
2692 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2695 // iteratively merge the blocks while they are at least half full
2696 // there's probably a really cool way to do this with a tree...
2697 while (rgKeyBlocks.Count > 1)
2699 ArrayList rgKeyBlocksNew = new ArrayList ();
2700 kbCurr = (KeyBlock) rgKeyBlocks [0];
2701 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2703 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2704 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2707 kbCurr.nLast = kb.nLast;
2708 kbCurr.Size += kb.Size;
2712 // start a new block
2713 rgKeyBlocksNew.Add (kbCurr);
2717 rgKeyBlocksNew.Add (kbCurr);
2718 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2720 rgKeyBlocks = rgKeyBlocksNew;
2723 // initialize the key lists
2724 foreach (KeyBlock kb in rgKeyBlocks)
2725 kb.rgKeys = new ArrayList ();
2727 // fill the key lists
2729 if (rgKeyBlocks.Count > 0) {
2730 kbCurr = (KeyBlock) rgKeyBlocks [0];
2731 foreach (object key in rgKeys)
2733 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2734 System.Convert.ToInt64 (key) > kbCurr.nLast;
2736 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2737 kbCurr.rgKeys.Add (key);
2741 // sort the blocks so we can tackle the largest ones first
2742 rgKeyBlocks.Sort ();
2744 // okay now we can start...
2745 ILGenerator ig = ec.ig;
2746 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2747 Label lblDefault = ig.DefineLabel ();
2749 Type typeKeys = null;
2750 if (rgKeys.Length > 0)
2751 typeKeys = rgKeys [0].GetType (); // used for conversions
2755 if (TypeManager.IsEnumType (SwitchType))
2756 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2758 compare_type = SwitchType;
2760 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2762 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2763 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2766 foreach (object key in kb.rgKeys)
2768 ig.Emit (OpCodes.Ldloc, val);
2769 EmitObjectInteger (ig, key);
2770 SwitchLabel sl = (SwitchLabel) Elements [key];
2771 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2776 // TODO: if all the keys in the block are the same and there are
2777 // no gaps/defaults then just use a range-check.
2778 if (compare_type == TypeManager.int64_type ||
2779 compare_type == TypeManager.uint64_type)
2781 // TODO: optimize constant/I4 cases
2783 // check block range (could be > 2^31)
2784 ig.Emit (OpCodes.Ldloc, val);
2785 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2786 ig.Emit (OpCodes.Blt, lblDefault);
2787 ig.Emit (OpCodes.Ldloc, val);
2788 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2789 ig.Emit (OpCodes.Bgt, lblDefault);
2792 ig.Emit (OpCodes.Ldloc, val);
2795 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2796 ig.Emit (OpCodes.Sub);
2798 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2803 ig.Emit (OpCodes.Ldloc, val);
2804 int nFirst = (int) kb.nFirst;
2807 IntConstant.EmitInt (ig, nFirst);
2808 ig.Emit (OpCodes.Sub);
2810 else if (nFirst < 0)
2812 IntConstant.EmitInt (ig, -nFirst);
2813 ig.Emit (OpCodes.Add);
2817 // first, build the list of labels for the switch
2819 int cJumps = kb.Length;
2820 Label [] rgLabels = new Label [cJumps];
2821 for (int iJump = 0; iJump < cJumps; iJump++)
2823 object key = kb.rgKeys [iKey];
2824 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2826 SwitchLabel sl = (SwitchLabel) Elements [key];
2827 rgLabels [iJump] = sl.GetILLabel (ec);
2831 rgLabels [iJump] = lblDefault;
2833 // emit the switch opcode
2834 ig.Emit (OpCodes.Switch, rgLabels);
2837 // mark the default for this block
2839 ig.MarkLabel (lblDefault);
2842 // TODO: find the default case and emit it here,
2843 // to prevent having to do the following jump.
2844 // make sure to mark other labels in the default section
2846 // the last default just goes to the end
2847 ig.Emit (OpCodes.Br, lblDefault);
2849 // now emit the code for the sections
2850 bool fFoundDefault = false;
2851 foreach (SwitchSection ss in Sections)
2853 foreach (SwitchLabel sl in ss.Labels)
2855 ig.MarkLabel (sl.GetILLabel (ec));
2856 ig.MarkLabel (sl.GetILLabelCode (ec));
2857 if (sl.Label == null)
2859 ig.MarkLabel (lblDefault);
2860 fFoundDefault = true;
2864 //ig.Emit (OpCodes.Br, lblEnd);
2867 if (!fFoundDefault) {
2868 ig.MarkLabel (lblDefault);
2870 ig.MarkLabel (lblEnd);
2873 // This simple emit switch works, but does not take advantage of the
2875 // TODO: remove non-string logic from here
2876 // TODO: binary search strings?
2878 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2880 ILGenerator ig = ec.ig;
2881 Label end_of_switch = ig.DefineLabel ();
2882 Label next_test = ig.DefineLabel ();
2883 Label null_target = ig.DefineLabel ();
2884 bool first_test = true;
2885 bool pending_goto_end = false;
2886 bool null_marked = false;
2889 ig.Emit (OpCodes.Ldloc, val);
2891 if (Elements.Contains (NullLiteral.Null)){
2892 ig.Emit (OpCodes.Brfalse, null_target);
2894 ig.Emit (OpCodes.Brfalse, default_target);
2896 ig.Emit (OpCodes.Ldloc, val);
2897 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2898 ig.Emit (OpCodes.Stloc, val);
2900 int section_count = Sections.Count;
2901 for (int section = 0; section < section_count; section++){
2902 SwitchSection ss = (SwitchSection) Sections [section];
2904 if (ss == default_section)
2907 Label sec_begin = ig.DefineLabel ();
2909 ig.Emit (OpCodes.Nop);
2911 if (pending_goto_end)
2912 ig.Emit (OpCodes.Br, end_of_switch);
2914 int label_count = ss.Labels.Count;
2916 for (int label = 0; label < label_count; label++){
2917 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2918 ig.MarkLabel (sl.GetILLabel (ec));
2921 ig.MarkLabel (next_test);
2922 next_test = ig.DefineLabel ();
2925 // If we are the default target
2927 if (sl.Label != null){
2928 object lit = sl.Converted;
2930 if (lit is NullLiteral){
2932 if (label_count == 1)
2933 ig.Emit (OpCodes.Br, next_test);
2937 StringConstant str = (StringConstant) lit;
2939 ig.Emit (OpCodes.Ldloc, val);
2940 ig.Emit (OpCodes.Ldstr, str.Value);
2941 if (label_count == 1)
2942 ig.Emit (OpCodes.Bne_Un, next_test);
2944 if (label+1 == label_count)
2945 ig.Emit (OpCodes.Bne_Un, next_test);
2947 ig.Emit (OpCodes.Beq, sec_begin);
2952 ig.MarkLabel (null_target);
2955 ig.MarkLabel (sec_begin);
2956 foreach (SwitchLabel sl in ss.Labels)
2957 ig.MarkLabel (sl.GetILLabelCode (ec));
2960 pending_goto_end = !ss.Block.HasRet;
2963 ig.MarkLabel (next_test);
2964 ig.MarkLabel (default_target);
2966 ig.MarkLabel (null_target);
2967 if (default_section != null)
2968 default_section.Block.Emit (ec);
2969 ig.MarkLabel (end_of_switch);
2972 SwitchSection FindSection (SwitchLabel label)
2974 foreach (SwitchSection ss in Sections){
2975 foreach (SwitchLabel sl in ss.Labels){
2984 public override bool Resolve (EmitContext ec)
2986 Expr = Expr.Resolve (ec);
2990 new_expr = SwitchGoverningType (ec, Expr.Type);
2991 if (new_expr == null){
2992 Report.Error (151, loc, "A value of an integral type or string expected for switch");
2997 SwitchType = new_expr.Type;
2999 if (!CheckSwitch (ec))
3002 Switch old_switch = ec.Switch;
3004 ec.Switch.SwitchType = SwitchType;
3006 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3007 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3009 is_constant = new_expr is Constant;
3011 object key = ((Constant) new_expr).GetValue ();
3012 SwitchLabel label = (SwitchLabel) Elements [key];
3014 constant_section = FindSection (label);
3015 if (constant_section == null)
3016 constant_section = default_section;
3020 foreach (SwitchSection ss in Sections){
3022 ec.CurrentBranching.CreateSibling (
3023 null, FlowBranching.SiblingType.SwitchSection);
3027 if (is_constant && (ss != constant_section)) {
3028 // If we're a constant switch, we're only emitting
3029 // one single section - mark all the others as
3031 ec.CurrentBranching.CurrentUsageVector.Goto ();
3032 if (!ss.Block.ResolveUnreachable (ec, true))
3035 if (!ss.Block.Resolve (ec))
3040 if (default_section == null)
3041 ec.CurrentBranching.CreateSibling (
3042 null, FlowBranching.SiblingType.SwitchSection);
3044 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3045 ec.Switch = old_switch;
3047 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3053 protected override void DoEmit (EmitContext ec)
3055 ILGenerator ig = ec.ig;
3057 // Store variable for comparission purposes
3060 value = ig.DeclareLocal (SwitchType);
3062 ig.Emit (OpCodes.Stloc, value);
3066 default_target = ig.DefineLabel ();
3069 // Setup the codegen context
3071 Label old_end = ec.LoopEnd;
3072 Switch old_switch = ec.Switch;
3074 ec.LoopEnd = ig.DefineLabel ();
3079 if (constant_section != null)
3080 constant_section.Block.Emit (ec);
3081 } else if (SwitchType == TypeManager.string_type)
3082 SimpleSwitchEmit (ec, value);
3084 TableSwitchEmit (ec, value);
3086 // Restore context state.
3087 ig.MarkLabel (ec.LoopEnd);
3090 // Restore the previous context
3092 ec.LoopEnd = old_end;
3093 ec.Switch = old_switch;
3097 public abstract class ExceptionStatement : Statement
3099 public abstract void EmitFinally (EmitContext ec);
3101 protected bool emit_finally = true;
3102 ArrayList parent_vectors;
3104 protected void DoEmitFinally (EmitContext ec)
3107 ec.ig.BeginFinallyBlock ();
3108 else if (ec.InIterator)
3109 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3113 protected void ResolveFinally (FlowBranchingException branching)
3115 emit_finally = branching.EmitFinally;
3117 branching.Parent.StealFinallyClauses (ref parent_vectors);
3121 public class Lock : ExceptionStatement {
3123 Statement Statement;
3126 public Lock (Expression expr, Statement stmt, Location l)
3133 public override bool Resolve (EmitContext ec)
3135 expr = expr.Resolve (ec);
3139 if (expr.Type.IsValueType){
3140 Report.Error (185, loc,
3141 "`{0}' is not a reference type as required by the lock statement",
3142 TypeManager.CSharpName (expr.Type));
3146 FlowBranchingException branching = ec.StartFlowBranching (this);
3147 bool ok = Statement.Resolve (ec);
3149 ec.KillFlowBranching ();
3153 ResolveFinally (branching);
3155 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3156 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3157 // Unfortunately, System.Reflection.Emit automatically emits
3158 // a leave to the end of the finally block.
3159 // This is a problem if `returns' is true since we may jump
3160 // to a point after the end of the method.
3161 // As a workaround, emit an explicit ret here.
3162 ec.NeedReturnLabel ();
3168 protected override void DoEmit (EmitContext ec)
3170 Type type = expr.Type;
3172 ILGenerator ig = ec.ig;
3173 temp = ig.DeclareLocal (type);
3176 ig.Emit (OpCodes.Dup);
3177 ig.Emit (OpCodes.Stloc, temp);
3178 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3182 ig.BeginExceptionBlock ();
3183 Statement.Emit (ec);
3188 ig.EndExceptionBlock ();
3191 public override void EmitFinally (EmitContext ec)
3193 ILGenerator ig = ec.ig;
3194 ig.Emit (OpCodes.Ldloc, temp);
3195 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3199 public class Unchecked : Statement {
3200 public readonly Block Block;
3202 public Unchecked (Block b)
3208 public override bool Resolve (EmitContext ec)
3210 bool previous_state = ec.CheckState;
3211 bool previous_state_const = ec.ConstantCheckState;
3213 ec.CheckState = false;
3214 ec.ConstantCheckState = false;
3215 bool ret = Block.Resolve (ec);
3216 ec.CheckState = previous_state;
3217 ec.ConstantCheckState = previous_state_const;
3222 protected override void DoEmit (EmitContext ec)
3224 bool previous_state = ec.CheckState;
3225 bool previous_state_const = ec.ConstantCheckState;
3227 ec.CheckState = false;
3228 ec.ConstantCheckState = false;
3230 ec.CheckState = previous_state;
3231 ec.ConstantCheckState = previous_state_const;
3235 public class Checked : Statement {
3236 public readonly Block Block;
3238 public Checked (Block b)
3241 b.Unchecked = false;
3244 public override bool Resolve (EmitContext ec)
3246 bool previous_state = ec.CheckState;
3247 bool previous_state_const = ec.ConstantCheckState;
3249 ec.CheckState = true;
3250 ec.ConstantCheckState = true;
3251 bool ret = Block.Resolve (ec);
3252 ec.CheckState = previous_state;
3253 ec.ConstantCheckState = previous_state_const;
3258 protected override void DoEmit (EmitContext ec)
3260 bool previous_state = ec.CheckState;
3261 bool previous_state_const = ec.ConstantCheckState;
3263 ec.CheckState = true;
3264 ec.ConstantCheckState = true;
3266 ec.CheckState = previous_state;
3267 ec.ConstantCheckState = previous_state_const;
3271 public class Unsafe : Statement {
3272 public readonly Block Block;
3274 public Unsafe (Block b)
3277 Block.Unsafe = true;
3280 public override bool Resolve (EmitContext ec)
3282 bool previous_state = ec.InUnsafe;
3286 val = Block.Resolve (ec);
3287 ec.InUnsafe = previous_state;
3292 protected override void DoEmit (EmitContext ec)
3294 bool previous_state = ec.InUnsafe;
3298 ec.InUnsafe = previous_state;
3305 public class Fixed : Statement {
3307 ArrayList declarators;
3308 Statement statement;
3313 abstract class Emitter
3315 protected LocalInfo vi;
3316 protected Expression converted;
3318 protected Emitter (Expression expr, LocalInfo li)
3324 public abstract void Emit (EmitContext ec);
3325 public abstract void EmitExit (ILGenerator ig);
3328 class ExpressionEmitter: Emitter {
3329 public ExpressionEmitter (Expression converted, LocalInfo li) :
3330 base (converted, li)
3334 public override void Emit (EmitContext ec) {
3336 // Store pointer in pinned location
3338 converted.Emit (ec);
3339 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3342 public override void EmitExit (ILGenerator ig)
3344 ig.Emit (OpCodes.Ldc_I4_0);
3345 ig.Emit (OpCodes.Conv_U);
3346 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3350 class StringEmitter: Emitter {
3351 LocalBuilder pinned_string;
3354 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3360 public override void Emit (EmitContext ec)
3362 ILGenerator ig = ec.ig;
3363 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3365 converted.Emit (ec);
3366 ig.Emit (OpCodes.Stloc, pinned_string);
3368 Expression sptr = new StringPtr (pinned_string, loc);
3369 converted = Convert.ImplicitConversionRequired (
3370 ec, sptr, vi.VariableType, loc);
3372 if (converted == null)
3375 converted.Emit (ec);
3376 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3379 public override void EmitExit(ILGenerator ig)
3381 ig.Emit (OpCodes.Ldnull);
3382 ig.Emit (OpCodes.Stloc, pinned_string);
3386 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3389 declarators = decls;
3394 public override bool Resolve (EmitContext ec)
3397 Expression.UnsafeError (loc);
3401 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3405 expr_type = texpr.ResolveType (ec);
3407 CheckObsolete (expr_type);
3409 data = new Emitter [declarators.Count];
3411 if (!expr_type.IsPointer){
3412 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3417 foreach (Pair p in declarators){
3418 LocalInfo vi = (LocalInfo) p.First;
3419 Expression e = (Expression) p.Second;
3421 vi.VariableInfo.SetAssigned (ec);
3422 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3425 // The rules for the possible declarators are pretty wise,
3426 // but the production on the grammar is more concise.
3428 // So we have to enforce these rules here.
3430 // We do not resolve before doing the case 1 test,
3431 // because the grammar is explicit in that the token &
3432 // is present, so we need to test for this particular case.
3436 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3441 // Case 1: & object.
3443 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3444 Expression child = ((Unary) e).Expr;
3446 if (child is ParameterReference || child is LocalVariableReference){
3449 "No need to use fixed statement for parameters or " +
3450 "local variable declarations (address is already " +
3455 ec.InFixedInitializer = true;
3457 ec.InFixedInitializer = false;
3461 child = ((Unary) e).Expr;
3463 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3466 data [i] = new ExpressionEmitter (e, vi);
3472 ec.InFixedInitializer = true;
3474 ec.InFixedInitializer = false;
3481 if (e.Type.IsArray){
3482 Type array_type = TypeManager.GetElementType (e.Type);
3485 // Provided that array_type is unmanaged,
3487 if (!TypeManager.VerifyUnManaged (array_type, loc))
3491 // and T* is implicitly convertible to the
3492 // pointer type given in the fixed statement.
3494 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3496 Expression converted = Convert.ImplicitConversionRequired (
3497 ec, array_ptr, vi.VariableType, loc);
3498 if (converted == null)
3501 data [i] = new ExpressionEmitter (converted, vi);
3510 if (e.Type == TypeManager.string_type){
3511 data [i] = new StringEmitter (e, vi, loc);
3516 // Case 4: fixed buffer
3517 FieldExpr fe = e as FieldExpr;
3519 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3521 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3523 Expression converted = Convert.ImplicitConversionRequired (
3524 ec, fixed_buffer_ptr, vi.VariableType, loc);
3525 if (converted == null)
3528 data [i] = new ExpressionEmitter (converted, vi);
3536 // For other cases, flag a `this is already fixed expression'
3538 if (e is LocalVariableReference || e is ParameterReference ||
3539 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3541 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3545 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3549 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3551 if (!statement.Resolve (ec)) {
3552 ec.KillFlowBranching ();
3556 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3557 has_ret = reachability.IsUnreachable;
3562 protected override void DoEmit (EmitContext ec)
3564 for (int i = 0; i < data.Length; i++) {
3568 statement.Emit (ec);
3573 ILGenerator ig = ec.ig;
3576 // Clear the pinned variable
3578 for (int i = 0; i < data.Length; i++) {
3579 data [i].EmitExit (ig);
3584 public class Catch: Statement {
3585 public readonly string Name;
3586 public readonly Block Block;
3588 Expression type_expr;
3591 public Catch (Expression type, string name, Block block, Location l)
3599 public Type CatchType {
3605 public bool IsGeneral {
3607 return type_expr == null;
3611 protected override void DoEmit(EmitContext ec)
3615 public override bool Resolve (EmitContext ec)
3617 bool was_catch = ec.InCatch;
3620 if (type_expr != null) {
3621 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3625 type = te.ResolveType (ec);
3627 CheckObsolete (type);
3629 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3630 Error (155, "The type caught or thrown must be derived from System.Exception");
3636 return Block.Resolve (ec);
3639 ec.InCatch = was_catch;
3644 public class Try : ExceptionStatement {
3645 public readonly Block Fini, Block;
3646 public readonly ArrayList Specific;
3647 public readonly Catch General;
3649 bool need_exc_block;
3652 // specific, general and fini might all be null.
3654 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3656 if (specific == null && general == null){
3657 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3661 this.Specific = specific;
3662 this.General = general;
3667 public override bool Resolve (EmitContext ec)
3671 FlowBranchingException branching = ec.StartFlowBranching (this);
3673 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3675 if (!Block.Resolve (ec))
3678 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3680 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3682 Type[] prevCatches = new Type [Specific.Count];
3684 foreach (Catch c in Specific){
3685 ec.CurrentBranching.CreateSibling (
3686 c.Block, FlowBranching.SiblingType.Catch);
3688 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3690 if (c.Name != null) {
3691 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3693 throw new Exception ();
3695 vi.VariableInfo = null;
3698 if (!c.Resolve (ec))
3701 Type resolvedType = c.CatchType;
3702 for (int ii = 0; ii < last_index; ++ii) {
3703 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3704 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
3709 prevCatches [last_index++] = resolvedType;
3710 need_exc_block = true;
3713 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3715 if (General != null){
3716 ec.CurrentBranching.CreateSibling (
3717 General.Block, FlowBranching.SiblingType.Catch);
3719 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3721 if (!General.Resolve (ec))
3724 need_exc_block = true;
3727 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3731 ec.CurrentBranching.CreateSibling (
3732 Fini, FlowBranching.SiblingType.Finally);
3734 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3735 bool was_finally = ec.InFinally;
3736 ec.InFinally = true;
3737 if (!Fini.Resolve (ec))
3739 ec.InFinally = was_finally;
3742 need_exc_block = true;
3745 if (ec.InIterator) {
3746 ResolveFinally (branching);
3747 need_exc_block |= emit_finally;
3749 emit_finally = Fini != null;
3751 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3753 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3755 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3757 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3758 // Unfortunately, System.Reflection.Emit automatically emits
3759 // a leave to the end of the finally block. This is a problem
3760 // if `returns' is true since we may jump to a point after the
3761 // end of the method.
3762 // As a workaround, emit an explicit ret here.
3763 ec.NeedReturnLabel ();
3769 protected override void DoEmit (EmitContext ec)
3771 ILGenerator ig = ec.ig;
3774 ig.BeginExceptionBlock ();
3777 foreach (Catch c in Specific){
3780 ig.BeginCatchBlock (c.CatchType);
3782 if (c.Name != null){
3783 vi = c.Block.GetLocalInfo (c.Name);
3785 throw new Exception ("Variable does not exist in this block");
3787 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3789 ig.Emit (OpCodes.Pop);
3794 if (General != null){
3795 ig.BeginCatchBlock (TypeManager.object_type);
3796 ig.Emit (OpCodes.Pop);
3797 General.Block.Emit (ec);
3802 ig.EndExceptionBlock ();
3805 public override void EmitFinally (EmitContext ec)
3811 public bool HasCatch
3814 return General != null || Specific.Count > 0;
3819 public class Using : ExceptionStatement {
3820 object expression_or_block;
3821 Statement Statement;
3826 Expression [] resolved_vars;
3827 Expression [] converted_vars;
3828 ExpressionStatement [] assign;
3829 LocalBuilder local_copy;
3831 public Using (object expression_or_block, Statement stmt, Location l)
3833 this.expression_or_block = expression_or_block;
3839 // Resolves for the case of using using a local variable declaration.
3841 bool ResolveLocalVariableDecls (EmitContext ec)
3845 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3849 expr_type = texpr.ResolveType (ec);
3852 // The type must be an IDisposable or an implicit conversion
3855 converted_vars = new Expression [var_list.Count];
3856 resolved_vars = new Expression [var_list.Count];
3857 assign = new ExpressionStatement [var_list.Count];
3859 bool need_conv = !TypeManager.ImplementsInterface (
3860 expr_type, TypeManager.idisposable_type);
3862 foreach (DictionaryEntry e in var_list){
3863 Expression var = (Expression) e.Key;
3865 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
3869 resolved_vars [i] = var;
3876 converted_vars [i] = Convert.ImplicitConversionRequired (
3877 ec, var, TypeManager.idisposable_type, loc);
3879 if (converted_vars [i] == null)
3886 foreach (DictionaryEntry e in var_list){
3887 Expression var = resolved_vars [i];
3888 Expression new_expr = (Expression) e.Value;
3891 a = new Assign (var, new_expr, loc);
3897 converted_vars [i] = var;
3898 assign [i] = (ExpressionStatement) a;
3905 bool ResolveExpression (EmitContext ec)
3907 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3908 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
3909 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
3910 TypeManager.CSharpName (expr_type));
3919 // Emits the code for the case of using using a local variable declaration.
3921 void EmitLocalVariableDecls (EmitContext ec)
3923 ILGenerator ig = ec.ig;
3926 for (i = 0; i < assign.Length; i++) {
3927 assign [i].EmitStatement (ec);
3930 ig.BeginExceptionBlock ();
3932 Statement.Emit (ec);
3933 var_list.Reverse ();
3938 void EmitLocalVariableDeclFinally (EmitContext ec)
3940 ILGenerator ig = ec.ig;
3942 int i = assign.Length;
3943 for (int ii = 0; ii < var_list.Count; ++ii){
3944 Expression var = resolved_vars [--i];
3945 Label skip = ig.DefineLabel ();
3947 if (!var.Type.IsValueType) {
3949 ig.Emit (OpCodes.Brfalse, skip);
3950 converted_vars [i].Emit (ec);
3951 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3953 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3955 if (!(ml is MethodGroupExpr)) {
3957 ig.Emit (OpCodes.Box, var.Type);
3958 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3960 MethodInfo mi = null;
3962 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3963 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3970 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3974 IMemoryLocation mloc = (IMemoryLocation) var;
3976 mloc.AddressOf (ec, AddressOp.Load);
3977 ig.Emit (OpCodes.Call, mi);
3981 ig.MarkLabel (skip);
3984 ig.EndExceptionBlock ();
3986 ig.BeginFinallyBlock ();
3991 void EmitExpression (EmitContext ec)
3994 // Make a copy of the expression and operate on that.
3996 ILGenerator ig = ec.ig;
3997 local_copy = ig.DeclareLocal (expr_type);
4002 ig.Emit (OpCodes.Stloc, local_copy);
4005 ig.BeginExceptionBlock ();
4007 Statement.Emit (ec);
4011 ig.EndExceptionBlock ();
4014 void EmitExpressionFinally (EmitContext ec)
4016 ILGenerator ig = ec.ig;
4017 if (!local_copy.LocalType.IsValueType) {
4018 Label skip = ig.DefineLabel ();
4019 ig.Emit (OpCodes.Ldloc, local_copy);
4020 ig.Emit (OpCodes.Brfalse, skip);
4021 ig.Emit (OpCodes.Ldloc, local_copy);
4022 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4023 ig.MarkLabel (skip);
4025 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4027 if (!(ml is MethodGroupExpr)) {
4028 ig.Emit (OpCodes.Ldloc, local_copy);
4029 ig.Emit (OpCodes.Box, local_copy.LocalType);
4030 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4032 MethodInfo mi = null;
4034 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4035 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4042 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4046 ig.Emit (OpCodes.Ldloca, local_copy);
4047 ig.Emit (OpCodes.Call, mi);
4052 public override bool Resolve (EmitContext ec)
4054 if (expression_or_block is DictionaryEntry){
4055 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4056 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4058 if (!ResolveLocalVariableDecls (ec))
4061 } else if (expression_or_block is Expression){
4062 expr = (Expression) expression_or_block;
4064 expr = expr.Resolve (ec);
4068 expr_type = expr.Type;
4070 if (!ResolveExpression (ec))
4074 FlowBranchingException branching = ec.StartFlowBranching (this);
4076 bool ok = Statement.Resolve (ec);
4079 ec.KillFlowBranching ();
4083 ResolveFinally (branching);
4084 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4086 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4087 // Unfortunately, System.Reflection.Emit automatically emits a leave
4088 // to the end of the finally block. This is a problem if `returns'
4089 // is true since we may jump to a point after the end of the method.
4090 // As a workaround, emit an explicit ret here.
4091 ec.NeedReturnLabel ();
4097 protected override void DoEmit (EmitContext ec)
4099 if (expression_or_block is DictionaryEntry)
4100 EmitLocalVariableDecls (ec);
4101 else if (expression_or_block is Expression)
4102 EmitExpression (ec);
4105 public override void EmitFinally (EmitContext ec)
4107 if (expression_or_block is DictionaryEntry)
4108 EmitLocalVariableDeclFinally (ec);
4109 else if (expression_or_block is Expression)
4110 EmitExpressionFinally (ec);
4115 /// Implementation of the foreach C# statement
4117 public class Foreach : Statement {
4119 Expression variable;
4121 Statement statement;
4123 CollectionForeach collection;
4125 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4126 Statement stmt, Location l)
4129 this.variable = var;
4135 public override bool Resolve (EmitContext ec)
4137 expr = expr.Resolve (ec);
4141 if (expr is NullLiteral) {
4142 Report.Error (186, loc, "Use of null is not valid in this context");
4146 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4150 Type var_type = texpr.Type;
4153 // We need an instance variable. Not sure this is the best
4154 // way of doing this.
4156 // FIXME: When we implement propertyaccess, will those turn
4157 // out to return values in ExprClass? I think they should.
4159 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4160 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4161 collection.error1579 ();
4165 if (expr.Type.IsArray) {
4166 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4167 return array.Resolve (ec);
4169 collection = new CollectionForeach (
4170 var_type, variable, expr, statement, loc);
4171 return collection.Resolve (ec);
4175 protected override void DoEmit (EmitContext ec)
4177 ILGenerator ig = ec.ig;
4179 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4180 ec.LoopBegin = ig.DefineLabel ();
4181 ec.LoopEnd = ig.DefineLabel ();
4183 if (collection != null)
4184 collection.Emit (ec);
4188 ec.LoopBegin = old_begin;
4189 ec.LoopEnd = old_end;
4192 protected class TemporaryVariable : Expression, IMemoryLocation
4196 public TemporaryVariable (Type type, Location loc)
4200 eclass = ExprClass.Value;
4203 public override Expression DoResolve (EmitContext ec)
4208 TypeExpr te = new TypeExpression (type, loc);
4209 li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
4210 if (!li.Resolve (ec))
4213 AnonymousContainer am = ec.CurrentAnonymousMethod;
4214 if ((am != null) && am.IsIterator)
4215 ec.CaptureVariable (li);
4220 public override void Emit (EmitContext ec)
4222 ILGenerator ig = ec.ig;
4224 if (li.FieldBuilder != null) {
4225 ig.Emit (OpCodes.Ldarg_0);
4226 ig.Emit (OpCodes.Ldfld, li.FieldBuilder);
4228 ig.Emit (OpCodes.Ldloc, li.LocalBuilder);
4232 public void EmitLoadAddress (EmitContext ec)
4234 ILGenerator ig = ec.ig;
4236 if (li.FieldBuilder != null) {
4237 ig.Emit (OpCodes.Ldarg_0);
4238 ig.Emit (OpCodes.Ldflda, li.FieldBuilder);
4240 ig.Emit (OpCodes.Ldloca, li.LocalBuilder);
4244 public void Store (EmitContext ec, Expression right_side)
4246 if (li.FieldBuilder != null)
4247 ec.ig.Emit (OpCodes.Ldarg_0);
4249 right_side.Emit (ec);
4250 if (li.FieldBuilder != null) {
4251 ec.ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4253 ec.ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4257 public void EmitThis (EmitContext ec)
4259 if (li.FieldBuilder != null) {
4260 ec.ig.Emit (OpCodes.Ldarg_0);
4264 public void EmitStore (ILGenerator ig)
4266 if (li.FieldBuilder != null)
4267 ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4269 ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4272 public void AddressOf (EmitContext ec, AddressOp mode)
4274 EmitLoadAddress (ec);
4278 protected class ArrayCounter : TemporaryVariable
4280 public ArrayCounter (Location loc)
4281 : base (TypeManager.int32_type, loc)
4284 public void Initialize (EmitContext ec)
4287 ec.ig.Emit (OpCodes.Ldc_I4_0);
4291 public void Increment (EmitContext ec)
4295 ec.ig.Emit (OpCodes.Ldc_I4_1);
4296 ec.ig.Emit (OpCodes.Add);
4301 protected class ArrayForeach : Statement
4303 Expression variable, expr, conv;
4304 Statement statement;
4305 Type array_type, element_type;
4307 TemporaryVariable[] lengths;
4308 ArrayCounter[] counter;
4311 TemporaryVariable copy;
4314 public ArrayForeach (Type var_type, Expression var,
4315 Expression expr, Statement stmt, Location l)
4317 this.var_type = var_type;
4318 this.variable = var;
4324 public override bool Resolve (EmitContext ec)
4326 array_type = expr.Type;
4327 element_type = TypeManager.GetElementType (array_type);
4328 rank = array_type.GetArrayRank ();
4330 copy = new TemporaryVariable (array_type, loc);
4333 counter = new ArrayCounter [rank];
4334 lengths = new TemporaryVariable [rank];
4336 ArrayList list = new ArrayList ();
4337 for (int i = 0; i < rank; i++) {
4338 counter [i] = new ArrayCounter (loc);
4339 counter [i].Resolve (ec);
4341 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4342 lengths [i].Resolve (ec);
4344 list.Add (counter [i]);
4347 access = new ElementAccess (copy, list, loc).Resolve (ec);
4351 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4357 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4358 ec.CurrentBranching.CreateSibling ();
4360 variable = variable.ResolveLValue (ec, conv, loc);
4361 if (variable == null)
4364 if (!statement.Resolve (ec))
4367 ec.EndFlowBranching ();
4372 protected override void DoEmit (EmitContext ec)
4374 ILGenerator ig = ec.ig;
4376 copy.Store (ec, expr);
4378 Label[] test = new Label [rank];
4379 Label[] loop = new Label [rank];
4381 for (int i = 0; i < rank; i++) {
4382 test [i] = ig.DefineLabel ();
4383 loop [i] = ig.DefineLabel ();
4385 lengths [i].EmitThis (ec);
4386 ((ArrayAccess) access).EmitGetLength (ec, i);
4387 lengths [i].EmitStore (ig);
4390 for (int i = 0; i < rank; i++) {
4391 counter [i].Initialize (ec);
4393 ig.Emit (OpCodes.Br, test [i]);
4394 ig.MarkLabel (loop [i]);
4397 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4399 statement.Emit (ec);
4401 ig.MarkLabel (ec.LoopBegin);
4403 for (int i = rank - 1; i >= 0; i--){
4404 counter [i].Increment (ec);
4406 ig.MarkLabel (test [i]);
4407 counter [i].Emit (ec);
4408 lengths [i].Emit (ec);
4409 ig.Emit (OpCodes.Blt, loop [i]);
4412 ig.MarkLabel (ec.LoopEnd);
4416 protected class CollectionForeach : ExceptionStatement
4418 Expression variable, expr;
4419 Statement statement;
4421 TemporaryVariable enumerator;
4425 MethodGroupExpr get_enumerator;
4426 PropertyExpr get_current;
4427 MethodInfo move_next;
4428 Type var_type, enumerator_type;
4431 public CollectionForeach (Type var_type, Expression var,
4432 Expression expr, Statement stmt, Location l)
4434 this.var_type = var_type;
4435 this.variable = var;
4441 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4443 Type [] args = TypeManager.GetArgumentTypes (mi);
4445 if (args.Length != 0)
4449 if (TypeManager.IsOverride (mi))
4452 // Check whether GetEnumerator is public
4453 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4456 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4458 // Apply the same optimization as MS: skip the GetEnumerator
4459 // returning an IEnumerator, and use the one returning a
4460 // CharEnumerator instead. This allows us to avoid the
4461 // try-finally block and the boxing.
4466 // Ok, we can access it, now make sure that we can do something
4467 // with this `GetEnumerator'
4470 Type return_type = mi.ReturnType;
4471 if (mi.ReturnType == TypeManager.ienumerator_type ||
4472 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4473 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4475 // If it is not an interface, lets try to find the methods ourselves.
4476 // For example, if we have:
4477 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4478 // We can avoid the iface call. This is a runtime perf boost.
4479 // even bigger if we have a ValueType, because we avoid the cost
4482 // We have to make sure that both methods exist for us to take
4483 // this path. If one of the methods does not exist, we will just
4484 // use the interface. Sadly, this complex if statement is the only
4485 // way I could do this without a goto
4488 if (return_type.IsInterface ||
4489 !FetchMoveNext (ec, return_type) ||
4490 !FetchGetCurrent (ec, return_type)) {
4491 move_next = TypeManager.bool_movenext_void;
4492 get_current = new PropertyExpr (
4493 ec, TypeManager.ienumerator_getcurrent, loc);
4498 // Ok, so they dont return an IEnumerable, we will have to
4499 // find if they support the GetEnumerator pattern.
4502 if (!FetchMoveNext (ec, return_type))
4505 if (!FetchGetCurrent (ec, return_type))
4509 enumerator_type = return_type;
4510 is_disposable = !enumerator_type.IsSealed ||
4511 TypeManager.ImplementsInterface (
4512 enumerator_type, TypeManager.idisposable_type);
4518 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4520 bool FetchMoveNext (EmitContext ec, Type t)
4522 MemberList move_next_list;
4524 move_next_list = TypeContainer.FindMembers (
4525 t, MemberTypes.Method,
4526 BindingFlags.Public | BindingFlags.Instance,
4527 Type.FilterName, "MoveNext");
4528 if (move_next_list.Count == 0)
4531 foreach (MemberInfo m in move_next_list){
4532 MethodInfo mi = (MethodInfo) m;
4535 args = TypeManager.GetArgumentTypes (mi);
4536 if ((args != null) && (args.Length == 0) &&
4537 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
4547 // Retrieves a `public T get_Current ()' method from the Type `t'
4549 bool FetchGetCurrent (EmitContext ec, Type t)
4551 PropertyExpr pe = Expression.MemberLookup (
4552 ec, t, "Current", MemberTypes.Property,
4553 Expression.AllBindingFlags, loc) as PropertyExpr;
4562 // Retrieves a `public void Dispose ()' method from the Type `t'
4564 static MethodInfo FetchMethodDispose (Type t)
4566 MemberList dispose_list;
4568 dispose_list = TypeContainer.FindMembers (
4569 t, MemberTypes.Method,
4570 BindingFlags.Public | BindingFlags.Instance,
4571 Type.FilterName, "Dispose");
4572 if (dispose_list.Count == 0)
4575 foreach (MemberInfo m in dispose_list){
4576 MethodInfo mi = (MethodInfo) m;
4579 args = TypeManager.GetArgumentTypes (mi);
4580 if (args != null && args.Length == 0){
4581 if (mi.ReturnType == TypeManager.void_type)
4588 public void error1579 ()
4590 Report.Error (1579, loc,
4591 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
4592 TypeManager.CSharpName (expr.Type));
4595 bool TryType (EmitContext ec, Type t)
4597 MethodGroupExpr mg = Expression.MemberLookup (
4598 ec, t, "GetEnumerator", MemberTypes.Method,
4599 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4603 foreach (MethodBase mb in mg.Methods) {
4604 if (!GetEnumeratorFilter (ec, (MethodInfo) mb))
4607 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) mb };
4608 get_enumerator = new MethodGroupExpr (mi, loc);
4610 if (t != expr.Type) {
4611 expr = Convert.ExplicitConversion (
4614 throw new InternalErrorException ();
4617 get_enumerator.InstanceExpression = expr;
4618 get_enumerator.IsBase = t != expr.Type;
4626 bool ProbeCollectionType (EmitContext ec, Type t)
4628 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4629 if (TryType (ec, tt))
4635 // Now try to find the method in the interfaces
4638 Type [] ifaces = t.GetInterfaces ();
4640 foreach (Type i in ifaces){
4641 if (TryType (ec, i))
4646 // Since TypeBuilder.GetInterfaces only returns the interface
4647 // types for this type, we have to keep looping, but once
4648 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4649 // done, because it returns all the types
4651 if ((t is TypeBuilder))
4660 public override bool Resolve (EmitContext ec)
4662 enumerator_type = TypeManager.ienumerator_type;
4663 is_disposable = true;
4665 if (!ProbeCollectionType (ec, expr.Type)) {
4670 enumerator = new TemporaryVariable (enumerator_type, loc);
4671 enumerator.Resolve (ec);
4673 init = new Invocation (get_enumerator, new ArrayList (), loc);
4674 init = init.Resolve (ec);
4678 Expression move_next_expr;
4680 MemberInfo[] mi = new MemberInfo[] { move_next };
4681 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
4682 mg.InstanceExpression = enumerator;
4684 move_next_expr = new Invocation (mg, new ArrayList (), loc);
4687 get_current.InstanceExpression = enumerator;
4689 Statement block = new CollectionForeachStatement (
4690 var_type, variable, get_current, statement, loc);
4692 loop = new While (move_next_expr, block, loc);
4696 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4697 ec.CurrentBranching.CreateSibling ();
4699 FlowBranchingException branching = null;
4701 branching = ec.StartFlowBranching (this);
4703 if (!loop.Resolve (ec))
4706 if (is_disposable) {
4707 ResolveFinally (branching);
4708 ec.EndFlowBranching ();
4710 emit_finally = true;
4712 ec.EndFlowBranching ();
4717 protected override void DoEmit (EmitContext ec)
4719 ILGenerator ig = ec.ig;
4721 enumerator.Store (ec, init);
4724 // Protect the code in a try/finalize block, so that
4725 // if the beast implement IDisposable, we get rid of it
4727 if (is_disposable && emit_finally)
4728 ig.BeginExceptionBlock ();
4733 // Now the finally block
4735 if (is_disposable) {
4738 ig.EndExceptionBlock ();
4743 public override void EmitFinally (EmitContext ec)
4745 ILGenerator ig = ec.ig;
4747 if (enumerator_type.IsValueType) {
4748 enumerator.Emit (ec);
4750 MethodInfo mi = FetchMethodDispose (enumerator_type);
4752 enumerator.EmitLoadAddress (ec);
4753 ig.Emit (OpCodes.Call, mi);
4755 enumerator.Emit (ec);
4756 ig.Emit (OpCodes.Box, enumerator_type);
4757 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4760 Label call_dispose = ig.DefineLabel ();
4762 enumerator.Emit (ec);
4763 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4764 ig.Emit (OpCodes.Dup);
4765 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4766 ig.Emit (OpCodes.Pop);
4768 Label end_finally = ig.DefineLabel ();
4769 ig.Emit (OpCodes.Br, end_finally);
4771 ig.MarkLabel (call_dispose);
4772 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4773 ig.MarkLabel (end_finally);
4778 protected class CollectionForeachStatement : Statement
4781 Expression variable, current, conv;
4782 Statement statement;
4785 public CollectionForeachStatement (Type type, Expression variable,
4786 Expression current, Statement statement,
4790 this.variable = variable;
4791 this.current = current;
4792 this.statement = statement;
4796 public override bool Resolve (EmitContext ec)
4798 current = current.Resolve (ec);
4799 if (current == null)
4802 conv = Convert.ExplicitConversion (ec, current, type, loc);
4806 assign = new Assign (variable, conv, loc);
4807 if (assign.Resolve (ec) == null)
4810 if (!statement.Resolve (ec))
4816 protected override void DoEmit (EmitContext ec)
4818 assign.EmitStatement (ec);
4819 statement.Emit (ec);