2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@ximian.com)
7 // Marek Safar (marek.safar@seznam.cz)
9 // (C) 2001, 2002, 2003 Ximian, Inc.
10 // (C) 2003, 2004 Novell, Inc.
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Diagnostics;
18 using System.Collections;
19 using System.Collections.Specialized;
21 namespace Mono.CSharp {
23 public abstract class Statement {
27 /// Resolves the statement, true means that all sub-statements
30 public virtual bool Resolve (EmitContext ec)
36 /// We already know that the statement is unreachable, but we still
37 /// need to resolve it to catch errors.
39 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
42 // This conflicts with csc's way of doing this, but IMHO it's
43 // the right thing to do.
45 // If something is unreachable, we still check whether it's
46 // correct. This means that you cannot use unassigned variables
47 // in unreachable code, for instance.
51 Report.Warning (162, 2, loc, "Unreachable code detected");
53 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
54 bool ok = Resolve (ec);
55 ec.KillFlowBranching ();
61 /// Return value indicates whether all code paths emitted return.
63 protected abstract void DoEmit (EmitContext ec);
66 /// Utility wrapper routine for Error, just to beautify the code
68 public void Error (int error, string format, params object[] args)
70 Error (error, String.Format (format, args));
73 public void Error (int error, string s)
76 Report.Error (error, loc, s);
78 Report.Error (error, s);
82 /// Return value indicates whether all code paths emitted return.
84 public virtual void Emit (EmitContext ec)
91 // This routine must be overrided in derived classes and make copies
92 // of all the data that might be modified if resolved
94 protected virtual void CloneTo (CloneContext clonectx, Statement target)
96 throw new Exception (String.Format ("Statement.CloneTo not implemented for {0}", this.GetType ()));
99 public Statement Clone (CloneContext clonectx)
101 Statement s = (Statement) this.MemberwiseClone ();
103 clonectx.AddBlockMap ((Block) this, (Block) s);
105 CloneTo (clonectx, s);
109 public Statement PerformClone ()
111 CloneContext clonectx = new CloneContext ();
113 return Clone (clonectx);
119 // This class is used during the Statement.Clone operation
120 // to remap objects that have been cloned.
122 // Since blocks are cloned by Block.Clone, we need a way for
123 // expressions that must reference the block to be cloned
124 // pointing to the new cloned block.
126 public class CloneContext {
127 Hashtable block_map = new Hashtable ();
128 Hashtable variable_map;
130 public void AddBlockMap (Block from, Block to)
132 if (block_map.Contains (from))
134 block_map [from] = to;
137 public Block LookupBlock (Block from)
139 Block result = (Block) block_map [from];
142 result = (Block) from.Clone (this);
143 block_map [from] = result;
149 public void AddVariableMap (LocalInfo from, LocalInfo to)
151 if (variable_map == null)
152 variable_map = new Hashtable ();
154 if (variable_map.Contains (from))
156 variable_map [from] = to;
159 public LocalInfo LookupVariable (LocalInfo from)
161 LocalInfo result = (LocalInfo) variable_map [from];
164 throw new Exception ("LookupVariable: looking up a variable that has not been registered yet");
170 public sealed class EmptyStatement : Statement {
172 private EmptyStatement () {}
174 public static readonly EmptyStatement Value = new EmptyStatement ();
176 public override bool Resolve (EmitContext ec)
181 public override bool ResolveUnreachable (EmitContext ec, bool warn)
186 protected override void DoEmit (EmitContext ec)
191 public class If : Statement {
193 public Statement TrueStatement;
194 public Statement FalseStatement;
198 public If (Expression expr, Statement trueStatement, Location l)
201 TrueStatement = trueStatement;
205 public If (Expression expr,
206 Statement trueStatement,
207 Statement falseStatement,
211 TrueStatement = trueStatement;
212 FalseStatement = falseStatement;
216 public override bool Resolve (EmitContext ec)
220 Report.Debug (1, "START IF BLOCK", loc);
222 expr = Expression.ResolveBoolean (ec, expr, loc);
228 Assign ass = expr as Assign;
229 if (ass != null && ass.Source is Constant) {
230 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
234 // Dead code elimination
236 if (expr is BoolConstant){
237 bool take = ((BoolConstant) expr).Value;
240 if (!TrueStatement.Resolve (ec))
243 if ((FalseStatement != null) &&
244 !FalseStatement.ResolveUnreachable (ec, true))
246 FalseStatement = null;
248 if (!TrueStatement.ResolveUnreachable (ec, true))
250 TrueStatement = null;
252 if ((FalseStatement != null) &&
253 !FalseStatement.Resolve (ec))
260 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
262 ok &= TrueStatement.Resolve (ec);
264 is_true_ret = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
266 ec.CurrentBranching.CreateSibling ();
268 if (FalseStatement != null)
269 ok &= FalseStatement.Resolve (ec);
271 ec.EndFlowBranching ();
273 Report.Debug (1, "END IF BLOCK", loc);
278 protected override void DoEmit (EmitContext ec)
280 ILGenerator ig = ec.ig;
281 Label false_target = ig.DefineLabel ();
285 // If we're a boolean expression, Resolve() already
286 // eliminated dead code for us.
288 if (expr is BoolConstant){
289 bool take = ((BoolConstant) expr).Value;
292 TrueStatement.Emit (ec);
293 else if (FalseStatement != null)
294 FalseStatement.Emit (ec);
299 expr.EmitBranchable (ec, false_target, false);
301 TrueStatement.Emit (ec);
303 if (FalseStatement != null){
304 bool branch_emitted = false;
306 end = ig.DefineLabel ();
308 ig.Emit (OpCodes.Br, end);
309 branch_emitted = true;
312 ig.MarkLabel (false_target);
313 FalseStatement.Emit (ec);
318 ig.MarkLabel (false_target);
322 protected override void CloneTo (CloneContext clonectx, Statement t)
326 target.expr = expr.Clone (clonectx);
327 target.TrueStatement = TrueStatement.Clone (clonectx);
328 target.FalseStatement = FalseStatement.Clone (clonectx);
332 public class Do : Statement {
333 public Expression expr;
334 public Statement EmbeddedStatement;
337 public Do (Statement statement, Expression boolExpr, Location l)
340 EmbeddedStatement = statement;
344 public override bool Resolve (EmitContext ec)
348 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
350 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
352 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
353 if (!EmbeddedStatement.Resolve (ec))
355 ec.EndFlowBranching ();
357 if (ec.CurrentBranching.CurrentUsageVector.IsUnreachable && !was_unreachable)
358 Report.Warning (162, 2, expr.Location, "Unreachable code detected");
360 expr = Expression.ResolveBoolean (ec, expr, loc);
363 else if (expr is BoolConstant){
364 bool res = ((BoolConstant) expr).Value;
370 ec.CurrentBranching.CurrentUsageVector.Goto ();
372 ec.EndFlowBranching ();
377 protected override void DoEmit (EmitContext ec)
379 ILGenerator ig = ec.ig;
380 Label loop = ig.DefineLabel ();
381 Label old_begin = ec.LoopBegin;
382 Label old_end = ec.LoopEnd;
384 ec.LoopBegin = ig.DefineLabel ();
385 ec.LoopEnd = ig.DefineLabel ();
388 EmbeddedStatement.Emit (ec);
389 ig.MarkLabel (ec.LoopBegin);
392 // Dead code elimination
394 if (expr is BoolConstant){
395 bool res = ((BoolConstant) expr).Value;
398 ec.ig.Emit (OpCodes.Br, loop);
400 expr.EmitBranchable (ec, loop, true);
402 ig.MarkLabel (ec.LoopEnd);
404 ec.LoopBegin = old_begin;
405 ec.LoopEnd = old_end;
408 protected override void CloneTo (CloneContext clonectx, Statement t)
412 target.EmbeddedStatement = EmbeddedStatement.Clone (clonectx);
413 target.expr = expr.Clone (clonectx);
417 public class While : Statement {
418 public Expression expr;
419 public Statement Statement;
420 bool infinite, empty;
422 public While (Expression boolExpr, Statement statement, Location l)
424 this.expr = boolExpr;
425 Statement = statement;
429 public override bool Resolve (EmitContext ec)
433 expr = Expression.ResolveBoolean (ec, expr, loc);
438 // Inform whether we are infinite or not
440 if (expr is BoolConstant){
441 BoolConstant bc = (BoolConstant) expr;
443 if (bc.Value == false){
444 if (!Statement.ResolveUnreachable (ec, true))
452 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
454 ec.CurrentBranching.CreateSibling ();
456 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
457 if (!Statement.Resolve (ec))
459 ec.EndFlowBranching ();
461 // There's no direct control flow from the end of the embedded statement to the end of the loop
462 ec.CurrentBranching.CurrentUsageVector.Goto ();
464 ec.EndFlowBranching ();
469 protected override void DoEmit (EmitContext ec)
474 ILGenerator ig = ec.ig;
475 Label old_begin = ec.LoopBegin;
476 Label old_end = ec.LoopEnd;
478 ec.LoopBegin = ig.DefineLabel ();
479 ec.LoopEnd = ig.DefineLabel ();
482 // Inform whether we are infinite or not
484 if (expr is BoolConstant){
485 ig.MarkLabel (ec.LoopBegin);
487 ig.Emit (OpCodes.Br, ec.LoopBegin);
490 // Inform that we are infinite (ie, `we return'), only
491 // if we do not `break' inside the code.
493 ig.MarkLabel (ec.LoopEnd);
495 Label while_loop = ig.DefineLabel ();
497 ig.Emit (OpCodes.Br, ec.LoopBegin);
498 ig.MarkLabel (while_loop);
502 ig.MarkLabel (ec.LoopBegin);
504 expr.EmitBranchable (ec, while_loop, true);
506 ig.MarkLabel (ec.LoopEnd);
509 ec.LoopBegin = old_begin;
510 ec.LoopEnd = old_end;
513 protected override void CloneTo (CloneContext clonectx, Statement t)
515 While target = (While) t;
517 target.expr = expr.Clone (clonectx);
518 target.Statement = Statement.Clone (clonectx);
522 public class For : Statement {
524 Statement InitStatement;
526 public Statement Statement;
527 bool infinite, empty;
529 public For (Statement initStatement,
535 InitStatement = initStatement;
537 Increment = increment;
538 Statement = statement;
542 public override bool Resolve (EmitContext ec)
546 if (InitStatement != null){
547 if (!InitStatement.Resolve (ec))
552 Test = Expression.ResolveBoolean (ec, Test, loc);
555 else if (Test is BoolConstant){
556 BoolConstant bc = (BoolConstant) Test;
558 if (bc.Value == false){
559 if (!Statement.ResolveUnreachable (ec, true))
561 if ((Increment != null) &&
562 !Increment.ResolveUnreachable (ec, false))
572 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
574 ec.CurrentBranching.CreateSibling ();
576 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
578 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
579 if (!Statement.Resolve (ec))
581 ec.EndFlowBranching ();
583 if (Increment != null){
584 if (ec.CurrentBranching.CurrentUsageVector.IsUnreachable) {
585 if (!Increment.ResolveUnreachable (ec, !was_unreachable))
588 if (!Increment.Resolve (ec))
593 // There's no direct control flow from the end of the embedded statement to the end of the loop
594 ec.CurrentBranching.CurrentUsageVector.Goto ();
596 ec.EndFlowBranching ();
601 protected override void DoEmit (EmitContext ec)
606 ILGenerator ig = ec.ig;
607 Label old_begin = ec.LoopBegin;
608 Label old_end = ec.LoopEnd;
609 Label loop = ig.DefineLabel ();
610 Label test = ig.DefineLabel ();
612 if (InitStatement != null && InitStatement != EmptyStatement.Value)
613 InitStatement.Emit (ec);
615 ec.LoopBegin = ig.DefineLabel ();
616 ec.LoopEnd = ig.DefineLabel ();
618 ig.Emit (OpCodes.Br, test);
622 ig.MarkLabel (ec.LoopBegin);
623 if (Increment != EmptyStatement.Value)
628 // If test is null, there is no test, and we are just
633 // The Resolve code already catches the case for
634 // Test == BoolConstant (false) so we know that
637 if (Test is BoolConstant)
638 ig.Emit (OpCodes.Br, loop);
640 Test.EmitBranchable (ec, loop, true);
643 ig.Emit (OpCodes.Br, loop);
644 ig.MarkLabel (ec.LoopEnd);
646 ec.LoopBegin = old_begin;
647 ec.LoopEnd = old_end;
650 protected override void CloneTo (CloneContext clonectx, Statement t)
652 For target = (For) t;
654 if (InitStatement != null)
655 target.InitStatement = InitStatement.Clone (clonectx);
657 target.Test = Test.Clone (clonectx);
658 if (Increment != null)
659 target.Increment = Increment.Clone (clonectx);
660 target.Statement = Statement.Clone (clonectx);
664 public class StatementExpression : Statement {
665 ExpressionStatement expr;
667 public StatementExpression (ExpressionStatement expr)
673 public override bool Resolve (EmitContext ec)
676 expr = expr.ResolveStatement (ec);
680 protected override void DoEmit (EmitContext ec)
682 expr.EmitStatement (ec);
685 public override string ToString ()
687 return "StatementExpression (" + expr + ")";
690 protected override void CloneTo (CloneContext clonectx, Statement t)
692 StatementExpression target = (StatementExpression) t;
694 target.expr = (ExpressionStatement) expr.Clone (clonectx);
699 /// Implements the return statement
701 public class Return : Statement {
702 public Expression Expr;
704 public Return (Expression expr, Location l)
712 public override bool Resolve (EmitContext ec)
714 AnonymousContainer am = ec.CurrentAnonymousMethod;
715 if ((am != null) && am.IsIterator && ec.InIterator) {
716 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
717 "statement to return a value, or yield break to end the iteration");
721 if (ec.ReturnType == null){
723 if (ec.CurrentAnonymousMethod != null){
724 Report.Error (1662, loc,
725 "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",
726 ec.CurrentAnonymousMethod.GetSignatureForError ());
728 Error (127, "A return keyword must not be followed by any expression when method returns void");
733 Error (126, "An object of a type convertible to `{0}' is required " +
734 "for the return statement",
735 TypeManager.CSharpName (ec.ReturnType));
739 Expr = Expr.Resolve (ec);
743 if (Expr.Type != ec.ReturnType) {
744 Expr = Convert.ImplicitConversionRequired (
745 ec, Expr, ec.ReturnType, loc);
751 int errors = Report.Errors;
752 unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
754 ec.NeedReturnLabel ();
755 ec.CurrentBranching.CurrentUsageVector.Goto ();
756 return errors == Report.Errors;
759 protected override void DoEmit (EmitContext ec)
765 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
769 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
771 ec.ig.Emit (OpCodes.Ret);
774 protected override void CloneTo (CloneContext clonectx, Statement t)
776 Return target = (Return) t;
778 target.Expr = Expr.Clone (clonectx);
782 public class Goto : Statement {
784 LabeledStatement label;
787 public override bool Resolve (EmitContext ec)
789 int errors = Report.Errors;
790 unwind_protect = ec.CurrentBranching.AddGotoOrigin (ec.CurrentBranching.CurrentUsageVector, this);
791 ec.CurrentBranching.CurrentUsageVector.Goto ();
792 return errors == Report.Errors;
795 public Goto (string label, Location l)
801 public string Target {
802 get { return target; }
805 public void SetResolvedTarget (LabeledStatement label)
808 label.AddReference ();
811 protected override void DoEmit (EmitContext ec)
814 throw new InternalErrorException ("goto emitted before target resolved");
815 Label l = label.LabelTarget (ec);
816 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
820 public class LabeledStatement : Statement {
827 FlowBranching.UsageVector vectors;
829 public LabeledStatement (string name, Location l)
835 public Label LabelTarget (EmitContext ec)
840 label = ec.ig.DefineLabel ();
850 public bool IsDefined {
851 get { return defined; }
854 public bool HasBeenReferenced {
855 get { return referenced; }
858 public FlowBranching.UsageVector JumpOrigins {
859 get { return vectors; }
862 public void AddUsageVector (FlowBranching.UsageVector vector)
864 vector = vector.Clone ();
865 vector.Next = vectors;
869 public override bool Resolve (EmitContext ec)
871 // this flow-branching will be terminated when the surrounding block ends
872 ec.StartFlowBranching (this);
876 protected override void DoEmit (EmitContext ec)
878 if (ig != null && ig != ec.ig)
879 throw new InternalErrorException ("cannot happen");
881 ec.ig.MarkLabel (label);
884 public void AddReference ()
892 /// `goto default' statement
894 public class GotoDefault : Statement {
896 public GotoDefault (Location l)
901 public override bool Resolve (EmitContext ec)
903 ec.CurrentBranching.CurrentUsageVector.Goto ();
907 protected override void DoEmit (EmitContext ec)
909 if (ec.Switch == null){
910 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
914 if (!ec.Switch.GotDefault){
915 Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
918 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
923 /// `goto case' statement
925 public class GotoCase : Statement {
929 public GotoCase (Expression e, Location l)
935 public override bool Resolve (EmitContext ec)
937 if (ec.Switch == null){
938 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
942 expr = expr.Resolve (ec);
946 Constant c = expr as Constant;
948 Error (150, "A constant value is expected");
952 Type type = ec.Switch.SwitchType;
953 if (!Convert.ImplicitStandardConversionExists (c, type))
954 Report.Warning (469, 2, loc, "The `goto case' value is not implicitly " +
955 "convertible to type `{0}'", TypeManager.CSharpName (type));
958 object val = c.GetValue ();
959 if ((val != null) && (c.Type != type) && (c.Type != TypeManager.object_type))
960 val = TypeManager.ChangeType (val, type, out fail);
963 Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
964 c.GetSignatureForError (), TypeManager.CSharpName (type));
969 val = SwitchLabel.NullStringCase;
971 sl = (SwitchLabel) ec.Switch.Elements [val];
974 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", c.GetValue () == null ? "null" : val.ToString ());
978 ec.CurrentBranching.CurrentUsageVector.Goto ();
982 protected override void DoEmit (EmitContext ec)
984 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
987 protected override void CloneTo (CloneContext clonectx, Statement t)
989 GotoCase target = (GotoCase) t;
991 target.expr = expr.Clone (clonectx);
992 target.sl = sl.Clone (clonectx);
996 public class Throw : Statement {
999 public Throw (Expression expr, Location l)
1005 public override bool Resolve (EmitContext ec)
1007 ec.CurrentBranching.CurrentUsageVector.Goto ();
1010 expr = expr.Resolve (ec);
1014 ExprClass eclass = expr.eclass;
1016 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
1017 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
1018 expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
1024 if ((t != TypeManager.exception_type) &&
1025 !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
1026 !(expr is NullLiteral)) {
1028 "The type caught or thrown must be derived " +
1029 "from System.Exception");
1036 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
1041 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
1047 protected override void DoEmit (EmitContext ec)
1050 ec.ig.Emit (OpCodes.Rethrow);
1054 ec.ig.Emit (OpCodes.Throw);
1058 protected override void CloneTo (CloneContext clonectx, Statement t)
1060 Throw target = (Throw) t;
1062 target.expr = expr.Clone (clonectx);
1066 public class Break : Statement {
1068 public Break (Location l)
1073 bool unwind_protect;
1075 public override bool Resolve (EmitContext ec)
1077 int errors = Report.Errors;
1078 unwind_protect = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1079 ec.CurrentBranching.CurrentUsageVector.Goto ();
1080 return errors == Report.Errors;
1083 protected override void DoEmit (EmitContext ec)
1085 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
1089 public class Continue : Statement {
1091 public Continue (Location l)
1096 bool unwind_protect;
1098 public override bool Resolve (EmitContext ec)
1100 int errors = Report.Errors;
1101 unwind_protect = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1102 ec.CurrentBranching.CurrentUsageVector.Goto ();
1103 return errors == Report.Errors;
1106 protected override void DoEmit (EmitContext ec)
1108 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
1112 public abstract class Variable
1114 public abstract Type Type {
1118 public abstract bool HasInstance {
1122 public abstract bool NeedsTemporary {
1126 public abstract void EmitInstance (EmitContext ec);
1128 public abstract void Emit (EmitContext ec);
1130 public abstract void EmitAssign (EmitContext ec);
1132 public abstract void EmitAddressOf (EmitContext ec);
1136 // The information about a user-perceived local variable
1138 public class LocalInfo {
1139 public Expression Type;
1141 public Type VariableType;
1142 public readonly string Name;
1143 public readonly Location Location;
1144 public readonly Block Block;
1146 public VariableInfo VariableInfo;
1149 public Variable Variable {
1161 CompilerGenerated = 64,
1165 public enum ReadOnlyContext: byte {
1172 ReadOnlyContext ro_context;
1173 LocalBuilder builder;
1175 public LocalInfo (Expression type, string name, Block block, Location l)
1183 public LocalInfo (DeclSpace ds, Block block, Location l)
1185 VariableType = ds.IsGeneric ? ds.CurrentType : ds.TypeBuilder;
1190 public void ResolveVariable (EmitContext ec)
1192 Block theblock = Block;
1193 if (theblock.ScopeInfo != null)
1194 var = theblock.ScopeInfo.GetCapturedVariable (this);
1199 // This is needed to compile on both .NET 1.x and .NET 2.x
1200 // the later introduced `DeclareLocal (Type t, bool pinned)'
1202 builder = TypeManager.DeclareLocalPinned (ec.ig, VariableType);
1204 builder = ec.ig.DeclareLocal (VariableType);
1206 var = new LocalVariable (this, builder);
1210 public void EmitSymbolInfo (EmitContext ec, string name)
1212 if (builder != null)
1213 ec.DefineLocalVariable (name, builder);
1216 public bool IsThisAssigned (EmitContext ec)
1218 if (VariableInfo == null)
1219 throw new Exception ();
1221 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1224 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, ec.loc);
1227 public bool IsAssigned (EmitContext ec)
1229 if (VariableInfo == null)
1230 throw new Exception ();
1232 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1235 public bool Resolve (EmitContext ec)
1237 if (VariableType == null) {
1238 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1242 VariableType = texpr.Type;
1245 if (VariableType == TypeManager.void_type) {
1246 Expression.Error_VoidInvalidInTheContext (Location);
1250 if (VariableType.IsAbstract && VariableType.IsSealed) {
1251 FieldBase.Error_VariableOfStaticClass (Location, Name, VariableType);
1255 if (VariableType.IsPointer && !ec.InUnsafe)
1256 Expression.UnsafeError (Location);
1261 public bool IsCaptured {
1263 return (flags & Flags.Captured) != 0;
1267 flags |= Flags.Captured;
1271 public bool IsConstant {
1273 return (flags & Flags.IsConstant) != 0;
1276 flags |= Flags.IsConstant;
1280 public bool AddressTaken {
1282 return (flags & Flags.AddressTaken) != 0;
1286 flags |= Flags.AddressTaken;
1290 public bool CompilerGenerated {
1292 return (flags & Flags.CompilerGenerated) != 0;
1296 flags |= Flags.CompilerGenerated;
1300 public override string ToString ()
1302 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1303 Name, Type, VariableInfo, Location);
1308 return (flags & Flags.Used) != 0;
1311 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1315 public bool ReadOnly {
1317 return (flags & Flags.ReadOnly) != 0;
1321 public void SetReadOnlyContext (ReadOnlyContext context)
1323 flags |= Flags.ReadOnly;
1324 ro_context = context;
1327 public string GetReadOnlyContext ()
1330 throw new InternalErrorException ("Variable is not readonly");
1332 switch (ro_context) {
1333 case ReadOnlyContext.Fixed:
1334 return "fixed variable";
1335 case ReadOnlyContext.Foreach:
1336 return "foreach iteration variable";
1337 case ReadOnlyContext.Using:
1338 return "using variable";
1340 throw new NotImplementedException ();
1344 // Whether the variable is pinned, if Pinned the variable has been
1345 // allocated in a pinned slot with DeclareLocal.
1347 public bool Pinned {
1349 return (flags & Flags.Pinned) != 0;
1352 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1356 public bool IsThis {
1358 return (flags & Flags.IsThis) != 0;
1361 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1365 protected class LocalVariable : Variable
1367 public readonly LocalInfo LocalInfo;
1368 LocalBuilder builder;
1370 public LocalVariable (LocalInfo local, LocalBuilder builder)
1372 this.LocalInfo = local;
1373 this.builder = builder;
1376 public override Type Type {
1377 get { return LocalInfo.VariableType; }
1380 public override bool HasInstance {
1381 get { return false; }
1384 public override bool NeedsTemporary {
1385 get { return false; }
1388 public override void EmitInstance (EmitContext ec)
1393 public override void Emit (EmitContext ec)
1395 ec.ig.Emit (OpCodes.Ldloc, builder);
1398 public override void EmitAssign (EmitContext ec)
1400 ec.ig.Emit (OpCodes.Stloc, builder);
1403 public override void EmitAddressOf (EmitContext ec)
1405 ec.ig.Emit (OpCodes.Ldloca, builder);
1409 public LocalInfo Clone (CloneContext clonectx)
1411 // Only this kind is created by the parser.
1412 return new LocalInfo (Type.Clone (clonectx), Name, clonectx.LookupBlock (Block), Location);
1417 /// Block represents a C# block.
1421 /// This class is used in a number of places: either to represent
1422 /// explicit blocks that the programmer places or implicit blocks.
1424 /// Implicit blocks are used as labels or to introduce variable
1427 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1428 /// they contain extra information that is not necessary on normal blocks.
1430 public class Block : Statement {
1431 public Block Parent;
1432 public readonly Location StartLocation;
1433 public Location EndLocation = Location.Null;
1435 public readonly ToplevelBlock Toplevel;
1438 public enum Flags : ushort {
1442 VariablesInitialized = 8,
1447 HasVarargs = 256, // Used in ToplevelBlock
1451 protected Flags flags;
1453 public bool Implicit {
1454 get { return (flags & Flags.Implicit) != 0; }
1457 public bool Unchecked {
1458 get { return (flags & Flags.Unchecked) != 0; }
1459 set { flags |= Flags.Unchecked; }
1462 public bool Unsafe {
1463 get { return (flags & Flags.Unsafe) != 0; }
1464 set { flags |= Flags.Unsafe; }
1468 // The statements in this block
1470 protected ArrayList statements;
1474 // An array of Blocks. We keep track of children just
1475 // to generate the local variable declarations.
1477 // Statements and child statements are handled through the
1483 // Labels. (label, block) pairs.
1488 // Keeps track of (name, type) pairs
1490 IDictionary variables;
1493 // Keeps track of constants
1494 Hashtable constants;
1497 // Temporary variables.
1499 ArrayList temporary_variables;
1502 // If this is a switch section, the enclosing switch block.
1506 ExpressionStatement scope_init;
1508 ArrayList anonymous_children;
1510 protected static int id;
1514 public Block (Block parent)
1515 : this (parent, (Flags) 0, Location.Null, Location.Null)
1518 public Block (Block parent, Flags flags)
1519 : this (parent, flags, Location.Null, Location.Null)
1522 public Block (Block parent, Location start, Location end)
1523 : this (parent, (Flags) 0, start, end)
1526 public Block (Block parent, Flags flags, Location start, Location end)
1529 parent.AddChild (this);
1531 this.Parent = parent;
1533 this.StartLocation = start;
1534 this.EndLocation = end;
1537 statements = new ArrayList ();
1539 if ((flags & Flags.IsToplevel) != 0)
1540 Toplevel = (ToplevelBlock) this;
1542 Toplevel = parent.Toplevel;
1544 if (parent != null && Implicit) {
1545 if (parent.known_variables == null)
1546 parent.known_variables = new Hashtable ();
1547 // share with parent
1548 known_variables = parent.known_variables;
1552 public Block CreateSwitchBlock (Location start)
1554 Block new_block = new Block (this, start, start);
1555 new_block.switch_block = this;
1560 get { return this_id; }
1563 public IDictionary Variables {
1565 if (variables == null)
1566 variables = new ListDictionary ();
1571 void AddChild (Block b)
1573 if (children == null)
1574 children = new ArrayList ();
1579 public void SetEndLocation (Location loc)
1584 protected static void Error_158 (string name, Location loc)
1586 Report.Error (158, loc, "The label `{0}' shadows another label " +
1587 "by the same name in a contained scope.", name);
1591 /// Adds a label to the current block.
1595 /// false if the name already exists in this block. true
1599 public bool AddLabel (LabeledStatement target)
1601 if (switch_block != null)
1602 return switch_block.AddLabel (target);
1604 string name = target.Name;
1607 while (cur != null) {
1608 if (cur.DoLookupLabel (name) != null) {
1609 Report.Error (140, target.loc,
1610 "The label `{0}' is a duplicate", name);
1620 while (cur != null) {
1621 if (cur.DoLookupLabel (name) != null) {
1622 Error_158 (name, target.loc);
1626 if (children != null) {
1627 foreach (Block b in children) {
1628 LabeledStatement s = b.DoLookupLabel (name);
1632 Error_158 (name, target.loc);
1640 Toplevel.CheckError158 (name, target.loc);
1643 labels = new Hashtable ();
1645 labels.Add (name, target);
1649 public LabeledStatement LookupLabel (string name)
1651 LabeledStatement s = DoLookupLabel (name);
1655 if (children == null)
1658 foreach (Block child in children) {
1659 if (!child.Implicit)
1662 s = child.LookupLabel (name);
1670 LabeledStatement DoLookupLabel (string name)
1672 if (switch_block != null)
1673 return switch_block.LookupLabel (name);
1676 if (labels.Contains (name))
1677 return ((LabeledStatement) labels [name]);
1682 Hashtable known_variables;
1685 // Marks a variable with name @name as being used in this or a child block.
1686 // If a variable name has been used in a child block, it's illegal to
1687 // declare a variable with the same name in the current block.
1689 void AddKnownVariable (string name, LocalInfo info)
1691 if (known_variables == null)
1692 known_variables = new Hashtable ();
1694 known_variables [name] = info;
1697 LocalInfo GetKnownVariableInfo (string name, bool recurse)
1699 if (known_variables != null) {
1700 LocalInfo vi = (LocalInfo) known_variables [name];
1705 if (!recurse || (children == null))
1708 foreach (Block block in children) {
1709 LocalInfo vi = block.GetKnownVariableInfo (name, true);
1717 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1720 LocalInfo kvi = b.GetKnownVariableInfo (name, true);
1721 while (kvi == null) {
1727 kvi = b.GetKnownVariableInfo (name, false);
1733 // Is kvi.Block nested inside 'b'
1734 if (b.known_variables != kvi.Block.known_variables) {
1736 // If a variable by the same name it defined in a nested block of this
1737 // block, we violate the invariant meaning in a block.
1740 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1741 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1746 // It's ok if the definition is in a nested subblock of b, but not
1747 // nested inside this block -- a definition in a sibling block
1748 // should not affect us.
1754 // Block 'b' and kvi.Block are the same textual block.
1755 // However, different variables are extant.
1757 // Check if the variable is in scope in both blocks. We use
1758 // an indirect check that depends on AddVariable doing its
1759 // part in maintaining the invariant-meaning-in-block property.
1761 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1765 // Even though we detected the error when the name is used, we
1766 // treat it as if the variable declaration was in error.
1768 Report.SymbolRelatedToPreviousError (loc, name);
1769 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1773 public bool CheckError136_InParents (string name, Location loc)
1775 for (Block b = Parent; b != null; b = b.Parent) {
1776 if (!b.DoCheckError136 (name, "parent or current", loc))
1780 for (Block b = Toplevel.ContainerBlock; b != null; b = b.Toplevel.ContainerBlock) {
1781 if (!b.CheckError136_InParents (name, loc))
1788 public bool CheckError136_InChildren (string name, Location loc)
1790 if (!DoCheckError136_InChildren (name, loc))
1794 while (b.Implicit) {
1795 if (!b.Parent.DoCheckError136_InChildren (name, loc))
1803 protected bool DoCheckError136_InChildren (string name, Location loc)
1805 if (!DoCheckError136 (name, "child", loc))
1808 if (AnonymousChildren != null) {
1809 foreach (ToplevelBlock child in AnonymousChildren) {
1810 if (!child.DoCheckError136_InChildren (name, loc))
1815 if (children != null) {
1816 foreach (Block child in children) {
1817 if (!child.DoCheckError136_InChildren (name, loc))
1825 public bool CheckError136 (string name, string scope, bool check_parents,
1826 bool check_children, Location loc)
1828 if (!DoCheckError136 (name, scope, loc))
1831 if (check_parents) {
1832 if (!CheckError136_InParents (name, loc))
1836 if (check_children) {
1837 if (!CheckError136_InChildren (name, loc))
1841 for (Block c = Toplevel.ContainerBlock; c != null; c = c.Toplevel.ContainerBlock) {
1842 if (!c.DoCheckError136 (name, "parent or current", loc))
1849 protected bool DoCheckError136 (string name, string scope, Location loc)
1851 LocalInfo vi = GetKnownVariableInfo (name, false);
1853 Report.SymbolRelatedToPreviousError (vi.Location, name);
1854 Error_AlreadyDeclared (loc, name, scope != null ? scope : "child");
1859 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1861 Report.SymbolRelatedToPreviousError (p.Location, name);
1862 Error_AlreadyDeclared (
1863 loc, name, scope != null ? scope : "method argument");
1870 public LocalInfo AddVariable (Expression type, string name, Location l)
1872 LocalInfo vi = GetLocalInfo (name);
1874 Report.SymbolRelatedToPreviousError (vi.Location, name);
1875 if (known_variables == vi.Block.known_variables)
1876 Report.Error (128, l,
1877 "A local variable named `{0}' is already defined in this scope", name);
1879 Error_AlreadyDeclared (l, name, "parent");
1883 if (!CheckError136 (name, null, true, true, l))
1886 vi = new LocalInfo (type, name, this, l);
1887 Variables.Add (name, vi);
1888 AddKnownVariable (name, vi);
1890 if ((flags & Flags.VariablesInitialized) != 0)
1891 throw new Exception ();
1896 void Error_AlreadyDeclared (Location loc, string var, string reason)
1898 Report.Error (136, loc, "A local variable named `{0}' cannot be declared " +
1899 "in this scope because it would give a different meaning " +
1900 "to `{0}', which is already used in a `{1}' scope " +
1901 "to denote something else", var, reason);
1904 public bool AddConstant (Expression type, string name, Expression value, Location l)
1906 if (AddVariable (type, name, l) == null)
1909 if (constants == null)
1910 constants = new Hashtable ();
1912 constants.Add (name, value);
1914 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1919 static int next_temp_id = 0;
1921 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1923 Report.Debug (64, "ADD TEMPORARY", this, Toplevel, loc);
1925 if (temporary_variables == null)
1926 temporary_variables = new ArrayList ();
1928 int id = ++next_temp_id;
1929 string name = "$s_" + id.ToString ();
1931 LocalInfo li = new LocalInfo (te, name, this, loc);
1932 li.CompilerGenerated = true;
1933 temporary_variables.Add (li);
1937 public LocalInfo GetLocalInfo (string name)
1939 for (Block b = this; b != null; b = b.Parent) {
1940 if (b.variables != null) {
1941 LocalInfo ret = b.variables [name] as LocalInfo;
1949 public Expression GetVariableType (string name)
1951 LocalInfo vi = GetLocalInfo (name);
1952 return vi == null ? null : vi.Type;
1955 public Expression GetConstantExpression (string name)
1957 for (Block b = this; b != null; b = b.Parent) {
1958 if (b.constants != null) {
1959 Expression ret = b.constants [name] as Expression;
1967 public void AddStatement (Statement s)
1970 flags |= Flags.BlockUsed;
1974 get { return (flags & Flags.BlockUsed) != 0; }
1979 flags |= Flags.BlockUsed;
1982 public bool HasRet {
1983 get { return (flags & Flags.HasRet) != 0; }
1986 public bool IsDestructor {
1987 get { return (flags & Flags.IsDestructor) != 0; }
1990 public void SetDestructor ()
1992 flags |= Flags.IsDestructor;
1995 VariableMap param_map, local_map;
1997 public VariableMap ParameterMap {
1999 if ((flags & Flags.VariablesInitialized) == 0){
2000 throw new Exception ("Variables have not been initialized yet");
2007 public VariableMap LocalMap {
2009 if ((flags & Flags.VariablesInitialized) == 0)
2010 throw new Exception ("Variables have not been initialized yet");
2016 public ScopeInfo ScopeInfo;
2018 public ScopeInfo CreateScopeInfo ()
2020 if (ScopeInfo == null)
2021 ScopeInfo = ScopeInfo.CreateScope (this);
2026 public ArrayList AnonymousChildren {
2027 get { return anonymous_children; }
2030 public void AddAnonymousChild (ToplevelBlock b)
2032 if (anonymous_children == null)
2033 anonymous_children = new ArrayList ();
2035 anonymous_children.Add (b);
2039 /// Emits the variable declarations and labels.
2042 /// tc: is our typecontainer (to resolve type references)
2043 /// ig: is the code generator:
2045 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
2047 Report.Debug (64, "BLOCK RESOLVE META", this, Parent, toplevel);
2049 // If some parent block was unsafe, we remain unsafe even if this block
2050 // isn't explicitly marked as such.
2051 using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
2053 // Compute the VariableMap's.
2055 // Unfortunately, we don't know the type when adding variables with
2056 // AddVariable(), so we need to compute this info here.
2060 if (variables != null) {
2061 foreach (LocalInfo li in variables.Values)
2064 locals = new LocalInfo [variables.Count];
2065 variables.Values.CopyTo (locals, 0);
2067 locals = new LocalInfo [0];
2070 local_map = new VariableMap (Parent.LocalMap, locals);
2072 local_map = new VariableMap (locals);
2074 param_map = new VariableMap (ip);
2075 flags |= Flags.VariablesInitialized;
2078 // Process this block variables
2080 if (variables != null) {
2081 foreach (DictionaryEntry de in variables) {
2082 string name = (string) de.Key;
2083 LocalInfo vi = (LocalInfo) de.Value;
2084 Type variable_type = vi.VariableType;
2086 if (variable_type == null)
2089 if (variable_type.IsPointer) {
2091 // Am not really convinced that this test is required (Microsoft does it)
2092 // but the fact is that you would not be able to use the pointer variable
2095 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
2100 if (constants == null)
2103 Expression cv = (Expression) constants [name];
2107 // Don't let 'const int Foo = Foo;' succeed.
2108 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
2109 // which in turn causes the 'must be constant' error to be triggered.
2110 constants.Remove (name);
2112 if (!Const.IsConstantTypeValid (variable_type)) {
2113 Const.Error_InvalidConstantType (variable_type, loc);
2117 using (ec.With (EmitContext.Flags.ConstantCheckState, (flags & Flags.Unchecked) == 0)) {
2118 ec.CurrentBlock = this;
2119 Expression e = cv.Resolve (ec);
2123 Constant ce = e as Constant;
2125 Const.Error_ExpressionMustBeConstant (vi.Location, name);
2129 e = ce.ConvertImplicitly (variable_type);
2131 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue)
2132 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
2134 ce.Error_ValueCannotBeConverted (null, vi.Location, variable_type, false);
2138 constants.Add (name, e);
2139 vi.IsConstant = true;
2145 // Now, handle the children
2147 if (children != null) {
2148 foreach (Block b in children)
2149 b.ResolveMeta (toplevel, ec, ip);
2155 // Emits the local variable declarations for a block
2157 public virtual void EmitMeta (EmitContext ec)
2159 Report.Debug (64, "BLOCK EMIT META", this, Parent, Toplevel, ScopeInfo, ec);
2160 if (ScopeInfo != null) {
2161 scope_init = ScopeInfo.GetScopeInitializer (ec);
2162 Report.Debug (64, "BLOCK EMIT META #1", this, Toplevel, ScopeInfo,
2166 if (variables != null){
2167 foreach (LocalInfo vi in variables.Values)
2168 vi.ResolveVariable (ec);
2171 if (temporary_variables != null) {
2172 foreach (LocalInfo vi in temporary_variables)
2173 vi.ResolveVariable (ec);
2176 if (children != null){
2177 foreach (Block b in children)
2182 void UsageWarning (FlowBranching.UsageVector vector)
2186 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
2187 foreach (DictionaryEntry de in variables){
2188 LocalInfo vi = (LocalInfo) de.Value;
2193 name = (string) de.Key;
2195 // vi.VariableInfo can be null for 'catch' variables
2196 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
2197 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
2199 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
2205 bool unreachable_shown;
2208 private void CheckPossibleMistakenEmptyStatement (Statement s)
2212 // Some statements are wrapped by a Block. Since
2213 // others' internal could be changed, here I treat
2214 // them as possibly wrapped by Block equally.
2215 Block b = s as Block;
2216 if (b != null && b.statements.Count == 1)
2217 s = (Statement) b.statements [0];
2220 body = ((Lock) s).Statement;
2222 body = ((For) s).Statement;
2223 else if (s is Foreach)
2224 body = ((Foreach) s).Statement;
2225 else if (s is While)
2226 body = ((While) s).Statement;
2227 else if (s is Using)
2228 body = ((Using) s).Statement;
2229 else if (s is Fixed)
2230 body = ((Fixed) s).Statement;
2234 if (body == null || body is EmptyStatement)
2235 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
2238 public override bool Resolve (EmitContext ec)
2240 Block prev_block = ec.CurrentBlock;
2243 int errors = Report.Errors;
2245 ec.CurrentBlock = this;
2246 ec.StartFlowBranching (this);
2248 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
2251 // This flag is used to notate nested statements as unreachable from the beginning of this block.
2252 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
2253 // from the beginning of the function. The outer Resolve() that detected the unreachability is
2254 // responsible for handling the situation.
2256 int statement_count = statements.Count;
2257 for (int ix = 0; ix < statement_count; ix++){
2258 Statement s = (Statement) statements [ix];
2259 // Check possible empty statement (CS0642)
2260 if (RootContext.WarningLevel >= 3 &&
2261 ix + 1 < statement_count &&
2262 statements [ix + 1] is Block)
2263 CheckPossibleMistakenEmptyStatement (s);
2266 // Warn if we detect unreachable code.
2269 if (s is EmptyStatement)
2273 ((Block) s).unreachable = true;
2275 if (!unreachable_shown && !(s is LabeledStatement)) {
2276 Report.Warning (162, 2, s.loc, "Unreachable code detected");
2277 unreachable_shown = true;
2282 // Note that we're not using ResolveUnreachable() for unreachable
2283 // statements here. ResolveUnreachable() creates a temporary
2284 // flow branching and kills it afterwards. This leads to problems
2285 // if you have two unreachable statements where the first one
2286 // assigns a variable and the second one tries to access it.
2289 if (!s.Resolve (ec)) {
2291 statements [ix] = EmptyStatement.Value;
2295 if (unreachable && !(s is LabeledStatement) && !(s is Block))
2296 statements [ix] = EmptyStatement.Value;
2298 num_statements = ix + 1;
2300 unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
2301 if (unreachable && s is LabeledStatement)
2302 throw new InternalErrorException ("should not happen");
2305 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
2306 ec.CurrentBranching, statement_count, num_statements);
2311 while (ec.CurrentBranching is FlowBranchingLabeled)
2312 ec.EndFlowBranching ();
2314 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
2316 ec.CurrentBlock = prev_block;
2318 // If we're a non-static `struct' constructor which doesn't have an
2319 // initializer, then we must initialize all of the struct's fields.
2320 if ((flags & Flags.IsToplevel) != 0 &&
2321 !Toplevel.IsThisAssigned (ec) &&
2322 !vector.IsUnreachable)
2325 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2326 foreach (LabeledStatement label in labels.Values)
2327 if (!label.HasBeenReferenced)
2328 Report.Warning (164, 2, label.loc,
2329 "This label has not been referenced");
2332 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2334 if (vector.IsUnreachable)
2335 flags |= Flags.HasRet;
2337 if (ok && (errors == Report.Errors)) {
2338 if (RootContext.WarningLevel >= 3)
2339 UsageWarning (vector);
2345 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2347 unreachable_shown = true;
2351 Report.Warning (162, 2, loc, "Unreachable code detected");
2353 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2354 bool ok = Resolve (ec);
2355 ec.KillFlowBranching ();
2360 protected override void DoEmit (EmitContext ec)
2362 for (int ix = 0; ix < num_statements; ix++){
2363 Statement s = (Statement) statements [ix];
2365 // Check whether we are the last statement in a
2368 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2369 ec.IsLastStatement = true;
2371 ec.IsLastStatement = false;
2377 public override void Emit (EmitContext ec)
2379 Block prev_block = ec.CurrentBlock;
2381 ec.CurrentBlock = this;
2383 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2384 bool is_lexical_block = !Implicit && (Parent != null);
2386 if (emit_debug_info) {
2387 if (is_lexical_block)
2390 ec.Mark (StartLocation, true);
2391 if (scope_init != null)
2392 scope_init.EmitStatement (ec);
2394 ec.Mark (EndLocation, true);
2396 if (emit_debug_info) {
2397 if (is_lexical_block)
2400 if (variables != null) {
2401 foreach (DictionaryEntry de in variables) {
2402 string name = (string) de.Key;
2403 LocalInfo vi = (LocalInfo) de.Value;
2405 vi.EmitSymbolInfo (ec, name);
2410 ec.CurrentBlock = prev_block;
2414 // Returns true if we ar ea child of `b'.
2416 public bool IsChildOf (Block b)
2418 Block current = this;
2421 if (current.Parent == b)
2423 current = current.Parent;
2424 } while (current != null);
2428 public override string ToString ()
2430 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2433 protected override void CloneTo (CloneContext clonectx, Statement t)
2435 Block target = (Block) t;
2438 target.Parent = clonectx.LookupBlock (Parent);
2440 target.statements = new ArrayList ();
2441 if (target.children != null){
2442 target.children = new ArrayList ();
2443 foreach (Block b in children){
2444 Block newblock = (Block) b.Clone (clonectx);
2446 target.children.Add (newblock);
2451 foreach (Statement s in statements)
2452 target.statements.Add (s.Clone (clonectx));
2454 if (variables != null){
2455 target.variables = new Hashtable ();
2457 foreach (DictionaryEntry de in variables){
2458 LocalInfo newlocal = ((LocalInfo) de.Value).Clone (clonectx);
2459 target.variables [de.Key] = newlocal;
2460 clonectx.AddVariableMap ((LocalInfo) de.Value, newlocal);
2465 // TODO: labels, switch_block, constants (?), anonymous_children
2471 // A toplevel block contains extra information, the split is done
2472 // only to separate information that would otherwise bloat the more
2473 // lightweight Block.
2475 // In particular, this was introduced when the support for Anonymous
2476 // Methods was implemented.
2478 public class ToplevelBlock : Block {
2480 // Pointer to the host of this anonymous method, or null
2481 // if we are the topmost block
2484 ToplevelBlock child;
2485 GenericMethod generic;
2486 FlowBranchingToplevel top_level_branching;
2487 AnonymousContainer anonymous_container;
2488 RootScopeInfo root_scope;
2490 public bool HasVarargs {
2491 get { return (flags & Flags.HasVarargs) != 0; }
2492 set { flags |= Flags.HasVarargs; }
2495 public bool IsIterator {
2496 get { return (flags & Flags.IsIterator) != 0; }
2500 // The parameters for the block.
2502 Parameters parameters;
2503 public Parameters Parameters {
2504 get { return parameters; }
2507 public bool CompleteContexts (EmitContext ec)
2509 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS", this,
2510 container, root_scope);
2512 if (root_scope != null)
2513 root_scope.LinkScopes ();
2515 if ((container == null) && (root_scope != null)) {
2516 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS #1", this,
2519 if (root_scope.DefineType () == null)
2521 if (!root_scope.ResolveType ())
2523 if (!root_scope.ResolveMembers ())
2525 if (!root_scope.DefineMembers ())
2532 public GenericMethod GenericMethod {
2533 get { return generic; }
2536 public ToplevelBlock Container {
2537 get { return container != null ? container.Toplevel : null; }
2540 public Block ContainerBlock {
2541 get { return container; }
2544 public AnonymousContainer AnonymousContainer {
2545 get { return anonymous_container; }
2546 set { anonymous_container = value; }
2550 // Parent is only used by anonymous blocks to link back to their
2553 public ToplevelBlock (Block container, Parameters parameters, Location start) :
2554 this (container, (Flags) 0, parameters, start)
2558 public ToplevelBlock (Block container, Parameters parameters, GenericMethod generic,
2560 this (container, parameters, start)
2562 this.generic = generic;
2565 public ToplevelBlock (Parameters parameters, Location start) :
2566 this (null, (Flags) 0, parameters, start)
2570 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2571 this (null, flags, parameters, start)
2575 public ToplevelBlock (Block container, Flags flags, Parameters parameters, Location start) :
2576 base (null, flags | Flags.IsToplevel, start, Location.Null)
2578 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2579 this.container = container;
2582 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2586 public bool CheckError158 (string name, Location loc)
2588 if (AnonymousChildren != null) {
2589 foreach (ToplevelBlock child in AnonymousChildren) {
2590 if (!child.CheckError158 (name, loc))
2595 for (ToplevelBlock c = Container; c != null; c = c.Container) {
2596 if (!c.DoCheckError158 (name, loc))
2603 bool DoCheckError158 (string name, Location loc)
2605 LabeledStatement s = LookupLabel (name);
2607 Error_158 (name, loc);
2614 public RootScopeInfo CreateRootScope (TypeContainer host)
2616 if (root_scope != null)
2619 if (Container == null)
2620 root_scope = new RootScopeInfo (
2621 this, host, generic, StartLocation);
2623 ScopeInfo = root_scope;
2627 public void CreateIteratorHost (RootScopeInfo root)
2629 Report.Debug (64, "CREATE ITERATOR HOST", this, root,
2630 container, root_scope);
2632 if ((container != null) || (root_scope != null))
2633 throw new InternalErrorException ();
2635 ScopeInfo = root_scope = root;
2638 public RootScopeInfo RootScope {
2640 if (root_scope != null)
2642 else if (Container != null)
2643 return Container.RootScope;
2649 public FlowBranchingToplevel TopLevelBranching {
2650 get { return top_level_branching; }
2654 // This is used if anonymous methods are used inside an iterator
2655 // (see 2test-22.cs for an example).
2657 // The AnonymousMethod is created while parsing - at a time when we don't
2658 // know yet that we're inside an iterator, so it's `Container' is initially
2659 // null. Later on, when resolving the iterator, we need to move the
2660 // anonymous method into that iterator.
2662 public void ReParent (ToplevelBlock new_parent)
2664 container = new_parent;
2665 Parent = new_parent;
2666 new_parent.child = this;
2670 // Returns a `ParameterReference' for the given name, or null if there
2671 // is no such parameter
2673 public ParameterReference GetParameterReference (string name, Location loc)
2678 for (ToplevelBlock t = this; t != null; t = t.Container) {
2679 Parameters pars = t.Parameters;
2680 par = pars.GetParameterByName (name, out idx);
2682 return new ParameterReference (par, this, idx, loc);
2688 // Whether the parameter named `name' is local to this block,
2689 // or false, if the parameter belongs to an encompassing block.
2691 public bool IsLocalParameter (string name)
2693 return Parameters.GetParameterByName (name) != null;
2697 // Whether the `name' is a parameter reference
2699 public bool IsParameterReference (string name)
2701 for (ToplevelBlock t = this; t != null; t = t.Container) {
2702 if (t.IsLocalParameter (name))
2708 LocalInfo this_variable = null;
2711 // Returns the "this" instance variable of this block.
2712 // See AddThisVariable() for more information.
2714 public LocalInfo ThisVariable {
2715 get { return this_variable; }
2720 // This is used by non-static `struct' constructors which do not have an
2721 // initializer - in this case, the constructor must initialize all of the
2722 // struct's fields. To do this, we add a "this" variable and use the flow
2723 // analysis code to ensure that it's been fully initialized before control
2724 // leaves the constructor.
2726 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2728 if (this_variable == null) {
2729 this_variable = new LocalInfo (ds, this, l);
2730 this_variable.Used = true;
2731 this_variable.IsThis = true;
2733 Variables.Add ("this", this_variable);
2736 return this_variable;
2739 public bool IsThisAssigned (EmitContext ec)
2741 return this_variable == null || this_variable.IsThisAssigned (ec);
2744 public bool ResolveMeta (EmitContext ec, Parameters ip)
2746 int errors = Report.Errors;
2748 if (top_level_branching != null)
2754 if (!IsIterator && (container != null) && (parameters != null)) {
2755 foreach (Parameter p in parameters.FixedParameters) {
2756 if (!CheckError136_InParents (p.Name, loc))
2761 ResolveMeta (this, ec, ip);
2764 child.ResolveMeta (this, ec, ip);
2766 top_level_branching = ec.StartFlowBranching (this);
2768 return Report.Errors == errors;
2771 public override void EmitMeta (EmitContext ec)
2774 parameters.ResolveVariable (this);
2777 public void MakeIterator (Iterator iterator)
2779 flags |= Flags.IsIterator;
2781 Block block = new Block (this);
2782 foreach (Statement stmt in statements)
2783 block.AddStatement (stmt);
2784 statements = new ArrayList ();
2785 statements.Add (new MoveNextStatement (iterator, block));
2788 protected class MoveNextStatement : Statement {
2792 public MoveNextStatement (Iterator iterator, Block block)
2794 this.iterator = iterator;
2796 this.loc = iterator.Location;
2799 public override bool Resolve (EmitContext ec)
2801 return block.Resolve (ec);
2804 protected override void DoEmit (EmitContext ec)
2806 iterator.EmitMoveNext (ec, block);
2810 public override string ToString ()
2812 return String.Format ("{0} ({1}:{2}{3}:{4})", GetType (), ID, StartLocation,
2813 root_scope, anonymous_container != null ?
2814 anonymous_container.Scope : null);
2818 public class SwitchLabel {
2825 Label il_label_code;
2826 bool il_label_code_set;
2828 public static readonly object NullStringCase = new object ();
2831 // if expr == null, then it is the default case.
2833 public SwitchLabel (Expression expr, Location l)
2839 public Expression Label {
2845 public object Converted {
2851 public Label GetILLabel (EmitContext ec)
2854 il_label = ec.ig.DefineLabel ();
2855 il_label_set = true;
2860 public Label GetILLabelCode (EmitContext ec)
2862 if (!il_label_code_set){
2863 il_label_code = ec.ig.DefineLabel ();
2864 il_label_code_set = true;
2866 return il_label_code;
2870 // Resolves the expression, reduces it to a literal if possible
2871 // and then converts it to the requested type.
2873 public bool ResolveAndReduce (EmitContext ec, Type required_type, bool allow_nullable)
2875 Expression e = label.Resolve (ec);
2880 Constant c = e as Constant;
2882 Report.Error (150, loc, "A constant value is expected");
2886 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2887 converted = NullStringCase;
2891 if (allow_nullable && c.GetValue () == null) {
2892 converted = NullStringCase;
2896 c = c.ImplicitConversionRequired (required_type, loc);
2900 converted = c.GetValue ();
2904 public void Erorr_AlreadyOccurs (Type switchType, SwitchLabel collisionWith)
2907 if (converted == null)
2909 else if (converted == NullStringCase)
2911 else if (TypeManager.IsEnumType (switchType))
2912 label = TypeManager.CSharpEnumValue (switchType, converted);
2914 label = converted.ToString ();
2916 Report.SymbolRelatedToPreviousError (collisionWith.loc, null);
2917 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2920 public SwitchLabel Clone (CloneContext clonectx)
2922 return new SwitchLabel (label.Clone (clonectx), loc);
2926 public class SwitchSection {
2927 // An array of SwitchLabels.
2928 public readonly ArrayList Labels;
2929 public readonly Block Block;
2931 public SwitchSection (ArrayList labels, Block block)
2937 public SwitchSection Clone (CloneContext clonectx)
2939 ArrayList cloned_labels = new ArrayList ();
2941 foreach (SwitchLabel sl in cloned_labels)
2942 cloned_labels.Add (sl.Clone (clonectx));
2944 return new SwitchSection (cloned_labels, clonectx.LookupBlock (Block));
2948 public class Switch : Statement {
2949 public ArrayList Sections;
2950 public Expression Expr;
2953 /// Maps constants whose type type SwitchType to their SwitchLabels.
2955 public IDictionary Elements;
2958 /// The governing switch type
2960 public Type SwitchType;
2965 Label default_target;
2967 Expression new_expr;
2969 SwitchSection constant_section;
2970 SwitchSection default_section;
2974 // Nullable Types support for GMCS.
2976 Nullable.Unwrap unwrap;
2978 protected bool HaveUnwrap {
2979 get { return unwrap != null; }
2982 protected bool HaveUnwrap {
2983 get { return false; }
2988 // The types allowed to be implicitly cast from
2989 // on the governing type
2991 static Type [] allowed_types;
2993 public Switch (Expression e, ArrayList sects, Location l)
3000 public bool GotDefault {
3002 return default_section != null;
3006 public Label DefaultTarget {
3008 return default_target;
3013 // Determines the governing type for a switch. The returned
3014 // expression might be the expression from the switch, or an
3015 // expression that includes any potential conversions to the
3016 // integral types or to string.
3018 Expression SwitchGoverningType (EmitContext ec, Expression expr)
3020 Type t = TypeManager.DropGenericTypeArguments (expr.Type);
3022 if (t == TypeManager.byte_type ||
3023 t == TypeManager.sbyte_type ||
3024 t == TypeManager.ushort_type ||
3025 t == TypeManager.short_type ||
3026 t == TypeManager.uint32_type ||
3027 t == TypeManager.int32_type ||
3028 t == TypeManager.uint64_type ||
3029 t == TypeManager.int64_type ||
3030 t == TypeManager.char_type ||
3031 t == TypeManager.string_type ||
3032 t == TypeManager.bool_type ||
3033 t.IsSubclassOf (TypeManager.enum_type))
3036 if (allowed_types == null){
3037 allowed_types = new Type [] {
3038 TypeManager.sbyte_type,
3039 TypeManager.byte_type,
3040 TypeManager.short_type,
3041 TypeManager.ushort_type,
3042 TypeManager.int32_type,
3043 TypeManager.uint32_type,
3044 TypeManager.int64_type,
3045 TypeManager.uint64_type,
3046 TypeManager.char_type,
3047 TypeManager.string_type,
3048 TypeManager.bool_type
3053 // Try to find a *user* defined implicit conversion.
3055 // If there is no implicit conversion, or if there are multiple
3056 // conversions, we have to report an error
3058 Expression converted = null;
3059 foreach (Type tt in allowed_types){
3062 e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
3067 // Ignore over-worked ImplicitUserConversions that do
3068 // an implicit conversion in addition to the user conversion.
3070 if (!(e is UserCast))
3073 if (converted != null){
3074 Report.ExtraInformation (
3076 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
3077 TypeManager.CSharpName (expr.Type)));
3087 // Performs the basic sanity checks on the switch statement
3088 // (looks for duplicate keys and non-constant expressions).
3090 // It also returns a hashtable with the keys that we will later
3091 // use to compute the switch tables
3093 bool CheckSwitch (EmitContext ec)
3096 Elements = Sections.Count > 10 ?
3097 (IDictionary)new Hashtable () :
3098 (IDictionary)new ListDictionary ();
3100 foreach (SwitchSection ss in Sections){
3101 foreach (SwitchLabel sl in ss.Labels){
3102 if (sl.Label == null){
3103 if (default_section != null){
3104 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)default_section.Labels [0]);
3107 default_section = ss;
3111 if (!sl.ResolveAndReduce (ec, SwitchType, HaveUnwrap)) {
3116 object key = sl.Converted;
3118 Elements.Add (key, sl);
3119 } catch (ArgumentException) {
3120 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)Elements [key]);
3128 void EmitObjectInteger (ILGenerator ig, object k)
3131 IntConstant.EmitInt (ig, (int) k);
3132 else if (k is Constant) {
3133 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3136 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3139 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3141 IntConstant.EmitInt (ig, (int) (long) k);
3142 ig.Emit (OpCodes.Conv_I8);
3145 LongConstant.EmitLong (ig, (long) k);
3147 else if (k is ulong)
3149 ulong ul = (ulong) k;
3152 IntConstant.EmitInt (ig, unchecked ((int) ul));
3153 ig.Emit (OpCodes.Conv_U8);
3157 LongConstant.EmitLong (ig, unchecked ((long) ul));
3161 IntConstant.EmitInt (ig, (int) ((char) k));
3162 else if (k is sbyte)
3163 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3165 IntConstant.EmitInt (ig, (int) ((byte) k));
3166 else if (k is short)
3167 IntConstant.EmitInt (ig, (int) ((short) k));
3168 else if (k is ushort)
3169 IntConstant.EmitInt (ig, (int) ((ushort) k));
3171 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3173 throw new Exception ("Unhandled case");
3176 // structure used to hold blocks of keys while calculating table switch
3177 class KeyBlock : IComparable
3179 public KeyBlock (long _nFirst)
3181 nFirst = nLast = _nFirst;
3185 public ArrayList rgKeys = null;
3186 // how many items are in the bucket
3187 public int Size = 1;
3190 get { return (int) (nLast - nFirst + 1); }
3192 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3194 return kbLast.nLast - kbFirst.nFirst + 1;
3196 public int CompareTo (object obj)
3198 KeyBlock kb = (KeyBlock) obj;
3199 int nLength = Length;
3200 int nLengthOther = kb.Length;
3201 if (nLengthOther == nLength)
3202 return (int) (kb.nFirst - nFirst);
3203 return nLength - nLengthOther;
3208 /// This method emits code for a lookup-based switch statement (non-string)
3209 /// Basically it groups the cases into blocks that are at least half full,
3210 /// and then spits out individual lookup opcodes for each block.
3211 /// It emits the longest blocks first, and short blocks are just
3212 /// handled with direct compares.
3214 /// <param name="ec"></param>
3215 /// <param name="val"></param>
3216 /// <returns></returns>
3217 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
3219 int cElements = Elements.Count;
3220 object [] rgKeys = new object [cElements];
3221 Elements.Keys.CopyTo (rgKeys, 0);
3222 Array.Sort (rgKeys);
3224 // initialize the block list with one element per key
3225 ArrayList rgKeyBlocks = new ArrayList ();
3226 foreach (object key in rgKeys)
3227 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
3230 // iteratively merge the blocks while they are at least half full
3231 // there's probably a really cool way to do this with a tree...
3232 while (rgKeyBlocks.Count > 1)
3234 ArrayList rgKeyBlocksNew = new ArrayList ();
3235 kbCurr = (KeyBlock) rgKeyBlocks [0];
3236 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3238 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3239 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3242 kbCurr.nLast = kb.nLast;
3243 kbCurr.Size += kb.Size;
3247 // start a new block
3248 rgKeyBlocksNew.Add (kbCurr);
3252 rgKeyBlocksNew.Add (kbCurr);
3253 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3255 rgKeyBlocks = rgKeyBlocksNew;
3258 // initialize the key lists
3259 foreach (KeyBlock kb in rgKeyBlocks)
3260 kb.rgKeys = new ArrayList ();
3262 // fill the key lists
3264 if (rgKeyBlocks.Count > 0) {
3265 kbCurr = (KeyBlock) rgKeyBlocks [0];
3266 foreach (object key in rgKeys)
3268 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
3269 System.Convert.ToInt64 (key) > kbCurr.nLast;
3271 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3272 kbCurr.rgKeys.Add (key);
3276 // sort the blocks so we can tackle the largest ones first
3277 rgKeyBlocks.Sort ();
3279 // okay now we can start...
3280 ILGenerator ig = ec.ig;
3281 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3282 Label lblDefault = ig.DefineLabel ();
3284 Type typeKeys = null;
3285 if (rgKeys.Length > 0)
3286 typeKeys = rgKeys [0].GetType (); // used for conversions
3290 if (TypeManager.IsEnumType (SwitchType))
3291 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3293 compare_type = SwitchType;
3295 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3297 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3298 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3301 foreach (object key in kb.rgKeys)
3303 ig.Emit (OpCodes.Ldloc, val);
3304 EmitObjectInteger (ig, key);
3305 SwitchLabel sl = (SwitchLabel) Elements [key];
3306 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
3311 // TODO: if all the keys in the block are the same and there are
3312 // no gaps/defaults then just use a range-check.
3313 if (compare_type == TypeManager.int64_type ||
3314 compare_type == TypeManager.uint64_type)
3316 // TODO: optimize constant/I4 cases
3318 // check block range (could be > 2^31)
3319 ig.Emit (OpCodes.Ldloc, val);
3320 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3321 ig.Emit (OpCodes.Blt, lblDefault);
3322 ig.Emit (OpCodes.Ldloc, val);
3323 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
3324 ig.Emit (OpCodes.Bgt, lblDefault);
3327 ig.Emit (OpCodes.Ldloc, val);
3330 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3331 ig.Emit (OpCodes.Sub);
3333 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3338 ig.Emit (OpCodes.Ldloc, val);
3339 int nFirst = (int) kb.nFirst;
3342 IntConstant.EmitInt (ig, nFirst);
3343 ig.Emit (OpCodes.Sub);
3345 else if (nFirst < 0)
3347 IntConstant.EmitInt (ig, -nFirst);
3348 ig.Emit (OpCodes.Add);
3352 // first, build the list of labels for the switch
3354 int cJumps = kb.Length;
3355 Label [] rgLabels = new Label [cJumps];
3356 for (int iJump = 0; iJump < cJumps; iJump++)
3358 object key = kb.rgKeys [iKey];
3359 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
3361 SwitchLabel sl = (SwitchLabel) Elements [key];
3362 rgLabels [iJump] = sl.GetILLabel (ec);
3366 rgLabels [iJump] = lblDefault;
3368 // emit the switch opcode
3369 ig.Emit (OpCodes.Switch, rgLabels);
3372 // mark the default for this block
3374 ig.MarkLabel (lblDefault);
3377 // TODO: find the default case and emit it here,
3378 // to prevent having to do the following jump.
3379 // make sure to mark other labels in the default section
3381 // the last default just goes to the end
3382 ig.Emit (OpCodes.Br, lblDefault);
3384 // now emit the code for the sections
3385 bool fFoundDefault = false;
3386 bool fFoundNull = false;
3387 foreach (SwitchSection ss in Sections)
3389 foreach (SwitchLabel sl in ss.Labels)
3390 if (sl.Converted == SwitchLabel.NullStringCase)
3394 foreach (SwitchSection ss in Sections)
3396 foreach (SwitchLabel sl in ss.Labels)
3398 ig.MarkLabel (sl.GetILLabel (ec));
3399 ig.MarkLabel (sl.GetILLabelCode (ec));
3400 if (sl.Converted == SwitchLabel.NullStringCase)
3401 ig.MarkLabel (null_target);
3402 else if (sl.Label == null) {
3403 ig.MarkLabel (lblDefault);
3404 fFoundDefault = true;
3406 ig.MarkLabel (null_target);
3412 if (!fFoundDefault) {
3413 ig.MarkLabel (lblDefault);
3415 ig.MarkLabel (lblEnd);
3418 // This simple emit switch works, but does not take advantage of the
3420 // TODO: remove non-string logic from here
3421 // TODO: binary search strings?
3423 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3425 ILGenerator ig = ec.ig;
3426 Label end_of_switch = ig.DefineLabel ();
3427 Label next_test = ig.DefineLabel ();
3428 bool first_test = true;
3429 bool pending_goto_end = false;
3430 bool null_marked = false;
3432 int section_count = Sections.Count;
3434 // TODO: implement switch optimization for string by using Hashtable
3435 //if (SwitchType == TypeManager.string_type && section_count > 7)
3436 // Console.WriteLine ("Switch optimization possible " + loc);
3438 ig.Emit (OpCodes.Ldloc, val);
3440 if (Elements.Contains (SwitchLabel.NullStringCase)){
3441 ig.Emit (OpCodes.Brfalse, null_target);
3443 ig.Emit (OpCodes.Brfalse, default_target);
3445 ig.Emit (OpCodes.Ldloc, val);
3446 ig.Emit (OpCodes.Call, TypeManager.string_isinterned_string);
3447 ig.Emit (OpCodes.Stloc, val);
3449 for (int section = 0; section < section_count; section++){
3450 SwitchSection ss = (SwitchSection) Sections [section];
3452 if (ss == default_section)
3455 Label sec_begin = ig.DefineLabel ();
3457 ig.Emit (OpCodes.Nop);
3459 if (pending_goto_end)
3460 ig.Emit (OpCodes.Br, end_of_switch);
3462 int label_count = ss.Labels.Count;
3464 for (int label = 0; label < label_count; label++){
3465 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
3466 ig.MarkLabel (sl.GetILLabel (ec));
3469 ig.MarkLabel (next_test);
3470 next_test = ig.DefineLabel ();
3473 // If we are the default target
3475 if (sl.Label != null){
3476 object lit = sl.Converted;
3478 if (lit == SwitchLabel.NullStringCase){
3480 if (label + 1 == label_count)
3481 ig.Emit (OpCodes.Br, next_test);
3485 ig.Emit (OpCodes.Ldloc, val);
3486 ig.Emit (OpCodes.Ldstr, (string)lit);
3487 if (label_count == 1)
3488 ig.Emit (OpCodes.Bne_Un, next_test);
3490 if (label+1 == label_count)
3491 ig.Emit (OpCodes.Bne_Un, next_test);
3493 ig.Emit (OpCodes.Beq, sec_begin);
3498 ig.MarkLabel (null_target);
3501 ig.MarkLabel (sec_begin);
3502 foreach (SwitchLabel sl in ss.Labels)
3503 ig.MarkLabel (sl.GetILLabelCode (ec));
3506 pending_goto_end = !ss.Block.HasRet;
3509 ig.MarkLabel (next_test);
3510 ig.MarkLabel (default_target);
3512 ig.MarkLabel (null_target);
3513 if (default_section != null)
3514 default_section.Block.Emit (ec);
3515 ig.MarkLabel (end_of_switch);
3518 SwitchSection FindSection (SwitchLabel label)
3520 foreach (SwitchSection ss in Sections){
3521 foreach (SwitchLabel sl in ss.Labels){
3530 public override bool Resolve (EmitContext ec)
3532 Expr = Expr.Resolve (ec);
3536 new_expr = SwitchGoverningType (ec, Expr);
3539 if ((new_expr == null) && TypeManager.IsNullableType (Expr.Type)) {
3540 unwrap = Nullable.Unwrap.Create (Expr, ec);
3544 new_expr = SwitchGoverningType (ec, unwrap);
3548 if (new_expr == null){
3549 Report.Error (151, loc, "A value of an integral type or string expected for switch");
3554 SwitchType = new_expr.Type;
3556 if (RootContext.Version == LanguageVersion.ISO_1 && SwitchType == TypeManager.bool_type) {
3557 Report.FeatureIsNotISO1 (loc, "switch expression of boolean type");
3561 if (!CheckSwitch (ec))
3565 Elements.Remove (SwitchLabel.NullStringCase);
3567 Switch old_switch = ec.Switch;
3569 ec.Switch.SwitchType = SwitchType;
3571 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3572 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3574 is_constant = new_expr is Constant;
3576 object key = ((Constant) new_expr).GetValue ();
3577 SwitchLabel label = (SwitchLabel) Elements [key];
3579 constant_section = FindSection (label);
3580 if (constant_section == null)
3581 constant_section = default_section;
3585 foreach (SwitchSection ss in Sections){
3587 ec.CurrentBranching.CreateSibling (
3588 null, FlowBranching.SiblingType.SwitchSection);
3592 if (is_constant && (ss != constant_section)) {
3593 // If we're a constant switch, we're only emitting
3594 // one single section - mark all the others as
3596 ec.CurrentBranching.CurrentUsageVector.Goto ();
3597 if (!ss.Block.ResolveUnreachable (ec, true))
3600 if (!ss.Block.Resolve (ec))
3605 if (default_section == null)
3606 ec.CurrentBranching.CreateSibling (
3607 null, FlowBranching.SiblingType.SwitchSection);
3609 ec.EndFlowBranching ();
3610 ec.Switch = old_switch;
3612 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching);
3617 protected override void DoEmit (EmitContext ec)
3619 ILGenerator ig = ec.ig;
3621 default_target = ig.DefineLabel ();
3622 null_target = ig.DefineLabel ();
3624 // Store variable for comparission purposes
3627 value = ig.DeclareLocal (SwitchType);
3629 unwrap.EmitCheck (ec);
3630 ig.Emit (OpCodes.Brfalse, null_target);
3632 ig.Emit (OpCodes.Stloc, value);
3634 } else if (!is_constant) {
3635 value = ig.DeclareLocal (SwitchType);
3637 ig.Emit (OpCodes.Stloc, value);
3642 // Setup the codegen context
3644 Label old_end = ec.LoopEnd;
3645 Switch old_switch = ec.Switch;
3647 ec.LoopEnd = ig.DefineLabel ();
3652 if (constant_section != null)
3653 constant_section.Block.Emit (ec);
3654 } else if (SwitchType == TypeManager.string_type)
3655 SimpleSwitchEmit (ec, value);
3657 TableSwitchEmit (ec, value);
3659 // Restore context state.
3660 ig.MarkLabel (ec.LoopEnd);
3663 // Restore the previous context
3665 ec.LoopEnd = old_end;
3666 ec.Switch = old_switch;
3669 protected override void CloneTo (CloneContext clonectx, Statement t)
3671 Switch target = (Switch) t;
3673 target.Expr = Expr.Clone (clonectx);
3674 target.Sections = new ArrayList ();
3675 foreach (SwitchSection ss in Sections){
3676 target.Sections.Add (ss.Clone (clonectx));
3681 public abstract class ExceptionStatement : Statement
3683 public abstract void EmitFinally (EmitContext ec);
3685 protected bool emit_finally = true;
3686 ArrayList parent_vectors;
3688 protected void DoEmitFinally (EmitContext ec)
3691 ec.ig.BeginFinallyBlock ();
3692 else if (ec.InIterator)
3693 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3697 protected void ResolveFinally (FlowBranchingException branching)
3699 emit_finally = branching.EmitFinally;
3701 branching.Parent.StealFinallyClauses (ref parent_vectors);
3705 public class Lock : ExceptionStatement {
3707 public Statement Statement;
3708 TemporaryVariable temp;
3710 public Lock (Expression expr, Statement stmt, Location l)
3717 public override bool Resolve (EmitContext ec)
3719 expr = expr.Resolve (ec);
3723 if (expr.Type.IsValueType){
3724 Report.Error (185, loc,
3725 "`{0}' is not a reference type as required by the lock statement",
3726 TypeManager.CSharpName (expr.Type));
3730 FlowBranchingException branching = ec.StartFlowBranching (this);
3731 bool ok = Statement.Resolve (ec);
3733 ec.KillFlowBranching ();
3737 ResolveFinally (branching);
3739 ec.EndFlowBranching ();
3741 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
3742 // So, ensure there's some IL code after the finally block.
3743 ec.NeedReturnLabel ();
3745 // Avoid creating libraries that reference the internal
3748 if (t == TypeManager.null_type)
3749 t = TypeManager.object_type;
3751 temp = new TemporaryVariable (t, loc);
3757 protected override void DoEmit (EmitContext ec)
3759 ILGenerator ig = ec.ig;
3761 temp.Store (ec, expr);
3763 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3767 ig.BeginExceptionBlock ();
3768 Statement.Emit (ec);
3773 ig.EndExceptionBlock ();
3776 public override void EmitFinally (EmitContext ec)
3779 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3782 protected override void CloneTo (CloneContext clonectx, Statement t)
3784 Lock target = (Lock) t;
3786 target.expr = expr.Clone (clonectx);
3787 target.Statement = Statement.Clone (clonectx);
3791 public class Unchecked : Statement {
3794 public Unchecked (Block b)
3800 public override bool Resolve (EmitContext ec)
3802 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3803 return Block.Resolve (ec);
3806 protected override void DoEmit (EmitContext ec)
3808 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3812 protected override void CloneTo (CloneContext clonectx, Statement t)
3814 Unchecked target = (Unchecked) t;
3816 target.Block = clonectx.LookupBlock (Block);
3820 public class Checked : Statement {
3823 public Checked (Block b)
3826 b.Unchecked = false;
3829 public override bool Resolve (EmitContext ec)
3831 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3832 return Block.Resolve (ec);
3835 protected override void DoEmit (EmitContext ec)
3837 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3841 protected override void CloneTo (CloneContext clonectx, Statement t)
3843 Checked target = (Checked) t;
3845 target.Block = clonectx.LookupBlock (Block);
3849 public class Unsafe : Statement {
3852 public Unsafe (Block b)
3855 Block.Unsafe = true;
3858 public override bool Resolve (EmitContext ec)
3860 using (ec.With (EmitContext.Flags.InUnsafe, true))
3861 return Block.Resolve (ec);
3864 protected override void DoEmit (EmitContext ec)
3866 using (ec.With (EmitContext.Flags.InUnsafe, true))
3869 protected override void CloneTo (CloneContext clonectx, Statement t)
3871 Unsafe target = (Unsafe) t;
3873 target.Block = clonectx.LookupBlock (Block);
3880 public class Fixed : Statement {
3882 ArrayList declarators;
3883 Statement statement;
3888 abstract class Emitter
3890 protected LocalInfo vi;
3891 protected Expression converted;
3893 protected Emitter (Expression expr, LocalInfo li)
3899 public abstract void Emit (EmitContext ec);
3900 public abstract void EmitExit (EmitContext ec);
3903 class ExpressionEmitter : Emitter {
3904 public ExpressionEmitter (Expression converted, LocalInfo li) :
3905 base (converted, li)
3909 public override void Emit (EmitContext ec) {
3911 // Store pointer in pinned location
3913 converted.Emit (ec);
3914 vi.Variable.EmitAssign (ec);
3917 public override void EmitExit (EmitContext ec)
3919 ec.ig.Emit (OpCodes.Ldc_I4_0);
3920 ec.ig.Emit (OpCodes.Conv_U);
3921 vi.Variable.EmitAssign (ec);
3925 class StringEmitter : Emitter {
3926 LocalBuilder pinned_string;
3929 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3935 public override void Emit (EmitContext ec)
3937 ILGenerator ig = ec.ig;
3938 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3940 converted.Emit (ec);
3941 ig.Emit (OpCodes.Stloc, pinned_string);
3943 Expression sptr = new StringPtr (pinned_string, loc);
3944 converted = Convert.ImplicitConversionRequired (
3945 ec, sptr, vi.VariableType, loc);
3947 if (converted == null)
3950 converted.Emit (ec);
3951 vi.Variable.EmitAssign (ec);
3954 public override void EmitExit (EmitContext ec)
3956 ec.ig.Emit (OpCodes.Ldnull);
3957 ec.ig.Emit (OpCodes.Stloc, pinned_string);
3961 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3964 declarators = decls;
3969 public Statement Statement {
3970 get { return statement; }
3973 public override bool Resolve (EmitContext ec)
3976 Expression.UnsafeError (loc);
3980 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3984 expr_type = texpr.Type;
3986 data = new Emitter [declarators.Count];
3988 if (!expr_type.IsPointer){
3989 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3994 foreach (Pair p in declarators){
3995 LocalInfo vi = (LocalInfo) p.First;
3996 Expression e = (Expression) p.Second;
3998 vi.VariableInfo.SetAssigned (ec);
3999 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
4002 // The rules for the possible declarators are pretty wise,
4003 // but the production on the grammar is more concise.
4005 // So we have to enforce these rules here.
4007 // We do not resolve before doing the case 1 test,
4008 // because the grammar is explicit in that the token &
4009 // is present, so we need to test for this particular case.
4013 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
4018 // Case 1: & object.
4020 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4021 Expression child = ((Unary) e).Expr;
4023 if (child is ParameterReference || child is LocalVariableReference){
4026 "No need to use fixed statement for parameters or " +
4027 "local variable declarations (address is already " +
4032 ec.InFixedInitializer = true;
4034 ec.InFixedInitializer = false;
4038 child = ((Unary) e).Expr;
4040 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4043 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
4044 e.Error_ValueCannotBeConverted (ec, e.Location, expr_type, false);
4048 data [i] = new ExpressionEmitter (e, vi);
4054 ec.InFixedInitializer = true;
4056 ec.InFixedInitializer = false;
4063 if (e.Type.IsArray){
4064 Type array_type = TypeManager.GetElementType (e.Type);
4067 // Provided that array_type is unmanaged,
4069 if (!TypeManager.VerifyUnManaged (array_type, loc))
4073 // and T* is implicitly convertible to the
4074 // pointer type given in the fixed statement.
4076 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
4078 Expression converted = Convert.ImplicitConversionRequired (
4079 ec, array_ptr, vi.VariableType, loc);
4080 if (converted == null)
4083 data [i] = new ExpressionEmitter (converted, vi);
4092 if (e.Type == TypeManager.string_type){
4093 data [i] = new StringEmitter (e, vi, loc);
4098 // Case 4: fixed buffer
4099 FieldExpr fe = e as FieldExpr;
4101 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
4103 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
4105 Expression converted = Convert.ImplicitConversionRequired (
4106 ec, fixed_buffer_ptr, vi.VariableType, loc);
4107 if (converted == null)
4110 data [i] = new ExpressionEmitter (converted, vi);
4118 // For other cases, flag a `this is already fixed expression'
4120 if (e is LocalVariableReference || e is ParameterReference ||
4121 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
4123 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
4127 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
4131 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
4133 if (!statement.Resolve (ec)) {
4134 ec.KillFlowBranching ();
4138 bool flow_unreachable = ec.EndFlowBranching ();
4139 has_ret = flow_unreachable;
4144 protected override void DoEmit (EmitContext ec)
4146 for (int i = 0; i < data.Length; i++) {
4150 statement.Emit (ec);
4156 // Clear the pinned variable
4158 for (int i = 0; i < data.Length; i++) {
4159 data [i].EmitExit (ec);
4163 protected override void CloneTo (CloneContext clonectx, Statement t)
4165 Fixed target = (Fixed) t;
4167 target.type = type.Clone (clonectx);
4168 target.declarators = new ArrayList ();
4169 foreach (LocalInfo var in declarators)
4170 target.declarators.Add (clonectx.LookupVariable (var));
4171 target.statement = statement.Clone (clonectx);
4175 public class Catch : Statement {
4176 public readonly string Name;
4178 public Block VarBlock;
4180 Expression type_expr;
4183 public Catch (Expression type, string name, Block block, Block var_block, Location l)
4188 VarBlock = var_block;
4192 public Type CatchType {
4198 public bool IsGeneral {
4200 return type_expr == null;
4204 protected override void DoEmit(EmitContext ec)
4206 ILGenerator ig = ec.ig;
4208 if (CatchType != null)
4209 ig.BeginCatchBlock (CatchType);
4211 ig.BeginCatchBlock (TypeManager.object_type);
4213 if (VarBlock != null)
4217 LocalInfo vi = Block.GetLocalInfo (Name);
4219 throw new Exception ("Variable does not exist in this block");
4221 if (vi.Variable.NeedsTemporary) {
4222 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
4223 ig.Emit (OpCodes.Stloc, e);
4225 vi.Variable.EmitInstance (ec);
4226 ig.Emit (OpCodes.Ldloc, e);
4227 vi.Variable.EmitAssign (ec);
4229 vi.Variable.EmitAssign (ec);
4231 ig.Emit (OpCodes.Pop);
4236 public override bool Resolve (EmitContext ec)
4238 using (ec.With (EmitContext.Flags.InCatch, true)) {
4239 if (type_expr != null) {
4240 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
4246 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4247 Error (155, "The type caught or thrown must be derived from System.Exception");
4253 if (!Block.Resolve (ec))
4256 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
4257 // emit the "unused variable" warnings.
4258 if (VarBlock != null)
4259 return VarBlock.Resolve (ec);
4265 protected override void CloneTo (CloneContext clonectx, Statement t)
4267 Catch target = (Catch) t;
4269 target.type_expr = type_expr.Clone (clonectx);
4270 target.Block = clonectx.LookupBlock (Block);
4271 target.VarBlock = clonectx.LookupBlock (VarBlock);
4275 public class Try : ExceptionStatement {
4276 public Block Fini, Block;
4277 public ArrayList Specific;
4278 public Catch General;
4280 bool need_exc_block;
4283 // specific, general and fini might all be null.
4285 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4287 if (specific == null && general == null){
4288 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4292 this.Specific = specific;
4293 this.General = general;
4298 public override bool Resolve (EmitContext ec)
4302 FlowBranchingException branching = ec.StartFlowBranching (this);
4304 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4306 if (!Block.Resolve (ec))
4309 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4311 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4313 Type[] prevCatches = new Type [Specific.Count];
4315 foreach (Catch c in Specific){
4316 ec.CurrentBranching.CreateSibling (
4317 c.Block, FlowBranching.SiblingType.Catch);
4319 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4321 if (c.Name != null) {
4322 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
4324 throw new Exception ();
4326 vi.VariableInfo = null;
4329 if (!c.Resolve (ec))
4332 Type resolvedType = c.CatchType;
4333 for (int ii = 0; ii < last_index; ++ii) {
4334 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
4335 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
4340 prevCatches [last_index++] = resolvedType;
4341 need_exc_block = true;
4344 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4346 if (General != null){
4347 if (CodeGen.Assembly.WrapNonExceptionThrows) {
4348 foreach (Catch c in Specific){
4349 if (c.CatchType == TypeManager.exception_type) {
4350 Report.Warning (1058, 1, c.loc, "A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a `System.Runtime.CompilerServices.RuntimeWrappedException'");
4355 ec.CurrentBranching.CreateSibling (
4356 General.Block, FlowBranching.SiblingType.Catch);
4358 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4360 if (!General.Resolve (ec))
4363 need_exc_block = true;
4366 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4370 ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
4372 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4373 using (ec.With (EmitContext.Flags.InFinally, true)) {
4374 if (!Fini.Resolve (ec))
4379 need_exc_block = true;
4382 if (ec.InIterator) {
4383 ResolveFinally (branching);
4384 need_exc_block |= emit_finally;
4386 emit_finally = Fini != null;
4388 ec.EndFlowBranching ();
4390 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4391 // So, ensure there's some IL code after the finally block.
4392 ec.NeedReturnLabel ();
4394 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4396 Report.Debug (1, "END OF TRY", ec.CurrentBranching, vector, f_vector);
4401 protected override void DoEmit (EmitContext ec)
4403 ILGenerator ig = ec.ig;
4406 ig.BeginExceptionBlock ();
4409 foreach (Catch c in Specific)
4412 if (General != null)
4417 ig.EndExceptionBlock ();
4420 public override void EmitFinally (EmitContext ec)
4426 public bool HasCatch
4429 return General != null || Specific.Count > 0;
4433 protected override void CloneTo (CloneContext clonectx, Statement t)
4435 Try target = (Try) t;
4437 target.Block = clonectx.LookupBlock (Block);
4439 target.Fini = clonectx.LookupBlock (Fini);
4440 if (General != null)
4441 target.General = (Catch) General.Clone (clonectx);
4442 if (Specific != null){
4443 target.Specific = new ArrayList ();
4444 foreach (Catch c in Specific)
4445 target.Specific.Add (c.Clone (clonectx));
4450 public class Using : ExceptionStatement {
4451 object expression_or_block;
4452 public Statement Statement;
4456 Expression [] resolved_vars;
4457 Expression [] converted_vars;
4458 ExpressionStatement [] assign;
4459 TemporaryVariable local_copy;
4461 public Using (object expression_or_block, Statement stmt, Location l)
4463 this.expression_or_block = expression_or_block;
4469 // Resolves for the case of using using a local variable declaration.
4471 bool ResolveLocalVariableDecls (EmitContext ec)
4475 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
4479 expr_type = texpr.Type;
4482 // The type must be an IDisposable or an implicit conversion
4485 converted_vars = new Expression [var_list.Count];
4486 resolved_vars = new Expression [var_list.Count];
4487 assign = new ExpressionStatement [var_list.Count];
4489 bool need_conv = !TypeManager.ImplementsInterface (
4490 expr_type, TypeManager.idisposable_type);
4492 foreach (DictionaryEntry e in var_list){
4493 Expression var = (Expression) e.Key;
4495 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
4499 resolved_vars [i] = var;
4506 converted_vars [i] = Convert.ImplicitConversion (
4507 ec, var, TypeManager.idisposable_type, loc);
4509 if (converted_vars [i] == null) {
4510 Error_IsNotConvertibleToIDisposable ();
4518 foreach (DictionaryEntry e in var_list){
4519 Expression var = resolved_vars [i];
4520 Expression new_expr = (Expression) e.Value;
4523 a = new Assign (var, new_expr, loc);
4529 converted_vars [i] = var;
4530 assign [i] = (ExpressionStatement) a;
4537 void Error_IsNotConvertibleToIDisposable ()
4539 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
4540 TypeManager.CSharpName (expr_type));
4543 bool ResolveExpression (EmitContext ec)
4545 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4546 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
4547 Error_IsNotConvertibleToIDisposable ();
4552 local_copy = new TemporaryVariable (expr_type, loc);
4553 local_copy.Resolve (ec);
4559 // Emits the code for the case of using using a local variable declaration.
4561 void EmitLocalVariableDecls (EmitContext ec)
4563 ILGenerator ig = ec.ig;
4566 for (i = 0; i < assign.Length; i++) {
4567 assign [i].EmitStatement (ec);
4570 ig.BeginExceptionBlock ();
4572 Statement.Emit (ec);
4574 var_list.Reverse ();
4579 void EmitLocalVariableDeclFinally (EmitContext ec)
4581 ILGenerator ig = ec.ig;
4583 int i = assign.Length;
4584 for (int ii = 0; ii < var_list.Count; ++ii){
4585 Expression var = resolved_vars [--i];
4586 Label skip = ig.DefineLabel ();
4589 ig.BeginFinallyBlock ();
4591 if (!var.Type.IsValueType) {
4593 ig.Emit (OpCodes.Brfalse, skip);
4594 converted_vars [i].Emit (ec);
4595 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4597 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4599 if (!(ml is MethodGroupExpr)) {
4601 ig.Emit (OpCodes.Box, var.Type);
4602 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4604 MethodInfo mi = null;
4606 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4607 if (TypeManager.GetParameterData (mk).Count == 0) {
4614 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4618 IMemoryLocation mloc = (IMemoryLocation) var;
4620 mloc.AddressOf (ec, AddressOp.Load);
4621 ig.Emit (OpCodes.Call, mi);
4625 ig.MarkLabel (skip);
4628 ig.EndExceptionBlock ();
4630 ig.BeginFinallyBlock ();
4635 void EmitExpression (EmitContext ec)
4638 // Make a copy of the expression and operate on that.
4640 ILGenerator ig = ec.ig;
4642 local_copy.Store (ec, expr);
4645 ig.BeginExceptionBlock ();
4647 Statement.Emit (ec);
4651 ig.EndExceptionBlock ();
4654 void EmitExpressionFinally (EmitContext ec)
4656 ILGenerator ig = ec.ig;
4657 if (!expr_type.IsValueType) {
4658 Label skip = ig.DefineLabel ();
4659 local_copy.Emit (ec);
4660 ig.Emit (OpCodes.Brfalse, skip);
4661 local_copy.Emit (ec);
4662 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4663 ig.MarkLabel (skip);
4665 Expression ml = Expression.MemberLookup (
4666 ec.ContainerType, TypeManager.idisposable_type, expr_type,
4667 "Dispose", Location.Null);
4669 if (!(ml is MethodGroupExpr)) {
4670 local_copy.Emit (ec);
4671 ig.Emit (OpCodes.Box, expr_type);
4672 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4674 MethodInfo mi = null;
4676 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4677 if (TypeManager.GetParameterData (mk).Count == 0) {
4684 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4688 local_copy.AddressOf (ec, AddressOp.Load);
4689 ig.Emit (OpCodes.Call, mi);
4694 public override bool Resolve (EmitContext ec)
4696 if (expression_or_block is DictionaryEntry){
4697 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4698 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4700 if (!ResolveLocalVariableDecls (ec))
4703 } else if (expression_or_block is Expression){
4704 expr = (Expression) expression_or_block;
4706 expr = expr.Resolve (ec);
4710 expr_type = expr.Type;
4712 if (!ResolveExpression (ec))
4716 FlowBranchingException branching = ec.StartFlowBranching (this);
4718 bool ok = Statement.Resolve (ec);
4721 ec.KillFlowBranching ();
4725 ResolveFinally (branching);
4727 ec.EndFlowBranching ();
4729 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4730 // So, ensure there's some IL code after the finally block.
4731 ec.NeedReturnLabel ();
4736 protected override void DoEmit (EmitContext ec)
4738 if (expression_or_block is DictionaryEntry)
4739 EmitLocalVariableDecls (ec);
4740 else if (expression_or_block is Expression)
4741 EmitExpression (ec);
4744 public override void EmitFinally (EmitContext ec)
4746 if (expression_or_block is DictionaryEntry)
4747 EmitLocalVariableDeclFinally (ec);
4748 else if (expression_or_block is Expression)
4749 EmitExpressionFinally (ec);
4752 protected override void CloneTo (CloneContext clonectx, Statement t)
4754 Using target = (Using) t;
4756 if (expression_or_block is Expression)
4757 target.expression_or_block = ((Expression) expression_or_block).Clone (clonectx);
4759 target.expression_or_block = ((Statement) expression_or_block).Clone (clonectx);
4761 target.Statement = Statement.Clone (clonectx);
4766 /// Implementation of the foreach C# statement
4768 public class Foreach : Statement {
4770 Expression variable;
4772 Statement statement;
4774 CollectionForeach collection;
4776 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4777 Statement stmt, Location l)
4780 this.variable = var;
4786 public Statement Statement {
4787 get { return statement; }
4790 public override bool Resolve (EmitContext ec)
4792 expr = expr.Resolve (ec);
4796 Constant c = expr as Constant;
4797 if (c != null && c.GetValue () == null) {
4798 Report.Error (186, loc, "Use of null is not valid in this context");
4802 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4806 Type var_type = texpr.Type;
4808 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
4809 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4810 expr.ExprClassName);
4815 // We need an instance variable. Not sure this is the best
4816 // way of doing this.
4818 // FIXME: When we implement propertyaccess, will those turn
4819 // out to return values in ExprClass? I think they should.
4821 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4822 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4823 collection.Error_Enumerator ();
4827 if (expr.Type.IsArray) {
4828 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4829 return array.Resolve (ec);
4831 collection = new CollectionForeach (
4832 var_type, variable, expr, statement, loc);
4833 return collection.Resolve (ec);
4837 protected override void DoEmit (EmitContext ec)
4839 ILGenerator ig = ec.ig;
4841 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4842 ec.LoopBegin = ig.DefineLabel ();
4843 ec.LoopEnd = ig.DefineLabel ();
4845 if (collection != null)
4846 collection.Emit (ec);
4850 ec.LoopBegin = old_begin;
4851 ec.LoopEnd = old_end;
4854 protected class ArrayCounter : TemporaryVariable
4856 public ArrayCounter (Location loc)
4857 : base (TypeManager.int32_type, loc)
4860 public void Initialize (EmitContext ec)
4863 ec.ig.Emit (OpCodes.Ldc_I4_0);
4867 public void Increment (EmitContext ec)
4871 ec.ig.Emit (OpCodes.Ldc_I4_1);
4872 ec.ig.Emit (OpCodes.Add);
4877 protected class ArrayForeach : Statement
4879 Expression variable, expr, conv;
4880 Statement statement;
4883 TemporaryVariable[] lengths;
4884 ArrayCounter[] counter;
4887 TemporaryVariable copy;
4890 public ArrayForeach (Type var_type, Expression var,
4891 Expression expr, Statement stmt, Location l)
4893 this.var_type = var_type;
4894 this.variable = var;
4900 public override bool Resolve (EmitContext ec)
4902 array_type = expr.Type;
4903 rank = array_type.GetArrayRank ();
4905 copy = new TemporaryVariable (array_type, loc);
4908 counter = new ArrayCounter [rank];
4909 lengths = new TemporaryVariable [rank];
4911 ArrayList list = new ArrayList ();
4912 for (int i = 0; i < rank; i++) {
4913 counter [i] = new ArrayCounter (loc);
4914 counter [i].Resolve (ec);
4916 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4917 lengths [i].Resolve (ec);
4919 list.Add (counter [i]);
4922 access = new ElementAccess (copy, list).Resolve (ec);
4926 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4932 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4933 ec.CurrentBranching.CreateSibling ();
4935 variable = variable.ResolveLValue (ec, conv, loc);
4936 if (variable == null)
4939 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4940 if (!statement.Resolve (ec))
4942 ec.EndFlowBranching ();
4944 // There's no direct control flow from the end of the embedded statement to the end of the loop
4945 ec.CurrentBranching.CurrentUsageVector.Goto ();
4947 ec.EndFlowBranching ();
4952 protected override void DoEmit (EmitContext ec)
4954 ILGenerator ig = ec.ig;
4956 copy.Store (ec, expr);
4958 Label[] test = new Label [rank];
4959 Label[] loop = new Label [rank];
4961 for (int i = 0; i < rank; i++) {
4962 test [i] = ig.DefineLabel ();
4963 loop [i] = ig.DefineLabel ();
4965 lengths [i].EmitThis (ec);
4966 ((ArrayAccess) access).EmitGetLength (ec, i);
4967 lengths [i].EmitStore (ec);
4970 for (int i = 0; i < rank; i++) {
4971 counter [i].Initialize (ec);
4973 ig.Emit (OpCodes.Br, test [i]);
4974 ig.MarkLabel (loop [i]);
4977 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4979 statement.Emit (ec);
4981 ig.MarkLabel (ec.LoopBegin);
4983 for (int i = rank - 1; i >= 0; i--){
4984 counter [i].Increment (ec);
4986 ig.MarkLabel (test [i]);
4987 counter [i].Emit (ec);
4988 lengths [i].Emit (ec);
4989 ig.Emit (OpCodes.Blt, loop [i]);
4992 ig.MarkLabel (ec.LoopEnd);
4996 protected class CollectionForeach : ExceptionStatement
4998 Expression variable, expr;
4999 Statement statement;
5001 TemporaryVariable enumerator;
5005 MethodGroupExpr get_enumerator;
5006 PropertyExpr get_current;
5007 MethodInfo move_next;
5008 Type var_type, enumerator_type;
5010 bool enumerator_found;
5012 public CollectionForeach (Type var_type, Expression var,
5013 Expression expr, Statement stmt, Location l)
5015 this.var_type = var_type;
5016 this.variable = var;
5022 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
5024 Type return_type = mi.ReturnType;
5026 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
5028 // Apply the same optimization as MS: skip the GetEnumerator
5029 // returning an IEnumerator, and use the one returning a
5030 // CharEnumerator instead. This allows us to avoid the
5031 // try-finally block and the boxing.
5036 // Ok, we can access it, now make sure that we can do something
5037 // with this `GetEnumerator'
5040 if (return_type == TypeManager.ienumerator_type ||
5041 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
5042 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
5044 // If it is not an interface, lets try to find the methods ourselves.
5045 // For example, if we have:
5046 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
5047 // We can avoid the iface call. This is a runtime perf boost.
5048 // even bigger if we have a ValueType, because we avoid the cost
5051 // We have to make sure that both methods exist for us to take
5052 // this path. If one of the methods does not exist, we will just
5053 // use the interface. Sadly, this complex if statement is the only
5054 // way I could do this without a goto
5059 // Prefer a generic enumerator over a non-generic one.
5061 if (return_type.IsInterface && return_type.IsGenericType) {
5062 enumerator_type = return_type;
5063 if (!FetchGetCurrent (ec, return_type))
5064 get_current = new PropertyExpr (
5065 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
5066 if (!FetchMoveNext (return_type))
5067 move_next = TypeManager.bool_movenext_void;
5072 if (return_type.IsInterface ||
5073 !FetchMoveNext (return_type) ||
5074 !FetchGetCurrent (ec, return_type)) {
5075 enumerator_type = return_type;
5076 move_next = TypeManager.bool_movenext_void;
5077 get_current = new PropertyExpr (
5078 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
5083 // Ok, so they dont return an IEnumerable, we will have to
5084 // find if they support the GetEnumerator pattern.
5087 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
5088 Report.Error (202, loc, "foreach statement requires that the return type `{0}' of `{1}' must have a suitable public MoveNext method and public Current property",
5089 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
5094 enumerator_type = return_type;
5095 is_disposable = !enumerator_type.IsSealed ||
5096 TypeManager.ImplementsInterface (
5097 enumerator_type, TypeManager.idisposable_type);
5103 // Retrieves a `public bool MoveNext ()' method from the Type `t'
5105 bool FetchMoveNext (Type t)
5107 MemberList move_next_list;
5109 move_next_list = TypeContainer.FindMembers (
5110 t, MemberTypes.Method,
5111 BindingFlags.Public | BindingFlags.Instance,
5112 Type.FilterName, "MoveNext");
5113 if (move_next_list.Count == 0)
5116 foreach (MemberInfo m in move_next_list){
5117 MethodInfo mi = (MethodInfo) m;
5119 if ((TypeManager.GetParameterData (mi).Count == 0) &&
5120 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
5130 // Retrieves a `public T get_Current ()' method from the Type `t'
5132 bool FetchGetCurrent (EmitContext ec, Type t)
5134 PropertyExpr pe = Expression.MemberLookup (
5135 ec.ContainerType, t, "Current", MemberTypes.Property,
5136 Expression.AllBindingFlags, loc) as PropertyExpr;
5145 // Retrieves a `public void Dispose ()' method from the Type `t'
5147 static MethodInfo FetchMethodDispose (Type t)
5149 MemberList dispose_list;
5151 dispose_list = TypeContainer.FindMembers (
5152 t, MemberTypes.Method,
5153 BindingFlags.Public | BindingFlags.Instance,
5154 Type.FilterName, "Dispose");
5155 if (dispose_list.Count == 0)
5158 foreach (MemberInfo m in dispose_list){
5159 MethodInfo mi = (MethodInfo) m;
5161 if (TypeManager.GetParameterData (mi).Count == 0){
5162 if (mi.ReturnType == TypeManager.void_type)
5169 public void Error_Enumerator ()
5171 if (enumerator_found) {
5175 Report.Error (1579, loc,
5176 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
5177 TypeManager.CSharpName (expr.Type));
5180 bool TryType (EmitContext ec, Type t)
5182 MethodGroupExpr mg = Expression.MemberLookup (
5183 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
5184 Expression.AllBindingFlags, loc) as MethodGroupExpr;
5188 MethodInfo result = null;
5189 MethodInfo tmp_move_next = null;
5190 PropertyExpr tmp_get_cur = null;
5191 Type tmp_enumerator_type = enumerator_type;
5192 foreach (MethodInfo mi in mg.Methods) {
5193 if (TypeManager.GetParameterData (mi).Count != 0)
5196 // Check whether GetEnumerator is public
5197 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
5200 if (TypeManager.IsOverride (mi))
5203 enumerator_found = true;
5205 if (!GetEnumeratorFilter (ec, mi))
5208 if (result != null) {
5209 if (TypeManager.IsGenericType (result.ReturnType)) {
5210 if (!TypeManager.IsGenericType (mi.ReturnType))
5213 MethodBase mb = TypeManager.DropGenericMethodArguments (mi);
5214 Report.SymbolRelatedToPreviousError (t);
5215 Report.Error(1640, loc, "foreach statement cannot operate on variables of type `{0}' " +
5216 "because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
5217 TypeManager.CSharpName (t), TypeManager.CSharpSignature (mb));
5221 // Always prefer generics enumerators
5222 if (!TypeManager.IsGenericType (mi.ReturnType)) {
5223 if (TypeManager.ImplementsInterface (mi.DeclaringType, result.DeclaringType) ||
5224 TypeManager.ImplementsInterface (result.DeclaringType, mi.DeclaringType))
5227 Report.SymbolRelatedToPreviousError (result);
5228 Report.SymbolRelatedToPreviousError (mi);
5229 Report.Warning (278, 2, loc, "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
5230 TypeManager.CSharpName (t), "enumerable", TypeManager.CSharpSignature (result), TypeManager.CSharpSignature (mi));
5235 tmp_move_next = move_next;
5236 tmp_get_cur = get_current;
5237 tmp_enumerator_type = enumerator_type;
5238 if (mi.DeclaringType == t)
5242 if (result != null) {
5243 move_next = tmp_move_next;
5244 get_current = tmp_get_cur;
5245 enumerator_type = tmp_enumerator_type;
5246 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
5247 get_enumerator = new MethodGroupExpr (mi, loc);
5249 if (t != expr.Type) {
5250 expr = Convert.ExplicitConversion (
5253 throw new InternalErrorException ();
5256 get_enumerator.InstanceExpression = expr;
5257 get_enumerator.IsBase = t != expr.Type;
5265 bool ProbeCollectionType (EmitContext ec, Type t)
5267 int errors = Report.Errors;
5268 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
5269 if (TryType (ec, tt))
5274 if (Report.Errors > errors)
5278 // Now try to find the method in the interfaces
5281 Type [] ifaces = t.GetInterfaces ();
5283 foreach (Type i in ifaces){
5284 if (TryType (ec, i))
5289 // Since TypeBuilder.GetInterfaces only returns the interface
5290 // types for this type, we have to keep looping, but once
5291 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5292 // done, because it returns all the types
5294 if ((t is TypeBuilder))
5303 public override bool Resolve (EmitContext ec)
5305 enumerator_type = TypeManager.ienumerator_type;
5306 is_disposable = true;
5308 if (!ProbeCollectionType (ec, expr.Type)) {
5309 Error_Enumerator ();
5313 enumerator = new TemporaryVariable (enumerator_type, loc);
5314 enumerator.Resolve (ec);
5316 init = new Invocation (get_enumerator, new ArrayList ());
5317 init = init.Resolve (ec);
5321 Expression move_next_expr;
5323 MemberInfo[] mi = new MemberInfo[] { move_next };
5324 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
5325 mg.InstanceExpression = enumerator;
5327 move_next_expr = new Invocation (mg, new ArrayList ());
5330 get_current.InstanceExpression = enumerator;
5332 Statement block = new CollectionForeachStatement (
5333 var_type, variable, get_current, statement, loc);
5335 loop = new While (move_next_expr, block, loc);
5339 FlowBranchingException branching = null;
5341 branching = ec.StartFlowBranching (this);
5343 if (!loop.Resolve (ec))
5346 if (is_disposable) {
5347 ResolveFinally (branching);
5348 ec.EndFlowBranching ();
5350 emit_finally = true;
5355 protected override void DoEmit (EmitContext ec)
5357 ILGenerator ig = ec.ig;
5359 enumerator.Store (ec, init);
5362 // Protect the code in a try/finalize block, so that
5363 // if the beast implement IDisposable, we get rid of it
5365 if (is_disposable && emit_finally)
5366 ig.BeginExceptionBlock ();
5371 // Now the finally block
5373 if (is_disposable) {
5376 ig.EndExceptionBlock ();
5381 public override void EmitFinally (EmitContext ec)
5383 ILGenerator ig = ec.ig;
5385 if (enumerator_type.IsValueType) {
5386 MethodInfo mi = FetchMethodDispose (enumerator_type);
5388 enumerator.EmitLoadAddress (ec);
5389 ig.Emit (OpCodes.Call, mi);
5391 enumerator.Emit (ec);
5392 ig.Emit (OpCodes.Box, enumerator_type);
5393 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5396 Label call_dispose = ig.DefineLabel ();
5398 enumerator.Emit (ec);
5399 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5400 ig.Emit (OpCodes.Dup);
5401 ig.Emit (OpCodes.Brtrue_S, call_dispose);
5402 ig.Emit (OpCodes.Pop);
5404 Label end_finally = ig.DefineLabel ();
5405 ig.Emit (OpCodes.Br, end_finally);
5407 ig.MarkLabel (call_dispose);
5408 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5409 ig.MarkLabel (end_finally);
5414 protected class CollectionForeachStatement : Statement
5417 Expression variable, current, conv;
5418 Statement statement;
5421 public CollectionForeachStatement (Type type, Expression variable,
5422 Expression current, Statement statement,
5426 this.variable = variable;
5427 this.current = current;
5428 this.statement = statement;
5432 public override bool Resolve (EmitContext ec)
5434 current = current.Resolve (ec);
5435 if (current == null)
5438 conv = Convert.ExplicitConversion (ec, current, type, loc);
5442 assign = new Assign (variable, conv, loc);
5443 if (assign.Resolve (ec) == null)
5446 if (!statement.Resolve (ec))
5452 protected override void DoEmit (EmitContext ec)
5454 assign.EmitStatement (ec);
5455 statement.Emit (ec);
5459 protected override void CloneTo (CloneContext clonectx, Statement t)
5461 Foreach target = (Foreach) t;
5463 target.type = type.Clone (clonectx);
5464 target.variable = variable.Clone (clonectx);
5465 target.expr = expr.Clone (clonectx);
5466 target.statement = statement.Clone (clonectx);